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
mit
ca8a5bde3ff1b11702a64c46841ebcce66a8a5a4
0
github-api-test-org/jenkins,guoxu0514/jenkins,maikeffi/hudson,bpzhang/jenkins,morficus/jenkins,kohsuke/hudson,goldchang/jenkins,292388900/jenkins,hplatou/jenkins,kohsuke/hudson,keyurpatankar/hudson,varmenise/jenkins,lilyJi/jenkins,daniel-beck/jenkins,hemantojhaa/jenkins,lindzh/jenkins,alvarolobato/jenkins,rlugojr/jenkins,seanlin816/jenkins,jk47/jenkins,stephenc/jenkins,khmarbaise/jenkins,tangkun75/jenkins,SebastienGllmt/jenkins,kohsuke/hudson,NehemiahMi/jenkins,bkmeneguello/jenkins,oleg-nenashev/jenkins,singh88/jenkins,ErikVerheul/jenkins,my7seven/jenkins,protazy/jenkins,jglick/jenkins,aheritier/jenkins,hudson/hudson-2.x,scoheb/jenkins,chbiel/jenkins,scoheb/jenkins,intelchen/jenkins,viqueen/jenkins,viqueen/jenkins,varmenise/jenkins,jenkinsci/jenkins,dbroady1/jenkins,pjanouse/jenkins,ChrisA89/jenkins,github-api-test-org/jenkins,duzifang/my-jenkins,abayer/jenkins,SebastienGllmt/jenkins,SebastienGllmt/jenkins,alvarolobato/jenkins,1and1/jenkins,liorhson/jenkins,huybrechts/hudson,paulmillar/jenkins,MichaelPranovich/jenkins_sc,shahharsh/jenkins,paulmillar/jenkins,shahharsh/jenkins,dbroady1/jenkins,Jimilian/jenkins,h4ck3rm1k3/jenkins,khmarbaise/jenkins,chbiel/jenkins,jpbriend/jenkins,jpederzolli/jenkins-1,hplatou/jenkins,ns163/jenkins,nandan4/Jenkins,MadsNielsen/jtemp,godfath3r/jenkins,daniel-beck/jenkins,vijayto/jenkins,jhoblitt/jenkins,Jimilian/jenkins,luoqii/jenkins,iqstack/jenkins,DanielWeber/jenkins,Jochen-A-Fuerbacher/jenkins,ajshastri/jenkins,akshayabd/jenkins,tastatur/jenkins,MichaelPranovich/jenkins_sc,FarmGeek4Life/jenkins,jtnord/jenkins,synopsys-arc-oss/jenkins,jhoblitt/jenkins,DoctorQ/jenkins,synopsys-arc-oss/jenkins,pantheon-systems/jenkins,liupugong/jenkins,daspilker/jenkins,amuniz/jenkins,singh88/jenkins,sathiya-mit/jenkins,Ykus/jenkins,DoctorQ/jenkins,Jochen-A-Fuerbacher/jenkins,deadmoose/jenkins,alvarolobato/jenkins,viqueen/jenkins,hplatou/jenkins,jhoblitt/jenkins,tfennelly/jenkins,evernat/jenkins,jcsirot/jenkins,mrooney/jenkins,abayer/jenkins,jzjzjzj/jenkins,Jimilian/jenkins,elkingtonmcb/jenkins,olivergondza/jenkins,hemantojhaa/jenkins,andresrc/jenkins,maikeffi/hudson,daspilker/jenkins,olivergondza/jenkins,paulmillar/jenkins,keyurpatankar/hudson,soenter/jenkins,akshayabd/jenkins,arunsingh/jenkins,sathiya-mit/jenkins,NehemiahMi/jenkins,seanlin816/jenkins,rsandell/jenkins,MarkEWaite/jenkins,csimons/jenkins,gusreiber/jenkins,AustinKwang/jenkins,escoem/jenkins,seanlin816/jenkins,oleg-nenashev/jenkins,ikedam/jenkins,lordofthejars/jenkins,morficus/jenkins,abayer/jenkins,viqueen/jenkins,daniel-beck/jenkins,guoxu0514/jenkins,CodeShane/jenkins,mrobinet/jenkins,vivek/hudson,mdonohue/jenkins,aheritier/jenkins,292388900/jenkins,v1v/jenkins,soenter/jenkins,paulmillar/jenkins,christ66/jenkins,AustinKwang/jenkins,everyonce/jenkins,intelchen/jenkins,ikedam/jenkins,my7seven/jenkins,liorhson/jenkins,damianszczepanik/jenkins,v1v/jenkins,chbiel/jenkins,rsandell/jenkins,kohsuke/hudson,evernat/jenkins,sathiya-mit/jenkins,v1v/jenkins,shahharsh/jenkins,kohsuke/hudson,damianszczepanik/jenkins,azweb76/jenkins,csimons/jenkins,csimons/jenkins,goldchang/jenkins,Krasnyanskiy/jenkins,mcanthony/jenkins,scoheb/jenkins,jpederzolli/jenkins-1,msrb/jenkins,MadsNielsen/jtemp,jzjzjzj/jenkins,morficus/jenkins,vlajos/jenkins,dennisjlee/jenkins,gusreiber/jenkins,albers/jenkins,everyonce/jenkins,dariver/jenkins,aheritier/jenkins,mdonohue/jenkins,synopsys-arc-oss/jenkins,csimons/jenkins,goldchang/jenkins,abayer/jenkins,MarkEWaite/jenkins,pselle/jenkins,patbos/jenkins,batmat/jenkins,vvv444/jenkins,maikeffi/hudson,godfath3r/jenkins,csimons/jenkins,protazy/jenkins,vjuranek/jenkins,liorhson/jenkins,jcarrothers-sap/jenkins,jtnord/jenkins,soenter/jenkins,stephenc/jenkins,iterate/coding-dojo,godfath3r/jenkins,christ66/jenkins,deadmoose/jenkins,msrb/jenkins,Ykus/jenkins,christ66/jenkins,singh88/jenkins,jpbriend/jenkins,rsandell/jenkins,jenkinsci/jenkins,ErikVerheul/jenkins,lordofthejars/jenkins,yonglehou/jenkins,bpzhang/jenkins,synopsys-arc-oss/jenkins,ChrisA89/jenkins,scoheb/jenkins,ajshastri/jenkins,KostyaSha/jenkins,ajshastri/jenkins,wuwen5/jenkins,jglick/jenkins,FTG-003/jenkins,vvv444/jenkins,NehemiahMi/jenkins,MadsNielsen/jtemp,vivek/hudson,dariver/jenkins,FTG-003/jenkins,hashar/jenkins,akshayabd/jenkins,kzantow/jenkins,csimons/jenkins,batmat/jenkins,thomassuckow/jenkins,ndeloof/jenkins,Krasnyanskiy/jenkins,jzjzjzj/jenkins,christ66/jenkins,SenolOzer/jenkins,pselle/jenkins,jhoblitt/jenkins,vvv444/jenkins,wuwen5/jenkins,protazy/jenkins,mrooney/jenkins,petermarcoen/jenkins,aduprat/jenkins,dennisjlee/jenkins,vlajos/jenkins,mcanthony/jenkins,nandan4/Jenkins,rlugojr/jenkins,alvarolobato/jenkins,patbos/jenkins,christ66/jenkins,keyurpatankar/hudson,elkingtonmcb/jenkins,guoxu0514/jenkins,mrooney/jenkins,DoctorQ/jenkins,bpzhang/jenkins,gorcz/jenkins,pselle/jenkins,FTG-003/jenkins,arcivanov/jenkins,bpzhang/jenkins,aquarellian/jenkins,vvv444/jenkins,lilyJi/jenkins,nandan4/Jenkins,h4ck3rm1k3/jenkins,amuniz/jenkins,stephenc/jenkins,vivek/hudson,kzantow/jenkins,my7seven/jenkins,escoem/jenkins,recena/jenkins,292388900/jenkins,jk47/jenkins,MadsNielsen/jtemp,mdonohue/jenkins,seanlin816/jenkins,mdonohue/jenkins,recena/jenkins,albers/jenkins,iterate/coding-dojo,abayer/jenkins,azweb76/jenkins,MarkEWaite/jenkins,lindzh/jenkins,everyonce/jenkins,huybrechts/hudson,goldchang/jenkins,lvotypko/jenkins,arunsingh/jenkins,hashar/jenkins,vlajos/jenkins,ErikVerheul/jenkins,everyonce/jenkins,petermarcoen/jenkins,liorhson/jenkins,ikedam/jenkins,ns163/jenkins,vjuranek/jenkins,verbitan/jenkins,amruthsoft9/Jenkis,oleg-nenashev/jenkins,damianszczepanik/jenkins,ikedam/jenkins,singh88/jenkins,DoctorQ/jenkins,bpzhang/jenkins,jpbriend/jenkins,aheritier/jenkins,MichaelPranovich/jenkins_sc,dbroady1/jenkins,SebastienGllmt/jenkins,ydubreuil/jenkins,aduprat/jenkins,ajshastri/jenkins,chbiel/jenkins,gorcz/jenkins,jk47/jenkins,viqueen/jenkins,vvv444/jenkins,jpbriend/jenkins,lindzh/jenkins,SenolOzer/jenkins,gitaccountforprashant/gittest,jcsirot/jenkins,bkmeneguello/jenkins,lvotypko/jenkins,jcsirot/jenkins,damianszczepanik/jenkins,dariver/jenkins,lordofthejars/jenkins,tfennelly/jenkins,github-api-test-org/jenkins,iqstack/jenkins,dennisjlee/jenkins,msrb/jenkins,FTG-003/jenkins,stephenc/jenkins,pantheon-systems/jenkins,keyurpatankar/hudson,svanoort/jenkins,lvotypko/jenkins3,lvotypko/jenkins3,yonglehou/jenkins,MarkEWaite/jenkins,jcarrothers-sap/jenkins,christ66/jenkins,SenolOzer/jenkins,DanielWeber/jenkins,guoxu0514/jenkins,soenter/jenkins,mattclark/jenkins,thomassuckow/jenkins,jglick/jenkins,alvarolobato/jenkins,AustinKwang/jenkins,github-api-test-org/jenkins,paulmillar/jenkins,jzjzjzj/jenkins,Vlatombe/jenkins,gorcz/jenkins,vijayto/jenkins,tfennelly/jenkins,h4ck3rm1k3/jenkins,SenolOzer/jenkins,andresrc/jenkins,fbelzunc/jenkins,hplatou/jenkins,KostyaSha/jenkins,goldchang/jenkins,my7seven/jenkins,stephenc/jenkins,hudson/hudson-2.x,liupugong/jenkins,rsandell/jenkins,daniel-beck/jenkins,intelchen/jenkins,AustinKwang/jenkins,aquarellian/jenkins,kzantow/jenkins,jcsirot/jenkins,guoxu0514/jenkins,vivek/hudson,ndeloof/jenkins,escoem/jenkins,gitaccountforprashant/gittest,DanielWeber/jenkins,fbelzunc/jenkins,Jochen-A-Fuerbacher/jenkins,kohsuke/hudson,viqueen/jenkins,jpederzolli/jenkins-1,pantheon-systems/jenkins,andresrc/jenkins,pjanouse/jenkins,liupugong/jenkins,escoem/jenkins,soenter/jenkins,oleg-nenashev/jenkins,Wilfred/jenkins,duzifang/my-jenkins,jk47/jenkins,Jochen-A-Fuerbacher/jenkins,keyurpatankar/hudson,jcsirot/jenkins,singh88/jenkins,mattclark/jenkins,aduprat/jenkins,ErikVerheul/jenkins,6WIND/jenkins,arunsingh/jenkins,jcarrothers-sap/jenkins,daniel-beck/jenkins,guoxu0514/jenkins,samatdav/jenkins,msrb/jenkins,jcarrothers-sap/jenkins,maikeffi/hudson,jenkinsci/jenkins,ydubreuil/jenkins,kzantow/jenkins,akshayabd/jenkins,rashmikanta-1984/jenkins,verbitan/jenkins,vijayto/jenkins,arunsingh/jenkins,elkingtonmcb/jenkins,hemantojhaa/jenkins,bpzhang/jenkins,SebastienGllmt/jenkins,lvotypko/jenkins3,escoem/jenkins,amruthsoft9/Jenkis,jglick/jenkins,dariver/jenkins,dariver/jenkins,DoctorQ/jenkins,iqstack/jenkins,jpederzolli/jenkins-1,gusreiber/jenkins,recena/jenkins,elkingtonmcb/jenkins,MichaelPranovich/jenkins_sc,Jochen-A-Fuerbacher/jenkins,hashar/jenkins,arcivanov/jenkins,1and1/jenkins,KostyaSha/jenkins,verbitan/jenkins,aquarellian/jenkins,everyonce/jenkins,liorhson/jenkins,KostyaSha/jenkins,evernat/jenkins,mpeltonen/jenkins,olivergondza/jenkins,iqstack/jenkins,FarmGeek4Life/jenkins,ns163/jenkins,stefanbrausch/hudson-main,mdonohue/jenkins,NehemiahMi/jenkins,morficus/jenkins,synopsys-arc-oss/jenkins,fbelzunc/jenkins,sathiya-mit/jenkins,patbos/jenkins,recena/jenkins,v1v/jenkins,patbos/jenkins,petermarcoen/jenkins,gitaccountforprashant/gittest,viqueen/jenkins,AustinKwang/jenkins,verbitan/jenkins,ydubreuil/jenkins,olivergondza/jenkins,lindzh/jenkins,Wilfred/jenkins,FarmGeek4Life/jenkins,iqstack/jenkins,lilyJi/jenkins,yonglehou/jenkins,ChrisA89/jenkins,wangyikai/jenkins,mpeltonen/jenkins,amruthsoft9/Jenkis,FTG-003/jenkins,stefanbrausch/hudson-main,abayer/jenkins,evernat/jenkins,292388900/jenkins,DoctorQ/jenkins,maikeffi/hudson,ChrisA89/jenkins,shahharsh/jenkins,rashmikanta-1984/jenkins,pjanouse/jenkins,svanoort/jenkins,singh88/jenkins,ydubreuil/jenkins,batmat/jenkins,mrobinet/jenkins,andresrc/jenkins,Krasnyanskiy/jenkins,gorcz/jenkins,292388900/jenkins,aldaris/jenkins,gitaccountforprashant/gittest,my7seven/jenkins,iterate/coding-dojo,fbelzunc/jenkins,maikeffi/hudson,thomassuckow/jenkins,seanlin816/jenkins,nandan4/Jenkins,rashmikanta-1984/jenkins,ChrisA89/jenkins,Jochen-A-Fuerbacher/jenkins,ndeloof/jenkins,oleg-nenashev/jenkins,patbos/jenkins,escoem/jenkins,aheritier/jenkins,dbroady1/jenkins,KostyaSha/jenkins,petermarcoen/jenkins,vijayto/jenkins,amruthsoft9/Jenkis,svanoort/jenkins,lvotypko/jenkins,vjuranek/jenkins,fbelzunc/jenkins,samatdav/jenkins,ajshastri/jenkins,tfennelly/jenkins,ErikVerheul/jenkins,CodeShane/jenkins,chbiel/jenkins,albers/jenkins,tfennelly/jenkins,bpzhang/jenkins,FarmGeek4Life/jenkins,KostyaSha/jenkins,vivek/hudson,mrooney/jenkins,sathiya-mit/jenkins,samatdav/jenkins,khmarbaise/jenkins,damianszczepanik/jenkins,recena/jenkins,duzifang/my-jenkins,albers/jenkins,6WIND/jenkins,daspilker/jenkins,rashmikanta-1984/jenkins,lvotypko/jenkins2,recena/jenkins,tangkun75/jenkins,synopsys-arc-oss/jenkins,jzjzjzj/jenkins,pjanouse/jenkins,pantheon-systems/jenkins,hashar/jenkins,jpbriend/jenkins,huybrechts/hudson,daniel-beck/jenkins,albers/jenkins,CodeShane/jenkins,amuniz/jenkins,jzjzjzj/jenkins,damianszczepanik/jenkins,arcivanov/jenkins,stefanbrausch/hudson-main,paulwellnerbou/jenkins,scoheb/jenkins,andresrc/jenkins,SenolOzer/jenkins,damianszczepanik/jenkins,292388900/jenkins,amuniz/jenkins,kzantow/jenkins,6WIND/jenkins,jglick/jenkins,iterate/coding-dojo,vvv444/jenkins,seanlin816/jenkins,jenkinsci/jenkins,pselle/jenkins,evernat/jenkins,jzjzjzj/jenkins,duzifang/my-jenkins,shahharsh/jenkins,soenter/jenkins,liupugong/jenkins,Ykus/jenkins,v1v/jenkins,jk47/jenkins,protazy/jenkins,arcivanov/jenkins,ikedam/jenkins,MichaelPranovich/jenkins_sc,chbiel/jenkins,paulmillar/jenkins,jcsirot/jenkins,AustinKwang/jenkins,vivek/hudson,vlajos/jenkins,my7seven/jenkins,vjuranek/jenkins,seanlin816/jenkins,mattclark/jenkins,Vlatombe/jenkins,brunocvcunha/jenkins,keyurpatankar/hudson,morficus/jenkins,lordofthejars/jenkins,kohsuke/hudson,gorcz/jenkins,nandan4/Jenkins,aheritier/jenkins,github-api-test-org/jenkins,intelchen/jenkins,hudson/hudson-2.x,pantheon-systems/jenkins,pjanouse/jenkins,jcarrothers-sap/jenkins,jenkinsci/jenkins,brunocvcunha/jenkins,liorhson/jenkins,github-api-test-org/jenkins,jtnord/jenkins,varmenise/jenkins,huybrechts/hudson,akshayabd/jenkins,wangyikai/jenkins,Ykus/jenkins,tfennelly/jenkins,alvarolobato/jenkins,fbelzunc/jenkins,amruthsoft9/Jenkis,h4ck3rm1k3/jenkins,DoctorQ/jenkins,liupugong/jenkins,lvotypko/jenkins,lvotypko/jenkins2,msrb/jenkins,mrooney/jenkins,Vlatombe/jenkins,292388900/jenkins,pjanouse/jenkins,lvotypko/jenkins2,olivergondza/jenkins,luoqii/jenkins,jtnord/jenkins,1and1/jenkins,sathiya-mit/jenkins,arcivanov/jenkins,intelchen/jenkins,wuwen5/jenkins,noikiy/jenkins,gusreiber/jenkins,nandan4/Jenkins,mrooney/jenkins,azweb76/jenkins,varmenise/jenkins,Jimilian/jenkins,MadsNielsen/jtemp,Krasnyanskiy/jenkins,noikiy/jenkins,brunocvcunha/jenkins,lvotypko/jenkins3,vvv444/jenkins,albers/jenkins,hplatou/jenkins,github-api-test-org/jenkins,tastatur/jenkins,gusreiber/jenkins,aquarellian/jenkins,deadmoose/jenkins,rsandell/jenkins,ndeloof/jenkins,v1v/jenkins,mcanthony/jenkins,aquarellian/jenkins,vlajos/jenkins,luoqii/jenkins,jhoblitt/jenkins,lvotypko/jenkins3,shahharsh/jenkins,gitaccountforprashant/gittest,mrobinet/jenkins,1and1/jenkins,Ykus/jenkins,ydubreuil/jenkins,jpbriend/jenkins,lvotypko/jenkins3,samatdav/jenkins,scoheb/jenkins,andresrc/jenkins,fbelzunc/jenkins,varmenise/jenkins,rashmikanta-1984/jenkins,tangkun75/jenkins,hudson/hudson-2.x,wangyikai/jenkins,kzantow/jenkins,lindzh/jenkins,DanielWeber/jenkins,SebastienGllmt/jenkins,h4ck3rm1k3/jenkins,synopsys-arc-oss/jenkins,sathiya-mit/jenkins,jtnord/jenkins,verbitan/jenkins,CodeShane/jenkins,morficus/jenkins,hudson/hudson-2.x,mattclark/jenkins,albers/jenkins,MadsNielsen/jtemp,deadmoose/jenkins,nandan4/Jenkins,stephenc/jenkins,paulwellnerbou/jenkins,MichaelPranovich/jenkins_sc,hemantojhaa/jenkins,maikeffi/hudson,svanoort/jenkins,azweb76/jenkins,Jimilian/jenkins,jenkinsci/jenkins,gitaccountforprashant/gittest,deadmoose/jenkins,wangyikai/jenkins,SenolOzer/jenkins,jcarrothers-sap/jenkins,rashmikanta-1984/jenkins,yonglehou/jenkins,patbos/jenkins,paulwellnerbou/jenkins,DoctorQ/jenkins,lindzh/jenkins,FarmGeek4Life/jenkins,tastatur/jenkins,verbitan/jenkins,lordofthejars/jenkins,MarkEWaite/jenkins,singh88/jenkins,lilyJi/jenkins,mdonohue/jenkins,mrobinet/jenkins,Krasnyanskiy/jenkins,Jimilian/jenkins,petermarcoen/jenkins,hashar/jenkins,shahharsh/jenkins,petermarcoen/jenkins,aldaris/jenkins,gorcz/jenkins,paulwellnerbou/jenkins,alvarolobato/jenkins,khmarbaise/jenkins,wangyikai/jenkins,msrb/jenkins,tangkun75/jenkins,Krasnyanskiy/jenkins,brunocvcunha/jenkins,SebastienGllmt/jenkins,daspilker/jenkins,CodeShane/jenkins,lordofthejars/jenkins,godfath3r/jenkins,FTG-003/jenkins,batmat/jenkins,ndeloof/jenkins,mcanthony/jenkins,pselle/jenkins,deadmoose/jenkins,aduprat/jenkins,svanoort/jenkins,mpeltonen/jenkins,tangkun75/jenkins,goldchang/jenkins,oleg-nenashev/jenkins,mpeltonen/jenkins,wuwen5/jenkins,Wilfred/jenkins,mcanthony/jenkins,liorhson/jenkins,varmenise/jenkins,dennisjlee/jenkins,MadsNielsen/jtemp,evernat/jenkins,ChrisA89/jenkins,keyurpatankar/hudson,daspilker/jenkins,luoqii/jenkins,DanielWeber/jenkins,wangyikai/jenkins,mrobinet/jenkins,svanoort/jenkins,rlugojr/jenkins,batmat/jenkins,lindzh/jenkins,FarmGeek4Life/jenkins,elkingtonmcb/jenkins,lvotypko/jenkins,intelchen/jenkins,amuniz/jenkins,noikiy/jenkins,tangkun75/jenkins,vlajos/jenkins,luoqii/jenkins,jk47/jenkins,arcivanov/jenkins,huybrechts/hudson,jenkinsci/jenkins,olivergondza/jenkins,ChrisA89/jenkins,iqstack/jenkins,arunsingh/jenkins,godfath3r/jenkins,mdonohue/jenkins,mcanthony/jenkins,daniel-beck/jenkins,vjuranek/jenkins,ikedam/jenkins,dennisjlee/jenkins,duzifang/my-jenkins,dennisjlee/jenkins,morficus/jenkins,daspilker/jenkins,gusreiber/jenkins,1and1/jenkins,msrb/jenkins,amuniz/jenkins,vijayto/jenkins,hemantojhaa/jenkins,KostyaSha/jenkins,huybrechts/hudson,rlugojr/jenkins,noikiy/jenkins,verbitan/jenkins,mrooney/jenkins,ydubreuil/jenkins,iqstack/jenkins,lvotypko/jenkins2,vivek/hudson,hudson/hudson-2.x,jtnord/jenkins,Vlatombe/jenkins,Vlatombe/jenkins,noikiy/jenkins,csimons/jenkins,jhoblitt/jenkins,gitaccountforprashant/gittest,thomassuckow/jenkins,paulmillar/jenkins,lordofthejars/jenkins,6WIND/jenkins,iterate/coding-dojo,aduprat/jenkins,MarkEWaite/jenkins,jhoblitt/jenkins,azweb76/jenkins,rlugojr/jenkins,noikiy/jenkins,lvotypko/jenkins,dariver/jenkins,luoqii/jenkins,aldaris/jenkins,wuwen5/jenkins,jcsirot/jenkins,NehemiahMi/jenkins,lilyJi/jenkins,wangyikai/jenkins,abayer/jenkins,brunocvcunha/jenkins,jpederzolli/jenkins-1,protazy/jenkins,recena/jenkins,MarkEWaite/jenkins,dbroady1/jenkins,jpbriend/jenkins,bkmeneguello/jenkins,KostyaSha/jenkins,liupugong/jenkins,rlugojr/jenkins,Jochen-A-Fuerbacher/jenkins,stefanbrausch/hudson-main,paulwellnerbou/jenkins,amruthsoft9/Jenkis,azweb76/jenkins,ns163/jenkins,lvotypko/jenkins3,ikedam/jenkins,chbiel/jenkins,petermarcoen/jenkins,batmat/jenkins,lilyJi/jenkins,h4ck3rm1k3/jenkins,duzifang/my-jenkins,gorcz/jenkins,maikeffi/hudson,jenkinsci/jenkins,ns163/jenkins,NehemiahMi/jenkins,rsandell/jenkins,vijayto/jenkins,pantheon-systems/jenkins,akshayabd/jenkins,tastatur/jenkins,vivek/hudson,ns163/jenkins,vijayto/jenkins,luoqii/jenkins,tastatur/jenkins,iterate/coding-dojo,pselle/jenkins,lvotypko/jenkins2,Wilfred/jenkins,tastatur/jenkins,khmarbaise/jenkins,olivergondza/jenkins,ajshastri/jenkins,patbos/jenkins,aldaris/jenkins,Ykus/jenkins,lvotypko/jenkins2,iterate/coding-dojo,mrobinet/jenkins,ndeloof/jenkins,batmat/jenkins,Jimilian/jenkins,akshayabd/jenkins,Vlatombe/jenkins,kzantow/jenkins,mpeltonen/jenkins,bkmeneguello/jenkins,mattclark/jenkins,soenter/jenkins,aheritier/jenkins,intelchen/jenkins,mcanthony/jenkins,gorcz/jenkins,mrobinet/jenkins,khmarbaise/jenkins,6WIND/jenkins,arunsingh/jenkins,yonglehou/jenkins,hemantojhaa/jenkins,scoheb/jenkins,ErikVerheul/jenkins,damianszczepanik/jenkins,h4ck3rm1k3/jenkins,deadmoose/jenkins,paulwellnerbou/jenkins,CodeShane/jenkins,stefanbrausch/hudson-main,yonglehou/jenkins,goldchang/jenkins,lvotypko/jenkins2,MichaelPranovich/jenkins_sc,liupugong/jenkins,brunocvcunha/jenkins,andresrc/jenkins,ydubreuil/jenkins,jzjzjzj/jenkins,aquarellian/jenkins,elkingtonmcb/jenkins,aquarellian/jenkins,bkmeneguello/jenkins,Krasnyanskiy/jenkins,hplatou/jenkins,christ66/jenkins,aduprat/jenkins,tfennelly/jenkins,hashar/jenkins,thomassuckow/jenkins,pantheon-systems/jenkins,hashar/jenkins,CodeShane/jenkins,jtnord/jenkins,escoem/jenkins,vlajos/jenkins,DanielWeber/jenkins,jglick/jenkins,godfath3r/jenkins,Ykus/jenkins,everyonce/jenkins,huybrechts/hudson,lvotypko/jenkins,bkmeneguello/jenkins,brunocvcunha/jenkins,SenolOzer/jenkins,arcivanov/jenkins,kohsuke/hudson,dariver/jenkins,FTG-003/jenkins,rsandell/jenkins,vjuranek/jenkins,ns163/jenkins,jpederzolli/jenkins-1,everyonce/jenkins,jk47/jenkins,stefanbrausch/hudson-main,jpederzolli/jenkins-1,tangkun75/jenkins,v1v/jenkins,yonglehou/jenkins,godfath3r/jenkins,vjuranek/jenkins,ikedam/jenkins,daniel-beck/jenkins,pjanouse/jenkins,protazy/jenkins,paulwellnerbou/jenkins,noikiy/jenkins,dbroady1/jenkins,tastatur/jenkins,github-api-test-org/jenkins,Wilfred/jenkins,wuwen5/jenkins,FarmGeek4Life/jenkins,amuniz/jenkins,mattclark/jenkins,rashmikanta-1984/jenkins,dennisjlee/jenkins,lilyJi/jenkins,jglick/jenkins,6WIND/jenkins,6WIND/jenkins,gusreiber/jenkins,Vlatombe/jenkins,jcarrothers-sap/jenkins,guoxu0514/jenkins,svanoort/jenkins,Wilfred/jenkins,samatdav/jenkins,DanielWeber/jenkins,pselle/jenkins,daspilker/jenkins,evernat/jenkins,MarkEWaite/jenkins,my7seven/jenkins,ajshastri/jenkins,azweb76/jenkins,dbroady1/jenkins,varmenise/jenkins,ndeloof/jenkins,1and1/jenkins,NehemiahMi/jenkins,aldaris/jenkins,thomassuckow/jenkins,samatdav/jenkins,rsandell/jenkins,protazy/jenkins,rlugojr/jenkins,samatdav/jenkins,mattclark/jenkins,khmarbaise/jenkins,AustinKwang/jenkins,aldaris/jenkins,arunsingh/jenkins,oleg-nenashev/jenkins,hplatou/jenkins,1and1/jenkins,mpeltonen/jenkins,amruthsoft9/Jenkis,duzifang/my-jenkins,shahharsh/jenkins,keyurpatankar/hudson,aldaris/jenkins,aduprat/jenkins,wuwen5/jenkins,stefanbrausch/hudson-main,Wilfred/jenkins,stephenc/jenkins,goldchang/jenkins,jcarrothers-sap/jenkins,elkingtonmcb/jenkins,ErikVerheul/jenkins,mpeltonen/jenkins,thomassuckow/jenkins,bkmeneguello/jenkins,hemantojhaa/jenkins
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Eric Lefevre-Ardant, Erik Ramfelt, Michael B. Donohue * * 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 hudson; import hudson.Launcher.LocalLauncher; import hudson.Launcher.RemoteLauncher; import hudson.model.Hudson; import hudson.model.TaskListener; import hudson.model.AbstractProject; import hudson.model.Item; import hudson.remoting.Callable; import hudson.remoting.Channel; import hudson.remoting.DelegatingCallable; import hudson.remoting.Future; import hudson.remoting.Pipe; import hudson.remoting.RemoteOutputStream; import hudson.remoting.VirtualChannel; import hudson.remoting.RemoteInputStream; import hudson.util.IOException2; import hudson.util.HeadBufferingStream; import hudson.util.FormValidation; import hudson.util.jna.GNUCLibrary; import static hudson.Util.fixEmpty; import static hudson.FilePath.TarCompression.GZIP; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Copy; import org.apache.tools.ant.types.FileSet; import org.apache.tools.tar.TarEntry; import org.apache.tools.tar.TarOutputStream; import org.apache.tools.tar.TarInputStream; import org.apache.tools.zip.ZipOutputStream; import org.apache.tools.zip.ZipEntry; import org.apache.commons.io.IOUtils; import org.apache.commons.fileupload.FileItem; import org.kohsuke.stapler.Stapler; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.io.Writer; import java.io.OutputStreamWriter; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.Arrays; import java.util.Comparator; import java.util.regex.Pattern; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.zip.GZIPOutputStream; import java.util.zip.GZIPInputStream; import java.util.zip.ZipInputStream; /** * {@link File} like object with remoting support. * * <p> * Unlike {@link File}, which always implies a file path on the current computer, * {@link FilePath} represents a file path on a specific slave or the master. * * Despite that, {@link FilePath} can be used much like {@link File}. It exposes * a bunch of operations (and we should add more operations as long as they are * generally useful), and when invoked against a file on a remote node, {@link FilePath} * executes the necessary code remotely, thereby providing semi-transparent file * operations. * * <h2>Using {@link FilePath} smartly</h2> * <p> * The transparency makes it easy to write plugins without worrying too much about * remoting, by making it works like NFS, where remoting happens at the file-system * later. * * <p> * But one should note that such use of remoting may not be optional. Sometimes, * it makes more sense to move some computation closer to the data, as opposed to * move the data to the computation. For example, if you are just computing a MD5 * digest of a file, then it would make sense to do the digest on the host where * the file is located, as opposed to send the whole data to the master and do MD5 * digesting there. * * <p> * {@link FilePath} supports this "code migration" by in the * {@link #act(FileCallable)} method. One can pass in a custom implementation * of {@link FileCallable}, to be executed on the node where the data is located. * The following code shows the example: * * <pre> * FilePath file = ...; * * // make 'file' a fresh empty directory. * file.act(new FileCallable&lt;Void>() { * // if 'file' is on a different node, this FileCallable will * // be transfered to that node and executed there. * public Void invoke(File f,VirtualChannel channel) { * // f and file represents the same thing * f.deleteContents(); * f.mkdirs(); * } * }); * </pre> * * <p> * When {@link FileCallable} is transfered to a remote node, it will be done so * by using the same Java serialization scheme that the remoting module uses. * See {@link Channel} for more about this. * * <p> * {@link FilePath} itself can be sent over to a remote node as a part of {@link Callable} * serialization. For example, sending a {@link FilePath} of a remote node to that * node causes {@link FilePath} to become "local". Similarly, sending a * {@link FilePath} that represents the local computer causes it to become "remote." * * @author Kohsuke Kawaguchi */ public final class FilePath implements Serializable { /** * When this {@link FilePath} represents the remote path, * this field is always non-null on master (the field represents * the channel to the remote slave.) When transferred to a slave via remoting, * this field reverts back to null, since it's transient. * * When this {@link FilePath} represents a path on the master, * this field is null on master. When transferred to a slave via remoting, * this field becomes non-null, representing the {@link Channel} * back to the master. * * This is used to determine whether we are running on the master or the slave. */ private transient VirtualChannel channel; // since the platform of the slave might be different, can't use java.io.File private final String remote; /** * Creates a {@link FilePath} that represents a path on the given node. * * @param channel * To create a path that represents a remote path, pass in a {@link Channel} * that's connected to that machine. If null, that means the local file path. */ public FilePath(VirtualChannel channel, String remote) { this.channel = channel; this.remote = remote; } /** * To create {@link FilePath} that represents a "local" path. * * <p> * A "local" path means a file path on the computer where the * constructor invocation happened. */ public FilePath(File localPath) { this.channel = null; this.remote = localPath.getPath(); } public FilePath(FilePath base, String rel) { this.channel = base.channel; if(isAbsolute(rel)) { // absolute this.remote = rel; } else if(base.isUnix()) { this.remote = base.remote+'/'+rel; } else { this.remote = base.remote+'\\'+rel; } } private static boolean isAbsolute(String rel) { return rel.startsWith("/") || DRIVE_PATTERN.matcher(rel).matches(); } private static final Pattern DRIVE_PATTERN = Pattern.compile("[A-Za-z]:\\\\.+"); /** * Checks if the remote path is Unix. */ private boolean isUnix() { // if the path represents a local path, there' no need to guess. if(!isRemote()) return File.pathSeparatorChar!=';'; // note that we can't use the usual File.pathSeparator and etc., as the OS of // the machine where this code runs and the OS that this FilePath refers to may be different. // Windows absolute path is 'X:\...', so this is usually a good indication of Windows path if(remote.length()>3 && remote.charAt(1)==':' && remote.charAt(2)=='\\') return false; // Windows can handle '/' as a path separator but Unix can't, // so err on Unix side return remote.indexOf("\\")==-1; } public String getRemote() { return remote; } /** * Creates a zip file from this directory or a file and sends that to the given output stream. */ public void createZipArchive(OutputStream os) throws IOException, InterruptedException { final OutputStream out = (channel!=null)?new RemoteOutputStream(os):os; act(new FileCallable<Void>() { private transient byte[] buf; public Void invoke(File f, VirtualChannel channel) throws IOException { buf = new byte[8192]; ZipOutputStream zip = new ZipOutputStream(out); zip.setEncoding(System.getProperty("file.encoding")); scan(f,zip,""); zip.close(); return null; } private void scan(File f, ZipOutputStream zip, String path) throws IOException { // Bitmask indicating directories in 'external attributes' of a ZIP archive entry. final long BITMASK_IS_DIRECTORY = 1<<4; if (f.canRead()) { if(f.isDirectory()) { ZipEntry dirZipEntry = new ZipEntry(path+f.getName()+'/'); // Setting this bit explicitly is needed by some unzipping applications (see HUDSON-3294). dirZipEntry.setExternalAttributes(BITMASK_IS_DIRECTORY); zip.putNextEntry(dirZipEntry); zip.closeEntry(); for( File child : f.listFiles() ) scan(child,zip,path+f.getName()+'/'); } else { zip.putNextEntry(new ZipEntry(path+f.getName())); FileInputStream in = new FileInputStream(f); int len; while((len=in.read(buf))>0) zip.write(buf,0,len); in.close(); zip.closeEntry(); } } } private static final long serialVersionUID = 1L; }); } /** * Creates a zip file from this directory by only including the files that match the given glob. * * @param glob * Ant style glob, like "**&#x2F;*.xml". If empty or null, this method * works like {@link #createZipArchive(OutputStream)} * * @since 1.129 */ public void createZipArchive(OutputStream os, final String glob) throws IOException, InterruptedException { if(glob==null || glob.length()==0) { createZipArchive(os); return; } final OutputStream out = (channel!=null)?new RemoteOutputStream(os):os; act(new FileCallable<Void>() { public Void invoke(File dir, VirtualChannel channel) throws IOException { byte[] buf = new byte[8192]; ZipOutputStream zip = new ZipOutputStream(out); zip.setEncoding(System.getProperty("file.encoding")); for( String entry : glob(dir,glob) ) { File file = new File(dir,entry); if (file.canRead()) { zip.putNextEntry(new ZipEntry(dir.getName()+'/'+entry)); FileInputStream in = new FileInputStream(file); int len; while((len=in.read(buf))>0) zip.write(buf,0,len); in.close(); zip.closeEntry(); } } zip.close(); return null; } private static final long serialVersionUID = 1L; }); } /** * When this {@link FilePath} represents a zip file, extracts that zip file. * * @param target * Target directory to expand files to. All the necessary directories will be created. * @since 1.248 * @see #unzipFrom(InputStream) */ public void unzip(final FilePath target) throws IOException, InterruptedException { target.act(new FileCallable<Void>() { public Void invoke(File dir, VirtualChannel channel) throws IOException { unzip(dir,FilePath.this.read()); return null; } private static final long serialVersionUID = 1L; }); } /** * When this {@link FilePath} represents a tar file, extracts that tar file. * * @param target * Target directory to expand files to. All the necessary directories will be created. * @param compression * Compression mode of this tar file. * @since 1.292 * @see #untarFrom(InputStream, TarCompression) */ public void untar(final FilePath target, final TarCompression compression) throws IOException, InterruptedException { target.act(new FileCallable<Void>() { public Void invoke(File dir, VirtualChannel channel) throws IOException { readFromTar(FilePath.this.getName(),dir,compression.extract(FilePath.this.read())); return null; } private static final long serialVersionUID = 1L; }); } /** * Reads the given InputStream as a zip file and extracts it into this directory. * * @param _in * The stream will be closed by this method after it's fully read. * @since 1.283 * @see #unzip(FilePath) */ public void unzipFrom(InputStream _in) throws IOException, InterruptedException { final InputStream in = new RemoteInputStream(_in); act(new FileCallable<Void>() { public Void invoke(File dir, VirtualChannel channel) throws IOException { unzip(dir, in); return null; } private static final long serialVersionUID = 1L; }); } private void unzip(File dir, InputStream in) throws IOException { dir = dir.getAbsoluteFile(); // without absolutization, getParentFile below seems to fail ZipInputStream zip = new ZipInputStream(in); java.util.zip.ZipEntry e; try { while((e=zip.getNextEntry())!=null) { File f = new File(dir,e.getName()); if(e.isDirectory()) { f.mkdirs(); } else { File p = f.getParentFile(); if(p!=null) p.mkdirs(); FileOutputStream out = new FileOutputStream(f); try { IOUtils.copy(zip, out); } finally { out.close(); } f.setLastModified(e.getTime()); zip.closeEntry(); } } } finally { zip.close(); } } /** * Supported tar file compression methods. */ public enum TarCompression { NONE { public InputStream extract(InputStream in) { return in; } public OutputStream compress(OutputStream out) { return out; } }, GZIP { public InputStream extract(InputStream _in) throws IOException { HeadBufferingStream in = new HeadBufferingStream(_in,SIDE_BUFFER_SIZE); try { return new GZIPInputStream(in,8192); } catch (IOException e) { // various people reported "java.io.IOException: Not in GZIP format" here, so diagnose this problem better in.fillSide(); throw new IOException2(e.getMessage()+"\nstream="+Util.toHexString(in.getSideBuffer()),e); } } public OutputStream compress(OutputStream out) throws IOException { return new GZIPOutputStream(new BufferedOutputStream(out)); } }; public abstract InputStream extract(InputStream in) throws IOException; public abstract OutputStream compress(OutputStream in) throws IOException; } /** * Reads the given InputStream as a tar file and extracts it into this directory. * * @param _in * The stream will be closed by this method after it's fully read. * @param compression * The compression method in use. * @since 1.292 */ public void untarFrom(InputStream _in, final TarCompression compression) throws IOException, InterruptedException { try { final InputStream in = new RemoteInputStream(_in); act(new FileCallable<Void>() { public Void invoke(File dir, VirtualChannel channel) throws IOException { readFromTar("input stream",dir, compression.extract(in)); return null; } private static final long serialVersionUID = 1L; }); } finally { IOUtils.closeQuietly(_in); } } /** * Given a tgz/zip file, extracts it to the given target directory, if necessary. * * <p> * This method is a convenience method designed for installing a binary package to a location * that supports upgrade and downgrade. Specifically, * * <ul> * <li>If the target directory doesn't exit {@linkplain #mkdirs() it'll be created}. * <li>The timestamp of the .tgz file is left in the installation directory upon extraction. * <li>If the timestamp left in the directory doesn't match with the timestamp of the current archive file, * the directory contents will be discarded and the archive file will be re-extracted. * </ul> * * @param archive * The resource that represents the tgz/zip file. This URL must support the "Last-Modified" header. * (Most common usage is to get this from {@link ClassLoader#getResource(String)}) * @param listener * If non-null, a message will be printed to this listener once this method decides to * extract an archive. * @return * true if the archive was extracted. false if the extraction was skipped because the target directory * was considered up to date. * @since 1.299 */ public boolean installIfNecessaryFrom(URL archive, TaskListener listener, String message) throws IOException, InterruptedException { URLConnection con = archive.openConnection(); long sourceTimestamp = con.getLastModified(); FilePath timestamp = this.child(".timestamp"); if(this.exists()) { if(timestamp.exists() && sourceTimestamp ==timestamp.lastModified()) return false; // already up to date this.deleteContents(); } if(listener!=null) listener.getLogger().println(message); if(archive.toExternalForm().endsWith(".zip")) unzipFrom(con.getInputStream()); else untarFrom(con.getInputStream(),GZIP); timestamp.touch(sourceTimestamp); return true; } /** * Reads the URL on the current VM, and writes all the data to this {@link FilePath} * (this is different from resolving URL remotely.) * * @since 1.293 */ public void copyFrom(URL url) throws IOException, InterruptedException { InputStream in = url.openStream(); try { copyFrom(in); } finally { in.close(); } } /** * Replaces the content of this file by the data from the given {@link InputStream}. * * @since 1.293 */ public void copyFrom(InputStream in) throws IOException, InterruptedException { OutputStream os = write(); try { IOUtils.copy(in, os); } finally { os.close(); } } /** * Place the data from {@link FileItem} into the file location specified by this {@link FilePath} object. */ public void copyFrom(FileItem file) throws IOException, InterruptedException { if(channel==null) { try { file.write(new File(remote)); } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException2(e); } } else { InputStream i = file.getInputStream(); OutputStream o = write(); try { IOUtils.copy(i,o); } finally { o.close(); i.close(); } } } /** * Code that gets executed on the machine where the {@link FilePath} is local. * Used to act on {@link FilePath}. * * @see FilePath#act(FileCallable) */ public static interface FileCallable<T> extends Serializable { /** * Performs the computational task on the node where the data is located. * * @param f * {@link File} that represents the local file that {@link FilePath} has represented. * @param channel * The "back pointer" of the {@link Channel} that represents the communication * with the node from where the code was sent. */ T invoke(File f, VirtualChannel channel) throws IOException; } /** * Executes some program on the machine that this {@link FilePath} exists, * so that one can perform local file operations. */ public <T> T act(final FileCallable<T> callable) throws IOException, InterruptedException { if(channel!=null) { // run this on a remote system try { return channel.call(new FileCallableWrapper<T>(callable)); } catch (IOException e) { // wrap it into a new IOException so that we get the caller's stack trace as well. throw new IOException2("remote file operation failed",e); } } else { // the file is on the local machine. return callable.invoke(new File(remote), Hudson.MasterComputer.localChannel); } } /** * Executes some program on the machine that this {@link FilePath} exists, * so that one can perform local file operations. */ public <T> Future<T> actAsync(final FileCallable<T> callable) throws IOException, InterruptedException { try { return (channel!=null ? channel : Hudson.MasterComputer.localChannel) .callAsync(new FileCallableWrapper<T>(callable)); } catch (IOException e) { // wrap it into a new IOException so that we get the caller's stack trace as well. throw new IOException2("remote file operation failed",e); } } /** * Executes some program on the machine that this {@link FilePath} exists, * so that one can perform local file operations. */ public <V,E extends Throwable> V act(Callable<V,E> callable) throws IOException, InterruptedException, E { if(channel!=null) { // run this on a remote system return channel.call(callable); } else { // the file is on the local machine return callable.call(); } } /** * Converts this file to the URI, relative to the machine * on which this file is available. */ public URI toURI() throws IOException, InterruptedException { return act(new FileCallable<URI>() { public URI invoke(File f, VirtualChannel channel) { return f.toURI(); } }); } /** * Creates this directory. */ public void mkdirs() throws IOException, InterruptedException { if(!act(new FileCallable<Boolean>() { public Boolean invoke(File f, VirtualChannel channel) throws IOException { if(f.mkdirs() || f.exists()) return true; // OK // following Ant <mkdir> task to avoid possible race condition. try { Thread.sleep(10); } catch (InterruptedException e) { // ignore } return f.mkdirs() || f.exists(); } })) throw new IOException("Failed to mkdirs: "+remote); } /** * Deletes this directory, including all its contents recursively. */ public void deleteRecursive() throws IOException, InterruptedException { act(new FileCallable<Void>() { public Void invoke(File f, VirtualChannel channel) throws IOException { Util.deleteRecursive(f); return null; } }); } /** * Deletes all the contents of this directory, but not the directory itself */ public void deleteContents() throws IOException, InterruptedException { act(new FileCallable<Void>() { public Void invoke(File f, VirtualChannel channel) throws IOException { Util.deleteContentsRecursive(f); return null; } }); } /** * Gets just the file name portion. * * This method assumes that the file name is the same between local and remote. */ public String getName() { String r = remote; if(r.endsWith("\\") || r.endsWith("/")) r = r.substring(0,r.length()-1); int len = r.length()-1; while(len>=0) { char ch = r.charAt(len); if(ch=='\\' || ch=='/') break; len--; } return r.substring(len+1); } /** * The same as {@code new FilePath(this,rel)} but more OO. */ public FilePath child(String rel) { return new FilePath(this,rel); } /** * Gets the parent file. */ public FilePath getParent() { int len = remote.length()-1; while(len>=0) { char ch = remote.charAt(len); if(ch=='\\' || ch=='/') break; len--; } return new FilePath( channel, remote.substring(0,len) ); } /** * Creates a temporary file in the directory that this {@link FilePath} object designates. */ public FilePath createTempFile(final String prefix, final String suffix) throws IOException, InterruptedException { try { return new FilePath(this,act(new FileCallable<String>() { public String invoke(File dir, VirtualChannel channel) throws IOException { File f = File.createTempFile(prefix, suffix, dir); return f.getName(); } })); } catch (IOException e) { throw new IOException2("Failed to create a temp file on "+remote,e); } } /** * Creates a temporary file in this directory and set the contents by the * given text (encoded in the platform default encoding) */ public FilePath createTextTempFile(final String prefix, final String suffix, final String contents) throws IOException, InterruptedException { return createTextTempFile(prefix,suffix,contents,true); } /** * Creates a temporary file in this directory and set the contents by the * given text (encoded in the platform default encoding) */ public FilePath createTextTempFile(final String prefix, final String suffix, final String contents, final boolean inThisDirectory) throws IOException, InterruptedException { try { return new FilePath(channel,act(new FileCallable<String>() { public String invoke(File dir, VirtualChannel channel) throws IOException { if(!inThisDirectory) dir = new File(System.getProperty("java.io.tmpdir")); else dir.mkdirs(); File f; try { f = File.createTempFile(prefix, suffix, dir); } catch (IOException e) { throw new IOException2("Failed to create a temporary directory in "+dir,e); } Writer w = new FileWriter(f); w.write(contents); w.close(); return f.getAbsolutePath(); } })); } catch (IOException e) { throw new IOException2("Failed to create a temp file on "+remote,e); } } /** * Deletes this file. */ public boolean delete() throws IOException, InterruptedException { return act(new FileCallable<Boolean>() { public Boolean invoke(File f, VirtualChannel channel) throws IOException { return f.delete(); } }); } /** * Checks if the file exists. */ public boolean exists() throws IOException, InterruptedException { return act(new FileCallable<Boolean>() { public Boolean invoke(File f, VirtualChannel channel) throws IOException { return f.exists(); } }); } /** * Gets the last modified time stamp of this file, by using the clock * of the machine where this file actually resides. * * @see File#lastModified() * @see #touch(long) */ public long lastModified() throws IOException, InterruptedException { return act(new FileCallable<Long>() { public Long invoke(File f, VirtualChannel channel) throws IOException { return f.lastModified(); } }); } /** * Creates a file (if not already exist) and sets the timestamp. * * @since 1.299 */ public void touch(final long timestamp) throws IOException, InterruptedException { act(new FileCallable<Void>() { public Void invoke(File f, VirtualChannel channel) throws IOException { if(!f.exists()) new FileOutputStream(f).close(); if(!f.setLastModified(timestamp)) throw new IOException("Failed to set the timestamp of "+f+" to "+timestamp); return null; } }); } /** * Checks if the file is a directory. */ public boolean isDirectory() throws IOException, InterruptedException { return act(new FileCallable<Boolean>() { public Boolean invoke(File f, VirtualChannel channel) throws IOException { return f.isDirectory(); } }); } /** * Returns the file size in bytes. * * @since 1.129 */ public long length() throws IOException, InterruptedException { return act(new FileCallable<Long>() { public Long invoke(File f, VirtualChannel channel) throws IOException { return f.length(); } }); } /** * List up files and directories in this directory. * * <p> * This method returns direct children of the directory denoted by the 'this' object. */ public List<FilePath> list() throws IOException, InterruptedException { return list((FileFilter)null); } /** * List up files in this directory, just like {@link File#listFiles(FileFilter)}. * * @param filter * The optional filter used to narrow down the result. * If non-null, must be {@link Serializable}. * If this {@link FilePath} represents a remote path, * the filter object will be executed on the remote machine. */ public List<FilePath> list(final FileFilter filter) throws IOException, InterruptedException { return act(new FileCallable<List<FilePath>>() { public List<FilePath> invoke(File f, VirtualChannel channel) throws IOException { File[] children = f.listFiles(filter); if(children ==null) return null; ArrayList<FilePath> r = new ArrayList<FilePath>(children.length); for (File child : children) r.add(new FilePath(child)); return r; } }); } /** * List up files in this directory that matches the given Ant-style filter. * * @param includes * See {@link FileSet} for the syntax. String like "foo/*.zip" or "foo/*&#42;/*.xml" * @return * can be empty but always non-null. */ public FilePath[] list(final String includes) throws IOException, InterruptedException { return act(new FileCallable<FilePath[]>() { public FilePath[] invoke(File f, VirtualChannel channel) throws IOException { String[] files = glob(f,includes); FilePath[] r = new FilePath[files.length]; for( int i=0; i<r.length; i++ ) r[i] = new FilePath(new File(f,files[i])); return r; } }); } /** * Runs Ant glob expansion. * * @return * A set of relative file names from the base directory. */ private static String[] glob(File dir, String includes) throws IOException { if(isAbsolute(includes)) throw new IOException("Expecting Ant GLOB pattern, but saw '"+includes+"'. See http://ant.apache.org/manual/CoreTypes/fileset.html for syntax"); FileSet fs = Util.createFileSet(dir,includes); DirectoryScanner ds = fs.getDirectoryScanner(new Project()); String[] files = ds.getIncludedFiles(); return files; } /** * Reads this file. */ public InputStream read() throws IOException { if(channel==null) return new FileInputStream(new File(remote)); final Pipe p = Pipe.createRemoteToLocal(); channel.callAsync(new Callable<Void,IOException>() { public Void call() throws IOException { FileInputStream fis=null; try { fis = new FileInputStream(new File(remote)); Util.copyStream(fis,p.getOut()); return null; } finally { IOUtils.closeQuietly(fis); IOUtils.closeQuietly(p.getOut()); } } }); return p.getIn(); } /** * Writes to this file. * If this file already exists, it will be overwritten. * If the directory doesn't exist, it will be created. */ public OutputStream write() throws IOException, InterruptedException { if(channel==null) { File f = new File(remote).getAbsoluteFile(); f.getParentFile().mkdirs(); return new FileOutputStream(f); } return channel.call(new Callable<OutputStream,IOException>() { public OutputStream call() throws IOException { File f = new File(remote).getAbsoluteFile(); f.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(f); return new RemoteOutputStream(fos); } }); } /** * Overwrites this file by placing the given String as the content. * * @param encoding * Null to use the platform default encoding. * @since 1.105 */ public void write(final String content, final String encoding) throws IOException, InterruptedException { act(new FileCallable<Void>() { public Void invoke(File f, VirtualChannel channel) throws IOException { f.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(f); Writer w = encoding != null ? new OutputStreamWriter(fos, encoding) : new OutputStreamWriter(fos); try { w.write(content); } finally { w.close(); } return null; } }); } /** * Computes the MD5 digest of the file in hex string. */ public String digest() throws IOException, InterruptedException { return act(new FileCallable<String>() { public String invoke(File f, VirtualChannel channel) throws IOException { return Util.getDigestOf(new FileInputStream(f)); } }); } /** * Rename this file/directory to the target filepath. This FilePath and the target must * be on the some host */ public void renameTo(final FilePath target) throws IOException, InterruptedException { if(this.channel != target.channel) { throw new IOException("renameTo target must be on the same host"); } act(new FileCallable<Void>() { public Void invoke(File f, VirtualChannel channel) throws IOException { f.renameTo(new File(target.remote)); return null; } }); } /** * Copies this file to the specified target. */ public void copyTo(FilePath target) throws IOException, InterruptedException { OutputStream out = target.write(); try { copyTo(out); } finally { out.close(); } } /** * Sends the contents of this file into the given {@link OutputStream}. */ public void copyTo(OutputStream os) throws IOException, InterruptedException { final OutputStream out = new RemoteOutputStream(os); act(new FileCallable<Void>() { public Void invoke(File f, VirtualChannel channel) throws IOException { FileInputStream fis = null; try { fis = new FileInputStream(f); Util.copyStream(fis,out); return null; } finally { IOUtils.closeQuietly(fis); IOUtils.closeQuietly(out); } } }); } /** * Remoting interface used for {@link FilePath#copyRecursiveTo(String, FilePath)}. * * TODO: this might not be the most efficient way to do the copy. */ interface RemoteCopier { /** * @param fileName * relative path name to the output file. Path separator must be '/'. */ void open(String fileName) throws IOException; void write(byte[] buf, int len) throws IOException; void close() throws IOException; } public int copyRecursiveTo(String fileMask, FilePath target) throws IOException, InterruptedException { return copyRecursiveTo(fileMask,null,target); } /** * Copies the files that match the given file mask to the specified target node. * * @param fileMask * Ant GLOB pattern. * String like "foo/bar/*.xml" Multiple patterns can be separated * by ',', and whitespace can surround ',' (so that you can write * "abc, def" and "abc,def" to mean the same thing. * @param excludes * Files to be excluded. Can be null. * @return * the number of files copied. */ public int copyRecursiveTo(final String fileMask, final String excludes, final FilePath target) throws IOException, InterruptedException { if(this.channel==target.channel) { // local to local copy. return act(new FileCallable<Integer>() { public Integer invoke(File base, VirtualChannel channel) throws IOException { if(!base.exists()) return 0; assert target.channel==null; try { class CopyImpl extends Copy { private int copySize; public CopyImpl() { setProject(new org.apache.tools.ant.Project()); } protected void doFileOperations() { copySize = super.fileCopyMap.size(); super.doFileOperations(); } public int getNumCopied() { return copySize; } } CopyImpl copyTask = new CopyImpl(); copyTask.setTodir(new File(target.remote)); copyTask.addFileset(Util.createFileSet(base,fileMask,excludes)); copyTask.setIncludeEmptyDirs(false); copyTask.execute(); return copyTask.getNumCopied(); } catch (BuildException e) { throw new IOException2("Failed to copy "+base+"/"+fileMask+" to "+target,e); } } }); } else if(this.channel==null) { // local -> remote copy final Pipe pipe = Pipe.createLocalToRemote(); Future<Void> future = target.actAsync(new FileCallable<Void>() { public Void invoke(File f, VirtualChannel channel) throws IOException { try { readFromTar(remote+'/'+fileMask, f,TarCompression.GZIP.extract(pipe.getIn())); return null; } finally { pipe.getIn().close(); } } }); int r = writeToTar(new File(remote),fileMask,excludes,TarCompression.GZIP.compress(pipe.getOut())); try { future.get(); } catch (ExecutionException e) { throw new IOException2(e); } return r; } else { // remote -> local copy final Pipe pipe = Pipe.createRemoteToLocal(); Future<Integer> future = actAsync(new FileCallable<Integer>() { public Integer invoke(File f, VirtualChannel channel) throws IOException { try { return writeToTar(f,fileMask,excludes,TarCompression.GZIP.compress(pipe.getOut())); } finally { pipe.getOut().close(); } } }); try { readFromTar(remote+'/'+fileMask,new File(target.remote),TarCompression.GZIP.extract(pipe.getIn())); } catch (IOException e) {// BuildException or IOException try { future.get(3,TimeUnit.SECONDS); throw e; // the remote side completed successfully, so the error must be local } catch (ExecutionException x) { // report both errors throw new IOException2(Functions.printThrowable(e),x); } catch (TimeoutException _) { // remote is hanging throw e; } } try { return future.get(); } catch (ExecutionException e) { throw new IOException2(e); } } } /** * Writes to a tar stream and stores obtained files to the base dir. * * @return * number of files/directories that are written. */ private Integer writeToTar(File baseDir, String fileMask, String excludes, OutputStream out) throws IOException { FileSet fs = Util.createFileSet(baseDir,fileMask,excludes); byte[] buf = new byte[8192]; TarOutputStream tar = new TarOutputStream(new BufferedOutputStream(out)); tar.setLongFileMode(TarOutputStream.LONGFILE_GNU); String[] files; if(baseDir.exists()) { DirectoryScanner ds = fs.getDirectoryScanner(new org.apache.tools.ant.Project()); files = ds.getIncludedFiles(); } else { files = new String[0]; } for( String f : files) { if(Functions.isWindows()) f = f.replace('\\','/'); File file = new File(baseDir, f); TarEntry te = new TarEntry(f); te.setModTime(file.lastModified()); if(!file.isDirectory()) te.setSize(file.length()); tar.putNextEntry(te); if (!file.isDirectory()) { FileInputStream in = new FileInputStream(file); int len; while((len=in.read(buf))>=0) tar.write(buf,0,len); in.close(); } tar.closeEntry(); } tar.close(); return files.length; } /** * Reads from a tar stream and stores obtained files to the base dir. */ private static void readFromTar(String name, File baseDir, InputStream in) throws IOException { TarInputStream t = new TarInputStream(in); try { TarEntry te; while ((te = t.getNextEntry()) != null) { File f = new File(baseDir,te.getName()); if(te.isDirectory()) { f.mkdirs(); } else { File parent = f.getParentFile(); if (parent != null) parent.mkdirs(); OutputStream fos = new FileOutputStream(f); try { IOUtils.copy(t,fos); } finally { fos.close(); } f.setLastModified(te.getModTime().getTime()); int mode = te.getMode()&0777; if(mode!=0 && !Hudson.isWindows()) // be defensive GNUCLibrary.LIBC.chmod(f.getPath(),mode); } } } catch(IOException e) { throw new IOException2("Failed to extract "+name,e); } finally { t.close(); } } /** * Creates a {@link Launcher} for starting processes on the node * that has this file. * @since 1.89 */ public Launcher createLauncher(TaskListener listener) throws IOException, InterruptedException { if(channel==null) return new LocalLauncher(listener); else return new RemoteLauncher(listener,channel,channel.call(new IsUnix())); } private static final class IsUnix implements Callable<Boolean,IOException> { public Boolean call() throws IOException { return File.pathSeparatorChar==':'; } private static final long serialVersionUID = 1L; } /** * Validates the ant file mask (like "foo/bar/*.txt, zot/*.jar") * against this directory, and try to point out the problem. * * <p> * This is useful in conjunction with {@link FormValidation}. * * @return * null if no error was found. Otherwise returns a human readable error message. * @since 1.90 * @see #validateFileMask(FilePath, String) */ public String validateAntFileMask(final String fileMasks) throws IOException, InterruptedException { return act(new FileCallable<String>() { public String invoke(File dir, VirtualChannel channel) throws IOException { if(fileMasks.startsWith("~")) return Messages.FilePath_TildaDoesntWork(); StringTokenizer tokens = new StringTokenizer(fileMasks,","); while(tokens.hasMoreTokens()) { final String fileMask = tokens.nextToken().trim(); if(hasMatch(dir,fileMask)) continue; // no error on this portion // in 1.172 we introduced an incompatible change to stop using ' ' as the separator // so see if we can match by using ' ' as the separator if(fileMask.contains(" ")) { boolean matched = true; for (String token : Util.tokenize(fileMask)) matched &= hasMatch(dir,token); if(matched) return Messages.FilePath_validateAntFileMask_whitespaceSeprator(); } // a common mistake is to assume the wrong base dir, and there are two variations // to this: (1) the user gave us aa/bb/cc/dd where cc/dd was correct // and (2) the user gave us cc/dd where aa/bb/cc/dd was correct. {// check the (1) above first String f=fileMask; while(true) { int idx = findSeparator(f); if(idx==-1) break; f=f.substring(idx+1); if(hasMatch(dir,f)) return Messages.FilePath_validateAntFileMask_doesntMatchAndSuggest(fileMask,f); } } {// check the (1) above next as this is more expensive. // Try prepending "**/" to see if that results in a match FileSet fs = Util.createFileSet(dir,"**/"+fileMask); DirectoryScanner ds = fs.getDirectoryScanner(new Project()); if(ds.getIncludedFilesCount()!=0) { // try shorter name first so that the suggestion results in least amount of changes String[] names = ds.getIncludedFiles(); Arrays.sort(names,SHORTER_STRING_FIRST); for( String f : names) { // now we want to decompose f to the leading portion that matched "**" // and the trailing portion that matched the file mask, so that // we can suggest the user error. // // this is not a very efficient/clever way to do it, but it's relatively simple String prefix=""; while(true) { int idx = findSeparator(f); if(idx==-1) break; prefix+=f.substring(0,idx)+'/'; f=f.substring(idx+1); if(hasMatch(dir,prefix+fileMask)) return Messages.FilePath_validateAntFileMask_doesntMatchAndSuggest(fileMask, prefix+fileMask); } } } } {// finally, see if we can identify any sub portion that's valid. Otherwise bail out String previous = null; String pattern = fileMask; while(true) { if(hasMatch(dir,pattern)) { // found a match if(previous==null) return String.format("'%s' doesn't match anything, although '%s' exists", fileMask, pattern ); else return String.format("'%s' doesn't match anything: '%s' exists but not '%s'", fileMask, pattern, previous ); } int idx = findSeparator(pattern); if(idx<0) {// no more path component left to go back if(pattern.equals(fileMask)) return String.format("'%s' doesn't match anything", fileMask ); else return String.format("'%s' doesn't match anything: even '%s' doesn't exist", fileMask, pattern ); } // cut off the trailing component and try again previous = pattern; pattern = pattern.substring(0,idx); } } } return null; // no error } private boolean hasMatch(File dir, String pattern) { FileSet fs = Util.createFileSet(dir,pattern); DirectoryScanner ds = fs.getDirectoryScanner(new Project()); return ds.getIncludedFilesCount()!=0 || ds.getIncludedDirsCount()!=0; } /** * Finds the position of the first path separator. */ private int findSeparator(String pattern) { int idx1 = pattern.indexOf('\\'); int idx2 = pattern.indexOf('/'); if(idx1==-1) return idx2; if(idx2==-1) return idx1; return Math.min(idx1,idx2); } }); } /** * Shortcut for {@link #validateFileMask(String)} in case the left-hand side can be null. */ public static FormValidation validateFileMask(FilePath pathOrNull, String value) throws IOException { if(pathOrNull==null) return FormValidation.ok(); return pathOrNull.validateFileMask(value); } /** * Short for {@code validateFileMask(value,true)} */ public FormValidation validateFileMask(String value) throws IOException { return validateFileMask(value,true); } /** * Checks the GLOB-style file mask. See {@link #validateAntFileMask(String)} * @since 1.294 */ public FormValidation validateFileMask(String value, boolean errorIfNotExist) throws IOException { value = fixEmpty(value); if(value==null) return FormValidation.ok(); try { if(!exists()) // no workspace. can't check return FormValidation.ok(); String msg = validateAntFileMask(value); if(errorIfNotExist) return FormValidation.error(msg); else return FormValidation.warning(msg); } catch (InterruptedException e) { return FormValidation.ok(); } } /** * Validates a relative file path from this {@link FilePath}. * * @param value * The relative path being validated. * @param errorIfNotExist * If true, report an error if the given relative path doesn't exist. Otherwise it's a warning. * @param expectingFile * If true, we expect the relative path to point to a file. * Otherwise, the relative path is expected to be pointing to a directory. */ public FormValidation validateRelativePath(String value, boolean errorIfNotExist, boolean expectingFile) throws IOException { AbstractProject subject = Stapler.getCurrentRequest().findAncestorObject(AbstractProject.class); subject.checkPermission(Item.CONFIGURE); value = fixEmpty(value); // none entered yet, or something is seriously wrong if(value==null || (AbstractProject<?,?>)subject ==null) return FormValidation.ok(); // a common mistake is to use wildcard if(value.contains("*")) return FormValidation.error("Wildcard is not allowed here"); try { if(!exists()) // no base directory. can't check return FormValidation.ok(); FilePath path = child(value); if(path.exists()) { if (expectingFile) { if(!path.isDirectory()) return FormValidation.ok(); else return FormValidation.error(value+" is not a file"); } else { if(path.isDirectory()) return FormValidation.ok(); else return FormValidation.error(value+" is not a directory"); } } String msg = "No such "+(expectingFile?"file":"directory")+": " + value; if(errorIfNotExist) return FormValidation.error(msg); else return FormValidation.warning(msg); } catch (InterruptedException e) { return FormValidation.ok(); } } /** * A convenience method over {@link #validateRelativePath(String, boolean, boolean)}. */ public FormValidation validateRelativeDirectory(String value, boolean errorIfNotExist) throws IOException { return validateRelativePath(value,errorIfNotExist,false); } public FormValidation validateRelativeDirectory(String value) throws IOException { return validateRelativeDirectory(value,true); } @Deprecated public String toString() { // to make writing JSPs easily, return local return remote; } public VirtualChannel getChannel() { if(channel!=null) return channel; else return Hudson.MasterComputer.localChannel; } /** * Returns true if this {@link FilePath} represents a remote file. */ public boolean isRemote() { return channel!=null; } private void writeObject(ObjectOutputStream oos) throws IOException { Channel target = Channel.current(); if(channel!=null && channel!=target) throw new IllegalStateException("Can't send a remote FilePath to a different remote channel"); oos.defaultWriteObject(); oos.writeBoolean(channel==null); } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { Channel channel = Channel.current(); assert channel!=null; ois.defaultReadObject(); if(ois.readBoolean()) { this.channel = channel; } else { this.channel = null; } } private static final long serialVersionUID = 1L; public static int SIDE_BUFFER_SIZE = 1024; /** * Adapts {@link FileCallable} to {@link Callable}. */ private class FileCallableWrapper<T> implements DelegatingCallable<T,IOException> { private final FileCallable<T> callable; public FileCallableWrapper(FileCallable<T> callable) { this.callable = callable; } public T call() throws IOException { return callable.invoke(new File(remote), Channel.current()); } public ClassLoader getClassLoader() { return callable.getClass().getClassLoader(); } private static final long serialVersionUID = 1L; } private static final Comparator<String> SHORTER_STRING_FIRST = new Comparator<String>() { public int compare(String o1, String o2) { return o1.length()-o2.length(); } }; }
core/src/main/java/hudson/FilePath.java
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Eric Lefevre-Ardant, Erik Ramfelt, Michael B. Donohue * * 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 hudson; import hudson.Launcher.LocalLauncher; import hudson.Launcher.RemoteLauncher; import hudson.model.Hudson; import hudson.model.TaskListener; import hudson.model.AbstractProject; import hudson.model.Item; import hudson.remoting.Callable; import hudson.remoting.Channel; import hudson.remoting.DelegatingCallable; import hudson.remoting.Future; import hudson.remoting.Pipe; import hudson.remoting.RemoteOutputStream; import hudson.remoting.VirtualChannel; import hudson.remoting.RemoteInputStream; import hudson.util.IOException2; import hudson.util.HeadBufferingStream; import hudson.util.FormValidation; import hudson.util.jna.GNUCLibrary; import static hudson.Util.fixEmpty; import static hudson.FilePath.TarCompression.GZIP; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Copy; import org.apache.tools.ant.types.FileSet; import org.apache.tools.tar.TarEntry; import org.apache.tools.tar.TarOutputStream; import org.apache.tools.tar.TarInputStream; import org.apache.tools.zip.ZipOutputStream; import org.apache.tools.zip.ZipEntry; import org.apache.commons.io.IOUtils; import org.apache.commons.fileupload.FileItem; import org.kohsuke.stapler.Stapler; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.io.Writer; import java.io.OutputStreamWriter; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.Arrays; import java.util.Comparator; import java.util.regex.Pattern; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.zip.GZIPOutputStream; import java.util.zip.GZIPInputStream; import java.util.zip.ZipInputStream; /** * {@link File} like object with remoting support. * * <p> * Unlike {@link File}, which always implies a file path on the current computer, * {@link FilePath} represents a file path on a specific slave or the master. * * Despite that, {@link FilePath} can be used much like {@link File}. It exposes * a bunch of operations (and we should add more operations as long as they are * generally useful), and when invoked against a file on a remote node, {@link FilePath} * executes the necessary code remotely, thereby providing semi-transparent file * operations. * * <h2>Using {@link FilePath} smartly</h2> * <p> * The transparency makes it easy to write plugins without worrying too much about * remoting, by making it works like NFS, where remoting happens at the file-system * later. * * <p> * But one should note that such use of remoting may not be optional. Sometimes, * it makes more sense to move some computation closer to the data, as opposed to * move the data to the computation. For example, if you are just computing a MD5 * digest of a file, then it would make sense to do the digest on the host where * the file is located, as opposed to send the whole data to the master and do MD5 * digesting there. * * <p> * {@link FilePath} supports this "code migration" by in the * {@link #act(FileCallable)} method. One can pass in a custom implementation * of {@link FileCallable}, to be executed on the node where the data is located. * The following code shows the example: * * <pre> * FilePath file = ...; * * // make 'file' a fresh empty directory. * file.act(new FileCallable&lt;Void>() { * // if 'file' is on a different node, this FileCallable will * // be transfered to that node and executed there. * public Void invoke(File f,VirtualChannel channel) { * // f and file represents the same thing * f.deleteContents(); * f.mkdirs(); * } * }); * </pre> * * <p> * When {@link FileCallable} is transfered to a remote node, it will be done so * by using the same Java serialization scheme that the remoting module uses. * See {@link Channel} for more about this. * * <p> * {@link FilePath} itself can be sent over to a remote node as a part of {@link Callable} * serialization. For example, sending a {@link FilePath} of a remote node to that * node causes {@link FilePath} to become "local". Similarly, sending a * {@link FilePath} that represents the local computer causes it to become "remote." * * @author Kohsuke Kawaguchi */ public final class FilePath implements Serializable { /** * When this {@link FilePath} represents the remote path, * this field is always non-null on master (the field represents * the channel to the remote slave.) When transferred to a slave via remoting, * this field reverts back to null, since it's transient. * * When this {@link FilePath} represents a path on the master, * this field is null on master. When transferred to a slave via remoting, * this field becomes non-null, representing the {@link Channel} * back to the master. * * This is used to determine whether we are running on the master or the slave. */ private transient VirtualChannel channel; // since the platform of the slave might be different, can't use java.io.File private final String remote; /** * Creates a {@link FilePath} that represents a path on the given node. * * @param channel * To create a path that represents a remote path, pass in a {@link Channel} * that's connected to that machine. If null, that means the local file path. */ public FilePath(VirtualChannel channel, String remote) { this.channel = channel; this.remote = remote; } /** * To create {@link FilePath} that represents a "local" path. * * <p> * A "local" path means a file path on the computer where the * constructor invocation happened. */ public FilePath(File localPath) { this.channel = null; this.remote = localPath.getPath(); } public FilePath(FilePath base, String rel) { this.channel = base.channel; if(isAbsolute(rel)) { // absolute this.remote = rel; } else if(base.isUnix()) { this.remote = base.remote+'/'+rel; } else { this.remote = base.remote+'\\'+rel; } } private static boolean isAbsolute(String rel) { return rel.startsWith("/") || DRIVE_PATTERN.matcher(rel).matches(); } private static final Pattern DRIVE_PATTERN = Pattern.compile("[A-Za-z]:\\\\.+"); /** * Checks if the remote path is Unix. */ private boolean isUnix() { // if the path represents a local path, there' no need to guess. if(!isRemote()) return File.pathSeparatorChar!=';'; // note that we can't use the usual File.pathSeparator and etc., as the OS of // the machine where this code runs and the OS that this FilePath refers to may be different. // Windows absolute path is 'X:\...', so this is usually a good indication of Windows path if(remote.length()>3 && remote.charAt(1)==':' && remote.charAt(2)=='\\') return false; // Windows can handle '/' as a path separator but Unix can't, // so err on Unix side return remote.indexOf("\\")==-1; } public String getRemote() { return remote; } /** * Creates a zip file from this directory or a file and sends that to the given output stream. */ public void createZipArchive(OutputStream os) throws IOException, InterruptedException { final OutputStream out = (channel!=null)?new RemoteOutputStream(os):os; act(new FileCallable<Void>() { private transient byte[] buf; public Void invoke(File f, VirtualChannel channel) throws IOException { buf = new byte[8192]; ZipOutputStream zip = new ZipOutputStream(out); zip.setEncoding(System.getProperty("file.encoding")); scan(f,zip,""); zip.close(); return null; } private void scan(File f, ZipOutputStream zip, String path) throws IOException { // Bitmask indicating directories in 'external attributes' of a ZIP archive entry. final long BITMASK_IS_DIRECTORY = 1<<4; if (f.canRead()) { if(f.isDirectory()) { ZipEntry dirZipEntry = new ZipEntry(path+f.getName()+'/'); // Setting this bit explicitly is needed by some unzipping applications (see HUDSON-3294). dirZipEntry.setExternalAttributes(BITMASK_IS_DIRECTORY); zip.putNextEntry(dirZipEntry); zip.closeEntry(); for( File child : f.listFiles() ) scan(child,zip,path+f.getName()+'/'); } else { zip.putNextEntry(new ZipEntry(path+f.getName())); FileInputStream in = new FileInputStream(f); int len; while((len=in.read(buf))>0) zip.write(buf,0,len); in.close(); zip.closeEntry(); } } } private static final long serialVersionUID = 1L; }); } /** * Creates a zip file from this directory by only including the files that match the given glob. * * @param glob * Ant style glob, like "**&#x2F;*.xml". If empty or null, this method * works like {@link #createZipArchive(OutputStream)} * * @since 1.129 */ public void createZipArchive(OutputStream os, final String glob) throws IOException, InterruptedException { if(glob==null || glob.length()==0) { createZipArchive(os); return; } final OutputStream out = (channel!=null)?new RemoteOutputStream(os):os; act(new FileCallable<Void>() { public Void invoke(File dir, VirtualChannel channel) throws IOException { byte[] buf = new byte[8192]; ZipOutputStream zip = new ZipOutputStream(out); zip.setEncoding(System.getProperty("file.encoding")); for( String entry : glob(dir,glob) ) { File file = new File(dir,entry); if (file.canRead()) { zip.putNextEntry(new ZipEntry(dir.getName()+'/'+entry)); FileInputStream in = new FileInputStream(file); int len; while((len=in.read(buf))>0) zip.write(buf,0,len); in.close(); zip.closeEntry(); } } zip.close(); return null; } private static final long serialVersionUID = 1L; }); } /** * When this {@link FilePath} represents a zip file, extracts that zip file. * * @param target * Target directory to expand files to. All the necessary directories will be created. * @since 1.248 * @see #unzipFrom(InputStream) */ public void unzip(final FilePath target) throws IOException, InterruptedException { target.act(new FileCallable<Void>() { public Void invoke(File dir, VirtualChannel channel) throws IOException { unzip(dir,FilePath.this.read()); return null; } private static final long serialVersionUID = 1L; }); } /** * When this {@link FilePath} represents a tar file, extracts that tar file. * * @param target * Target directory to expand files to. All the necessary directories will be created. * @param compression * Compression mode of this tar file. * @since 1.292 * @see #untarFrom(InputStream, TarCompression) */ public void untar(final FilePath target, final TarCompression compression) throws IOException, InterruptedException { target.act(new FileCallable<Void>() { public Void invoke(File dir, VirtualChannel channel) throws IOException { readFromTar(FilePath.this.getName(),dir,compression.extract(FilePath.this.read())); return null; } private static final long serialVersionUID = 1L; }); } /** * Reads the given InputStream as a zip file and extracts it into this directory. * * @param _in * The stream will be closed by this method after it's fully read. * @since 1.283 * @see #unzip(FilePath) */ public void unzipFrom(InputStream _in) throws IOException, InterruptedException { final InputStream in = new RemoteInputStream(_in); act(new FileCallable<Void>() { public Void invoke(File dir, VirtualChannel channel) throws IOException { unzip(dir, in); return null; } private static final long serialVersionUID = 1L; }); } private void unzip(File dir, InputStream in) throws IOException { dir = dir.getAbsoluteFile(); // without absolutization, getParentFile below seems to fail ZipInputStream zip = new ZipInputStream(in); java.util.zip.ZipEntry e; try { while((e=zip.getNextEntry())!=null) { File f = new File(dir,e.getName()); if(e.isDirectory()) { f.mkdirs(); } else { File p = f.getParentFile(); if(p!=null) p.mkdirs(); FileOutputStream out = new FileOutputStream(f); try { IOUtils.copy(zip, out); } finally { out.close(); } f.setLastModified(e.getTime()); zip.closeEntry(); } } } finally { zip.close(); } } /** * Supported tar file compression methods. */ public enum TarCompression { NONE { public InputStream extract(InputStream in) { return in; } public OutputStream compress(OutputStream out) { return out; } }, GZIP { public InputStream extract(InputStream _in) throws IOException { HeadBufferingStream in = new HeadBufferingStream(_in,SIDE_BUFFER_SIZE); try { return new GZIPInputStream(in); } catch (IOException e) { // various people reported "java.io.IOException: Not in GZIP format" here, so diagnose this problem better in.fillSide(); throw new IOException2(e.getMessage()+"\nstream="+Util.toHexString(in.getSideBuffer()),e); } } public OutputStream compress(OutputStream out) throws IOException { return new GZIPOutputStream(out); } }; public abstract InputStream extract(InputStream in) throws IOException; public abstract OutputStream compress(OutputStream in) throws IOException; } /** * Reads the given InputStream as a tar file and extracts it into this directory. * * @param _in * The stream will be closed by this method after it's fully read. * @param compression * The compression method in use. * @since 1.292 */ public void untarFrom(InputStream _in, final TarCompression compression) throws IOException, InterruptedException { try { final InputStream in = new RemoteInputStream(_in); act(new FileCallable<Void>() { public Void invoke(File dir, VirtualChannel channel) throws IOException { readFromTar("input stream",dir, compression.extract(new BufferedInputStream(in))); return null; } private static final long serialVersionUID = 1L; }); } finally { IOUtils.closeQuietly(_in); } } /** * Given a tgz/zip file, extracts it to the given target directory, if necessary. * * <p> * This method is a convenience method designed for installing a binary package to a location * that supports upgrade and downgrade. Specifically, * * <ul> * <li>If the target directory doesn't exit {@linkplain #mkdirs() it'll be created}. * <li>The timestamp of the .tgz file is left in the installation directory upon extraction. * <li>If the timestamp left in the directory doesn't match with the timestamp of the current archive file, * the directory contents will be discarded and the archive file will be re-extracted. * </ul> * * @param archive * The resource that represents the tgz/zip file. This URL must support the "Last-Modified" header. * (Most common usage is to get this from {@link ClassLoader#getResource(String)}) * @param listener * If non-null, a message will be printed to this listener once this method decides to * extract an archive. * @return * true if the archive was extracted. false if the extraction was skipped because the target directory * was considered up to date. * @since 1.299 */ public boolean installIfNecessaryFrom(URL archive, TaskListener listener, String message) throws IOException, InterruptedException { URLConnection con = archive.openConnection(); long sourceTimestamp = con.getLastModified(); FilePath timestamp = this.child(".timestamp"); if(this.exists()) { if(timestamp.exists() && sourceTimestamp ==timestamp.lastModified()) return false; // already up to date this.deleteContents(); } if(listener!=null) listener.getLogger().println(message); if(archive.toExternalForm().endsWith(".zip")) unzipFrom(con.getInputStream()); else untarFrom(con.getInputStream(),GZIP); timestamp.touch(sourceTimestamp); return true; } /** * Reads the URL on the current VM, and writes all the data to this {@link FilePath} * (this is different from resolving URL remotely.) * * @since 1.293 */ public void copyFrom(URL url) throws IOException, InterruptedException { InputStream in = url.openStream(); try { copyFrom(in); } finally { in.close(); } } /** * Replaces the content of this file by the data from the given {@link InputStream}. * * @since 1.293 */ public void copyFrom(InputStream in) throws IOException, InterruptedException { OutputStream os = write(); try { IOUtils.copy(in, os); } finally { os.close(); } } /** * Place the data from {@link FileItem} into the file location specified by this {@link FilePath} object. */ public void copyFrom(FileItem file) throws IOException, InterruptedException { if(channel==null) { try { file.write(new File(remote)); } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException2(e); } } else { InputStream i = file.getInputStream(); OutputStream o = write(); try { IOUtils.copy(i,o); } finally { o.close(); i.close(); } } } /** * Code that gets executed on the machine where the {@link FilePath} is local. * Used to act on {@link FilePath}. * * @see FilePath#act(FileCallable) */ public static interface FileCallable<T> extends Serializable { /** * Performs the computational task on the node where the data is located. * * @param f * {@link File} that represents the local file that {@link FilePath} has represented. * @param channel * The "back pointer" of the {@link Channel} that represents the communication * with the node from where the code was sent. */ T invoke(File f, VirtualChannel channel) throws IOException; } /** * Executes some program on the machine that this {@link FilePath} exists, * so that one can perform local file operations. */ public <T> T act(final FileCallable<T> callable) throws IOException, InterruptedException { if(channel!=null) { // run this on a remote system try { return channel.call(new FileCallableWrapper<T>(callable)); } catch (IOException e) { // wrap it into a new IOException so that we get the caller's stack trace as well. throw new IOException2("remote file operation failed",e); } } else { // the file is on the local machine. return callable.invoke(new File(remote), Hudson.MasterComputer.localChannel); } } /** * Executes some program on the machine that this {@link FilePath} exists, * so that one can perform local file operations. */ public <T> Future<T> actAsync(final FileCallable<T> callable) throws IOException, InterruptedException { try { return (channel!=null ? channel : Hudson.MasterComputer.localChannel) .callAsync(new FileCallableWrapper<T>(callable)); } catch (IOException e) { // wrap it into a new IOException so that we get the caller's stack trace as well. throw new IOException2("remote file operation failed",e); } } /** * Executes some program on the machine that this {@link FilePath} exists, * so that one can perform local file operations. */ public <V,E extends Throwable> V act(Callable<V,E> callable) throws IOException, InterruptedException, E { if(channel!=null) { // run this on a remote system return channel.call(callable); } else { // the file is on the local machine return callable.call(); } } /** * Converts this file to the URI, relative to the machine * on which this file is available. */ public URI toURI() throws IOException, InterruptedException { return act(new FileCallable<URI>() { public URI invoke(File f, VirtualChannel channel) { return f.toURI(); } }); } /** * Creates this directory. */ public void mkdirs() throws IOException, InterruptedException { if(!act(new FileCallable<Boolean>() { public Boolean invoke(File f, VirtualChannel channel) throws IOException { if(f.mkdirs() || f.exists()) return true; // OK // following Ant <mkdir> task to avoid possible race condition. try { Thread.sleep(10); } catch (InterruptedException e) { // ignore } return f.mkdirs() || f.exists(); } })) throw new IOException("Failed to mkdirs: "+remote); } /** * Deletes this directory, including all its contents recursively. */ public void deleteRecursive() throws IOException, InterruptedException { act(new FileCallable<Void>() { public Void invoke(File f, VirtualChannel channel) throws IOException { Util.deleteRecursive(f); return null; } }); } /** * Deletes all the contents of this directory, but not the directory itself */ public void deleteContents() throws IOException, InterruptedException { act(new FileCallable<Void>() { public Void invoke(File f, VirtualChannel channel) throws IOException { Util.deleteContentsRecursive(f); return null; } }); } /** * Gets just the file name portion. * * This method assumes that the file name is the same between local and remote. */ public String getName() { String r = remote; if(r.endsWith("\\") || r.endsWith("/")) r = r.substring(0,r.length()-1); int len = r.length()-1; while(len>=0) { char ch = r.charAt(len); if(ch=='\\' || ch=='/') break; len--; } return r.substring(len+1); } /** * The same as {@code new FilePath(this,rel)} but more OO. */ public FilePath child(String rel) { return new FilePath(this,rel); } /** * Gets the parent file. */ public FilePath getParent() { int len = remote.length()-1; while(len>=0) { char ch = remote.charAt(len); if(ch=='\\' || ch=='/') break; len--; } return new FilePath( channel, remote.substring(0,len) ); } /** * Creates a temporary file in the directory that this {@link FilePath} object designates. */ public FilePath createTempFile(final String prefix, final String suffix) throws IOException, InterruptedException { try { return new FilePath(this,act(new FileCallable<String>() { public String invoke(File dir, VirtualChannel channel) throws IOException { File f = File.createTempFile(prefix, suffix, dir); return f.getName(); } })); } catch (IOException e) { throw new IOException2("Failed to create a temp file on "+remote,e); } } /** * Creates a temporary file in this directory and set the contents by the * given text (encoded in the platform default encoding) */ public FilePath createTextTempFile(final String prefix, final String suffix, final String contents) throws IOException, InterruptedException { return createTextTempFile(prefix,suffix,contents,true); } /** * Creates a temporary file in this directory and set the contents by the * given text (encoded in the platform default encoding) */ public FilePath createTextTempFile(final String prefix, final String suffix, final String contents, final boolean inThisDirectory) throws IOException, InterruptedException { try { return new FilePath(channel,act(new FileCallable<String>() { public String invoke(File dir, VirtualChannel channel) throws IOException { if(!inThisDirectory) dir = new File(System.getProperty("java.io.tmpdir")); else dir.mkdirs(); File f; try { f = File.createTempFile(prefix, suffix, dir); } catch (IOException e) { throw new IOException2("Failed to create a temporary directory in "+dir,e); } Writer w = new FileWriter(f); w.write(contents); w.close(); return f.getAbsolutePath(); } })); } catch (IOException e) { throw new IOException2("Failed to create a temp file on "+remote,e); } } /** * Deletes this file. */ public boolean delete() throws IOException, InterruptedException { return act(new FileCallable<Boolean>() { public Boolean invoke(File f, VirtualChannel channel) throws IOException { return f.delete(); } }); } /** * Checks if the file exists. */ public boolean exists() throws IOException, InterruptedException { return act(new FileCallable<Boolean>() { public Boolean invoke(File f, VirtualChannel channel) throws IOException { return f.exists(); } }); } /** * Gets the last modified time stamp of this file, by using the clock * of the machine where this file actually resides. * * @see File#lastModified() * @see #touch(long) */ public long lastModified() throws IOException, InterruptedException { return act(new FileCallable<Long>() { public Long invoke(File f, VirtualChannel channel) throws IOException { return f.lastModified(); } }); } /** * Creates a file (if not already exist) and sets the timestamp. * * @since 1.299 */ public void touch(final long timestamp) throws IOException, InterruptedException { act(new FileCallable<Void>() { public Void invoke(File f, VirtualChannel channel) throws IOException { if(!f.exists()) new FileOutputStream(f).close(); if(!f.setLastModified(timestamp)) throw new IOException("Failed to set the timestamp of "+f+" to "+timestamp); return null; } }); } /** * Checks if the file is a directory. */ public boolean isDirectory() throws IOException, InterruptedException { return act(new FileCallable<Boolean>() { public Boolean invoke(File f, VirtualChannel channel) throws IOException { return f.isDirectory(); } }); } /** * Returns the file size in bytes. * * @since 1.129 */ public long length() throws IOException, InterruptedException { return act(new FileCallable<Long>() { public Long invoke(File f, VirtualChannel channel) throws IOException { return f.length(); } }); } /** * List up files and directories in this directory. * * <p> * This method returns direct children of the directory denoted by the 'this' object. */ public List<FilePath> list() throws IOException, InterruptedException { return list((FileFilter)null); } /** * List up files in this directory, just like {@link File#listFiles(FileFilter)}. * * @param filter * The optional filter used to narrow down the result. * If non-null, must be {@link Serializable}. * If this {@link FilePath} represents a remote path, * the filter object will be executed on the remote machine. */ public List<FilePath> list(final FileFilter filter) throws IOException, InterruptedException { return act(new FileCallable<List<FilePath>>() { public List<FilePath> invoke(File f, VirtualChannel channel) throws IOException { File[] children = f.listFiles(filter); if(children ==null) return null; ArrayList<FilePath> r = new ArrayList<FilePath>(children.length); for (File child : children) r.add(new FilePath(child)); return r; } }); } /** * List up files in this directory that matches the given Ant-style filter. * * @param includes * See {@link FileSet} for the syntax. String like "foo/*.zip" or "foo/*&#42;/*.xml" * @return * can be empty but always non-null. */ public FilePath[] list(final String includes) throws IOException, InterruptedException { return act(new FileCallable<FilePath[]>() { public FilePath[] invoke(File f, VirtualChannel channel) throws IOException { String[] files = glob(f,includes); FilePath[] r = new FilePath[files.length]; for( int i=0; i<r.length; i++ ) r[i] = new FilePath(new File(f,files[i])); return r; } }); } /** * Runs Ant glob expansion. * * @return * A set of relative file names from the base directory. */ private static String[] glob(File dir, String includes) throws IOException { if(isAbsolute(includes)) throw new IOException("Expecting Ant GLOB pattern, but saw '"+includes+"'. See http://ant.apache.org/manual/CoreTypes/fileset.html for syntax"); FileSet fs = Util.createFileSet(dir,includes); DirectoryScanner ds = fs.getDirectoryScanner(new Project()); String[] files = ds.getIncludedFiles(); return files; } /** * Reads this file. */ public InputStream read() throws IOException { if(channel==null) return new FileInputStream(new File(remote)); final Pipe p = Pipe.createRemoteToLocal(); channel.callAsync(new Callable<Void,IOException>() { public Void call() throws IOException { FileInputStream fis=null; try { fis = new FileInputStream(new File(remote)); Util.copyStream(fis,p.getOut()); return null; } finally { IOUtils.closeQuietly(fis); IOUtils.closeQuietly(p.getOut()); } } }); return p.getIn(); } /** * Writes to this file. * If this file already exists, it will be overwritten. * If the directory doesn't exist, it will be created. */ public OutputStream write() throws IOException, InterruptedException { if(channel==null) { File f = new File(remote).getAbsoluteFile(); f.getParentFile().mkdirs(); return new FileOutputStream(f); } return channel.call(new Callable<OutputStream,IOException>() { public OutputStream call() throws IOException { File f = new File(remote).getAbsoluteFile(); f.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(f); return new RemoteOutputStream(fos); } }); } /** * Overwrites this file by placing the given String as the content. * * @param encoding * Null to use the platform default encoding. * @since 1.105 */ public void write(final String content, final String encoding) throws IOException, InterruptedException { act(new FileCallable<Void>() { public Void invoke(File f, VirtualChannel channel) throws IOException { f.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(f); Writer w = encoding != null ? new OutputStreamWriter(fos, encoding) : new OutputStreamWriter(fos); try { w.write(content); } finally { w.close(); } return null; } }); } /** * Computes the MD5 digest of the file in hex string. */ public String digest() throws IOException, InterruptedException { return act(new FileCallable<String>() { public String invoke(File f, VirtualChannel channel) throws IOException { return Util.getDigestOf(new FileInputStream(f)); } }); } /** * Rename this file/directory to the target filepath. This FilePath and the target must * be on the some host */ public void renameTo(final FilePath target) throws IOException, InterruptedException { if(this.channel != target.channel) { throw new IOException("renameTo target must be on the same host"); } act(new FileCallable<Void>() { public Void invoke(File f, VirtualChannel channel) throws IOException { f.renameTo(new File(target.remote)); return null; } }); } /** * Copies this file to the specified target. */ public void copyTo(FilePath target) throws IOException, InterruptedException { OutputStream out = target.write(); try { copyTo(out); } finally { out.close(); } } /** * Sends the contents of this file into the given {@link OutputStream}. */ public void copyTo(OutputStream os) throws IOException, InterruptedException { final OutputStream out = new RemoteOutputStream(os); act(new FileCallable<Void>() { public Void invoke(File f, VirtualChannel channel) throws IOException { FileInputStream fis = null; try { fis = new FileInputStream(f); Util.copyStream(fis,out); return null; } finally { IOUtils.closeQuietly(fis); IOUtils.closeQuietly(out); } } }); } /** * Remoting interface used for {@link FilePath#copyRecursiveTo(String, FilePath)}. * * TODO: this might not be the most efficient way to do the copy. */ interface RemoteCopier { /** * @param fileName * relative path name to the output file. Path separator must be '/'. */ void open(String fileName) throws IOException; void write(byte[] buf, int len) throws IOException; void close() throws IOException; } public int copyRecursiveTo(String fileMask, FilePath target) throws IOException, InterruptedException { return copyRecursiveTo(fileMask,null,target); } /** * Copies the files that match the given file mask to the specified target node. * * @param fileMask * Ant GLOB pattern. * String like "foo/bar/*.xml" Multiple patterns can be separated * by ',', and whitespace can surround ',' (so that you can write * "abc, def" and "abc,def" to mean the same thing. * @param excludes * Files to be excluded. Can be null. * @return * the number of files copied. */ public int copyRecursiveTo(final String fileMask, final String excludes, final FilePath target) throws IOException, InterruptedException { if(this.channel==target.channel) { // local to local copy. return act(new FileCallable<Integer>() { public Integer invoke(File base, VirtualChannel channel) throws IOException { if(!base.exists()) return 0; assert target.channel==null; try { class CopyImpl extends Copy { private int copySize; public CopyImpl() { setProject(new org.apache.tools.ant.Project()); } protected void doFileOperations() { copySize = super.fileCopyMap.size(); super.doFileOperations(); } public int getNumCopied() { return copySize; } } CopyImpl copyTask = new CopyImpl(); copyTask.setTodir(new File(target.remote)); copyTask.addFileset(Util.createFileSet(base,fileMask,excludes)); copyTask.setIncludeEmptyDirs(false); copyTask.execute(); return copyTask.getNumCopied(); } catch (BuildException e) { throw new IOException2("Failed to copy "+base+"/"+fileMask+" to "+target,e); } } }); } else if(this.channel==null) { // local -> remote copy final Pipe pipe = Pipe.createLocalToRemote(); Future<Void> future = target.actAsync(new FileCallable<Void>() { public Void invoke(File f, VirtualChannel channel) throws IOException { try { readFromTar(remote+'/'+fileMask, f,TarCompression.GZIP.extract(pipe.getIn())); return null; } finally { pipe.getIn().close(); } } }); int r = writeToTar(new File(remote),fileMask,excludes,new GZIPOutputStream(pipe.getOut())); try { future.get(); } catch (ExecutionException e) { throw new IOException2(e); } return r; } else { // remote -> local copy final Pipe pipe = Pipe.createRemoteToLocal(); Future<Integer> future = actAsync(new FileCallable<Integer>() { public Integer invoke(File f, VirtualChannel channel) throws IOException { try { return writeToTar(f,fileMask,excludes,new GZIPOutputStream(pipe.getOut())); } finally { pipe.getOut().close(); } } }); try { readFromTar(remote+'/'+fileMask,new File(target.remote),TarCompression.GZIP.extract(pipe.getIn())); } catch (IOException e) {// BuildException or IOException try { future.get(3,TimeUnit.SECONDS); throw e; // the remote side completed successfully, so the error must be local } catch (ExecutionException x) { // report both errors throw new IOException2(Functions.printThrowable(e),x); } catch (TimeoutException _) { // remote is hanging throw e; } } try { return future.get(); } catch (ExecutionException e) { throw new IOException2(e); } } } /** * Writes to a tar stream and stores obtained files to the base dir. * * @return * number of files/directories that are written. */ private Integer writeToTar(File baseDir, String fileMask, String excludes, OutputStream out) throws IOException { FileSet fs = Util.createFileSet(baseDir,fileMask,excludes); byte[] buf = new byte[8192]; TarOutputStream tar = new TarOutputStream(new BufferedOutputStream(out)); tar.setLongFileMode(TarOutputStream.LONGFILE_GNU); String[] files; if(baseDir.exists()) { DirectoryScanner ds = fs.getDirectoryScanner(new org.apache.tools.ant.Project()); files = ds.getIncludedFiles(); } else { files = new String[0]; } for( String f : files) { if(Functions.isWindows()) f = f.replace('\\','/'); File file = new File(baseDir, f); TarEntry te = new TarEntry(f); te.setModTime(file.lastModified()); if(!file.isDirectory()) te.setSize(file.length()); tar.putNextEntry(te); if (!file.isDirectory()) { FileInputStream in = new FileInputStream(file); int len; while((len=in.read(buf))>=0) tar.write(buf,0,len); in.close(); } tar.closeEntry(); } tar.close(); return files.length; } /** * Reads from a tar stream and stores obtained files to the base dir. */ private static void readFromTar(String name, File baseDir, InputStream in) throws IOException { TarInputStream t = new TarInputStream(in); try { TarEntry te; while ((te = t.getNextEntry()) != null) { File f = new File(baseDir,te.getName()); if(te.isDirectory()) { f.mkdirs(); } else { File parent = f.getParentFile(); if (parent != null) parent.mkdirs(); OutputStream fos = new FileOutputStream(f); try { IOUtils.copy(t,fos); } finally { fos.close(); } f.setLastModified(te.getModTime().getTime()); int mode = te.getMode()&0777; if(mode!=0 && !Hudson.isWindows()) // be defensive GNUCLibrary.LIBC.chmod(f.getPath(),mode); } } } catch(IOException e) { throw new IOException2("Failed to extract "+name,e); } finally { t.close(); } } /** * Creates a {@link Launcher} for starting processes on the node * that has this file. * @since 1.89 */ public Launcher createLauncher(TaskListener listener) throws IOException, InterruptedException { if(channel==null) return new LocalLauncher(listener); else return new RemoteLauncher(listener,channel,channel.call(new IsUnix())); } private static final class IsUnix implements Callable<Boolean,IOException> { public Boolean call() throws IOException { return File.pathSeparatorChar==':'; } private static final long serialVersionUID = 1L; } /** * Validates the ant file mask (like "foo/bar/*.txt, zot/*.jar") * against this directory, and try to point out the problem. * * <p> * This is useful in conjunction with {@link FormValidation}. * * @return * null if no error was found. Otherwise returns a human readable error message. * @since 1.90 * @see #validateFileMask(FilePath, String) */ public String validateAntFileMask(final String fileMasks) throws IOException, InterruptedException { return act(new FileCallable<String>() { public String invoke(File dir, VirtualChannel channel) throws IOException { if(fileMasks.startsWith("~")) return Messages.FilePath_TildaDoesntWork(); StringTokenizer tokens = new StringTokenizer(fileMasks,","); while(tokens.hasMoreTokens()) { final String fileMask = tokens.nextToken().trim(); if(hasMatch(dir,fileMask)) continue; // no error on this portion // in 1.172 we introduced an incompatible change to stop using ' ' as the separator // so see if we can match by using ' ' as the separator if(fileMask.contains(" ")) { boolean matched = true; for (String token : Util.tokenize(fileMask)) matched &= hasMatch(dir,token); if(matched) return Messages.FilePath_validateAntFileMask_whitespaceSeprator(); } // a common mistake is to assume the wrong base dir, and there are two variations // to this: (1) the user gave us aa/bb/cc/dd where cc/dd was correct // and (2) the user gave us cc/dd where aa/bb/cc/dd was correct. {// check the (1) above first String f=fileMask; while(true) { int idx = findSeparator(f); if(idx==-1) break; f=f.substring(idx+1); if(hasMatch(dir,f)) return Messages.FilePath_validateAntFileMask_doesntMatchAndSuggest(fileMask,f); } } {// check the (1) above next as this is more expensive. // Try prepending "**/" to see if that results in a match FileSet fs = Util.createFileSet(dir,"**/"+fileMask); DirectoryScanner ds = fs.getDirectoryScanner(new Project()); if(ds.getIncludedFilesCount()!=0) { // try shorter name first so that the suggestion results in least amount of changes String[] names = ds.getIncludedFiles(); Arrays.sort(names,SHORTER_STRING_FIRST); for( String f : names) { // now we want to decompose f to the leading portion that matched "**" // and the trailing portion that matched the file mask, so that // we can suggest the user error. // // this is not a very efficient/clever way to do it, but it's relatively simple String prefix=""; while(true) { int idx = findSeparator(f); if(idx==-1) break; prefix+=f.substring(0,idx)+'/'; f=f.substring(idx+1); if(hasMatch(dir,prefix+fileMask)) return Messages.FilePath_validateAntFileMask_doesntMatchAndSuggest(fileMask, prefix+fileMask); } } } } {// finally, see if we can identify any sub portion that's valid. Otherwise bail out String previous = null; String pattern = fileMask; while(true) { if(hasMatch(dir,pattern)) { // found a match if(previous==null) return String.format("'%s' doesn't match anything, although '%s' exists", fileMask, pattern ); else return String.format("'%s' doesn't match anything: '%s' exists but not '%s'", fileMask, pattern, previous ); } int idx = findSeparator(pattern); if(idx<0) {// no more path component left to go back if(pattern.equals(fileMask)) return String.format("'%s' doesn't match anything", fileMask ); else return String.format("'%s' doesn't match anything: even '%s' doesn't exist", fileMask, pattern ); } // cut off the trailing component and try again previous = pattern; pattern = pattern.substring(0,idx); } } } return null; // no error } private boolean hasMatch(File dir, String pattern) { FileSet fs = Util.createFileSet(dir,pattern); DirectoryScanner ds = fs.getDirectoryScanner(new Project()); return ds.getIncludedFilesCount()!=0 || ds.getIncludedDirsCount()!=0; } /** * Finds the position of the first path separator. */ private int findSeparator(String pattern) { int idx1 = pattern.indexOf('\\'); int idx2 = pattern.indexOf('/'); if(idx1==-1) return idx2; if(idx2==-1) return idx1; return Math.min(idx1,idx2); } }); } /** * Shortcut for {@link #validateFileMask(String)} in case the left-hand side can be null. */ public static FormValidation validateFileMask(FilePath pathOrNull, String value) throws IOException { if(pathOrNull==null) return FormValidation.ok(); return pathOrNull.validateFileMask(value); } /** * Short for {@code validateFileMask(value,true)} */ public FormValidation validateFileMask(String value) throws IOException { return validateFileMask(value,true); } /** * Checks the GLOB-style file mask. See {@link #validateAntFileMask(String)} * @since 1.294 */ public FormValidation validateFileMask(String value, boolean errorIfNotExist) throws IOException { value = fixEmpty(value); if(value==null) return FormValidation.ok(); try { if(!exists()) // no workspace. can't check return FormValidation.ok(); String msg = validateAntFileMask(value); if(errorIfNotExist) return FormValidation.error(msg); else return FormValidation.warning(msg); } catch (InterruptedException e) { return FormValidation.ok(); } } /** * Validates a relative file path from this {@link FilePath}. * * @param value * The relative path being validated. * @param errorIfNotExist * If true, report an error if the given relative path doesn't exist. Otherwise it's a warning. * @param expectingFile * If true, we expect the relative path to point to a file. * Otherwise, the relative path is expected to be pointing to a directory. */ public FormValidation validateRelativePath(String value, boolean errorIfNotExist, boolean expectingFile) throws IOException { AbstractProject subject = Stapler.getCurrentRequest().findAncestorObject(AbstractProject.class); subject.checkPermission(Item.CONFIGURE); value = fixEmpty(value); // none entered yet, or something is seriously wrong if(value==null || (AbstractProject<?,?>)subject ==null) return FormValidation.ok(); // a common mistake is to use wildcard if(value.contains("*")) return FormValidation.error("Wildcard is not allowed here"); try { if(!exists()) // no base directory. can't check return FormValidation.ok(); FilePath path = child(value); if(path.exists()) { if (expectingFile) { if(!path.isDirectory()) return FormValidation.ok(); else return FormValidation.error(value+" is not a file"); } else { if(path.isDirectory()) return FormValidation.ok(); else return FormValidation.error(value+" is not a directory"); } } String msg = "No such "+(expectingFile?"file":"directory")+": " + value; if(errorIfNotExist) return FormValidation.error(msg); else return FormValidation.warning(msg); } catch (InterruptedException e) { return FormValidation.ok(); } } /** * A convenience method over {@link #validateRelativePath(String, boolean, boolean)}. */ public FormValidation validateRelativeDirectory(String value, boolean errorIfNotExist) throws IOException { return validateRelativePath(value,errorIfNotExist,false); } public FormValidation validateRelativeDirectory(String value) throws IOException { return validateRelativeDirectory(value,true); } @Deprecated public String toString() { // to make writing JSPs easily, return local return remote; } public VirtualChannel getChannel() { if(channel!=null) return channel; else return Hudson.MasterComputer.localChannel; } /** * Returns true if this {@link FilePath} represents a remote file. */ public boolean isRemote() { return channel!=null; } private void writeObject(ObjectOutputStream oos) throws IOException { Channel target = Channel.current(); if(channel!=null && channel!=target) throw new IllegalStateException("Can't send a remote FilePath to a different remote channel"); oos.defaultWriteObject(); oos.writeBoolean(channel==null); } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { Channel channel = Channel.current(); assert channel!=null; ois.defaultReadObject(); if(ois.readBoolean()) { this.channel = channel; } else { this.channel = null; } } private static final long serialVersionUID = 1L; public static int SIDE_BUFFER_SIZE = 1024; /** * Adapts {@link FileCallable} to {@link Callable}. */ private class FileCallableWrapper<T> implements DelegatingCallable<T,IOException> { private final FileCallable<T> callable; public FileCallableWrapper(FileCallable<T> callable) { this.callable = callable; } public T call() throws IOException { return callable.invoke(new File(remote), Channel.current()); } public ClassLoader getClassLoader() { return callable.getClass().getClassLoader(); } private static final long serialVersionUID = 1L; } private static final Comparator<String> SHORTER_STRING_FIRST = new Comparator<String>() { public int compare(String o1, String o2) { return o1.length()-o2.length(); } }; }
[FIXED HUDSON-3254] Use a bigger buffer size to improve remote I/O performance. Will be in 1.302. git-svn-id: 28f34f9aa52bc55a5ddd5be9e183c5cccadc6ee4@17491 71c3de6d-444a-0410-be80-ed276b4c234a
core/src/main/java/hudson/FilePath.java
[FIXED HUDSON-3254] Use a bigger buffer size to improve remote I/O performance. Will be in 1.302.
<ide><path>ore/src/main/java/hudson/FilePath.java <ide> public InputStream extract(InputStream _in) throws IOException { <ide> HeadBufferingStream in = new HeadBufferingStream(_in,SIDE_BUFFER_SIZE); <ide> try { <del> return new GZIPInputStream(in); <add> return new GZIPInputStream(in,8192); <ide> } catch (IOException e) { <ide> // various people reported "java.io.IOException: Not in GZIP format" here, so diagnose this problem better <ide> in.fillSide(); <ide> } <ide> } <ide> public OutputStream compress(OutputStream out) throws IOException { <del> return new GZIPOutputStream(out); <add> return new GZIPOutputStream(new BufferedOutputStream(out)); <ide> } <ide> }; <ide> <ide> final InputStream in = new RemoteInputStream(_in); <ide> act(new FileCallable<Void>() { <ide> public Void invoke(File dir, VirtualChannel channel) throws IOException { <del> readFromTar("input stream",dir, compression.extract(new BufferedInputStream(in))); <add> readFromTar("input stream",dir, compression.extract(in)); <ide> return null; <ide> } <ide> private static final long serialVersionUID = 1L; <ide> } <ide> } <ide> }); <del> int r = writeToTar(new File(remote),fileMask,excludes,new GZIPOutputStream(pipe.getOut())); <add> int r = writeToTar(new File(remote),fileMask,excludes,TarCompression.GZIP.compress(pipe.getOut())); <ide> try { <ide> future.get(); <ide> } catch (ExecutionException e) { <ide> Future<Integer> future = actAsync(new FileCallable<Integer>() { <ide> public Integer invoke(File f, VirtualChannel channel) throws IOException { <ide> try { <del> return writeToTar(f,fileMask,excludes,new GZIPOutputStream(pipe.getOut())); <add> return writeToTar(f,fileMask,excludes,TarCompression.GZIP.compress(pipe.getOut())); <ide> } finally { <ide> pipe.getOut().close(); <ide> }
Java
apache-2.0
56302c19489391701f6c5d1ae30341d78207f5a1
0
vvv1559/intellij-community,allotria/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,da1z/intellij-community,da1z/intellij-community,FHannes/intellij-community,FHannes/intellij-community,asedunov/intellij-community,asedunov/intellij-community,FHannes/intellij-community,signed/intellij-community,ibinti/intellij-community,allotria/intellij-community,semonte/intellij-community,apixandru/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,apixandru/intellij-community,FHannes/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,signed/intellij-community,da1z/intellij-community,signed/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,FHannes/intellij-community,apixandru/intellij-community,ibinti/intellij-community,signed/intellij-community,allotria/intellij-community,da1z/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,asedunov/intellij-community,signed/intellij-community,semonte/intellij-community,signed/intellij-community,xfournet/intellij-community,da1z/intellij-community,apixandru/intellij-community,FHannes/intellij-community,xfournet/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,asedunov/intellij-community,da1z/intellij-community,ibinti/intellij-community,semonte/intellij-community,suncycheng/intellij-community,allotria/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,signed/intellij-community,semonte/intellij-community,ibinti/intellij-community,signed/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,semonte/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,signed/intellij-community,semonte/intellij-community,xfournet/intellij-community,asedunov/intellij-community,allotria/intellij-community,allotria/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,apixandru/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,semonte/intellij-community,signed/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,signed/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,xfournet/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,allotria/intellij-community,signed/intellij-community,da1z/intellij-community,asedunov/intellij-community,semonte/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,allotria/intellij-community,apixandru/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,allotria/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,xfournet/intellij-community,ibinti/intellij-community,FHannes/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,asedunov/intellij-community,semonte/intellij-community,suncycheng/intellij-community
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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.intellij.psi.impl.file; import com.intellij.ide.util.PsiNavigationSupport; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.navigation.ItemPresentation; import com.intellij.navigation.ItemPresentationProviders; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.progress.ProgressIndicatorProvider; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.ui.Queryable; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.*; import com.intellij.psi.*; import com.intellij.psi.impl.CheckUtil; import com.intellij.psi.impl.PsiElementBase; import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.impl.source.SourceTreeToPsiMap; import com.intellij.psi.impl.source.tree.ChangeUtil; import com.intellij.psi.impl.source.tree.TreeElement; import com.intellij.psi.search.PsiElementProcessor; import com.intellij.psi.search.PsiFileSystemItemProcessor; import com.intellij.psi.util.PsiUtilCore; import com.intellij.testFramework.LightVirtualFile; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.PlatformIcons; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.io.IOException; import java.util.ArrayList; import java.util.Map; public class PsiDirectoryImpl extends PsiElementBase implements PsiDirectory, Queryable { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.file.PsiDirectoryImpl"); private final PsiManagerImpl myManager; private final VirtualFile myFile; public PsiDirectoryImpl(PsiManagerImpl manager, @NotNull VirtualFile file) { myManager = manager; myFile = file; } @Override @NotNull public VirtualFile getVirtualFile() { return myFile; } @Override public boolean isDirectory() { return true; } @Override public boolean isValid() { return myFile.isValid() && !getProject().isDisposed(); } @Override @NotNull public Language getLanguage() { return Language.ANY; } @Override public PsiManager getManager() { return myManager; } @Override @NotNull public String getName() { return myFile.getName(); } @Override @NotNull public PsiElement setName(@NotNull String name) throws IncorrectOperationException { checkSetName(name); try { myFile.rename(myManager, name); } catch (IOException e) { throw new IncorrectOperationException(e.toString()); } return this; } @Override public void checkSetName(String name) throws IncorrectOperationException { CheckUtil.checkWritable(this); VirtualFile parentFile = myFile.getParent(); if (parentFile == null) { throw new IncorrectOperationException(VfsBundle.message("cannot.rename.root.directory", myFile.getPath())); } VirtualFile child = parentFile.findChild(name); if (child != null && !child.equals(myFile)) { throw new IncorrectOperationException(VfsBundle.message("file.already.exists.error", child.getPresentableUrl())); } } @Override public PsiDirectory getParentDirectory() { VirtualFile parentFile = myFile.getParent(); if (parentFile == null) return null; if (!parentFile.isValid()) { LOG.error("Invalid parent: " + parentFile + " of dir " + myFile + ", dir.valid=" + myFile.isValid()); return null; } return myManager.findDirectory(parentFile); } @Override @NotNull public PsiDirectory[] getSubdirectories() { VirtualFile[] files = myFile.getChildren(); ArrayList<PsiDirectory> dirs = new ArrayList<>(); for (VirtualFile file : files) { PsiDirectory dir = myManager.findDirectory(file); if (dir != null) { dirs.add(dir); } } return dirs.toArray(new PsiDirectory[dirs.size()]); } @Override @NotNull public PsiFile[] getFiles() { if (!myFile.isValid()) throw new InvalidVirtualFileAccessException(myFile); VirtualFile[] files = myFile.getChildren(); ArrayList<PsiFile> psiFiles = new ArrayList<>(); for (VirtualFile file : files) { PsiFile psiFile = myManager.findFile(file); if (psiFile != null) { psiFiles.add(psiFile); } } return PsiUtilCore.toPsiFileArray(psiFiles); } @Override public PsiDirectory findSubdirectory(@NotNull String name) { ProgressManager.checkCanceled(); VirtualFile childVFile = myFile.findChild(name); if (childVFile == null) return null; return myManager.findDirectory(childVFile); } @Override public PsiFile findFile(@NotNull String name) { ProgressManager.checkCanceled(); VirtualFile childVFile = myFile.findChild(name); if (childVFile == null) return null; if (!childVFile.isValid()) { LOG.error("Invalid file: " + childVFile + " in dir " + myFile + ", dir.valid=" + myFile.isValid()); return null; } return myManager.findFile(childVFile); } @Override public boolean processChildren(PsiElementProcessor<PsiFileSystemItem> processor) { checkValid(); ProgressIndicatorProvider.checkCanceled(); for (VirtualFile vFile : myFile.getChildren()) { boolean isDir = vFile.isDirectory(); if (processor instanceof PsiFileSystemItemProcessor && !((PsiFileSystemItemProcessor)processor).acceptItem(vFile.getName(), isDir)) { continue; } PsiFileSystemItem item = isDir ? myManager.findDirectory(vFile) : myManager.findFile(vFile); if (item != null && !processor.execute(item)) { return false; } } return true; } @Override @NotNull public PsiElement[] getChildren() { checkValid(); VirtualFile[] files = myFile.getChildren(); final ArrayList<PsiElement> children = new ArrayList<>(files.length); processChildren(new PsiElementProcessor<PsiFileSystemItem>() { @Override public boolean execute(@NotNull final PsiFileSystemItem element) { children.add(element); return true; } }); return PsiUtilCore.toPsiElementArray(children); } private void checkValid() { if (!isValid()) { throw new PsiInvalidElementAccessException(this); } } @Override public PsiDirectory getParent() { return getParentDirectory(); } @Override public PsiFile getContainingFile() { return null; } @Override public TextRange getTextRange() { return null; } @Override public int getStartOffsetInParent() { return -1; } @Override public int getTextLength() { return -1; } @Override public PsiElement findElementAt(int offset) { return null; } @Override public int getTextOffset() { return -1; } @Override public String getText() { return ""; } @Override @NotNull public char[] textToCharArray() { return ArrayUtil.EMPTY_CHAR_ARRAY; } @Override public boolean textMatches(@NotNull CharSequence text) { return false; } @Override public boolean textMatches(@NotNull PsiElement element) { return false; } @Override public final boolean isWritable() { return myFile.isWritable(); } @Override public boolean isPhysical() { return !(myFile.getFileSystem() instanceof NonPhysicalFileSystem) && !myFile.getFileSystem().getProtocol().equals("temp"); } @Override public PsiElement copy() { throw new IncorrectOperationException(); } @Override @NotNull public PsiDirectory createSubdirectory(@NotNull String name) throws IncorrectOperationException { checkCreateSubdirectory(name); try { VirtualFile file = getVirtualFile().createChildDirectory(myManager, name); PsiDirectory directory = myManager.findDirectory(file); if (directory == null) throw new IncorrectOperationException("Cannot find directory in '" + file.getPresentableUrl() + "'"); return directory; } catch (IOException e) { throw new IncorrectOperationException(e.toString()); } } @Override public void checkCreateSubdirectory(@NotNull String name) throws IncorrectOperationException { VirtualFile existingFile = getVirtualFile().findChild(name); if (existingFile != null) { throw new IncorrectOperationException(VfsBundle.message("file.already.exists.error", existingFile.getPresentableUrl())); } CheckUtil.checkWritable(this); } @Override @NotNull public PsiFile createFile(@NotNull String name) throws IncorrectOperationException { checkCreateFile(name); try { VirtualFile vFile = getVirtualFile().createChildData(myManager, name); PsiFile psiFile = myManager.findFile(vFile); assert psiFile != null : vFile.getPath(); return psiFile; } catch (IOException e) { throw new IncorrectOperationException(e.toString()); } } @Override @NotNull public PsiFile copyFileFrom(@NotNull String newName, @NotNull PsiFile originalFile) throws IncorrectOperationException { checkCreateFile(newName); final Document document = PsiDocumentManager.getInstance(getProject()).getDocument(originalFile); if (document != null) { FileDocumentManager.getInstance().saveDocument(document); } final VirtualFile parent = getVirtualFile(); try { final VirtualFile vFile = originalFile.getVirtualFile(); if (vFile == null) throw new IncorrectOperationException("Cannot copy non-physical file: " + originalFile); VirtualFile copyVFile; if (parent.getFileSystem() == vFile.getFileSystem()) { copyVFile = vFile.copy(this, parent, newName); } else if (vFile instanceof LightVirtualFile) { copyVFile = parent.createChildData(this, newName); copyVFile.setBinaryContent(originalFile.getText().getBytes(copyVFile.getCharset())); } else { copyVFile = VfsUtilCore.copyFile(this, vFile, parent, newName); } if (copyVFile == null) throw new IncorrectOperationException("File was not copied: " + vFile); DumbService.getInstance(getProject()).completeJustSubmittedTasks(); final PsiFile copyPsi = myManager.findFile(copyVFile); if (copyPsi == null) throw new IncorrectOperationException("Could not find file " + copyVFile + " after copying " + vFile); updateAddedFile(copyPsi); return copyPsi; } catch (IOException e) { throw new IncorrectOperationException(e); } } private static void updateAddedFile(@NotNull PsiFile copyPsi) throws IncorrectOperationException { final UpdateAddedFileProcessor processor = UpdateAddedFileProcessor.forElement(copyPsi); if (processor != null) { final TreeElement tree = (TreeElement)SourceTreeToPsiMap.psiElementToTree(copyPsi); if (tree != null) { ChangeUtil.encodeInformation(tree); } processor.update(copyPsi, null); if (tree != null) { ChangeUtil.decodeInformation(tree); } } } @Override public void checkCreateFile(@NotNull String name) throws IncorrectOperationException { VirtualFile existingFile = getVirtualFile().findChild(name); if (existingFile != null) { throw new IncorrectOperationException(VfsBundle.message("file.already.exists.error", existingFile.getPresentableUrl())); } CheckUtil.checkWritable(this); } @Override public PsiElement add(@NotNull PsiElement element) throws IncorrectOperationException { checkAdd(element); if (element instanceof PsiFile) { PsiFile originalFile = (PsiFile)element; try { VirtualFile newVFile; final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(myManager.getProject()); if (originalFile instanceof PsiFileImpl) { newVFile = myFile.createChildData(myManager, originalFile.getName()); String text = originalFile.getText(); final PsiFile psiFile = getManager().findFile(newVFile); final Document document = psiFile == null ? null : psiDocumentManager.getDocument(psiFile); final FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance(); if (document != null) { document.setText(text); fileDocumentManager.saveDocument(document); } else { String lineSeparator = fileDocumentManager.getLineSeparator(newVFile, getProject()); if (!lineSeparator.equals("\n")) { text = StringUtil.convertLineSeparators(text, lineSeparator); } LoadTextUtil.write(getProject(), newVFile, myManager, text, -1); } } else { byte[] storedContents = ((PsiBinaryFileImpl)originalFile).getStoredContents(); if (storedContents != null) { newVFile = myFile.createChildData(myManager, originalFile.getName()); newVFile.setBinaryContent(storedContents); } else { newVFile = VfsUtilCore.copyFile(null, originalFile.getVirtualFile(), myFile); } } psiDocumentManager.commitAllDocuments(); PsiFile newFile = myManager.findFile(newVFile); if (newFile == null) throw new IncorrectOperationException("Could not find file " + newVFile); updateAddedFile(newFile); return newFile; } catch (IOException e) { throw new IncorrectOperationException(e); } } throw new IncorrectOperationException(element + " (" + element.getClass() + ")"); } @Override public void checkAdd(@NotNull PsiElement element) throws IncorrectOperationException { CheckUtil.checkWritable(this); if (element instanceof PsiDirectory) { String name = ((PsiDirectory)element).getName(); checkName(name, getSubdirectories(), "dir.already.exists.error"); } else if (element instanceof PsiFile) { String name = ((PsiFile)element).getName(); checkName(name, getFiles(), "file.already.exists.error"); } else { throw new IncorrectOperationException(element.getClass().getName()); } } private void checkName(String name, PsiFileSystemItem[] items, String key) { boolean caseSensitive = getVirtualFile().getFileSystem().isCaseSensitive(); for (PsiFileSystemItem item : items) { if (Comparing.strEqual(item.getName(), name, caseSensitive)) { throw new IncorrectOperationException(VfsBundle.message(key, item.getVirtualFile().getPresentableUrl())); } } } @Override public PsiElement addBefore(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException { throw new IncorrectOperationException(); } @Override public PsiElement addAfter(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException { throw new IncorrectOperationException(); } @Override public void delete() throws IncorrectOperationException { checkDelete(); try { myFile.delete(myManager); } catch (IOException e) { throw new IncorrectOperationException(e); } } @Override public void checkDelete() throws IncorrectOperationException { CheckUtil.checkDelete(myFile); } @Override public PsiElement replace(@NotNull PsiElement newElement) throws IncorrectOperationException { throw new IncorrectOperationException(); } @Override public void accept(@NotNull PsiElementVisitor visitor) { visitor.visitDirectory(this); } public String toString() { return "PsiDirectory:" + myFile.getPresentableUrl(); } @Override public ASTNode getNode() { return null; } @Override public boolean canNavigateToSource() { return false; } @Override public ItemPresentation getPresentation() { return ItemPresentationProviders.getItemPresentation(this); } @Override public void navigate(boolean requestFocus) { PsiNavigationSupport.getInstance().navigateToDirectory(this, requestFocus); } @Override protected Icon getElementIcon(final int flags) { return PlatformIcons.DIRECTORY_CLOSED_ICON; } @Override public void putInfo(@NotNull Map<String, String> info) { info.put("fileName", getName()); } }
platform/core-impl/src/com/intellij/psi/impl/file/PsiDirectoryImpl.java
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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.intellij.psi.impl.file; import com.intellij.ide.util.PsiNavigationSupport; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.navigation.ItemPresentation; import com.intellij.navigation.ItemPresentationProviders; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.progress.ProgressIndicatorProvider; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.ui.Queryable; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.*; import com.intellij.psi.*; import com.intellij.psi.impl.CheckUtil; import com.intellij.psi.impl.PsiElementBase; import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.impl.source.SourceTreeToPsiMap; import com.intellij.psi.impl.source.tree.ChangeUtil; import com.intellij.psi.impl.source.tree.TreeElement; import com.intellij.psi.search.PsiElementProcessor; import com.intellij.psi.search.PsiFileSystemItemProcessor; import com.intellij.psi.util.PsiUtilCore; import com.intellij.testFramework.LightVirtualFile; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.PlatformIcons; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.io.IOException; import java.util.ArrayList; import java.util.Map; public class PsiDirectoryImpl extends PsiElementBase implements PsiDirectory, Queryable { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.file.PsiDirectoryImpl"); private final PsiManagerImpl myManager; private final VirtualFile myFile; public PsiDirectoryImpl(PsiManagerImpl manager, @NotNull VirtualFile file) { myManager = manager; myFile = file; } @Override @NotNull public VirtualFile getVirtualFile() { return myFile; } @Override public boolean isDirectory() { return true; } @Override public boolean isValid() { return myFile.isValid(); } @Override @NotNull public Language getLanguage() { return Language.ANY; } @Override public PsiManager getManager() { return myManager; } @Override @NotNull public String getName() { return myFile.getName(); } @Override @NotNull public PsiElement setName(@NotNull String name) throws IncorrectOperationException { checkSetName(name); try { myFile.rename(myManager, name); } catch (IOException e) { throw new IncorrectOperationException(e.toString()); } return this; } @Override public void checkSetName(String name) throws IncorrectOperationException { CheckUtil.checkWritable(this); VirtualFile parentFile = myFile.getParent(); if (parentFile == null) { throw new IncorrectOperationException(VfsBundle.message("cannot.rename.root.directory", myFile.getPath())); } VirtualFile child = parentFile.findChild(name); if (child != null && !child.equals(myFile)) { throw new IncorrectOperationException(VfsBundle.message("file.already.exists.error", child.getPresentableUrl())); } } @Override public PsiDirectory getParentDirectory() { VirtualFile parentFile = myFile.getParent(); if (parentFile == null) return null; if (!parentFile.isValid()) { LOG.error("Invalid parent: " + parentFile + " of dir " + myFile + ", dir.valid=" + myFile.isValid()); return null; } return myManager.findDirectory(parentFile); } @Override @NotNull public PsiDirectory[] getSubdirectories() { VirtualFile[] files = myFile.getChildren(); ArrayList<PsiDirectory> dirs = new ArrayList<>(); for (VirtualFile file : files) { PsiDirectory dir = myManager.findDirectory(file); if (dir != null) { dirs.add(dir); } } return dirs.toArray(new PsiDirectory[dirs.size()]); } @Override @NotNull public PsiFile[] getFiles() { if (!myFile.isValid()) throw new InvalidVirtualFileAccessException(myFile); VirtualFile[] files = myFile.getChildren(); ArrayList<PsiFile> psiFiles = new ArrayList<>(); for (VirtualFile file : files) { PsiFile psiFile = myManager.findFile(file); if (psiFile != null) { psiFiles.add(psiFile); } } return PsiUtilCore.toPsiFileArray(psiFiles); } @Override public PsiDirectory findSubdirectory(@NotNull String name) { ProgressManager.checkCanceled(); VirtualFile childVFile = myFile.findChild(name); if (childVFile == null) return null; return myManager.findDirectory(childVFile); } @Override public PsiFile findFile(@NotNull String name) { ProgressManager.checkCanceled(); VirtualFile childVFile = myFile.findChild(name); if (childVFile == null) return null; if (!childVFile.isValid()) { LOG.error("Invalid file: " + childVFile + " in dir " + myFile + ", dir.valid=" + myFile.isValid()); return null; } return myManager.findFile(childVFile); } @Override public boolean processChildren(PsiElementProcessor<PsiFileSystemItem> processor) { checkValid(); ProgressIndicatorProvider.checkCanceled(); for (VirtualFile vFile : myFile.getChildren()) { boolean isDir = vFile.isDirectory(); if (processor instanceof PsiFileSystemItemProcessor && !((PsiFileSystemItemProcessor)processor).acceptItem(vFile.getName(), isDir)) { continue; } PsiFileSystemItem item = isDir ? myManager.findDirectory(vFile) : myManager.findFile(vFile); if (item != null && !processor.execute(item)) { return false; } } return true; } @Override @NotNull public PsiElement[] getChildren() { checkValid(); VirtualFile[] files = myFile.getChildren(); final ArrayList<PsiElement> children = new ArrayList<>(files.length); processChildren(new PsiElementProcessor<PsiFileSystemItem>() { @Override public boolean execute(@NotNull final PsiFileSystemItem element) { children.add(element); return true; } }); return PsiUtilCore.toPsiElementArray(children); } private void checkValid() { if (!isValid()) { throw new PsiInvalidElementAccessException(this); } } @Override public PsiDirectory getParent() { return getParentDirectory(); } @Override public PsiFile getContainingFile() { return null; } @Override public TextRange getTextRange() { return null; } @Override public int getStartOffsetInParent() { return -1; } @Override public int getTextLength() { return -1; } @Override public PsiElement findElementAt(int offset) { return null; } @Override public int getTextOffset() { return -1; } @Override public String getText() { return ""; } @Override @NotNull public char[] textToCharArray() { return ArrayUtil.EMPTY_CHAR_ARRAY; } @Override public boolean textMatches(@NotNull CharSequence text) { return false; } @Override public boolean textMatches(@NotNull PsiElement element) { return false; } @Override public final boolean isWritable() { return myFile.isWritable(); } @Override public boolean isPhysical() { return !(myFile.getFileSystem() instanceof NonPhysicalFileSystem) && !myFile.getFileSystem().getProtocol().equals("temp"); } @Override public PsiElement copy() { throw new IncorrectOperationException(); } @Override @NotNull public PsiDirectory createSubdirectory(@NotNull String name) throws IncorrectOperationException { checkCreateSubdirectory(name); try { VirtualFile file = getVirtualFile().createChildDirectory(myManager, name); PsiDirectory directory = myManager.findDirectory(file); if (directory == null) throw new IncorrectOperationException("Cannot find directory in '" + file.getPresentableUrl() + "'"); return directory; } catch (IOException e) { throw new IncorrectOperationException(e.toString()); } } @Override public void checkCreateSubdirectory(@NotNull String name) throws IncorrectOperationException { VirtualFile existingFile = getVirtualFile().findChild(name); if (existingFile != null) { throw new IncorrectOperationException(VfsBundle.message("file.already.exists.error", existingFile.getPresentableUrl())); } CheckUtil.checkWritable(this); } @Override @NotNull public PsiFile createFile(@NotNull String name) throws IncorrectOperationException { checkCreateFile(name); try { VirtualFile vFile = getVirtualFile().createChildData(myManager, name); PsiFile psiFile = myManager.findFile(vFile); assert psiFile != null : vFile.getPath(); return psiFile; } catch (IOException e) { throw new IncorrectOperationException(e.toString()); } } @Override @NotNull public PsiFile copyFileFrom(@NotNull String newName, @NotNull PsiFile originalFile) throws IncorrectOperationException { checkCreateFile(newName); final Document document = PsiDocumentManager.getInstance(getProject()).getDocument(originalFile); if (document != null) { FileDocumentManager.getInstance().saveDocument(document); } final VirtualFile parent = getVirtualFile(); try { final VirtualFile vFile = originalFile.getVirtualFile(); if (vFile == null) throw new IncorrectOperationException("Cannot copy non-physical file: " + originalFile); VirtualFile copyVFile; if (parent.getFileSystem() == vFile.getFileSystem()) { copyVFile = vFile.copy(this, parent, newName); } else if (vFile instanceof LightVirtualFile) { copyVFile = parent.createChildData(this, newName); copyVFile.setBinaryContent(originalFile.getText().getBytes(copyVFile.getCharset())); } else { copyVFile = VfsUtilCore.copyFile(this, vFile, parent, newName); } if (copyVFile == null) throw new IncorrectOperationException("File was not copied: " + vFile); DumbService.getInstance(getProject()).completeJustSubmittedTasks(); final PsiFile copyPsi = myManager.findFile(copyVFile); if (copyPsi == null) throw new IncorrectOperationException("Could not find file " + copyVFile + " after copying " + vFile); updateAddedFile(copyPsi); return copyPsi; } catch (IOException e) { throw new IncorrectOperationException(e); } } private static void updateAddedFile(@NotNull PsiFile copyPsi) throws IncorrectOperationException { final UpdateAddedFileProcessor processor = UpdateAddedFileProcessor.forElement(copyPsi); if (processor != null) { final TreeElement tree = (TreeElement)SourceTreeToPsiMap.psiElementToTree(copyPsi); if (tree != null) { ChangeUtil.encodeInformation(tree); } processor.update(copyPsi, null); if (tree != null) { ChangeUtil.decodeInformation(tree); } } } @Override public void checkCreateFile(@NotNull String name) throws IncorrectOperationException { VirtualFile existingFile = getVirtualFile().findChild(name); if (existingFile != null) { throw new IncorrectOperationException(VfsBundle.message("file.already.exists.error", existingFile.getPresentableUrl())); } CheckUtil.checkWritable(this); } @Override public PsiElement add(@NotNull PsiElement element) throws IncorrectOperationException { checkAdd(element); if (element instanceof PsiFile) { PsiFile originalFile = (PsiFile)element; try { VirtualFile newVFile; final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(myManager.getProject()); if (originalFile instanceof PsiFileImpl) { newVFile = myFile.createChildData(myManager, originalFile.getName()); String text = originalFile.getText(); final PsiFile psiFile = getManager().findFile(newVFile); final Document document = psiFile == null ? null : psiDocumentManager.getDocument(psiFile); final FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance(); if (document != null) { document.setText(text); fileDocumentManager.saveDocument(document); } else { String lineSeparator = fileDocumentManager.getLineSeparator(newVFile, getProject()); if (!lineSeparator.equals("\n")) { text = StringUtil.convertLineSeparators(text, lineSeparator); } LoadTextUtil.write(getProject(), newVFile, myManager, text, -1); } } else { byte[] storedContents = ((PsiBinaryFileImpl)originalFile).getStoredContents(); if (storedContents != null) { newVFile = myFile.createChildData(myManager, originalFile.getName()); newVFile.setBinaryContent(storedContents); } else { newVFile = VfsUtilCore.copyFile(null, originalFile.getVirtualFile(), myFile); } } psiDocumentManager.commitAllDocuments(); PsiFile newFile = myManager.findFile(newVFile); if (newFile == null) throw new IncorrectOperationException("Could not find file " + newVFile); updateAddedFile(newFile); return newFile; } catch (IOException e) { throw new IncorrectOperationException(e); } } throw new IncorrectOperationException(element + " (" + element.getClass() + ")"); } @Override public void checkAdd(@NotNull PsiElement element) throws IncorrectOperationException { CheckUtil.checkWritable(this); if (element instanceof PsiDirectory) { String name = ((PsiDirectory)element).getName(); checkName(name, getSubdirectories(), "dir.already.exists.error"); } else if (element instanceof PsiFile) { String name = ((PsiFile)element).getName(); checkName(name, getFiles(), "file.already.exists.error"); } else { throw new IncorrectOperationException(element.getClass().getName()); } } private void checkName(String name, PsiFileSystemItem[] items, String key) { boolean caseSensitive = getVirtualFile().getFileSystem().isCaseSensitive(); for (PsiFileSystemItem item : items) { if (Comparing.strEqual(item.getName(), name, caseSensitive)) { throw new IncorrectOperationException(VfsBundle.message(key, item.getVirtualFile().getPresentableUrl())); } } } @Override public PsiElement addBefore(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException { throw new IncorrectOperationException(); } @Override public PsiElement addAfter(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException { throw new IncorrectOperationException(); } @Override public void delete() throws IncorrectOperationException { checkDelete(); try { myFile.delete(myManager); } catch (IOException e) { throw new IncorrectOperationException(e); } } @Override public void checkDelete() throws IncorrectOperationException { CheckUtil.checkDelete(myFile); } @Override public PsiElement replace(@NotNull PsiElement newElement) throws IncorrectOperationException { throw new IncorrectOperationException(); } @Override public void accept(@NotNull PsiElementVisitor visitor) { visitor.visitDirectory(this); } public String toString() { return "PsiDirectory:" + myFile.getPresentableUrl(); } @Override public ASTNode getNode() { return null; } @Override public boolean canNavigateToSource() { return false; } @Override public ItemPresentation getPresentation() { return ItemPresentationProviders.getItemPresentation(this); } @Override public void navigate(boolean requestFocus) { PsiNavigationSupport.getInstance().navigateToDirectory(this, requestFocus); } @Override protected Icon getElementIcon(final int flags) { return PlatformIcons.DIRECTORY_CLOSED_ICON; } @Override public void putInfo(@NotNull Map<String, String> info) { info.put("fileName", getName()); } }
PsiDirectory should be invalid when project is disposed
platform/core-impl/src/com/intellij/psi/impl/file/PsiDirectoryImpl.java
PsiDirectory should be invalid when project is disposed
<ide><path>latform/core-impl/src/com/intellij/psi/impl/file/PsiDirectoryImpl.java <ide> <ide> @Override <ide> public boolean isValid() { <del> return myFile.isValid(); <add> return myFile.isValid() && !getProject().isDisposed(); <ide> } <ide> <ide> @Override
Java
apache-2.0
228d06babcde91bf047a74b05ddffeeb88168720
0
Commonjava/indy,jdcasey/indy,ligangty/indy,ligangty/indy,ligangty/indy,yma88/indy,ruhan1/indy,jdcasey/indy,Commonjava/indy,Commonjava/indy,pkocandr/indy,pkocandr/indy,ruhan1/indy,ligangty/indy,Commonjava/indy,Commonjava/indy,ruhan1/indy,yma88/indy,pkocandr/indy,yma88/indy,ligangty/indy,jdcasey/indy,pkocandr/indy,yma88/indy,pkocandr/indy,jdcasey/indy,jdcasey/indy,yma88/indy,ruhan1/indy,ligangty/indy,yma88/indy,jdcasey/indy,ruhan1/indy,pkocandr/indy,ruhan1/indy,Commonjava/indy
/******************************************************************************* * Copyright (c) 2014 Red Hat, Inc.. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.commonjava.aprox.depgraph.jaxrs; import static org.commonjava.aprox.bind.jaxrs.util.ResponseUtils.formatOkResponseWithJsonEntity; import static org.commonjava.aprox.bind.jaxrs.util.ResponseUtils.formatResponse; import static org.commonjava.aprox.model.util.HttpUtils.parseQueryMap; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import org.apache.commons.lang.StringUtils; import org.commonjava.aprox.AproxWorkflowException; import org.commonjava.aprox.bind.jaxrs.AproxResources; import org.commonjava.aprox.depgraph.rest.GraphController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Path( "/api/depgraph/rel" ) @ApplicationScoped public class GraphResource implements AproxResources { private final Logger logger = LoggerFactory.getLogger( getClass() ); @Inject private GraphController controller; @Path( "/reindex{gav: (/[^/]+/[^/]+/[^/]+)?}" ) @GET public Response reindex( final @PathParam( "gav" ) String coord, @QueryParam( "wsid" ) final String wsid ) { Response response = null; try { controller.reindex( coordToGav( coord ), wsid ); response = Response.ok() .build(); } catch ( final AproxWorkflowException e ) { logger.error( e.getMessage(), e ); response = formatResponse( e, true ); } return response; } @Path( "/errors{gav: (/[^/]+/[^/]+/[^/]+)?}" ) @GET public Response errors( final @PathParam( "gav" ) String coord, @QueryParam( "wsid" ) final String wsid ) { Response response = null; try { final String json = controller.errors( coordToGav( coord ), wsid ); if ( json != null ) { response = formatOkResponseWithJsonEntity( json ); } else { response = Response.ok() .build(); } } catch ( final AproxWorkflowException e ) { logger.error( e.getMessage(), e ); response = formatResponse( e, true ); } return response; } @Path( "/incomplete{gav: (/[^/]+/[^/]+/[^/]+)?}" ) @GET public Response incomplete( final @PathParam( "gav" ) String coord, @QueryParam( "wsid" ) final String wsid, @Context final HttpServletRequest request ) { Response response = null; try { final String json = controller.incomplete( coordToGav( coord ), wsid, parseQueryMap( request.getQueryString() ) ); if ( json != null ) { response = formatOkResponseWithJsonEntity( json ); } else { response = Response.ok() .build(); } } catch ( final AproxWorkflowException e ) { logger.error( e.getMessage(), e ); response = formatResponse( e, true ); } return response; } @Path( "/variable{gav: (/[^/]+/[^/]+/[^/]+)?}" ) @GET public Response variable( final @PathParam( "gav" ) String coord, @QueryParam( "wsid" ) final String wsid, @Context final HttpServletRequest request ) { Response response = null; try { final String json = controller.variable( coordToGav( coord ), wsid, parseQueryMap( request.getQueryString() ) ); if ( json != null ) { response = formatOkResponseWithJsonEntity( json ); } else { response = Response.ok() .build(); } } catch ( final AproxWorkflowException e ) { logger.error( e.getMessage(), e ); response = formatResponse( e, true ); } return response; } /** * Converts the coordination info from URL path into GAV. The coord format is * &quot;/{groupId}/{artifactId}/{version}&quot;. The target format is * &quot;{groupId}:{artifactId}:{version}&quot;. * * @param coord the coordination info, can be {@code null} * @return {@code null} if the passed input is empty, otherwise input converted into GAV format */ private String coordToGav( final String coord ) { final String result; if ( StringUtils.isEmpty( coord ) ) { result = null; } else { String[] parts = coord.split( "/" ); if ( parts.length != 4 || parts[0].length() > 0 ) { throw new IllegalArgumentException( "Cannot parse the coordination info \"" + coord + "\". The expected format is \"/{groupId}/{artifactId}/{version}\"." ); } result = parts[1] + ':' + parts[2] + ':' + parts[3]; } return result; } @Path( "/ancestry/{groupId}/{artifactId}/{version}" ) @GET public Response ancestryOf( final @PathParam( "groupId" ) String gid, @PathParam( "artifactId" ) final String aid, @PathParam( "version" ) final String ver, @QueryParam( "wsid" ) final String wsid ) { Response response = null; try { final String json = controller.ancestryOf( gid, aid, ver, wsid ); if ( json != null ) { response = formatOkResponseWithJsonEntity( json ); } else { response = Response.ok() .build(); } } catch ( final AproxWorkflowException e ) { logger.error( e.getMessage(), e ); response = formatResponse( e, true ); } return response; } @Path( "/build-order/{groupId}/{artifactId}/{version}" ) @GET public Response buildOrder( @PathParam( "groupId" ) final String gid, @PathParam( "artifactId" ) final String aid, @PathParam( "version" ) final String ver, @QueryParam( "wsid" ) final String wsid, @Context final HttpServletRequest request ) { Response response = null; try { final String json = controller.buildOrder( gid, aid, ver, wsid, parseQueryMap( request.getQueryString() ) ); if ( json != null ) { response = formatOkResponseWithJsonEntity( json ); } else { response = Response.ok() .build(); } } catch ( final AproxWorkflowException e ) { logger.error( e.getMessage(), e ); response = formatResponse( e, true ); } return response; } @Path( "/project/{groupId}/{artifactId}/{version}" ) @GET public Response projectGraph( @PathParam( "groupId" ) final String gid, @PathParam( "artifactId" ) final String aid, @PathParam( "version" ) final String ver, @QueryParam( "wsid" ) final String wsid, @Context final HttpServletRequest request ) { Response response = null; try { final String json = controller.projectGraph( gid, aid, ver, wsid, parseQueryMap( request.getQueryString() ) ); if ( json != null ) { response = formatOkResponseWithJsonEntity( json ); } else { response = Response.ok() .build(); } } catch ( final AproxWorkflowException e ) { logger.error( e.getMessage(), e ); response = formatResponse( e, true ); } return response; } }
addons/depgraph/jaxrs/src/main/java/org/commonjava/aprox/depgraph/jaxrs/GraphResource.java
/******************************************************************************* * Copyright (c) 2014 Red Hat, Inc.. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.commonjava.aprox.depgraph.jaxrs; import static org.commonjava.aprox.bind.jaxrs.util.ResponseUtils.formatOkResponseWithJsonEntity; import static org.commonjava.aprox.bind.jaxrs.util.ResponseUtils.formatResponse; import static org.commonjava.aprox.model.util.HttpUtils.parseQueryMap; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import org.commonjava.aprox.AproxWorkflowException; import org.commonjava.aprox.bind.jaxrs.AproxResources; import org.commonjava.aprox.depgraph.rest.GraphController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Path( "/api/depgraph/rel" ) @ApplicationScoped public class GraphResource implements AproxResources { private final Logger logger = LoggerFactory.getLogger( getClass() ); @Inject private GraphController controller; @Path( "/reindex{gav: ([^/]+/[^/]+/[^/]+)?}" ) @GET public Response reindex( final @PathParam( "gav" ) String coord, @QueryParam( "wsid" ) final String wsid ) { Response response = null; try { controller.reindex( coord, wsid ); response = Response.ok() .build(); } catch ( final AproxWorkflowException e ) { logger.error( e.getMessage(), e ); response = formatResponse( e, true ); } return response; } @Path( "/errors{gav: ([^/]+/[^/]+/[^/]+)?}" ) @GET public Response errors( final @PathParam( "gav" ) String coord, @QueryParam( "wsid" ) final String wsid ) { Response response = null; try { final String json = controller.errors( coord, wsid ); if ( json != null ) { response = formatOkResponseWithJsonEntity( json ); } else { response = Response.ok() .build(); } } catch ( final AproxWorkflowException e ) { logger.error( e.getMessage(), e ); response = formatResponse( e, true ); } return response; } @Path( "/incomplete{gav: ([^/]+/[^/]+/[^/]+)?}" ) @GET public Response incomplete( final @PathParam( "gav" ) String coord, @QueryParam( "wsid" ) final String wsid, @Context final HttpServletRequest request ) { Response response = null; try { final String json = controller.incomplete( coord, wsid, parseQueryMap( request.getQueryString() ) ); if ( json != null ) { response = formatOkResponseWithJsonEntity( json ); } else { response = Response.ok() .build(); } } catch ( final AproxWorkflowException e ) { logger.error( e.getMessage(), e ); response = formatResponse( e, true ); } return response; } @Path( "/variable{gav: ([^/]+/[^/]+/[^/]+)?}" ) @GET public Response variable( final @PathParam( "gav" ) String coord, @QueryParam( "wsid" ) final String wsid, @Context final HttpServletRequest request ) { Response response = null; try { final String json = controller.variable( coord, wsid, parseQueryMap( request.getQueryString() ) ); if ( json != null ) { response = formatOkResponseWithJsonEntity( json ); } else { response = Response.ok() .build(); } } catch ( final AproxWorkflowException e ) { logger.error( e.getMessage(), e ); response = formatResponse( e, true ); } return response; } @Path( "/ancestry/{groupId}/{artifactId}/{version}" ) @GET public Response ancestryOf( final @PathParam( "groupId" ) String gid, @PathParam( "artifactId" ) final String aid, @PathParam( "version" ) final String ver, @QueryParam( "wsid" ) final String wsid ) { Response response = null; try { final String json = controller.ancestryOf( gid, aid, ver, wsid ); if ( json != null ) { response = formatOkResponseWithJsonEntity( json ); } else { response = Response.ok() .build(); } } catch ( final AproxWorkflowException e ) { logger.error( e.getMessage(), e ); response = formatResponse( e, true ); } return response; } @Path( "/build-order/{groupId}/{artifactId}/{version}" ) @GET public Response buildOrder( @PathParam( "groupId" ) final String gid, @PathParam( "artifactId" ) final String aid, @PathParam( "version" ) final String ver, @QueryParam( "wsid" ) final String wsid, @Context final HttpServletRequest request ) { Response response = null; try { final String json = controller.buildOrder( gid, aid, ver, wsid, parseQueryMap( request.getQueryString() ) ); if ( json != null ) { response = formatOkResponseWithJsonEntity( json ); } else { response = Response.ok() .build(); } } catch ( final AproxWorkflowException e ) { logger.error( e.getMessage(), e ); response = formatResponse( e, true ); } return response; } @Path( "/project/{groupId}/{artifactId}/{version}" ) @GET public Response projectGraph( @PathParam( "groupId" ) final String gid, @PathParam( "artifactId" ) final String aid, @PathParam( "version" ) final String ver, @QueryParam( "wsid" ) final String wsid, @Context final HttpServletRequest request ) { Response response = null; try { final String json = controller.projectGraph( gid, aid, ver, wsid, parseQueryMap( request.getQueryString() ) ); if ( json != null ) { response = formatOkResponseWithJsonEntity( json ); } else { response = Response.ok() .build(); } } catch ( final AproxWorkflowException e ) { logger.error( e.getMessage(), e ); response = formatResponse( e, true ); } return response; } }
Fix reading of GAVs from URLs in GraphResource methods The affected methods were reindex, errors, incomplete and variable. They were all suffering from the same problems * there was no slash expected/allowed after the method name, so one had to use for example /errorscommons-lang/commons-lang/2.6 * the value used / as separator between groupId, artifactId and version, but the called methods expected standard GAV with colons * when no value passed the parameter was an empty string, but the called methods expected null
addons/depgraph/jaxrs/src/main/java/org/commonjava/aprox/depgraph/jaxrs/GraphResource.java
Fix reading of GAVs from URLs in GraphResource methods The affected methods were reindex, errors, incomplete and variable.
<ide><path>ddons/depgraph/jaxrs/src/main/java/org/commonjava/aprox/depgraph/jaxrs/GraphResource.java <ide> import javax.ws.rs.core.Context; <ide> import javax.ws.rs.core.Response; <ide> <add>import org.apache.commons.lang.StringUtils; <ide> import org.commonjava.aprox.AproxWorkflowException; <ide> import org.commonjava.aprox.bind.jaxrs.AproxResources; <ide> import org.commonjava.aprox.depgraph.rest.GraphController; <ide> @Inject <ide> private GraphController controller; <ide> <del> @Path( "/reindex{gav: ([^/]+/[^/]+/[^/]+)?}" ) <add> @Path( "/reindex{gav: (/[^/]+/[^/]+/[^/]+)?}" ) <ide> @GET <ide> public Response reindex( final @PathParam( "gav" ) String coord, @QueryParam( "wsid" ) final String wsid ) <ide> { <ide> Response response = null; <ide> try <ide> { <del> controller.reindex( coord, wsid ); <add> controller.reindex( coordToGav( coord ), wsid ); <ide> response = Response.ok() <ide> .build(); <ide> } <ide> return response; <ide> } <ide> <del> @Path( "/errors{gav: ([^/]+/[^/]+/[^/]+)?}" ) <add> @Path( "/errors{gav: (/[^/]+/[^/]+/[^/]+)?}" ) <ide> @GET <ide> public Response errors( final @PathParam( "gav" ) String coord, @QueryParam( "wsid" ) final String wsid ) <ide> { <ide> Response response = null; <ide> try <ide> { <del> final String json = controller.errors( coord, wsid ); <del> if ( json != null ) <del> { <del> response = formatOkResponseWithJsonEntity( json ); <del> } <del> else <del> { <del> response = Response.ok() <del> .build(); <del> } <del> } <del> catch ( final AproxWorkflowException e ) <del> { <del> logger.error( e.getMessage(), e ); <del> response = formatResponse( e, true ); <del> } <del> return response; <del> } <del> <del> @Path( "/incomplete{gav: ([^/]+/[^/]+/[^/]+)?}" ) <add> final String json = controller.errors( coordToGav( coord ), wsid ); <add> if ( json != null ) <add> { <add> response = formatOkResponseWithJsonEntity( json ); <add> } <add> else <add> { <add> response = Response.ok() <add> .build(); <add> } <add> } <add> catch ( final AproxWorkflowException e ) <add> { <add> logger.error( e.getMessage(), e ); <add> response = formatResponse( e, true ); <add> } <add> return response; <add> } <add> <add> @Path( "/incomplete{gav: (/[^/]+/[^/]+/[^/]+)?}" ) <ide> @GET <ide> public Response incomplete( final @PathParam( "gav" ) String coord, @QueryParam( "wsid" ) final String wsid, <ide> @Context final HttpServletRequest request ) <ide> Response response = null; <ide> try <ide> { <del> final String json = controller.incomplete( coord, wsid, parseQueryMap( request.getQueryString() ) ); <del> <del> if ( json != null ) <del> { <del> response = formatOkResponseWithJsonEntity( json ); <del> } <del> else <del> { <del> response = Response.ok() <del> .build(); <del> } <del> } <del> catch ( final AproxWorkflowException e ) <del> { <del> logger.error( e.getMessage(), e ); <del> response = formatResponse( e, true ); <del> } <del> return response; <del> } <del> <del> @Path( "/variable{gav: ([^/]+/[^/]+/[^/]+)?}" ) <add> final String json = controller.incomplete( coordToGav( coord ), wsid, parseQueryMap( request.getQueryString() ) ); <add> <add> if ( json != null ) <add> { <add> response = formatOkResponseWithJsonEntity( json ); <add> } <add> else <add> { <add> response = Response.ok() <add> .build(); <add> } <add> } <add> catch ( final AproxWorkflowException e ) <add> { <add> logger.error( e.getMessage(), e ); <add> response = formatResponse( e, true ); <add> } <add> return response; <add> } <add> <add> @Path( "/variable{gav: (/[^/]+/[^/]+/[^/]+)?}" ) <ide> @GET <ide> public Response variable( final @PathParam( "gav" ) String coord, @QueryParam( "wsid" ) final String wsid, <ide> @Context final HttpServletRequest request ) <ide> Response response = null; <ide> try <ide> { <del> final String json = controller.variable( coord, wsid, parseQueryMap( request.getQueryString() ) ); <del> <del> if ( json != null ) <del> { <del> response = formatOkResponseWithJsonEntity( json ); <del> } <del> else <del> { <del> response = Response.ok() <del> .build(); <del> } <del> } <del> catch ( final AproxWorkflowException e ) <del> { <del> logger.error( e.getMessage(), e ); <del> response = formatResponse( e, true ); <del> } <del> return response; <add> final String json = controller.variable( coordToGav( coord ), wsid, parseQueryMap( request.getQueryString() ) ); <add> <add> if ( json != null ) <add> { <add> response = formatOkResponseWithJsonEntity( json ); <add> } <add> else <add> { <add> response = Response.ok() <add> .build(); <add> } <add> } <add> catch ( final AproxWorkflowException e ) <add> { <add> logger.error( e.getMessage(), e ); <add> response = formatResponse( e, true ); <add> } <add> return response; <add> } <add> <add> /** <add> * Converts the coordination info from URL path into GAV. The coord format is <add> * &quot;/{groupId}/{artifactId}/{version}&quot;. The target format is <add> * &quot;{groupId}:{artifactId}:{version}&quot;. <add> * <add> * @param coord the coordination info, can be {@code null} <add> * @return {@code null} if the passed input is empty, otherwise input converted into GAV format <add> */ <add> private String coordToGav( final String coord ) <add> { <add> final String result; <add> if ( StringUtils.isEmpty( coord ) ) <add> { <add> result = null; <add> } <add> else <add> { <add> String[] parts = coord.split( "/" ); <add> if ( parts.length != 4 || parts[0].length() > 0 ) <add> { <add> throw new IllegalArgumentException( "Cannot parse the coordination info \"" + coord <add> + "\". The expected format is \"/{groupId}/{artifactId}/{version}\"." ); <add> } <add> result = parts[1] + ':' + parts[2] + ':' + parts[3]; <add> } <add> return result; <ide> } <ide> <ide> @Path( "/ancestry/{groupId}/{artifactId}/{version}" )
Java
bsd-3-clause
20c6dcbfc9b718905cdb003b5ce25cb3490fcf3c
0
dbgroup-at-ucsc/dbtune,dbgroup-at-ucsc/dbtune
package edu.ucsc.dbtune.inum; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import edu.ucsc.dbtune.core.DBIndex; import edu.ucsc.dbtune.core.DatabaseConnection; import edu.ucsc.dbtune.spi.core.Console; import edu.ucsc.dbtune.util.StopWatch; import java.io.IOException; import java.sql.SQLException; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; /** * It serves as the entry point to the INUM functionality. It will * orchestrate the execution of INUM. * * @author [email protected] (Huascar A. Sanchez) */ public class Inum { private final DatabaseConnection connection; private final Precomputation precomputation; private final MatchingStrategy matchingLogic; private final AtomicBoolean isStarted; private static final Set<String> WORKLOADS; static { final SetupWorkloadVisitor loader = new SetupWorkloadVisitor(); final WorkloadDirectoryNode workloadDirectory = new WorkloadDirectoryNode(); WORKLOADS = ImmutableSet.copyOf(workloadDirectory.accept(loader)); } private Inum(DatabaseConnection connection, Precomputation precomputation, MatchingStrategy matchingLogic){ this.connection = connection; this.precomputation = precomputation; this.matchingLogic = matchingLogic; this.isStarted = new AtomicBoolean(false); } public static Inum newInumInstance(DatabaseConnection connection, Precomputation precomputation, MatchingStrategy matchingLogic){ final DatabaseConnection nonNullConnection = Preconditions.checkNotNull(connection); final Precomputation nonNullPrecomputation = Preconditions.checkNotNull(precomputation); final MatchingStrategy nonNullMatchingLogic = Preconditions.checkNotNull(matchingLogic); return new Inum(nonNullConnection, nonNullPrecomputation, nonNullMatchingLogic); } public static Inum newInumInstance(DatabaseConnection connection){ final DatabaseConnection nonNullConnection = Preconditions.checkNotNull(connection); return newInumInstance( nonNullConnection, new InumPrecomputation(nonNullConnection), new InumMatchingStrategy() ); } public InumSpace getInumSpace(){ return precomputation.getInumSpace(); } /** * INUM setup will load any representative workload found in the inum workload * directory. */ public void start(){ try { start(WORKLOADS); } catch (IOException e) { Console.streaming().error("unable to load workload", e); } } /** * INUM will get prepopulated first with representative workloads and configurations. * @param input * a list of representative workloads. * @throws IOException * if unable to parse the input. */ public void start(Set<String> input) throws IOException { isStarted.set(true); final StopWatch timing = new StopWatch(); for(String eachQuery : input){ // todo(Huascar) question to Team: should we parse the interesting orders or rely on // the recommended indexes by the extractor? For sake of speed, I am // using the recommended indexes. For parsing the interesting orders, we // need to use Zql parser (included in Dash's code). final Iterable<DBIndex> ios = recommendPromissingIndexes(eachQuery, connection); precomputation.setup(eachQuery, ios); } timing.resetAndLog("precomputation took "); } private static Iterable<DBIndex> recommendPromissingIndexes(String query, DatabaseConnection connection){ try { return connection.getIndexExtractor().recommendIndexes(query); } catch (SQLException e) { Console.streaming().error("unable to get indexes. an empty set is returned.", e); return ImmutableSet.of(); } } public double calculateQueryCost(String workload, Iterable<DBIndex> inputConfiguration){ if(!isStarted.get()) throw new InumExecutionException("INUM has not been started yet. Please call start(..) method."); if(!precomputation.skip(workload)) { precomputation.setup(workload, inputConfiguration); } final InumSpace cachedPlans = precomputation.getInumSpace(); final OptimalPlan singleOptimalPlan = matchingLogic.matches( cachedPlans.getAllSavedOptimalPlans(), inputConfiguration ); return matchingLogic.derivesCost(singleOptimalPlan, inputConfiguration); } public void end() { isStarted.set(false); precomputation.getInumSpace().clear(); } }
extensions/inum/src/edu/ucsc/dbtune/inum/Inum.java
package edu.ucsc.dbtune.inum; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import edu.ucsc.dbtune.core.DBIndex; import edu.ucsc.dbtune.core.DatabaseConnection; import edu.ucsc.dbtune.spi.core.Console; import edu.ucsc.dbtune.util.StopWatch; import java.io.IOException; import java.sql.SQLException; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; /** * It serves as the entry point to the INUM functionality. It will * orchestrate the execution of INUM. * * @author [email protected] (Huascar A. Sanchez) */ public class Inum { private final DatabaseConnection connection; private final Precomputation precomputation; private final MatchingStrategy matchingLogic; private final AtomicBoolean isStarted; private static final Set<String> WORKLOADS; static { final SetupWorkloadVisitor loader = new SetupWorkloadVisitor(); final WorkloadDirectoryNode workloadDirectory = new WorkloadDirectoryNode(); WORKLOADS = ImmutableSet.copyOf(workloadDirectory.accept(loader)); } private Inum(DatabaseConnection connection, Precomputation precomputation, MatchingStrategy matchingLogic){ this.connection = connection; this.precomputation = precomputation; this.matchingLogic = matchingLogic; this.isStarted = new AtomicBoolean(false); } public static Inum newInumInstance(DatabaseConnection connection, Precomputation precomputation, MatchingStrategy matchingLogic){ final DatabaseConnection nonNullConnection = Preconditions.checkNotNull(connection); final Precomputation nonNullPrecomputation = Preconditions.checkNotNull(precomputation); final MatchingStrategy nonNullMatchingLogic = Preconditions.checkNotNull(matchingLogic); return new Inum(nonNullConnection, nonNullPrecomputation, nonNullMatchingLogic); } public static Inum newInumInstance(DatabaseConnection connection){ final DatabaseConnection nonNullConnection = Preconditions.checkNotNull(connection); return newInumInstance( nonNullConnection, new InumPrecomputation(nonNullConnection), new InumMatchingStrategy() ); } public InumSpace getInumSpace(){ return precomputation.getInumSpace(); } /** * INUM setup will load any representative workload found in the inum workload * directory. */ public void start(){ try { start(WORKLOADS); } catch (IOException e) { Console.streaming().error("unable to load workload", e); } } /** * INUM will get prepopulated first with representative workloads and configurations. * @param input * a list of representative workloads. * @throws IOException * if unable to parse the input. */ public void start(Set<String> input) throws IOException { isStarted.set(true); final StopWatch timing = new StopWatch(); for(String eachQuery : input){ // todo(Huascar) question to Team: should we parse the interesting orders or rely on // the recommended indexes by the extractor? For sake of speed, I am // using the recommended indexes. For parsing the interesting orders, we // need using Zql parser (include in Dash's code. final Iterable<DBIndex> ios = recommendPromissingIndexes(eachQuery, connection); precomputation.setup(eachQuery, ios); } timing.resetAndLog("precomputation took "); } private static Iterable<DBIndex> recommendPromissingIndexes(String query, DatabaseConnection connection){ try { return connection.getIndexExtractor().recommendIndexes(query); } catch (SQLException e) { Console.streaming().error("unable to get indexes. an empty set is returned.", e); return ImmutableSet.of(); } } public double calculateQueryCost(String workload, Iterable<DBIndex> inputConfiguration){ if(!isStarted.get()) throw new InumExecutionException("INUM has not been started yet. Please call start(..) method."); if(!precomputation.skip(workload)) { precomputation.setup(workload, inputConfiguration); } final InumSpace cachedPlans = precomputation.getInumSpace(); final OptimalPlan singleOptimalPlan = matchingLogic.matches( cachedPlans.getAllSavedOptimalPlans(), inputConfiguration ); return matchingLogic.derivesCost(singleOptimalPlan, inputConfiguration); } public void end() { isStarted.set(false); precomputation.getInumSpace().clear(); } }
Fixed JavaDoc error on Inum class
extensions/inum/src/edu/ucsc/dbtune/inum/Inum.java
Fixed JavaDoc error on Inum class
<ide><path>xtensions/inum/src/edu/ucsc/dbtune/inum/Inum.java <ide> // todo(Huascar) question to Team: should we parse the interesting orders or rely on <ide> // the recommended indexes by the extractor? For sake of speed, I am <ide> // using the recommended indexes. For parsing the interesting orders, we <del> // need using Zql parser (include in Dash's code. <add> // need to use Zql parser (included in Dash's code). <ide> final Iterable<DBIndex> ios = recommendPromissingIndexes(eachQuery, connection); <ide> precomputation.setup(eachQuery, ios); <ide> }
Java
apache-2.0
f7be437825b9e4350aee89896cf8cb88919d4cc1
0
rmaz/buck,SeleniumHQ/buck,SeleniumHQ/buck,brettwooldridge/buck,facebook/buck,kageiit/buck,romanoid/buck,brettwooldridge/buck,kageiit/buck,nguyentruongtho/buck,romanoid/buck,shs96c/buck,brettwooldridge/buck,rmaz/buck,zpao/buck,nguyentruongtho/buck,JoelMarcey/buck,shs96c/buck,JoelMarcey/buck,kageiit/buck,rmaz/buck,rmaz/buck,facebook/buck,romanoid/buck,shs96c/buck,romanoid/buck,JoelMarcey/buck,SeleniumHQ/buck,SeleniumHQ/buck,zpao/buck,SeleniumHQ/buck,brettwooldridge/buck,romanoid/buck,zpao/buck,Addepar/buck,nguyentruongtho/buck,SeleniumHQ/buck,shs96c/buck,JoelMarcey/buck,rmaz/buck,kageiit/buck,facebook/buck,kageiit/buck,JoelMarcey/buck,brettwooldridge/buck,Addepar/buck,nguyentruongtho/buck,JoelMarcey/buck,rmaz/buck,Addepar/buck,Addepar/buck,romanoid/buck,nguyentruongtho/buck,kageiit/buck,JoelMarcey/buck,JoelMarcey/buck,nguyentruongtho/buck,shs96c/buck,romanoid/buck,zpao/buck,JoelMarcey/buck,Addepar/buck,SeleniumHQ/buck,brettwooldridge/buck,Addepar/buck,rmaz/buck,SeleniumHQ/buck,zpao/buck,brettwooldridge/buck,shs96c/buck,shs96c/buck,brettwooldridge/buck,facebook/buck,Addepar/buck,brettwooldridge/buck,romanoid/buck,brettwooldridge/buck,romanoid/buck,JoelMarcey/buck,shs96c/buck,zpao/buck,romanoid/buck,shs96c/buck,kageiit/buck,brettwooldridge/buck,rmaz/buck,Addepar/buck,facebook/buck,shs96c/buck,facebook/buck,SeleniumHQ/buck,SeleniumHQ/buck,shs96c/buck,brettwooldridge/buck,JoelMarcey/buck,brettwooldridge/buck,romanoid/buck,shs96c/buck,shs96c/buck,rmaz/buck,rmaz/buck,rmaz/buck,JoelMarcey/buck,romanoid/buck,nguyentruongtho/buck,rmaz/buck,rmaz/buck,zpao/buck,JoelMarcey/buck,Addepar/buck,Addepar/buck,SeleniumHQ/buck,facebook/buck,Addepar/buck,Addepar/buck,SeleniumHQ/buck,romanoid/buck,SeleniumHQ/buck,Addepar/buck
/* * Copyright 2015-present Facebook, 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 com.facebook.buck.crosscell; import static com.facebook.buck.android.toolchain.ndk.impl.AndroidNdkHelper.SymbolGetter; import static com.facebook.buck.android.toolchain.ndk.impl.AndroidNdkHelper.SymbolsAndDtNeeded; import static com.facebook.buck.util.environment.Platform.WINDOWS; import static java.nio.charset.StandardCharsets.UTF_8; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeThat; import com.facebook.buck.android.AssumeAndroidPlatform; import com.facebook.buck.android.toolchain.ndk.NdkCxxPlatform; import com.facebook.buck.android.toolchain.ndk.impl.AndroidNdkHelper; import com.facebook.buck.core.cell.Cell; import com.facebook.buck.core.exceptions.HumanReadableException; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.model.BuildTargetFactory; import com.facebook.buck.core.rules.SourcePathRuleFinder; import com.facebook.buck.core.rules.config.KnownConfigurationRuleTypes; import com.facebook.buck.core.rules.config.impl.PluginBasedKnownConfigurationRuleTypesFactory; import com.facebook.buck.core.rules.knowntypes.DefaultKnownBuildRuleTypesFactory; import com.facebook.buck.core.rules.knowntypes.KnownBuildRuleTypesProvider; import com.facebook.buck.core.rules.resolver.impl.TestActionGraphBuilder; import com.facebook.buck.core.sourcepath.resolver.SourcePathResolver; import com.facebook.buck.core.sourcepath.resolver.impl.DefaultSourcePathResolver; import com.facebook.buck.event.BuckEventBus; import com.facebook.buck.event.BuckEventBusForTests; import com.facebook.buck.io.ExecutableFinder; import com.facebook.buck.io.file.MorePaths; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.io.filesystem.TestProjectFilesystems; import com.facebook.buck.parser.DefaultParser; import com.facebook.buck.parser.Parser; import com.facebook.buck.parser.ParserConfig; import com.facebook.buck.parser.ParserPythonInterpreterProvider; import com.facebook.buck.parser.PerBuildStateFactory; import com.facebook.buck.parser.TargetSpecResolver; import com.facebook.buck.parser.exceptions.BuildFileParseException; import com.facebook.buck.plugin.impl.BuckPluginManagerFactory; import com.facebook.buck.rules.coercer.ConstructorArgMarshaller; import com.facebook.buck.rules.coercer.DefaultTypeCoercerFactory; import com.facebook.buck.rules.coercer.TypeCoercerFactory; import com.facebook.buck.sandbox.TestSandboxExecutionStrategyFactory; import com.facebook.buck.testutil.ProcessResult; import com.facebook.buck.testutil.TemporaryPaths; import com.facebook.buck.testutil.TestConsole; import com.facebook.buck.testutil.integration.ProjectWorkspace; import com.facebook.buck.testutil.integration.TestDataHelper; import com.facebook.buck.testutil.integration.ZipInspector; import com.facebook.buck.util.DefaultProcessExecutor; import com.facebook.buck.util.ProcessExecutor; import com.facebook.buck.util.RichStream; import com.facebook.buck.util.environment.Platform; import com.facebook.buck.util.types.Pair; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.hash.HashCode; import com.google.common.hash.Hashing; import com.google.common.util.concurrent.MoreExecutors; import java.io.File; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.List; import java.util.Optional; import java.util.concurrent.Executors; import java.util.stream.Collectors; import org.hamcrest.Matchers; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.pf4j.PluginManager; /** Cross-cell related integration tests that don't fit anywhere else. */ public class InterCellIntegrationTest { @Rule public TemporaryPaths tmp = new TemporaryPaths(); @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void ensureThatNormalBuildsWorkAsExpected() throws IOException { ProjectWorkspace secondary = TestDataHelper.createProjectWorkspaceForScenario( this, "inter-cell/export-file/secondary", tmp); secondary.setUp(); ProcessResult result = secondary.runBuckBuild("//:hello"); result.assertSuccess(); } @Test public void shouldBeAbleToUseAnExportFileXRepoTarget() throws IOException { Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); String expected = secondary.getFileContents("hello.txt"); Path path = primary.buildAndReturnOutput("//:exported-file"); String actual = new String(Files.readAllBytes(path), UTF_8); assertEquals(expected, actual); Path secondaryPath = primary.buildAndReturnRelativeOutput("secondary//:hello"); actual = new String(Files.readAllBytes(secondary.resolve(secondaryPath)), UTF_8); assertEquals(expected, actual); } @Test public void shouldBeAbleToUseTargetsCommandXCell() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); ProjectWorkspace primary = cells.getFirst(); ProcessResult result = primary.runBuckCommand("targets", "--show-target-hash", "//:cxxbinary"); result.assertSuccess(); ProcessResult result2 = primary.runBuckCommand("targets", "secondary//:cxxlib"); result2.assertSuccess(); } @Test public void shouldBeAbleToUseQueryCommandXCell() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); ProjectWorkspace primary = createWorkspace("inter-cell/multi-cell/primary"); ProjectWorkspace secondary = createWorkspace("inter-cell/multi-cell/secondary"); ProjectWorkspace ternary = createWorkspace("inter-cell/multi-cell/ternary"); registerCell(secondary, "ternary", ternary); registerCell(primary, "secondary", secondary); registerCell(primary, "ternary", ternary); primary.runBuckCommand("targets", "--show-target-hash", "//:cxxbinary"); secondary.runBuckCommand("targets", "--show-target-hash", "//:cxxlib"); ternary.runBuckCommand("targets", "--show-target-hash", "//:cxxlib2"); ProcessResult result = primary.runBuckCommand("query", "deps(%s)", "//:cxxbinary"); result.assertSuccess(); assertThat(result.getStdout(), is(primary.getFileContents("stdout-cross-cell-dep"))); } @Test public void shouldBeAbleToUseProjectCommandXCell() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); ProjectWorkspace primary = cells.getFirst(); ProcessResult result = primary.runBuckCommand("project", "//:cxxbinary"); result.assertSuccess(); } @Test public void shouldBeAbleToUseACxxLibraryXCell() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); ProjectWorkspace primary = cells.getFirst(); ProcessResult result = primary.runBuckBuild("//:cxxbinary"); result.assertSuccess(); } @Test public void shouldBeAbleToUseMultipleXCell() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); ProjectWorkspace primary = createWorkspace("inter-cell/multi-cell/primary"); ProjectWorkspace secondary = createWorkspace("inter-cell/multi-cell/secondary"); ProjectWorkspace ternary = createWorkspace("inter-cell/multi-cell/ternary"); registerCell(secondary, "ternary", ternary); registerCell(primary, "secondary", secondary); registerCell(primary, "ternary", ternary); primary.runBuckCommand("targets", "--show-target-hash", "//:cxxbinary"); secondary.runBuckCommand("targets", "--show-target-hash", "//:cxxlib"); ternary.runBuckCommand("targets", "--show-target-hash", "//:cxxlib2"); ProcessResult result = primary.runBuckBuild("//:cxxbinary"); result.assertSuccess(); } @Test public void xCellCxxLibraryBuildsShouldBeHermetic() throws InterruptedException, IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); primary.runBuckBuild("//:cxxbinary"); ImmutableMap<String, HashCode> firstPrimaryObjectFiles = findObjectFiles(primary); ImmutableMap<String, HashCode> firstObjectFiles = findObjectFiles(secondary); // Now recreate an identical checkout cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); primary = cells.getFirst(); secondary = cells.getSecond(); primary.runBuckBuild("//:cxxbinary"); ImmutableMap<String, HashCode> secondPrimaryObjectFiles = findObjectFiles(primary); ImmutableMap<String, HashCode> secondObjectFiles = findObjectFiles(secondary); assertEquals(firstPrimaryObjectFiles, secondPrimaryObjectFiles); assertEquals(firstObjectFiles, secondObjectFiles); // TODO(yiding): The binaries are not identical due to changes to the relative path components. // Relative path from the binary's cell is embedded in order to allow tooling to correctly find // debug symbols. } private ImmutableMap<String, HashCode> findObjectFiles(ProjectWorkspace workspace) throws IOException { ProjectFilesystem filesystem = TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath()); Path buckOut = workspace.getPath(filesystem.getBuckPaths().getBuckOut()); ImmutableMap.Builder<String, HashCode> objectHashCodes = ImmutableMap.builder(); Files.walkFileTree( buckOut, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (MorePaths.getFileExtension(file).equals("o")) { HashCode hash = MorePaths.asByteSource(file).hash(Hashing.sha1()); objectHashCodes.put(buckOut.relativize(file).toString(), hash); } return FileVisitResult.CONTINUE; } }); ImmutableMap<String, HashCode> toReturn = objectHashCodes.build(); Preconditions.checkState(!toReturn.isEmpty()); return toReturn; } @Test public void shouldBeAbleToUseAJavaLibraryTargetXCell() throws IOException { Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/java/primary", "inter-cell/java/secondary"); ProjectWorkspace primary = cells.getFirst(); primary.runBuckBuild("//:primary_lib").assertSuccess(); primary.runBuckBuild("//:java-binary", "-v", "5").assertSuccess(); } @Test public void shouldBeAbleToCompileWithBootclasspathXCell() throws IOException { Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/java/primary", "inter-cell/java/secondary"); ProjectWorkspace primary = cells.getFirst(); String systemBootclasspath = System.getProperty("sun.boot.class.path"); ProcessResult result = primary.runBuckBuild( "//:java-binary", "--config", "java.source_level=7", "--config", "java.target_level=7", "--config", String.format( "//java.bootclasspath-7=primary.jar%s%s", File.pathSeparator, systemBootclasspath), "--config", String.format( "secondary//java.bootclasspath-7=secondary.jar%s%s", File.pathSeparator, systemBootclasspath), "-v", "5"); result.assertSuccess(); List<String> verboseLogs = Splitter.on('\n').trimResults().omitEmptyStrings().splitToList(result.getStderr()); // Check the javac invocations for properly a resolved bootclasspath and that we aren't // accidentally mixing bootclasspaths assertThat( verboseLogs, Matchers.hasItem( Matchers.allOf( containsString("javac"), containsString("-bootclasspath"), containsString(String.format("%sprimary.jar", File.separator)), containsString("primary_lib")))); assertThat( verboseLogs, Matchers.hasItem( Matchers.allOf( containsString("javac"), containsString("-bootclasspath"), containsString(String.format("%ssecondary.jar", File.separator)), containsString("secondary_lib"), not(containsString("primary_lib"))))); } @Test public void buildFileNamesCanBeDifferentCrossCell() throws IOException { Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/build-file-names/primary", "inter-cell/build-file-names/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); Path output = primary.buildAndReturnOutput("//:export"); String expected = secondary.getFileContents("hello-world.txt"); assertEquals(expected, new String(Files.readAllBytes(output), UTF_8)); } @SuppressWarnings("PMD.EmptyCatchBlock") @Test public void xCellVisibilityShouldWorkAsExpected() throws IOException, InterruptedException, BuildFileParseException { thrown.expect(HumanReadableException.class); parseTargetForXCellVisibility("//:not-visible-target"); } @Test public void xCellVisibilityPatternsBasedOnPublicBuildTargetsWork() throws InterruptedException, BuildFileParseException, IOException { parseTargetForXCellVisibility("//:public-target"); } @Test public void xCellVisibilityPatternsBasedOnExplicitBuildTargetsWork() throws InterruptedException, BuildFileParseException, IOException { parseTargetForXCellVisibility("//:visible-target"); } @Test public void xCellSingleDirectoryVisibilityPatternsWork() throws InterruptedException, BuildFileParseException, IOException { parseTargetForXCellVisibility("//sub2:directory"); } @Test public void xCellSubDirectoryVisibilityPatternsWork() throws InterruptedException, BuildFileParseException, IOException { parseTargetForXCellVisibility("//sub:wild-card"); } private void parseTargetForXCellVisibility(String targetName) throws IOException, InterruptedException, BuildFileParseException { Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/visibility/primary", "inter-cell/visibility/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); registerCell(primary, "primary", primary); registerCell(secondary, "primary", primary); // We could just do a build, but that's a little extreme since all we need is the target graph ProcessExecutor processExecutor = new DefaultProcessExecutor(new TestConsole()); PluginManager pluginManager = BuckPluginManagerFactory.createPluginManager(); KnownBuildRuleTypesProvider knownBuildRuleTypesProvider = KnownBuildRuleTypesProvider.of( DefaultKnownBuildRuleTypesFactory.of( processExecutor, pluginManager, new TestSandboxExecutionStrategyFactory())); ParserConfig parserConfig = primary.asCell().getBuckConfig().getView(ParserConfig.class); KnownConfigurationRuleTypes knownConfigurationRuleTypes = PluginBasedKnownConfigurationRuleTypesFactory.createFromPlugins(pluginManager); TypeCoercerFactory coercerFactory = new DefaultTypeCoercerFactory(); Parser parser = new DefaultParser( new PerBuildStateFactory( coercerFactory, new ConstructorArgMarshaller(coercerFactory), knownBuildRuleTypesProvider, knownConfigurationRuleTypes, new ParserPythonInterpreterProvider(parserConfig, new ExecutableFinder())), parserConfig, coercerFactory, new TargetSpecResolver()); BuckEventBus eventBus = BuckEventBusForTests.newInstance(); Cell primaryCell = primary.asCell(); BuildTarget namedTarget = BuildTargetFactory.newInstance(primaryCell.getFilesystem().getRootPath(), targetName); // It's enough that this parses cleanly. parser.buildTargetGraph( eventBus, primaryCell, false, MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()), ImmutableSet.of(namedTarget)); } @Test @Ignore public void allOutputsShouldBePlacedInTheSameRootOutputFolder() {} @Test public void circularCellReferencesAreAllowed() throws IOException { ProjectWorkspace mainRepo = TestDataHelper.createProjectWorkspaceForScenarioWithoutDefaultCell( this, "inter-cell/circular", tmp); mainRepo.setUp(); Path primary = mainRepo.getPath("primary"); ProcessResult result = mainRepo.runBuckCommandWithEnvironmentOverridesAndContext( primary, Optional.empty(), ImmutableMap.of(), "build", "//:bin"); result.assertSuccess(); } @Test public void testCommandLineConfigOverridesShouldSucceed() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); TestDataHelper.overrideBuckconfig( secondary, ImmutableMap.of("cxx", ImmutableMap.of("cc", "/does/not/exist"))); ProcessResult result = primary.runBuckBuild("--config", "secondary//cxx.cc=", "//:cxxbinary"); result.assertSuccess(); } @Test public void testCommandLineConfigOverridesShouldFail() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); TestDataHelper.overrideBuckconfig( secondary, ImmutableMap.of("cxx", ImmutableMap.of("cc", "/does/not/exist"))); thrown.expect(HumanReadableException.class); thrown.expectMessage( "Overridden cxx:cc path not found: /does/not/exist\n\n" + "This error happened while trying to get dependency 'secondary//:cxxlib' of target '//:cxxbinary'"); // This should throw primary.runBuckBuild("//:cxxbinary"); } @Test public void testCommandLineConfigOverridesWithConfigFile() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); TestDataHelper.overrideBuckconfig( secondary, ImmutableMap.of("cxx", ImmutableMap.of("cc", "/does/not/exist"))); Path arg = tmp.newFile("buckconfig"); Files.write(arg, ImmutableList.of("[cxx]", " cc =")); ProcessResult result = primary.runBuckBuild("--config-file", "secondary//=" + arg, "//:cxxbinary"); result.assertSuccess(); } @Test public void globalCommandLineConfigOverridesShouldWork() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); TestDataHelper.overrideBuckconfig( primary, ImmutableMap.of("cxx", ImmutableMap.of("cc", "/does/not/exist"))); TestDataHelper.overrideBuckconfig( secondary, ImmutableMap.of("cxx", ImmutableMap.of("cc", "/does/not/exist"))); ProcessResult result = primary.runBuckBuild("--config", "cxx.cc=", "//:cxxbinary"); result.assertSuccess(); } @Test public void buildFilesCanIncludeDefsFromOtherCells() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); ProjectWorkspace root = createWorkspace("inter-cell/include-defs/root"); ProjectWorkspace other = createWorkspace("inter-cell/include-defs/other"); registerCell(root, "other", other); registerCell(root, "root", root); registerCell(other, "root", root); root.runBuckBuild("//:rule", "other//:rule").assertSuccess(); } @Test public void buildFilesCanIncludeDefsFromOtherCellsUsingImplicitIncludes() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); ProjectWorkspace root = createWorkspace("inter-cell/includes/root"); ProjectWorkspace other = createWorkspace("inter-cell/includes/other"); registerCell(root, "other", other); registerCell(root, "root", root); registerCell(other, "root", root); TestDataHelper.overrideBuckconfig( root, ImmutableMap.of("buildfile", ImmutableMap.of("includes", "other//DEFS"))); root.runBuckBuild("//:rule", "other//:rule").assertSuccess(); } @Test public void shouldBeAbleToTestACxxLibrary() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); ProjectWorkspace workspace = createWorkspace("inter-cell/gtest/secondary"); TestDataHelper.overrideBuckconfig( workspace, ImmutableMap.of("cxx", ImmutableMap.of("gtest_dep", "//gtest:gtest"))); ProcessResult result = workspace.runBuckBuild("//test:cxxtest"); result.assertSuccess(); result = workspace.runBuckCommand("test", "//test:cxxtest"); result.assertSuccess(); } @Test public void shouldBeAbleToTestACxxLibraryXCell() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/gtest/primary", "inter-cell/gtest/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); TestDataHelper.overrideBuckconfig( secondary, ImmutableMap.of("cxx", ImmutableMap.of("gtest_dep", "//gtest:gtest"))); ProcessResult result = primary.runBuckBuild("secondary//test:cxxtest"); result.assertSuccess(); result = primary.runBuckCommand("test", "secondary//test:cxxtest"); result.assertSuccess(); result = primary.runBuckCommand("test", "//main:main"); result.assertSuccess(); } @Test public void shouldBeAbleToShareGtest() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/gtest/primary", "inter-cell/gtest/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); TestDataHelper.overrideBuckconfig( primary, ImmutableMap.of("cxx", ImmutableMap.of("gtest_dep", "secondary//gtest:gtest"))); // TODO(mzlee,dwh): secondary//gtest:gtest should be //gtest:gtest or we // should be able to use different cell names registerCell(secondary, "secondary", secondary); TestDataHelper.overrideBuckconfig( secondary, ImmutableMap.of("cxx", ImmutableMap.of("gtest_dep", "secondary//gtest:gtest"))); // TODO(mzlee,dwh): //test:cxxtest should be able to safely depend on // secondary//lib:cxxlib instead of having its own copy ProcessResult result = primary.runBuckCommand("test", "//test:cxxtest", "secondary//test:cxxtest"); result.assertSuccess(); } @Test public void childCellWithCellMappingNotInRootCellShouldThrowError() throws IOException { thrown.expect(HumanReadableException.class); thrown.expectMessage("repositories.third must exist in the root cell's cell mappings."); ProjectWorkspace root = createWorkspace("inter-cell/validation/root"); ProjectWorkspace second = createWorkspace("inter-cell/validation/root"); ProjectWorkspace third = createWorkspace("inter-cell/validation/root"); registerCell(root, "second", second); registerCell(second, "third", third); // should fail since "third" is not specified in root root.runBuckBuild("//:dummy"); } @Test public void childCellWithCellMappingInRootCellShouldSucceed() throws IOException { ProjectWorkspace root = createWorkspace("inter-cell/validation/root"); ProjectWorkspace second = createWorkspace("inter-cell/validation/root"); ProjectWorkspace third = createWorkspace("inter-cell/validation/root"); registerCell(root, "second", second); registerCell(second, "third", third); // now that "third" is registered in root, should succeed registerCell(root, "third", third); ProcessResult result = root.runBuckBuild("//:dummy"); result.assertSuccess(); } @Test public void childCellWithCellMappingThatDiffersFromRootCellShouldThrowError() throws IOException { thrown.expect(HumanReadableException.class); thrown.expectMessage( "repositories.third must point to the same directory as the root cell's cell " + "mapping:"); ProjectWorkspace root = createWorkspace("inter-cell/validation/root"); ProjectWorkspace second = createWorkspace("inter-cell/validation/root"); ProjectWorkspace third = createWorkspace("inter-cell/validation/root"); registerCell(root, "second", second); registerCell(second, "third", third); registerCell(root, "third", second); // should fail since we mapped "third" to wrong cell root.runBuckBuild("//:dummy"); } @Test public void testCrossCellAndroidLibrary() throws InterruptedException, IOException { AssumeAndroidPlatform.assumeSdkIsAvailable(); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/android/primary", "inter-cell/android/secondary"); ProjectWorkspace primary = cells.getFirst(); String target = "//apps/sample:app_with_cross_cell_android_lib"; ProcessResult result = primary.runBuckCommand("build", target); result.assertSuccess(); } @Test public void testCrossCellAndroidLibraryMerge() throws IOException, InterruptedException { AssumeAndroidPlatform.assumeSdkIsAvailable(); AssumeAndroidPlatform.assumeNdkIsAvailable(); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/android/primary", "inter-cell/android/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); TestDataHelper.overrideBuckconfig( primary, ImmutableMap.of("ndk", ImmutableMap.of("cpu_abis", "x86"))); TestDataHelper.overrideBuckconfig( secondary, ImmutableMap.of("ndk", ImmutableMap.of("cpu_abis", "x86"))); NdkCxxPlatform platform = AndroidNdkHelper.getNdkCxxPlatform(primary.asCell().getFilesystem()); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(new SourcePathRuleFinder(new TestActionGraphBuilder())); Path tmpDir = tmp.newFolder("merging_tmp"); SymbolGetter syms = new SymbolGetter( new DefaultProcessExecutor(new TestConsole()), tmpDir, platform.getObjdump(), pathResolver); SymbolsAndDtNeeded info; Path apkPath = primary.buildAndReturnOutput("//apps/sample:app_with_merged_cross_cell_libs"); ZipInspector zipInspector = new ZipInspector(apkPath); zipInspector.assertFileDoesNotExist("lib/x86/lib1a.so"); zipInspector.assertFileDoesNotExist("lib/x86/lib1b.so"); zipInspector.assertFileDoesNotExist("lib/x86/lib1g.so"); zipInspector.assertFileDoesNotExist("lib/x86/lib1h.so"); info = syms.getSymbolsAndDtNeeded(apkPath, "lib/x86/lib1.so"); assertThat(info.symbols.global, Matchers.hasItem("A")); assertThat(info.symbols.global, Matchers.hasItem("B")); assertThat(info.symbols.global, Matchers.hasItem("G")); assertThat(info.symbols.global, Matchers.hasItem("H")); assertThat(info.symbols.global, Matchers.hasItem("glue_1")); assertThat(info.symbols.global, not(Matchers.hasItem("glue_2"))); assertThat(info.dtNeeded, not(Matchers.hasItem("libnative_merge_B.so"))); assertThat(info.dtNeeded, not(Matchers.hasItem("libmerge_G.so"))); assertThat(info.dtNeeded, not(Matchers.hasItem("libmerge_H.so"))); } @Test public void testCrossCellDependencyMerge() throws IOException, InterruptedException { AssumeAndroidPlatform.assumeSdkIsAvailable(); AssumeAndroidPlatform.assumeNdkIsAvailable(); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/android/primary", "inter-cell/android/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); TestDataHelper.overrideBuckconfig( primary, ImmutableMap.of("ndk", ImmutableMap.of("cpu_abis", "x86"))); TestDataHelper.overrideBuckconfig( secondary, ImmutableMap.of("ndk", ImmutableMap.of("cpu_abis", "x86"))); NdkCxxPlatform platform = AndroidNdkHelper.getNdkCxxPlatform(primary.asCell().getFilesystem()); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(new SourcePathRuleFinder(new TestActionGraphBuilder())); Path tmpDir = tmp.newFolder("merging_tmp"); SymbolGetter syms = new SymbolGetter( new DefaultProcessExecutor(new TestConsole()), tmpDir, platform.getObjdump(), pathResolver); SymbolsAndDtNeeded info; Path apkPath = primary.buildAndReturnOutput("//apps/sample:app_with_merged_cross_cell_deps"); ZipInspector zipInspector = new ZipInspector(apkPath); zipInspector.assertFileDoesNotExist("lib/x86/lib1a.so"); zipInspector.assertFileDoesNotExist("lib/x86/lib1b.so"); zipInspector.assertFileDoesNotExist("lib/x86/lib1g.so"); zipInspector.assertFileDoesNotExist("lib/x86/lib1h.so"); zipInspector.assertFileExists("lib/x86/libI.so"); info = syms.getSymbolsAndDtNeeded(apkPath, "lib/x86/lib1.so"); assertThat(info.symbols.global, Matchers.hasItem("A")); assertThat(info.symbols.global, Matchers.hasItem("B")); assertThat(info.symbols.global, Matchers.hasItem("G")); assertThat(info.symbols.global, Matchers.hasItem("H")); assertThat(info.symbols.global, Matchers.hasItem("glue_1")); assertThat(info.symbols.global, not(Matchers.hasItem("glue_2"))); assertThat(info.dtNeeded, not(Matchers.hasItem("libnative_merge_B.so"))); assertThat(info.dtNeeded, not(Matchers.hasItem("libmerge_G.so"))); assertThat(info.dtNeeded, not(Matchers.hasItem("libmerge_H.so"))); } @Test public void targetsReferencingSameTargetsWithDifferentCellNamesAreConsideredTheSame() throws Exception { // This test case builds a cxx binary rule with libraries that all depend on the same targets. // If these targets were treated as distinct targets, the rule will have duplicate symbols. assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/canonicalization/primary", "inter-cell/canonicalization/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); registerCell(primary, "primary", primary); registerCell(secondary, "primary", primary); Path output = primary.buildAndReturnOutput(":a.out"); assertEquals( "The produced binary should give the expected exit code", 111, primary.runCommand(output.toString()).getExitCode()); } @Test public void targetsInOtherCellsArePrintedAsRelativeToRootCell() throws Exception { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/canonicalization/primary", "inter-cell/canonicalization/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); registerCell(primary, "primary", primary); registerCell(secondary, "primary", primary); String queryResult = primary.runBuckCommand("query", "deps(//:a.out)").assertSuccess().getStdout(); assertEquals( "Should refer to root cell targets without prefix and secondary cell targets with prefix", Joiner.on("\n").join("//:a.out", "//:rootlib", "secondary//:lib", "secondary//:lib2"), sortLines(queryResult)); queryResult = primary.runBuckCommand("query", "deps(secondary//:lib)").assertSuccess().getStdout(); assertEquals( "... even if query starts in a non-root cell.", Joiner.on("\n").join("//:rootlib", "secondary//:lib", "secondary//:lib2"), sortLines(queryResult)); } @Test public void testCrossCellCleanCommand() throws IOException, InterruptedException { Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); List<Path> primaryDirs = ImmutableList.of( primary.getPath(primary.getBuckPaths().getScratchDir()), primary.getPath(primary.getBuckPaths().getGenDir()), primary.getPath(primary.getBuckPaths().getTrashDir())); List<Path> secondaryDirs = ImmutableList.of( secondary.getPath(secondary.getBuckPaths().getScratchDir()), secondary.getPath(secondary.getBuckPaths().getGenDir()), secondary.getPath(secondary.getBuckPaths().getTrashDir())); // Set up the directories to be cleaned for (Path dir : primaryDirs) { Files.createDirectories(dir); assertTrue(Files.exists(dir)); } for (Path dir : secondaryDirs) { Files.createDirectories(dir); assertTrue(Files.exists(dir)); } primary.runBuckCommand("clean", "--keep-cache").assertSuccess(); for (Path dir : primaryDirs) { assertFalse(Files.exists(dir)); } for (Path dir : secondaryDirs) { assertFalse(Files.exists(dir)); } } @Test public void testParserFunctionsWithCells() throws IOException { Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/parser-functions/primary", "inter-cell/parser-functions/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); // Set up the remaining cells registerCell(primary, "primary", primary); registerCell(secondary, "primary", primary); registerCell(secondary, "secondary", secondary); String expected = primary.getFileContents("one/.txt"); Path path = primary.buildAndReturnOutput("//one:one"); String actual = new String(Files.readAllBytes(path), UTF_8); assertEquals(expected, actual); expected = secondary.getFileContents("two/secondary.txt"); path = primary.buildAndReturnOutput("//one:two"); actual = new String(Files.readAllBytes(path), UTF_8); assertEquals(expected, actual); expected = primary.getFileContents("one/primary.txt"); path = secondary.buildAndReturnOutput("//two:one"); actual = new String(Files.readAllBytes(path), UTF_8); assertEquals(expected, actual); expected = secondary.getFileContents("two/.txt"); path = secondary.buildAndReturnOutput("//two:two"); actual = new String(Files.readAllBytes(path), UTF_8); assertEquals(expected, actual); } @Test public void testCrossCellHandlesSQLiteMetadataConsistently() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); // This test case verifies that building the same target from different cells doesn't cause the // SQLite metadata store and filesystem to get out of sync. Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/metadata/primary", "inter-cell/metadata/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); // Set up the remaining cells registerCell(primary, "primary", primary); registerCell(secondary, "primary", primary); registerCell(secondary, "secondary", secondary); TestDataHelper.overrideBuckconfig( primary, ImmutableMap.of("build", ImmutableMap.of("metadata_storage", "sqlite"))); TestDataHelper.overrideBuckconfig( secondary, ImmutableMap.of("build", ImmutableMap.of("metadata_storage", "sqlite"))); // Build in the root cell. This populates the db with //:hello // entries, and the filesystem with RECORDED_PATHS metadata at paths like: // bin/.hello/metadata/RECORDED_PATHS primary.runBuckBuild("//:hello", "-c", "build.metadata_storage=sqlite").assertSuccess(); // Build in the secondary cell. This should overwrite the cell1 db with entries like //:hello, // and overwrite the filesystem with bin/.hello/metadata/RECORDED_PATHS. Note: it's important // that the DB keys are the same as in the previous step! If we use fully-qualified target // names, the rows can get out of sync. secondary.runBuckBuild("primary//:hello").assertSuccess(); // Introduce changes to both files, including a compile error, and build again. The compiler // error will cause // the build to delete the //:hello rows from the DB, and delete .hello/metadata/RECORDED_PATHS String hello = primary.getFileContents("hello.cpp"); String main = primary.getFileContents("main.cpp"); primary.writeContentsToPath(hello + "compile error\n", "hello.cpp"); primary.writeContentsToPath(main + "// foo\n", "main.cpp"); primary.runBuckBuild("//:hello").assertFailure(); // Revert the compile error, and build in the secondary. primary.writeContentsToPath(hello, "hello.cpp"); secondary.runBuckBuild("primary//:hello").assertSuccess(); } private static String sortLines(String input) { return RichStream.from(Splitter.on('\n').trimResults().omitEmptyStrings().split(input)) .sorted() .collect(Collectors.joining("\n")); } private Pair<ProjectWorkspace, ProjectWorkspace> prepare(String primaryPath, String secondaryPath) throws IOException { ProjectWorkspace primary = createWorkspace(primaryPath); ProjectWorkspace secondary = createWorkspace(secondaryPath); registerCell(primary, "secondary", secondary); return new Pair<>(primary, secondary); } private ProjectWorkspace createWorkspace(String scenarioName) throws IOException { Path tmpSubfolder = tmp.newFolder(); ProjectWorkspace projectWorkspace = TestDataHelper.createProjectWorkspaceForScenarioWithoutDefaultCell( this, scenarioName, tmpSubfolder); projectWorkspace.setUp(); return projectWorkspace; } private void registerCell( ProjectWorkspace cellToModifyConfigOf, String cellName, ProjectWorkspace cellToRegisterAsCellName) throws IOException { TestDataHelper.overrideBuckconfig( cellToModifyConfigOf, ImmutableMap.of( "repositories", ImmutableMap.of( cellName, cellToRegisterAsCellName.getPath(".").normalize().toString()))); } }
test/com/facebook/buck/crosscell/InterCellIntegrationTest.java
/* * Copyright 2015-present Facebook, 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 com.facebook.buck.crosscell; import static com.facebook.buck.android.toolchain.ndk.impl.AndroidNdkHelper.SymbolGetter; import static com.facebook.buck.android.toolchain.ndk.impl.AndroidNdkHelper.SymbolsAndDtNeeded; import static com.facebook.buck.util.environment.Platform.WINDOWS; import static java.nio.charset.StandardCharsets.UTF_8; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeThat; import com.facebook.buck.android.AssumeAndroidPlatform; import com.facebook.buck.android.toolchain.ndk.NdkCxxPlatform; import com.facebook.buck.android.toolchain.ndk.impl.AndroidNdkHelper; import com.facebook.buck.core.cell.Cell; import com.facebook.buck.core.exceptions.HumanReadableException; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.model.BuildTargetFactory; import com.facebook.buck.core.rules.SourcePathRuleFinder; import com.facebook.buck.core.rules.config.KnownConfigurationRuleTypes; import com.facebook.buck.core.rules.config.impl.PluginBasedKnownConfigurationRuleTypesFactory; import com.facebook.buck.core.rules.knowntypes.DefaultKnownBuildRuleTypesFactory; import com.facebook.buck.core.rules.knowntypes.KnownBuildRuleTypesProvider; import com.facebook.buck.core.rules.resolver.impl.TestActionGraphBuilder; import com.facebook.buck.core.sourcepath.resolver.SourcePathResolver; import com.facebook.buck.core.sourcepath.resolver.impl.DefaultSourcePathResolver; import com.facebook.buck.event.BuckEventBus; import com.facebook.buck.event.BuckEventBusForTests; import com.facebook.buck.io.ExecutableFinder; import com.facebook.buck.io.file.MorePaths; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.io.filesystem.TestProjectFilesystems; import com.facebook.buck.parser.DefaultParser; import com.facebook.buck.parser.Parser; import com.facebook.buck.parser.ParserConfig; import com.facebook.buck.parser.ParserPythonInterpreterProvider; import com.facebook.buck.parser.PerBuildStateFactory; import com.facebook.buck.parser.TargetSpecResolver; import com.facebook.buck.parser.exceptions.BuildFileParseException; import com.facebook.buck.plugin.impl.BuckPluginManagerFactory; import com.facebook.buck.rules.coercer.ConstructorArgMarshaller; import com.facebook.buck.rules.coercer.DefaultTypeCoercerFactory; import com.facebook.buck.rules.coercer.TypeCoercerFactory; import com.facebook.buck.sandbox.TestSandboxExecutionStrategyFactory; import com.facebook.buck.testutil.ProcessResult; import com.facebook.buck.testutil.TemporaryPaths; import com.facebook.buck.testutil.TestConsole; import com.facebook.buck.testutil.integration.ProjectWorkspace; import com.facebook.buck.testutil.integration.TestDataHelper; import com.facebook.buck.testutil.integration.ZipInspector; import com.facebook.buck.util.DefaultProcessExecutor; import com.facebook.buck.util.ProcessExecutor; import com.facebook.buck.util.RichStream; import com.facebook.buck.util.environment.Platform; import com.facebook.buck.util.types.Pair; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.hash.HashCode; import com.google.common.hash.Hashing; import com.google.common.util.concurrent.MoreExecutors; import java.io.File; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.List; import java.util.Optional; import java.util.concurrent.Executors; import java.util.stream.Collectors; import org.hamcrest.Matchers; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.pf4j.PluginManager; /** Cross-cell related integration tests that don't fit anywhere else. */ public class InterCellIntegrationTest { @Rule public TemporaryPaths tmp = new TemporaryPaths(); @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void ensureThatNormalBuildsWorkAsExpected() throws IOException { ProjectWorkspace secondary = TestDataHelper.createProjectWorkspaceForScenario( this, "inter-cell/export-file/secondary", tmp); secondary.setUp(); ProcessResult result = secondary.runBuckBuild("//:hello"); result.assertSuccess(); } @Test public void shouldBeAbleToUseAnExportFileXRepoTarget() throws IOException { Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); String expected = secondary.getFileContents("hello.txt"); Path path = primary.buildAndReturnOutput("//:exported-file"); String actual = new String(Files.readAllBytes(path), UTF_8); assertEquals(expected, actual); Path secondaryPath = primary.buildAndReturnRelativeOutput("secondary//:hello"); actual = new String(Files.readAllBytes(secondary.resolve(secondaryPath)), UTF_8); assertEquals(expected, actual); } @Test public void shouldBeAbleToUseTargetsCommandXCell() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); ProjectWorkspace primary = cells.getFirst(); ProcessResult result = primary.runBuckCommand("targets", "--show-target-hash", "//:cxxbinary"); result.assertSuccess(); ProcessResult result2 = primary.runBuckCommand("targets", "secondary//:cxxlib"); result2.assertSuccess(); } @Test public void shouldBeAbleToUseQueryCommandXCell() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); ProjectWorkspace primary = createWorkspace("inter-cell/multi-cell/primary"); ProjectWorkspace secondary = createWorkspace("inter-cell/multi-cell/secondary"); ProjectWorkspace ternary = createWorkspace("inter-cell/multi-cell/ternary"); registerCell(secondary, "ternary", ternary); registerCell(primary, "secondary", secondary); registerCell(primary, "ternary", ternary); primary.runBuckCommand("targets", "--show-target-hash", "//:cxxbinary"); secondary.runBuckCommand("targets", "--show-target-hash", "//:cxxlib"); ternary.runBuckCommand("targets", "--show-target-hash", "//:cxxlib2"); ProcessResult result = primary.runBuckCommand("query", "deps(%s)", "//:cxxbinary"); result.assertSuccess(); assertThat(result.getStdout(), is(primary.getFileContents("stdout-cross-cell-dep"))); } @Test public void shouldBeAbleToUseProjectCommandXCell() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); ProjectWorkspace primary = cells.getFirst(); ProcessResult result = primary.runBuckCommand("project", "//:cxxbinary"); result.assertSuccess(); } @Test public void shouldBeAbleToUseACxxLibraryXCell() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); ProjectWorkspace primary = cells.getFirst(); ProcessResult result = primary.runBuckBuild("//:cxxbinary"); result.assertSuccess(); } @Test public void shouldBeAbleToUseMultipleXCell() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); ProjectWorkspace primary = createWorkspace("inter-cell/multi-cell/primary"); ProjectWorkspace secondary = createWorkspace("inter-cell/multi-cell/secondary"); ProjectWorkspace ternary = createWorkspace("inter-cell/multi-cell/ternary"); registerCell(secondary, "ternary", ternary); registerCell(primary, "secondary", secondary); registerCell(primary, "ternary", ternary); primary.runBuckCommand("targets", "--show-target-hash", "//:cxxbinary"); secondary.runBuckCommand("targets", "--show-target-hash", "//:cxxlib"); ternary.runBuckCommand("targets", "--show-target-hash", "//:cxxlib2"); ProcessResult result = primary.runBuckBuild("//:cxxbinary"); result.assertSuccess(); } @Test public void xCellCxxLibraryBuildsShouldBeHermetic() throws InterruptedException, IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); primary.runBuckBuild("//:cxxbinary"); ImmutableMap<String, HashCode> firstPrimaryObjectFiles = findObjectFiles(primary); ImmutableMap<String, HashCode> firstObjectFiles = findObjectFiles(secondary); // Now recreate an identical checkout cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); primary = cells.getFirst(); secondary = cells.getSecond(); primary.runBuckBuild("//:cxxbinary"); ImmutableMap<String, HashCode> secondPrimaryObjectFiles = findObjectFiles(primary); ImmutableMap<String, HashCode> secondObjectFiles = findObjectFiles(secondary); assertEquals(firstPrimaryObjectFiles, secondPrimaryObjectFiles); assertEquals(firstObjectFiles, secondObjectFiles); // TODO(yiding): The binaries are not identical due to changes to the relative path components. // Relative path from the binary's cell is embedded in order to allow tooling to correctly find // debug symbols. } private ImmutableMap<String, HashCode> findObjectFiles(ProjectWorkspace workspace) throws IOException { ProjectFilesystem filesystem = TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath()); Path buckOut = workspace.getPath(filesystem.getBuckPaths().getBuckOut()); ImmutableMap.Builder<String, HashCode> objectHashCodes = ImmutableMap.builder(); Files.walkFileTree( buckOut, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (MorePaths.getFileExtension(file).equals("o")) { HashCode hash = MorePaths.asByteSource(file).hash(Hashing.sha1()); objectHashCodes.put(buckOut.relativize(file).toString(), hash); } return FileVisitResult.CONTINUE; } }); ImmutableMap<String, HashCode> toReturn = objectHashCodes.build(); Preconditions.checkState(!toReturn.isEmpty()); return toReturn; } @Test public void shouldBeAbleToUseAJavaLibraryTargetXCell() throws IOException { Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/java/primary", "inter-cell/java/secondary"); ProjectWorkspace primary = cells.getFirst(); primary.runBuckBuild("//:primary_lib").assertSuccess(); primary.runBuckBuild("//:java-binary", "-v", "5").assertSuccess(); } @Test public void shouldBeAbleToCompileWithBootclasspathXCell() throws IOException { Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/java/primary", "inter-cell/java/secondary"); ProjectWorkspace primary = cells.getFirst(); String systemBootclasspath = System.getProperty("sun.boot.class.path"); ProcessResult result = primary.runBuckBuild( "//:java-binary", "--config", "java.source_level=7", "--config", "java.target_level=7", "--config", String.format( "//java.bootclasspath-7=primary.jar%s%s", File.pathSeparator, systemBootclasspath), "--config", String.format( "secondary//java.bootclasspath-7=secondary.jar%s%s", File.pathSeparator, systemBootclasspath), "-v", "5"); result.assertSuccess(); List<String> verboseLogs = Splitter.on('\n').trimResults().omitEmptyStrings().splitToList(result.getStderr()); // Check the javac invocations for properly a resolved bootclasspath and that we aren't // accidentally mixing bootclasspaths assertThat( verboseLogs, Matchers.hasItem( Matchers.allOf( containsString("javac"), containsString("-bootclasspath"), containsString(String.format("%sprimary.jar", File.separator)), containsString("primary_lib")))); assertThat( verboseLogs, Matchers.hasItem( Matchers.allOf( containsString("javac"), containsString("-bootclasspath"), containsString(String.format("%ssecondary.jar", File.separator)), containsString("secondary_lib"), not(containsString("primary_lib"))))); } @Test public void buildFileNamesCanBeDifferentCrossCell() throws IOException { Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/build-file-names/primary", "inter-cell/build-file-names/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); Path output = primary.buildAndReturnOutput("//:export"); String expected = secondary.getFileContents("hello-world.txt"); assertEquals(expected, new String(Files.readAllBytes(output), UTF_8)); } @SuppressWarnings("PMD.EmptyCatchBlock") @Test public void xCellVisibilityShouldWorkAsExpected() throws IOException, InterruptedException, BuildFileParseException { try { parseTargetForXCellVisibility("//:not-visible-target"); fail("Did not expect parsing to succeed"); } catch (HumanReadableException expected) { // Everything is as it should be. } } @Test public void xCellVisibilityPatternsBasedOnPublicBuildTargetsWork() throws InterruptedException, BuildFileParseException, IOException { parseTargetForXCellVisibility("//:public-target"); } @Test public void xCellVisibilityPatternsBasedOnExplicitBuildTargetsWork() throws InterruptedException, BuildFileParseException, IOException { parseTargetForXCellVisibility("//:visible-target"); } @Test public void xCellSingleDirectoryVisibilityPatternsWork() throws InterruptedException, BuildFileParseException, IOException { parseTargetForXCellVisibility("//sub2:directory"); } @Test public void xCellSubDirectoryVisibilityPatternsWork() throws InterruptedException, BuildFileParseException, IOException { parseTargetForXCellVisibility("//sub:wild-card"); } private void parseTargetForXCellVisibility(String targetName) throws IOException, InterruptedException, BuildFileParseException { Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/visibility/primary", "inter-cell/visibility/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); registerCell(primary, "primary", primary); registerCell(secondary, "primary", primary); // We could just do a build, but that's a little extreme since all we need is the target graph ProcessExecutor processExecutor = new DefaultProcessExecutor(new TestConsole()); PluginManager pluginManager = BuckPluginManagerFactory.createPluginManager(); KnownBuildRuleTypesProvider knownBuildRuleTypesProvider = KnownBuildRuleTypesProvider.of( DefaultKnownBuildRuleTypesFactory.of( processExecutor, pluginManager, new TestSandboxExecutionStrategyFactory())); ParserConfig parserConfig = primary.asCell().getBuckConfig().getView(ParserConfig.class); KnownConfigurationRuleTypes knownConfigurationRuleTypes = PluginBasedKnownConfigurationRuleTypesFactory.createFromPlugins(pluginManager); TypeCoercerFactory coercerFactory = new DefaultTypeCoercerFactory(); Parser parser = new DefaultParser( new PerBuildStateFactory( coercerFactory, new ConstructorArgMarshaller(coercerFactory), knownBuildRuleTypesProvider, knownConfigurationRuleTypes, new ParserPythonInterpreterProvider(parserConfig, new ExecutableFinder())), parserConfig, coercerFactory, new TargetSpecResolver()); BuckEventBus eventBus = BuckEventBusForTests.newInstance(); Cell primaryCell = primary.asCell(); BuildTarget namedTarget = BuildTargetFactory.newInstance(primaryCell.getFilesystem().getRootPath(), targetName); // It's enough that this parses cleanly. parser.buildTargetGraph( eventBus, primaryCell, false, MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()), ImmutableSet.of(namedTarget)); } @Test @Ignore public void allOutputsShouldBePlacedInTheSameRootOutputFolder() {} @Test public void circularCellReferencesAreAllowed() throws IOException { ProjectWorkspace mainRepo = TestDataHelper.createProjectWorkspaceForScenarioWithoutDefaultCell( this, "inter-cell/circular", tmp); mainRepo.setUp(); Path primary = mainRepo.getPath("primary"); ProcessResult result = mainRepo.runBuckCommandWithEnvironmentOverridesAndContext( primary, Optional.empty(), ImmutableMap.of(), "build", "//:bin"); result.assertSuccess(); } @SuppressWarnings("PMD.EmptyCatchBlock") @Test public void shouldBeAbleToUseCommandLineConfigOverrides() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); TestDataHelper.overrideBuckconfig( secondary, ImmutableMap.of("cxx", ImmutableMap.of("cc", "/does/not/exist"))); try { primary.runBuckBuild("//:cxxbinary"); fail("Did not expect to finish building"); } catch (HumanReadableException expected) { assertEquals( expected.getMessage(), "Overridden cxx:cc path not found: /does/not/exist\n\n" + "This error happened while trying to get dependency 'secondary//:cxxlib' of target '//:cxxbinary'"); } ProcessResult result = primary.runBuckBuild("--config", "secondary//cxx.cc=", "//:cxxbinary"); result.assertSuccess(); } @Test public void shouldBeAbleToUseCommandLineConfigFileOverrides() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); TestDataHelper.overrideBuckconfig( secondary, ImmutableMap.of("cxx", ImmutableMap.of("cc", "/does/not/exist"))); Path arg = tmp.newFile("buckconfig"); Files.write(arg, ImmutableList.of("[cxx]", " cc =")); ProcessResult result = primary.runBuckBuild("--config-file", "secondary//=" + arg, "//:cxxbinary"); result.assertSuccess(); thrown.expect(HumanReadableException.class); thrown.expectMessage( "Overridden cxx:cc path not found: /does/not/exist\n\n" + "This error happened while trying to get dependency 'secondary//:cxxlib' of target '//:cxxbinary'"); // This should throw primary.runBuckBuild("//:cxxbinary"); } @Test public void globalCommandLineConfigOverridesShouldWork() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); TestDataHelper.overrideBuckconfig( primary, ImmutableMap.of("cxx", ImmutableMap.of("cc", "/does/not/exist"))); TestDataHelper.overrideBuckconfig( secondary, ImmutableMap.of("cxx", ImmutableMap.of("cc", "/does/not/exist"))); try { primary.runBuckBuild("//:cxxbinary"); fail("Did not expect to finish building"); } catch (HumanReadableException expected) { assertEquals(expected.getMessage(), "Overridden cxx:cc path not found: /does/not/exist"); } ProcessResult result = primary.runBuckBuild("--config", "cxx.cc=", "//:cxxbinary"); result.assertSuccess(); } @Test public void buildFilesCanIncludeDefsFromOtherCells() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); ProjectWorkspace root = createWorkspace("inter-cell/include-defs/root"); ProjectWorkspace other = createWorkspace("inter-cell/include-defs/other"); registerCell(root, "other", other); registerCell(root, "root", root); registerCell(other, "root", root); root.runBuckBuild("//:rule", "other//:rule").assertSuccess(); } @Test public void buildFilesCanIncludeDefsFromOtherCellsUsingImplicitIncludes() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); ProjectWorkspace root = createWorkspace("inter-cell/includes/root"); ProjectWorkspace other = createWorkspace("inter-cell/includes/other"); registerCell(root, "other", other); registerCell(root, "root", root); registerCell(other, "root", root); TestDataHelper.overrideBuckconfig( root, ImmutableMap.of("buildfile", ImmutableMap.of("includes", "other//DEFS"))); root.runBuckBuild("//:rule", "other//:rule").assertSuccess(); } @Test public void shouldBeAbleToTestACxxLibrary() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); ProjectWorkspace workspace = createWorkspace("inter-cell/gtest/secondary"); TestDataHelper.overrideBuckconfig( workspace, ImmutableMap.of("cxx", ImmutableMap.of("gtest_dep", "//gtest:gtest"))); ProcessResult result = workspace.runBuckBuild("//test:cxxtest"); result.assertSuccess(); result = workspace.runBuckCommand("test", "//test:cxxtest"); result.assertSuccess(); } @Test public void shouldBeAbleToTestACxxLibraryXCell() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/gtest/primary", "inter-cell/gtest/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); TestDataHelper.overrideBuckconfig( secondary, ImmutableMap.of("cxx", ImmutableMap.of("gtest_dep", "//gtest:gtest"))); ProcessResult result = primary.runBuckBuild("secondary//test:cxxtest"); result.assertSuccess(); result = primary.runBuckCommand("test", "secondary//test:cxxtest"); result.assertSuccess(); result = primary.runBuckCommand("test", "//main:main"); result.assertSuccess(); } @Test public void shouldBeAbleToShareGtest() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/gtest/primary", "inter-cell/gtest/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); TestDataHelper.overrideBuckconfig( primary, ImmutableMap.of("cxx", ImmutableMap.of("gtest_dep", "secondary//gtest:gtest"))); // TODO(mzlee,dwh): secondary//gtest:gtest should be //gtest:gtest or we // should be able to use different cell names registerCell(secondary, "secondary", secondary); TestDataHelper.overrideBuckconfig( secondary, ImmutableMap.of("cxx", ImmutableMap.of("gtest_dep", "secondary//gtest:gtest"))); // TODO(mzlee,dwh): //test:cxxtest should be able to safely depend on // secondary//lib:cxxlib instead of having its own copy ProcessResult result = primary.runBuckCommand("test", "//test:cxxtest", "secondary//test:cxxtest"); result.assertSuccess(); } @Test public void childCellWithCellMappingNotInRootCellShouldThrowError() throws IOException { ProjectWorkspace root = createWorkspace("inter-cell/validation/root"); ProjectWorkspace second = createWorkspace("inter-cell/validation/root"); ProjectWorkspace third = createWorkspace("inter-cell/validation/root"); registerCell(root, "second", second); registerCell(second, "third", third); // should fail if "third" is not specified in root try { root.runBuckBuild("//:dummy"); fail("Should have thrown a HumanReadableException."); } catch (HumanReadableException e) { assertThat( e.getHumanReadableErrorMessage(), containsString("repositories.third must exist in the root cell's cell mappings.")); } // and succeeds when it is registerCell(root, "third", third); ProcessResult result = root.runBuckBuild("//:dummy"); result.assertSuccess(); } @Test public void childCellWithCellMappingThatDiffersFromRootCellShouldThrowError() throws IOException { ProjectWorkspace root = createWorkspace("inter-cell/validation/root"); ProjectWorkspace second = createWorkspace("inter-cell/validation/root"); ProjectWorkspace third = createWorkspace("inter-cell/validation/root"); registerCell(root, "second", second); registerCell(second, "third", third); // should fail if "third" is not mapped to third in the root. registerCell(root, "third", second); try { root.runBuckBuild("//:dummy"); fail("Should have thrown a HumanReadableException."); } catch (HumanReadableException e) { assertThat( e.getHumanReadableErrorMessage(), containsString( "repositories.third must point to the same directory as the root cell's cell " + "mapping:")); } // and succeeds when it is registerCell(root, "third", third); ProcessResult result = root.runBuckBuild("//:dummy"); result.assertSuccess(); } @Test public void testCrossCellAndroidLibrary() throws InterruptedException, IOException { AssumeAndroidPlatform.assumeSdkIsAvailable(); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/android/primary", "inter-cell/android/secondary"); ProjectWorkspace primary = cells.getFirst(); String target = "//apps/sample:app_with_cross_cell_android_lib"; ProcessResult result = primary.runBuckCommand("build", target); result.assertSuccess(); } @Test public void testCrossCellAndroidLibraryMerge() throws IOException, InterruptedException { AssumeAndroidPlatform.assumeSdkIsAvailable(); AssumeAndroidPlatform.assumeNdkIsAvailable(); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/android/primary", "inter-cell/android/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); TestDataHelper.overrideBuckconfig( primary, ImmutableMap.of("ndk", ImmutableMap.of("cpu_abis", "x86"))); TestDataHelper.overrideBuckconfig( secondary, ImmutableMap.of("ndk", ImmutableMap.of("cpu_abis", "x86"))); NdkCxxPlatform platform = AndroidNdkHelper.getNdkCxxPlatform(primary.asCell().getFilesystem()); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(new SourcePathRuleFinder(new TestActionGraphBuilder())); Path tmpDir = tmp.newFolder("merging_tmp"); SymbolGetter syms = new SymbolGetter( new DefaultProcessExecutor(new TestConsole()), tmpDir, platform.getObjdump(), pathResolver); SymbolsAndDtNeeded info; Path apkPath = primary.buildAndReturnOutput("//apps/sample:app_with_merged_cross_cell_libs"); ZipInspector zipInspector = new ZipInspector(apkPath); zipInspector.assertFileDoesNotExist("lib/x86/lib1a.so"); zipInspector.assertFileDoesNotExist("lib/x86/lib1b.so"); zipInspector.assertFileDoesNotExist("lib/x86/lib1g.so"); zipInspector.assertFileDoesNotExist("lib/x86/lib1h.so"); info = syms.getSymbolsAndDtNeeded(apkPath, "lib/x86/lib1.so"); assertThat(info.symbols.global, Matchers.hasItem("A")); assertThat(info.symbols.global, Matchers.hasItem("B")); assertThat(info.symbols.global, Matchers.hasItem("G")); assertThat(info.symbols.global, Matchers.hasItem("H")); assertThat(info.symbols.global, Matchers.hasItem("glue_1")); assertThat(info.symbols.global, not(Matchers.hasItem("glue_2"))); assertThat(info.dtNeeded, not(Matchers.hasItem("libnative_merge_B.so"))); assertThat(info.dtNeeded, not(Matchers.hasItem("libmerge_G.so"))); assertThat(info.dtNeeded, not(Matchers.hasItem("libmerge_H.so"))); } @Test public void testCrossCellDependencyMerge() throws IOException, InterruptedException { AssumeAndroidPlatform.assumeSdkIsAvailable(); AssumeAndroidPlatform.assumeNdkIsAvailable(); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/android/primary", "inter-cell/android/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); TestDataHelper.overrideBuckconfig( primary, ImmutableMap.of("ndk", ImmutableMap.of("cpu_abis", "x86"))); TestDataHelper.overrideBuckconfig( secondary, ImmutableMap.of("ndk", ImmutableMap.of("cpu_abis", "x86"))); NdkCxxPlatform platform = AndroidNdkHelper.getNdkCxxPlatform(primary.asCell().getFilesystem()); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(new SourcePathRuleFinder(new TestActionGraphBuilder())); Path tmpDir = tmp.newFolder("merging_tmp"); SymbolGetter syms = new SymbolGetter( new DefaultProcessExecutor(new TestConsole()), tmpDir, platform.getObjdump(), pathResolver); SymbolsAndDtNeeded info; Path apkPath = primary.buildAndReturnOutput("//apps/sample:app_with_merged_cross_cell_deps"); ZipInspector zipInspector = new ZipInspector(apkPath); zipInspector.assertFileDoesNotExist("lib/x86/lib1a.so"); zipInspector.assertFileDoesNotExist("lib/x86/lib1b.so"); zipInspector.assertFileDoesNotExist("lib/x86/lib1g.so"); zipInspector.assertFileDoesNotExist("lib/x86/lib1h.so"); zipInspector.assertFileExists("lib/x86/libI.so"); info = syms.getSymbolsAndDtNeeded(apkPath, "lib/x86/lib1.so"); assertThat(info.symbols.global, Matchers.hasItem("A")); assertThat(info.symbols.global, Matchers.hasItem("B")); assertThat(info.symbols.global, Matchers.hasItem("G")); assertThat(info.symbols.global, Matchers.hasItem("H")); assertThat(info.symbols.global, Matchers.hasItem("glue_1")); assertThat(info.symbols.global, not(Matchers.hasItem("glue_2"))); assertThat(info.dtNeeded, not(Matchers.hasItem("libnative_merge_B.so"))); assertThat(info.dtNeeded, not(Matchers.hasItem("libmerge_G.so"))); assertThat(info.dtNeeded, not(Matchers.hasItem("libmerge_H.so"))); } @Test public void targetsReferencingSameTargetsWithDifferentCellNamesAreConsideredTheSame() throws Exception { // This test case builds a cxx binary rule with libraries that all depend on the same targets. // If these targets were treated as distinct targets, the rule will have duplicate symbols. assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/canonicalization/primary", "inter-cell/canonicalization/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); registerCell(primary, "primary", primary); registerCell(secondary, "primary", primary); Path output = primary.buildAndReturnOutput(":a.out"); assertEquals( "The produced binary should give the expected exit code", 111, primary.runCommand(output.toString()).getExitCode()); } @Test public void targetsInOtherCellsArePrintedAsRelativeToRootCell() throws Exception { assumeThat(Platform.detect(), is(not(WINDOWS))); Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/canonicalization/primary", "inter-cell/canonicalization/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); registerCell(primary, "primary", primary); registerCell(secondary, "primary", primary); String queryResult = primary.runBuckCommand("query", "deps(//:a.out)").assertSuccess().getStdout(); assertEquals( "Should refer to root cell targets without prefix and secondary cell targets with prefix", Joiner.on("\n").join("//:a.out", "//:rootlib", "secondary//:lib", "secondary//:lib2"), sortLines(queryResult)); queryResult = primary.runBuckCommand("query", "deps(secondary//:lib)").assertSuccess().getStdout(); assertEquals( "... even if query starts in a non-root cell.", Joiner.on("\n").join("//:rootlib", "secondary//:lib", "secondary//:lib2"), sortLines(queryResult)); } @Test public void testCrossCellCleanCommand() throws IOException, InterruptedException { Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); List<Path> primaryDirs = ImmutableList.of( primary.getPath(primary.getBuckPaths().getScratchDir()), primary.getPath(primary.getBuckPaths().getGenDir()), primary.getPath(primary.getBuckPaths().getTrashDir())); List<Path> secondaryDirs = ImmutableList.of( secondary.getPath(secondary.getBuckPaths().getScratchDir()), secondary.getPath(secondary.getBuckPaths().getGenDir()), secondary.getPath(secondary.getBuckPaths().getTrashDir())); // Set up the directories to be cleaned for (Path dir : primaryDirs) { Files.createDirectories(dir); assertTrue(Files.exists(dir)); } for (Path dir : secondaryDirs) { Files.createDirectories(dir); assertTrue(Files.exists(dir)); } primary.runBuckCommand("clean", "--keep-cache").assertSuccess(); for (Path dir : primaryDirs) { assertFalse(Files.exists(dir)); } for (Path dir : secondaryDirs) { assertFalse(Files.exists(dir)); } } @Test public void testParserFunctionsWithCells() throws IOException { Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/parser-functions/primary", "inter-cell/parser-functions/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); // Set up the remaining cells registerCell(primary, "primary", primary); registerCell(secondary, "primary", primary); registerCell(secondary, "secondary", secondary); String expected = primary.getFileContents("one/.txt"); Path path = primary.buildAndReturnOutput("//one:one"); String actual = new String(Files.readAllBytes(path), UTF_8); assertEquals(expected, actual); expected = secondary.getFileContents("two/secondary.txt"); path = primary.buildAndReturnOutput("//one:two"); actual = new String(Files.readAllBytes(path), UTF_8); assertEquals(expected, actual); expected = primary.getFileContents("one/primary.txt"); path = secondary.buildAndReturnOutput("//two:one"); actual = new String(Files.readAllBytes(path), UTF_8); assertEquals(expected, actual); expected = secondary.getFileContents("two/.txt"); path = secondary.buildAndReturnOutput("//two:two"); actual = new String(Files.readAllBytes(path), UTF_8); assertEquals(expected, actual); } @Test public void testCrossCellHandlesSQLiteMetadataConsistently() throws IOException { assumeThat(Platform.detect(), is(not(WINDOWS))); // This test case verifies that building the same target from different cells doesn't cause the // SQLite metadata store and filesystem to get out of sync. Pair<ProjectWorkspace, ProjectWorkspace> cells = prepare("inter-cell/metadata/primary", "inter-cell/metadata/secondary"); ProjectWorkspace primary = cells.getFirst(); ProjectWorkspace secondary = cells.getSecond(); // Set up the remaining cells registerCell(primary, "primary", primary); registerCell(secondary, "primary", primary); registerCell(secondary, "secondary", secondary); TestDataHelper.overrideBuckconfig( primary, ImmutableMap.of("build", ImmutableMap.of("metadata_storage", "sqlite"))); TestDataHelper.overrideBuckconfig( secondary, ImmutableMap.of("build", ImmutableMap.of("metadata_storage", "sqlite"))); // Build in the root cell. This populates the db with //:hello // entries, and the filesystem with RECORDED_PATHS metadata at paths like: // bin/.hello/metadata/RECORDED_PATHS primary.runBuckBuild("//:hello", "-c", "build.metadata_storage=sqlite").assertSuccess(); // Build in the secondary cell. This should overwrite the cell1 db with entries like //:hello, // and overwrite the filesystem with bin/.hello/metadata/RECORDED_PATHS. Note: it's important // that the DB keys are the same as in the previous step! If we use fully-qualified target // names, the rows can get out of sync. secondary.runBuckBuild("primary//:hello").assertSuccess(); // Introduce changes to both files, including a compile error, and build again. The compiler // error will cause // the build to delete the //:hello rows from the DB, and delete .hello/metadata/RECORDED_PATHS String hello = primary.getFileContents("hello.cpp"); String main = primary.getFileContents("main.cpp"); primary.writeContentsToPath(hello + "compile error\n", "hello.cpp"); primary.writeContentsToPath(main + "// foo\n", "main.cpp"); primary.runBuckBuild("//:hello").assertFailure(); // Revert the compile error, and build in the secondary. primary.writeContentsToPath(hello, "hello.cpp"); secondary.runBuckBuild("primary//:hello").assertSuccess(); } private static String sortLines(String input) { return RichStream.from(Splitter.on('\n').trimResults().omitEmptyStrings().split(input)) .sorted() .collect(Collectors.joining("\n")); } private Pair<ProjectWorkspace, ProjectWorkspace> prepare(String primaryPath, String secondaryPath) throws IOException { ProjectWorkspace primary = createWorkspace(primaryPath); ProjectWorkspace secondary = createWorkspace(secondaryPath); registerCell(primary, "secondary", secondary); return new Pair<>(primary, secondary); } private ProjectWorkspace createWorkspace(String scenarioName) throws IOException { Path tmpSubfolder = tmp.newFolder(); ProjectWorkspace projectWorkspace = TestDataHelper.createProjectWorkspaceForScenarioWithoutDefaultCell( this, scenarioName, tmpSubfolder); projectWorkspace.setUp(); return projectWorkspace; } private void registerCell( ProjectWorkspace cellToModifyConfigOf, String cellName, ProjectWorkspace cellToRegisterAsCellName) throws IOException { TestDataHelper.overrideBuckconfig( cellToModifyConfigOf, ImmutableMap.of( "repositories", ImmutableMap.of( cellName, cellToRegisterAsCellName.getPath(".").normalize().toString()))); } }
Refactor InterCellIntegrationTest exception handling Summary: Replace all try ... catch blocks with junit's [`ExpectedException`](http://junit.org/javadoc/latest/org/junit/rules/ExpectedException.html) Reviewed By: styurin fbshipit-source-id: cb6ee14520
test/com/facebook/buck/crosscell/InterCellIntegrationTest.java
Refactor InterCellIntegrationTest exception handling
<ide><path>est/com/facebook/buck/crosscell/InterCellIntegrationTest.java <ide> import static org.junit.Assert.assertFalse; <ide> import static org.junit.Assert.assertThat; <ide> import static org.junit.Assert.assertTrue; <del>import static org.junit.Assert.fail; <ide> import static org.junit.Assume.assumeThat; <ide> <ide> import com.facebook.buck.android.AssumeAndroidPlatform; <ide> @Test <ide> public void xCellVisibilityShouldWorkAsExpected() <ide> throws IOException, InterruptedException, BuildFileParseException { <del> try { <del> parseTargetForXCellVisibility("//:not-visible-target"); <del> fail("Did not expect parsing to succeed"); <del> } catch (HumanReadableException expected) { <del> // Everything is as it should be. <del> } <add> thrown.expect(HumanReadableException.class); <add> parseTargetForXCellVisibility("//:not-visible-target"); <ide> } <ide> <ide> @Test <ide> result.assertSuccess(); <ide> } <ide> <del> @SuppressWarnings("PMD.EmptyCatchBlock") <del> @Test <del> public void shouldBeAbleToUseCommandLineConfigOverrides() throws IOException { <add> @Test <add> public void testCommandLineConfigOverridesShouldSucceed() throws IOException { <ide> assumeThat(Platform.detect(), is(not(WINDOWS))); <ide> <ide> Pair<ProjectWorkspace, ProjectWorkspace> cells = <ide> TestDataHelper.overrideBuckconfig( <ide> secondary, ImmutableMap.of("cxx", ImmutableMap.of("cc", "/does/not/exist"))); <ide> <del> try { <del> primary.runBuckBuild("//:cxxbinary"); <del> fail("Did not expect to finish building"); <del> } catch (HumanReadableException expected) { <del> assertEquals( <del> expected.getMessage(), <del> "Overridden cxx:cc path not found: /does/not/exist\n\n" <del> + "This error happened while trying to get dependency 'secondary//:cxxlib' of target '//:cxxbinary'"); <del> } <del> <ide> ProcessResult result = primary.runBuckBuild("--config", "secondary//cxx.cc=", "//:cxxbinary"); <ide> <ide> result.assertSuccess(); <ide> } <ide> <ide> @Test <del> public void shouldBeAbleToUseCommandLineConfigFileOverrides() throws IOException { <add> public void testCommandLineConfigOverridesShouldFail() throws IOException { <ide> assumeThat(Platform.detect(), is(not(WINDOWS))); <ide> <ide> Pair<ProjectWorkspace, ProjectWorkspace> cells = <ide> ProjectWorkspace secondary = cells.getSecond(); <ide> TestDataHelper.overrideBuckconfig( <ide> secondary, ImmutableMap.of("cxx", ImmutableMap.of("cc", "/does/not/exist"))); <del> <del> Path arg = tmp.newFile("buckconfig"); <del> Files.write(arg, ImmutableList.of("[cxx]", " cc =")); <del> <del> ProcessResult result = <del> primary.runBuckBuild("--config-file", "secondary//=" + arg, "//:cxxbinary"); <del> <del> result.assertSuccess(); <ide> <ide> thrown.expect(HumanReadableException.class); <ide> thrown.expectMessage( <ide> } <ide> <ide> @Test <add> public void testCommandLineConfigOverridesWithConfigFile() throws IOException { <add> assumeThat(Platform.detect(), is(not(WINDOWS))); <add> <add> Pair<ProjectWorkspace, ProjectWorkspace> cells = <add> prepare("inter-cell/export-file/primary", "inter-cell/export-file/secondary"); <add> ProjectWorkspace primary = cells.getFirst(); <add> ProjectWorkspace secondary = cells.getSecond(); <add> TestDataHelper.overrideBuckconfig( <add> secondary, ImmutableMap.of("cxx", ImmutableMap.of("cc", "/does/not/exist"))); <add> <add> Path arg = tmp.newFile("buckconfig"); <add> Files.write(arg, ImmutableList.of("[cxx]", " cc =")); <add> <add> ProcessResult result = <add> primary.runBuckBuild("--config-file", "secondary//=" + arg, "//:cxxbinary"); <add> <add> result.assertSuccess(); <add> } <add> <add> @Test <ide> public void globalCommandLineConfigOverridesShouldWork() throws IOException { <ide> assumeThat(Platform.detect(), is(not(WINDOWS))); <ide> <ide> primary, ImmutableMap.of("cxx", ImmutableMap.of("cc", "/does/not/exist"))); <ide> TestDataHelper.overrideBuckconfig( <ide> secondary, ImmutableMap.of("cxx", ImmutableMap.of("cc", "/does/not/exist"))); <del> <del> try { <del> primary.runBuckBuild("//:cxxbinary"); <del> fail("Did not expect to finish building"); <del> } catch (HumanReadableException expected) { <del> assertEquals(expected.getMessage(), "Overridden cxx:cc path not found: /does/not/exist"); <del> } <ide> <ide> ProcessResult result = primary.runBuckBuild("--config", "cxx.cc=", "//:cxxbinary"); <ide> <ide> <ide> @Test <ide> public void childCellWithCellMappingNotInRootCellShouldThrowError() throws IOException { <add> thrown.expect(HumanReadableException.class); <add> thrown.expectMessage("repositories.third must exist in the root cell's cell mappings."); <add> <ide> ProjectWorkspace root = createWorkspace("inter-cell/validation/root"); <ide> ProjectWorkspace second = createWorkspace("inter-cell/validation/root"); <ide> ProjectWorkspace third = createWorkspace("inter-cell/validation/root"); <ide> registerCell(root, "second", second); <ide> registerCell(second, "third", third); <ide> <del> // should fail if "third" is not specified in root <del> try { <del> root.runBuckBuild("//:dummy"); <del> fail("Should have thrown a HumanReadableException."); <del> } catch (HumanReadableException e) { <del> assertThat( <del> e.getHumanReadableErrorMessage(), <del> containsString("repositories.third must exist in the root cell's cell mappings.")); <del> } <del> <del> // and succeeds when it is <del> registerCell(root, "third", third); <del> ProcessResult result = root.runBuckBuild("//:dummy"); <del> result.assertSuccess(); <del> } <del> <del> @Test <del> public void childCellWithCellMappingThatDiffersFromRootCellShouldThrowError() throws IOException { <add> // should fail since "third" is not specified in root <add> root.runBuckBuild("//:dummy"); <add> } <add> <add> @Test <add> public void childCellWithCellMappingInRootCellShouldSucceed() throws IOException { <ide> ProjectWorkspace root = createWorkspace("inter-cell/validation/root"); <ide> ProjectWorkspace second = createWorkspace("inter-cell/validation/root"); <ide> ProjectWorkspace third = createWorkspace("inter-cell/validation/root"); <ide> registerCell(root, "second", second); <ide> registerCell(second, "third", third); <ide> <del> // should fail if "third" is not mapped to third in the root. <del> registerCell(root, "third", second); <del> try { <del> root.runBuckBuild("//:dummy"); <del> fail("Should have thrown a HumanReadableException."); <del> } catch (HumanReadableException e) { <del> assertThat( <del> e.getHumanReadableErrorMessage(), <del> containsString( <del> "repositories.third must point to the same directory as the root cell's cell " <del> + "mapping:")); <del> } <del> <del> // and succeeds when it is <add> // now that "third" is registered in root, should succeed <ide> registerCell(root, "third", third); <ide> ProcessResult result = root.runBuckBuild("//:dummy"); <ide> result.assertSuccess(); <add> } <add> <add> @Test <add> public void childCellWithCellMappingThatDiffersFromRootCellShouldThrowError() throws IOException { <add> thrown.expect(HumanReadableException.class); <add> thrown.expectMessage( <add> "repositories.third must point to the same directory as the root cell's cell " <add> + "mapping:"); <add> ProjectWorkspace root = createWorkspace("inter-cell/validation/root"); <add> ProjectWorkspace second = createWorkspace("inter-cell/validation/root"); <add> ProjectWorkspace third = createWorkspace("inter-cell/validation/root"); <add> registerCell(root, "second", second); <add> registerCell(second, "third", third); <add> registerCell(root, "third", second); <add> <add> // should fail since we mapped "third" to wrong cell <add> root.runBuckBuild("//:dummy"); <ide> } <ide> <ide> @Test
Java
apache-2.0
1cc4bb4988c387fc7d97cc1a7545224e347aeb25
0
warnerbros/cpe-manifest-android-experience
package com.wb.nextgenlibrary.activity; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.media.MediaPlayer; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.VideoView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.model.GlideUrl; import com.bumptech.glide.load.resource.drawable.GlideDrawable; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.target.Target; import com.wb.nextgenlibrary.NextGenExperience; import com.wb.nextgenlibrary.R; import com.wb.nextgenlibrary.analytic.NextGenAnalyticData; import com.wb.nextgenlibrary.data.MovieMetaData; import com.wb.nextgenlibrary.data.StyleData; import com.wb.nextgenlibrary.parser.cpestyle.BackgroundOverlayAreaType; import com.wb.nextgenlibrary.testassets.TestItemsActivity; import com.wb.nextgenlibrary.util.Size; import com.wb.nextgenlibrary.util.TabletUtils; import com.wb.nextgenlibrary.util.utils.F; import com.wb.nextgenlibrary.util.utils.NextGenGlide; import com.wb.nextgenlibrary.util.utils.NextGenLogger; import com.wb.nextgenlibrary.util.utils.StringHelper; import com.wb.nextgenlibrary.widget.FixedAspectRatioFrameLayout; import java.util.Timer; import java.util.TimerTask; /** * Created by gzcheng on 1/7/16. */ public class NextGenActivity extends NextGenHideStatusBarActivity implements View.OnClickListener { VideoView startupVideoView; ImageView startupImageView; MediaPlayer audioPlayer; ImageButton playMovieButton; ImageButton extraButton; ImageButton purchaseButton; Button playMovieTextButton; Button extraTextButton; View imageButtonsFrame; View textButtonsFrame; Size startupVideoSize = null; Size bgImageSize = null; View exitIcon = null; FixedAspectRatioFrameLayout videoParentFrame; FixedAspectRatioFrameLayout imageParentFrame; FixedAspectRatioFrameLayout buttonParentFrame; private int videoLoopPoint = 0; private int buttonAnimationStartTime = 0; private TimerTask startUpTimerTask; private Timer startUpTimer; private boolean isStartUp = true; StyleData.ExperienceStyle mainStyle = NextGenExperience.getMovieMetaData() != null ? NextGenExperience.getMovieMetaData().getRootExperienceStyle() : null; @Override public void onCreate(Bundle savedState) { super.onCreate(savedState); setContentView(R.layout.next_gen_startup_view); if (NextGenExperience.getMovieMetaData() == null) finish(); videoParentFrame = (FixedAspectRatioFrameLayout)findViewById(R.id.video_parent_aspect_ratio_frame); buttonParentFrame = (FixedAspectRatioFrameLayout)findViewById(R.id.button_parent_aspect_ratio_frame); imageParentFrame = (FixedAspectRatioFrameLayout)findViewById(R.id.image_background_aspect_ratio_frame); textButtonsFrame = findViewById(R.id.startup_text_buttons_layout); exitIcon = findViewById(R.id.nge_main_exit); startupVideoView = (VideoView)findViewById(R.id.startup_video_view); startupImageView = (ImageView) findViewById(R.id.startup_image_view); imageButtonsFrame = findViewById(R.id.startup_buttons_layout); setPlayExtraButtonsVisibility(ButtonsMode.ALL_INVISIBLE); if (exitIcon != null){ exitIcon.setOnClickListener(this); } playMovieButton = (ImageButton) findViewById(R.id.next_gen_startup_play_button); if (playMovieButton != null){ playMovieButton.setOnClickListener(this); } playMovieTextButton = (Button)findViewById(R.id.next_gen_startup_play_text_button); if (playMovieTextButton != null){ playMovieTextButton.setOnClickListener(this); } View.OnLongClickListener extraLongClickListener = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Intent intent = new Intent(NextGenActivity.this, TestItemsActivity.class); startActivity(intent); return true; } }; extraButton = (ImageButton) findViewById(R.id.next_gen_startup_extra_button); if (extraButton != null){ extraButton.setOnClickListener(this); // extraButton.setOnLongClickListener(extraLongClickListener); } extraTextButton = (Button)findViewById(R.id.next_gen_startup_extra_text_button); if (extraTextButton != null){ extraTextButton.setOnClickListener(this); //extraTextButton.setOnLongClickListener(extraLongClickListener); } purchaseButton = (ImageButton) findViewById(R.id.next_gen_startup_purchase_button); if (purchaseButton != null){ purchaseButton.setOnClickListener(this); } StyleData.NodeBackground nodeBackground = (mainStyle != null ) ? mainStyle.getBackground() : null; if (nodeBackground != null && !StringHelper.isEmpty(nodeBackground.getVideoUrl())) { videoLoopPoint = nodeBackground.getVideoLoopingPoint(); if (videoLoopPoint > 500) buttonAnimationStartTime = nodeBackground.getVideoLoopingPoint() - 500; } MovieMetaData.PictureImageData bgImageData = (mainStyle != null ) ? mainStyle.getBackgroundImage() : null; if (bgImageData != null && !StringHelper.isEmpty(bgImageData.url)){ String bgImageUrl = bgImageData.url; imageParentFrame.setAspectRatio(bgImageData.width, bgImageData.height); bgImageSize = new Size(bgImageData.width, bgImageData.height); if (startupImageView != null && !StringHelper.isEmpty(bgImageUrl)){ startupImageView.setVisibility(View.VISIBLE); NextGenGlide.load(this, bgImageUrl).asBitmap().fitCenter().into(startupImageView); } }else{ // load default image String imageurl = NextGenExperience.getMovieMetaData().getExtraExperience().getPosterImgUrl(); videoParentFrame.setVisibility(View.GONE); NextGenGlide.load(this, imageurl).listener(new RequestListener<GlideUrl, GlideDrawable>() { @Override public boolean onException(Exception e, GlideUrl model, Target<GlideDrawable> target, boolean isFirstResource) { return false; } @Override public boolean onResourceReady(final GlideDrawable resource, GlideUrl model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) { runOnUiThread(new Runnable() { @Override public void run() { imageParentFrame.setAspectRatio(resource.getIntrinsicWidth(), resource.getIntrinsicHeight()); } }); return false; } }).fitCenter().into(startupImageView); } View.OnClickListener showButtonOnClickLister = new View.OnClickListener() { @Override public void onClick(View v) { animateButtonsOn(); } }; if (startupVideoView != null){ startupVideoView.setOnClickListener(showButtonOnClickLister); } if (buttonParentFrame != null){ buttonParentFrame.setOnClickListener(showButtonOnClickLister); } arrangeLayoutAccordingToScreenOrientation(getResources().getConfiguration().orientation); } @Override public void onStart(){ super.onStart(); if (TabletUtils.isTablet()) setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); else setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR); if (mainStyle != null) { if (StringHelper.isEmpty(mainStyle.getBackgroundVideoUrl())) { // if there's no background video startupVideoView.setVisibility(View.GONE); setPlayExtraButtonsVisibility(ButtonsMode.IMAGE_BUTTON_VISIBLE); } else { if (!isStartUp) { startupVideoView.seekTo(videoLoopPoint); startupVideoView.start(); return; } isStartUp = false; startupVideoSize = mainStyle.getBackgroundVideoSize(); if (startupVideoSize != null) videoParentFrame.setAspectRatio(startupVideoSize.getWidth(), startupVideoSize.getHeight()); startupVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(final MediaPlayer mp) { runOnUiThread(new Runnable() { @Override public void run() { if (startupVideoSize == null) { startupVideoSize = new Size(mp.getVideoWidth(), mp.getVideoHeight()); videoParentFrame.setAspectRatio(startupVideoSize.getWidth(), startupVideoSize.getHeight()); } //adjustButtonSizesAndPosition(); } }); startupVideoView.start(); animateButtonsOn(); //added: tr 9/19 mp.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() { @Override public void onSeekComplete(MediaPlayer mp) { startupVideoView.start(); } }); } }); startupVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { startupVideoView.seekTo(videoLoopPoint); //need to wait until the seekTo is complete before restarting. //startupVideoView.start(); } }); startupVideoView.requestFocus(); if (Build.FINGERPRINT.contains("generic")){ startupVideoView.setVideoURI(Uri.parse("https://ia800201.us.archive.org/12/items/BigBuckBunny_328/BigBuckBunny_512kb.mp4")); }else startupVideoView.setVideoURI(Uri.parse(mainStyle.getBackgroundVideoUrl())); if (!StringHelper.isEmpty(mainStyle.getBackgroundAudioUrl())){ try { audioPlayer = MediaPlayer.create(this, Uri.parse(mainStyle.getBackgroundAudioUrl())); audioPlayer.setLooping(true); audioPlayer.start(); }catch (Exception ex){ NextGenLogger.e(F.TAG, ex.getMessage()); } } } }else { setPlayExtraButtonsVisibility(ButtonsMode.TEXT_BUTTON_VISIBLE); } } private void animateButtonsOn(){ if (startUpTimer == null) { startUpTimer = new Timer(); } if (startUpTimerTask == null) { startUpTimerTask = new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { StyleData.NodeStyleData nodeStyleData = mainStyle.getNodeStyleData(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); StyleData.ThemeData buttonTheme = mainStyle.getNodeStyleData(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE).theme; MovieMetaData.PictureImageData extraBtnImageData = buttonTheme.getImageData(StyleData.ThemeData.EXTRA_BUTTON); MovieMetaData.PictureImageData playBtnImageData = buttonTheme.getImageData(StyleData.ThemeData.PLAY_BUTTON); if (imageButtonsFrame != null && extraBtnImageData != null && playBtnImageData != null) { setPlayExtraButtonsVisibility(ButtonsMode.IMAGE_BUTTON_VISIBLE); imageButtonsFrame.setVisibility(View.VISIBLE); imageButtonsFrame.setAlpha(0.0f); // Start the animation imageButtonsFrame.animate().setDuration(1000).alpha(1.0f); } if (exitIcon != null){ exitIcon.setVisibility(View.GONE); exitIcon.setVisibility(View.VISIBLE); exitIcon.setAlpha(0.0f); // Start the animation exitIcon.animate().setDuration(1000).alpha(1.0f); } } }); } }; startUpTimer.schedule(startUpTimerTask, buttonAnimationStartTime); } } public void onPause(){ super.onPause(); if (startupVideoView.isPlaying()){ startupVideoView.pause(); } if (audioPlayer != null){ audioPlayer.pause(); } } @Override public void onResume(){ super.onResume(); if (!startupVideoView.isPlaying() && startupVideoView.getVisibility() == View.VISIBLE){ startupVideoView.start(); } if (audioPlayer != null){ audioPlayer.start(); } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); arrangeLayoutAccordingToScreenOrientation(newConfig.orientation); } private void arrangeLayoutAccordingToScreenOrientation(final int orientation){ imageParentFrame.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { arrangeLayoutAccordingToScreenOrientation_priv(orientation); imageParentFrame.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); } private void arrangeLayoutAccordingToScreenOrientation_priv(int orientation){ ViewGroup.LayoutParams layoutParams = videoParentFrame.getLayoutParams(); FixedAspectRatioFrameLayout buttonsReferenceFrame; Size buttonsReferenceFrameSize; Size buttonsReferenceFrameSourceSize; StyleData.NodeStyleData nodeStyleData; boolean isPortrait = false; if (mainStyle == null) // if there's no main style, no calculations of button positions will be needed return; if (orientation == Configuration.ORIENTATION_PORTRAIT && !TabletUtils.isTablet()) { // handle portrait mode only when it's on phone isPortrait = true; buttonsReferenceFrameSize = new Size(imageParentFrame.getWidth(), imageParentFrame.getHeight()); buttonsReferenceFrame = imageParentFrame; buttonsReferenceFrameSourceSize = bgImageSize; nodeStyleData = mainStyle.getNodeStyleData(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); if (!StringHelper.isEmpty(mainStyle.getBackgroundVideoUrl())) { videoParentFrame.setAspectRatioPriority(FixedAspectRatioFrameLayout.Priority.WIDTH_PRIORITY); layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT; videoParentFrame.setLayoutParams(layoutParams); } else { } }else /*if (orientation == Configuration.ORIENTATION_LANDSCAPE)*/{ // for tablets and Landscape mode nodeStyleData = mainStyle.getNodeStyleData(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); if (!StringHelper.isEmpty(mainStyle.getBackgroundVideoUrl())) { Size videoSize = mainStyle.getBackgroundVideoSize(); Size screenSize = NextGenExperience.getScreenSize(NextGenExperience.getApplicationContext()); float videoAspectRatio = ((float) videoSize.getHeight()) /((float) videoSize.getWidth()); float screenAspectRatio = ((float) screenSize.getHeight()) /((float) screenSize.getWidth()); if (screenAspectRatio > 1) screenAspectRatio = 1/ screenAspectRatio; if (screenAspectRatio >= videoAspectRatio) { videoParentFrame.setAspectRatioPriority(FixedAspectRatioFrameLayout.Priority.HEIGHT_PRIORITY); layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT; } else { videoParentFrame.setAspectRatioPriority(FixedAspectRatioFrameLayout.Priority.WIDTH_PRIORITY); layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT; } videoParentFrame.setLayoutParams(layoutParams); buttonsReferenceFrameSize = new Size(videoParentFrame.getWidth(), videoParentFrame.getHeight()); buttonsReferenceFrame = videoParentFrame; buttonsReferenceFrameSourceSize = startupVideoSize; } else { buttonsReferenceFrameSize = new Size(imageParentFrame.getWidth(), imageParentFrame.getHeight()); buttonsReferenceFrame = imageParentFrame; buttonsReferenceFrameSourceSize = bgImageSize; } } if (nodeStyleData != null) { textButtonsFrame.setVisibility(View.GONE); StyleData.ThemeData buttonTheme = nodeStyleData.theme; BackgroundOverlayAreaType buttonLayoutArea = nodeStyleData.getBGOverlay(); if (!StringHelper.isEmpty(mainStyle.getBackgroundVideoUrl()) && startupVideoSize == null) return; double shrinkRatio = ((double) buttonsReferenceFrameSize.getWidth()) / ((double) buttonsReferenceFrameSourceSize.getWidth()); double buttonShrinkRation = shrinkRatio; buttonParentFrame.copyFrameParams(buttonsReferenceFrame); int width = (int) (((double) buttonLayoutArea.getWidthPixels().intValue()) * shrinkRatio); int screenWidth = NextGenExperience.getScreenWidth(this); if (width > screenWidth){ // if the specific area is wider than the screen, set the button area to be the screen width width = screenWidth - 20 ; // 20 being the padding on the size, 10 pixels each side buttonShrinkRation = ((double) width / ((double) buttonLayoutArea.getWidthPixels().intValue())); } int height = (int) (((double) buttonLayoutArea.getHeightPixels().intValue()) * buttonShrinkRation); int y = (int) (((double) buttonsReferenceFrameSourceSize.getHeight() - buttonLayoutArea.getPixelsFromBottom().intValue()) * shrinkRatio) - height; int x = (int) (((double) buttonLayoutArea.getPixelsFromLeft().intValue()) * shrinkRatio); if (isPortrait){ x = (buttonsReferenceFrameSize.getWidth() - width) / 2; } ViewGroup.LayoutParams buttonsLayoutParams = imageButtonsFrame.getLayoutParams(); if (buttonsLayoutParams instanceof LinearLayout.LayoutParams) { ((LinearLayout.LayoutParams) buttonsLayoutParams).setMargins(x, y, 0, 0); } else if (buttonsLayoutParams instanceof RelativeLayout.LayoutParams) { ((RelativeLayout.LayoutParams) buttonsLayoutParams).setMargins(x, y, 0, 0); } else if (buttonsLayoutParams instanceof FrameLayout.LayoutParams) { ((FrameLayout.LayoutParams) buttonsLayoutParams).setMargins(x, y, 0, 0); } buttonsLayoutParams.height = height; buttonsLayoutParams.width = width; imageButtonsFrame.setLayoutParams(buttonsLayoutParams); MovieMetaData.PictureImageData extraBtnImageData = buttonTheme.getImageData(StyleData.ThemeData.EXTRA_BUTTON); MovieMetaData.PictureImageData playBtnImageData = buttonTheme.getImageData(StyleData.ThemeData.PLAY_BUTTON); MovieMetaData.PictureImageData purchaseBtnImageData = buttonTheme.getImageData(StyleData.ThemeData.PURCHASE_BUTTON); if (extraBtnImageData != null && playBtnImageData != null) { double buttonRatio = (double) width / (double) playBtnImageData.width; ViewGroup.LayoutParams playBtnParams = null; if (playMovieButton != null) { playBtnParams = playMovieButton.getLayoutParams(); int newHeight = (int) ((double) playBtnImageData.height * buttonRatio); playBtnParams.height = newHeight; playMovieButton.setLayoutParams(playBtnParams); if (playBtnImageData != null) NextGenGlide.load(this, playBtnImageData.url).into(playMovieButton); } if (purchaseButton != null) { if (purchaseBtnImageData != null && playBtnParams != null) { //purchaseButton.setVisibility(View.VISIBLE); ViewGroup.LayoutParams buttonsParams = purchaseButton.getLayoutParams(); buttonsParams.height = playBtnParams.height; purchaseButton.setLayoutParams(buttonsParams); NextGenGlide.load(this, purchaseBtnImageData.url).into(purchaseButton); } else purchaseButton.setVisibility(View.GONE); } if (extraButton != null) { ViewGroup.LayoutParams buttonsParams = extraButton.getLayoutParams(); int newWidth = (int) ((double) extraBtnImageData.width * buttonRatio); int newHeight = (int) ((double) extraBtnImageData.height * buttonRatio); buttonsParams.height = newHeight; buttonsParams.width = newWidth; int extra_x, extra_y; extra_x = (buttonsLayoutParams.width - newWidth) / 2; //calculate extra Btn position if (purchaseBtnImageData != null) { extra_y = (buttonsLayoutParams.height - newHeight) / 2; } else { extra_y = buttonsLayoutParams.height - newHeight; } if (buttonsParams instanceof LinearLayout.LayoutParams) { ((LinearLayout.LayoutParams) buttonsParams).setMargins(extra_x, extra_y, 0, 0); } else if (buttonsParams instanceof RelativeLayout.LayoutParams) { ((RelativeLayout.LayoutParams) buttonsParams).setMargins(extra_x, extra_y, 0, 0); } else if (buttonsParams instanceof FrameLayout.LayoutParams) { ((FrameLayout.LayoutParams) buttonsParams).setMargins(extra_x, extra_y, 0, 0); } extraButton.setLayoutParams(buttonsParams); if (extraBtnImageData != null) NextGenGlide.load(this, extraBtnImageData.url).into(extraButton); } imageButtonsFrame.invalidate(); if (StringHelper.isEmpty(mainStyle.getBackgroundVideoUrl())) { imageButtonsFrame.setVisibility(View.VISIBLE); exitIcon.setVisibility(View.VISIBLE); } }else{ setPlayExtraButtonsVisibility(ButtonsMode.TEXT_BUTTON_VISIBLE); } return; } } @Override public void onClick(View v){ if (v.getId() == R.id.next_gen_startup_play_button || v.getId() == R.id.next_gen_startup_play_text_button) { Intent intent = new Intent(this, NextGenPlayer.class); intent.setDataAndType(Uri.parse(NextGenExperience.getMovieMetaData().getMainMovieUrl()), "video/*"); startActivity(intent); NextGenAnalyticData.reportEvent(this, null, NextGenAnalyticData.AnalyticAction.ACTION_PLAY_MOVIE, null, null); } else if (v.getId() == R.id.next_gen_startup_extra_button || v.getId() == R.id.next_gen_startup_extra_text_button) { Intent extraIntent = new Intent(this, NextGenExtraActivity.class); startActivity(extraIntent); NextGenAnalyticData.reportEvent(this, null, NextGenAnalyticData.AnalyticAction.ACTION_EXTRAS, null, null); } else if (v.getId() == R.id.next_gen_startup_purchase_button) { if (NextGenExperience.getNextGenEventHandler() != null) NextGenExperience.getNextGenEventHandler().handlePurchaseButtonPressed(this, NextGenExperience.getNextgenPlaybackObject()); NextGenAnalyticData.reportEvent(this, null, NextGenAnalyticData.AnalyticAction.ACTION_BUY, null, null); } else if (v.getId() == R.id.nge_main_exit){ NextGenAnalyticData.reportEvent(this, null, NextGenAnalyticData.AnalyticAction.ACTION_EXIT, null, null); finish(); } } static enum ButtonsMode{ TEXT_BUTTON_VISIBLE, IMAGE_BUTTON_VISIBLE, ALL_INVISIBLE; } private void setPlayExtraButtonsVisibility(ButtonsMode mode){ switch (mode){ case TEXT_BUTTON_VISIBLE: textButtonsFrame.setVisibility(View.VISIBLE); imageButtonsFrame.setVisibility(View.GONE); exitIcon.setVisibility(View.VISIBLE); break; case IMAGE_BUTTON_VISIBLE: imageButtonsFrame.setVisibility(View.VISIBLE); textButtonsFrame.setVisibility(View.GONE); exitIcon.setVisibility(View.VISIBLE); break; case ALL_INVISIBLE: default: imageButtonsFrame.setVisibility(View.GONE); textButtonsFrame.setVisibility(View.GONE); exitIcon.setVisibility(View.GONE); } } }
src/com/wb/nextgenlibrary/activity/NextGenActivity.java
package com.wb.nextgenlibrary.activity; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.media.MediaPlayer; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.VideoView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.model.GlideUrl; import com.bumptech.glide.load.resource.drawable.GlideDrawable; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.target.Target; import com.wb.nextgenlibrary.NextGenExperience; import com.wb.nextgenlibrary.R; import com.wb.nextgenlibrary.analytic.NextGenAnalyticData; import com.wb.nextgenlibrary.data.MovieMetaData; import com.wb.nextgenlibrary.data.StyleData; import com.wb.nextgenlibrary.parser.cpestyle.BackgroundOverlayAreaType; import com.wb.nextgenlibrary.testassets.TestItemsActivity; import com.wb.nextgenlibrary.util.Size; import com.wb.nextgenlibrary.util.TabletUtils; import com.wb.nextgenlibrary.util.utils.F; import com.wb.nextgenlibrary.util.utils.NextGenGlide; import com.wb.nextgenlibrary.util.utils.NextGenLogger; import com.wb.nextgenlibrary.util.utils.StringHelper; import com.wb.nextgenlibrary.widget.FixedAspectRatioFrameLayout; import java.util.Timer; import java.util.TimerTask; /** * Created by gzcheng on 1/7/16. */ public class NextGenActivity extends NextGenHideStatusBarActivity implements View.OnClickListener { VideoView startupVideoView; ImageView startupImageView; MediaPlayer audioPlayer; ImageButton playMovieButton; ImageButton extraButton; ImageButton purchaseButton; Button playMovieTextButton; Button extraTextButton; View imageButtonsFrame; View textButtonsFrame; Size startupVideoSize = null; Size bgImageSize = null; View exitIcon = null; FixedAspectRatioFrameLayout videoParentFrame; FixedAspectRatioFrameLayout imageParentFrame; FixedAspectRatioFrameLayout buttonParentFrame; private int videoLoopPoint = 0; private int buttonAnimationStartTime = 0; private TimerTask startUpTimerTask; private Timer startUpTimer; private boolean isStartUp = true; StyleData.ExperienceStyle mainStyle = NextGenExperience.getMovieMetaData() != null ? NextGenExperience.getMovieMetaData().getRootExperienceStyle() : null; @Override public void onCreate(Bundle savedState) { super.onCreate(savedState); setContentView(R.layout.next_gen_startup_view); if (NextGenExperience.getMovieMetaData() == null) finish(); videoParentFrame = (FixedAspectRatioFrameLayout)findViewById(R.id.video_parent_aspect_ratio_frame); buttonParentFrame = (FixedAspectRatioFrameLayout)findViewById(R.id.button_parent_aspect_ratio_frame); imageParentFrame = (FixedAspectRatioFrameLayout)findViewById(R.id.image_background_aspect_ratio_frame); textButtonsFrame = findViewById(R.id.startup_text_buttons_layout); exitIcon = findViewById(R.id.nge_main_exit); startupVideoView = (VideoView)findViewById(R.id.startup_video_view); startupImageView = (ImageView) findViewById(R.id.startup_image_view); imageButtonsFrame = findViewById(R.id.startup_buttons_layout); setPlayExtraButtonsVisibility(ButtonsMode.ALL_INVISIBLE); if (exitIcon != null){ exitIcon.setOnClickListener(this); } playMovieButton = (ImageButton) findViewById(R.id.next_gen_startup_play_button); if (playMovieButton != null){ playMovieButton.setOnClickListener(this); } playMovieTextButton = (Button)findViewById(R.id.next_gen_startup_play_text_button); if (playMovieTextButton != null){ playMovieTextButton.setOnClickListener(this); } View.OnLongClickListener extraLongClickListener = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Intent intent = new Intent(NextGenActivity.this, TestItemsActivity.class); startActivity(intent); return true; } }; extraButton = (ImageButton) findViewById(R.id.next_gen_startup_extra_button); if (extraButton != null){ extraButton.setOnClickListener(this); // extraButton.setOnLongClickListener(extraLongClickListener); } extraTextButton = (Button)findViewById(R.id.next_gen_startup_extra_text_button); if (extraTextButton != null){ extraTextButton.setOnClickListener(this); //extraTextButton.setOnLongClickListener(extraLongClickListener); } purchaseButton = (ImageButton) findViewById(R.id.next_gen_startup_purchase_button); if (purchaseButton != null){ purchaseButton.setOnClickListener(this); } StyleData.NodeBackground nodeBackground = (mainStyle != null ) ? mainStyle.getBackground() : null; if (nodeBackground != null && !StringHelper.isEmpty(nodeBackground.getVideoUrl())) { videoLoopPoint = nodeBackground.getVideoLoopingPoint(); if (videoLoopPoint > 500) buttonAnimationStartTime = nodeBackground.getVideoLoopingPoint() - 500; } MovieMetaData.PictureImageData bgImageData = (mainStyle != null ) ? mainStyle.getBackgroundImage() : null; if (bgImageData != null && !StringHelper.isEmpty(bgImageData.url)){ String bgImageUrl = bgImageData.url; imageParentFrame.setAspectRatio(bgImageData.width, bgImageData.height); bgImageSize = new Size(bgImageData.width, bgImageData.height); if (startupImageView != null && !StringHelper.isEmpty(bgImageUrl)){ startupImageView.setVisibility(View.VISIBLE); NextGenGlide.load(this, bgImageUrl).asBitmap().fitCenter().into(startupImageView); } }else{ // load default image String imageurl = NextGenExperience.getMovieMetaData().getExtraExperience().getPosterImgUrl(); videoParentFrame.setVisibility(View.GONE); NextGenGlide.load(this, imageurl).listener(new RequestListener<GlideUrl, GlideDrawable>() { @Override public boolean onException(Exception e, GlideUrl model, Target<GlideDrawable> target, boolean isFirstResource) { return false; } @Override public boolean onResourceReady(final GlideDrawable resource, GlideUrl model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) { runOnUiThread(new Runnable() { @Override public void run() { imageParentFrame.setAspectRatio(resource.getIntrinsicWidth(), resource.getIntrinsicHeight()); } }); return false; } }).fitCenter().into(startupImageView); } arrangeLayoutAccordingToScreenOrientation(getResources().getConfiguration().orientation); } @Override public void onStart(){ super.onStart(); if (TabletUtils.isTablet()) setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); else setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR); if (mainStyle != null) { if (StringHelper.isEmpty(mainStyle.getBackgroundVideoUrl())) { // if there's no background video startupVideoView.setVisibility(View.GONE); setPlayExtraButtonsVisibility(ButtonsMode.IMAGE_BUTTON_VISIBLE); } else { if (!isStartUp) { startupVideoView.seekTo(videoLoopPoint); startupVideoView.start(); return; } isStartUp = false; startupVideoSize = mainStyle.getBackgroundVideoSize(); if (startupVideoSize != null) videoParentFrame.setAspectRatio(startupVideoSize.getWidth(), startupVideoSize.getHeight()); startupVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(final MediaPlayer mp) { runOnUiThread(new Runnable() { @Override public void run() { if (startupVideoSize == null) { startupVideoSize = new Size(mp.getVideoWidth(), mp.getVideoHeight()); videoParentFrame.setAspectRatio(startupVideoSize.getWidth(), startupVideoSize.getHeight()); } //adjustButtonSizesAndPosition(); } }); startupVideoView.start(); if (startUpTimer == null) { startUpTimer = new Timer(); } if (startUpTimerTask == null) { startUpTimerTask = new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { StyleData.NodeStyleData nodeStyleData = mainStyle.getNodeStyleData(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); StyleData.ThemeData buttonTheme = mainStyle.getNodeStyleData(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE).theme; MovieMetaData.PictureImageData extraBtnImageData = buttonTheme.getImageData(StyleData.ThemeData.EXTRA_BUTTON); MovieMetaData.PictureImageData playBtnImageData = buttonTheme.getImageData(StyleData.ThemeData.PLAY_BUTTON); if (imageButtonsFrame != null && extraBtnImageData != null && playBtnImageData != null) { setPlayExtraButtonsVisibility(ButtonsMode.IMAGE_BUTTON_VISIBLE); imageButtonsFrame.setVisibility(View.VISIBLE); imageButtonsFrame.setAlpha(0.0f); // Start the animation imageButtonsFrame.animate().setDuration(1000).alpha(1.0f); } if (exitIcon != null){ exitIcon.setVisibility(View.GONE); exitIcon.setVisibility(View.VISIBLE); exitIcon.setAlpha(0.0f); // Start the animation exitIcon.animate().setDuration(1000).alpha(1.0f); } } }); } }; startUpTimer.schedule(startUpTimerTask, buttonAnimationStartTime); } //added: tr 9/19 mp.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() { @Override public void onSeekComplete(MediaPlayer mp) { startupVideoView.start(); } }); } }); startupVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { startupVideoView.seekTo(videoLoopPoint); //need to wait until the seekTo is complete before restarting. //startupVideoView.start(); } }); startupVideoView.requestFocus(); if (Build.FINGERPRINT.contains("generic")){ startupVideoView.setVideoURI(Uri.parse("https://ia800201.us.archive.org/12/items/BigBuckBunny_328/BigBuckBunny_512kb.mp4")); }else startupVideoView.setVideoURI(Uri.parse(mainStyle.getBackgroundVideoUrl())); if (!StringHelper.isEmpty(mainStyle.getBackgroundAudioUrl())){ try { audioPlayer = MediaPlayer.create(this, Uri.parse(mainStyle.getBackgroundAudioUrl())); audioPlayer.setLooping(true); audioPlayer.start(); }catch (Exception ex){ NextGenLogger.e(F.TAG, ex.getMessage()); } } } }else { setPlayExtraButtonsVisibility(ButtonsMode.TEXT_BUTTON_VISIBLE); } } public void onPause(){ super.onPause(); if (startupVideoView.isPlaying()){ startupVideoView.pause(); } if (audioPlayer != null){ audioPlayer.pause(); } } @Override public void onResume(){ super.onResume(); if (!startupVideoView.isPlaying() && startupVideoView.getVisibility() == View.VISIBLE){ startupVideoView.start(); } if (audioPlayer != null){ audioPlayer.start(); } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); arrangeLayoutAccordingToScreenOrientation(newConfig.orientation); } private void arrangeLayoutAccordingToScreenOrientation(final int orientation){ imageParentFrame.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { arrangeLayoutAccordingToScreenOrientation_priv(orientation); imageParentFrame.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); } private void arrangeLayoutAccordingToScreenOrientation_priv(int orientation){ ViewGroup.LayoutParams layoutParams = videoParentFrame.getLayoutParams(); FixedAspectRatioFrameLayout buttonsReferenceFrame; Size buttonsReferenceFrameSize; Size buttonsReferenceFrameSourceSize; StyleData.NodeStyleData nodeStyleData; boolean isPortrait = false; if (mainStyle == null) // if there's no main style, no calculations of button positions will be needed return; if (orientation == Configuration.ORIENTATION_PORTRAIT && !TabletUtils.isTablet()) { // handle portrait mode only when it's on phone isPortrait = true; buttonsReferenceFrameSize = new Size(imageParentFrame.getWidth(), imageParentFrame.getHeight()); buttonsReferenceFrame = imageParentFrame; buttonsReferenceFrameSourceSize = bgImageSize; nodeStyleData = mainStyle.getNodeStyleData(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); if (!StringHelper.isEmpty(mainStyle.getBackgroundVideoUrl())) { videoParentFrame.setAspectRatioPriority(FixedAspectRatioFrameLayout.Priority.WIDTH_PRIORITY); layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT; videoParentFrame.setLayoutParams(layoutParams); } else { } }else /*if (orientation == Configuration.ORIENTATION_LANDSCAPE)*/{ // for tablets and Landscape mode nodeStyleData = mainStyle.getNodeStyleData(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); if (!StringHelper.isEmpty(mainStyle.getBackgroundVideoUrl())) { Size videoSize = mainStyle.getBackgroundVideoSize(); Size screenSize = NextGenExperience.getScreenSize(NextGenExperience.getApplicationContext()); float videoAspectRatio = ((float) videoSize.getHeight()) /((float) videoSize.getWidth()); float screenAspectRatio = ((float) screenSize.getHeight()) /((float) screenSize.getWidth()); if (screenAspectRatio > 1) screenAspectRatio = 1/ screenAspectRatio; if (screenAspectRatio >= videoAspectRatio) { videoParentFrame.setAspectRatioPriority(FixedAspectRatioFrameLayout.Priority.HEIGHT_PRIORITY); layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT; } else { videoParentFrame.setAspectRatioPriority(FixedAspectRatioFrameLayout.Priority.WIDTH_PRIORITY); layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT; } videoParentFrame.setLayoutParams(layoutParams); buttonsReferenceFrameSize = new Size(videoParentFrame.getWidth(), videoParentFrame.getHeight()); buttonsReferenceFrame = videoParentFrame; buttonsReferenceFrameSourceSize = startupVideoSize; } else { buttonsReferenceFrameSize = new Size(imageParentFrame.getWidth(), imageParentFrame.getHeight()); buttonsReferenceFrame = imageParentFrame; buttonsReferenceFrameSourceSize = bgImageSize; } } if (nodeStyleData != null) { textButtonsFrame.setVisibility(View.GONE); StyleData.ThemeData buttonTheme = nodeStyleData.theme; BackgroundOverlayAreaType buttonLayoutArea = nodeStyleData.getBGOverlay(); if (!StringHelper.isEmpty(mainStyle.getBackgroundVideoUrl()) && startupVideoSize == null) return; double shrinkRatio = ((double) buttonsReferenceFrameSize.getWidth()) / ((double) buttonsReferenceFrameSourceSize.getWidth()); double buttonShrinkRation = shrinkRatio; buttonParentFrame.copyFrameParams(buttonsReferenceFrame); int width = (int) (((double) buttonLayoutArea.getWidthPixels().intValue()) * shrinkRatio); int screenWidth = NextGenExperience.getScreenWidth(this); if (width > screenWidth){ // if the specific area is wider than the screen, set the button area to be the screen width width = screenWidth - 20 ; // 20 being the padding on the size, 10 pixels each side buttonShrinkRation = ((double) width / ((double) buttonLayoutArea.getWidthPixels().intValue())); } int height = (int) (((double) buttonLayoutArea.getHeightPixels().intValue()) * buttonShrinkRation); int y = (int) (((double) buttonsReferenceFrameSourceSize.getHeight() - buttonLayoutArea.getPixelsFromBottom().intValue()) * shrinkRatio) - height; int x = (int) (((double) buttonLayoutArea.getPixelsFromLeft().intValue()) * shrinkRatio); if (isPortrait){ x = (buttonsReferenceFrameSize.getWidth() - width) / 2; } ViewGroup.LayoutParams buttonsLayoutParams = imageButtonsFrame.getLayoutParams(); if (buttonsLayoutParams instanceof LinearLayout.LayoutParams) { ((LinearLayout.LayoutParams) buttonsLayoutParams).setMargins(x, y, 0, 0); } else if (buttonsLayoutParams instanceof RelativeLayout.LayoutParams) { ((RelativeLayout.LayoutParams) buttonsLayoutParams).setMargins(x, y, 0, 0); } else if (buttonsLayoutParams instanceof FrameLayout.LayoutParams) { ((FrameLayout.LayoutParams) buttonsLayoutParams).setMargins(x, y, 0, 0); } buttonsLayoutParams.height = height; buttonsLayoutParams.width = width; imageButtonsFrame.setLayoutParams(buttonsLayoutParams); MovieMetaData.PictureImageData extraBtnImageData = buttonTheme.getImageData(StyleData.ThemeData.EXTRA_BUTTON); MovieMetaData.PictureImageData playBtnImageData = buttonTheme.getImageData(StyleData.ThemeData.PLAY_BUTTON); MovieMetaData.PictureImageData purchaseBtnImageData = buttonTheme.getImageData(StyleData.ThemeData.PURCHASE_BUTTON); if (extraBtnImageData != null && playBtnImageData != null) { double buttonRatio = (double) width / (double) playBtnImageData.width; ViewGroup.LayoutParams playBtnParams = null; if (playMovieButton != null) { playBtnParams = playMovieButton.getLayoutParams(); int newHeight = (int) ((double) playBtnImageData.height * buttonRatio); playBtnParams.height = newHeight; playMovieButton.setLayoutParams(playBtnParams); if (playBtnImageData != null) NextGenGlide.load(this, playBtnImageData.url).into(playMovieButton); } if (purchaseButton != null) { if (purchaseBtnImageData != null && playBtnParams != null) { //purchaseButton.setVisibility(View.VISIBLE); ViewGroup.LayoutParams buttonsParams = purchaseButton.getLayoutParams(); buttonsParams.height = playBtnParams.height; purchaseButton.setLayoutParams(buttonsParams); NextGenGlide.load(this, purchaseBtnImageData.url).into(purchaseButton); } else purchaseButton.setVisibility(View.GONE); } if (extraButton != null) { ViewGroup.LayoutParams buttonsParams = extraButton.getLayoutParams(); int newWidth = (int) ((double) extraBtnImageData.width * buttonRatio); int newHeight = (int) ((double) extraBtnImageData.height * buttonRatio); buttonsParams.height = newHeight; buttonsParams.width = newWidth; int extra_x, extra_y; extra_x = (buttonsLayoutParams.width - newWidth) / 2; //calculate extra Btn position if (purchaseBtnImageData != null) { extra_y = (buttonsLayoutParams.height - newHeight) / 2; } else { extra_y = buttonsLayoutParams.height - newHeight; } if (buttonsParams instanceof LinearLayout.LayoutParams) { ((LinearLayout.LayoutParams) buttonsParams).setMargins(extra_x, extra_y, 0, 0); } else if (buttonsParams instanceof RelativeLayout.LayoutParams) { ((RelativeLayout.LayoutParams) buttonsParams).setMargins(extra_x, extra_y, 0, 0); } else if (buttonsParams instanceof FrameLayout.LayoutParams) { ((FrameLayout.LayoutParams) buttonsParams).setMargins(extra_x, extra_y, 0, 0); } extraButton.setLayoutParams(buttonsParams); if (extraBtnImageData != null) NextGenGlide.load(this, extraBtnImageData.url).into(extraButton); } imageButtonsFrame.invalidate(); if (StringHelper.isEmpty(mainStyle.getBackgroundVideoUrl())) { imageButtonsFrame.setVisibility(View.VISIBLE); exitIcon.setVisibility(View.VISIBLE); } }else{ setPlayExtraButtonsVisibility(ButtonsMode.TEXT_BUTTON_VISIBLE); } return; } } @Override public void onClick(View v){ if (v.getId() == R.id.next_gen_startup_play_button || v.getId() == R.id.next_gen_startup_play_text_button) { Intent intent = new Intent(this, NextGenPlayer.class); intent.setDataAndType(Uri.parse(NextGenExperience.getMovieMetaData().getMainMovieUrl()), "video/*"); startActivity(intent); NextGenAnalyticData.reportEvent(this, null, NextGenAnalyticData.AnalyticAction.ACTION_PLAY_MOVIE, null, null); } else if (v.getId() == R.id.next_gen_startup_extra_button || v.getId() == R.id.next_gen_startup_extra_text_button) { Intent extraIntent = new Intent(this, NextGenExtraActivity.class); startActivity(extraIntent); NextGenAnalyticData.reportEvent(this, null, NextGenAnalyticData.AnalyticAction.ACTION_EXTRAS, null, null); } else if (v.getId() == R.id.next_gen_startup_purchase_button) { if (NextGenExperience.getNextGenEventHandler() != null) NextGenExperience.getNextGenEventHandler().handlePurchaseButtonPressed(this, NextGenExperience.getNextgenPlaybackObject()); NextGenAnalyticData.reportEvent(this, null, NextGenAnalyticData.AnalyticAction.ACTION_BUY, null, null); } else if (v.getId() == R.id.nge_main_exit){ NextGenAnalyticData.reportEvent(this, null, NextGenAnalyticData.AnalyticAction.ACTION_EXIT, null, null); finish(); } } static enum ButtonsMode{ TEXT_BUTTON_VISIBLE, IMAGE_BUTTON_VISIBLE, ALL_INVISIBLE; } private void setPlayExtraButtonsVisibility(ButtonsMode mode){ switch (mode){ case TEXT_BUTTON_VISIBLE: textButtonsFrame.setVisibility(View.VISIBLE); imageButtonsFrame.setVisibility(View.GONE); exitIcon.setVisibility(View.VISIBLE); break; case IMAGE_BUTTON_VISIBLE: imageButtonsFrame.setVisibility(View.VISIBLE); textButtonsFrame.setVisibility(View.GONE); exitIcon.setVisibility(View.VISIBLE); break; case ALL_INVISIBLE: default: imageButtonsFrame.setVisibility(View.GONE); textButtonsFrame.setVisibility(View.GONE); exitIcon.setVisibility(View.GONE); } } }
NGE-697: Android: Display Experience Exit button even if experience launch view / video doesn't load
src/com/wb/nextgenlibrary/activity/NextGenActivity.java
NGE-697: Android: Display Experience Exit button even if experience launch view / video doesn't load
<ide><path>rc/com/wb/nextgenlibrary/activity/NextGenActivity.java <ide> <ide> } <ide> <add> View.OnClickListener showButtonOnClickLister = new View.OnClickListener() { <add> @Override <add> public void onClick(View v) { <add> animateButtonsOn(); <add> } <add> }; <add> <add> if (startupVideoView != null){ <add> startupVideoView.setOnClickListener(showButtonOnClickLister); <add> } <add> <add> if (buttonParentFrame != null){ <add> buttonParentFrame.setOnClickListener(showButtonOnClickLister); <add> } <add> <ide> <ide> <ide> arrangeLayoutAccordingToScreenOrientation(getResources().getConfiguration().orientation); <ide> } <ide> }); <ide> startupVideoView.start(); <del> if (startUpTimer == null) { <del> startUpTimer = new Timer(); <del> } <del> if (startUpTimerTask == null) { <del> startUpTimerTask = new TimerTask() { <del> @Override <del> public void run() { <del> <del> runOnUiThread(new Runnable() { <del> @Override <del> public void run() { <del> StyleData.NodeStyleData nodeStyleData = mainStyle.getNodeStyleData(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); <del> StyleData.ThemeData buttonTheme = mainStyle.getNodeStyleData(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE).theme; <del> MovieMetaData.PictureImageData extraBtnImageData = buttonTheme.getImageData(StyleData.ThemeData.EXTRA_BUTTON); <del> MovieMetaData.PictureImageData playBtnImageData = buttonTheme.getImageData(StyleData.ThemeData.PLAY_BUTTON); <del> if (imageButtonsFrame != null && extraBtnImageData != null && playBtnImageData != null) { <del> setPlayExtraButtonsVisibility(ButtonsMode.IMAGE_BUTTON_VISIBLE); <del> imageButtonsFrame.setVisibility(View.VISIBLE); <del> imageButtonsFrame.setAlpha(0.0f); <del> <del> // Start the animation <del> imageButtonsFrame.animate().setDuration(1000).alpha(1.0f); <del> <del> } <del> if (exitIcon != null){ <del> exitIcon.setVisibility(View.GONE); <del> exitIcon.setVisibility(View.VISIBLE); <del> exitIcon.setAlpha(0.0f); <del> <del> // Start the animation <del> exitIcon.animate().setDuration(1000).alpha(1.0f); <del> } <del> <del> } <del> }); <del> } <del> }; <del> startUpTimer.schedule(startUpTimerTask, buttonAnimationStartTime); <del> } <del> <add> <add> animateButtonsOn(); <ide> //added: tr 9/19 <ide> mp.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() { <ide> @Override <ide> }else { <ide> setPlayExtraButtonsVisibility(ButtonsMode.TEXT_BUTTON_VISIBLE); <ide> } <add> } <add> <add> private void animateButtonsOn(){ <add> <add> if (startUpTimer == null) { <add> startUpTimer = new Timer(); <add> } <add> if (startUpTimerTask == null) { <add> startUpTimerTask = new TimerTask() { <add> @Override <add> public void run() { <add> <add> runOnUiThread(new Runnable() { <add> @Override <add> public void run() { <add> StyleData.NodeStyleData nodeStyleData = mainStyle.getNodeStyleData(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); <add> StyleData.ThemeData buttonTheme = mainStyle.getNodeStyleData(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE).theme; <add> MovieMetaData.PictureImageData extraBtnImageData = buttonTheme.getImageData(StyleData.ThemeData.EXTRA_BUTTON); <add> MovieMetaData.PictureImageData playBtnImageData = buttonTheme.getImageData(StyleData.ThemeData.PLAY_BUTTON); <add> if (imageButtonsFrame != null && extraBtnImageData != null && playBtnImageData != null) { <add> setPlayExtraButtonsVisibility(ButtonsMode.IMAGE_BUTTON_VISIBLE); <add> imageButtonsFrame.setVisibility(View.VISIBLE); <add> imageButtonsFrame.setAlpha(0.0f); <add> <add> // Start the animation <add> imageButtonsFrame.animate().setDuration(1000).alpha(1.0f); <add> <add> } <add> if (exitIcon != null){ <add> exitIcon.setVisibility(View.GONE); <add> exitIcon.setVisibility(View.VISIBLE); <add> exitIcon.setAlpha(0.0f); <add> <add> // Start the animation <add> exitIcon.animate().setDuration(1000).alpha(1.0f); <add> } <add> <add> } <add> }); <add> } <add> }; <add> startUpTimer.schedule(startUpTimerTask, buttonAnimationStartTime); <add> } <add> <add> <ide> } <ide> <ide> public void onPause(){
Java
apache-2.0
35705c844128c34766c1519bf97c983a6cd3099f
0
fkbyf14/installator,fkbyf14/installator
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package installator.stages.config; import installator.ConfigStage; import java.util.Enumeration; import javax.swing.AbstractButton; import javax.swing.JRadioButton; /** * * @author alina */ public class ChoicePanel extends javax.swing.JPanel implements StagePanel<Integer> { private ChoiceStage<Integer> stage; javax.swing.GroupLayout layout; private javax.swing.GroupLayout.SequentialGroup buttonHorizontalGroup; private javax.swing.GroupLayout.ParallelGroup radioHorizontalGroup; private javax.swing.GroupLayout.SequentialGroup allHorizontalGroup; private javax.swing.GroupLayout.ParallelGroup buttonVertcalGroup; private javax.swing.GroupLayout.SequentialGroup allVertcalGroup; private final int LEFT_BUTTON_GAP = 101; private final int WIDTH_BUTTON = 88; private final int HEIGHT_BUTTON = 25; private final JRadioButton[] radioButtons; //TODO // 1)сделать обработчик нажатия на кнопку, в котором вызвать метод //stage.setData(getData()); // 2)сделать метод setText который устанавливает переданный текст в метку /** * Creates new form ChoicePanel */ public ChoicePanel(ChoiceStage<Integer> stage, String name, String text, String[] radioButtonsText) { radioButtons = new JRadioButton[radioButtonsText.length]; myInit(radioButtonsText); setName(name); jLabel1.setText(text); // for (int i = 0; i < radioButtonText.length; i++) { // radioButtons[i]=new JRadioButton(); // radioButtons[i].setText(text); // buttonGroup1.add(radioButtons[i]); // } this.stage = stage; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel1; // End of variables declaration//GEN-END:variables @Override public Integer getData() { Enumeration<AbstractButton> en = buttonGroup1.getElements(); int i = 0; while (en.hasMoreElements()) { if (en.nextElement().isSelected()) { return new Integer(i); } i++; } return null; } private void fillButtonGroup() { buttonHorizontalGroup .addGap(0, LEFT_BUTTON_GAP, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, WIDTH_BUTTON, javax.swing.GroupLayout.PREFERRED_SIZE); buttonVertcalGroup .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE); } private void fillAllGroup() { AbstractButton radBut; radioHorizontalGroup .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, buttonHorizontalGroup); allVertcalGroup .addContainerGap() .addComponent(jLabel1); Enumeration<AbstractButton> en = buttonGroup1.getElements(); int i = 0; while (en.hasMoreElements()) { radBut = en.nextElement(); radioHorizontalGroup.addComponent(radBut, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE); allVertcalGroup .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(radBut); } allVertcalGroup .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 141, Short.MAX_VALUE) .addGroup(buttonVertcalGroup) .addContainerGap(); allHorizontalGroup .addContainerGap() .addGroup(radioHorizontalGroup) .addContainerGap(); } private void myInit(String[] radioButtonsText) { buttonGroup1 = new javax.swing.ButtonGroup(); for (int i = 0; i < radioButtonsText.length; i++) { radioButtons[i]=new JRadioButton(); radioButtons[i].setText(radioButtonsText[i]); buttonGroup1.add(radioButtons[i]); } jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton1.setText("Назад"); jButton1.setMaximumSize(new java.awt.Dimension(WIDTH_BUTTON, HEIGHT_BUTTON)); jButton1.setMinimumSize(new java.awt.Dimension(WIDTH_BUTTON, HEIGHT_BUTTON)); jButton1.setPreferredSize(new java.awt.Dimension(WIDTH_BUTTON, HEIGHT_BUTTON)); jButton2.setText("Далее"); jButton2.setMaximumSize(new java.awt.Dimension(WIDTH_BUTTON, HEIGHT_BUTTON)); jButton2.setMinimumSize(new java.awt.Dimension(WIDTH_BUTTON, HEIGHT_BUTTON)); jButton2.setPreferredSize(new java.awt.Dimension(WIDTH_BUTTON, HEIGHT_BUTTON)); jButton3.setText("Отмена"); jButton3.setMaximumSize(new java.awt.Dimension(WIDTH_BUTTON, HEIGHT_BUTTON)); jButton3.setMinimumSize(new java.awt.Dimension(WIDTH_BUTTON, HEIGHT_BUTTON)); jButton3.setPreferredSize(new java.awt.Dimension(WIDTH_BUTTON, HEIGHT_BUTTON)); layout = new javax.swing.GroupLayout(this); buttonHorizontalGroup = layout.createSequentialGroup(); radioHorizontalGroup = layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING); allHorizontalGroup = layout.createSequentialGroup(); buttonVertcalGroup = layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE); allVertcalGroup = layout.createSequentialGroup(); fillButtonGroup(); fillAllGroup(); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(allHorizontalGroup)); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(allVertcalGroup)); } }
src/installator/stages/config/ChoicePanel.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package installator.stages.config; import installator.ConfigStage; import java.util.Enumeration; import javax.swing.AbstractButton; import javax.swing.JRadioButton; /** * * @author alina */ public class ChoicePanel extends javax.swing.JPanel implements StagePanel<Integer> { private ChoiceStage<Integer> stage; javax.swing.GroupLayout layout; private javax.swing.GroupLayout.SequentialGroup buttonHorizontalGroup; private javax.swing.GroupLayout.ParallelGroup radioHorizontalGroup; private javax.swing.GroupLayout.SequentialGroup allHorizontalGroup; private javax.swing.GroupLayout.ParallelGroup buttonVertcalGroup; private javax.swing.GroupLayout.SequentialGroup allVertcalGroup; private final int LEFT_BUTTON_GAP = 101; private final int WIDTH_BUTTON = 88; private final int HEIGHT_BUTTON = 25; private final JRadioButton[] radioButtons; //TODO // 1)сделать обработчик нажатия на кнопку, в котором вызвать метод //stage.setData(getData()); // 2)сделать метод setText который устанавливает переданный текст в метку /** * Creates new form ChoicePanel */ public ChoicePanel(ChoiceStage<Integer> stage, String name, String text, String[] radioButtonText) { radioButtons = new JRadioButton[radioButtonText.length]; myInit(radioButtonText); setName(name); jLabel1.setText(text); for (int i = 0; i < radioButtonText.length; i++) { radioButtons[i]=new JRadioButton(); radioButtons[i].setText(text); buttonGroup1.add(radioButtons[i]); } this.stage = stage; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel1; // End of variables declaration//GEN-END:variables @Override public Integer getData() { Enumeration<AbstractButton> en = buttonGroup1.getElements(); int i = 0; while (en.hasMoreElements()) { if (en.nextElement().isSelected()) { return new Integer(i); } i++; } return null; } private void fillButtonGroup() { buttonHorizontalGroup .addGap(0, LEFT_BUTTON_GAP, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, WIDTH_BUTTON, javax.swing.GroupLayout.PREFERRED_SIZE); buttonVertcalGroup .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE); } private void fillAllGroup() { AbstractButton radBut; radioHorizontalGroup .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, buttonHorizontalGroup); allVertcalGroup .addContainerGap() .addComponent(jLabel1); Enumeration<AbstractButton> en = buttonGroup1.getElements(); int i = 0; while (en.hasMoreElements()) { radBut = en.nextElement(); radioHorizontalGroup.addComponent(radBut, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE); allVertcalGroup .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(radBut); } allVertcalGroup .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 141, Short.MAX_VALUE) .addGroup(buttonVertcalGroup) .addContainerGap(); allHorizontalGroup .addContainerGap() .addGroup(radioHorizontalGroup) .addContainerGap(); } private void myInit(String[] radioButtonsText) { buttonGroup1 = new javax.swing.ButtonGroup(); jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton1.setText("Назад"); jButton1.setMaximumSize(new java.awt.Dimension(WIDTH_BUTTON, HEIGHT_BUTTON)); jButton1.setMinimumSize(new java.awt.Dimension(WIDTH_BUTTON, HEIGHT_BUTTON)); jButton1.setPreferredSize(new java.awt.Dimension(WIDTH_BUTTON, HEIGHT_BUTTON)); jButton2.setText("Далее"); jButton2.setMaximumSize(new java.awt.Dimension(WIDTH_BUTTON, HEIGHT_BUTTON)); jButton2.setMinimumSize(new java.awt.Dimension(WIDTH_BUTTON, HEIGHT_BUTTON)); jButton2.setPreferredSize(new java.awt.Dimension(WIDTH_BUTTON, HEIGHT_BUTTON)); jButton3.setText("Отмена"); jButton3.setMaximumSize(new java.awt.Dimension(WIDTH_BUTTON, HEIGHT_BUTTON)); jButton3.setMinimumSize(new java.awt.Dimension(WIDTH_BUTTON, HEIGHT_BUTTON)); jButton3.setPreferredSize(new java.awt.Dimension(WIDTH_BUTTON, HEIGHT_BUTTON)); layout = new javax.swing.GroupLayout(this); buttonHorizontalGroup = layout.createSequentialGroup(); radioHorizontalGroup = layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING); allHorizontalGroup = layout.createSequentialGroup(); buttonVertcalGroup = layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE); allVertcalGroup = layout.createSequentialGroup(); fillButtonGroup(); fillAllGroup(); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(allHorizontalGroup)); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(allVertcalGroup)); } }
Цикл для радиобаттонов, всё работает)
src/installator/stages/config/ChoicePanel.java
Цикл для радиобаттонов, всё работает)
<ide><path>rc/installator/stages/config/ChoicePanel.java <ide> * Creates new form ChoicePanel <ide> */ <ide> public ChoicePanel(ChoiceStage<Integer> stage, String name, String text, <del> String[] radioButtonText) { <del> radioButtons = new JRadioButton[radioButtonText.length]; <del> myInit(radioButtonText); <add> String[] radioButtonsText) { <add> radioButtons = new JRadioButton[radioButtonsText.length]; <add> myInit(radioButtonsText); <ide> setName(name); <ide> jLabel1.setText(text); <del> for (int i = 0; i < radioButtonText.length; i++) { <del> radioButtons[i]=new JRadioButton(); <del> radioButtons[i].setText(text); <del> buttonGroup1.add(radioButtons[i]); <del> } <add>// for (int i = 0; i < radioButtonText.length; i++) { <add>// radioButtons[i]=new JRadioButton(); <add>// radioButtons[i].setText(text); <add>// buttonGroup1.add(radioButtons[i]); <add>// } <ide> <ide> this.stage = stage; <ide> } <ide> <ide> private void myInit(String[] radioButtonsText) { <ide> buttonGroup1 = new javax.swing.ButtonGroup(); <add> for (int i = 0; i < radioButtonsText.length; i++) { <add> radioButtons[i]=new JRadioButton(); <add> radioButtons[i].setText(radioButtonsText[i]); <add> buttonGroup1.add(radioButtons[i]); <add> } <ide> jLabel1 = new javax.swing.JLabel(); <ide> jButton1 = new javax.swing.JButton(); <ide> jButton2 = new javax.swing.JButton();
Java
apache-2.0
8eed23be0ebce2a60e5da46ebf495d01a8c4b9ee
0
OpenXIP/xip-host,OpenXIP/xip-host
/** * Copyright (c) 2008 Washington University in St. Louis. All Rights Reserved. */ package edu.wustl.xipHost.dataModel; import java.util.ArrayList; import java.util.List; import edu.wustl.xipHost.iterator.Criteria; /** * SearchResult is a data structure that holds results of a query. * Initially query result is received in a proprietary format and that is converted to SearchResult. * It is thought that SearchResult is gradually growing and new information is added to it. The SearchResult assembly reflects the concept of the progressive query. * Nodes are updated gradually depending on the JTree selection and SearchResult is updated as new subqueries result in nodes updates. * @author Jaroslaw Krych * */ public class SearchResult { String datasoureDescription; List<Patient> patients = new ArrayList<Patient>(); List<Item> items = new ArrayList<Item>(); Criteria originalCriteria; public SearchResult(){ } public SearchResult(String datasoureDescription){ this.datasoureDescription = datasoureDescription; } public String getDataSourceDescription(){ return new String(this.datasoureDescription); } public void setDataSourceDescription(String sourceDescription){ datasoureDescription = sourceDescription; } public String toString(){ return String.valueOf(patients.size()) + " patients and " + String.valueOf(items.size()) + " items."; } public void addPatient(Patient patient){ this.patients.add(patient); } public List<Patient> getPatients(){ return patients; } public boolean contains(String patientID){ for(int i = 0; i < patients.size(); i++){ if(patients.get(i).getPatientID().equalsIgnoreCase(patientID)){return true;} } return false; } public Patient getPatient(String patientId){ for(Patient patient : patients){ if(patient.getPatientID().equalsIgnoreCase(patientId)){ return patient; } } return null; } public void removePatient(Patient patient){ patients.remove(patient); } public void addItem(Item item){ this.items.add(item); } public List<Item> getItems(){ return items; } public boolean containsItem(String itemID){ for(int i = 0; i < items.size(); i++){ if(items.get(i).getItemID().equalsIgnoreCase(itemID)){return true;} } return false; } public Criteria getOriginalCriteria() { return originalCriteria; } public void setOriginalCriteria(Criteria originalCriteria) { this.originalCriteria = originalCriteria; } }
src/edu/wustl/xipHost/dataModel/SearchResult.java
/** * Copyright (c) 2008 Washington University in St. Louis. All Rights Reserved. */ package edu.wustl.xipHost.dataModel; import java.util.ArrayList; import java.util.List; import edu.wustl.xipHost.avt2ext.iterator.Criteria; /** * SearchResult is a data structure that holds results of a query. * Initially query result is received in a proprietary format and that is converted to SearchResult. * It is thought that SearchResult is gradually growing and new information is added to it. The SearchResult assembly reflects the concept of the progressive query. * Nodes are updated gradually depending on the JTree selection and SearchResult is updated as new subqueries result in nodes updates. * @author Jaroslaw Krych * */ public class SearchResult { String datasoureDescription; List<Patient> patients = new ArrayList<Patient>(); List<Item> items = new ArrayList<Item>(); Criteria originalCriteria; public SearchResult(){ } public SearchResult(String datasoureDescription){ this.datasoureDescription = datasoureDescription; } public String getDataSourceDescription(){ return new String(this.datasoureDescription); } public void setDataSourceDescription(String sourceDescription){ datasoureDescription = sourceDescription; } public String toString(){ return String.valueOf(patients.size()) + " patients and " + String.valueOf(items.size()) + " items."; } public void addPatient(Patient patient){ this.patients.add(patient); } public List<Patient> getPatients(){ return patients; } public boolean contains(String patientID){ for(int i = 0; i < patients.size(); i++){ if(patients.get(i).getPatientID().equalsIgnoreCase(patientID)){return true;} } return false; } public Patient getPatient(String patientId){ for(Patient patient : patients){ if(patient.getPatientID().equalsIgnoreCase(patientId)){ return patient; } } return null; } public void removePatient(Patient patient){ patients.remove(patient); } public void addItem(Item item){ this.items.add(item); } public List<Item> getItems(){ return items; } public boolean containsItem(String itemID){ for(int i = 0; i < items.size(); i++){ if(items.get(i).getItemID().equalsIgnoreCase(itemID)){return true;} } return false; } public Criteria getOriginalCriteria() { return originalCriteria; } public void setOriginalCriteria(Criteria originalCriteria) { this.originalCriteria = originalCriteria; } }
Changed referenced to the new iterator package. SVN-Revision: 702
src/edu/wustl/xipHost/dataModel/SearchResult.java
Changed referenced to the new iterator package.
<ide><path>rc/edu/wustl/xipHost/dataModel/SearchResult.java <ide> <ide> import java.util.ArrayList; <ide> import java.util.List; <del>import edu.wustl.xipHost.avt2ext.iterator.Criteria; <add>import edu.wustl.xipHost.iterator.Criteria; <ide> <ide> <ide> /**
Java
lgpl-2.1
15be775832624528ab544d914af952d64a869db2
0
concord-consortium/otrunk,concord-consortium/otrunk
/* * Copyright (C) 2004 The Concord Consortium, Inc., * 10 Concord Crossing, Concord, MA 01742 * * Web Site: http://www.concord.org * Email: [email protected] * * 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 * * END LICENSE */ /* * Last modification information: * $Revision: 1.92 $ * $Date: 2007-10-16 22:06:33 $ * $Author: scytacki $ * * Licence Information * Copyright 2004 The Concord Consortium */ package org.concord.otrunk.view; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Toolkit; import java.awt.event.AWTEventListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Hashtable; import java.util.Vector; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.border.EmptyBorder; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.TreePath; import org.concord.applesupport.AppleApplicationAdapter; import org.concord.applesupport.AppleApplicationUtil; import org.concord.framework.otrunk.OTChangeEvent; import org.concord.framework.otrunk.OTChangeListener; import org.concord.framework.otrunk.OTID; import org.concord.framework.otrunk.OTObject; import org.concord.framework.otrunk.OTObjectService; import org.concord.framework.otrunk.OTrunk; import org.concord.framework.otrunk.view.OTExternalAppService; import org.concord.framework.otrunk.view.OTFrameManager; import org.concord.framework.otrunk.view.OTJComponentServiceFactory; import org.concord.framework.otrunk.view.OTUserListService; import org.concord.framework.otrunk.view.OTViewContainer; import org.concord.framework.otrunk.view.OTViewContainerChangeEvent; import org.concord.framework.otrunk.view.OTViewContainerListener; import org.concord.framework.otrunk.view.OTViewContext; import org.concord.framework.otrunk.view.OTViewFactory; import org.concord.framework.text.UserMessageHandler; import org.concord.framework.util.SimpleTreeNode; import org.concord.otrunk.OTMLToXHTMLConverter; import org.concord.otrunk.OTObjectServiceImpl; import org.concord.otrunk.OTStateRoot; import org.concord.otrunk.OTSystem; import org.concord.otrunk.OTrunkImpl; import org.concord.otrunk.datamodel.OTDataObject; import org.concord.otrunk.datamodel.OTDatabase; import org.concord.otrunk.user.OTUserObject; import org.concord.otrunk.xml.ExporterJDOM; import org.concord.otrunk.xml.XMLDatabase; import org.concord.otrunk.xml.XMLDatabaseChangeEvent; import org.concord.otrunk.xml.XMLDatabaseChangeListener; import org.concord.swing.CustomDialog; import org.concord.swing.MemoryMonitorPanel; import org.concord.swing.MostRecentFileDialog; import org.concord.swing.StreamRecord; import org.concord.swing.StreamRecordView; import org.concord.swing.util.Util; import org.concord.view.SimpleTreeModel; import org.concord.view.SwingUserMessageHandler; /** * OTViewer Class name and description * * Date created: Dec 14, 2004 * * @author scott * <p> * */ public class OTViewer extends JFrame implements TreeSelectionListener, OTViewContainerListener, AppleApplicationAdapter { /** * first version of this class */ private static final long serialVersionUID = 1L; public final static String TITLE_PROP = "otrunk.view.frame_title"; public final static String HIDE_TREE_PROP = "otrunk.view.hide_tree"; public final static String SHOW_CONSOLE_PROP = "otrunk.view.show_console"; public final static String HTTP_PUT = "PUT"; public final static String HTTP_POST = "POST"; private static OTrunkImpl otrunk; private static OTViewFactory otViewFactory; protected int userMode = OTConfig.NO_USER_MODE; OTUserObject currentUser = null; URL currentURL = null; String baseFrameTitle = "OTrunk Viewer"; OTViewContainerPanel bodyPanel; OTFrameManagerImpl frameManager; JTree folderTreeArea; SimpleTreeModel folderTreeModel; JTree dataTreeArea; SimpleTreeModel dataTreeModel; JSplitPane splitPane; JFrame consoleFrame; // Temp, to close the window AbstractAction exitAction; AbstractAction saveAsAction; JMenuBar menuBar; XMLDatabase xmlDB; XMLDatabase userDataDB; File currentAuthoredFile = null; File currentUserFile = null; Hashtable otContainers = new Hashtable(); String startupMessage = ""; boolean justStarted = false; boolean showTree = false; URL remoteURL; private AbstractAction saveUserDataAsAction; private AbstractAction saveUserDataAction; private AbstractAction debugAction; private AbstractAction showConsoleAction; private AbstractAction newUserDataAction; private AbstractAction loadUserDataAction; private AbstractAction loadAction; private AbstractAction reloadWindowAction; private AbstractAction saveAction; private AbstractAction saveRemoteAsAction; private AbstractAction exportImageAction; private AbstractAction exportHiResImageAction; private AbstractAction exportToHtmlAction; private JDialog commDialog; /** * This is true if the user was asked about saving user data after they * initiated a close of the current view. */ private boolean askedAboutSavingUserData = false; /** * This is true if the user was asked about saving the user data, and said * yes */ private boolean needToSaveUserData = false; private boolean useScrollPane; private OTChangeListener systemChangeListener; private OTSystem userSystem; private ArrayList services = new ArrayList(); private JPanel statusPanel; public static class ServiceEntry { Object service; Class serviceInterface; public ServiceEntry(Object service, Class serviceInterface) { this.service = service; this.serviceInterface = serviceInterface; } } public static void setOTViewFactory(OTViewFactory factory) { otViewFactory = factory; } public OTViewer() { super(); this.showTree = true; AppleApplicationUtil.registerWithMacOSX(this); try { // this overrides the default base frame title String title = System.getProperty(TITLE_PROP, null); if (title != null) { baseFrameTitle = title; } } catch (Throwable t) { // do nothing, just use the default title } setTitle(baseFrameTitle); setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { exitAction.actionPerformed(null); } }); consoleFrame = new JFrame("Console"); StreamRecord record = new StreamRecord(10000); StreamRecordView view = new StreamRecordView(record); consoleFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); System.setOut((PrintStream) view.addOutputStream(System.out, "Console")); System.setErr((PrintStream) view.addOutputStream(System.err, System.out)); consoleFrame.getContentPane().add(view); consoleFrame.setSize(800, 600); if (OTConfig.getBooleanProp(SHOW_CONSOLE_PROP, false)) { consoleFrame.setVisible(true); } commDialog = new JDialog(this, true); // for debugging // add a breakpoint below, run in debugging mode, and then hit Meta-B // the object you're currently focused on will be passed in here and you // can // start exploring the data structures, etc. KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); KeyEventDispatcher deleteDispatcher = new KeyEventDispatcher(){ public boolean dispatchKeyEvent(KeyEvent e) { if ((e.getID() == java.awt.event.KeyEvent.KEY_RELEASED) && ((e.getModifiersEx() & java.awt.event.InputEvent.META_DOWN_MASK) != 0) && (e.getKeyCode() == java.awt.event.KeyEvent.VK_B)) { Object o = e.getSource(); System.out.println(o.toString()); return true; } return false; } }; focusManager.addKeyEventDispatcher(deleteDispatcher); // If the mouse click is a real right click event and alt is pressed // then this code will print // out the toString method of the object which the mouse is over. AWTEventListener awtEventListener = new AWTEventListener(){ public void eventDispatched(AWTEvent event) { if(!(event instanceof MouseEvent)){ return; } MouseEvent mEvent = (MouseEvent) event; if (mEvent.getID() == MouseEvent.MOUSE_CLICKED && (mEvent.getButton() == MouseEvent.BUTTON3) && (mEvent.getModifiersEx() & MouseEvent.ALT_DOWN_MASK) != 0) { System.out.println(event.getSource().toString()); } } }; Toolkit.getDefaultToolkit().addAWTEventListener(awtEventListener, AWTEvent.MOUSE_EVENT_MASK); } /** * this needs to be called before initialized. * * @param serviceInterface * @param service */ public void addService(Class serviceInterface, Object service) { ServiceEntry entry = new ServiceEntry(service, serviceInterface); services.add(entry); } public void setUserMode(int mode) { userMode = mode; } public int getUserMode() { return userMode; } public void updateTreePane() { Dimension minimumSize = new Dimension(100, 50); folderTreeArea = new JTree(folderTreeModel); // we are just disabling this however if we want to // use this tree for authoring, or for managing student // created objects this will need to be some form of option folderTreeArea.setEditable(false); folderTreeArea.addTreeSelectionListener(this); JComponent leftComponent = null; JScrollPane folderTreeScrollPane = new JScrollPane(folderTreeArea); if (System.getProperty(OTConfig.DEBUG_PROP, "").equals("true")) { // ViewFactory.getComponent(root); dataTreeArea = new JTree(dataTreeModel); dataTreeArea.setEditable(false); dataTreeArea.addTreeSelectionListener(this); JScrollPane dataTreeScrollPane = new JScrollPane(dataTreeArea); JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.add("Folders", folderTreeScrollPane); tabbedPane.add("Resources", dataTreeScrollPane); // Provide minimum sizes for the two components in the split pane folderTreeScrollPane.setMinimumSize(minimumSize); dataTreeScrollPane.setMinimumSize(minimumSize); tabbedPane.setMinimumSize(minimumSize); leftComponent = tabbedPane; } else { leftComponent = folderTreeScrollPane; } if (splitPane == null) { splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftComponent, bodyPanel); } else { splitPane.setLeftComponent(leftComponent); } splitPane.setOneTouchExpandable(true); splitPane.setDividerLocation(200); } public void initArgs(String[] args) { URL authorOTMLURL = OTViewerHelper.getURLFromArgs(args); if ("file".equalsIgnoreCase(authorOTMLURL.getProtocol())) { currentAuthoredFile = new File(authorOTMLURL.getPath()); } String urlStr = authorOTMLURL.toString(); initWithWizard(urlStr); } /** * @param args * @return */ public String getURL(String[] args) { URL authorOTMLURL = OTViewerHelper.getURLFromArgs(args); if ("file".equalsIgnoreCase(authorOTMLURL.getProtocol())) { try { URI authorOTMLURI = new URI(authorOTMLURL.toString()); currentAuthoredFile = new File(authorOTMLURI); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return authorOTMLURL.toString(); } public void init(String url) { updateRemoteURL(url); createActions(); updateMenuBar(); setJMenuBar(menuBar); frameManager = new OTFrameManagerImpl(); bodyPanel = new OTViewContainerPanel(frameManager); bodyPanel.addViewContainerListener(this); if (showTree) { dataTreeModel = new SimpleTreeModel(); folderTreeModel = new SimpleTreeModel(); updateTreePane(); getContentPane().add(splitPane); } else { getContentPane().add(bodyPanel); } if (OTConfig.isShowStatus()) { statusPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING, 3, 1)); final JLabel saveStateLabel = new JLabel("File saved"); statusPanel.add(saveStateLabel); statusPanel.add(Box.createHorizontalStrut(20)); statusPanel.add(new MemoryMonitorPanel()); statusPanel.add(Box.createHorizontalStrut(5)); getContentPane().add(statusPanel, BorderLayout.SOUTH); // It takes a while for xmlDM to be initialized... Thread waitForDB = new Thread() { public void run() { while (xmlDB == null) { try { sleep(1000); } catch (Exception e) { } } xmlDB.addXMLDatabaseChangeListener(new XMLDatabaseChangeListener() { public void stateChanged(XMLDatabaseChangeEvent e) { if (xmlDB.isDirty()) { saveStateLabel.setText("Unsaved changes"); } else { saveStateLabel.setText("File saved"); } statusPanel.repaint(); } }); } }; waitForDB.start(); } SwingUtilities.invokeLater(new Runnable() { public void run() { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); if (screenSize.width < 1000 || screenSize.height < 700) { setVisible(true); int state = getExtendedState(); // Set the maximized bits state |= Frame.MAXIMIZED_BOTH; // Maximize the frame setExtendedState(state); } else { int cornerX = 100; int cornerY = 100; int sizeX = 725; int sizeY = 500; // OTViewService viewService = otViewFactory. setBounds(cornerX, cornerY, cornerX + sizeX, cornerY + sizeY); setVisible(true); } } }); if (url == null) { return; } try { initializeURL(new URL(url)); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (Exception e) { // FIXME: this should popup a dialog System.err.println("Can't load url"); e.printStackTrace(); return; } } public void initializeURL(URL url) throws Exception { loadURL(url); OTMainFrame mainFrame = (OTMainFrame) otrunk.getService(OTMainFrame.class); if (OTConfig.getBooleanProp(HIDE_TREE_PROP, false) || !mainFrame.getShowLeftPanel()) { splitPane.getLeftComponent().setVisible(false); } useScrollPane = true; if (mainFrame.getFrame() != null) { if (mainFrame.getFrame().isResourceSet("width") && mainFrame.getFrame().isResourceSet("height")) { int cornerX = 100; int cornerY = 100; int sizeX = mainFrame.getFrame().getWidth(); int sizeY = mainFrame.getFrame().getHeight(); setBounds(cornerX, cornerY, cornerX + sizeX, cornerY + sizeY); repaint(); } useScrollPane = mainFrame.getFrame().getUseScrollPane(); } bodyPanel.setUseScrollPane(useScrollPane); setupBodyPanel(); } public void initWithWizard(String url) { justStarted = true; init(url); if (userMode == OTConfig.SINGLE_USER_MODE) { SwingUtilities.invokeLater(new Runnable() { public void run() { instructionPanel(); } }); } } public void loadUserDataFile(File file) { currentUserFile = file; try { loadUserDataURL(file.toURL(), file.getName()); } catch (Exception e) { e.printStackTrace(); } } public void loadUserDataURL(URL url, String name) throws Exception { XMLDatabase db = new XMLDatabase(url); db.loadObjects(); loadUserDataDb(db, name); } public void loadUserDataDb(XMLDatabase db, String name) throws Exception { userDataDB = db; currentUser = otrunk.registerUserDataDatabase(userDataDB, name); reloadWindow(); } public void reloadOverlays() { try { otrunk.reloadOverlays(currentUser, userDataDB); reloadWindow(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void loadFile(File file) { currentAuthoredFile = file; try { initializeURL(currentAuthoredFile.toURL()); } catch (Exception e) { e.printStackTrace(); } } public void loadURL(URL url) throws Exception { XMLDatabase systemDB = null; try { // try loading in the system object if there is one String systemOtmlUrlStr = OTConfig.getStringProp(OTConfig.SYSTEM_OTML_PROP); if(systemOtmlUrlStr != null){ URL systemOtmlUrl = new URL(systemOtmlUrlStr); systemDB = new XMLDatabase(systemOtmlUrl, System.out); // don't track the resource info on the system db. systemDB.loadObjects(); } } catch (Exception e){ e.printStackTrace(); systemDB = null; } try { xmlDB = new XMLDatabase(url, System.out); // Only track the resource info when there isn't a user. Currently // all classroom uses // of OTViewer has NO_USER_MODE turned off, so using this setting // safe to test // the resource tracking without affecting real users. if (userMode == OTConfig.NO_USER_MODE) { xmlDB.setTrackResourceInfo(true); } xmlDB.loadObjects(); } catch (org.jdom.input.JDOMParseException e) { String xmlWarningTitle = "XML Decoding error"; String xmlWarningMessage = "There appears to a problem parsing the XML of this document. \n" + "Please show this error message to one of the workshop leaders. \n\n" + e.getMessage(); JOptionPane.showMessageDialog(null, xmlWarningMessage, xmlWarningTitle, JOptionPane.ERROR_MESSAGE); throw e; } int servicesSize = services.size(); int numDefaultServices = 1; Object [] serviceArray = new Object[servicesSize + numDefaultServices]; serviceArray[0] = new SwingUserMessageHandler(this); Class [] serviceInterfaces = new Class[servicesSize + numDefaultServices]; serviceInterfaces[0] = UserMessageHandler.class; for(int i=0; i<services.size(); i++){ ServiceEntry entry = (ServiceEntry) services.get(i); serviceArray[i+numDefaultServices] = entry.service; serviceInterfaces[i+numDefaultServices] = entry.serviceInterface; } otrunk = new OTrunkImpl(systemDB, xmlDB, serviceArray, serviceInterfaces); OTViewFactory myViewFactory = (OTViewFactory) otrunk.getService(OTViewFactory.class); if (myViewFactory != null) { otViewFactory = myViewFactory; } OTViewContext factoryContext = otViewFactory.getViewContext(); factoryContext.addViewService(OTrunk.class, otrunk); factoryContext.addViewService(OTFrameManager.class, frameManager); factoryContext.addViewService(OTJComponentServiceFactory.class, new OTJComponentServiceFactoryImpl()); factoryContext.addViewService(OTExternalAppService.class, new OTExternalAppServiceImpl()); factoryContext.addViewService(OTUserListService.class, new OTUserListService() { public Vector getUserList() { return otrunk.getUsers(); } }); currentURL = url; } // This method was refactored out of loadURL private void setupBodyPanel() throws Exception { bodyPanel.setTopLevelContainer(true); bodyPanel.setOTViewFactory(otViewFactory); // set the current mode from the viewservice to the main bodyPanel // bodyPanel.setViewMode(otViewFactory.getDefaultMode()); // set the viewFactory of the frame manager frameManager.setViewFactory(otViewFactory); xmlDB.setDirty(false); reloadWindow(); } public OTObject getAuthoredRoot() throws Exception { String rootLocalId = OTConfig.getStringProp(OTConfig.ROOT_OBJECT_PROP); if(rootLocalId != null){ OTID rootID = xmlDB.getOTIDFromLocalID(rootLocalId); return otrunk.getOTObject(rootID); } return otrunk.getRoot(); } public OTObject getRoot() throws Exception { switch (userMode) { case OTConfig.NO_USER_MODE: return getAuthoredRoot(); case OTConfig.SINGLE_USER_MODE: if (userDataDB == null) { return null; } OTObject otRoot = getAuthoredRoot(); return otrunk.getUserRuntimeObject(otRoot, currentUser); } return null; } private void reloadWindow() throws Exception { OTObject root = getRoot(); boolean overrideShowTree = false; if (userMode == OTConfig.SINGLE_USER_MODE) { if (root == null) { // FIXME This is an error // the newAnonUserData should have been called before this // method is // called // no user file has been started yet overrideShowTree = true; } else { OTObject realRoot = otrunk.getRealRoot(); if (realRoot instanceof OTSystem) { OTSystem localUserSystem = (OTSystem) otrunk.getUserRuntimeObject(realRoot, currentUser); // FIXME there should be a better way than this because we // have to handle // multiple users. if (localUserSystem != userSystem) { userSystem = localUserSystem; systemChangeListener = new OTChangeListener() { public void stateChanged(OTChangeEvent e) { if ("overlays".equals(e.getProperty())) { reloadOverlays(); } } }; userSystem.addOTChangeListener(systemChangeListener); } } } } if (showTree && !overrideShowTree) { OTDataObject rootDataObject = xmlDB.getRoot(); dataTreeModel.setRoot(new OTDataObjectNode("root", rootDataObject, otrunk)); folderTreeModel.setRoot(new OTFolderNode(root)); } bodyPanel.setCurrentObject(root); if (showTree && !overrideShowTree) { folderTreeModel.fireTreeStructureChanged(new TreePath( (SimpleTreeNode) folderTreeModel.getRoot())); dataTreeModel.fireTreeStructureChanged(new TreePath( (SimpleTreeNode) dataTreeModel.getRoot())); } Frame frame = (Frame) SwingUtilities.getRoot(this); switch (userMode) { case OTConfig.NO_USER_MODE: if (remoteURL != null) { frame.setTitle(baseFrameTitle + ": " + remoteURL.toString()); } else { frame.setTitle(baseFrameTitle + ": " + currentURL.toString()); } break; case OTConfig.SINGLE_USER_MODE: if (currentUserFile != null) { frame.setTitle(baseFrameTitle + ": " + currentUserFile.toString()); } else if (System.getProperty(TITLE_PROP, null) != null) { frame.setTitle(baseFrameTitle); } else if (userDataDB != null) { frame.setTitle(baseFrameTitle + ": Untitled"); } else { frame.setTitle(baseFrameTitle); } break; } saveUserDataAction.setEnabled(userDataDB != null); saveUserDataAsAction.setEnabled(userDataDB != null); } public void reload() throws Exception { initializeURL(currentURL); } public OTDatabase getUserDataDb() { return userDataDB; } /** * You should call reloadWindow after calling this method to make sure the * display reflects this change * * @param userObject */ public void setCurrentUser(OTUserObject userObject) { currentUser = userObject; } public static void main(String[] args) { System.setProperty("apple.laf.useScreenMenuBar", "true"); OTViewer viewer = new OTViewer(); if (OTConfig.getBooleanProp(OTConfig.SINGLE_USER_PROP, false)) { viewer.setUserMode(OTConfig.SINGLE_USER_MODE); } else if (OTConfig.getBooleanProp(OTConfig.NO_USER_PROP, false)) { viewer.setUserMode(OTConfig.NO_USER_MODE); } viewer.initArgs(args); } class ExitAction extends AbstractAction { /** * nothing to serialize here. */ private static final long serialVersionUID = 1L; public ExitAction() { super("Exit"); } public void actionPerformed(ActionEvent e) { // If this suceeds then the VM will exit so // the window will get disposed exit(); } } /* * (non-Javadoc) * * @see org.concord.otrunk.view.OTViewContainerListener#currentObjectChanged(org.concord.framework.otrunk.view.OTViewContainer) */ public void currentObjectChanged(OTViewContainerChangeEvent evt) { final OTViewContainer myContainer = (OTViewContainer) evt.getSource(); // TODO Auto-generated method stub SwingUtilities.invokeLater(new Runnable() { public void run() { OTObject currentObject = myContainer.getCurrentObject(); if (folderTreeArea != null) { OTFolderNode node = (OTFolderNode) folderTreeArea.getLastSelectedPathComponent(); if (node == null) return; if (node.getPfObject() != currentObject) { folderTreeArea.setSelectionPath(null); } } } }); } /* * (non-Javadoc) * * @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent) */ public void valueChanged(TreeSelectionEvent event) { if (event.getSource() == folderTreeArea) { OTFolderNode node = (OTFolderNode) folderTreeArea.getLastSelectedPathComponent(); if (node == null) return; OTObject pfObject = node.getPfObject(); bodyPanel.setCurrentObject(pfObject); if (splitPane.getRightComponent() != bodyPanel) { splitPane.setRightComponent(bodyPanel); } } else if (event.getSource() == dataTreeArea) { SimpleTreeNode node = (SimpleTreeNode) dataTreeArea.getLastSelectedPathComponent(); Object resourceValue = null; if (node != null) { resourceValue = node.getObject(); if (resourceValue == null) { resourceValue = "null resource value"; } } else { resourceValue = "no selected data object"; } JComponent nodeView = null; if (resourceValue instanceof OTDataObject) { nodeView = new OTDataObjectView((OTDataObject) resourceValue); } else { nodeView = new JTextArea(resourceValue.toString()); } JScrollPane scrollPane = new JScrollPane(nodeView); splitPane.setRightComponent(scrollPane); } } private void updateRemoteURL(String defaultURL) { String remote = System.getProperty(OTConfig.REMOTE_URL_PROP, null); try { if (remote == null) { if (defaultURL.startsWith("http:")) { remoteURL = new URL(defaultURL); } } else { remoteURL = new URL(remote); } } catch (Exception e) { remoteURL = null; System.err.println("Remote URL is invalid."); e.printStackTrace(); } } public void remoteSaveData(String method) throws Exception { HttpURLConnection urlConn; DataOutputStream urlDataOut; BufferedReader urlDataIn; // If method isn't "POST" or "PUT", throw an exception if (!(method.compareTo(OTViewer.HTTP_POST) == 0 || method.compareTo(OTViewer.HTTP_PUT) == 0)) { throw new Exception("Invalid HTTP Request method for data saving"); } urlConn = (HttpURLConnection) remoteURL.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestMethod(method); urlConn.setRequestProperty("Content-Type", "application/xml"); // Send POST output. urlDataOut = new DataOutputStream(urlConn.getOutputStream()); ExporterJDOM.export(urlDataOut, xmlDB.getRoot(), xmlDB); urlDataOut.flush(); urlDataOut.close(); // Get response data. urlDataIn = new BufferedReader(new InputStreamReader(new DataInputStream( urlConn.getInputStream()))); String str; String response = ""; while (null != ((str = urlDataIn.readLine()))) { response += str + "\n"; } urlDataIn.close(); // Need to trap non-HTTP 200/300 responses and throw an exception (if an // exception isn't thrown already) and capture the exceptions upstream int code = urlConn.getResponseCode(); if (code >= 400) { throw new Exception("HTTP Response: " + urlConn.getResponseMessage() + "\n\n" + response); } urlConn.disconnect(); xmlDB.setDirty(false); setTitle(remoteURL.toString()); } public void createActions() { newUserDataAction = new AbstractAction("New") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { createNewUser(); } }; loadUserDataAction = new AbstractAction("Open...") { /** * nothing to serialize here. Just the parent class. */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { openUserData(); } }; exportToHtmlAction = new AbstractAction("Export to html...") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent arg0) { File fileToSave = getReportFile(); OTMLToXHTMLConverter otxc = new OTMLToXHTMLConverter(otViewFactory, bodyPanel.getViewContainer()); otxc.setXHTMLParams(fileToSave, 800, 600); (new Thread(otxc)).start(); } }; // Isn't it enabled by default? exportToHtmlAction.setEnabled(true); saveUserDataAction = new AbstractAction("Save") { /** * Nothing to serialize here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { System.out.println("saving"); if (currentUserFile == null || !currentUserFile.exists()) { System.out.println("saving as"); saveUserDataAsAction.actionPerformed(arg0); return; } if (currentUserFile.exists()) { System.out.println(" file exists"); System.out.println(" "+currentUserFile); try { ExporterJDOM.export(currentUserFile, userDataDB.getRoot(), userDataDB); userDataDB.setDirty(false); } catch (Exception e) { e.printStackTrace(); } } System.out.println("finished saving"); } }; saveUserDataAsAction = new AbstractAction("Save As...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.saveotml"); mrfd.setFilenameFilter("otml"); if (currentUserFile != null) { mrfd.setCurrentDirectory(currentUserFile.getParentFile()); mrfd.setSelectedFile(currentUserFile); } int retval = mrfd.showSaveDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); String fileName = file.getPath(); currentUserFile = file; if (!fileName.toLowerCase().endsWith(".otml")) { currentUserFile = new File(currentUserFile.getAbsolutePath() + ".otml"); } try { ExporterJDOM.export(currentUserFile, userDataDB.getRoot(), userDataDB); userDataDB.setDirty(false); setTitle(baseFrameTitle + ": " + currentUserFile.toString()); } catch (Exception e) { e.printStackTrace(); } frame.setTitle(fileName); } } }; loadAction = new AbstractAction("Open Authored Content...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.openotml"); mrfd.setFilenameFilter("otml"); int retval = mrfd.showOpenDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); } if (file != null && file.exists()) { System.out.println("load file name: " + file); // if they open an authored file then they are overriding // the remoteURL, // at least for now. This makes the title bar update // correctly, and // fixes a lockup that happens when they have opened a local // file and then // try to save it again. remoteURL = null; loadFile(file); exportToHtmlAction.setEnabled(true); } } }; loadAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); saveAction = new AbstractAction("Save Authored Content...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { System.out.println("trying to save authored content"); if (remoteURL != null) { System.out.println(" remote url = "+remoteURL); try { if (OTConfig.isRestEnabled()) { System.out.println(" is rest enabled"); try { remoteSaveData(OTViewer.HTTP_PUT); } catch (Exception e) { remoteSaveData(OTViewer.HTTP_POST); } } else { System.out.println(" not rest enabled, posting"); remoteSaveData(OTViewer.HTTP_POST); } } catch (Exception e) { System.out.println(" caught"); JOptionPane.showMessageDialog( (Frame) SwingUtilities.getRoot(OTViewer.this), "There was an error saving. Check your URL and try again.", "Error Saving", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } else { System.out.println(" no remote url"); if (currentAuthoredFile == null) { System.out.println(" currentAuthoredFile = null"); saveAsAction.actionPerformed(arg0); return; } if (checkForReplace(currentAuthoredFile)) { System.out.println(" check for replace"); try { System.out.println(" exporting"); ExporterJDOM.export(currentAuthoredFile, xmlDB.getRoot(), xmlDB); xmlDB.setDirty(false); } catch (Exception e) { System.out.println(" caught export exception"); e.printStackTrace(); } } } // end if (remoteUrl == null) } }; saveAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); saveAsAction = new AbstractAction("Save Authored Content As...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.saveotml"); mrfd.setFilenameFilter("otml"); if (currentAuthoredFile != null) { mrfd.setCurrentDirectory(currentAuthoredFile.getParentFile()); mrfd.setSelectedFile(currentAuthoredFile); } int retval = mrfd.showSaveDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); String fileName = file.getPath(); if (!fileName.toLowerCase().endsWith(".otml")) { file = new File(file.getAbsolutePath() + ".otml"); } if (checkForReplace(file)) { try { ExporterJDOM.export(file, xmlDB.getRoot(), xmlDB); currentAuthoredFile = file; currentURL = file.toURL(); xmlDB.setDirty(false); } catch (Exception e) { e.printStackTrace(); } } frame.setTitle(fileName); remoteURL = null; updateMenuBar(); } } }; saveRemoteAsAction = new AbstractAction("Save Remotely As...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { // Pop up a dialog asking for a URL // Post the otml to the url JPanel panel = new JPanel(); panel.setBorder(new EmptyBorder(10, 10, 10, 10)); panel.setLayout(new BorderLayout()); JLabel prompt = new JLabel("Please enter the URL to which you would like to save:"); prompt.setBorder(new EmptyBorder(0, 0, 10, 0)); JTextField textField = new JTextField(); if (remoteURL == null) { textField.setText("http://"); } else { textField.setText(remoteURL.toString()); } JPanel checkboxPanel = new JPanel(); JCheckBox restCheckbox = new JCheckBox("REST Enabled?"); restCheckbox.setSelected(OTConfig.isRestEnabled()); checkboxPanel.setBorder(new EmptyBorder(5, 5, 0, 0)); checkboxPanel.add(restCheckbox); panel.add(prompt, BorderLayout.NORTH); panel.add(textField, BorderLayout.CENTER); panel.add(checkboxPanel, BorderLayout.SOUTH); int returnVal = CustomDialog.showOKCancelDialog( (Frame) SwingUtilities.getRoot(OTViewer.this), // parent panel, // custom content "Save URL", // title false, // resizeable true // modal ); if (returnVal == 0) { try { remoteURL = new URL(textField.getText()); // WARNING this will cause a security exception if we // are running in a applet or jnlp which // has a security sandbox. System.setProperty(OTConfig.REST_ENABLED_PROP, Boolean.toString(restCheckbox.isSelected())); remoteSaveData(OTViewer.HTTP_POST); updateMenuBar(); } catch (Exception e) { System.err.println("Bad URL. Not saving."); JOptionPane.showMessageDialog( (Frame) SwingUtilities.getRoot(OTViewer.this), "There was an error saving. Check your URL and try again.", "Error Saving", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } else { // CANCELLED } } }; exportImageAction = new AbstractAction("Export Image...") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { // this introduces a dependency on concord Swing project // instead there needs to be a way to added these actions // through // the xml Component currentComp = bodyPanel.getCurrentComponent(); Util.makeScreenShot(currentComp); } }; exportHiResImageAction = new AbstractAction("Export Hi Res Image...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { Component currentComp = bodyPanel.getCurrentComponent(); Util.makeScreenShot(currentComp, 2, 2); } }; debugAction = new AbstractAction("Debug Mode") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (((JCheckBoxMenuItem) source).isSelected()) { System.setProperty(OTConfig.DEBUG_PROP, "true"); } else { System.setProperty(OTConfig.DEBUG_PROP, "false"); } try { reloadWindow(); } catch (Exception exp) { exp.printStackTrace(); } SwingUtilities.invokeLater(new Runnable() { public void run() { updateMenuBar(); } }); exportToHtmlAction.setEnabled(true); } }; showConsoleAction = new AbstractAction("Show Console") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { if (consoleFrame != null) { consoleFrame.setVisible(true); } } }; reloadWindowAction = new AbstractAction("Reload window") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { try { reload(); } catch (Exception e1) { e1.printStackTrace(); } } }; exitAction = new ExitAction(); } /** * @return Returns the menuBar. */ public JMenuBar updateMenuBar() { // /////////////////////////////////////////////// JMenu fileMenu = null; if (menuBar == null) { menuBar = new JMenuBar(); fileMenu = new JMenu("File"); menuBar.add(fileMenu); } else { fileMenu = menuBar.getMenu(0); fileMenu.removeAll(); } if (OTConfig.isAuthorMode()) { userMode = OTConfig.NO_USER_MODE; } if (userMode == OTConfig.SINGLE_USER_MODE) { fileMenu.setEnabled(!justStarted); fileMenu.add(newUserDataAction); fileMenu.add(loadUserDataAction); fileMenu.add(saveUserDataAction); fileMenu.add(saveUserDataAsAction); } if (OTConfig.isDebug()) { if (userMode == OTConfig.SINGLE_USER_MODE) { loadAction.putValue(Action.NAME, "Open Authored Content..."); saveAction.putValue(Action.NAME, "Save Authored Content"); saveAsAction.putValue(Action.NAME, "Save Authored Content As..."); saveRemoteAsAction.putValue(Action.NAME, "Save Authored Content Remotely As..."); } else { loadAction.putValue(Action.NAME, "Open..."); saveAction.putValue(Action.NAME, "Save"); saveAsAction.putValue(Action.NAME, "Save As..."); saveRemoteAsAction.putValue(Action.NAME, "Save Remotely As..."); } fileMenu.add(loadAction); fileMenu.add(saveAction); fileMenu.add(saveAsAction); fileMenu.add(saveRemoteAsAction); } if (OTConfig.isAuthorMode() && !OTConfig.isDebug()) { if (userMode == OTConfig.SINGLE_USER_MODE) { loadAction.putValue(Action.NAME, "Open Authored Content..."); saveAction.putValue(Action.NAME, "Save Authored Content"); saveAsAction.putValue(Action.NAME, "Save Authored Content As..."); } else { loadAction.putValue(Action.NAME, "Open..."); saveAction.putValue(Action.NAME, "Save"); saveAsAction.putValue(Action.NAME, "Save As..."); } fileMenu.add(loadAction); fileMenu.add(saveAction); fileMenu.add(saveAsAction); } if (OTConfig.getBooleanProp("otrunk.view.export_image", false)) { fileMenu.add(exportImageAction); fileMenu.add(exportHiResImageAction); } fileMenu.add(exportToHtmlAction); fileMenu.add(showConsoleAction); if (OTConfig.isAuthorMode() || OTConfig.isDebug()) { fileMenu.add(reloadWindowAction); } JCheckBoxMenuItem debugItem = new JCheckBoxMenuItem(debugAction); debugItem.setSelected(OTConfig.isDebug()); fileMenu.add(debugItem); fileMenu.add(exitAction); return menuBar; } boolean checkForReplace(File file) { if (file == null){ return false; } if (!file.exists()) { return true; // File doesn't exist, so go ahead and save } if (currentAuthoredFile != null && file.compareTo(currentAuthoredFile) == 0){ return true; // we're already authoring this file, so no need to // prompt } final Object[] options = { "Yes", "No" }; return javax.swing.JOptionPane.showOptionDialog(null, "The file '" + file.getName() + "' already exists. " + "Replace existing file?", "Warning", javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, options, options[1]) == javax.swing.JOptionPane.YES_OPTION; } /** * Checks if the user has unsaved work. If they do then it prompts them to * confirm what they are doing. If they cancel then it returns false. * * @return */ public boolean checkForUnsavedUserData() { if (currentUser != null && userDataDB != null) { if (userDataDB.isDirty()) { // show dialog message telling them they haven't // saved their work // FIXME String options[] = { "Don't Save", "Cancel", "Save" }; askedAboutSavingUserData = true; int chosenOption = JOptionPane.showOptionDialog(this, "Save Changes?", "Save Changes?", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[2]); switch (chosenOption) { case 0: System.err.println("Not saving work"); break; case 1: System.err.println("Canceling close"); return false; case 2: System.err.println("Set needToSaveUserData true"); needToSaveUserData = true; break; } } } return true; } /** * Checks if the user has unsaved authored data. If they do then it prompts * them to confirm what they are doing. If they cancel then it returns * false. * * @return */ public boolean checkForUnsavedAuthorData() { if (xmlDB != null) { if (xmlDB.isDirty()) { // show dialog message telling them they haven't // saved their work // FIXME String options[] = { "Don't Save", "Cancel", "Save" }; int chosenOption = JOptionPane.showOptionDialog(this, "Save Changes?", "Save Changes?", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[2]); switch (chosenOption) { case 0: System.err.println("Not saving authored data"); break; case 1: System.err.println("Canceling close"); return false; case 2: System.err.println("Saving authored data"); saveAction.actionPerformed(null); break; } } } return true; } /** * This does not check for unsaved user data * */ public void newAnonUserData() { // call some new method for creating a new un-saved user state // this should set the currentUserFile to null, so the save check // prompts // for a file name try { // need to make a brand new stateDB userDataDB = new XMLDatabase(); // System.out.println("otrunk: " + otrunk + " userDatabase: " + // userDataDB); OTObjectService objService = otrunk.createObjectService(userDataDB); OTStateRoot stateRoot = (OTStateRoot) objService.createObject(OTStateRoot.class); userDataDB.setRoot(stateRoot.getGlobalId()); stateRoot.setFormatVersionString("1.0"); OTUserObject userObject = OTViewerHelper.createUser("anon_single_user", objService); otrunk.initUserObjectService((OTObjectServiceImpl) objService, userObject, stateRoot); userDataDB.setDirty(false); currentUserFile = null; setCurrentUser(userObject); reloadWindow(); } catch (Exception e) { e.printStackTrace(); } } public boolean exit() { try { if (!checkForUnsavedUserData()) { // the user canceled the operation return false; } if (OTConfig.isAuthorMode() && !checkForUnsavedAuthorData()) { // the user canceled the operation return false; } // FIXME there is a problem with this logic. If the user saved data // just before closing // checkForUnsavedUserData will not see any unsaved data. But if // some view creates // data in the viewClosed method then that data will not get saved // here. // I think the key to solving this is to seperate the // automatic/logging data from the // user visible data. And then make a rule that saving data in the // viewClosed method // is not allowed. bodyPanel.setCurrentObject(null); conditionalSaveUserData(); if (otrunk != null) otrunk.close(); } catch (Exception exp) { exp.printStackTrace(); // exit anyhow } System.exit(0); return true; } protected void conditionalSaveUserData() { if (!askedAboutSavingUserData) { checkForUnsavedUserData(); } if (needToSaveUserData) { saveUserDataAction.actionPerformed(null); } else { System.err.println("Not saving work before closing."); } // Reset these back to false, so if the user is switching to a new // user or loading a new file we are in a clean state, for that file or // user askedAboutSavingUserData = false; needToSaveUserData = false; } public File getReportFile() { Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.saveotml"); mrfd.setFilenameFilter("html"); if (currentUserFile != null) { mrfd.setCurrentDirectory(currentUserFile.getParentFile()); } int retval = mrfd.showSaveDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); String fileName = file.getPath(); if (!fileName.toLowerCase().endsWith(".html")) { file = new File(file.getAbsolutePath() + ".html"); } return file; } return null; } public void createNewUser() { if (!checkForUnsavedUserData()) { // the user canceled the operation return; } // This ensures viewClosed is called bodyPanel.setCurrentObject(null); conditionalSaveUserData(); // call some new method for creating a new un-saved user state // this should set the currentUserFile to null, so the save check // prompts // for a file name newAnonUserData(); exportToHtmlAction.setEnabled(true); } public void openUserData() { if (!checkForUnsavedUserData()) { // the user canceled the operation return; } // FIXME Calling the method below would insure the view is closed, and // that any data that is // is modified in that view closed operation will get saved, however if // the user // cancels the open dialog then we would be left in an unknown // state. The current view would be closed which they would want to see // again. // bodyPanel.setCurrentObject(null); conditionalSaveUserData(); Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.openotml"); mrfd.setFilenameFilter("otml"); int retval = mrfd.showOpenDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); } if (file != null && file.exists()) { loadUserDataFile(file); exportToHtmlAction.setEnabled(true); } } public void instructionPanel() { commDialog.setResizable(false); JPanel panel = new JPanel(); panel.setBackground(Color.WHITE); panel.setLayout(null); JLabel lNew = new JLabel("Click the \"New\" button to create a new portfolio:"); JLabel lOpen = new JLabel("Click the \"Open\" button to open a saved portfolio:"); JButton bNew = new JButton("New"); JButton bOpen = new JButton("Open"); panel.add(lNew); panel.add(lOpen); panel.add(bNew); panel.add(bOpen); lNew.setLocation(50, 100); lOpen.setLocation(50, 150); bNew.setLocation(400, 100); bOpen.setLocation(400, 150); lNew.setSize(340, 30); lOpen.setSize(340, 30); bNew.setSize(70, 25); bOpen.setSize(70, 25); bNew.setOpaque(false); bOpen.setOpaque(false); bNew.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { commDialog.setVisible(false); createNewUser(); } }); bOpen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { commDialog.setVisible(false); openUserData(); } }); commDialog.getContentPane().add(panel); commDialog.setBounds(200, 200, 500, 300); SwingUtilities.invokeLater(new Runnable() { public void run() { commDialog.setVisible(true); justStarted = false; updateMenuBar(); } }); } public OTViewContainerPanel getViewContainerPanel() { return this.bodyPanel; } public void setExitAction(AbstractAction exitAction) { this.exitAction = exitAction; } /* * (non-Javadoc) * * @see org.concord.applesupport.AppleApplicationAdapter#about() */ public void about() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see org.concord.applesupport.AppleApplicationAdapter#preferences() */ public void preferences() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see org.concord.applesupport.AppleApplicationAdapter#quit() */ public void quit() { exitAction.actionPerformed(null); } public OTrunk getOTrunk() { return otrunk; } } // @jve:decl-index=0:visual-constraint="10,10" class HtmlFileFilter extends javax.swing.filechooser.FileFilter { public boolean accept(File f) { if (f == null) return false; if (f.isDirectory()) return true; return (f.getName().toLowerCase().endsWith(".html")); } public String getDescription() { return "HTML files"; } } // @jve:decl-index=0:visual-constraint="10,10"
src/java/org/concord/otrunk/view/OTViewer.java
/* * Copyright (C) 2004 The Concord Consortium, Inc., * 10 Concord Crossing, Concord, MA 01742 * * Web Site: http://www.concord.org * Email: [email protected] * * 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 * * END LICENSE */ /* * Last modification information: * $Revision: 1.92 $ * $Date: 2007-10-16 22:06:33 $ * $Author: scytacki $ * * Licence Information * Copyright 2004 The Concord Consortium */ package org.concord.otrunk.view; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Toolkit; import java.awt.event.AWTEventListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Hashtable; import java.util.Vector; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.border.EmptyBorder; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.TreePath; import org.concord.applesupport.AppleApplicationAdapter; import org.concord.applesupport.AppleApplicationUtil; import org.concord.framework.otrunk.OTChangeEvent; import org.concord.framework.otrunk.OTChangeListener; import org.concord.framework.otrunk.OTID; import org.concord.framework.otrunk.OTObject; import org.concord.framework.otrunk.OTObjectService; import org.concord.framework.otrunk.OTrunk; import org.concord.framework.otrunk.view.OTExternalAppService; import org.concord.framework.otrunk.view.OTFrameManager; import org.concord.framework.otrunk.view.OTJComponentServiceFactory; import org.concord.framework.otrunk.view.OTUserListService; import org.concord.framework.otrunk.view.OTViewContainer; import org.concord.framework.otrunk.view.OTViewContainerChangeEvent; import org.concord.framework.otrunk.view.OTViewContainerListener; import org.concord.framework.otrunk.view.OTViewContext; import org.concord.framework.otrunk.view.OTViewFactory; import org.concord.framework.text.UserMessageHandler; import org.concord.framework.util.SimpleTreeNode; import org.concord.otrunk.OTMLToXHTMLConverter; import org.concord.otrunk.OTObjectServiceImpl; import org.concord.otrunk.OTStateRoot; import org.concord.otrunk.OTSystem; import org.concord.otrunk.OTrunkImpl; import org.concord.otrunk.datamodel.OTDataObject; import org.concord.otrunk.datamodel.OTDatabase; import org.concord.otrunk.user.OTUserObject; import org.concord.otrunk.xml.ExporterJDOM; import org.concord.otrunk.xml.XMLDatabase; import org.concord.otrunk.xml.XMLDatabaseChangeEvent; import org.concord.otrunk.xml.XMLDatabaseChangeListener; import org.concord.swing.CustomDialog; import org.concord.swing.MemoryMonitorPanel; import org.concord.swing.MostRecentFileDialog; import org.concord.swing.StreamRecord; import org.concord.swing.StreamRecordView; import org.concord.swing.util.Util; import org.concord.view.SimpleTreeModel; import org.concord.view.SwingUserMessageHandler; /** * OTViewer Class name and description * * Date created: Dec 14, 2004 * * @author scott * <p> * */ public class OTViewer extends JFrame implements TreeSelectionListener, OTViewContainerListener, AppleApplicationAdapter { /** * first version of this class */ private static final long serialVersionUID = 1L; public final static String TITLE_PROP = "otrunk.view.frame_title"; public final static String HIDE_TREE_PROP = "otrunk.view.hide_tree"; public final static String SHOW_CONSOLE_PROP = "otrunk.view.show_console"; public final static String HTTP_PUT = "PUT"; public final static String HTTP_POST = "POST"; private static OTrunkImpl otrunk; private static OTViewFactory otViewFactory; protected int userMode = OTConfig.NO_USER_MODE; OTUserObject currentUser = null; URL currentURL = null; String baseFrameTitle = "OTrunk Viewer"; OTViewContainerPanel bodyPanel; OTFrameManagerImpl frameManager; JTree folderTreeArea; SimpleTreeModel folderTreeModel; JTree dataTreeArea; SimpleTreeModel dataTreeModel; JSplitPane splitPane; JFrame consoleFrame; // Temp, to close the window AbstractAction exitAction; AbstractAction saveAsAction; JMenuBar menuBar; XMLDatabase xmlDB; XMLDatabase userDataDB; File currentAuthoredFile = null; File currentUserFile = null; Hashtable otContainers = new Hashtable(); String startupMessage = ""; boolean justStarted = false; boolean showTree = false; URL remoteURL; private AbstractAction saveUserDataAsAction; private AbstractAction saveUserDataAction; private AbstractAction debugAction; private AbstractAction showConsoleAction; private AbstractAction newUserDataAction; private AbstractAction loadUserDataAction; private AbstractAction loadAction; private AbstractAction reloadWindowAction; private AbstractAction saveAction; private AbstractAction saveRemoteAsAction; private AbstractAction exportImageAction; private AbstractAction exportHiResImageAction; private AbstractAction exportToHtmlAction; private JDialog commDialog; /** * This is true if the user was asked about saving user data after they * initiated a close of the current view. */ private boolean askedAboutSavingUserData = false; /** * This is true if the user was asked about saving the user data, and said * yes */ private boolean needToSaveUserData = false; private boolean useScrollPane; private OTChangeListener systemChangeListener; private OTSystem userSystem; private ArrayList services = new ArrayList(); private JPanel statusPanel; public static class ServiceEntry { Object service; Class serviceInterface; public ServiceEntry(Object service, Class serviceInterface) { this.service = service; this.serviceInterface = serviceInterface; } } public static void setOTViewFactory(OTViewFactory factory) { otViewFactory = factory; } public OTViewer() { super(); this.showTree = true; AppleApplicationUtil.registerWithMacOSX(this); try { // this overrides the default base frame title String title = System.getProperty(TITLE_PROP, null); if (title != null) { baseFrameTitle = title; } } catch (Throwable t) { // do nothing, just use the default title } setTitle(baseFrameTitle); setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { exitAction.actionPerformed(null); } }); consoleFrame = new JFrame("Console"); StreamRecord record = new StreamRecord(10000); StreamRecordView view = new StreamRecordView(record); consoleFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); System.setOut((PrintStream) view.addOutputStream(System.out, "Console")); System.setErr((PrintStream) view.addOutputStream(System.err, System.out)); consoleFrame.getContentPane().add(view); consoleFrame.setSize(800, 600); if (OTConfig.getBooleanProp(SHOW_CONSOLE_PROP, false)) { consoleFrame.setVisible(true); } commDialog = new JDialog(this, true); // for debugging // add a breakpoint below, run in debugging mode, and then hit Meta-B // the object you're currently focused on will be passed in here and you // can // start exploring the data structures, etc. KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); KeyEventDispatcher deleteDispatcher = new KeyEventDispatcher(){ public boolean dispatchKeyEvent(KeyEvent e) { if ((e.getID() == java.awt.event.KeyEvent.KEY_RELEASED) && ((e.getModifiersEx() & java.awt.event.InputEvent.META_DOWN_MASK) != 0) && (e.getKeyCode() == java.awt.event.KeyEvent.VK_B)) { Object o = e.getSource(); System.out.println(o.toString()); return true; } return false; } }; focusManager.addKeyEventDispatcher(deleteDispatcher); // If the mouse click is a real right click event and alt is pressed // then this code will print // out the toString method of the object which the mouse is over. AWTEventListener awtEventListener = new AWTEventListener(){ public void eventDispatched(AWTEvent event) { if(!(event instanceof MouseEvent)){ return; } MouseEvent mEvent = (MouseEvent) event; if (mEvent.getID() == MouseEvent.MOUSE_CLICKED && (mEvent.getButton() == MouseEvent.BUTTON3) && (mEvent.getModifiersEx() & MouseEvent.ALT_DOWN_MASK) != 0) { System.out.println(event.getSource().toString()); } } }; Toolkit.getDefaultToolkit().addAWTEventListener(awtEventListener, AWTEvent.MOUSE_EVENT_MASK); } /** * this needs to be called before initialized. * * @param serviceInterface * @param service */ public void addService(Class serviceInterface, Object service) { ServiceEntry entry = new ServiceEntry(service, serviceInterface); services.add(entry); } public void setUserMode(int mode) { userMode = mode; } public int getUserMode() { return userMode; } public void updateTreePane() { Dimension minimumSize = new Dimension(100, 50); folderTreeArea = new JTree(folderTreeModel); // we are just disabling this however if we want to // use this tree for authoring, or for managing student // created objects this will need to be some form of option folderTreeArea.setEditable(false); folderTreeArea.addTreeSelectionListener(this); JComponent leftComponent = null; JScrollPane folderTreeScrollPane = new JScrollPane(folderTreeArea); if (System.getProperty(OTConfig.DEBUG_PROP, "").equals("true")) { // ViewFactory.getComponent(root); dataTreeArea = new JTree(dataTreeModel); dataTreeArea.setEditable(false); dataTreeArea.addTreeSelectionListener(this); JScrollPane dataTreeScrollPane = new JScrollPane(dataTreeArea); JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.add("Folders", folderTreeScrollPane); tabbedPane.add("Resources", dataTreeScrollPane); // Provide minimum sizes for the two components in the split pane folderTreeScrollPane.setMinimumSize(minimumSize); dataTreeScrollPane.setMinimumSize(minimumSize); tabbedPane.setMinimumSize(minimumSize); leftComponent = tabbedPane; } else { leftComponent = folderTreeScrollPane; } if (splitPane == null) { splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftComponent, bodyPanel); } else { splitPane.setLeftComponent(leftComponent); } splitPane.setOneTouchExpandable(true); splitPane.setDividerLocation(200); } public void initArgs(String[] args) { URL authorOTMLURL = OTViewerHelper.getURLFromArgs(args); if ("file".equalsIgnoreCase(authorOTMLURL.getProtocol())) { currentAuthoredFile = new File(authorOTMLURL.getPath()); } String urlStr = authorOTMLURL.toString(); initWithWizard(urlStr); } /** * @param args * @return */ public String getURL(String[] args) { URL authorOTMLURL = OTViewerHelper.getURLFromArgs(args); if ("file".equalsIgnoreCase(authorOTMLURL.getProtocol())) { try { URI authorOTMLURI = new URI(authorOTMLURL.toString()); currentAuthoredFile = new File(authorOTMLURI); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return authorOTMLURL.toString(); } public void init(String url) { updateRemoteURL(url); createActions(); updateMenuBar(); setJMenuBar(menuBar); frameManager = new OTFrameManagerImpl(); bodyPanel = new OTViewContainerPanel(frameManager); bodyPanel.addViewContainerListener(this); if (showTree) { dataTreeModel = new SimpleTreeModel(); folderTreeModel = new SimpleTreeModel(); updateTreePane(); getContentPane().add(splitPane); } else { getContentPane().add(bodyPanel); } if (OTConfig.isShowStatus()) { statusPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING, 3, 1)); final JLabel saveStateLabel = new JLabel("File saved"); statusPanel.add(saveStateLabel); statusPanel.add(Box.createHorizontalStrut(20)); statusPanel.add(new MemoryMonitorPanel()); statusPanel.add(Box.createHorizontalStrut(5)); getContentPane().add(statusPanel, BorderLayout.SOUTH); // It takes a while for xmlDM to be initialized... Thread waitForDB = new Thread() { public void run() { while (xmlDB == null) { try { sleep(1000); } catch (Exception e) { } } xmlDB.addXMLDatabaseChangeListener(new XMLDatabaseChangeListener() { public void stateChanged(XMLDatabaseChangeEvent e) { if (xmlDB.isDirty()) { saveStateLabel.setText("Unsaved changes"); } else { saveStateLabel.setText("File saved"); } statusPanel.repaint(); } }); } }; waitForDB.start(); } SwingUtilities.invokeLater(new Runnable() { public void run() { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); if (screenSize.width < 1000 || screenSize.height < 700) { setVisible(true); int state = getExtendedState(); // Set the maximized bits state |= Frame.MAXIMIZED_BOTH; // Maximize the frame setExtendedState(state); } else { int cornerX = 100; int cornerY = 100; int sizeX = 725; int sizeY = 500; // OTViewService viewService = otViewFactory. setBounds(cornerX, cornerY, cornerX + sizeX, cornerY + sizeY); setVisible(true); } } }); if (url == null) { return; } try { initializeURL(new URL(url)); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (Exception e) { // FIXME: this should popup a dialog System.err.println("Can't load url"); e.printStackTrace(); return; } } public void initializeURL(URL url) throws Exception { loadURL(url); OTMainFrame mainFrame = (OTMainFrame) otrunk.getService(OTMainFrame.class); if (OTConfig.getBooleanProp(HIDE_TREE_PROP, false) || !mainFrame.getShowLeftPanel()) { splitPane.getLeftComponent().setVisible(false); } useScrollPane = true; if (mainFrame.getFrame() != null) { if (mainFrame.getFrame().isResourceSet("width") && mainFrame.getFrame().isResourceSet("height")) { int cornerX = 100; int cornerY = 100; int sizeX = mainFrame.getFrame().getWidth(); int sizeY = mainFrame.getFrame().getHeight(); setBounds(cornerX, cornerY, cornerX + sizeX, cornerY + sizeY); repaint(); } useScrollPane = mainFrame.getFrame().getUseScrollPane(); } bodyPanel.setUseScrollPane(useScrollPane); setupBodyPanel(); } public void initWithWizard(String url) { justStarted = true; init(url); if (userMode == OTConfig.SINGLE_USER_MODE) { SwingUtilities.invokeLater(new Runnable() { public void run() { instructionPanel(); } }); } } public void loadUserDataFile(File file) { currentUserFile = file; try { loadUserDataURL(file.toURL(), file.getName()); } catch (Exception e) { e.printStackTrace(); } } public void loadUserDataURL(URL url, String name) throws Exception { XMLDatabase db = new XMLDatabase(url); db.loadObjects(); loadUserDataDb(db, name); } public void loadUserDataDb(XMLDatabase db, String name) throws Exception { userDataDB = db; currentUser = otrunk.registerUserDataDatabase(userDataDB, name); reloadWindow(); } public void reloadOverlays() { try { otrunk.reloadOverlays(currentUser, userDataDB); reloadWindow(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void loadFile(File file) { currentAuthoredFile = file; try { initializeURL(currentAuthoredFile.toURL()); } catch (Exception e) { e.printStackTrace(); } } public void loadURL(URL url) throws Exception { XMLDatabase systemDB = null; try { // try loading in the system object if there is one String systemOtmlUrlStr = OTConfig.getStringProp(OTConfig.SYSTEM_OTML_PROP); if(systemOtmlUrlStr != null){ URL systemOtmlUrl = new URL(systemOtmlUrlStr); systemDB = new XMLDatabase(systemOtmlUrl, System.out); // don't track the resource info on the system db. systemDB.loadObjects(); } } catch (Exception e){ e.printStackTrace(); systemDB = null; } try { xmlDB = new XMLDatabase(url, System.out); // Only track the resource info when there isn't a user. Currently // all classroom uses // of OTViewer has NO_USER_MODE turned off, so using this setting // safe to test // the resource tracking without affecting real users. if (userMode == OTConfig.NO_USER_MODE) { xmlDB.setTrackResourceInfo(true); } xmlDB.loadObjects(); } catch (org.jdom.input.JDOMParseException e) { String xmlWarningTitle = "XML Decoding error"; String xmlWarningMessage = "There appears to a problem parsing the XML of this document. \n" + "Please show this error message to one of the workshop leaders. \n\n" + e.getMessage(); JOptionPane.showMessageDialog(null, xmlWarningMessage, xmlWarningTitle, JOptionPane.ERROR_MESSAGE); throw e; } int servicesSize = services.size(); int numDefaultServices = 1; Object [] serviceArray = new Object[servicesSize + numDefaultServices]; serviceArray[0] = new SwingUserMessageHandler(this); Class [] serviceInterfaces = new Class[servicesSize + numDefaultServices]; serviceInterfaces[0] = UserMessageHandler.class; for(int i=0; i<services.size(); i++){ ServiceEntry entry = (ServiceEntry) services.get(i); serviceArray[i+numDefaultServices] = entry.service; serviceInterfaces[i+numDefaultServices] = entry.serviceInterface; } otrunk = new OTrunkImpl(systemDB, xmlDB, serviceArray, serviceInterfaces); OTViewFactory myViewFactory = (OTViewFactory) otrunk.getService(OTViewFactory.class); if (myViewFactory != null) { otViewFactory = myViewFactory; } OTViewContext factoryContext = otViewFactory.getViewContext(); factoryContext.addViewService(OTrunk.class, otrunk); factoryContext.addViewService(OTFrameManager.class, frameManager); factoryContext.addViewService(OTJComponentServiceFactory.class, new OTJComponentServiceFactoryImpl()); factoryContext.addViewService(OTExternalAppService.class, new OTExternalAppServiceImpl()); factoryContext.addViewService(OTUserListService.class, new OTUserListService() { public Vector getUserList() { return otrunk.getUsers(); } }); currentURL = url; } // This method was refactored out of loadURL private void setupBodyPanel() throws Exception { bodyPanel.setTopLevelContainer(true); bodyPanel.setOTViewFactory(otViewFactory); // set the current mode from the viewservice to the main bodyPanel // bodyPanel.setViewMode(otViewFactory.getDefaultMode()); // set the viewFactory of the frame manager frameManager.setViewFactory(otViewFactory); xmlDB.setDirty(false); reloadWindow(); } public OTObject getAuthoredRoot() throws Exception { String rootLocalId = OTConfig.getStringProp(OTConfig.ROOT_OBJECT_PROP); if(rootLocalId != null){ OTID rootID = xmlDB.getOTIDFromLocalID(rootLocalId); return otrunk.getOTObject(rootID); } return otrunk.getRoot(); } public OTObject getRoot() throws Exception { switch (userMode) { case OTConfig.NO_USER_MODE: return getAuthoredRoot(); case OTConfig.SINGLE_USER_MODE: if (userDataDB == null) { return null; } OTObject otRoot = getAuthoredRoot(); return otrunk.getUserRuntimeObject(otRoot, currentUser); } return null; } private void reloadWindow() throws Exception { OTObject root = getRoot(); boolean overrideShowTree = false; if (userMode == OTConfig.SINGLE_USER_MODE) { if (root == null) { // FIXME This is an error // the newAnonUserData should have been called before this // method is // called // no user file has been started yet overrideShowTree = true; } else { OTObject realRoot = otrunk.getRealRoot(); if (realRoot instanceof OTSystem) { OTSystem localUserSystem = (OTSystem) otrunk.getUserRuntimeObject(realRoot, currentUser); // FIXME there should be a better way than this because we // have to handle // multiple users. if (localUserSystem != userSystem) { userSystem = localUserSystem; systemChangeListener = new OTChangeListener() { public void stateChanged(OTChangeEvent e) { if ("overlays".equals(e.getProperty())) { reloadOverlays(); } } }; userSystem.addOTChangeListener(systemChangeListener); } } } } if (showTree && !overrideShowTree) { OTDataObject rootDataObject = xmlDB.getRoot(); dataTreeModel.setRoot(new OTDataObjectNode("root", rootDataObject, otrunk)); folderTreeModel.setRoot(new OTFolderNode(root)); } bodyPanel.setCurrentObject(root); if (showTree && !overrideShowTree) { folderTreeModel.fireTreeStructureChanged(new TreePath( (SimpleTreeNode) folderTreeModel.getRoot())); dataTreeModel.fireTreeStructureChanged(new TreePath( (SimpleTreeNode) dataTreeModel.getRoot())); } Frame frame = (Frame) SwingUtilities.getRoot(this); switch (userMode) { case OTConfig.NO_USER_MODE: if (remoteURL != null) { frame.setTitle(baseFrameTitle + ": " + remoteURL.toString()); } else { frame.setTitle(baseFrameTitle + ": " + currentURL.toString()); } break; case OTConfig.SINGLE_USER_MODE: if (currentUserFile != null) { frame.setTitle(baseFrameTitle + ": " + currentUserFile.toString()); } else if (System.getProperty(TITLE_PROP, null) != null) { frame.setTitle(baseFrameTitle); } else if (userDataDB != null) { frame.setTitle(baseFrameTitle + ": Untitled"); } else { frame.setTitle(baseFrameTitle); } break; } saveUserDataAction.setEnabled(userDataDB != null); saveUserDataAsAction.setEnabled(userDataDB != null); } public void reload() throws Exception { initializeURL(currentURL); } public OTDatabase getUserDataDb() { return userDataDB; } /** * You should call reloadWindow after calling this method to make sure the * display reflects this change * * @param userObject */ public void setCurrentUser(OTUserObject userObject) { currentUser = userObject; } public static void main(String[] args) { System.setProperty("apple.laf.useScreenMenuBar", "true"); OTViewer viewer = new OTViewer(); if (OTConfig.getBooleanProp(OTConfig.SINGLE_USER_PROP, false)) { viewer.setUserMode(OTConfig.SINGLE_USER_MODE); } else if (OTConfig.getBooleanProp(OTConfig.NO_USER_PROP, false)) { viewer.setUserMode(OTConfig.NO_USER_MODE); } viewer.initArgs(args); } class ExitAction extends AbstractAction { /** * nothing to serialize here. */ private static final long serialVersionUID = 1L; public ExitAction() { super("Exit"); } public void actionPerformed(ActionEvent e) { // If this suceeds then the VM will exit so // the window will get disposed exit(); } } /* * (non-Javadoc) * * @see org.concord.otrunk.view.OTViewContainerListener#currentObjectChanged(org.concord.framework.otrunk.view.OTViewContainer) */ public void currentObjectChanged(OTViewContainerChangeEvent evt) { final OTViewContainer myContainer = (OTViewContainer) evt.getSource(); // TODO Auto-generated method stub SwingUtilities.invokeLater(new Runnable() { public void run() { OTObject currentObject = myContainer.getCurrentObject(); if (folderTreeArea != null) { OTFolderNode node = (OTFolderNode) folderTreeArea.getLastSelectedPathComponent(); if (node == null) return; if (node.getPfObject() != currentObject) { folderTreeArea.setSelectionPath(null); } } } }); } /* * (non-Javadoc) * * @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent) */ public void valueChanged(TreeSelectionEvent event) { if (event.getSource() == folderTreeArea) { OTFolderNode node = (OTFolderNode) folderTreeArea.getLastSelectedPathComponent(); if (node == null) return; OTObject pfObject = node.getPfObject(); bodyPanel.setCurrentObject(pfObject); if (splitPane.getRightComponent() != bodyPanel) { splitPane.setRightComponent(bodyPanel); } } else if (event.getSource() == dataTreeArea) { SimpleTreeNode node = (SimpleTreeNode) dataTreeArea.getLastSelectedPathComponent(); Object resourceValue = null; if (node != null) { resourceValue = node.getObject(); if (resourceValue == null) { resourceValue = "null resource value"; } } else { resourceValue = "no selected data object"; } JComponent nodeView = null; if (resourceValue instanceof OTDataObject) { nodeView = new OTDataObjectView((OTDataObject) resourceValue); } else { nodeView = new JTextArea(resourceValue.toString()); } JScrollPane scrollPane = new JScrollPane(nodeView); splitPane.setRightComponent(scrollPane); } } private void updateRemoteURL(String defaultURL) { String remote = System.getProperty(OTConfig.REMOTE_URL_PROP, null); try { if (remote == null) { if (defaultURL.startsWith("http:")) { remoteURL = new URL(defaultURL); } } else { remoteURL = new URL(remote); } } catch (Exception e) { remoteURL = null; System.err.println("Remote URL is invalid."); e.printStackTrace(); } } public void remoteSaveData(String method) throws Exception { HttpURLConnection urlConn; DataOutputStream urlDataOut; BufferedReader urlDataIn; // If method isn't "POST" or "PUT", throw an exception if (!(method.compareTo(OTViewer.HTTP_POST) == 0 || method.compareTo(OTViewer.HTTP_PUT) == 0)) { throw new Exception("Invalid HTTP Request method for data saving"); } urlConn = (HttpURLConnection) remoteURL.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestMethod(method); urlConn.setRequestProperty("Content-Type", "application/xml"); // Send POST output. urlDataOut = new DataOutputStream(urlConn.getOutputStream()); ExporterJDOM.export(urlDataOut, xmlDB.getRoot(), xmlDB); urlDataOut.flush(); urlDataOut.close(); // Get response data. urlDataIn = new BufferedReader(new InputStreamReader(new DataInputStream( urlConn.getInputStream()))); String str; String response = ""; while (null != ((str = urlDataIn.readLine()))) { response += str + "\n"; } urlDataIn.close(); // Need to trap non-HTTP 200/300 responses and throw an exception (if an // exception isn't thrown already) and capture the exceptions upstream int code = urlConn.getResponseCode(); if (code >= 400) { throw new Exception("HTTP Response: " + urlConn.getResponseMessage() + "\n\n" + response); } urlConn.disconnect(); xmlDB.setDirty(false); setTitle(remoteURL.toString()); } public void createActions() { newUserDataAction = new AbstractAction("New") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { createNewUser(); } }; loadUserDataAction = new AbstractAction("Open...") { /** * nothing to serialize here. Just the parent class. */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { openUserData(); } }; exportToHtmlAction = new AbstractAction("Export to html...") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent arg0) { File fileToSave = getReportFile(); OTMLToXHTMLConverter otxc = new OTMLToXHTMLConverter(otViewFactory, bodyPanel.getViewContainer()); otxc.setXHTMLParams(fileToSave, 800, 600); (new Thread(otxc)).start(); } }; // Isn't it enabled by default? exportToHtmlAction.setEnabled(true); saveUserDataAction = new AbstractAction("Save") { /** * Nothing to serialize here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { System.out.println("saving"); if (currentUserFile == null || !currentUserFile.exists()) { System.out.println("saving as"); saveUserDataAsAction.actionPerformed(arg0); return; } if (currentUserFile.exists()) { System.out.println(" file exists"); System.out.println(" "+currentUserFile); try { ExporterJDOM.export(currentUserFile, userDataDB.getRoot(), userDataDB); userDataDB.setDirty(false); } catch (Exception e) { e.printStackTrace(); } } System.out.println("finished saving"); } }; saveUserDataAsAction = new AbstractAction("Save As...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.saveotml"); mrfd.setFilenameFilter("otml"); if (currentUserFile != null) { mrfd.setCurrentDirectory(currentUserFile.getParentFile()); mrfd.setSelectedFile(currentUserFile); } int retval = mrfd.showSaveDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); String fileName = file.getPath(); currentUserFile = file; if (!fileName.toLowerCase().endsWith(".otml")) { currentUserFile = new File(currentUserFile.getAbsolutePath() + ".otml"); } try { ExporterJDOM.export(currentUserFile, userDataDB.getRoot(), userDataDB); userDataDB.setDirty(false); setTitle(baseFrameTitle + ": " + currentUserFile.toString()); } catch (Exception e) { e.printStackTrace(); } frame.setTitle(fileName); } } }; loadAction = new AbstractAction("Open Authored Content...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.openotml"); mrfd.setFilenameFilter("otml"); int retval = mrfd.showOpenDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); } if (file != null && file.exists()) { System.out.println("load file name: " + file); // if they open an authored file then they are overriding // the remoteURL, // at least for now. This makes the title bar update // correctly, and // fixes a lockup that happens when they have opened a local // file and then // try to save it again. remoteURL = null; loadFile(file); exportToHtmlAction.setEnabled(true); } } }; loadAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); saveAction = new AbstractAction("Save Authored Content...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { if (remoteURL != null) { try { if (OTConfig.isRestEnabled()) { try { remoteSaveData(OTViewer.HTTP_PUT); } catch (Exception e) { remoteSaveData(OTViewer.HTTP_POST); } } else { remoteSaveData(OTViewer.HTTP_POST); } } catch (Exception e) { JOptionPane.showMessageDialog( (Frame) SwingUtilities.getRoot(OTViewer.this), "There was an error saving. Check your URL and try again.", "Error Saving", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } else { if (currentAuthoredFile == null) { saveAsAction.actionPerformed(arg0); return; } if (checkForReplace(currentAuthoredFile)) { try { ExporterJDOM.export(currentAuthoredFile, xmlDB.getRoot(), xmlDB); xmlDB.setDirty(false); } catch (Exception e) { e.printStackTrace(); } } } // end if (remoteUrl == null) } }; saveAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); saveAsAction = new AbstractAction("Save Authored Content As...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.saveotml"); mrfd.setFilenameFilter("otml"); if (currentAuthoredFile != null) { mrfd.setCurrentDirectory(currentAuthoredFile.getParentFile()); mrfd.setSelectedFile(currentAuthoredFile); } int retval = mrfd.showSaveDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); String fileName = file.getPath(); if (!fileName.toLowerCase().endsWith(".otml")) { file = new File(file.getAbsolutePath() + ".otml"); } if (checkForReplace(file)) { try { ExporterJDOM.export(file, xmlDB.getRoot(), xmlDB); currentAuthoredFile = file; currentURL = file.toURL(); xmlDB.setDirty(false); } catch (Exception e) { e.printStackTrace(); } } frame.setTitle(fileName); remoteURL = null; updateMenuBar(); } } }; saveRemoteAsAction = new AbstractAction("Save Remotely As...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { // Pop up a dialog asking for a URL // Post the otml to the url JPanel panel = new JPanel(); panel.setBorder(new EmptyBorder(10, 10, 10, 10)); panel.setLayout(new BorderLayout()); JLabel prompt = new JLabel("Please enter the URL to which you would like to save:"); prompt.setBorder(new EmptyBorder(0, 0, 10, 0)); JTextField textField = new JTextField(); if (remoteURL == null) { textField.setText("http://"); } else { textField.setText(remoteURL.toString()); } JPanel checkboxPanel = new JPanel(); JCheckBox restCheckbox = new JCheckBox("REST Enabled?"); restCheckbox.setSelected(OTConfig.isRestEnabled()); checkboxPanel.setBorder(new EmptyBorder(5, 5, 0, 0)); checkboxPanel.add(restCheckbox); panel.add(prompt, BorderLayout.NORTH); panel.add(textField, BorderLayout.CENTER); panel.add(checkboxPanel, BorderLayout.SOUTH); int returnVal = CustomDialog.showOKCancelDialog( (Frame) SwingUtilities.getRoot(OTViewer.this), // parent panel, // custom content "Save URL", // title false, // resizeable true // modal ); if (returnVal == 0) { try { remoteURL = new URL(textField.getText()); // WARNING this will cause a security exception if we // are running in a applet or jnlp which // has a security sandbox. System.setProperty(OTConfig.REST_ENABLED_PROP, Boolean.toString(restCheckbox.isSelected())); remoteSaveData(OTViewer.HTTP_POST); updateMenuBar(); } catch (Exception e) { System.err.println("Bad URL. Not saving."); JOptionPane.showMessageDialog( (Frame) SwingUtilities.getRoot(OTViewer.this), "There was an error saving. Check your URL and try again.", "Error Saving", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } else { // CANCELLED } } }; exportImageAction = new AbstractAction("Export Image...") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { // this introduces a dependency on concord Swing project // instead there needs to be a way to added these actions // through // the xml Component currentComp = bodyPanel.getCurrentComponent(); Util.makeScreenShot(currentComp); } }; exportHiResImageAction = new AbstractAction("Export Hi Res Image...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { Component currentComp = bodyPanel.getCurrentComponent(); Util.makeScreenShot(currentComp, 2, 2); } }; debugAction = new AbstractAction("Debug Mode") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (((JCheckBoxMenuItem) source).isSelected()) { System.setProperty(OTConfig.DEBUG_PROP, "true"); } else { System.setProperty(OTConfig.DEBUG_PROP, "false"); } try { reloadWindow(); } catch (Exception exp) { exp.printStackTrace(); } SwingUtilities.invokeLater(new Runnable() { public void run() { updateMenuBar(); } }); exportToHtmlAction.setEnabled(true); } }; showConsoleAction = new AbstractAction("Show Console") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { if (consoleFrame != null) { consoleFrame.setVisible(true); } } }; reloadWindowAction = new AbstractAction("Reload window") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { try { reload(); } catch (Exception e1) { e1.printStackTrace(); } } }; exitAction = new ExitAction(); } /** * @return Returns the menuBar. */ public JMenuBar updateMenuBar() { // /////////////////////////////////////////////// JMenu fileMenu = null; if (menuBar == null) { menuBar = new JMenuBar(); fileMenu = new JMenu("File"); menuBar.add(fileMenu); } else { fileMenu = menuBar.getMenu(0); fileMenu.removeAll(); } if (OTConfig.isAuthorMode()) { userMode = OTConfig.NO_USER_MODE; } if (userMode == OTConfig.SINGLE_USER_MODE) { fileMenu.setEnabled(!justStarted); fileMenu.add(newUserDataAction); fileMenu.add(loadUserDataAction); fileMenu.add(saveUserDataAction); fileMenu.add(saveUserDataAsAction); } if (OTConfig.isDebug()) { if (userMode == OTConfig.SINGLE_USER_MODE) { loadAction.putValue(Action.NAME, "Open Authored Content..."); saveAction.putValue(Action.NAME, "Save Authored Content"); saveAsAction.putValue(Action.NAME, "Save Authored Content As..."); saveRemoteAsAction.putValue(Action.NAME, "Save Authored Content Remotely As..."); } else { loadAction.putValue(Action.NAME, "Open..."); saveAction.putValue(Action.NAME, "Save"); saveAsAction.putValue(Action.NAME, "Save As..."); saveRemoteAsAction.putValue(Action.NAME, "Save Remotely As..."); } fileMenu.add(loadAction); fileMenu.add(saveAction); fileMenu.add(saveAsAction); fileMenu.add(saveRemoteAsAction); } if (OTConfig.isAuthorMode() && !OTConfig.isDebug()) { if (userMode == OTConfig.SINGLE_USER_MODE) { loadAction.putValue(Action.NAME, "Open Authored Content..."); saveAction.putValue(Action.NAME, "Save Authored Content"); saveAsAction.putValue(Action.NAME, "Save Authored Content As..."); } else { loadAction.putValue(Action.NAME, "Open..."); saveAction.putValue(Action.NAME, "Save"); saveAsAction.putValue(Action.NAME, "Save As..."); } fileMenu.add(loadAction); fileMenu.add(saveAction); fileMenu.add(saveAsAction); } if (OTConfig.getBooleanProp("otrunk.view.export_image", false)) { fileMenu.add(exportImageAction); fileMenu.add(exportHiResImageAction); } fileMenu.add(exportToHtmlAction); fileMenu.add(showConsoleAction); if (OTConfig.isAuthorMode() || OTConfig.isDebug()) { fileMenu.add(reloadWindowAction); } JCheckBoxMenuItem debugItem = new JCheckBoxMenuItem(debugAction); debugItem.setSelected(OTConfig.isDebug()); fileMenu.add(debugItem); fileMenu.add(exitAction); return menuBar; } boolean checkForReplace(File file) { if (file == null){ return false; } if (!file.exists()) { return true; // File doesn't exist, so go ahead and save } if (currentAuthoredFile != null && file.compareTo(currentAuthoredFile) == 0){ return true; // we're already authoring this file, so no need to // prompt } final Object[] options = { "Yes", "No" }; return javax.swing.JOptionPane.showOptionDialog(null, "The file '" + file.getName() + "' already exists. " + "Replace existing file?", "Warning", javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, options, options[1]) == javax.swing.JOptionPane.YES_OPTION; } /** * Checks if the user has unsaved work. If they do then it prompts them to * confirm what they are doing. If they cancel then it returns false. * * @return */ public boolean checkForUnsavedUserData() { if (currentUser != null && userDataDB != null) { if (userDataDB.isDirty()) { // show dialog message telling them they haven't // saved their work // FIXME String options[] = { "Don't Save", "Cancel", "Save" }; askedAboutSavingUserData = true; int chosenOption = JOptionPane.showOptionDialog(this, "Save Changes?", "Save Changes?", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[2]); switch (chosenOption) { case 0: System.err.println("Not saving work"); break; case 1: System.err.println("Canceling close"); return false; case 2: System.err.println("Set needToSaveUserData true"); needToSaveUserData = true; break; } } } return true; } /** * Checks if the user has unsaved authored data. If they do then it prompts * them to confirm what they are doing. If they cancel then it returns * false. * * @return */ public boolean checkForUnsavedAuthorData() { if (xmlDB != null) { if (xmlDB.isDirty()) { // show dialog message telling them they haven't // saved their work // FIXME String options[] = { "Don't Save", "Cancel", "Save" }; int chosenOption = JOptionPane.showOptionDialog(this, "Save Changes?", "Save Changes?", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[2]); switch (chosenOption) { case 0: System.err.println("Not saving authored data"); break; case 1: System.err.println("Canceling close"); return false; case 2: System.err.println("Saving authored data"); saveAction.actionPerformed(null); break; } } } return true; } /** * This does not check for unsaved user data * */ public void newAnonUserData() { // call some new method for creating a new un-saved user state // this should set the currentUserFile to null, so the save check // prompts // for a file name try { // need to make a brand new stateDB userDataDB = new XMLDatabase(); // System.out.println("otrunk: " + otrunk + " userDatabase: " + // userDataDB); OTObjectService objService = otrunk.createObjectService(userDataDB); OTStateRoot stateRoot = (OTStateRoot) objService.createObject(OTStateRoot.class); userDataDB.setRoot(stateRoot.getGlobalId()); stateRoot.setFormatVersionString("1.0"); OTUserObject userObject = OTViewerHelper.createUser("anon_single_user", objService); otrunk.initUserObjectService((OTObjectServiceImpl) objService, userObject, stateRoot); userDataDB.setDirty(false); currentUserFile = null; setCurrentUser(userObject); reloadWindow(); } catch (Exception e) { e.printStackTrace(); } } public boolean exit() { try { if (!checkForUnsavedUserData()) { // the user canceled the operation return false; } if (OTConfig.isAuthorMode() && !checkForUnsavedAuthorData()) { // the user canceled the operation return false; } // FIXME there is a problem with this logic. If the user saved data // just before closing // checkForUnsavedUserData will not see any unsaved data. But if // some view creates // data in the viewClosed method then that data will not get saved // here. // I think the key to solving this is to seperate the // automatic/logging data from the // user visible data. And then make a rule that saving data in the // viewClosed method // is not allowed. bodyPanel.setCurrentObject(null); conditionalSaveUserData(); if (otrunk != null) otrunk.close(); } catch (Exception exp) { exp.printStackTrace(); // exit anyhow } System.exit(0); return true; } protected void conditionalSaveUserData() { if (!askedAboutSavingUserData) { checkForUnsavedUserData(); } if (needToSaveUserData) { saveUserDataAction.actionPerformed(null); } else { System.err.println("Not saving work before closing."); } // Reset these back to false, so if the user is switching to a new // user or loading a new file we are in a clean state, for that file or // user askedAboutSavingUserData = false; needToSaveUserData = false; } public File getReportFile() { Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.saveotml"); mrfd.setFilenameFilter("html"); if (currentUserFile != null) { mrfd.setCurrentDirectory(currentUserFile.getParentFile()); } int retval = mrfd.showSaveDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); String fileName = file.getPath(); if (!fileName.toLowerCase().endsWith(".html")) { file = new File(file.getAbsolutePath() + ".html"); } return file; } return null; } public void createNewUser() { if (!checkForUnsavedUserData()) { // the user canceled the operation return; } // This ensures viewClosed is called bodyPanel.setCurrentObject(null); conditionalSaveUserData(); // call some new method for creating a new un-saved user state // this should set the currentUserFile to null, so the save check // prompts // for a file name newAnonUserData(); exportToHtmlAction.setEnabled(true); } public void openUserData() { if (!checkForUnsavedUserData()) { // the user canceled the operation return; } // FIXME Calling the method below would insure the view is closed, and // that any data that is // is modified in that view closed operation will get saved, however if // the user // cancels the open dialog then we would be left in an unknown // state. The current view would be closed which they would want to see // again. // bodyPanel.setCurrentObject(null); conditionalSaveUserData(); Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.openotml"); mrfd.setFilenameFilter("otml"); int retval = mrfd.showOpenDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); } if (file != null && file.exists()) { loadUserDataFile(file); exportToHtmlAction.setEnabled(true); } } public void instructionPanel() { commDialog.setResizable(false); JPanel panel = new JPanel(); panel.setBackground(Color.WHITE); panel.setLayout(null); JLabel lNew = new JLabel("Click the \"New\" button to create a new portfolio:"); JLabel lOpen = new JLabel("Click the \"Open\" button to open a saved portfolio:"); JButton bNew = new JButton("New"); JButton bOpen = new JButton("Open"); panel.add(lNew); panel.add(lOpen); panel.add(bNew); panel.add(bOpen); lNew.setLocation(50, 100); lOpen.setLocation(50, 150); bNew.setLocation(400, 100); bOpen.setLocation(400, 150); lNew.setSize(340, 30); lOpen.setSize(340, 30); bNew.setSize(70, 25); bOpen.setSize(70, 25); bNew.setOpaque(false); bOpen.setOpaque(false); bNew.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { commDialog.setVisible(false); createNewUser(); } }); bOpen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { commDialog.setVisible(false); openUserData(); } }); commDialog.getContentPane().add(panel); commDialog.setBounds(200, 200, 500, 300); SwingUtilities.invokeLater(new Runnable() { public void run() { commDialog.setVisible(true); justStarted = false; updateMenuBar(); } }); } public OTViewContainerPanel getViewContainerPanel() { return this.bodyPanel; } public void setExitAction(AbstractAction exitAction) { this.exitAction = exitAction; } /* * (non-Javadoc) * * @see org.concord.applesupport.AppleApplicationAdapter#about() */ public void about() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see org.concord.applesupport.AppleApplicationAdapter#preferences() */ public void preferences() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see org.concord.applesupport.AppleApplicationAdapter#quit() */ public void quit() { exitAction.actionPerformed(null); } public OTrunk getOTrunk() { return otrunk; } } // @jve:decl-index=0:visual-constraint="10,10" class HtmlFileFilter extends javax.swing.filechooser.FileFilter { public boolean accept(File f) { if (f == null) return false; if (f.isDirectory()) return true; return (f.getName().toLowerCase().endsWith(".html")); } public String getDescription() { return "HTML files"; } } // @jve:decl-index=0:visual-constraint="10,10"
test saving procedure git-svn-id: 8ebed0c25533aaea68ca43268d4d516467f97e6a@12701 6e01202a-0783-4428-890a-84243c50cc2b
src/java/org/concord/otrunk/view/OTViewer.java
test saving procedure
<ide><path>rc/java/org/concord/otrunk/view/OTViewer.java <ide> */ <ide> public void actionPerformed(ActionEvent arg0) <ide> { <add> System.out.println("trying to save authored content"); <ide> if (remoteURL != null) { <add> System.out.println(" remote url = "+remoteURL); <ide> try { <ide> if (OTConfig.isRestEnabled()) { <add> System.out.println(" is rest enabled"); <ide> try { <ide> remoteSaveData(OTViewer.HTTP_PUT); <ide> } catch (Exception e) { <ide> remoteSaveData(OTViewer.HTTP_POST); <ide> } <ide> } else { <add> System.out.println(" not rest enabled, posting"); <ide> remoteSaveData(OTViewer.HTTP_POST); <ide> } <ide> } catch (Exception e) { <add> System.out.println(" caught"); <ide> JOptionPane.showMessageDialog( <ide> (Frame) SwingUtilities.getRoot(OTViewer.this), <ide> "There was an error saving. Check your URL and try again.", <ide> e.printStackTrace(); <ide> } <ide> } else { <add> System.out.println(" no remote url"); <ide> if (currentAuthoredFile == null) { <add> System.out.println(" currentAuthoredFile = null"); <ide> saveAsAction.actionPerformed(arg0); <ide> return; <ide> } <ide> <ide> if (checkForReplace(currentAuthoredFile)) { <add> System.out.println(" check for replace"); <ide> try { <add> System.out.println(" exporting"); <ide> ExporterJDOM.export(currentAuthoredFile, xmlDB.getRoot(), <ide> xmlDB); <ide> xmlDB.setDirty(false); <ide> } catch (Exception e) { <add> System.out.println(" caught export exception"); <ide> e.printStackTrace(); <ide> } <ide> }
Java
mit
2898dc6e1fe26be28ba4f389a465a092dd7cf778
0
YcleptJohn/SortAnalytics
package uk.co.johnjtaylor.events.sorts.bubble; import uk.co.johnjtaylor.events.EventImportance; import uk.co.johnjtaylor.events.EventType; import uk.co.johnjtaylor.events.generic.SortEvent; /** * Represents the end of a bubble sort across a dataset; * (detected via the lack of swaps and then spawned) * @author John */ public class BubbleSortEndEvent extends SortEvent { private static final long serialVersionUID = -8427959870167493795L; // Enforced serializable due to EventObject extension private static final EventType TYPE = EventType.BubbleSortEndEvent; private static final EventImportance IMPORTANCE = EventImportance.MEDIUM; /** * @param source The source that is spawning the new instance of this event */ public BubbleSortEndEvent(Object source) { super(source, TYPE, IMPORTANCE); } }
src/uk/co/johnjtaylor/events/sorts/bubble/BubbleSortEndEvent.java
package uk.co.johnjtaylor.events.sorts.bubble; import uk.co.johnjtaylor.events.generic.SortEvent; public class BubbleSortEndEvent extends SortEvent { }
Created a base for the BubbleSortEndEvent +jdoc
src/uk/co/johnjtaylor/events/sorts/bubble/BubbleSortEndEvent.java
Created a base for the BubbleSortEndEvent +jdoc
<ide><path>rc/uk/co/johnjtaylor/events/sorts/bubble/BubbleSortEndEvent.java <ide> package uk.co.johnjtaylor.events.sorts.bubble; <ide> <add>import uk.co.johnjtaylor.events.EventImportance; <add>import uk.co.johnjtaylor.events.EventType; <ide> import uk.co.johnjtaylor.events.generic.SortEvent; <del> <add>/** <add> * Represents the end of a bubble sort across a dataset; <add> * (detected via the lack of swaps and then spawned) <add> * @author John <add> */ <ide> public class BubbleSortEndEvent extends SortEvent { <del> <add> private static final long serialVersionUID = -8427959870167493795L; // Enforced serializable due to EventObject extension <add> private static final EventType TYPE = EventType.BubbleSortEndEvent; <add> private static final EventImportance IMPORTANCE = EventImportance.MEDIUM; <add> <add> /** <add> * @param source The source that is spawning the new instance of this event <add> */ <add> public BubbleSortEndEvent(Object source) { <add> super(source, TYPE, IMPORTANCE); <add> } <ide> }
Java
mit
f22cff860125bb6d529b921a485b00d41f86ab74
0
UNINETT/daas-apps,UNINETT/daas-apps
package com.github.sparkcaller; import com.github.sparkcaller.preprocessing.*; import com.github.sparkcaller.variantdiscovery.HaplotypeCaller; import org.apache.commons.cli.*; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.log4j.Logger; import scala.Tuple2; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Properties; public class SparkCaller { final private JavaSparkContext sparkContext; final private Logger log; private String pathToReference; private String knownSites; private Properties toolsExtraArgs; /* * The SparkCaller is used for managing the workflow * @param pathToReference the path to the file to use as a reference. * Keep in mind that this file has to be reachable by all nodes, and has to be indexed. * * @param pathToReference the path to the file containing the dbsnp to use when ex. performing BQSR. * Keep in mind that this file has to be reachable by all nodes. * * @param toolsExtraArguments the Properties object containing strings of extra arguments to pass to each tool. * */ public SparkCaller(JavaSparkContext sparkContext, String pathToReference, String knownSites, Properties toolsExtraArguments) { this.sparkContext = sparkContext; this.log = Logger.getLogger(this.getClass()); this.pathToReference = pathToReference; this.toolsExtraArgs = toolsExtraArguments; this.knownSites = knownSites; } /* Performs the preprocessing stage of the GATK pipeline. * This is performed in a simple scatter-gather manner. * See the following link for details: https://www.broadinstitute.org/gatk/guide/bp_step.php?p=1 * * @param pathToSAMFiles the path to the folder containing the SAM files created by the aligner. * */ public JavaRDD<File> preprocessSAMFiles(String pathToSAMFiles) { this.log.info("Preprocessing SAM files!"); // Get all the SAM files generated by the aligner ArrayList<File> samFiles = Utils.getFilesInFolder(pathToSAMFiles, "sam"); if (samFiles != null) { this.log.info("Distributing the SAM files to the nodes..."); JavaRDD<File> samFilesRDD = sparkContext.parallelize(samFiles); this.log.info("Converting the SAM files to sorted BAM files..."); JavaRDD<File> bamFilesRDD = samFilesRDD.map(new SamToSortedBam()); this.log.info("Marking duplicates..."); bamFilesRDD = bamFilesRDD.map(new DuplicateMarker(this.toolsExtraArgs.getProperty("MarkDuplicates"))); // Create an index, since this is required by the indel realigner this.log.info("Creating BAM indexes..."); bamFilesRDD = bamFilesRDD.map(new BamIndexer()); bamFilesRDD = realignIndels(bamFilesRDD); bamFilesRDD = performBQSR(bamFilesRDD); this.log.info("Preprocessing finished!"); return bamFilesRDD; } return null; } public JavaRDD<File> performBQSR(JavaRDD<File> bamFilesRDD) { this.log.info("Creating targets on which to perform BQSR..."); JavaRDD<Tuple2<File, File>> bqsrTables = bamFilesRDD.map(new BQSRTargetGenerator(this.pathToReference, this.knownSites, this.toolsExtraArgs.getProperty("BaseRecalibrator"))); this.log.info("Performing BQSR..."); return bqsrTables.map(new BQSR(this.pathToReference, this.toolsExtraArgs.getProperty("PrintReads"))); } public JavaRDD<File> realignIndels(JavaRDD<File> bamFilesRDD) { this.log.info("Creating indel targets..."); JavaRDD<Tuple2<File, File>> indelTargetsRDD = bamFilesRDD.map(new IndelTargetCreator(this.pathToReference, this.toolsExtraArgs.getProperty("RealignerTargetCreator"))); this.log.info("Realigning indels..."); return indelTargetsRDD.map(new RealignIndels(this.pathToReference, this.toolsExtraArgs.getProperty("IndelRealigner"))); } /* Performs the variant discovery stage of the GATK pipeline. * See the following link for details: https://www.broadinstitute.org/gatk/guide/bp_step.php?p=2 * * @param preprocessedBAMFiles a spark RDD containing the File object for each preprocessed BAM file. * */ public JavaRDD<File> discoverVariants(JavaRDD<File> preprocessedBAMFiles) { this.log.info("Starting variant discovery!"); this.log.info("Running HaplotypeCaller..."); JavaRDD<File> variantsVCFFiles = preprocessedBAMFiles.map(new HaplotypeCaller(this.pathToReference, this.toolsExtraArgs.getProperty("HaplotypeCaller"))); return variantsVCFFiles; } /* * Handles the initialization of the pipeline, as well as running the actual pipeline in the correct order. * * @param pathToSAMFiles the path to the folder containing the SAM files created by the aligner. * */ public List<File> runPipeline(String pathToSAMFiles) { JavaRDD<File> preprocessedBAMFiles = preprocessSAMFiles(pathToSAMFiles); if (preprocessedBAMFiles != null) { JavaRDD<File> variantsVCFFiles = discoverVariants(preprocessedBAMFiles); List<File> outputFiles = variantsVCFFiles.collect(); return outputFiles; } else { System.err.println("Could not preprocess SAM files!"); return null; } } public static Options initCommandLineOptions() { Options options = new Options(); Option reference = new Option("R", "Reference", true, "The path to the reference file."); reference.setRequired(true); options.addOption(reference); Option inputFolder = new Option("I", "InputFolder", true, "The path to the folder containing the input files."); inputFolder.setRequired(true); options.addOption(inputFolder); Option knownSites = new Option("S", "KnownSites", true, "The path to the file containing known sites (used in BQSR)."); knownSites.setRequired(true); options.addOption(knownSites); Option configFile = new Option("C", "ConfigFile", true, "The path to the file configuration file."); configFile.setRequired(true); options.addOption(configFile); return options; } public static CommandLine parseCommandLineOptions(Options options, String[] argv) { CommandLineParser parser = new GnuParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(options, argv); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("Sparkcaller", "", options, "See https://github.com/UNINETT/daas-apps/tree/master/genomics for documentation.", true); System.exit(1); return null; } return cmd; } public static void main(String argv[]) throws Exception { Options options = SparkCaller.initCommandLineOptions(); CommandLine cmdArgs = SparkCaller.parseCommandLineOptions(options, argv); JavaSparkContext sparkContext = SparkCaller.initSpark("SparkCaller"); String pathToReference = cmdArgs.getOptionValue("Reference"); String pathToSAMFiles = cmdArgs.getOptionValue("InputFolder"); String knownSites = cmdArgs.getOptionValue("KnownSites"); String configFilepath = cmdArgs.getOptionValue("ConfigFile"); Properties toolsExtraArguments = Utils.loadConfigFile(configFilepath); SparkCaller caller = new SparkCaller(sparkContext, pathToReference, knownSites, toolsExtraArguments); caller.runPipeline(pathToSAMFiles); } public static JavaSparkContext initSpark(String appName) { SparkConf conf = new SparkConf().setAppName(appName); JavaSparkContext sparkContext = new JavaSparkContext(conf); return sparkContext; } }
genomics/sparkcaller/src/main/java/com/github/sparkcaller/SparkCaller.java
package com.github.sparkcaller; import com.github.sparkcaller.preprocessing.*; import com.github.sparkcaller.variantdiscovery.HaplotypeCaller; import org.apache.commons.cli.*; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.log4j.Logger; import scala.Tuple2; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Properties; public class SparkCaller { final private JavaSparkContext sparkContext; final private Logger log; private String pathToReference; private String knownSites; private Properties toolsExtraArgs; /* * The SparkCaller is used for managing the workflow * @param pathToReference the path to the file to use as a reference. * Keep in mind that this file has to be reachable by all nodes, and has to be indexed. * * @param pathToReference the path to the file containing the dbsnp to use when ex. performing BQSR. * Keep in mind that this file has to be reachable by all nodes. * * @param toolsExtraArguments the Properties object containing strings of extra arguments to pass to each tool. * */ public SparkCaller(JavaSparkContext sparkContext, String pathToReference, String knownSites, Properties toolsExtraArguments) { this.sparkContext = sparkContext; this.log = Logger.getLogger(this.getClass()); this.pathToReference = pathToReference; this.toolsExtraArgs = toolsExtraArguments; this.knownSites = knownSites; } /* Performs the preprocessing stage of the GATK pipeline. * This is performed in a simple scatter-gather manner. * See the following link for details: https://www.broadinstitute.org/gatk/guide/bp_step.php?p=1 * * @param pathToSAMFiles the path to the folder containing the SAM files created by the aligner. * */ public JavaRDD<File> preprocessSAMFiles(String pathToSAMFiles) { this.log.info("Preprocessing SAM files!"); // Get all the SAM files generated by the aligner ArrayList<File> samFiles = Utils.getFilesInFolder(pathToSAMFiles, "sam"); if (samFiles != null) { this.log.info("Distributing the SAM files to the nodes..."); JavaRDD<File> samFilesRDD = sparkContext.parallelize(samFiles); this.log.info("Converting the SAM files to sorted BAM files..."); JavaRDD<File> bamFilesRDD = samFilesRDD.map(new SamToSortedBam()); this.log.info("Marking duplicates..."); bamFilesRDD = bamFilesRDD.map(new DuplicateMarker(this.toolsExtraArgs.getProperty("MarkDuplicates"))); // Create an index, since this is required by the indel realigner this.log.info("Creating BAM indexes..."); bamFilesRDD = bamFilesRDD.map(new BamIndexer()); bamFilesRDD = realignIndels(bamFilesRDD); bamFilesRDD = performBQSR(bamFilesRDD); this.log.info("Preprocessing finished!"); return bamFilesRDD; } return null; } public JavaRDD<File> performBQSR(JavaRDD<File> bamFilesRDD) { this.log.info("Creating targets on which to perform BQSR..."); JavaRDD<Tuple2<File, File>> bqsrTables = bamFilesRDD.map(new BQSRTargetGenerator(this.pathToReference, this.knownSites, this.toolsExtraArgs.getProperty("BaseRecalibrator"))); this.log.info("Performing BQSR..."); bamFilesRDD = bqsrTables.map(new BQSR(this.pathToReference, this.toolsExtraArgs.getProperty("PrintReads"))); return bamFilesRDD; } public JavaRDD<File> realignIndels(JavaRDD<File> bamFilesRDD) { this.log.info("Creating indel targets..."); JavaRDD<Tuple2<File, File>> indelTargetsRDD = bamFilesRDD.map(new IndelTargetCreator(this.pathToReference, this.toolsExtraArgs.getProperty("RealignerTargetCreator"))); this.log.info("Realigning indels..."); bamFilesRDD = indelTargetsRDD.map(new RealignIndels(this.pathToReference, this.toolsExtraArgs.getProperty("IndelRealigner"))); return bamFilesRDD; } /* Performs the variant discovery stage of the GATK pipeline. * See the following link for details: https://www.broadinstitute.org/gatk/guide/bp_step.php?p=2 * * @param preprocessedBAMFiles a spark RDD containing the File object for each preprocessed BAM file. * */ public JavaRDD<File> discoverVariants(JavaRDD<File> preprocessedBAMFiles) { this.log.info("Starting variant discovery!"); this.log.info("Running HaplotypeCaller..."); JavaRDD<File> variantsVCFFiles = preprocessedBAMFiles.map(new HaplotypeCaller(this.pathToReference, this.toolsExtraArgs.getProperty("HaplotypeCaller"))); return variantsVCFFiles; } /* * Handles the initialization of the pipeline, as well as running the actual pipeline in the correct order. * * @param pathToSAMFiles the path to the folder containing the SAM files created by the aligner. * */ public List<File> runPipeline(String pathToSAMFiles) { JavaRDD<File> preprocessedBAMFiles = preprocessSAMFiles(pathToSAMFiles); if (preprocessedBAMFiles != null) { JavaRDD<File> variantsVCFFiles = discoverVariants(preprocessedBAMFiles); List<File> outputFiles = variantsVCFFiles.collect(); return outputFiles; } else { System.err.println("Could not preprocess SAM files!"); return null; } } public static Options initCommandLineOptions() { Options options = new Options(); Option reference = new Option("R", "Reference", true, "The path to the reference file."); reference.setRequired(true); options.addOption(reference); Option inputFolder = new Option("I", "InputFolder", true, "The path to the folder containing the input files."); inputFolder.setRequired(true); options.addOption(inputFolder); Option knownSites = new Option("S", "KnownSites", true, "The path to the file containing known sites (used in BQSR)."); knownSites.setRequired(true); options.addOption(knownSites); Option configFile = new Option("C", "ConfigFile", true, "The path to the file configuration file."); configFile.setRequired(true); options.addOption(configFile); return options; } public static CommandLine parseCommandLineOptions(Options options, String[] argv) { CommandLineParser parser = new GnuParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(options, argv); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("Sparkcaller", "", options, "See https://github.com/UNINETT/daas-apps/tree/master/genomics for documentation.", true); System.exit(1); return null; } return cmd; } public static void main(String argv[]) throws Exception { Options options = SparkCaller.initCommandLineOptions(); CommandLine cmdArgs = SparkCaller.parseCommandLineOptions(options, argv); JavaSparkContext sparkContext = SparkCaller.initSpark("SparkCaller"); String pathToReference = cmdArgs.getOptionValue("Reference"); String pathToSAMFiles = cmdArgs.getOptionValue("InputFolder"); String knownSites = cmdArgs.getOptionValue("KnownSites"); String configFilepath = cmdArgs.getOptionValue("ConfigFile"); Properties toolsExtraArguments = Utils.loadConfigFile(configFilepath); SparkCaller caller = new SparkCaller(sparkContext, pathToReference, knownSites, toolsExtraArguments); caller.runPipeline(pathToSAMFiles); } public static JavaSparkContext initSpark(String appName) { SparkConf conf = new SparkConf().setAppName(appName); JavaSparkContext sparkContext = new JavaSparkContext(conf); return sparkContext; } }
[Genomics]: Stop using temporary variables in some places where it is not necessary and where it does not work as documentation.
genomics/sparkcaller/src/main/java/com/github/sparkcaller/SparkCaller.java
[Genomics]: Stop using temporary variables in some places where it is not necessary and where it does not work as documentation.
<ide><path>enomics/sparkcaller/src/main/java/com/github/sparkcaller/SparkCaller.java <ide> this.toolsExtraArgs.getProperty("BaseRecalibrator"))); <ide> <ide> this.log.info("Performing BQSR..."); <del> bamFilesRDD = bqsrTables.map(new BQSR(this.pathToReference, this.toolsExtraArgs.getProperty("PrintReads"))); <del> <del> return bamFilesRDD; <add> return bqsrTables.map(new BQSR(this.pathToReference, this.toolsExtraArgs.getProperty("PrintReads"))); <ide> } <ide> <ide> public JavaRDD<File> realignIndels(JavaRDD<File> bamFilesRDD) { <ide> this.toolsExtraArgs.getProperty("RealignerTargetCreator"))); <ide> <ide> this.log.info("Realigning indels..."); <del> bamFilesRDD = indelTargetsRDD.map(new RealignIndels(this.pathToReference, <add> return indelTargetsRDD.map(new RealignIndels(this.pathToReference, <ide> this.toolsExtraArgs.getProperty("IndelRealigner"))); <del> <del> return bamFilesRDD; <ide> } <ide> <ide> /* Performs the variant discovery stage of the GATK pipeline.
JavaScript
isc
72aefc2425204a3972c77e9bdc1f84e4c896537b
0
mcollina/mqemitter,mcollina/mqemitter
'use strict' module.exports = function abstractTests (opts) { var builder = opts.builder var test = opts.test test('support on and emit', function (t) { t.plan(4) const e = builder() const expected = { topic: 'hello world', payload: { my: 'message' } } e.on('hello world', function (message, cb) { t.equal(e.current, 1, 'number of current messages') t.deepEqual(message, expected) t.equal(this, e) cb() }, function () { e.emit(expected, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support multiple subscribers', function (t) { t.plan(3) const e = builder() const expected = { topic: 'hello world', payload: { my: 'message' } } e.on('hello world', function (message, cb) { t.ok(message, 'message received') cb() }, function () { e.on('hello world', function (message, cb) { t.ok(message, 'message received') cb() }, function () { e.emit(expected, function () { e.close(function () { t.pass('closed') }) }) }) }) }) test('support multiple subscribers and unsubscribers', function (t) { t.plan(2) const e = builder() const expected = { topic: 'hello world', payload: { my: 'message' } } function first (message, cb) { t.fail('first listener should not receive any events') cb() } function second (message, cb) { t.ok(message, 'second listener must receive the message') cb() e.close(function () { t.pass('closed') }) } e.on('hello world', first, function () { e.on('hello world', second, function () { e.removeListener('hello world', first, function () { e.emit(expected) }) }) }) }) test('removeListener', function (t) { t.plan(1) const e = builder() const expected = { topic: 'hello world', payload: { my: 'message' } } var toRemoveCalled = false function toRemove (message, cb) { toRemoveCalled = true cb() } e.on('hello world', function (message, cb) { cb() }, function () { e.on('hello world', toRemove, function () { e.removeListener('hello world', toRemove, function () { e.emit(expected, function () { e.close(function () { t.notOk(toRemoveCalled, 'the toRemove function must not be called') }) }) }) }) }) }) test('without a callback on emit and on', function (t) { t.plan(1) const e = builder() const expected = { topic: 'hello world', payload: { my: 'message' } } e.on('hello world', function (message, cb) { cb() e.close(function () { t.pass('closed') }) }) setTimeout(function () { e.emit(expected) }, 100) }) test('without any listeners', function (t) { t.plan(2) const e = builder() const expected = { topic: 'hello world', payload: { my: 'message' } } e.emit(expected) t.equal(e.current, 0, 'reset the current messages trackers') e.close(function () { t.pass('closed') }) }) test('support one level wildcard', function (t) { t.plan(2) const e = builder() const expected = { topic: 'hello/world', payload: { my: 'message' } } e.on('hello/+', function (message, cb) { t.equal(message.topic, 'hello/world') cb() }, function () { // this will not be catched e.emit({ topic: 'hello/my/world' }) // this will be catched e.emit(expected, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support one level wildcard - not match empty words', function (t) { t.plan(2) const e = builder({ matchEmptyLevels: false }) const expected = { topic: 'hello/dummy/world', payload: { my: 'message' } } e.on('hello/+/world', function (message, cb) { t.equal(message.topic, 'hello/dummy/world') cb() }, function () { // this will not be catched e.emit({ topic: 'hello//world' }) // this will be catched e.emit(expected, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support one level wildcard - match empty words', function (t) { t.plan(3) const e = builder({ matchEmptyLevels: true }) e.on('hello/+/world', function (message, cb) { const topic = message.topic if (topic === 'hello//world' || topic === 'hello/dummy/world') { t.pass('received ' + topic) } cb() }, function () { // this will be catched e.emit({ topic: 'hello//world' }) // this will be catched e.emit({ topic: 'hello/dummy/world' }, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support one level wildcard - match empty words', function (t) { t.plan(2) const e = builder({ matchEmptyLevels: true }) e.on('hello/+', function (message, cb) { t.equal(message.topic, 'hello/') cb() }, function () { // this will be catched e.emit({ topic: 'hello/' }, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support one level wildcard - not match empty words', function (t) { t.plan(1) const e = builder({ matchEmptyLevels: false }) e.on('hello/+', function (message, cb) { t.fail('should not catch') cb() }, function () { // this will not be catched e.emit({ topic: 'hello/' }, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support changing one level wildcard', function (t) { t.plan(2) const e = builder({ wildcardOne: '~' }) const expected = { topic: 'hello/world', payload: { my: 'message' } } e.on('hello/~', function (message, cb) { t.equal(message.topic, 'hello/world') cb() }, function () { e.emit(expected, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support deep wildcard', function (t) { t.plan(2) const e = builder() const expected = { topic: 'hello/my/world', payload: { my: 'message' } } e.on('hello/#', function (message, cb) { t.equal(message.topic, 'hello/my/world') cb() }, function () { e.emit(expected, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support deep wildcard without separator', function (t) { t.plan(2) const e = builder() const expected = { topic: 'hello', payload: { my: 'message' } } e.on('#', function (message, cb) { t.equal(message.topic, expected.topic) cb() }, function () { e.emit(expected, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support deep wildcard - match empty words', function (t) { t.plan(2) const e = builder({ matchEmptyLevels: true }) const expected = { topic: 'hello', payload: { my: 'message' } } const wrong = { topic: 'hellooo', payload: { my: 'message' } } e.on('hello/#', function (message, cb) { t.equal(message.topic, expected.topic) cb() }, function () { e.emit(wrong) // this should not be received e.emit(expected, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support changing deep wildcard', function (t) { t.plan(2) const e = builder({ wildcardSome: '*' }) const expected = { topic: 'hello/my/world', payload: { my: 'message' } } e.on('hello/*', function (message, cb) { t.equal(message.topic, 'hello/my/world') cb() }, function () { e.emit(expected, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support changing the level separator', function (t) { t.plan(2) const e = builder({ separator: '~' }) const expected = { topic: 'hello~world', payload: { my: 'message' } } e.on('hello~+', function (message, cb) { t.equal(message.topic, 'hello~world') cb() }, function () { e.emit(expected, function () { e.close(function () { t.pass('closed') }) }) }) }) test('close support', function (t) { const e = builder() var check = false t.notOk(e.closed, 'must have a false closed property') e.close(function () { t.ok(check, 'must delay the close callback') t.ok(e.closed, 'must have a true closed property') t.end() }) check = true }) test('emit after close errors', function (t) { const e = builder() e.close(function () { e.emit({ topic: 'hello' }, function (err) { t.ok(err, 'must return an error') t.end() }) }) }) test('support multiple subscribers with wildcards', function (t) { const e = builder() const expected = { topic: 'hello/world', payload: { my: 'message' } } var firstCalled = false var secondCalled = false e.on('hello/#', function (message, cb) { t.notOk(firstCalled, 'first subscriber must only be called once') firstCalled = true cb() }) e.on('hello/+', function (message, cb) { t.notOk(secondCalled, 'second subscriber must only be called once') secondCalled = true cb() }, function () { e.emit(expected, function () { e.close(function () { t.end() }) }) }) }) test('support multiple subscribers with wildcards (deep)', function (t) { const e = builder() const expected = { topic: 'hello/my/world', payload: { my: 'message' } } var firstCalled = false var secondCalled = false e.on('hello/#', function (message, cb) { t.notOk(firstCalled, 'first subscriber must only be called once') firstCalled = true cb() }) e.on('hello/+/world', function (message, cb) { t.notOk(secondCalled, 'second subscriber must only be called once') secondCalled = true cb() }, function () { e.emit(expected, function () { e.close(function () { t.end() }) }) }) }) test('emit & receive buffers', function (t) { const e = builder() const msg = Buffer.from('hello') const expected = { topic: 'hello', payload: msg } e.on('hello', function (message, cb) { t.deepEqual(msg, message.payload) cb() }, function () { e.emit(expected, function () { e.close(function () { t.end() }) }) }) }) test('packets are emitted in order', function (t) { const e = builder() const total = 10000 const topic = 'test' var received = 0 e.on(topic, function (msg, cb) { var fail = false if (received !== msg.payload) { t.fail(`leak detected. Count: ${received} - Payload: ${msg.payload}`) fail = true } received++ if (fail || received === total) { e.close(function () { t.end() }) } cb() }) for (let payload = 0; payload < total; payload++) { e.emit({ topic, payload }) } }) test('calling emit without cb when closed doesn\'t throw error', function (t) { const e = builder() const msg = Buffer.from('hello') const expected = { topic: 'hello', payload: msg } e.close(function () { try { e.emit(expected) } catch (error) { t.error('throws error') } t.end() }) }) }
abstractTest.js
'use strict' module.exports = function abstractTests (opts) { var builder = opts.builder var test = opts.test test('support on and emit', function (t) { t.plan(4) const e = builder() const expected = { topic: 'hello world', payload: { my: 'message' } } e.on('hello world', function (message, cb) { t.equal(e.current, 1, 'number of current messages') t.deepEqual(message, expected) t.equal(this, e) cb() }, function () { e.emit(expected, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support multiple subscribers', function (t) { t.plan(3) const e = builder() const expected = { topic: 'hello world', payload: { my: 'message' } } e.on('hello world', function (message, cb) { t.ok(message, 'message received') cb() }, function () { e.on('hello world', function (message, cb) { t.ok(message, 'message received') cb() }, function () { e.emit(expected, function () { e.close(function () { t.pass('closed') }) }) }) }) }) test('support multiple subscribers and unsubscribers', function (t) { t.plan(2) const e = builder() const expected = { topic: 'hello world', payload: { my: 'message' } } function first (message, cb) { t.fail('first listener should not receive any events') cb() } function second (message, cb) { t.ok(message, 'second listener must receive the message') cb() e.close(function () { t.pass('closed') }) } e.on('hello world', first, function () { e.on('hello world', second, function () { e.removeListener('hello world', first, function () { e.emit(expected) }) }) }) }) test('removeListener', function (t) { t.plan(1) const e = builder() const expected = { topic: 'hello world', payload: { my: 'message' } } var toRemoveCalled = false function toRemove (message, cb) { toRemoveCalled = true cb() } e.on('hello world', function (message, cb) { cb() }, function () { e.on('hello world', toRemove, function () { e.removeListener('hello world', toRemove, function () { e.emit(expected, function () { e.close(function () { t.notOk(toRemoveCalled, 'the toRemove function must not be called') }) }) }) }) }) }) test('without a callback on emit and on', function (t) { t.plan(1) const e = builder() const expected = { topic: 'hello world', payload: { my: 'message' } } e.on('hello world', function (message, cb) { cb() e.close(function () { t.pass('closed') }) }) setTimeout(function () { e.emit(expected) }, 100) }) test('without any listeners', function (t) { t.plan(2) const e = builder() const expected = { topic: 'hello world', payload: { my: 'message' } } e.emit(expected) t.equal(e.current, 0, 'reset the current messages trackers') e.close(function () { t.pass('closed') }) }) test('support one level wildcard', function (t) { t.plan(2) const e = builder() const expected = { topic: 'hello/world', payload: { my: 'message' } } e.on('hello/+', function (message, cb) { t.equal(message.topic, 'hello/world') cb() }, function () { // this will not be catched e.emit({ topic: 'hello/my/world' }) // this will be catched e.emit(expected, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support one level wildcard - not match empty words', function (t) { t.plan(2) const e = builder({ matchEmptyLevels: false }) const expected = { topic: 'hello/dummy/world', payload: { my: 'message' } } e.on('hello/+/world', function (message, cb) { t.equal(message.topic, 'hello/dummy/world') cb() }, function () { // this will not be catched e.emit({ topic: 'hello//world' }) // this will be catched e.emit(expected, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support one level wildcard - match empty words', function (t) { t.plan(3) const e = builder({ matchEmptyLevels: true }) e.on('hello/+/world', function (message, cb) { const topic = message.topic if (topic === 'hello//world' || topic === 'hello/dummy/world') { t.pass('received ' + topic) } cb() }, function () { // this will be catched e.emit({ topic: 'hello//world' }) // this will be catched e.emit({ topic: 'hello/dummy/world' }, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support one level wildcard - match empty words', function (t) { t.plan(2) const e = builder({ matchEmptyLevels: true }) e.on('hello/+', function (message, cb) { t.equal(message.topic, 'hello/') cb() }, function () { // this will be catched e.emit({ topic: 'hello/' }, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support one level wildcard - not match empty words', function (t) { t.plan(1) const e = builder({ matchEmptyLevels: false }) e.on('hello/+', function (message, cb) { t.fail('should not catch') cb() }, function () { // this will not be catched e.emit({ topic: 'hello/' }, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support changing one level wildcard', function (t) { t.plan(2) const e = builder({ wildcardOne: '~' }) const expected = { topic: 'hello/world', payload: { my: 'message' } } e.on('hello/~', function (message, cb) { t.equal(message.topic, 'hello/world') cb() }, function () { e.emit(expected, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support deep wildcard', function (t) { t.plan(2) const e = builder() const expected = { topic: 'hello/my/world', payload: { my: 'message' } } e.on('hello/#', function (message, cb) { t.equal(message.topic, 'hello/my/world') cb() }, function () { e.emit(expected, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support deep wildcard without separator', function (t) { t.plan(2) const e = builder() const expected = { topic: 'hello', payload: { my: 'message' } } e.on('#', function (message, cb) { t.equal(message.topic, expected.topic) cb() }, function () { e.emit(expected, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support deep wildcard - match empty words', function (t) { t.plan(2) const e = builder({ matchEmptyLevels: true }) const expected = { topic: 'hello', payload: { my: 'message' } } const wrong = { topic: 'hellooo', payload: { my: 'message' } } e.on('hello/#', function (message, cb) { t.equal(message.topic, expected.topic) cb() }, function () { e.emit(wrong) // this should not be received e.emit(expected, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support changing deep wildcard', function (t) { t.plan(2) const e = builder({ wildcardSome: '*' }) const expected = { topic: 'hello/my/world', payload: { my: 'message' } } e.on('hello/*', function (message, cb) { t.equal(message.topic, 'hello/my/world') cb() }, function () { e.emit(expected, function () { e.close(function () { t.pass('closed') }) }) }) }) test('support changing the level separator', function (t) { t.plan(2) const e = builder({ separator: '~' }) const expected = { topic: 'hello~world', payload: { my: 'message' } } e.on('hello~+', function (message, cb) { t.equal(message.topic, 'hello~world') cb() }, function () { e.emit(expected, function () { e.close(function () { t.pass('closed') }) }) }) }) test('close support', function (t) { const e = builder() var check = false t.notOk(e.closed, 'must have a false closed property') e.close(function () { t.ok(check, 'must delay the close callback') t.ok(e.closed, 'must have a true closed property') t.end() }) check = true }) test('emit after close errors', function (t) { const e = builder() e.close(function () { e.emit({ topic: 'hello' }, function (err) { t.ok(err, 'must return an error') t.end() }) }) }) test('support multiple subscribers with wildcards', function (t) { const e = builder() const expected = { topic: 'hello/world', payload: { my: 'message' } } var firstCalled = false var secondCalled = false e.on('hello/#', function (message, cb) { t.notOk(firstCalled, 'first subscriber must only be called once') firstCalled = true cb() }) e.on('hello/+', function (message, cb) { t.notOk(secondCalled, 'second subscriber must only be called once') secondCalled = true cb() }, function () { e.emit(expected, function () { e.close(function () { t.end() }) }) }) }) test('support multiple subscribers with wildcards (deep)', function (t) { const e = builder() const expected = { topic: 'hello/my/world', payload: { my: 'message' } } var firstCalled = false var secondCalled = false e.on('hello/#', function (message, cb) { t.notOk(firstCalled, 'first subscriber must only be called once') firstCalled = true cb() }) e.on('hello/+/world', function (message, cb) { t.notOk(secondCalled, 'second subscriber must only be called once') secondCalled = true cb() }, function () { e.emit(expected, function () { e.close(function () { t.end() }) }) }) }) test('emit & receive buffers', function (t) { const e = builder() const msg = Buffer.from('hello') const expected = { topic: 'hello', payload: msg } e.on('hello', function (message, cb) { t.deepEqual(msg, message.payload) cb() }, function () { e.emit(expected, function () { e.close(function () { t.end() }) }) }) }) test('calling emit without cb when closed doesn\'t throw error', function (t) { const e = builder() const msg = Buffer.from('hello') const expected = { topic: 'hello', payload: msg } e.close(function () { try { e.emit(expected) } catch (error) { t.error('throws error') } t.end() }) }) }
fix: check emitted packets order to avoid leaks (#34)
abstractTest.js
fix: check emitted packets order to avoid leaks (#34)
<ide><path>bstractTest.js <ide> }) <ide> }) <ide> <add> test('packets are emitted in order', function (t) { <add> const e = builder() <add> const total = 10000 <add> const topic = 'test' <add> <add> var received = 0 <add> <add> e.on(topic, function (msg, cb) { <add> var fail = false <add> if (received !== msg.payload) { <add> t.fail(`leak detected. Count: ${received} - Payload: ${msg.payload}`) <add> fail = true <add> } <add> <add> received++ <add> <add> if (fail || received === total) { <add> e.close(function () { <add> t.end() <add> }) <add> } <add> cb() <add> }) <add> <add> for (let payload = 0; payload < total; payload++) { <add> e.emit({ topic, payload }) <add> } <add> }) <add> <ide> test('calling emit without cb when closed doesn\'t throw error', function (t) { <ide> const e = builder() <ide> const msg = Buffer.from('hello')
Java
apache-2.0
8d836fd0dffe4116064dc7b0216ddb5db883c859
0
SAGROUP2/apps-android-wikipedia,Duct-and-rice/KrswtkhrWiki4Android,dbrant/apps-android-wikipedia,Duct-and-rice/KrswtkhrWiki4Android,anirudh24seven/apps-android-wikipedia,dbrant/apps-android-wikipedia,anirudh24seven/apps-android-wikipedia,carloshwa/apps-android-wikipedia,anirudh24seven/apps-android-wikipedia,anirudh24seven/apps-android-wikipedia,parvez3019/apps-android-wikipedia,carloshwa/apps-android-wikipedia,SAGROUP2/apps-android-wikipedia,anirudh24seven/apps-android-wikipedia,dbrant/apps-android-wikipedia,wikimedia/apps-android-wikipedia,carloshwa/apps-android-wikipedia,SAGROUP2/apps-android-wikipedia,Wikinaut/wikipedia-app,parvez3019/apps-android-wikipedia,Duct-and-rice/KrswtkhrWiki4Android,SAGROUP2/apps-android-wikipedia,Wikinaut/wikipedia-app,Wikinaut/wikipedia-app,dbrant/apps-android-wikipedia,Wikinaut/wikipedia-app,SAGROUP2/apps-android-wikipedia,parvez3019/apps-android-wikipedia,dbrant/apps-android-wikipedia,Duct-and-rice/KrswtkhrWiki4Android,wikimedia/apps-android-wikipedia,wikimedia/apps-android-wikipedia,Duct-and-rice/KrswtkhrWiki4Android,wikimedia/apps-android-wikipedia,carloshwa/apps-android-wikipedia,Wikinaut/wikipedia-app,parvez3019/apps-android-wikipedia,carloshwa/apps-android-wikipedia,parvez3019/apps-android-wikipedia
package org.wikipedia.test; import android.content.Intent; import android.test.ActivityUnitTestCase; import org.mediawiki.api.json.ApiException; import org.wikipedia.page.PageTitle; import org.wikipedia.Site; import org.wikipedia.WikipediaApp; import org.wikipedia.editing.DoEditTask; import org.wikipedia.editing.EditTokenStorage; import org.wikipedia.editing.EditingResult; import org.wikipedia.editing.FetchSectionWikitextTask; import org.wikipedia.login.LoginResult; import org.wikipedia.login.LoginTask; import org.wikipedia.login.User; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class DoEditTaskTests extends ActivityUnitTestCase<TestDummyActivity> { private static final int TASK_COMPLETION_TIMEOUT = 20000; private static final int SECTION_ID = 3; public DoEditTaskTests() { super(TestDummyActivity.class); } public void testEdit() throws Throwable { startActivity(new Intent(), null, null); final CountDownLatch completionLatch = new CountDownLatch(1); runTestOnUiThread(new Runnable() { @Override public void run() { doSave(completionLatch); } }); assertTrue(completionLatch.await(TASK_COMPLETION_TIMEOUT, TimeUnit.MILLISECONDS)); } private void doSave(final CountDownLatch completionLatch) { final PageTitle title = new PageTitle(null, "Test_page_for_app_testing/Section1", new Site("test.wikipedia.org")); final String wikitext = "== Section 2 ==\n\nEditing section INSERT RANDOM & HERE test at " + System.currentTimeMillis(); final WikipediaApp app = (WikipediaApp) getInstrumentation().getTargetContext().getApplicationContext(); app.getEditTokenStorage().get(title.getSite(), new EditTokenStorage.TokenRetrievedCallback() { @Override public void onTokenRetrieved(String token) { new DoEditTask(getInstrumentation().getTargetContext(), title, wikitext, SECTION_ID, token, "", false) { @Override public void onFinish(EditingResult result) { assertNotNull(result); assertEquals("Success", result.getResult()); new FetchSectionWikitextTask(getInstrumentation().getTargetContext(), title, SECTION_ID) { @Override public void onFinish(String result) { assertNotNull(result); assertEquals(wikitext, result); completionLatch.countDown(); } }.execute(); } @Override public void onCatch(Throwable caught) { // borrowed mainly from EditSectionActivity: final WikipediaApp app = WikipediaApp.getInstance(); if (caught instanceof ApiException) { ApiException ee = (ApiException) caught; if (app.getUserInfoStorage().isLoggedIn() && "badtoken".equals(ee.getCode())) { // looks like our session expired. app.getEditTokenStorage().clearAllTokens(); app.getCookieManager().clearAllCookies(); User user = app.getUserInfoStorage().getUser(); new LoginTask(app, app.getPrimarySite(), user.getUsername(), user.getPassword()) { @Override public void onFinish(LoginResult result) { assertEquals("Login failed!", "Success", result.getCode()); try { doSave(completionLatch); } catch (Throwable throwable) { fail("Retry failed: " + throwable.getMessage()); } } }.execute(); } } else { throw new RuntimeException(caught); } } }.execute(); } @Override public void onTokenFailed(Throwable caught) { fail("Fetching token failed: " + caught.getMessage()); } }); } }
wikipedia/src/androidTest/java/org/wikipedia/test/DoEditTaskTests.java
package org.wikipedia.test; import android.content.Intent; import android.test.ActivityUnitTestCase; import org.mediawiki.api.json.ApiException; import org.wikipedia.page.PageTitle; import org.wikipedia.Site; import org.wikipedia.WikipediaApp; import org.wikipedia.editing.DoEditTask; import org.wikipedia.editing.EditTokenStorage; import org.wikipedia.editing.EditingException; import org.wikipedia.editing.EditingResult; import org.wikipedia.editing.FetchSectionWikitextTask; import org.wikipedia.login.LoginResult; import org.wikipedia.login.LoginTask; import org.wikipedia.login.User; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class DoEditTaskTests extends ActivityUnitTestCase<TestDummyActivity> { private static final int TASK_COMPLETION_TIMEOUT = 20000; private static final int SECTION_ID = 3; public DoEditTaskTests() { super(TestDummyActivity.class); } public void testEdit() throws Throwable { startActivity(new Intent(), null, null); final CountDownLatch completionLatch = new CountDownLatch(1); runTestOnUiThread(new Runnable() { @Override public void run() { doSave(completionLatch); } }); assertTrue(completionLatch.await(TASK_COMPLETION_TIMEOUT, TimeUnit.MILLISECONDS)); } private void doSave(final CountDownLatch completionLatch) { final PageTitle title = new PageTitle(null, "Test_page_for_app_testing/Section1", new Site("test.wikipedia.org")); final String wikitext = "== Section 2 ==\n\nEditing section INSERT RANDOM & HERE test at " + System.currentTimeMillis(); final WikipediaApp app = (WikipediaApp) getInstrumentation().getTargetContext().getApplicationContext(); app.getEditTokenStorage().get(title.getSite(), new EditTokenStorage.TokenRetrievedCallback() { @Override public void onTokenRetrieved(String token) { new DoEditTask(getInstrumentation().getTargetContext(), title, wikitext, SECTION_ID, token, "", false) { @Override public void onFinish(EditingResult result) { assertNotNull(result); assertEquals("Success", result.getResult()); new FetchSectionWikitextTask(getInstrumentation().getTargetContext(), title, SECTION_ID) { @Override public void onFinish(String result) { assertNotNull(result); assertEquals(wikitext, result); completionLatch.countDown(); } }.execute(); } @Override public void onCatch(Throwable caught) { // borrowed mainly from EditSectionActivity: final WikipediaApp app = WikipediaApp.getInstance(); if (caught instanceof EditingException) { EditingException ee = (EditingException) caught; if (app.getUserInfoStorage().isLoggedIn() && ee.getCode().equals("badtoken")) { // looks like our session expired. app.getEditTokenStorage().clearAllTokens(); app.getCookieManager().clearAllCookies(); User user = app.getUserInfoStorage().getUser(); new LoginTask(app, app.getPrimarySite(), user.getUsername(), user.getPassword()) { @Override public void onFinish(LoginResult result) { assertEquals("Login failed!", "Success", result.getCode()); try { doSave(completionLatch); } catch (Throwable throwable) { fail("Retry failed: " + throwable.getMessage()); } } }.execute(); return; } } if (!(caught instanceof ApiException)) { throw new RuntimeException(caught); } } }.execute(); } @Override public void onTokenFailed(Throwable caught) { fail("Fetching token failed: " + caught.getMessage()); } }); } }
Fix editing tests. Change-Id: I73ca53eeab046e7ddda3d3032813c1e9a0d06f7b
wikipedia/src/androidTest/java/org/wikipedia/test/DoEditTaskTests.java
Fix editing tests.
<ide><path>ikipedia/src/androidTest/java/org/wikipedia/test/DoEditTaskTests.java <ide> import org.wikipedia.WikipediaApp; <ide> import org.wikipedia.editing.DoEditTask; <ide> import org.wikipedia.editing.EditTokenStorage; <del>import org.wikipedia.editing.EditingException; <ide> import org.wikipedia.editing.EditingResult; <ide> import org.wikipedia.editing.FetchSectionWikitextTask; <ide> import org.wikipedia.login.LoginResult; <ide> public void onCatch(Throwable caught) { <ide> // borrowed mainly from EditSectionActivity: <ide> final WikipediaApp app = WikipediaApp.getInstance(); <del> if (caught instanceof EditingException) { <del> EditingException ee = (EditingException) caught; <del> if (app.getUserInfoStorage().isLoggedIn() && ee.getCode().equals("badtoken")) { <add> if (caught instanceof ApiException) { <add> ApiException ee = (ApiException) caught; <add> if (app.getUserInfoStorage().isLoggedIn() && "badtoken".equals(ee.getCode())) { <ide> // looks like our session expired. <ide> app.getEditTokenStorage().clearAllTokens(); <ide> app.getCookieManager().clearAllCookies(); <ide> } <ide> } <ide> }.execute(); <del> return; <ide> } <del> } <del> if (!(caught instanceof ApiException)) { <add> } else { <ide> throw new RuntimeException(caught); <ide> } <ide> }
Java
apache-2.0
1d200bd8ec57a5bc0968e635de685ac4d48bdf0f
0
stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,stefanneuhaus/DependencyCheck,stefanneuhaus/DependencyCheck,stefanneuhaus/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck
/* * This file is part of dependency-check-cli. * * 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. * * Copyright (c) 2012 Jeremy Long. All Rights Reserved. */ package org.owasp.dependencycheck; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.File; import java.io.FileNotFoundException; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.owasp.dependencycheck.reporting.ReportGenerator.Format; import org.owasp.dependencycheck.utils.InvalidSettingException; import org.owasp.dependencycheck.utils.Settings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A utility to parse command line arguments for the DependencyCheck. * * @author Jeremy Long */ //suppress hard-coded password rule @SuppressWarnings("squid:S2068") public final class CliParser { /** * The logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(CliParser.class); /** * The command line. */ private CommandLine line; /** * Indicates whether the arguments are valid. */ private boolean isValid = true; /** * The configured settings. */ private final Settings settings; /** * The supported reported formats. */ private static final String SUPPORTED_FORMATS = "HTML, XML, CSV, JSON, JUNIT, SARIF, or ALL"; /** * Constructs a new CLI Parser object with the configured settings. * * @param settings the configured settings */ public CliParser(Settings settings) { this.settings = settings; } /** * Parses the arguments passed in and captures the results for later use. * * @param args the command line arguments * @throws FileNotFoundException is thrown when a 'file' argument does not * point to a file that exists. * @throws ParseException is thrown when a Parse Exception occurs. */ public void parse(String[] args) throws FileNotFoundException, ParseException { line = parseArgs(args); if (line != null) { validateArgs(); } } /** * Parses the command line arguments. * * @param args the command line arguments * @return the results of parsing the command line arguments * @throws ParseException if the arguments are invalid */ private CommandLine parseArgs(String[] args) throws ParseException { final CommandLineParser parser = new DefaultParser(); final Options options = createCommandLineOptions(); return parser.parse(options, args); } /** * Validates that the command line arguments are valid. * * @throws FileNotFoundException if there is a file specified by either the * SCAN or CPE command line arguments that does not exist. * @throws ParseException is thrown if there is an exception parsing the * command line. */ private void validateArgs() throws FileNotFoundException, ParseException { if (isUpdateOnly() || isRunScan()) { String value = line.getOptionValue(ARGUMENT.CVE_VALID_FOR_HOURS); if (value != null) { try { final int i = Integer.parseInt(value); if (i < 0) { throw new ParseException("Invalid Setting: cveValidForHours must be a number greater than or equal to 0."); } } catch (NumberFormatException ex) { throw new ParseException("Invalid Setting: cveValidForHours must be a number greater than or equal to 0."); } } value = line.getOptionValue(ARGUMENT.CVE_START_YEAR); if (value != null) { try { final int i = Integer.parseInt(value); if (i < 2002) { throw new ParseException("Invalid Setting: cveStartYear must be a number greater than or equal to 2002."); } } catch (NumberFormatException ex) { throw new ParseException("Invalid Setting: cveStartYear must be a number greater than or equal to 2002."); } } } if (isRunScan()) { validatePathExists(getScanFiles(), ARGUMENT.SCAN); validatePathExists(getReportDirectory(), ARGUMENT.OUT); final String pathToCore = getStringArgument(ARGUMENT.PATH_TO_CORE); if (pathToCore != null) { validatePathExists(pathToCore, ARGUMENT.PATH_TO_CORE); } if (line.hasOption(ARGUMENT.OUTPUT_FORMAT)) { String validating = null; try { for (String format : getReportFormat()) { validating = format; Format.valueOf(format); } } catch (IllegalArgumentException ex) { final String msg = String.format("An invalid 'format' of '%s' was specified. " + "Supported output formats are " + SUPPORTED_FORMATS, validating); throw new ParseException(msg); } } final String base = getStringArgument(ARGUMENT.CVE_BASE_URL); final String modified = getStringArgument(ARGUMENT.CVE_MODIFIED_URL); if ((base != null && modified == null) || (base == null && modified != null)) { final String msg = "If one of the CVE URLs is specified they must all be specified; please add the missing CVE URL."; throw new ParseException(msg); } if (line.hasOption(ARGUMENT.SYM_LINK_DEPTH)) { try { final int i = Integer.parseInt(line.getOptionValue(ARGUMENT.SYM_LINK_DEPTH)); if (i < 0) { throw new ParseException("Symbolic Link Depth (symLink) must be greater than zero."); } } catch (NumberFormatException ex) { throw new ParseException("Symbolic Link Depth (symLink) is not a number."); } } } } /** * Validates whether or not the path(s) points at a file that exists; if the * path(s) does not point to an existing file a FileNotFoundException is * thrown. * * @param paths the paths to validate if they exists * @param optType the option being validated (e.g. scan, out, etc.) * @throws FileNotFoundException is thrown if one of the paths being * validated does not exist. */ private void validatePathExists(String[] paths, String optType) throws FileNotFoundException { for (String path : paths) { validatePathExists(path, optType); } } /** * Validates whether or not the path points at a file that exists; if the * path does not point to an existing file a FileNotFoundException is * thrown. * * @param path the paths to validate if they exists * @param argumentName the argument being validated (e.g. scan, out, etc.) * @throws FileNotFoundException is thrown if the path being validated does * not exist. */ private void validatePathExists(String path, String argumentName) throws FileNotFoundException { if (path == null) { isValid = false; final String msg = String.format("Invalid '%s' argument: null", argumentName); throw new FileNotFoundException(msg); } else if (!path.contains("*") && !path.contains("?")) { File f = new File(path); final String[] formats = this.getReportFormat(); if ("o".equalsIgnoreCase(argumentName.substring(0, 1)) && formats.length == 1 && !"ALL".equalsIgnoreCase(formats[0])) { final String checkPath = path.toLowerCase(); if (checkPath.endsWith(".html") || checkPath.endsWith(".xml") || checkPath.endsWith(".htm") || checkPath.endsWith(".csv") || checkPath.endsWith(".json")) { if (f.getParentFile() == null) { f = new File(".", path); } if (!f.getParentFile().isDirectory()) { isValid = false; final String msg = String.format("Invalid '%s' argument: '%s' - directory path does not exist", argumentName, path); throw new FileNotFoundException(msg); } } } else if ("o".equalsIgnoreCase(argumentName.substring(0, 1)) && !f.isDirectory()) { if (f.getParentFile() != null && f.getParentFile().isDirectory() && !f.mkdir()) { isValid = false; final String msg = String.format("Invalid '%s' argument: '%s' - unable to create the output directory", argumentName, path); throw new FileNotFoundException(msg); } if (!f.isDirectory()) { isValid = false; final String msg = String.format("Invalid '%s' argument: '%s' - path does not exist", argumentName, path); throw new FileNotFoundException(msg); } } else if (!f.exists()) { isValid = false; final String msg = String.format("Invalid '%s' argument: '%s' - path does not exist", argumentName, path); throw new FileNotFoundException(msg); } // } else if (path.startsWith("//") || path.startsWith("\\\\")) { // isValid = false; // final String msg = String.format("Invalid '%s' argument: '%s'%nUnable to scan paths that start with '//'.", argumentName, path); // throw new FileNotFoundException(msg); } else if ((path.endsWith("/*") && !path.endsWith("**/*")) || (path.endsWith("\\*") && path.endsWith("**\\*"))) { LOGGER.warn("Possibly incorrect path '{}' from argument '{}' because it ends with a slash star; " + "dependency-check uses ant-style paths", path, argumentName); } } /** * Generates an Options collection that is used to parse the command line * and to display the help message. * * @return the command line options used for parsing the command line */ @SuppressWarnings("static-access") private Options createCommandLineOptions() { final Options options = new Options(); addStandardOptions(options); addAdvancedOptions(options); // addDeprecatedOptions(options); return options; } /** * Adds the standard command line options to the given options collection. * * @param options a collection of command line arguments */ @SuppressWarnings("static-access") private void addStandardOptions(final Options options) { //This is an option group because it can be specified more then once. options.addOptionGroup(newOptionGroup(newOptionWithArg(ARGUMENT.SCAN_SHORT, ARGUMENT.SCAN, "path", "The path to scan - this option can be specified multiple times. Ant style paths are supported (e.g. 'path/**/*.jar'); " + "if using Ant style paths it is highly recommended to quote the argument value."))) .addOptionGroup(newOptionGroup(newOptionWithArg(ARGUMENT.EXCLUDE, "pattern", "Specify an exclusion pattern. This option " + "can be specified multiple times and it accepts Ant style exclusions."))) .addOption(newOptionWithArg(ARGUMENT.PROJECT, "name", "The name of the project being scanned.")) .addOption(newOptionWithArg(ARGUMENT.OUT_SHORT, ARGUMENT.OUT, "path", "The folder to write reports to. This defaults to the current directory. It is possible to set this to a specific " + "file name if the format argument is not set to ALL.")) .addOption(newOptionWithArg(ARGUMENT.OUTPUT_FORMAT_SHORT, ARGUMENT.OUTPUT_FORMAT, "format", "The report format (" + SUPPORTED_FORMATS + "). The default is HTML. Multiple format parameters can be specified.")) .addOption(newOption(ARGUMENT.PRETTY_PRINT, "When specified the JSON and XML report formats will be pretty printed.")) .addOption(newOption(ARGUMENT.VERSION_SHORT, ARGUMENT.VERSION, "Print the version information.")) .addOption(newOption(ARGUMENT.HELP_SHORT, ARGUMENT.HELP, "Print this message.")) .addOption(newOption(ARGUMENT.ADVANCED_HELP, "Print the advanced help message.")) .addOption(newOption(ARGUMENT.DISABLE_AUTO_UPDATE_SHORT, ARGUMENT.DISABLE_AUTO_UPDATE, "Disables the automatic updating of the CPE data.")) .addOption(newOptionWithArg(ARGUMENT.VERBOSE_LOG_SHORT, ARGUMENT.VERBOSE_LOG, "file", "The file path to write verbose logging information.")) .addOptionGroup(newOptionGroup(newOptionWithArg(ARGUMENT.SUPPRESSION_FILES, "file", "The file path to the suppression XML file. This can be specified more then once to utilize multiple suppression files"))) .addOption(newOption(ARGUMENT.EXPERIMENTAL, "Enables the experimental analyzers.")) .addOption(newOptionWithArg(ARGUMENT.FAIL_ON_CVSS, "score", "Specifies if the build should be failed if a CVSS score above a specified level is identified. The default is 11; " + "since the CVSS scores are 0-10, by default the build will never fail.")) .addOption(newOptionWithArg(ARGUMENT.FAIL_JUNIT_ON_CVSS, "score", "Specifies the CVSS score that is considered a failure when generating the junit report. The default is 0.")); } /** * Adds the advanced command line options to the given options collection. * These are split out for purposes of being able to display two different * help messages. * * @param options a collection of command line arguments */ @SuppressWarnings("static-access") private void addAdvancedOptions(final Options options) { options .addOption(newOption(ARGUMENT.UPDATE_ONLY, "Only update the local NVD data cache; no scan will be executed.")) .addOption(newOptionWithArg(ARGUMENT.CVE_BASE_URL, "url", "Base URL for each year’s CVE files (json.gz), the %d will be replaced with the year.")) .addOption(newOptionWithArg(ARGUMENT.CVE_MODIFIED_URL, "url", "URL for the modified CVE (json.gz).")) .addOption(newOptionWithArg(ARGUMENT.CVE_DOWNLOAD_WAIT_TIME, "milliseconds", "Time in milliseconds to wait between downloading from the NVD.")) .addOption(newOptionWithArg(ARGUMENT.CVE_USER, "user", "Credentials for basic authentication to the CVE data.")) .addOption(newOptionWithArg(ARGUMENT.CVE_PASSWORD, "password", "Credentials for basic authentication to the CVE data.")) .addOption(newOptionWithArg(ARGUMENT.PROXY_PORT, "port", "The proxy port to use when downloading resources.")) .addOption(newOptionWithArg(ARGUMENT.PROXY_SERVER, "server", "The proxy server to use when downloading resources.")) .addOption(newOptionWithArg(ARGUMENT.PROXY_USERNAME, "user", "The proxy username to use when downloading resources.")) .addOption(newOptionWithArg(ARGUMENT.PROXY_PASSWORD, "pass", "The proxy password to use when downloading resources.")) .addOption(newOptionWithArg(ARGUMENT.NON_PROXY_HOSTS, "list", "The proxy exclusion list: hostnames (or patterns) for which proxy should not be used. " + "Use pipe, comma or colon as list separator.")) .addOption(newOptionWithArg(ARGUMENT.CONNECTION_TIMEOUT_SHORT, ARGUMENT.CONNECTION_TIMEOUT, "timeout", "The connection timeout (in milliseconds) to use when downloading resources.")) .addOption(newOptionWithArg(ARGUMENT.CONNECTION_STRING, "connStr", "The connection string to the database.")) .addOption(newOptionWithArg(ARGUMENT.DB_NAME, "user", "The username used to connect to the database.")) .addOption(newOptionWithArg(ARGUMENT.DATA_DIRECTORY_SHORT, ARGUMENT.DATA_DIRECTORY, "path", "The location of the H2 Database file. This option should generally not be set.")) .addOption(newOptionWithArg(ARGUMENT.DB_PASSWORD, "password", "The password for connecting to the database.")) .addOption(newOptionWithArg(ARGUMENT.DB_DRIVER, "driver", "The database driver name.")) .addOption(newOptionWithArg(ARGUMENT.DB_DRIVER_PATH, "path", "The path to the database driver; note, this does not need to be set unless the JAR is " + "outside of the classpath.")) .addOption(newOptionWithArg(ARGUMENT.SYM_LINK_DEPTH, "depth", "Sets how deep nested symbolic links will be followed; 0 indicates symbolic links will not be followed.")) .addOption(newOptionWithArg(ARGUMENT.PATH_TO_BUNDLE_AUDIT, "path", "The path to bundle-audit for Gem bundle analysis.")) .addOption(newOptionWithArg(ARGUMENT.PATH_TO_BUNDLE_AUDIT_WORKING_DIRECTORY, "path", "The path to working directory that the bundle-audit command should be executed from when " + "doing Gem bundle analysis.")) .addOption(newOptionWithArg(ARGUMENT.OSSINDEX_USERNAME, "username", "The username to authenticate to Sonatype's OSS Index. If not set the Sonatype OSS Index " + "Analyzer will use an unauthenticated connection.")) .addOption(newOptionWithArg(ARGUMENT.OSSINDEX_PASSWORD, "password", "" + "The password to authenticate to Sonatype's OSS Index. If not set the Sonatype OSS " + "Index Analyzer will use an unauthenticated connection.")) .addOption(newOption(ARGUMENT.RETIRE_JS_FORCEUPDATE, "Force the RetireJS Analyzer to update " + "even if autoupdate is disabled")) .addOption(newOptionWithArg(ARGUMENT.RETIREJS_URL, "url", "The Retire JS Respository URL")) .addOption(newOption(ARGUMENT.RETIREJS_FILTER_NON_VULNERABLE, "Specifies that the Retire JS " + "Analyzer should filter out non-vulnerable JS files from the report.")) .addOption(newOptionWithArg(ARGUMENT.ARTIFACTORY_PARALLEL_ANALYSIS, "true/false", "Whether the Artifactory Analyzer should use parallel analysis.")) .addOption(newOptionWithArg(ARGUMENT.ARTIFACTORY_USES_PROXY, "true/false", "Whether the Artifactory Analyzer should use the proxy.")) .addOption(newOptionWithArg(ARGUMENT.ARTIFACTORY_USERNAME, "username", "The Artifactory username for authentication.")) .addOption(newOptionWithArg(ARGUMENT.ARTIFACTORY_API_TOKEN, "token", "The Artifactory API token.")) .addOption(newOptionWithArg(ARGUMENT.ARTIFACTORY_BEARER_TOKEN, "token", "The Artifactory bearer token.")) .addOption(newOptionWithArg(ARGUMENT.ARTIFACTORY_URL, "url", "The Artifactory URL.")) .addOption(newOptionWithArg(ARGUMENT.PATH_TO_GO, "path", "The path to the `go` executable.")) .addOption(newOptionWithArg(ARGUMENT.PATH_TO_YARN, "path", "The path to the `yarn` executable.")) .addOption(newOptionWithArg(ARGUMENT.PATH_TO_PNPM, "path", "The path to the `pnpm` executable.")) .addOption(newOptionWithArg(ARGUMENT.CVE_VALID_FOR_HOURS, "hours", "The number of hours to wait before checking for new updates from the NVD.")) .addOption(newOptionWithArg(ARGUMENT.CVE_START_YEAR, "year", "The first year to retrieve NVD CVE data for; default is 2002.")) .addOption(newOptionWithArg(ARGUMENT.RETIREJS_FILTERS, "pattern", "Specify Retire JS content filter used to exclude files from analysis based on their content; " + "most commonly used to exclude based on your applications own copyright line. This " + "option can be specified multiple times.")) .addOption(newOptionWithArg(ARGUMENT.NEXUS_URL, "url", "The url to the Nexus Server's REST API Endpoint (http://domain/nexus/service/local). If not " + "set the Nexus Analyzer will be disabled.")) .addOption(newOptionWithArg(ARGUMENT.NEXUS_USERNAME, "username", "The username to authenticate to the Nexus Server's REST API Endpoint. If not set the Nexus " + "Analyzer will use an unauthenticated connection.")) .addOption(newOptionWithArg(ARGUMENT.NEXUS_PASSWORD, "password", "The password to authenticate to the Nexus Server's REST API Endpoint. If not set the Nexus " + "Analyzer will use an unauthenticated connection.")) //TODO remove as this should be covered by non-proxy hosts .addOption(newOptionWithArg(ARGUMENT.NEXUS_USES_PROXY, "true/false", "Whether or not the configured proxy should be used when connecting to Nexus.")) .addOption(newOptionWithArg(ARGUMENT.ADDITIONAL_ZIP_EXTENSIONS, "extensions", "A comma separated list of additional extensions to be scanned as ZIP files (ZIP, EAR, WAR " + "are already treated as zip files)")) .addOption(newOptionWithArg(ARGUMENT.PROP_SHORT, ARGUMENT.PROP, "file", "A property file to load.")) .addOption(newOptionWithArg(ARGUMENT.PATH_TO_CORE, "path", "The path to dotnet core.")) .addOption(newOptionWithArg(ARGUMENT.HINTS_FILE, "file", "The file path to the hints XML file.")) .addOption(newOption(ARGUMENT.RETIRED, "Enables the retired analyzers.")) .addOption(newOption(ARGUMENT.DISABLE_MSBUILD, "Disable the MS Build Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_JAR, "Disable the Jar Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_ARCHIVE, "Disable the Archive Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_ASSEMBLY, "Disable the .NET Assembly Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_PY_DIST, "Disable the Python Distribution Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_CMAKE, "Disable the Cmake Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_PY_PKG, "Disable the Python Package Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_MIX_AUDIT, "Disable the Elixir mix_audit Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_RUBYGEMS, "Disable the Ruby Gemspec Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_BUNDLE_AUDIT, "Disable the Ruby Bundler-Audit Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_FILENAME, "Disable the File Name Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_AUTOCONF, "Disable the Autoconf Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_PIP, "Disable the pip Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_PIPFILE, "Disable the Pipfile Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_COMPOSER, "Disable the PHP Composer Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_CPAN, "Disable the Perl CPAN file Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_GOLANG_MOD, "Disable the Golang Mod Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_OPENSSL, "Disable the OpenSSL Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_NUSPEC, "Disable the Nuspec Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_NUGETCONF, "Disable the Nuget packages.config Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_CENTRAL, "Disable the Central Analyzer. If this analyzer " + "is disabled it is likely you also want to disable the Nexus Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_CENTRAL_CACHE, "Disallow the Central Analyzer from caching results")) .addOption(newOption(ARGUMENT.DISABLE_OSSINDEX, "Disable the Sonatype OSS Index Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_OSSINDEX_CACHE, "Disallow the OSS Index Analyzer from caching results")) .addOption(newOption(ARGUMENT.DISABLE_COCOAPODS, "Disable the CocoaPods Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_SWIFT, "Disable the swift package Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_SWIFT_RESOLVED, "Disable the swift package resolved Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_GO_DEP, "Disable the Golang Package Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_NODE_JS, "Disable the Node.js Package Analyzer.")) .addOption(newOption(ARGUMENT.NODE_PACKAGE_SKIP_DEV_DEPENDENCIES, "Configures the Node Package Analyzer to skip devDependencies")) .addOption(newOption(ARGUMENT.DISABLE_NODE_AUDIT, "Disable the Node Audit Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_YARN_AUDIT, "Disable the Yarn Audit Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_NODE_AUDIT_CACHE, "Disallow the Node Audit Analyzer from caching results")) .addOption(newOption(ARGUMENT.DISABLE_NODE_AUDIT_SKIPDEV, "Configures the Node Audit Analyzer to skip devDependencies")) .addOption(newOption(ARGUMENT.DISABLE_RETIRE_JS, "Disable the RetireJS Analyzer.")) .addOption(newOption(ARGUMENT.ENABLE_NEXUS, "Disable the Nexus Analyzer.")) .addOption(newOption(ARGUMENT.ARTIFACTORY_ENABLED, "Whether the Artifactory Analyzer should be enabled.")) .addOption(newOption(ARGUMENT.PURGE_NVD, "Purges the local NVD data cache")); } // /** // * Adds the deprecated command line options to the given options collection. // * These are split out for purposes of not including them in the help // * message. We need to add the deprecated options so as not to break // * existing scripts. // * // * @param options a collection of command line arguments // */ // @SuppressWarnings({"static-access", "deprecation"}) // private void addDeprecatedOptions(final Options options) { // //all deprecated arguments have been removed (for now) // } /** * Determines if the 'version' command line argument was passed in. * * @return whether or not the 'version' command line argument was passed in */ public boolean isGetVersion() { return (line != null) && line.hasOption(ARGUMENT.VERSION); } /** * Determines if the 'help' command line argument was passed in. * * @return whether or not the 'help' command line argument was passed in */ public boolean isGetHelp() { return (line != null) && line.hasOption(ARGUMENT.HELP); } /** * Determines if the 'scan' command line argument was passed in. * * @return whether or not the 'scan' command line argument was passed in */ public boolean isRunScan() { return (line != null) && isValid && line.hasOption(ARGUMENT.SCAN); } /** * Returns the symbolic link depth (how deeply symbolic links will be * followed). * * @return the symbolic link depth */ public int getSymLinkDepth() { int value = 0; try { value = Integer.parseInt(line.getOptionValue(ARGUMENT.SYM_LINK_DEPTH, "0")); if (value < 0) { value = 0; } } catch (NumberFormatException ex) { LOGGER.debug("Symbolic link was not a number"); } return value; } /** * Utility method to determine if one of the disable options has been set. * If not set, this method will check the currently configured settings for * the current value to return. * <p> * Example given `--disableArchive` on the command line would cause this * method to return true for the disable archive setting. * * @param argument the command line argument * @param setting the corresponding settings key * @return true if the disable option was set, if not set the currently * configured value will be returned */ public boolean hasDisableOption(String argument, String setting) { if (line == null || !line.hasOption(argument)) { try { return !settings.getBoolean(setting); } catch (InvalidSettingException ise) { LOGGER.warn("Invalid property setting '{}' defaulting to false", setting); return false; } } else { return true; } } /** * Returns true if the disableNodeAudit command line argument was specified. * * @return true if the disableNodeAudit command line argument was specified; * otherwise false */ public boolean isNodeAuditDisabled() { if (hasDisableOption("disableNSP", Settings.KEYS.ANALYZER_NODE_AUDIT_ENABLED)) { LOGGER.error("The disableNSP argument has been deprecated and replaced by disableNodeAudit"); LOGGER.error("The disableNSP argument will be removed in the next version"); return true; } return hasDisableOption(ARGUMENT.DISABLE_NODE_AUDIT, Settings.KEYS.ANALYZER_NODE_AUDIT_ENABLED); } /** * Returns true if the disableYarnAudit command line argument was specified. * * @return true if the disableYarnAudit command line argument was specified; * otherwise false */ public boolean isYarnAuditDisabled() { return hasDisableOption(ARGUMENT.DISABLE_YARN_AUDIT, Settings.KEYS.ANALYZER_YARN_AUDIT_ENABLED); } /** * Returns true if the disablePnpmAudit command line argument was specified. * * @return true if the disablePnpmAudit command line argument was specified; * otherwise false */ public boolean isPnpmAuditDisabled() { return hasDisableOption(ARGUMENT.DISABLE_PNPM_AUDIT, Settings.KEYS.ANALYZER_PNPM_AUDIT_ENABLED); } /** * Returns true if the Nexus Analyzer should use the configured proxy to * connect to Nexus; otherwise false is returned. * * @return true if the Nexus Analyzer should use the configured proxy to * connect to Nexus; otherwise false */ public boolean isNexusUsesProxy() { // If they didn't specify whether Nexus needs to use the proxy, we should // still honor the property if it's set. if (line == null || !line.hasOption(ARGUMENT.NEXUS_USES_PROXY)) { try { return settings.getBoolean(Settings.KEYS.ANALYZER_NEXUS_USES_PROXY); } catch (InvalidSettingException ise) { return true; } } else { return Boolean.parseBoolean(line.getOptionValue(ARGUMENT.NEXUS_USES_PROXY)); } } /** * Returns the argument boolean value. * * @param argument the argument * @return the argument boolean value */ @SuppressFBWarnings(justification = "Accepting that this is a bad practice - used a Boolean as we needed three states", value = {"NP_BOOLEAN_RETURN_NULL"}) public Boolean getBooleanArgument(String argument) { if (line != null && line.hasOption(argument)) { final String value = line.getOptionValue(argument); if (value != null) { return Boolean.parseBoolean(value); } } return null; } /** * Returns the argument value for the given option. * * @param option the option * @return the value of the argument */ public String getStringArgument(String option) { return getStringArgument(option, null); } /** * Returns the argument value for the given option. * * @param option the option * @param key the dependency-check settings key for the option. * @return the value of the argument */ public String getStringArgument(String option, String key) { if (line != null && line.hasOption(option)) { if (key != null && (option.toLowerCase().endsWith("password") || option.toLowerCase().endsWith("pass"))) { LOGGER.warn("{} used on the command line, consider moving the password " + "to a properties file using the key `{}` and using the " + "--propertyfile argument instead", option, key); } return line.getOptionValue(option); } return null; } /** * Returns the argument value for the given option. * * @param option the option * @return the value of the argument */ public String[] getStringArguments(String option) { if (line != null && line.hasOption(option)) { return line.getOptionValues(option); } return null; } /** * Returns the argument value for the given option. * * @param option the option * @return the value of the argument */ public File getFileArgument(String option) { final String path = line.getOptionValue(option); if (path != null) { return new File(path); } return null; } /** * Displays the command line help message to the standard output. */ public void printHelp() { final HelpFormatter formatter = new HelpFormatter(); final Options options = new Options(); addStandardOptions(options); if (line != null && line.hasOption(ARGUMENT.ADVANCED_HELP)) { addAdvancedOptions(options); } final String helpMsg = String.format("%n%s" + " can be used to identify if there are any known CVE vulnerabilities in libraries utilized by an application. " + "%s will automatically update required data from the Internet, such as the CVE and CPE data files from nvd.nist.gov.%n%n", settings.getString(Settings.KEYS.APPLICATION_NAME, "DependencyCheck"), settings.getString(Settings.KEYS.APPLICATION_NAME, "DependencyCheck")); formatter.printHelp(settings.getString(Settings.KEYS.APPLICATION_NAME, "DependencyCheck"), helpMsg, options, "", true); } /** * Retrieves the file command line parameter(s) specified for the 'scan' * argument. * * @return the file paths specified on the command line for scan */ public String[] getScanFiles() { return line.getOptionValues(ARGUMENT.SCAN); } /** * Retrieves the list of excluded file patterns specified by the 'exclude' * argument. * * @return the excluded file patterns */ public String[] getExcludeList() { return line.getOptionValues(ARGUMENT.EXCLUDE); } /** * Retrieves the list of retire JS content filters used to exclude JS files * by content. * * @return the retireJS filters */ public String[] getRetireJsFilters() { return line.getOptionValues(ARGUMENT.RETIREJS_FILTERS); } /** * Returns whether or not the retireJS analyzer should exclude * non-vulnerable JS from the report. * * @return <code>true</code> if non-vulnerable JS should be filtered in the * RetireJS Analyzer; otherwise <code>null</code> */ @SuppressFBWarnings(justification = "Accepting that this is a bad practice - but made more sense in this use case", value = {"NP_BOOLEAN_RETURN_NULL"}) public Boolean isRetireJsFilterNonVulnerable() { return (line != null && line.hasOption(ARGUMENT.RETIREJS_FILTER_NON_VULNERABLE)) ? true : null; } /** * Returns the directory to write the reports to specified on the command * line. * * @return the path to the reports directory. */ public String getReportDirectory() { return line.getOptionValue(ARGUMENT.OUT, "."); } /** * Returns the output format specified on the command line. Defaults to HTML * if no format was specified. * * @return the output format name. */ public String[] getReportFormat() { if (line.hasOption(ARGUMENT.OUTPUT_FORMAT)) { return line.getOptionValues(ARGUMENT.OUTPUT_FORMAT); } return new String[]{"HTML"}; } /** * Returns the application name specified on the command line. * * @return the application name. */ public String getProjectName() { String name = line.getOptionValue(ARGUMENT.PROJECT); if (name == null) { name = ""; } return name; } /** * <p> * Prints the manifest information to standard output.</p> * <ul><li>Implementation-Title: ${pom.name}</li> * <li>Implementation-Version: ${pom.version}</li></ul> */ public void printVersionInfo() { final String version = String.format("%s version %s", settings.getString(Settings.KEYS.APPLICATION_NAME, "dependency-check"), settings.getString(Settings.KEYS.APPLICATION_VERSION, "Unknown")); System.out.println(version); } /** * Checks if the update only flag has been set. * * @return <code>true</code> if the update only flag has been set; otherwise * <code>false</code>. */ public boolean isUpdateOnly() { return line != null && line.hasOption(ARGUMENT.UPDATE_ONLY); } /** * Checks if the purge NVD flag has been set. * * @return <code>true</code> if the purge nvd flag has been set; otherwise * <code>false</code>. */ public boolean isPurge() { return line != null && line.hasOption(ARGUMENT.PURGE_NVD); } /** * Returns the database driver name if specified; otherwise null is * returned. * * @return the database driver name if specified; otherwise null is returned */ public String getDatabaseDriverName() { return line.getOptionValue(ARGUMENT.DB_DRIVER); } /** * Returns the argument value. * * @param argument the argument * @return the value of the argument */ public Integer getIntegerValue(String argument) { final String v = line.getOptionValue(argument); if (v != null) { return Integer.parseInt(v); } return null; } /** * Checks if the option is present. If present it will return * <code>true</code>; otherwise <code>false</code>. * * @param option the option to check * @return <code>true</code> if auto-update is allowed; otherwise * <code>null</code> */ @SuppressFBWarnings(justification = "Accepting that this is a bad practice - but made more sense in this use case", value = {"NP_BOOLEAN_RETURN_NULL"}) public Boolean hasOption(String option) { return (line != null && line.hasOption(option)) ? true : null; } /** * Returns the CVSS value to fail on. * * @return 11 if nothing is set. Otherwise it returns the int passed from * the command line arg */ public float getFailOnCVSS() { if (line.hasOption(ARGUMENT.FAIL_ON_CVSS)) { final String value = line.getOptionValue(ARGUMENT.FAIL_ON_CVSS); try { return Float.parseFloat(value); } catch (NumberFormatException nfe) { return 11; } } else { return 11; } } /** * Returns the float argument for the given option. * * @param option the option * @param defaultValue the value if the option is not present * @return the value of the argument if present; otherwise the defaultValue */ public float getFloatArgument(String option, float defaultValue) { if (line.hasOption(option)) { final String value = line.getOptionValue(option); try { return Integer.parseInt(value); } catch (NumberFormatException nfe) { return defaultValue; } } else { return defaultValue; } } /** * Builds a new option. * * @param name the long name * @param description the description * @return a new option */ private Option newOption(String name, String description) { return Option.builder().longOpt(name).desc(description).build(); } /** * Builds a new option. * * @param shortName the short name * @param name the long name * @param description the description * @return a new option */ private Option newOption(String shortName, String name, String description) { return Option.builder(shortName).longOpt(name).desc(description).build(); } /** * Builds a new option. * * @param name the long name * @param arg the argument name * @param description the description * @return a new option */ private Option newOptionWithArg(String name, String arg, String description) { return Option.builder().longOpt(name).argName(arg).hasArg().desc(description).build(); } /** * Builds a new option. * * @param shortName the short name * @param name the long name * @param arg the argument name * @param description the description * @return a new option */ private Option newOptionWithArg(String shortName, String name, String arg, String description) { return Option.builder(shortName).longOpt(name).argName(arg).hasArg().desc(description).build(); } /** * Builds a new option group so that an option can be specified multiple * times on the command line. * * @param option the option to add to the group * @return a new option group */ private OptionGroup newOptionGroup(Option option) { final OptionGroup group = new OptionGroup(); group.addOption(option); return group; } /** * A collection of static final strings that represent the possible command * line arguments. */ public static class ARGUMENT { /** * The long CLI argument name specifying the directory/file to scan. */ public static final String SCAN = "scan"; /** * The short CLI argument name specifying the directory/file to scan. */ public static final String SCAN_SHORT = "s"; /** * The long CLI argument name specifying that the CPE/CVE/etc. data * should not be automatically updated. */ public static final String DISABLE_AUTO_UPDATE = "noupdate"; /** * The short CLI argument name specifying that the CPE/CVE/etc. data * should not be automatically updated. */ public static final String DISABLE_AUTO_UPDATE_SHORT = "n"; /** * The long CLI argument name specifying that only the update phase * should be executed; no scan should be run. */ public static final String UPDATE_ONLY = "updateonly"; /** * The long CLI argument name specifying that only the update phase * should be executed; no scan should be run. */ public static final String PURGE_NVD = "purge"; /** * The long CLI argument name specifying the directory to write the * reports to. */ public static final String OUT = "out"; /** * The short CLI argument name specifying the directory to write the * reports to. */ public static final String OUT_SHORT = "o"; /** * The long CLI argument name specifying the output format to write the * reports to. */ public static final String OUTPUT_FORMAT = "format"; /** * The short CLI argument name specifying the output format to write the * reports to. */ public static final String OUTPUT_FORMAT_SHORT = "f"; /** * The long CLI argument name specifying the name of the project to be * scanned. */ public static final String PROJECT = "project"; /** * The long CLI argument name asking for help. */ public static final String HELP = "help"; /** * The long CLI argument name asking for advanced help. */ public static final String ADVANCED_HELP = "advancedHelp"; /** * The short CLI argument name asking for help. */ public static final String HELP_SHORT = "h"; /** * The long CLI argument name asking for the version. */ public static final String VERSION_SHORT = "v"; /** * The short CLI argument name asking for the version. */ public static final String VERSION = "version"; /** * The CLI argument name indicating the proxy port. */ public static final String PROXY_PORT = "proxyport"; /** * The CLI argument name indicating the proxy server. */ public static final String PROXY_SERVER = "proxyserver"; /** * The CLI argument name indicating the proxy username. */ public static final String PROXY_USERNAME = "proxyuser"; /** * The CLI argument name indicating the proxy password. */ public static final String PROXY_PASSWORD = "proxypass"; /** * The CLI argument name indicating the proxy proxy exclusion list. */ public static final String NON_PROXY_HOSTS = "nonProxyHosts"; /** * The short CLI argument name indicating the connection timeout. */ public static final String CONNECTION_TIMEOUT_SHORT = "c"; /** * The CLI argument name indicating the connection timeout. */ public static final String CONNECTION_TIMEOUT = "connectiontimeout"; /** * The short CLI argument name for setting the location of an additional * properties file. */ public static final String PROP_SHORT = "P"; /** * The CLI argument name for setting the location of an additional * properties file. */ public static final String PROP = "propertyfile"; /** * The CLI argument name for setting the location of the data directory. */ public static final String DATA_DIRECTORY = "data"; /** * The CLI argument name for setting the URL for the CVE Data Files. */ public static final String CVE_MODIFIED_URL = "cveUrlModified"; /** * The CLI argument name for setting the URL for the CVE Data Files. */ public static final String CVE_BASE_URL = "cveUrlBase"; /** * The time in milliseconds to wait between downloading NVD CVE data. */ public static final String CVE_DOWNLOAD_WAIT_TIME = "cveDownloadWait"; /** * The short CLI argument name for setting the location of the data * directory. */ public static final String DATA_DIRECTORY_SHORT = "d"; /** * The CLI argument name for setting the location of the data directory. */ public static final String VERBOSE_LOG = "log"; /** * The short CLI argument name for setting the location of the data * directory. */ public static final String VERBOSE_LOG_SHORT = "l"; /** * The CLI argument name for setting the depth of symbolic links that * will be followed. */ public static final String SYM_LINK_DEPTH = "symLink"; /** * The CLI argument name for setting the location of the suppression * file(s). */ public static final String SUPPRESSION_FILES = "suppression"; /** * The CLI argument name for setting the location of the hint file. */ public static final String HINTS_FILE = "hints"; /** * The CLI argument name for setting the number of hours to wait before * checking for new updates from the NVD. */ public static final String CVE_VALID_FOR_HOURS = "cveValidForHours"; /** * The CLI argument name for setting the first year to retrieve NVD * data. */ public static final String CVE_START_YEAR = "cveStartYear"; /** * The username for basic auth to the CVE data. */ public static final String CVE_USER = "cveUser"; /** * The password for basic auth to the CVE data. */ public static final String CVE_PASSWORD = "cvePassword"; /** * Disables the Jar Analyzer. */ public static final String DISABLE_JAR = "disableJar"; /** * Disable the MS Build Analyzer. */ public static final String DISABLE_MSBUILD = "disableMSBuild"; /** * Disables the Archive Analyzer. */ public static final String DISABLE_ARCHIVE = "disableArchive"; /** * Disables the Python Distribution Analyzer. */ public static final String DISABLE_PY_DIST = "disablePyDist"; /** * Disables the Python Package Analyzer. */ public static final String DISABLE_PY_PKG = "disablePyPkg"; /** * Disables the Elixir mix audit Analyzer. */ public static final String DISABLE_MIX_AUDIT = "disableMixAudit"; /** * Disables the Golang Dependency Analyzer. */ public static final String DISABLE_GO_DEP = "disableGolangDep"; /** * Disables the PHP Composer Analyzer. */ public static final String DISABLE_COMPOSER = "disableComposer"; /** * Disables the Perl CPAN File Analyzer. */ public static final String DISABLE_CPAN = "disableCpan"; /** * Disables the Golang Mod Analyzer. */ public static final String DISABLE_GOLANG_MOD = "disableGolangMod"; /** * The CLI argument name for setting the path to `go`. */ public static final String PATH_TO_GO = "go"; /** * The CLI argument name for setting the path to `yarn`. */ public static final String PATH_TO_YARN = "yarn"; /** * The CLI argument name for setting the path to `pnpm`. */ public static final String PATH_TO_PNPM = "pnpm"; /** * Disables the Ruby Gemspec Analyzer. */ public static final String DISABLE_RUBYGEMS = "disableRubygems"; /** * Disables the Autoconf Analyzer. */ public static final String DISABLE_AUTOCONF = "disableAutoconf"; /** * Disables the pip Analyzer. */ public static final String DISABLE_PIP = "disablePip"; /** * Disables the Pipfile Analyzer. */ public static final String DISABLE_PIPFILE = "disablePipfile"; /** * Disables the Cmake Analyzer. */ public static final String DISABLE_CMAKE = "disableCmake"; /** * Disables the cocoapods analyzer. */ public static final String DISABLE_COCOAPODS = "disableCocoapodsAnalyzer"; /** * Disables the swift package manager analyzer. */ public static final String DISABLE_SWIFT = "disableSwiftPackageManagerAnalyzer"; /** * Disables the swift package resolved analyzer. */ public static final String DISABLE_SWIFT_RESOLVED = "disableSwiftPackageResolvedAnalyzer"; /** * Disables the Assembly Analyzer. */ public static final String DISABLE_ASSEMBLY = "disableAssembly"; /** * Disables the Ruby Bundler Audit Analyzer. */ public static final String DISABLE_BUNDLE_AUDIT = "disableBundleAudit"; /** * Disables the File Name Analyzer. */ public static final String DISABLE_FILENAME = "disableFileName"; /** * Disables the Nuspec Analyzer. */ public static final String DISABLE_NUSPEC = "disableNuspec"; /** * Disables the Nuget packages.config Analyzer. */ public static final String DISABLE_NUGETCONF = "disableNugetconf"; /** * Disables the Central Analyzer. */ public static final String DISABLE_CENTRAL = "disableCentral"; /** * Disables the Central Analyzer's ability to cache results locally. */ public static final String DISABLE_CENTRAL_CACHE = "disableCentralCache"; /** * Disables the Nexus Analyzer. */ public static final String ENABLE_NEXUS = "enableNexus"; /** * Disables the Sonatype OSS Index Analyzer. */ public static final String DISABLE_OSSINDEX = "disableOssIndex"; /** * Disables the Sonatype OSS Index Analyzer's ability to cache results * locally. */ public static final String DISABLE_OSSINDEX_CACHE = "disableOssIndexCache"; /** * The username for the Sonatype OSS Index. */ public static final String OSSINDEX_USERNAME = "ossIndexUsername"; /** * The password for the Sonatype OSS Index. */ public static final String OSSINDEX_PASSWORD = "ossIndexPassword"; /** * Disables the OpenSSL Analyzer. */ public static final String DISABLE_OPENSSL = "disableOpenSSL"; /** * Disables the Node.js Package Analyzer. */ public static final String DISABLE_NODE_JS = "disableNodeJS"; /** * Skips dev dependencies in Node Package Analyzer. */ public static final String NODE_PACKAGE_SKIP_DEV_DEPENDENCIES = "nodePackageSkipDevDependencies"; /** * Disables the Node Audit Analyzer. */ public static final String DISABLE_NODE_AUDIT = "disableNodeAudit"; /** * Disables the Yarn Audit Analyzer. */ public static final String DISABLE_YARN_AUDIT = "disableYarnAudit"; /** * Disables the Pnpm Audit Analyzer. */ public static final String DISABLE_PNPM_AUDIT = "disablePnpmAudit"; /** * Disables the Node Audit Analyzer's ability to cache results locally. */ public static final String DISABLE_NODE_AUDIT_CACHE = "disableNodeAuditCache"; /** * Configures the Node Audit Analyzer to skip the dev dependencies. */ public static final String DISABLE_NODE_AUDIT_SKIPDEV = "nodeAuditSkipDevDependencies"; /** * Disables the RetireJS Analyzer. */ public static final String DISABLE_RETIRE_JS = "disableRetireJS"; /** * Whether the RetireJS Analyzer will update regardless of the * `autoupdate` setting. */ public static final String RETIRE_JS_FORCEUPDATE = "retireJsForceUpdate"; /** * The URL to the retire JS repository. */ public static final String RETIREJS_URL = "retireJsUrl"; /** * The URL of the nexus server. */ public static final String NEXUS_URL = "nexus"; /** * The username for the nexus server. */ public static final String NEXUS_USERNAME = "nexusUser"; /** * The password for the nexus server. */ public static final String NEXUS_PASSWORD = "nexusPass"; /** * Whether or not the defined proxy should be used when connecting to * Nexus. */ public static final String NEXUS_USES_PROXY = "nexusUsesProxy"; /** * The CLI argument name for setting the connection string. */ public static final String CONNECTION_STRING = "connectionString"; /** * The CLI argument name for setting the database user name. */ public static final String DB_NAME = "dbUser"; /** * The CLI argument name for setting the database password. */ public static final String DB_PASSWORD = "dbPassword"; /** * The CLI argument name for setting the database driver name. */ public static final String DB_DRIVER = "dbDriverName"; /** * The CLI argument name for setting the path to the database driver; in * case it is not on the class path. */ public static final String DB_DRIVER_PATH = "dbDriverPath"; /** * The CLI argument name for setting the path to dotnet core. */ public static final String PATH_TO_CORE = "dotnet"; /** * The CLI argument name for setting extra extensions. */ public static final String ADDITIONAL_ZIP_EXTENSIONS = "zipExtensions"; /** * Exclude path argument. */ public static final String EXCLUDE = "exclude"; /** * The CLI argument name for setting the path to bundle-audit for Ruby * bundle analysis. */ public static final String PATH_TO_BUNDLE_AUDIT = "bundleAudit"; /** * The CLI argument name for setting the path that should be used as the * working directory that the bundle-audit command used for Ruby bundle * analysis should be executed from. This will allow for the usage of * rbenv */ public static final String PATH_TO_BUNDLE_AUDIT_WORKING_DIRECTORY = "bundleAuditWorkingDirectory"; /** * The CLI argument name for setting the path to mix_audit for Elixir * analysis. */ public static final String PATH_TO_MIX_AUDIT = "mixAudit"; /** * The CLI argument to enable the experimental analyzers. */ public static final String EXPERIMENTAL = "enableExperimental"; /** * The CLI argument to enable the retired analyzers. */ public static final String RETIRED = "enableRetired"; /** * The CLI argument for the retire js content filters. */ public static final String RETIREJS_FILTERS = "retirejsFilter"; /** * The CLI argument for the retire js content filters. */ public static final String RETIREJS_FILTER_NON_VULNERABLE = "retirejsFilterNonVulnerable"; /** * The CLI argument for indicating if the Artifactory analyzer should be * enabled. */ public static final String ARTIFACTORY_ENABLED = "enableArtifactory"; /** * The CLI argument for indicating if the Artifactory analyzer should * use the proxy. */ public static final String ARTIFACTORY_URL = "artifactoryUrl"; /** * The CLI argument for indicating the Artifactory username. */ public static final String ARTIFACTORY_USERNAME = "artifactoryUsername"; /** * The CLI argument for indicating the Artifactory API token. */ public static final String ARTIFACTORY_API_TOKEN = "artifactoryApiToken"; /** * The CLI argument for indicating the Artifactory bearer token. */ public static final String ARTIFACTORY_BEARER_TOKEN = "artifactoryBearerToken"; /** * The CLI argument for indicating if the Artifactory analyzer should * use the proxy. */ public static final String ARTIFACTORY_USES_PROXY = "artifactoryUseProxy"; /** * The CLI argument for indicating if the Artifactory analyzer should * use the parallel analysis. */ public static final String ARTIFACTORY_PARALLEL_ANALYSIS = "artifactoryParallelAnalysis"; /** * The CLI argument to configure when the execution should be considered * a failure. */ public static final String FAIL_ON_CVSS = "failOnCVSS"; /** * The CLI argument to configure if the XML and JSON reports should be * pretty printed. */ public static final String PRETTY_PRINT = "prettyPrint"; /** * The CLI argument to set the threshold that is considered a failure * when generating the JUNIT report format. */ public static final String FAIL_JUNIT_ON_CVSS = "junitFailOnCVSS"; } }
cli/src/main/java/org/owasp/dependencycheck/CliParser.java
/* * This file is part of dependency-check-cli. * * 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. * * Copyright (c) 2012 Jeremy Long. All Rights Reserved. */ package org.owasp.dependencycheck; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.File; import java.io.FileNotFoundException; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.owasp.dependencycheck.reporting.ReportGenerator.Format; import org.owasp.dependencycheck.utils.InvalidSettingException; import org.owasp.dependencycheck.utils.Settings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A utility to parse command line arguments for the DependencyCheck. * * @author Jeremy Long */ //suppress hard-coded password rule @SuppressWarnings("squid:S2068") public final class CliParser { /** * The logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(CliParser.class); /** * The command line. */ private CommandLine line; /** * Indicates whether the arguments are valid. */ private boolean isValid = true; /** * The configured settings. */ private final Settings settings; /** * The supported reported formats. */ private static final String SUPPORTED_FORMATS = "HTML, XML, CSV, JSON, JUNIT, SARIF, or ALL"; /** * Constructs a new CLI Parser object with the configured settings. * * @param settings the configured settings */ public CliParser(Settings settings) { this.settings = settings; } /** * Parses the arguments passed in and captures the results for later use. * * @param args the command line arguments * @throws FileNotFoundException is thrown when a 'file' argument does not * point to a file that exists. * @throws ParseException is thrown when a Parse Exception occurs. */ public void parse(String[] args) throws FileNotFoundException, ParseException { line = parseArgs(args); if (line != null) { validateArgs(); } } /** * Parses the command line arguments. * * @param args the command line arguments * @return the results of parsing the command line arguments * @throws ParseException if the arguments are invalid */ private CommandLine parseArgs(String[] args) throws ParseException { final CommandLineParser parser = new DefaultParser(); final Options options = createCommandLineOptions(); return parser.parse(options, args); } /** * Validates that the command line arguments are valid. * * @throws FileNotFoundException if there is a file specified by either the * SCAN or CPE command line arguments that does not exist. * @throws ParseException is thrown if there is an exception parsing the * command line. */ private void validateArgs() throws FileNotFoundException, ParseException { if (isUpdateOnly() || isRunScan()) { String value = line.getOptionValue(ARGUMENT.CVE_VALID_FOR_HOURS); if (value != null) { try { final int i = Integer.parseInt(value); if (i < 0) { throw new ParseException("Invalid Setting: cveValidForHours must be a number greater than or equal to 0."); } } catch (NumberFormatException ex) { throw new ParseException("Invalid Setting: cveValidForHours must be a number greater than or equal to 0."); } } value = line.getOptionValue(ARGUMENT.CVE_START_YEAR); if (value != null) { try { final int i = Integer.parseInt(value); if (i < 2002) { throw new ParseException("Invalid Setting: cveStartYear must be a number greater than or equal to 2002."); } } catch (NumberFormatException ex) { throw new ParseException("Invalid Setting: cveStartYear must be a number greater than or equal to 2002."); } } } if (isRunScan()) { validatePathExists(getScanFiles(), ARGUMENT.SCAN); validatePathExists(getReportDirectory(), ARGUMENT.OUT); final String pathToCore = getStringArgument(ARGUMENT.PATH_TO_CORE); if (pathToCore != null) { validatePathExists(pathToCore, ARGUMENT.PATH_TO_CORE); } if (line.hasOption(ARGUMENT.OUTPUT_FORMAT)) { String validating = null; try { for (String format : getReportFormat()) { validating = format; Format.valueOf(format); } } catch (IllegalArgumentException ex) { final String msg = String.format("An invalid 'format' of '%s' was specified. " + "Supported output formats are " + SUPPORTED_FORMATS, validating); throw new ParseException(msg); } } final String base = getStringArgument(ARGUMENT.CVE_BASE_URL); final String modified = getStringArgument(ARGUMENT.CVE_MODIFIED_URL); if ((base != null && modified == null) || (base == null && modified != null)) { final String msg = "If one of the CVE URLs is specified they must all be specified; please add the missing CVE URL."; throw new ParseException(msg); } if (line.hasOption(ARGUMENT.SYM_LINK_DEPTH)) { try { final int i = Integer.parseInt(line.getOptionValue(ARGUMENT.SYM_LINK_DEPTH)); if (i < 0) { throw new ParseException("Symbolic Link Depth (symLink) must be greater than zero."); } } catch (NumberFormatException ex) { throw new ParseException("Symbolic Link Depth (symLink) is not a number."); } } } } /** * Validates whether or not the path(s) points at a file that exists; if the * path(s) does not point to an existing file a FileNotFoundException is * thrown. * * @param paths the paths to validate if they exists * @param optType the option being validated (e.g. scan, out, etc.) * @throws FileNotFoundException is thrown if one of the paths being * validated does not exist. */ private void validatePathExists(String[] paths, String optType) throws FileNotFoundException { for (String path : paths) { validatePathExists(path, optType); } } /** * Validates whether or not the path points at a file that exists; if the * path does not point to an existing file a FileNotFoundException is * thrown. * * @param path the paths to validate if they exists * @param argumentName the argument being validated (e.g. scan, out, etc.) * @throws FileNotFoundException is thrown if the path being validated does * not exist. */ private void validatePathExists(String path, String argumentName) throws FileNotFoundException { if (path == null) { isValid = false; final String msg = String.format("Invalid '%s' argument: null", argumentName); throw new FileNotFoundException(msg); } else if (!path.contains("*") && !path.contains("?")) { File f = new File(path); final String[] formats = this.getReportFormat(); if ("o".equalsIgnoreCase(argumentName.substring(0, 1)) && formats.length == 1 && !"ALL".equalsIgnoreCase(formats[0])) { final String checkPath = path.toLowerCase(); if (checkPath.endsWith(".html") || checkPath.endsWith(".xml") || checkPath.endsWith(".htm") || checkPath.endsWith(".csv") || checkPath.endsWith(".json")) { if (f.getParentFile() == null) { f = new File(".", path); } if (!f.getParentFile().isDirectory()) { isValid = false; final String msg = String.format("Invalid '%s' argument: '%s' - directory path does not exist", argumentName, path); throw new FileNotFoundException(msg); } } } else if ("o".equalsIgnoreCase(argumentName.substring(0, 1)) && !f.isDirectory()) { if (f.getParentFile() != null && f.getParentFile().isDirectory() && !f.mkdir()) { isValid = false; final String msg = String.format("Invalid '%s' argument: '%s' - unable to create the output directory", argumentName, path); throw new FileNotFoundException(msg); } if (!f.isDirectory()) { isValid = false; final String msg = String.format("Invalid '%s' argument: '%s' - path does not exist", argumentName, path); throw new FileNotFoundException(msg); } } else if (!f.exists()) { isValid = false; final String msg = String.format("Invalid '%s' argument: '%s' - path does not exist", argumentName, path); throw new FileNotFoundException(msg); } // } else if (path.startsWith("//") || path.startsWith("\\\\")) { // isValid = false; // final String msg = String.format("Invalid '%s' argument: '%s'%nUnable to scan paths that start with '//'.", argumentName, path); // throw new FileNotFoundException(msg); } else if ((path.endsWith("/*") && !path.endsWith("**/*")) || (path.endsWith("\\*") && path.endsWith("**\\*"))) { LOGGER.warn("Possibly incorrect path '{}' from argument '{}' because it ends with a slash star; " + "dependency-check uses ant-style paths", path, argumentName); } } /** * Generates an Options collection that is used to parse the command line * and to display the help message. * * @return the command line options used for parsing the command line */ @SuppressWarnings("static-access") private Options createCommandLineOptions() { final Options options = new Options(); addStandardOptions(options); addAdvancedOptions(options); // addDeprecatedOptions(options); return options; } /** * Adds the standard command line options to the given options collection. * * @param options a collection of command line arguments */ @SuppressWarnings("static-access") private void addStandardOptions(final Options options) { //This is an option group because it can be specified more then once. options.addOptionGroup(newOptionGroup(newOptionWithArg(ARGUMENT.SCAN_SHORT, ARGUMENT.SCAN, "path", "The path to scan - this option can be specified multiple times. Ant style paths are supported (e.g. 'path/**/*.jar'); " + "if using Ant style paths it is highly recommended to quote the argument value."))) .addOptionGroup(newOptionGroup(newOptionWithArg(ARGUMENT.EXCLUDE, "pattern", "Specify an exclusion pattern. This option " + "can be specified multiple times and it accepts Ant style exclusions."))) .addOption(newOptionWithArg(ARGUMENT.PROJECT, "name", "The name of the project being scanned.")) .addOption(newOptionWithArg(ARGUMENT.OUT_SHORT, ARGUMENT.OUT, "path", "The folder to write reports to. This defaults to the current directory. It is possible to set this to a specific " + "file name if the format argument is not set to ALL.")) .addOption(newOptionWithArg(ARGUMENT.OUTPUT_FORMAT_SHORT, ARGUMENT.OUTPUT_FORMAT, "format", "The report format (" + SUPPORTED_FORMATS + "). The default is HTML. Multiple format parameters can be specified.")) .addOption(newOption(ARGUMENT.PRETTY_PRINT, "When specified the JSON and XML report formats will be pretty printed.")) .addOption(newOption(ARGUMENT.VERSION_SHORT, ARGUMENT.VERSION, "Print the version information.")) .addOption(newOption(ARGUMENT.HELP_SHORT, ARGUMENT.HELP, "Print this message.")) .addOption(newOption(ARGUMENT.ADVANCED_HELP, "Print the advanced help message.")) .addOption(newOption(ARGUMENT.DISABLE_AUTO_UPDATE_SHORT, ARGUMENT.DISABLE_AUTO_UPDATE, "Disables the automatic updating of the CPE data.")) .addOption(newOptionWithArg(ARGUMENT.VERBOSE_LOG_SHORT, ARGUMENT.VERBOSE_LOG, "file", "The file path to write verbose logging information.")) .addOptionGroup(newOptionGroup(newOptionWithArg(ARGUMENT.SUPPRESSION_FILES, "file", "The file path to the suppression XML file. This can be specified more then once to utilize multiple suppression files"))) .addOption(newOption(ARGUMENT.EXPERIMENTAL, "Enables the experimental analyzers.")) .addOption(newOptionWithArg(ARGUMENT.FAIL_ON_CVSS, "score", "Specifies if the build should be failed if a CVSS score above a specified level is identified. The default is 11; " + "since the CVSS scores are 0-10, by default the build will never fail.")) .addOption(newOptionWithArg(ARGUMENT.FAIL_JUNIT_ON_CVSS, "score", "Specifies the CVSS score that is considered a failure when generating the junit report. The default is 0.")); } /** * Adds the advanced command line options to the given options collection. * These are split out for purposes of being able to display two different * help messages. * * @param options a collection of command line arguments */ @SuppressWarnings("static-access") private void addAdvancedOptions(final Options options) { options .addOption(newOption(ARGUMENT.UPDATE_ONLY, "Only update the local NVD data cache; no scan will be executed.")) .addOption(newOptionWithArg(ARGUMENT.CVE_BASE_URL, "url", "Base URL for each year’s CVE files (json.gz), the %d will be replaced with the year.")) .addOption(newOptionWithArg(ARGUMENT.CVE_MODIFIED_URL, "url", "URL for the modified CVE (json.gz).")) .addOption(newOptionWithArg(ARGUMENT.CVE_DOWNLOAD_WAIT_TIME, "milliseconds", "Time in milliseconds to wait between downloading from the NVD.")) .addOption(newOptionWithArg(ARGUMENT.CVE_USER, "user", "Credentials for basic authentication to the CVE data.")) .addOption(newOptionWithArg(ARGUMENT.CVE_PASSWORD, "password", "Credentials for basic authentication to the CVE data.")) .addOption(newOptionWithArg(ARGUMENT.PROXY_PORT, "port", "The proxy port to use when downloading resources.")) .addOption(newOptionWithArg(ARGUMENT.PROXY_SERVER, "server", "The proxy server to use when downloading resources.")) .addOption(newOptionWithArg(ARGUMENT.PROXY_USERNAME, "user", "The proxy username to use when downloading resources.")) .addOption(newOptionWithArg(ARGUMENT.PROXY_PASSWORD, "pass", "The proxy password to use when downloading resources.")) .addOption(newOptionWithArg(ARGUMENT.NON_PROXY_HOSTS, "list", "The proxy exclusion list: hostnames (or patterns) for which proxy should not be used. " + "Use pipe, comma or colon as list separator.")) .addOption(newOptionWithArg(ARGUMENT.CONNECTION_TIMEOUT_SHORT, ARGUMENT.CONNECTION_TIMEOUT, "timeout", "The connection timeout (in milliseconds) to use when downloading resources.")) .addOption(newOptionWithArg(ARGUMENT.CONNECTION_STRING, "connStr", "The connection string to the database.")) .addOption(newOptionWithArg(ARGUMENT.DB_NAME, "user", "The username used to connect to the database.")) .addOption(newOptionWithArg(ARGUMENT.DATA_DIRECTORY_SHORT, ARGUMENT.DATA_DIRECTORY, "path", "The location of the H2 Database file. This option should generally not be set.")) .addOption(newOptionWithArg(ARGUMENT.DB_PASSWORD, "password", "The password for connecting to the database.")) .addOption(newOptionWithArg(ARGUMENT.DB_DRIVER, "driver", "The database driver name.")) .addOption(newOptionWithArg(ARGUMENT.DB_DRIVER_PATH, "path", "The path to the database driver; note, this does not need to be set unless the JAR is " + "outside of the classpath.")) .addOption(newOptionWithArg(ARGUMENT.SYM_LINK_DEPTH, "depth", "Sets how deep nested symbolic links will be followed; 0 indicates symbolic links will not be followed.")) .addOption(newOptionWithArg(ARGUMENT.PATH_TO_BUNDLE_AUDIT, "path", "The path to bundle-audit for Gem bundle analysis.")) .addOption(newOptionWithArg(ARGUMENT.PATH_TO_BUNDLE_AUDIT_WORKING_DIRECTORY, "path", "The path to working directory that the bundle-audit command should be executed from when " + "doing Gem bundle analysis.")) .addOption(newOptionWithArg(ARGUMENT.OSSINDEX_USERNAME, "username", "The username to authenticate to Sonatype's OSS Index. If not set the Sonatype OSS Index " + "Analyzer will use an unauthenticated connection.")) .addOption(newOptionWithArg(ARGUMENT.OSSINDEX_PASSWORD, "password", "" + "The password to authenticate to Sonatype's OSS Index. If not set the Sonatype OSS " + "Index Analyzer will use an unauthenticated connection.")) .addOption(newOption(ARGUMENT.RETIRE_JS_FORCEUPDATE, "Force the RetireJS Analyzer to update " + "even if autoupdate is disabled")) .addOption(newOptionWithArg(ARGUMENT.RETIREJS_URL, "url", "The Retire JS Respository URL")) .addOption(newOption(ARGUMENT.RETIREJS_FILTER_NON_VULNERABLE, "Specifies that the Retire JS " + "Analyzer should filter out non-vulnerable JS files from the report.")) .addOption(newOptionWithArg(ARGUMENT.ARTIFACTORY_PARALLEL_ANALYSIS, "true/false", "Whether the Artifactory Analyzer should use parallel analysis.")) .addOption(newOptionWithArg(ARGUMENT.ARTIFACTORY_USES_PROXY, "true/false", "Whether the Artifactory Analyzer should use the proxy.")) .addOption(newOptionWithArg(ARGUMENT.ARTIFACTORY_USERNAME, "username", "The Artifactory username for authentication.")) .addOption(newOptionWithArg(ARGUMENT.ARTIFACTORY_API_TOKEN, "token", "The Artifactory API token.")) .addOption(newOptionWithArg(ARGUMENT.ARTIFACTORY_BEARER_TOKEN, "token", "The Artifactory bearer token.")) .addOption(newOptionWithArg(ARGUMENT.ARTIFACTORY_URL, "url", "The Artifactory URL.")) .addOption(newOptionWithArg(ARGUMENT.PATH_TO_GO, "path", "The path to the `go` executable.")) .addOption(newOptionWithArg(ARGUMENT.PATH_TO_YARN, "path", "The path to the `yarn` executable.")) .addOption(newOptionWithArg(ARGUMENT.CVE_VALID_FOR_HOURS, "hours", "The number of hours to wait before checking for new updates from the NVD.")) .addOption(newOptionWithArg(ARGUMENT.CVE_START_YEAR, "year", "The first year to retrieve NVD CVE data for; default is 2002.")) .addOption(newOptionWithArg(ARGUMENT.RETIREJS_FILTERS, "pattern", "Specify Retire JS content filter used to exclude files from analysis based on their content; " + "most commonly used to exclude based on your applications own copyright line. This " + "option can be specified multiple times.")) .addOption(newOptionWithArg(ARGUMENT.NEXUS_URL, "url", "The url to the Nexus Server's REST API Endpoint (http://domain/nexus/service/local). If not " + "set the Nexus Analyzer will be disabled.")) .addOption(newOptionWithArg(ARGUMENT.NEXUS_USERNAME, "username", "The username to authenticate to the Nexus Server's REST API Endpoint. If not set the Nexus " + "Analyzer will use an unauthenticated connection.")) .addOption(newOptionWithArg(ARGUMENT.NEXUS_PASSWORD, "password", "The password to authenticate to the Nexus Server's REST API Endpoint. If not set the Nexus " + "Analyzer will use an unauthenticated connection.")) //TODO remove as this should be covered by non-proxy hosts .addOption(newOptionWithArg(ARGUMENT.NEXUS_USES_PROXY, "true/false", "Whether or not the configured proxy should be used when connecting to Nexus.")) .addOption(newOptionWithArg(ARGUMENT.ADDITIONAL_ZIP_EXTENSIONS, "extensions", "A comma separated list of additional extensions to be scanned as ZIP files (ZIP, EAR, WAR " + "are already treated as zip files)")) .addOption(newOptionWithArg(ARGUMENT.PROP_SHORT, ARGUMENT.PROP, "file", "A property file to load.")) .addOption(newOptionWithArg(ARGUMENT.PATH_TO_CORE, "path", "The path to dotnet core.")) .addOption(newOptionWithArg(ARGUMENT.HINTS_FILE, "file", "The file path to the hints XML file.")) .addOption(newOption(ARGUMENT.RETIRED, "Enables the retired analyzers.")) .addOption(newOption(ARGUMENT.DISABLE_MSBUILD, "Disable the MS Build Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_JAR, "Disable the Jar Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_ARCHIVE, "Disable the Archive Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_ASSEMBLY, "Disable the .NET Assembly Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_PY_DIST, "Disable the Python Distribution Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_CMAKE, "Disable the Cmake Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_PY_PKG, "Disable the Python Package Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_MIX_AUDIT, "Disable the Elixir mix_audit Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_RUBYGEMS, "Disable the Ruby Gemspec Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_BUNDLE_AUDIT, "Disable the Ruby Bundler-Audit Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_FILENAME, "Disable the File Name Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_AUTOCONF, "Disable the Autoconf Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_PIP, "Disable the pip Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_PIPFILE, "Disable the Pipfile Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_COMPOSER, "Disable the PHP Composer Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_CPAN, "Disable the Perl CPAN file Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_GOLANG_MOD, "Disable the Golang Mod Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_OPENSSL, "Disable the OpenSSL Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_NUSPEC, "Disable the Nuspec Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_NUGETCONF, "Disable the Nuget packages.config Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_CENTRAL, "Disable the Central Analyzer. If this analyzer " + "is disabled it is likely you also want to disable the Nexus Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_CENTRAL_CACHE, "Disallow the Central Analyzer from caching results")) .addOption(newOption(ARGUMENT.DISABLE_OSSINDEX, "Disable the Sonatype OSS Index Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_OSSINDEX_CACHE, "Disallow the OSS Index Analyzer from caching results")) .addOption(newOption(ARGUMENT.DISABLE_COCOAPODS, "Disable the CocoaPods Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_SWIFT, "Disable the swift package Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_SWIFT_RESOLVED, "Disable the swift package resolved Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_GO_DEP, "Disable the Golang Package Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_NODE_JS, "Disable the Node.js Package Analyzer.")) .addOption(newOption(ARGUMENT.NODE_PACKAGE_SKIP_DEV_DEPENDENCIES, "Configures the Node Package Analyzer to skip devDependencies")) .addOption(newOption(ARGUMENT.DISABLE_NODE_AUDIT, "Disable the Node Audit Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_YARN_AUDIT, "Disable the Yarn Audit Analyzer.")) .addOption(newOption(ARGUMENT.DISABLE_NODE_AUDIT_CACHE, "Disallow the Node Audit Analyzer from caching results")) .addOption(newOption(ARGUMENT.DISABLE_NODE_AUDIT_SKIPDEV, "Configures the Node Audit Analyzer to skip devDependencies")) .addOption(newOption(ARGUMENT.DISABLE_RETIRE_JS, "Disable the RetireJS Analyzer.")) .addOption(newOption(ARGUMENT.ENABLE_NEXUS, "Disable the Nexus Analyzer.")) .addOption(newOption(ARGUMENT.ARTIFACTORY_ENABLED, "Whether the Artifactory Analyzer should be enabled.")) .addOption(newOption(ARGUMENT.PURGE_NVD, "Purges the local NVD data cache")); } // /** // * Adds the deprecated command line options to the given options collection. // * These are split out for purposes of not including them in the help // * message. We need to add the deprecated options so as not to break // * existing scripts. // * // * @param options a collection of command line arguments // */ // @SuppressWarnings({"static-access", "deprecation"}) // private void addDeprecatedOptions(final Options options) { // //all deprecated arguments have been removed (for now) // } /** * Determines if the 'version' command line argument was passed in. * * @return whether or not the 'version' command line argument was passed in */ public boolean isGetVersion() { return (line != null) && line.hasOption(ARGUMENT.VERSION); } /** * Determines if the 'help' command line argument was passed in. * * @return whether or not the 'help' command line argument was passed in */ public boolean isGetHelp() { return (line != null) && line.hasOption(ARGUMENT.HELP); } /** * Determines if the 'scan' command line argument was passed in. * * @return whether or not the 'scan' command line argument was passed in */ public boolean isRunScan() { return (line != null) && isValid && line.hasOption(ARGUMENT.SCAN); } /** * Returns the symbolic link depth (how deeply symbolic links will be * followed). * * @return the symbolic link depth */ public int getSymLinkDepth() { int value = 0; try { value = Integer.parseInt(line.getOptionValue(ARGUMENT.SYM_LINK_DEPTH, "0")); if (value < 0) { value = 0; } } catch (NumberFormatException ex) { LOGGER.debug("Symbolic link was not a number"); } return value; } /** * Utility method to determine if one of the disable options has been set. * If not set, this method will check the currently configured settings for * the current value to return. * <p> * Example given `--disableArchive` on the command line would cause this * method to return true for the disable archive setting. * * @param argument the command line argument * @param setting the corresponding settings key * @return true if the disable option was set, if not set the currently * configured value will be returned */ public boolean hasDisableOption(String argument, String setting) { if (line == null || !line.hasOption(argument)) { try { return !settings.getBoolean(setting); } catch (InvalidSettingException ise) { LOGGER.warn("Invalid property setting '{}' defaulting to false", setting); return false; } } else { return true; } } /** * Returns true if the disableNodeAudit command line argument was specified. * * @return true if the disableNodeAudit command line argument was specified; * otherwise false */ public boolean isNodeAuditDisabled() { if (hasDisableOption("disableNSP", Settings.KEYS.ANALYZER_NODE_AUDIT_ENABLED)) { LOGGER.error("The disableNSP argument has been deprecated and replaced by disableNodeAudit"); LOGGER.error("The disableNSP argument will be removed in the next version"); return true; } return hasDisableOption(ARGUMENT.DISABLE_NODE_AUDIT, Settings.KEYS.ANALYZER_NODE_AUDIT_ENABLED); } /** * Returns true if the disableYarnAudit command line argument was specified. * * @return true if the disableYarnAudit command line argument was specified; * otherwise false */ public boolean isYarnAuditDisabled() { return hasDisableOption(ARGUMENT.DISABLE_YARN_AUDIT, Settings.KEYS.ANALYZER_YARN_AUDIT_ENABLED); } /** * Returns true if the disablePnpmAudit command line argument was specified. * * @return true if the disablePnpmAudit command line argument was specified; * otherwise false */ public boolean isPnpmAuditDisabled() { return hasDisableOption(ARGUMENT.DISABLE_PNPM_AUDIT, Settings.KEYS.ANALYZER_PNPM_AUDIT_ENABLED); } /** * Returns true if the Nexus Analyzer should use the configured proxy to * connect to Nexus; otherwise false is returned. * * @return true if the Nexus Analyzer should use the configured proxy to * connect to Nexus; otherwise false */ public boolean isNexusUsesProxy() { // If they didn't specify whether Nexus needs to use the proxy, we should // still honor the property if it's set. if (line == null || !line.hasOption(ARGUMENT.NEXUS_USES_PROXY)) { try { return settings.getBoolean(Settings.KEYS.ANALYZER_NEXUS_USES_PROXY); } catch (InvalidSettingException ise) { return true; } } else { return Boolean.parseBoolean(line.getOptionValue(ARGUMENT.NEXUS_USES_PROXY)); } } /** * Returns the argument boolean value. * * @param argument the argument * @return the argument boolean value */ @SuppressFBWarnings(justification = "Accepting that this is a bad practice - used a Boolean as we needed three states", value = {"NP_BOOLEAN_RETURN_NULL"}) public Boolean getBooleanArgument(String argument) { if (line != null && line.hasOption(argument)) { final String value = line.getOptionValue(argument); if (value != null) { return Boolean.parseBoolean(value); } } return null; } /** * Returns the argument value for the given option. * * @param option the option * @return the value of the argument */ public String getStringArgument(String option) { return getStringArgument(option, null); } /** * Returns the argument value for the given option. * * @param option the option * @param key the dependency-check settings key for the option. * @return the value of the argument */ public String getStringArgument(String option, String key) { if (line != null && line.hasOption(option)) { if (key != null && (option.toLowerCase().endsWith("password") || option.toLowerCase().endsWith("pass"))) { LOGGER.warn("{} used on the command line, consider moving the password " + "to a properties file using the key `{}` and using the " + "--propertyfile argument instead", option, key); } return line.getOptionValue(option); } return null; } /** * Returns the argument value for the given option. * * @param option the option * @return the value of the argument */ public String[] getStringArguments(String option) { if (line != null && line.hasOption(option)) { return line.getOptionValues(option); } return null; } /** * Returns the argument value for the given option. * * @param option the option * @return the value of the argument */ public File getFileArgument(String option) { final String path = line.getOptionValue(option); if (path != null) { return new File(path); } return null; } /** * Displays the command line help message to the standard output. */ public void printHelp() { final HelpFormatter formatter = new HelpFormatter(); final Options options = new Options(); addStandardOptions(options); if (line != null && line.hasOption(ARGUMENT.ADVANCED_HELP)) { addAdvancedOptions(options); } final String helpMsg = String.format("%n%s" + " can be used to identify if there are any known CVE vulnerabilities in libraries utilized by an application. " + "%s will automatically update required data from the Internet, such as the CVE and CPE data files from nvd.nist.gov.%n%n", settings.getString(Settings.KEYS.APPLICATION_NAME, "DependencyCheck"), settings.getString(Settings.KEYS.APPLICATION_NAME, "DependencyCheck")); formatter.printHelp(settings.getString(Settings.KEYS.APPLICATION_NAME, "DependencyCheck"), helpMsg, options, "", true); } /** * Retrieves the file command line parameter(s) specified for the 'scan' * argument. * * @return the file paths specified on the command line for scan */ public String[] getScanFiles() { return line.getOptionValues(ARGUMENT.SCAN); } /** * Retrieves the list of excluded file patterns specified by the 'exclude' * argument. * * @return the excluded file patterns */ public String[] getExcludeList() { return line.getOptionValues(ARGUMENT.EXCLUDE); } /** * Retrieves the list of retire JS content filters used to exclude JS files * by content. * * @return the retireJS filters */ public String[] getRetireJsFilters() { return line.getOptionValues(ARGUMENT.RETIREJS_FILTERS); } /** * Returns whether or not the retireJS analyzer should exclude * non-vulnerable JS from the report. * * @return <code>true</code> if non-vulnerable JS should be filtered in the * RetireJS Analyzer; otherwise <code>null</code> */ @SuppressFBWarnings(justification = "Accepting that this is a bad practice - but made more sense in this use case", value = {"NP_BOOLEAN_RETURN_NULL"}) public Boolean isRetireJsFilterNonVulnerable() { return (line != null && line.hasOption(ARGUMENT.RETIREJS_FILTER_NON_VULNERABLE)) ? true : null; } /** * Returns the directory to write the reports to specified on the command * line. * * @return the path to the reports directory. */ public String getReportDirectory() { return line.getOptionValue(ARGUMENT.OUT, "."); } /** * Returns the output format specified on the command line. Defaults to HTML * if no format was specified. * * @return the output format name. */ public String[] getReportFormat() { if (line.hasOption(ARGUMENT.OUTPUT_FORMAT)) { return line.getOptionValues(ARGUMENT.OUTPUT_FORMAT); } return new String[]{"HTML"}; } /** * Returns the application name specified on the command line. * * @return the application name. */ public String getProjectName() { String name = line.getOptionValue(ARGUMENT.PROJECT); if (name == null) { name = ""; } return name; } /** * <p> * Prints the manifest information to standard output.</p> * <ul><li>Implementation-Title: ${pom.name}</li> * <li>Implementation-Version: ${pom.version}</li></ul> */ public void printVersionInfo() { final String version = String.format("%s version %s", settings.getString(Settings.KEYS.APPLICATION_NAME, "dependency-check"), settings.getString(Settings.KEYS.APPLICATION_VERSION, "Unknown")); System.out.println(version); } /** * Checks if the update only flag has been set. * * @return <code>true</code> if the update only flag has been set; otherwise * <code>false</code>. */ public boolean isUpdateOnly() { return line != null && line.hasOption(ARGUMENT.UPDATE_ONLY); } /** * Checks if the purge NVD flag has been set. * * @return <code>true</code> if the purge nvd flag has been set; otherwise * <code>false</code>. */ public boolean isPurge() { return line != null && line.hasOption(ARGUMENT.PURGE_NVD); } /** * Returns the database driver name if specified; otherwise null is * returned. * * @return the database driver name if specified; otherwise null is returned */ public String getDatabaseDriverName() { return line.getOptionValue(ARGUMENT.DB_DRIVER); } /** * Returns the argument value. * * @param argument the argument * @return the value of the argument */ public Integer getIntegerValue(String argument) { final String v = line.getOptionValue(argument); if (v != null) { return Integer.parseInt(v); } return null; } /** * Checks if the option is present. If present it will return * <code>true</code>; otherwise <code>false</code>. * * @param option the option to check * @return <code>true</code> if auto-update is allowed; otherwise * <code>null</code> */ @SuppressFBWarnings(justification = "Accepting that this is a bad practice - but made more sense in this use case", value = {"NP_BOOLEAN_RETURN_NULL"}) public Boolean hasOption(String option) { return (line != null && line.hasOption(option)) ? true : null; } /** * Returns the CVSS value to fail on. * * @return 11 if nothing is set. Otherwise it returns the int passed from * the command line arg */ public float getFailOnCVSS() { if (line.hasOption(ARGUMENT.FAIL_ON_CVSS)) { final String value = line.getOptionValue(ARGUMENT.FAIL_ON_CVSS); try { return Float.parseFloat(value); } catch (NumberFormatException nfe) { return 11; } } else { return 11; } } /** * Returns the float argument for the given option. * * @param option the option * @param defaultValue the value if the option is not present * @return the value of the argument if present; otherwise the defaultValue */ public float getFloatArgument(String option, float defaultValue) { if (line.hasOption(option)) { final String value = line.getOptionValue(option); try { return Integer.parseInt(value); } catch (NumberFormatException nfe) { return defaultValue; } } else { return defaultValue; } } /** * Builds a new option. * * @param name the long name * @param description the description * @return a new option */ private Option newOption(String name, String description) { return Option.builder().longOpt(name).desc(description).build(); } /** * Builds a new option. * * @param shortName the short name * @param name the long name * @param description the description * @return a new option */ private Option newOption(String shortName, String name, String description) { return Option.builder(shortName).longOpt(name).desc(description).build(); } /** * Builds a new option. * * @param name the long name * @param arg the argument name * @param description the description * @return a new option */ private Option newOptionWithArg(String name, String arg, String description) { return Option.builder().longOpt(name).argName(arg).hasArg().desc(description).build(); } /** * Builds a new option. * * @param shortName the short name * @param name the long name * @param arg the argument name * @param description the description * @return a new option */ private Option newOptionWithArg(String shortName, String name, String arg, String description) { return Option.builder(shortName).longOpt(name).argName(arg).hasArg().desc(description).build(); } /** * Builds a new option group so that an option can be specified multiple * times on the command line. * * @param option the option to add to the group * @return a new option group */ private OptionGroup newOptionGroup(Option option) { final OptionGroup group = new OptionGroup(); group.addOption(option); return group; } /** * A collection of static final strings that represent the possible command * line arguments. */ public static class ARGUMENT { /** * The long CLI argument name specifying the directory/file to scan. */ public static final String SCAN = "scan"; /** * The short CLI argument name specifying the directory/file to scan. */ public static final String SCAN_SHORT = "s"; /** * The long CLI argument name specifying that the CPE/CVE/etc. data * should not be automatically updated. */ public static final String DISABLE_AUTO_UPDATE = "noupdate"; /** * The short CLI argument name specifying that the CPE/CVE/etc. data * should not be automatically updated. */ public static final String DISABLE_AUTO_UPDATE_SHORT = "n"; /** * The long CLI argument name specifying that only the update phase * should be executed; no scan should be run. */ public static final String UPDATE_ONLY = "updateonly"; /** * The long CLI argument name specifying that only the update phase * should be executed; no scan should be run. */ public static final String PURGE_NVD = "purge"; /** * The long CLI argument name specifying the directory to write the * reports to. */ public static final String OUT = "out"; /** * The short CLI argument name specifying the directory to write the * reports to. */ public static final String OUT_SHORT = "o"; /** * The long CLI argument name specifying the output format to write the * reports to. */ public static final String OUTPUT_FORMAT = "format"; /** * The short CLI argument name specifying the output format to write the * reports to. */ public static final String OUTPUT_FORMAT_SHORT = "f"; /** * The long CLI argument name specifying the name of the project to be * scanned. */ public static final String PROJECT = "project"; /** * The long CLI argument name asking for help. */ public static final String HELP = "help"; /** * The long CLI argument name asking for advanced help. */ public static final String ADVANCED_HELP = "advancedHelp"; /** * The short CLI argument name asking for help. */ public static final String HELP_SHORT = "h"; /** * The long CLI argument name asking for the version. */ public static final String VERSION_SHORT = "v"; /** * The short CLI argument name asking for the version. */ public static final String VERSION = "version"; /** * The CLI argument name indicating the proxy port. */ public static final String PROXY_PORT = "proxyport"; /** * The CLI argument name indicating the proxy server. */ public static final String PROXY_SERVER = "proxyserver"; /** * The CLI argument name indicating the proxy username. */ public static final String PROXY_USERNAME = "proxyuser"; /** * The CLI argument name indicating the proxy password. */ public static final String PROXY_PASSWORD = "proxypass"; /** * The CLI argument name indicating the proxy proxy exclusion list. */ public static final String NON_PROXY_HOSTS = "nonProxyHosts"; /** * The short CLI argument name indicating the connection timeout. */ public static final String CONNECTION_TIMEOUT_SHORT = "c"; /** * The CLI argument name indicating the connection timeout. */ public static final String CONNECTION_TIMEOUT = "connectiontimeout"; /** * The short CLI argument name for setting the location of an additional * properties file. */ public static final String PROP_SHORT = "P"; /** * The CLI argument name for setting the location of an additional * properties file. */ public static final String PROP = "propertyfile"; /** * The CLI argument name for setting the location of the data directory. */ public static final String DATA_DIRECTORY = "data"; /** * The CLI argument name for setting the URL for the CVE Data Files. */ public static final String CVE_MODIFIED_URL = "cveUrlModified"; /** * The CLI argument name for setting the URL for the CVE Data Files. */ public static final String CVE_BASE_URL = "cveUrlBase"; /** * The time in milliseconds to wait between downloading NVD CVE data. */ public static final String CVE_DOWNLOAD_WAIT_TIME = "cveDownloadWait"; /** * The short CLI argument name for setting the location of the data * directory. */ public static final String DATA_DIRECTORY_SHORT = "d"; /** * The CLI argument name for setting the location of the data directory. */ public static final String VERBOSE_LOG = "log"; /** * The short CLI argument name for setting the location of the data * directory. */ public static final String VERBOSE_LOG_SHORT = "l"; /** * The CLI argument name for setting the depth of symbolic links that * will be followed. */ public static final String SYM_LINK_DEPTH = "symLink"; /** * The CLI argument name for setting the location of the suppression * file(s). */ public static final String SUPPRESSION_FILES = "suppression"; /** * The CLI argument name for setting the location of the hint file. */ public static final String HINTS_FILE = "hints"; /** * The CLI argument name for setting the number of hours to wait before * checking for new updates from the NVD. */ public static final String CVE_VALID_FOR_HOURS = "cveValidForHours"; /** * The CLI argument name for setting the first year to retrieve NVD * data. */ public static final String CVE_START_YEAR = "cveStartYear"; /** * The username for basic auth to the CVE data. */ public static final String CVE_USER = "cveUser"; /** * The password for basic auth to the CVE data. */ public static final String CVE_PASSWORD = "cvePassword"; /** * Disables the Jar Analyzer. */ public static final String DISABLE_JAR = "disableJar"; /** * Disable the MS Build Analyzer. */ public static final String DISABLE_MSBUILD = "disableMSBuild"; /** * Disables the Archive Analyzer. */ public static final String DISABLE_ARCHIVE = "disableArchive"; /** * Disables the Python Distribution Analyzer. */ public static final String DISABLE_PY_DIST = "disablePyDist"; /** * Disables the Python Package Analyzer. */ public static final String DISABLE_PY_PKG = "disablePyPkg"; /** * Disables the Elixir mix audit Analyzer. */ public static final String DISABLE_MIX_AUDIT = "disableMixAudit"; /** * Disables the Golang Dependency Analyzer. */ public static final String DISABLE_GO_DEP = "disableGolangDep"; /** * Disables the PHP Composer Analyzer. */ public static final String DISABLE_COMPOSER = "disableComposer"; /** * Disables the Perl CPAN File Analyzer. */ public static final String DISABLE_CPAN = "disableCpan"; /** * Disables the Golang Mod Analyzer. */ public static final String DISABLE_GOLANG_MOD = "disableGolangMod"; /** * The CLI argument name for setting the path to `go`. */ public static final String PATH_TO_GO = "go"; /** * The CLI argument name for setting the path to `yarn`. */ public static final String PATH_TO_YARN = "yarn"; /** * The CLI argument name for setting the path to `pnpm`. */ public static final String PATH_TO_PNPM = "pnpm"; /** * Disables the Ruby Gemspec Analyzer. */ public static final String DISABLE_RUBYGEMS = "disableRubygems"; /** * Disables the Autoconf Analyzer. */ public static final String DISABLE_AUTOCONF = "disableAutoconf"; /** * Disables the pip Analyzer. */ public static final String DISABLE_PIP = "disablePip"; /** * Disables the Pipfile Analyzer. */ public static final String DISABLE_PIPFILE = "disablePipfile"; /** * Disables the Cmake Analyzer. */ public static final String DISABLE_CMAKE = "disableCmake"; /** * Disables the cocoapods analyzer. */ public static final String DISABLE_COCOAPODS = "disableCocoapodsAnalyzer"; /** * Disables the swift package manager analyzer. */ public static final String DISABLE_SWIFT = "disableSwiftPackageManagerAnalyzer"; /** * Disables the swift package resolved analyzer. */ public static final String DISABLE_SWIFT_RESOLVED = "disableSwiftPackageResolvedAnalyzer"; /** * Disables the Assembly Analyzer. */ public static final String DISABLE_ASSEMBLY = "disableAssembly"; /** * Disables the Ruby Bundler Audit Analyzer. */ public static final String DISABLE_BUNDLE_AUDIT = "disableBundleAudit"; /** * Disables the File Name Analyzer. */ public static final String DISABLE_FILENAME = "disableFileName"; /** * Disables the Nuspec Analyzer. */ public static final String DISABLE_NUSPEC = "disableNuspec"; /** * Disables the Nuget packages.config Analyzer. */ public static final String DISABLE_NUGETCONF = "disableNugetconf"; /** * Disables the Central Analyzer. */ public static final String DISABLE_CENTRAL = "disableCentral"; /** * Disables the Central Analyzer's ability to cache results locally. */ public static final String DISABLE_CENTRAL_CACHE = "disableCentralCache"; /** * Disables the Nexus Analyzer. */ public static final String ENABLE_NEXUS = "enableNexus"; /** * Disables the Sonatype OSS Index Analyzer. */ public static final String DISABLE_OSSINDEX = "disableOssIndex"; /** * Disables the Sonatype OSS Index Analyzer's ability to cache results * locally. */ public static final String DISABLE_OSSINDEX_CACHE = "disableOssIndexCache"; /** * The username for the Sonatype OSS Index. */ public static final String OSSINDEX_USERNAME = "ossIndexUsername"; /** * The password for the Sonatype OSS Index. */ public static final String OSSINDEX_PASSWORD = "ossIndexPassword"; /** * Disables the OpenSSL Analyzer. */ public static final String DISABLE_OPENSSL = "disableOpenSSL"; /** * Disables the Node.js Package Analyzer. */ public static final String DISABLE_NODE_JS = "disableNodeJS"; /** * Skips dev dependencies in Node Package Analyzer. */ public static final String NODE_PACKAGE_SKIP_DEV_DEPENDENCIES = "nodePackageSkipDevDependencies"; /** * Disables the Node Audit Analyzer. */ public static final String DISABLE_NODE_AUDIT = "disableNodeAudit"; /** * Disables the Yarn Audit Analyzer. */ public static final String DISABLE_YARN_AUDIT = "disableYarnAudit"; /** * Disables the Pnpm Audit Analyzer. */ public static final String DISABLE_PNPM_AUDIT = "disablePnpmAudit"; /** * Disables the Node Audit Analyzer's ability to cache results locally. */ public static final String DISABLE_NODE_AUDIT_CACHE = "disableNodeAuditCache"; /** * Configures the Node Audit Analyzer to skip the dev dependencies. */ public static final String DISABLE_NODE_AUDIT_SKIPDEV = "nodeAuditSkipDevDependencies"; /** * Disables the RetireJS Analyzer. */ public static final String DISABLE_RETIRE_JS = "disableRetireJS"; /** * Whether the RetireJS Analyzer will update regardless of the * `autoupdate` setting. */ public static final String RETIRE_JS_FORCEUPDATE = "retireJsForceUpdate"; /** * The URL to the retire JS repository. */ public static final String RETIREJS_URL = "retireJsUrl"; /** * The URL of the nexus server. */ public static final String NEXUS_URL = "nexus"; /** * The username for the nexus server. */ public static final String NEXUS_USERNAME = "nexusUser"; /** * The password for the nexus server. */ public static final String NEXUS_PASSWORD = "nexusPass"; /** * Whether or not the defined proxy should be used when connecting to * Nexus. */ public static final String NEXUS_USES_PROXY = "nexusUsesProxy"; /** * The CLI argument name for setting the connection string. */ public static final String CONNECTION_STRING = "connectionString"; /** * The CLI argument name for setting the database user name. */ public static final String DB_NAME = "dbUser"; /** * The CLI argument name for setting the database password. */ public static final String DB_PASSWORD = "dbPassword"; /** * The CLI argument name for setting the database driver name. */ public static final String DB_DRIVER = "dbDriverName"; /** * The CLI argument name for setting the path to the database driver; in * case it is not on the class path. */ public static final String DB_DRIVER_PATH = "dbDriverPath"; /** * The CLI argument name for setting the path to dotnet core. */ public static final String PATH_TO_CORE = "dotnet"; /** * The CLI argument name for setting extra extensions. */ public static final String ADDITIONAL_ZIP_EXTENSIONS = "zipExtensions"; /** * Exclude path argument. */ public static final String EXCLUDE = "exclude"; /** * The CLI argument name for setting the path to bundle-audit for Ruby * bundle analysis. */ public static final String PATH_TO_BUNDLE_AUDIT = "bundleAudit"; /** * The CLI argument name for setting the path that should be used as the * working directory that the bundle-audit command used for Ruby bundle * analysis should be executed from. This will allow for the usage of * rbenv */ public static final String PATH_TO_BUNDLE_AUDIT_WORKING_DIRECTORY = "bundleAuditWorkingDirectory"; /** * The CLI argument name for setting the path to mix_audit for Elixir * analysis. */ public static final String PATH_TO_MIX_AUDIT = "mixAudit"; /** * The CLI argument to enable the experimental analyzers. */ public static final String EXPERIMENTAL = "enableExperimental"; /** * The CLI argument to enable the retired analyzers. */ public static final String RETIRED = "enableRetired"; /** * The CLI argument for the retire js content filters. */ public static final String RETIREJS_FILTERS = "retirejsFilter"; /** * The CLI argument for the retire js content filters. */ public static final String RETIREJS_FILTER_NON_VULNERABLE = "retirejsFilterNonVulnerable"; /** * The CLI argument for indicating if the Artifactory analyzer should be * enabled. */ public static final String ARTIFACTORY_ENABLED = "enableArtifactory"; /** * The CLI argument for indicating if the Artifactory analyzer should * use the proxy. */ public static final String ARTIFACTORY_URL = "artifactoryUrl"; /** * The CLI argument for indicating the Artifactory username. */ public static final String ARTIFACTORY_USERNAME = "artifactoryUsername"; /** * The CLI argument for indicating the Artifactory API token. */ public static final String ARTIFACTORY_API_TOKEN = "artifactoryApiToken"; /** * The CLI argument for indicating the Artifactory bearer token. */ public static final String ARTIFACTORY_BEARER_TOKEN = "artifactoryBearerToken"; /** * The CLI argument for indicating if the Artifactory analyzer should * use the proxy. */ public static final String ARTIFACTORY_USES_PROXY = "artifactoryUseProxy"; /** * The CLI argument for indicating if the Artifactory analyzer should * use the parallel analysis. */ public static final String ARTIFACTORY_PARALLEL_ANALYSIS = "artifactoryParallelAnalysis"; /** * The CLI argument to configure when the execution should be considered * a failure. */ public static final String FAIL_ON_CVSS = "failOnCVSS"; /** * The CLI argument to configure if the XML and JSON reports should be * pretty printed. */ public static final String PRETTY_PRINT = "prettyPrint"; /** * The CLI argument to set the threshold that is considered a failure * when generating the JUNIT report format. */ public static final String FAIL_JUNIT_ON_CVSS = "junitFailOnCVSS"; } }
fix pnpm CLI arg
cli/src/main/java/org/owasp/dependencycheck/CliParser.java
fix pnpm CLI arg
<ide><path>li/src/main/java/org/owasp/dependencycheck/CliParser.java <ide> "The path to the `go` executable.")) <ide> .addOption(newOptionWithArg(ARGUMENT.PATH_TO_YARN, "path", <ide> "The path to the `yarn` executable.")) <add> .addOption(newOptionWithArg(ARGUMENT.PATH_TO_PNPM, "path", <add> "The path to the `pnpm` executable.")) <ide> .addOption(newOptionWithArg(ARGUMENT.CVE_VALID_FOR_HOURS, "hours", <ide> "The number of hours to wait before checking for new updates from the NVD.")) <ide> .addOption(newOptionWithArg(ARGUMENT.CVE_START_YEAR, "year",
Java
bsd-2-clause
c3ff11db783d8f5a335d309fc211e839c7f52c5b
0
TehSAUCE/imagej,TehSAUCE/imagej,TehSAUCE/imagej,biovoxxel/imagej,biovoxxel/imagej,biovoxxel/imagej
plugins/commands/src/main/java/imagej/core/commands/debug/ParameterTester.java
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2013 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package imagej.core.commands.debug; import imagej.command.Command; import imagej.command.Previewable; import imagej.data.Dataset; import imagej.util.ColorRGB; import imagej.widget.ChoiceWidget; import imagej.widget.NumberWidget; import java.io.File; import java.math.BigDecimal; import java.math.BigInteger; import org.scijava.ItemIO; import org.scijava.ItemVisibility; import org.scijava.event.StatusService; import org.scijava.log.LogService; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; /** * Test plugin for verifying that various plugin features work properly. * * @author Curtis Rueden */ @Plugin(type = Command.class, menuPath = "Plugins>Debug>Parameter Tester", headless = true) public class ParameterTester implements Command, Previewable { @Parameter private LogService log; @Parameter private StatusService statusService; @Parameter(visibility = ItemVisibility.MESSAGE) private final String label = "The parameter tester demonstrates various widgets in action!"; @Parameter(label = "boolean") private boolean pBoolean; @Parameter(label = "Boolean") private Boolean oBoolean; @Parameter(label = "byte") private byte pByte; @Parameter(label = "double") private double pDouble; @Parameter(label = "float") private float pFloat; @Parameter(label = "int") private int pInt; @Parameter(label = "long") private long pLong; @Parameter(label = "short") private short pShort; @Parameter(label = "Byte") private Byte oByte; @Parameter(label = "Double") private Double oDouble; @Parameter(label = "Float") private Float oFloat; @Parameter(label = "Integer") private Integer oInt; @Parameter(label = "Long") private Long oLong; @Parameter(label = "Short") private Short oShort; @Parameter private BigInteger bigInteger; @Parameter private BigDecimal bigDecimal; @Parameter(label = "char") private char pChar; @Parameter(label = "Character") private Character oChar; @Parameter(label = "String") private String string; @Parameter(label = "multiple choice", choices = { "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog" }) private String choice; @Parameter private File file; @Parameter private ColorRGB color; @Parameter private Dataset dataset; @Parameter(label = "spinner", style = NumberWidget.SPINNER_STYLE, min = "0", max = "1000") private int spinnerNumber; @Parameter(label = "slider", style = NumberWidget.SLIDER_STYLE, min = "0", max = "1000", stepSize = "50") private int sliderNumber; @Parameter(label = "scroll bar", style = NumberWidget.SCROLL_BAR_STYLE, min = "0", max = "1000") private int scrollBarNumber; @Parameter(label = "radio buttons", style = ChoiceWidget.RADIO_BUTTON_HORIZONTAL_STYLE, choices = { "Yes", "No", "Maybe" }) private String choiceRadioH; @Parameter(label = "radio buttons", style = ChoiceWidget.RADIO_BUTTON_VERTICAL_STYLE, choices = { "Loved", "Really liked", "Liked", "Disliked", "Really disliked" }) private String choiceRadioV; @Parameter(label = "x", callback = "xChanged") private float x; @Parameter(label = "2x", description = "Demonstrates callback functionality. Equal to double x.", callback = "twoXChanged") private float twoX; @Parameter(description = "Demonstrates preview functionality by " + "displaying the given message in the ImageJ status bar.") private String message = "Type a status message here."; @Parameter(label = "Results", type = ItemIO.OUTPUT) private String output; public String getOutput() { return output; } @Override public void run() { final StringBuilder sb = new StringBuilder(); append(sb, "ParameterTester results:"); append(sb, ""); append(sb, "-- Toggles --"); append(sb, "\tboolean = " + pBoolean); append(sb, "\tBoolean = " + oBoolean); append(sb, ""); append(sb, "-- Numeric --"); append(sb, "\tbyte = " + pByte); append(sb, "\tdouble = " + pDouble); append(sb, "\tfloat = " + pFloat); append(sb, "\tint = " + pInt); append(sb, "\tlong = " + pLong); append(sb, "\tshort = " + pShort); append(sb, "\tByte = " + oByte); append(sb, "\tDouble = " + oDouble); append(sb, "\tFloat = " + oFloat); append(sb, "\tInteger = " + oInt); append(sb, "\tLong = " + oLong); append(sb, "\tShort = " + oShort); append(sb, "\tBigInteger = " + bigInteger); append(sb, "\tBigDecimal = " + bigDecimal); append(sb, ""); append(sb, "-- Text --"); append(sb, "\tchar = " + "'" + pChar + "' [" + Character.getNumericValue(pChar) + "]"); final String oCharValue = oChar == null ? "null" : "" + Character.getNumericValue(oChar); append(sb, "\tCharacter = " + "'" + oChar + "' [" + oCharValue + "]"); append(sb, "\tString = " + string); append(sb, ""); append(sb, "-- Choice --"); append(sb, "\tchoice = " + choice); append(sb, ""); append(sb, "-- Object --"); append(sb, "\tDataset = " + dataset); append(sb, ""); append(sb, "-- File --"); append(sb, "\tFile = " + file); append(sb, ""); append(sb, "-- Color --"); append(sb, "\tcolor = " + color); append(sb, ""); append(sb, "-- Widget styles --"); append(sb, "\tnumber (spinner) = " + spinnerNumber); append(sb, "\tnumber (slider) = " + sliderNumber); append(sb, "\tnumber (scroll bar) = " + scrollBarNumber); append(sb, "\tradio buttons (horizontal) = " + choiceRadioH); append(sb, "\tradio buttons (vertical) = " + choiceRadioV); append(sb, ""); append(sb, "-- Miscellaneous --"); append(sb, "\tx = " + x); append(sb, "\t2x = " + twoX); append(sb, "\tmessage = " + message); output = sb.toString(); } private int previews = 0; @Override public void preview() { log.info("ParameterTester: " + ++previews + " previews and counting"); statusService.showStatus(message); } @Override public void cancel() { log.info("ParameterTester: canceled"); } @SuppressWarnings("unused") private void xChanged() { log.info("ParameterTester: x changed"); twoX = x * 2; } @SuppressWarnings("unused") private void twoXChanged() { log.info("ParameterTester: 2x changed"); x = twoX / 2; } private void append(final StringBuilder sb, final String s) { sb.append(s + "\n"); } }
Move ParameterTester example to ImageJ tutorials
plugins/commands/src/main/java/imagej/core/commands/debug/ParameterTester.java
Move ParameterTester example to ImageJ tutorials
<ide><path>lugins/commands/src/main/java/imagej/core/commands/debug/ParameterTester.java <del>/* <del> * #%L <del> * ImageJ software for multidimensional image processing and analysis. <del> * %% <del> * Copyright (C) 2009 - 2013 Board of Regents of the University of <del> * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck <del> * Institute of Molecular Cell Biology and Genetics. <del> * %% <del> * Redistribution and use in source and binary forms, with or without <del> * modification, are permitted provided that the following conditions are met: <del> * <del> * 1. Redistributions of source code must retain the above copyright notice, <del> * this list of conditions and the following disclaimer. <del> * 2. Redistributions in binary form must reproduce the above copyright notice, <del> * this list of conditions and the following disclaimer in the documentation <del> * and/or other materials provided with the distribution. <del> * <del> * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" <del> * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE <del> * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE <del> * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE <del> * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR <del> * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF <del> * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS <del> * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN <del> * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) <del> * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE <del> * POSSIBILITY OF SUCH DAMAGE. <del> * <del> * The views and conclusions contained in the software and documentation are <del> * those of the authors and should not be interpreted as representing official <del> * policies, either expressed or implied, of any organization. <del> * #L% <del> */ <del> <del>package imagej.core.commands.debug; <del> <del>import imagej.command.Command; <del>import imagej.command.Previewable; <del>import imagej.data.Dataset; <del>import imagej.util.ColorRGB; <del>import imagej.widget.ChoiceWidget; <del>import imagej.widget.NumberWidget; <del> <del>import java.io.File; <del>import java.math.BigDecimal; <del>import java.math.BigInteger; <del> <del>import org.scijava.ItemIO; <del>import org.scijava.ItemVisibility; <del>import org.scijava.event.StatusService; <del>import org.scijava.log.LogService; <del>import org.scijava.plugin.Parameter; <del>import org.scijava.plugin.Plugin; <del> <del>/** <del> * Test plugin for verifying that various plugin features work properly. <del> * <del> * @author Curtis Rueden <del> */ <del>@Plugin(type = Command.class, menuPath = "Plugins>Debug>Parameter Tester", <del> headless = true) <del>public class ParameterTester implements Command, Previewable { <del> <del> @Parameter <del> private LogService log; <del> <del> @Parameter <del> private StatusService statusService; <del> <del> @Parameter(visibility = ItemVisibility.MESSAGE) <del> private final String label = <del> "The parameter tester demonstrates various widgets in action!"; <del> <del> @Parameter(label = "boolean") <del> private boolean pBoolean; <del> <del> @Parameter(label = "Boolean") <del> private Boolean oBoolean; <del> <del> @Parameter(label = "byte") <del> private byte pByte; <del> <del> @Parameter(label = "double") <del> private double pDouble; <del> <del> @Parameter(label = "float") <del> private float pFloat; <del> <del> @Parameter(label = "int") <del> private int pInt; <del> <del> @Parameter(label = "long") <del> private long pLong; <del> <del> @Parameter(label = "short") <del> private short pShort; <del> <del> @Parameter(label = "Byte") <del> private Byte oByte; <del> <del> @Parameter(label = "Double") <del> private Double oDouble; <del> <del> @Parameter(label = "Float") <del> private Float oFloat; <del> <del> @Parameter(label = "Integer") <del> private Integer oInt; <del> <del> @Parameter(label = "Long") <del> private Long oLong; <del> <del> @Parameter(label = "Short") <del> private Short oShort; <del> <del> @Parameter <del> private BigInteger bigInteger; <del> <del> @Parameter <del> private BigDecimal bigDecimal; <del> <del> @Parameter(label = "char") <del> private char pChar; <del> <del> @Parameter(label = "Character") <del> private Character oChar; <del> <del> @Parameter(label = "String") <del> private String string; <del> <del> @Parameter(label = "multiple choice", choices = { "The", "quick", "brown", <del> "fox", "jumps", "over", "the", "lazy", "dog" }) <del> private String choice; <del> <del> @Parameter <del> private File file; <del> <del> @Parameter <del> private ColorRGB color; <del> <del> @Parameter <del> private Dataset dataset; <del> <del> @Parameter(label = "spinner", style = NumberWidget.SPINNER_STYLE, min = "0", <del> max = "1000") <del> private int spinnerNumber; <del> <del> @Parameter(label = "slider", style = NumberWidget.SLIDER_STYLE, min = "0", <del> max = "1000", stepSize = "50") <del> private int sliderNumber; <del> <del> @Parameter(label = "scroll bar", style = NumberWidget.SCROLL_BAR_STYLE, <del> min = "0", max = "1000") <del> private int scrollBarNumber; <del> <del> @Parameter(label = "radio buttons", <del> style = ChoiceWidget.RADIO_BUTTON_HORIZONTAL_STYLE, choices = { "Yes", <del> "No", "Maybe" }) <del> private String choiceRadioH; <del> <del> @Parameter(label = "radio buttons", <del> style = ChoiceWidget.RADIO_BUTTON_VERTICAL_STYLE, choices = { "Loved", <del> "Really liked", "Liked", "Disliked", "Really disliked" }) <del> private String choiceRadioV; <del> <del> @Parameter(label = "x", callback = "xChanged") <del> private float x; <del> <del> @Parameter(label = "2x", <del> description = "Demonstrates callback functionality. Equal to double x.", <del> callback = "twoXChanged") <del> private float twoX; <del> <del> @Parameter(description = "Demonstrates preview functionality by " <del> + "displaying the given message in the ImageJ status bar.") <del> private String message = "Type a status message here."; <del> <del> @Parameter(label = "Results", type = ItemIO.OUTPUT) <del> private String output; <del> <del> public String getOutput() { <del> return output; <del> } <del> <del> @Override <del> public void run() { <del> final StringBuilder sb = new StringBuilder(); <del> <del> append(sb, "ParameterTester results:"); <del> <del> append(sb, ""); <del> append(sb, "-- Toggles --"); <del> append(sb, "\tboolean = " + pBoolean); <del> append(sb, "\tBoolean = " + oBoolean); <del> <del> append(sb, ""); <del> append(sb, "-- Numeric --"); <del> append(sb, "\tbyte = " + pByte); <del> append(sb, "\tdouble = " + pDouble); <del> append(sb, "\tfloat = " + pFloat); <del> append(sb, "\tint = " + pInt); <del> append(sb, "\tlong = " + pLong); <del> append(sb, "\tshort = " + pShort); <del> append(sb, "\tByte = " + oByte); <del> append(sb, "\tDouble = " + oDouble); <del> append(sb, "\tFloat = " + oFloat); <del> append(sb, "\tInteger = " + oInt); <del> append(sb, "\tLong = " + oLong); <del> append(sb, "\tShort = " + oShort); <del> append(sb, "\tBigInteger = " + bigInteger); <del> append(sb, "\tBigDecimal = " + bigDecimal); <del> <del> append(sb, ""); <del> append(sb, "-- Text --"); <del> append(sb, "\tchar = " + "'" + pChar + "' [" + <del> Character.getNumericValue(pChar) + "]"); <del> final String oCharValue = <del> oChar == null ? "null" : "" + Character.getNumericValue(oChar); <del> append(sb, "\tCharacter = " + "'" + oChar + "' [" + oCharValue + "]"); <del> append(sb, "\tString = " + string); <del> <del> append(sb, ""); <del> append(sb, "-- Choice --"); <del> append(sb, "\tchoice = " + choice); <del> <del> append(sb, ""); <del> append(sb, "-- Object --"); <del> append(sb, "\tDataset = " + dataset); <del> <del> append(sb, ""); <del> append(sb, "-- File --"); <del> append(sb, "\tFile = " + file); <del> <del> append(sb, ""); <del> append(sb, "-- Color --"); <del> append(sb, "\tcolor = " + color); <del> <del> append(sb, ""); <del> append(sb, "-- Widget styles --"); <del> append(sb, "\tnumber (spinner) = " + spinnerNumber); <del> append(sb, "\tnumber (slider) = " + sliderNumber); <del> append(sb, "\tnumber (scroll bar) = " + scrollBarNumber); <del> append(sb, "\tradio buttons (horizontal) = " + choiceRadioH); <del> append(sb, "\tradio buttons (vertical) = " + choiceRadioV); <del> <del> append(sb, ""); <del> append(sb, "-- Miscellaneous --"); <del> append(sb, "\tx = " + x); <del> append(sb, "\t2x = " + twoX); <del> append(sb, "\tmessage = " + message); <del> <del> output = sb.toString(); <del> } <del> <del> private int previews = 0; <del> <del> @Override <del> public void preview() { <del> log.info("ParameterTester: " + ++previews + " previews and counting"); <del> statusService.showStatus(message); <del> } <del> <del> @Override <del> public void cancel() { <del> log.info("ParameterTester: canceled"); <del> } <del> <del> @SuppressWarnings("unused") <del> private void xChanged() { <del> log.info("ParameterTester: x changed"); <del> twoX = x * 2; <del> } <del> <del> @SuppressWarnings("unused") <del> private void twoXChanged() { <del> log.info("ParameterTester: 2x changed"); <del> x = twoX / 2; <del> } <del> <del> private void append(final StringBuilder sb, final String s) { <del> sb.append(s + "\n"); <del> } <del> <del>}
Java
mit
error: pathspec '1-algorithm/13-leetcode/java/src/fundamentals/tree/root2leafnum/lc113_pathsum2/Solution.java' did not match any file(s) known to git
f32bedefa0b64205410152a266d829496fc14768
1
cdai/interview
package fundamentals.tree.root2leafnum.lc113_pathsum2; import fundamentals.tree.TreeNode; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Stack; /** * Given a binary tree and a sum, find all root-to-leaf paths * where each path's sum equals the given sum. */ public class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { if (root == null) { return Collections.emptyList(); } List<List<Integer>> paths = new ArrayList<>(); LinkedList<Integer> path = new LinkedList<>(); doPathSum(paths, path, root, sum); return paths; } private void doPathSum(List<List<Integer>> paths, LinkedList<Integer> path, TreeNode node, int sum) { path.add(node.val); sum -= node.val; if (node.left == null && node.right == null) { if (sum == 0) { paths.add(new ArrayList<>(path)); } } else { if (node.left != null) { doPathSum(paths, path, node.left, sum); } if (node.right != null) { doPathSum(paths, path, node.right, sum); } } path.removeLast(); } public List<List<Integer>> pathSum_Nonrecursive(TreeNode root, int sum) { List<List<Integer>> paths = new ArrayList<>(); if (root == null) { return paths; } Stack<TreeNode> stack = new Stack<>(); stack.push(root); int curSum = 0; // error1: init to 0 nor root.val LinkedList<Integer> curPath = new LinkedList<>(); while (!stack.isEmpty()) { TreeNode n = stack.pop(); curSum += n.val; curPath.add(n.val); if (n.left == null && n.right == null) { if (curSum == sum) { paths.add(new ArrayList<>(curPath)); } curSum -= n.val; curPath.removeLast(); // error2: when to remove internal node from path? } else { if (n.right != null) { stack.push(n.right); } if (n.left != null) { stack.push(n.left); } } } return paths; } }
1-algorithm/13-leetcode/java/src/fundamentals/tree/root2leafnum/lc113_pathsum2/Solution.java
leetcode-113 path sum 2
1-algorithm/13-leetcode/java/src/fundamentals/tree/root2leafnum/lc113_pathsum2/Solution.java
leetcode-113 path sum 2
<ide><path>-algorithm/13-leetcode/java/src/fundamentals/tree/root2leafnum/lc113_pathsum2/Solution.java <add>package fundamentals.tree.root2leafnum.lc113_pathsum2; <add> <add>import fundamentals.tree.TreeNode; <add> <add>import java.util.ArrayList; <add>import java.util.Collections; <add>import java.util.LinkedList; <add>import java.util.List; <add>import java.util.Stack; <add> <add>/** <add> * Given a binary tree and a sum, find all root-to-leaf paths <add> * where each path's sum equals the given sum. <add> */ <add>public class Solution { <add> <add> public List<List<Integer>> pathSum(TreeNode root, int sum) { <add> if (root == null) { <add> return Collections.emptyList(); <add> } <add> <add> List<List<Integer>> paths = new ArrayList<>(); <add> LinkedList<Integer> path = new LinkedList<>(); <add> <add> doPathSum(paths, path, root, sum); <add> <add> return paths; <add> } <add> <add> private void doPathSum(List<List<Integer>> paths, LinkedList<Integer> path, TreeNode node, int sum) { <add> path.add(node.val); <add> sum -= node.val; <add> <add> if (node.left == null && node.right == null) { <add> if (sum == 0) { <add> paths.add(new ArrayList<>(path)); <add> } <add> } else { <add> if (node.left != null) { <add> doPathSum(paths, path, node.left, sum); <add> } <add> if (node.right != null) { <add> doPathSum(paths, path, node.right, sum); <add> } <add> } <add> <add> path.removeLast(); <add> } <add> <add> public List<List<Integer>> pathSum_Nonrecursive(TreeNode root, int sum) { <add> List<List<Integer>> paths = new ArrayList<>(); <add> <add> if (root == null) { <add> return paths; <add> } <add> <add> Stack<TreeNode> stack = new Stack<>(); <add> stack.push(root); <add> <add> int curSum = 0; // error1: init to 0 nor root.val <add> LinkedList<Integer> curPath = new LinkedList<>(); <add> while (!stack.isEmpty()) { <add> TreeNode n = stack.pop(); <add> curSum += n.val; <add> curPath.add(n.val); <add> <add> if (n.left == null && n.right == null) { <add> if (curSum == sum) { <add> paths.add(new ArrayList<>(curPath)); <add> } <add> curSum -= n.val; <add> curPath.removeLast(); // error2: when to remove internal node from path? <add> } else { <add> if (n.right != null) { <add> stack.push(n.right); <add> } <add> if (n.left != null) { <add> stack.push(n.left); <add> } <add> } <add> } <add> return paths; <add> } <add>}
Java
mit
75cfecb2374dd5dca2be0741c967fc5eefe877a6
0
BrassGoggledCoders/MoarLibs,BrassGoggledCoders/OpenTransport
package xyz.brassgoggledcoders.opentransport.minecarts.entities; import com.google.common.base.Optional; import net.minecraft.client.gui.Gui; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.inventory.Container; import net.minecraft.item.ItemMinecart; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.datasync.DataParameter; import net.minecraft.network.datasync.DataSerializers; import net.minecraft.network.datasync.EntityDataManager; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import xyz.brassgoggledcoders.boilerplate.client.guis.IOpenableGUI; import xyz.brassgoggledcoders.boilerplate.entity.minecarts.EntityMinecartBase; import xyz.brassgoggledcoders.opentransport.api.blockcontainers.IBlockContainer; import xyz.brassgoggledcoders.opentransport.api.entities.IHolderEntity; import xyz.brassgoggledcoders.opentransport.minecarts.items.ItemMinecartHolder; import xyz.brassgoggledcoders.opentransport.registries.BlockContainerRegistry; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class EntityMinecartHolder extends EntityMinecartBase implements IHolderEntity<EntityMinecartHolder>, IOpenableGUI { private static final DataParameter<String> BLOCK_CONTAINER_NAME = EntityDataManager.createKey(EntityMinecartHolder.class, DataSerializers.STRING); private static final DataParameter<Optional<ItemStack>> ITEM_CART = EntityDataManager.createKey(EntityMinecartHolder.class, DataSerializers.OPTIONAL_ITEM_STACK); private IBlockContainer blockContainer; public EntityMinecartHolder(World world) { super(world); } @Override protected void entityInit() { super.entityInit(); this.dataManager.register(BLOCK_CONTAINER_NAME, ""); this.dataManager.register(ITEM_CART, Optional.absent()); } @Nonnull @Override public ItemMinecart getItem() { Optional<ItemStack> itemStackCart = this.dataManager.get(ITEM_CART); if(itemStackCart.isPresent()) { return (ItemMinecart)itemStackCart.get().getItem(); } return (ItemMinecart)Items.MINECART; } public void setItemCart(@Nonnull ItemStack itemCartStack) { if(itemCartStack.getItem() instanceof ItemMinecartHolder) { this.dataManager.set(ITEM_CART, Optional.of(itemCartStack)); } } @Override public EntityMinecartHolder getEntity() { return this; } @Override public IBlockContainer getBlockContainer() { if(this.blockContainer == null) { String containerName = this.dataManager.get(BLOCK_CONTAINER_NAME); this.blockContainer = BlockContainerRegistry.getBlockContainer(containerName); if(this.blockContainer != null) { this.blockContainer.setHolder(this); } } return this.blockContainer; } @Override public void setBlockContainer(IBlockContainer blockContainer) { this.dataManager.set(BLOCK_CONTAINER_NAME, blockContainer.getUnlocalizedName()); this.blockContainer = blockContainer; this.blockContainer.setHolder(this); } @Override public boolean processInitialInteract(@Nonnull EntityPlayer entityPlayer, @Nullable ItemStack itemStack, EnumHand hand) { return this.getBlockContainer() != null && this.getBlockContainer().onInteract(entityPlayer, hand, itemStack); } @Override @Nonnull public NBTTagCompound writeToNBT(NBTTagCompound nbtTagCompound) { super.writeToNBT(nbtTagCompound); nbtTagCompound.setString("CONTAINER_NAME", this.dataManager.get(BLOCK_CONTAINER_NAME)); if(blockContainer != null) { NBTTagCompound containerTag = new NBTTagCompound(); containerTag = blockContainer.writeToNBT(containerTag); nbtTagCompound.setTag("CONTAINER", containerTag); } return nbtTagCompound; } @Override public void readFromNBT(NBTTagCompound nbtTagCompound) { super.readFromNBT(nbtTagCompound); this.dataManager.set(BLOCK_CONTAINER_NAME, nbtTagCompound.getString("CONTAINER_NAME")); this.setBlockContainer(BlockContainerRegistry.getBlockContainer(nbtTagCompound.getString("CONTAINER_NAME"))); blockContainer.setHolder(this); blockContainer.readFromNBT(nbtTagCompound.getCompoundTag("CONTAINER")); } @Override public Gui getClientGuiElement(int ID, EntityPlayer player, World world, BlockPos blockPos) { return this.getBlockContainer().getInterface().getGUI(player, this, this.getBlockContainer()); } @Override public Container getServerGuiElement(int ID, EntityPlayer player, World world, BlockPos blockPos) { return this.getBlockContainer().getInterface().getContainer(player, this, this.getBlockContainer()); } }
src/main/java/xyz/brassgoggledcoders/opentransport/minecarts/entities/EntityMinecartHolder.java
package xyz.brassgoggledcoders.opentransport.minecarts.entities; import com.google.common.base.Optional; import net.minecraft.client.gui.Gui; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.inventory.Container; import net.minecraft.item.ItemMinecart; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.datasync.DataParameter; import net.minecraft.network.datasync.DataSerializers; import net.minecraft.network.datasync.EntityDataManager; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import xyz.brassgoggledcoders.boilerplate.client.guis.IOpenableGUI; import xyz.brassgoggledcoders.boilerplate.entity.minecarts.EntityMinecartBase; import xyz.brassgoggledcoders.opentransport.api.blockcontainers.IBlockContainer; import xyz.brassgoggledcoders.opentransport.api.entities.IHolderEntity; import xyz.brassgoggledcoders.opentransport.minecarts.items.ItemMinecartHolder; import xyz.brassgoggledcoders.opentransport.registries.BlockContainerRegistry; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class EntityMinecartHolder extends EntityMinecartBase implements IHolderEntity<EntityMinecartHolder>, IOpenableGUI { private static final DataParameter<String> BLOCK_CONTAINER_NAME = EntityDataManager.createKey(EntityMinecartHolder.class, DataSerializers.STRING); private static final DataParameter<Optional<ItemStack>> ITEM_CART = EntityDataManager.createKey(EntityMinecartHolder.class, DataSerializers.OPTIONAL_ITEM_STACK); private IBlockContainer blockContainer; public EntityMinecartHolder(World world) { super(world); } @Override protected void entityInit() { super.entityInit(); this.dataManager.register(BLOCK_CONTAINER_NAME, ""); } @Nonnull @Override public ItemMinecart getItem() { Optional<ItemStack> itemStackCart = this.dataManager.get(ITEM_CART); if(itemStackCart.isPresent()) { return (ItemMinecart)itemStackCart.get().getItem(); } return (ItemMinecart)Items.MINECART; } public void setItemCart(@Nonnull ItemStack itemCartStack) { if(itemCartStack.getItem() instanceof ItemMinecartHolder) { this.dataManager.set(ITEM_CART, Optional.of(itemCartStack)); } } @Override public EntityMinecartHolder getEntity() { return this; } @Override public IBlockContainer getBlockContainer() { if(this.blockContainer == null) { String containerName = this.dataManager.get(BLOCK_CONTAINER_NAME); this.blockContainer = BlockContainerRegistry.getBlockContainer(containerName); if(this.blockContainer != null) { this.blockContainer.setHolder(this); } } return this.blockContainer; } @Override public void setBlockContainer(IBlockContainer blockContainer) { this.dataManager.set(BLOCK_CONTAINER_NAME, blockContainer.getUnlocalizedName()); this.blockContainer = blockContainer; this.blockContainer.setHolder(this); } @Override public boolean processInitialInteract(@Nonnull EntityPlayer entityPlayer, @Nullable ItemStack itemStack, EnumHand hand) { return this.getBlockContainer() != null && this.getBlockContainer().onInteract(entityPlayer, hand, itemStack); } @Override @Nonnull public NBTTagCompound writeToNBT(NBTTagCompound nbtTagCompound) { super.writeToNBT(nbtTagCompound); nbtTagCompound.setString("CONTAINER_NAME", this.dataManager.get(BLOCK_CONTAINER_NAME)); if(blockContainer != null) { NBTTagCompound containerTag = new NBTTagCompound(); containerTag = blockContainer.writeToNBT(containerTag); nbtTagCompound.setTag("CONTAINER", containerTag); } return nbtTagCompound; } @Override public void readFromNBT(NBTTagCompound nbtTagCompound) { super.readFromNBT(nbtTagCompound); this.dataManager.set(BLOCK_CONTAINER_NAME, nbtTagCompound.getString("CONTAINER_NAME")); this.setBlockContainer(BlockContainerRegistry.getBlockContainer(nbtTagCompound.getString("CONTAINER_NAME"))); blockContainer.setHolder(this); blockContainer.readFromNBT(nbtTagCompound.getCompoundTag("CONTAINER")); } @Override public Gui getClientGuiElement(int ID, EntityPlayer player, World world, BlockPos blockPos) { return this.getBlockContainer().getInterface().getGUI(player, this, this.getBlockContainer()); } @Override public Container getServerGuiElement(int ID, EntityPlayer player, World world, BlockPos blockPos) { return this.getBlockContainer().getInterface().getContainer(player, this, this.getBlockContainer()); } }
Fix Minecarts crashing when setting Item
src/main/java/xyz/brassgoggledcoders/opentransport/minecarts/entities/EntityMinecartHolder.java
Fix Minecarts crashing when setting Item
<ide><path>rc/main/java/xyz/brassgoggledcoders/opentransport/minecarts/entities/EntityMinecartHolder.java <ide> protected void entityInit() { <ide> super.entityInit(); <ide> this.dataManager.register(BLOCK_CONTAINER_NAME, ""); <add> this.dataManager.register(ITEM_CART, Optional.absent()); <ide> } <ide> <ide> @Nonnull
Java
agpl-3.0
3e90e9d72dee157a9027eaa800e9ab4ce20af45b
0
WASP-System/central,WASP-System/central,WASP-System/central,WASP-System/central,WASP-System/central,WASP-System/central
package edu.yu.einstein.wasp.macstwo.batch.tasklet; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameter; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.item.ExecutionContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import edu.yu.einstein.wasp.Assert; import edu.yu.einstein.wasp.daemon.batch.tasklets.WaspRemotingTasklet; import edu.yu.einstein.wasp.grid.GridHostResolver; import edu.yu.einstein.wasp.grid.work.GridResult; import edu.yu.einstein.wasp.grid.work.GridTransportConnection; import edu.yu.einstein.wasp.grid.work.GridWorkService; import edu.yu.einstein.wasp.grid.work.WorkUnit; import edu.yu.einstein.wasp.grid.work.WorkUnitGridConfiguration; import edu.yu.einstein.wasp.grid.work.WorkUnitGridConfiguration.ProcessMode; import edu.yu.einstein.wasp.integration.messages.WaspSoftwareJobParameters; import edu.yu.einstein.wasp.macstwo.integration.messages.MacstwoSoftwareJobParameters; import edu.yu.einstein.wasp.macstwo.service.MacstwoService; import edu.yu.einstein.wasp.macstwo.software.Macstwo; import edu.yu.einstein.wasp.model.FileGroup; import edu.yu.einstein.wasp.model.FileGroupMeta; import edu.yu.einstein.wasp.model.FileHandle; import edu.yu.einstein.wasp.model.FileType; import edu.yu.einstein.wasp.model.Job; import edu.yu.einstein.wasp.model.Run; import edu.yu.einstein.wasp.model.RunMeta; import edu.yu.einstein.wasp.model.Sample; import edu.yu.einstein.wasp.model.SampleMeta; import edu.yu.einstein.wasp.model.SampleSource; import edu.yu.einstein.wasp.model.Software; import edu.yu.einstein.wasp.plugin.mps.grid.software.Imagemagick; import edu.yu.einstein.wasp.plugin.mps.grid.software.R; import edu.yu.einstein.wasp.plugin.supplemental.organism.Build; import edu.yu.einstein.wasp.service.FileService; import edu.yu.einstein.wasp.service.GenomeService; import edu.yu.einstein.wasp.service.JobService; import edu.yu.einstein.wasp.service.RunService; import edu.yu.einstein.wasp.service.SampleService; public class MacstwoTaskletModel extends WaspRemotingTasklet implements StepExecutionListener { private String jobIdAsString = ""; private Integer jobId = null; private Job job = null; private String prefixForFileName = ""; private String macs2AnalysisFileGroupIdAsString = ""; private String workingDirectory = ""; private String resultsDirectory = ""; private Integer macs2AnalysisFileGroupId = null; private String commandLineCall; private String softwareIdUsedListAsString; private StepExecution stepExecution; @Autowired private FileType textFileType;//here, the model.r script output file @Autowired private FileType pdfFileType;//output pdf file after running the model.r script @Autowired private FileType pngFileType;//output after imagemagik on the pdf file @Autowired private JobService jobService; @Autowired private FileService fileService; @Autowired private GridHostResolver gridHostResolver; @Autowired private Macstwo macs2; @Autowired private MacstwoService macstwoService; public MacstwoTaskletModel() { // proxy } /** * * @param contrib * @param context * @return * @throws Exception */ @Transactional("entityManager") @Override public GridResult doExecute(ChunkContext context) throws Exception { logger.debug("Starting MacstwoTaskletModel execute"); JobExecution jobExecution = this.stepExecution.getJobExecution(); ExecutionContext executionContext = jobExecution.getExecutionContext(); if(executionContext.containsKey(MacstwoService.JOB_ID_AS_STRING)){ this.jobIdAsString = (String) executionContext.get(MacstwoService.JOB_ID_AS_STRING); this.jobId = Integer.parseInt(jobIdAsString); this.job = jobService.getJobByJobId(jobId); } if(executionContext.containsKey(MacstwoService.PREFIX_FOR_FILE_NAME)){ prefixForFileName = (String) executionContext.get(MacstwoService.PREFIX_FOR_FILE_NAME); prefixForFileName = fileService.getSanitizedName(prefixForFileName); } if(executionContext.containsKey(MacstwoService.MACSTWO_ANALYSIS_FILEGROUP_ID_AS_STRING)){ this.macs2AnalysisFileGroupIdAsString = (String) executionContext.get(MacstwoService.MACSTWO_ANALYSIS_FILEGROUP_ID_AS_STRING); macs2AnalysisFileGroupId = Integer.parseInt(macs2AnalysisFileGroupIdAsString); } if(executionContext.containsKey(MacstwoService.WORKING_DIRECTORY)){ this.workingDirectory = (String) executionContext.get(MacstwoService.WORKING_DIRECTORY); } if(executionContext.containsKey(MacstwoService.RESULTS_DIRECTORY)){ this.resultsDirectory = (String) executionContext.get(MacstwoService.RESULTS_DIRECTORY); } logger.debug("in MacstwoTaskletModel.doExecute this.jobIdAsString: " + this.jobIdAsString); logger.debug("in MacstwoTaskletModel.doExecute this.jobId (an integer.tostring()): " + this.jobId.toString()); logger.debug("in MacstwoTaskletModel.doExecute this.job.getName(): " + job.getName()); logger.debug("in MacstwoTaskletModel.doExecute this.prefixForFileName: " + this.prefixForFileName); logger.debug("in MacstwoTaskletModel.doExecute this.macs2AnalysisFileGroupIdAsString: " + this.macs2AnalysisFileGroupIdAsString); logger.debug("in MacstwoTaskletModel.doExecute this.macs2AnalysisFileGroupId (an integer.tostring()): " + this.macs2AnalysisFileGroupId.toString()); logger.debug("in MacstwoTaskletModel.doExecute this.workingDirectory: " + this.workingDirectory); logger.debug("in MacstwoTaskletModel.doExecute this.resultsDirectory: " + this.resultsDirectory); Assert.assertTrue(!this.jobIdAsString.isEmpty()); Assert.assertTrue(this.jobId!=null); Assert.assertTrue(this.job!=null && this.job.getId()!=null); Assert.assertTrue(!this.prefixForFileName.isEmpty()); Assert.assertTrue(!this.macs2AnalysisFileGroupIdAsString.isEmpty()); Assert.assertTrue(this.macs2AnalysisFileGroupId!=null); Assert.assertTrue(!this.workingDirectory.isEmpty()); Assert.assertTrue(!this.resultsDirectory.isEmpty()); logger.debug("preparing to generate workunit in MacstwoTaskletModel.doExecute()"); String modelFileName = prefixForFileName + "_model.r"; String pdfFileName = modelFileName.replaceAll(".r$", ".pdf");//abc_model.r will be used to generate abc_model.pdf String pngFileName = modelFileName.replaceAll(".r$", ".png");//abc_model.pdf will be used to generate abc_model.png WorkUnit w = macs2.getModel(modelFileName, pdfFileName, pngFileName);//configure logger.debug("OK, workunit has been generated in MacstwoTaskletModel.doExecute()"); this.commandLineCall = w.getCommand(); this.commandLineCall = this.commandLineCall.replaceAll("\\n", "<br /><br />");//the workunit tagged on a newline at the end of the command; so remove it for db storage and replace with <br /> for display purposes //will add commandLineCall (concat); see below Imagemagick imagemagickSoftware = (Imagemagick) macs2.getSoftwareDependencyByIname("imagemagick"); R rSoftware = (R) macs2.getSoftwareDependencyByIname("rPackage"); this.softwareIdUsedListAsString = rSoftware.getId().toString() + ":" + imagemagickSoftware.getId().toString(); //will add (concatenate) with existing softwareIdUsedListAsString; see below //deal with the files List<String> listOfFileHandleNames = new ArrayList<String>(); LinkedHashSet<FileHandle> files = new LinkedHashSet<FileHandle>(); Set <FileGroup> innerFileGroupSet = new HashSet<FileGroup>(); //the prefixForFileName_model.r file (which may or may not have already been generated). Well, if we are at this line, a decider has already determined that this file HAS BEEN generated. FileHandle modelScriptFileHandle = macstwoService.createAndSaveInnerFileHandle(modelFileName, textFileType); listOfFileHandleNames.add(modelScriptFileHandle.getFileName()); files.add(modelScriptFileHandle); FileGroup modelScriptFileGroup = macstwoService.createAndSaveInnerFileGroup(modelScriptFileHandle, macs2, "xxx_model.r is a macs2-generated R script that can be converted into a pdf (using RScript) and illustrates the peak model"); innerFileGroupSet.add(modelScriptFileGroup); //the pdf (generated from running Rscript on xx_model.r file) FileHandle modelPdfFileHandle = macstwoService.createAndSaveInnerFileHandle(pdfFileName, pdfFileType); listOfFileHandleNames.add(modelPdfFileHandle.getFileName()); files.add(modelPdfFileHandle); FileGroup modelPdfFileGroup = macstwoService.createAndSaveInnerFileGroup(modelPdfFileHandle, rSoftware, "xxx_model.pdf is a pdf file generated by running RScript against xxx_model.r and is an image of the read distribution in model peaks and fragment size estimation"); innerFileGroupSet.add(modelPdfFileGroup); //the png (converted from the pdf using ImageMagick) FileHandle modelPngFileHandle = macstwoService.createAndSaveInnerFileHandle(pngFileName, pngFileType); listOfFileHandleNames.add(modelPngFileHandle.getFileName()); files.add(modelPngFileHandle); FileGroup modelPngFileGroup = macstwoService.createAndSaveInnerFileGroup(modelPngFileHandle, imagemagickSoftware, "xxx_model.png is a png image file converted from xxx_model.pdf using ImageMagick"); innerFileGroupSet.add(modelPngFileGroup); //important; add these three files to the collection FileGroup macs2AnalysisFileGroup = fileService.getFileGroupById(macs2AnalysisFileGroupId.intValue()); macs2AnalysisFileGroup = fileService.addToFileGroupCollection(macs2AnalysisFileGroup, innerFileGroupSet); logger.debug("dealt with files in in MacstwoTaskletModel.doExecute()"); //place in the step context in case of crash ExecutionContext stepContext = this.stepExecution.getExecutionContext(); stepContext.put("jobId", this.jobId); //needed? I don't believe so stepContext.put("macs2AnalysisFileGroupId", this.macs2AnalysisFileGroupId); stepContext.put("softwareIdUsedListAsString", this.softwareIdUsedListAsString); stepContext.put("commandLineCall", this.commandLineCall); logger.debug("saved variables in stepContext in case of crash in MacstwoTaskletModel.doExecute()"); w.setResultFiles(files); /// use next two lines here instead w.getConfiguration().setResultsDirectory(fileService.generateJobSoftwareBaseFolderName(job, macs2)); w.getConfiguration().setResultsDirectory(resultsDirectory); w.getConfiguration().setWorkingDirectory(workingDirectory); logger.debug("w.getConfiguration().setResultsDirectory() set as: " + resultsDirectory); logger.debug("w.getConfiguration().setWorkingDirectory() set as: " + workingDirectory); int counter = 0; for(String fileName : listOfFileHandleNames){//need to make these symbolic links in order to properly copy files w.addCommand("ln -sf " + fileName + " ${" + WorkUnit.OUTPUT_FILE+"["+counter+"]}"); logger.debug("add command: " + "ln -sf " + fileName + " ${" + WorkUnit.OUTPUT_FILE+"["+counter+"]}"); counter++; } GridResult result = gridHostResolver.execute(w); logger.debug("***********Executed gridHostResolver.execute(w) in MactwoTaskletModel.doExecute()"); return result; } /** * {@inheritDoc} */ @Override public ExitStatus afterStep(StepExecution stepExecution) { return super.afterStep(stepExecution); } /** * {@inheritDoc} */ @Override public void beforeStep(StepExecution stepExecution) { super.beforeStep(stepExecution); logger.debug("***** StepExecutionListener beforeStep saving StepExecution in MacstwoTaskletModel.beforeStep"); this.stepExecution = stepExecution; ExecutionContext stepContext = this.stepExecution.getExecutionContext(); //in case of crash if(this.jobId==null){//set initially in constructor this.jobId = (Integer) stepContext.get("jobId"); } this.macs2AnalysisFileGroupId = (Integer) stepContext.get("macs2AnalysisFileGroupId"); this.commandLineCall = (String) stepContext.get("commandLineCall"); this.softwareIdUsedListAsString = (String) stepContext.get("softwareIdUsedListAsString"); } /** * {@inheritDoc} */ @Override @Transactional("entityManager") public void doPreFinish(ChunkContext context) throws Exception { logger.debug("starting MacstwoTaskletModeldoPreFinish()"); //at Andy's suggestion, do this here too: ExecutionContext stepContext = this.stepExecution.getExecutionContext(); this.commandLineCall = (String) stepContext.get("commandLineCall"); this.macs2AnalysisFileGroupId = (Integer) stepContext.get("macs2AnalysisFileGroupId"); this.softwareIdUsedListAsString = (String) stepContext.get("softwareIdUsedListAsString"); logger.debug("in middle of MacstwoTaskletModel.doPreFinish(), getting ready to set to active the 3 model files and update two meta attributes"); if (this.macs2AnalysisFileGroupId != null){ FileGroup macs2AnalysisFileGroup = fileService.getFileGroupById(this.macs2AnalysisFileGroupId); //macs2AnalysisFileGroup already set to active in previous tasklet for(FileGroup childFG : macs2AnalysisFileGroup.getChildren()){ if(childFG.getIsActive().intValue()==0){ childFG.setIsActive(1); fileService.addFileGroup(childFG);//save new active setting } } ///already done fileService.setSampleFile(macs2AnalysisFileGroupId, testSample); List<FileGroupMeta> fgmList = new ArrayList<FileGroupMeta>(); //want to update these two outer fileGroup metadata fields boolean foundCommandLineCallMeta = false; boolean foundSoftwareIdUsedListAsStringMeta = false; for(FileGroupMeta fgm : macs2AnalysisFileGroup.getFileGroupMeta()){//existing meta fields if(fgm.getK().equals("macs2Analysis.commandLineCall")){//this is an existing meta field fgm.setV(fgm.getV() + this.commandLineCall);//simply concatenate fgmList.add(fgm); foundCommandLineCallMeta = true; } if(fgm.getK().equals("macs2Analysis.softwareIdUsedListAsString")){//this is an existing meta field fgm.setV(fgm.getV() + ":" + this.softwareIdUsedListAsString);//add : then concatenate fgmList.add(fgm); foundSoftwareIdUsedListAsStringMeta = true; } } if(!foundCommandLineCallMeta){//most likely the field already exists, so will not need to execute this FileGroupMeta fgm5 = new FileGroupMeta(); fgm5.setK("macs2Analysis.commandLineCall"); fgm5.setV(this.commandLineCall); fgm5.setFileGroupId(macs2AnalysisFileGroup.getId()); fgmList.add(fgm5); } if(!foundSoftwareIdUsedListAsStringMeta){//most likely the field already exists, so will not need to execute this FileGroupMeta fgm8 = new FileGroupMeta(); fgm8.setK("macs2Analysis.softwareIdUsedListAsString"); fgm8.setV(this.softwareIdUsedListAsString); fgm8.setFileGroupId(macs2AnalysisFileGroup.getId()); fgmList.add(fgm8); } if(!fgmList.isEmpty()){//save the updates as needed fileService.saveFileGroupMeta(fgmList, macs2AnalysisFileGroup); } } logger.debug("ending MacstwoTaskletModel.doPreFinish() "); } @Override public void doCleanupBeforeRestart(StepExecution stepExecution) throws Exception { // TODO Auto-generated method stub } }
plugins/macsTwo/src/main/java/edu/yu/einstein/wasp/macstwo/batch/tasklet/MacstwoTaskletModel.java
package edu.yu.einstein.wasp.macstwo.batch.tasklet; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameter; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.item.ExecutionContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import edu.yu.einstein.wasp.Assert; import edu.yu.einstein.wasp.daemon.batch.tasklets.WaspRemotingTasklet; import edu.yu.einstein.wasp.grid.GridHostResolver; import edu.yu.einstein.wasp.grid.work.GridResult; import edu.yu.einstein.wasp.grid.work.GridTransportConnection; import edu.yu.einstein.wasp.grid.work.GridWorkService; import edu.yu.einstein.wasp.grid.work.WorkUnit; import edu.yu.einstein.wasp.grid.work.WorkUnitGridConfiguration; import edu.yu.einstein.wasp.grid.work.WorkUnitGridConfiguration.ProcessMode; import edu.yu.einstein.wasp.integration.messages.WaspSoftwareJobParameters; import edu.yu.einstein.wasp.macstwo.integration.messages.MacstwoSoftwareJobParameters; import edu.yu.einstein.wasp.macstwo.service.MacstwoService; import edu.yu.einstein.wasp.macstwo.software.Macstwo; import edu.yu.einstein.wasp.model.FileGroup; import edu.yu.einstein.wasp.model.FileGroupMeta; import edu.yu.einstein.wasp.model.FileHandle; import edu.yu.einstein.wasp.model.FileType; import edu.yu.einstein.wasp.model.Job; import edu.yu.einstein.wasp.model.Run; import edu.yu.einstein.wasp.model.RunMeta; import edu.yu.einstein.wasp.model.Sample; import edu.yu.einstein.wasp.model.SampleMeta; import edu.yu.einstein.wasp.model.SampleSource; import edu.yu.einstein.wasp.model.Software; import edu.yu.einstein.wasp.plugin.mps.grid.software.Imagemagick; import edu.yu.einstein.wasp.plugin.mps.grid.software.R; import edu.yu.einstein.wasp.plugin.supplemental.organism.Build; import edu.yu.einstein.wasp.service.FileService; import edu.yu.einstein.wasp.service.GenomeService; import edu.yu.einstein.wasp.service.JobService; import edu.yu.einstein.wasp.service.RunService; import edu.yu.einstein.wasp.service.SampleService; public class MacstwoTaskletModel extends WaspRemotingTasklet implements StepExecutionListener { private String jobIdAsString = ""; private Integer jobId = null; private Job job = null; private String prefixForFileName = ""; private String macs2AnalysisFileGroupIdAsString = ""; private String workingDirectory = ""; private String resultsDirectory = ""; private Integer macs2AnalysisFileGroupId = null; private String commandLineCall; private String softwareIdUsedListAsString; private StepExecution stepExecution; @Autowired private FileType textFileType;//here, the model.r script output file @Autowired private FileType pdfFileType;//output pdf file after running the model.r script @Autowired private FileType pngFileType;//output after imagemagik on the pdf file @Autowired private JobService jobService; @Autowired private FileService fileService; @Autowired private GridHostResolver gridHostResolver; @Autowired private Macstwo macs2; @Autowired private MacstwoService macstwoService; public MacstwoTaskletModel() { // proxy } /** * * @param contrib * @param context * @return * @throws Exception */ @Transactional("entityManager") @Override public GridResult doExecute(ChunkContext context) throws Exception { logger.debug("Starting MacstwoTaskletModel execute"); JobExecution jobExecution = this.stepExecution.getJobExecution(); ExecutionContext executionContext = jobExecution.getExecutionContext(); if(executionContext.containsKey(MacstwoService.JOB_ID_AS_STRING)){ this.jobIdAsString = (String) executionContext.get(MacstwoService.JOB_ID_AS_STRING); this.jobId = Integer.parseInt(jobIdAsString); this.job = jobService.getJobByJobId(jobId); } if(executionContext.containsKey(MacstwoService.PREFIX_FOR_FILE_NAME)){ this.prefixForFileName = (String) executionContext.get(MacstwoService.PREFIX_FOR_FILE_NAME); fileService.getSanitizedName(prefixForFileName); } if(executionContext.containsKey(MacstwoService.MACSTWO_ANALYSIS_FILEGROUP_ID_AS_STRING)){ this.macs2AnalysisFileGroupIdAsString = (String) executionContext.get(MacstwoService.MACSTWO_ANALYSIS_FILEGROUP_ID_AS_STRING); macs2AnalysisFileGroupId = Integer.parseInt(macs2AnalysisFileGroupIdAsString); } if(executionContext.containsKey(MacstwoService.WORKING_DIRECTORY)){ this.workingDirectory = (String) executionContext.get(MacstwoService.WORKING_DIRECTORY); } if(executionContext.containsKey(MacstwoService.RESULTS_DIRECTORY)){ this.resultsDirectory = (String) executionContext.get(MacstwoService.RESULTS_DIRECTORY); } logger.debug("in MacstwoTaskletModel.doExecute this.jobIdAsString: " + this.jobIdAsString); logger.debug("in MacstwoTaskletModel.doExecute this.jobId (an integer.tostring()): " + this.jobId.toString()); logger.debug("in MacstwoTaskletModel.doExecute this.job.getName(): " + job.getName()); logger.debug("in MacstwoTaskletModel.doExecute this.prefixForFileName: " + this.prefixForFileName); logger.debug("in MacstwoTaskletModel.doExecute this.macs2AnalysisFileGroupIdAsString: " + this.macs2AnalysisFileGroupIdAsString); logger.debug("in MacstwoTaskletModel.doExecute this.macs2AnalysisFileGroupId (an integer.tostring()): " + this.macs2AnalysisFileGroupId.toString()); logger.debug("in MacstwoTaskletModel.doExecute this.workingDirectory: " + this.workingDirectory); logger.debug("in MacstwoTaskletModel.doExecute this.resultsDirectory: " + this.resultsDirectory); Assert.assertTrue(!this.jobIdAsString.isEmpty()); Assert.assertTrue(this.jobId!=null); Assert.assertTrue(this.job!=null && this.job.getId()!=null); Assert.assertTrue(!this.prefixForFileName.isEmpty()); Assert.assertTrue(!this.macs2AnalysisFileGroupIdAsString.isEmpty()); Assert.assertTrue(this.macs2AnalysisFileGroupId!=null); Assert.assertTrue(!this.workingDirectory.isEmpty()); Assert.assertTrue(!this.resultsDirectory.isEmpty()); logger.debug("preparing to generate workunit in MacstwoTaskletModel.doExecute()"); String modelFileName = prefixForFileName + "_model.r"; String pdfFileName = modelFileName.replaceAll(".r$", ".pdf");//abc_model.r will be used to generate abc_model.pdf String pngFileName = modelFileName.replaceAll(".r$", ".png");//abc_model.pdf will be used to generate abc_model.png WorkUnit w = macs2.getModel(modelFileName, pdfFileName, pngFileName);//configure logger.debug("OK, workunit has been generated in MacstwoTaskletModel.doExecute()"); this.commandLineCall = w.getCommand(); this.commandLineCall = this.commandLineCall.replaceAll("\\n", "<br /><br />");//the workunit tagged on a newline at the end of the command; so remove it for db storage and replace with <br /> for display purposes //will add commandLineCall (concat); see below Imagemagick imagemagickSoftware = (Imagemagick) macs2.getSoftwareDependencyByIname("imagemagick"); R rSoftware = (R) macs2.getSoftwareDependencyByIname("rPackage"); this.softwareIdUsedListAsString = rSoftware.getId().toString() + ":" + imagemagickSoftware.getId().toString(); //will add (concatenate) with existing softwareIdUsedListAsString; see below //deal with the files List<String> listOfFileHandleNames = new ArrayList<String>(); LinkedHashSet<FileHandle> files = new LinkedHashSet<FileHandle>(); Set <FileGroup> innerFileGroupSet = new HashSet<FileGroup>(); //the prefixForFileName_model.r file (which may or may not have already been generated). Well, if we are at this line, a decider has already determined that this file HAS BEEN generated. FileHandle modelScriptFileHandle = macstwoService.createAndSaveInnerFileHandle(modelFileName, textFileType); listOfFileHandleNames.add(modelScriptFileHandle.getFileName()); files.add(modelScriptFileHandle); FileGroup modelScriptFileGroup = macstwoService.createAndSaveInnerFileGroup(modelScriptFileHandle, macs2, "xxx_model.r is a macs2-generated R script that can be converted into a pdf (using RScript) and illustrates the peak model"); innerFileGroupSet.add(modelScriptFileGroup); //the pdf (generated from running Rscript on xx_model.r file) FileHandle modelPdfFileHandle = macstwoService.createAndSaveInnerFileHandle(pdfFileName, pdfFileType); listOfFileHandleNames.add(modelPdfFileHandle.getFileName()); files.add(modelPdfFileHandle); FileGroup modelPdfFileGroup = macstwoService.createAndSaveInnerFileGroup(modelPdfFileHandle, rSoftware, "xxx_model.pdf is a pdf file generated by running RScript against xxx_model.r and is an image of the read distribution in model peaks and fragment size estimation"); innerFileGroupSet.add(modelPdfFileGroup); //the png (converted from the pdf using ImageMagick) FileHandle modelPngFileHandle = macstwoService.createAndSaveInnerFileHandle(pngFileName, pngFileType); listOfFileHandleNames.add(modelPngFileHandle.getFileName()); files.add(modelPngFileHandle); FileGroup modelPngFileGroup = macstwoService.createAndSaveInnerFileGroup(modelPngFileHandle, imagemagickSoftware, "xxx_model.png is a png image file converted from xxx_model.pdf using ImageMagick"); innerFileGroupSet.add(modelPngFileGroup); //important; add these three files to the collection FileGroup macs2AnalysisFileGroup = fileService.getFileGroupById(macs2AnalysisFileGroupId.intValue()); macs2AnalysisFileGroup = fileService.addToFileGroupCollection(macs2AnalysisFileGroup, innerFileGroupSet); logger.debug("dealt with files in in MacstwoTaskletModel.doExecute()"); //place in the step context in case of crash ExecutionContext stepContext = this.stepExecution.getExecutionContext(); stepContext.put("jobId", this.jobId); //needed? I don't believe so stepContext.put("macs2AnalysisFileGroupId", this.macs2AnalysisFileGroupId); stepContext.put("softwareIdUsedListAsString", this.softwareIdUsedListAsString); stepContext.put("commandLineCall", this.commandLineCall); logger.debug("saved variables in stepContext in case of crash in MacstwoTaskletModel.doExecute()"); w.setResultFiles(files); /// use next two lines here instead w.getConfiguration().setResultsDirectory(fileService.generateJobSoftwareBaseFolderName(job, macs2)); w.getConfiguration().setResultsDirectory(resultsDirectory); w.getConfiguration().setWorkingDirectory(workingDirectory); logger.debug("w.getConfiguration().setResultsDirectory() set as: " + resultsDirectory); logger.debug("w.getConfiguration().setWorkingDirectory() set as: " + workingDirectory); int counter = 0; for(String fileName : listOfFileHandleNames){//need to make these symbolic links in order to properly copy files w.addCommand("ln -sf " + fileName + " ${" + WorkUnit.OUTPUT_FILE+"["+counter+"]}"); logger.debug("add command: " + "ln -sf " + fileName + " ${" + WorkUnit.OUTPUT_FILE+"["+counter+"]}"); counter++; } GridResult result = gridHostResolver.execute(w); logger.debug("***********Executed gridHostResolver.execute(w) in MactwoTaskletModel.doExecute()"); return result; } /** * {@inheritDoc} */ @Override public ExitStatus afterStep(StepExecution stepExecution) { return super.afterStep(stepExecution); } /** * {@inheritDoc} */ @Override public void beforeStep(StepExecution stepExecution) { super.beforeStep(stepExecution); logger.debug("***** StepExecutionListener beforeStep saving StepExecution in MacstwoTaskletModel.beforeStep"); this.stepExecution = stepExecution; ExecutionContext stepContext = this.stepExecution.getExecutionContext(); //in case of crash if(this.jobId==null){//set initially in constructor this.jobId = (Integer) stepContext.get("jobId"); } this.macs2AnalysisFileGroupId = (Integer) stepContext.get("macs2AnalysisFileGroupId"); this.commandLineCall = (String) stepContext.get("commandLineCall"); this.softwareIdUsedListAsString = (String) stepContext.get("softwareIdUsedListAsString"); } /** * {@inheritDoc} */ @Override @Transactional("entityManager") public void doPreFinish(ChunkContext context) throws Exception { logger.debug("starting MacstwoTaskletModeldoPreFinish()"); //at Andy's suggestion, do this here too: ExecutionContext stepContext = this.stepExecution.getExecutionContext(); this.commandLineCall = (String) stepContext.get("commandLineCall"); this.macs2AnalysisFileGroupId = (Integer) stepContext.get("macs2AnalysisFileGroupId"); this.softwareIdUsedListAsString = (String) stepContext.get("softwareIdUsedListAsString"); logger.debug("in middle of MacstwoTaskletModel.doPreFinish(), getting ready to set to active the 3 model files and update two meta attributes"); if (this.macs2AnalysisFileGroupId != null){ FileGroup macs2AnalysisFileGroup = fileService.getFileGroupById(this.macs2AnalysisFileGroupId); //macs2AnalysisFileGroup already set to active in previous tasklet for(FileGroup childFG : macs2AnalysisFileGroup.getChildren()){ if(childFG.getIsActive().intValue()==0){ childFG.setIsActive(1); fileService.addFileGroup(childFG);//save new active setting } } ///already done fileService.setSampleFile(macs2AnalysisFileGroupId, testSample); List<FileGroupMeta> fgmList = new ArrayList<FileGroupMeta>(); //want to update these two outer fileGroup metadata fields boolean foundCommandLineCallMeta = false; boolean foundSoftwareIdUsedListAsStringMeta = false; for(FileGroupMeta fgm : macs2AnalysisFileGroup.getFileGroupMeta()){//existing meta fields if(fgm.getK().equals("macs2Analysis.commandLineCall")){//this is an existing meta field fgm.setV(fgm.getV() + this.commandLineCall);//simply concatenate fgmList.add(fgm); foundCommandLineCallMeta = true; } if(fgm.getK().equals("macs2Analysis.softwareIdUsedListAsString")){//this is an existing meta field fgm.setV(fgm.getV() + ":" + this.softwareIdUsedListAsString);//add : then concatenate fgmList.add(fgm); foundSoftwareIdUsedListAsStringMeta = true; } } if(!foundCommandLineCallMeta){//most likely the field already exists, so will not need to execute this FileGroupMeta fgm5 = new FileGroupMeta(); fgm5.setK("macs2Analysis.commandLineCall"); fgm5.setV(this.commandLineCall); fgm5.setFileGroupId(macs2AnalysisFileGroup.getId()); fgmList.add(fgm5); } if(!foundSoftwareIdUsedListAsStringMeta){//most likely the field already exists, so will not need to execute this FileGroupMeta fgm8 = new FileGroupMeta(); fgm8.setK("macs2Analysis.softwareIdUsedListAsString"); fgm8.setV(this.softwareIdUsedListAsString); fgm8.setFileGroupId(macs2AnalysisFileGroup.getId()); fgmList.add(fgm8); } if(!fgmList.isEmpty()){//save the updates as needed fileService.saveFileGroupMeta(fgmList, macs2AnalysisFileGroup); } } logger.debug("ending MacstwoTaskletModel.doPreFinish() "); } @Override public void doCleanupBeforeRestart(StepExecution stepExecution) throws Exception { // TODO Auto-generated method stub } }
actually fixed the previous problem
plugins/macsTwo/src/main/java/edu/yu/einstein/wasp/macstwo/batch/tasklet/MacstwoTaskletModel.java
actually fixed the previous problem
<ide><path>lugins/macsTwo/src/main/java/edu/yu/einstein/wasp/macstwo/batch/tasklet/MacstwoTaskletModel.java <ide> this.job = jobService.getJobByJobId(jobId); <ide> } <ide> if(executionContext.containsKey(MacstwoService.PREFIX_FOR_FILE_NAME)){ <del> this.prefixForFileName = (String) executionContext.get(MacstwoService.PREFIX_FOR_FILE_NAME); <del> fileService.getSanitizedName(prefixForFileName); <add> prefixForFileName = (String) executionContext.get(MacstwoService.PREFIX_FOR_FILE_NAME); <add> prefixForFileName = fileService.getSanitizedName(prefixForFileName); <ide> } <ide> if(executionContext.containsKey(MacstwoService.MACSTWO_ANALYSIS_FILEGROUP_ID_AS_STRING)){ <ide> this.macs2AnalysisFileGroupIdAsString = (String) executionContext.get(MacstwoService.MACSTWO_ANALYSIS_FILEGROUP_ID_AS_STRING);
Java
mit
91cc19ebe42ed0838ccfc34ce7a060bf3dce4257
0
Innovimax-SARL/mix-them
package innovimax.mixthem; import innovimax.mixthem.arguments.Arguments; import innovimax.mixthem.exceptions.ArgumentException; import org.junit.Assert; import org.junit.Test; /* Created by innovimax-jim Basic tests for this application */ public class BasicTest { @Test public final void failedPrintUsage() { boolean check = false; try { final String args[] = {}; Arguments mixArgs = Arguments.checkArguments(args); check = true; } catch (ArgumentException e) { System.out.println(e.getMessage()); } Assert.assertFalse(check); check = false; try { final String args[] = { "ghost1", "ghost2" }; Arguments mixArgs = Arguments.checkArguments(args); check = true; } catch (ArgumentException e) { System.out.println(e.getMessage()); } Assert.assertFalse(check); Arguments.printUsage(); } }
src/test/java/innovimax/mixthem/BasicTest.java
package innovimax.mixthem; import innovimax.mixthem.MixThem; import innovimax.mixthem.arguments.Arguments; import innovimax.mixthem.exceptions.ArgumentException; import org.junit.Assert; import org.junit.Test; /* Created by innovimax-jim Basic tests for this application */ public class BasicTest { @Test public final void failedPrintUsage() { boolean check = false; try { final String args[] = {}; Arguments mixArgs = Arguments.checkArguments(args); check = true; } catch (ArgumentException e) { System.out.println(e.getMessage()); } Assert.assertFalse(check); check = false; try { final String args[] = { "ghost1", "ghost2" }; Arguments mixArgs = Arguments.checkArguments(args); check = true; } catch (ArgumentException e) { System.out.println(e.getMessage()); } Assert.assertFalse(check); MixThem.printUsage(); } }
Fix BasicTest.java use Arguments.printUsage() remove useless import of MixThem
src/test/java/innovimax/mixthem/BasicTest.java
Fix BasicTest.java
<ide><path>rc/test/java/innovimax/mixthem/BasicTest.java <ide> package innovimax.mixthem; <ide> <del>import innovimax.mixthem.MixThem; <ide> import innovimax.mixthem.arguments.Arguments; <ide> import innovimax.mixthem.exceptions.ArgumentException; <ide> <ide> System.out.println(e.getMessage()); <ide> } <ide> Assert.assertFalse(check); <del> MixThem.printUsage(); <add> Arguments.printUsage(); <ide> } <ide> <ide> }
Java
mit
9a8e4d2ef0ddfe466923a6c0177184c1b2dea8cf
0
BoozePal/BoozePal,BoozePal/BoozePal,BoozePal/BoozePal,BoozePal/BoozePal
package hu.deik.boozepal.service.impl; import java.util.Arrays; import javax.annotation.PostConstruct; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; import javax.interceptor.Interceptors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor; import hu.deik.boozepal.common.entity.Role; import hu.deik.boozepal.common.entity.User; import hu.deik.boozepal.core.repo.RoleRepository; import hu.deik.boozepal.core.repo.UserRepository; import hu.deik.boozepal.service.StartupService; @Startup @Singleton @TransactionManagement(TransactionManagementType.BEAN) @Interceptors({ SpringBeanAutowiringInterceptor.class }) public class StartupServiceImpl implements StartupService { /* password = admin */ private static final String PASSWORD = "$2a$04$e9R7K4j5IYZRxOUB4.yVweDsguwUCdiqkd5kzJ0uO/0F7CQxJdjZ."; private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private UserRepository userDao; @Autowired private RoleRepository roleDao; private Role userRole; private User user; @PostConstruct public void init() { logger.info("StartupService#init()"); try { userRole = roleDao.findByRoleName("ROLE_ADMIN"); user = userDao.findByUsername("admin"); if (userRole == null && user == null) { createAdminUser(); } else { user.setPassword(PASSWORD); userDao.save(user); } } catch (Exception e) { logger.error("Failed to deploy application.", e); } } /* A jelszó admin */ public void createAdminUser() { userRole = roleDao.save(new Role("ROLE_ADMIN")); logger.debug("Create admin role : " + userRole.toString()); user = userDao.save(User.builder().username("admin").password(PASSWORD).email("[email protected]").remove(false) .roles(Arrays.asList(userRole)).build()); logger.debug("Create user : " + user.toString()); } }
boozepal/boozepal-service/src/main/java/hu/deik/boozepal/service/impl/StartupServiceImpl.java
package hu.deik.boozepal.service.impl; import java.util.Arrays; import javax.annotation.PostConstruct; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; import javax.interceptor.Interceptors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor; import hu.deik.boozepal.common.entity.Role; import hu.deik.boozepal.common.entity.User; import hu.deik.boozepal.core.repo.RoleRepository; import hu.deik.boozepal.core.repo.UserRepository; import hu.deik.boozepal.service.StartupService; @Startup @Singleton @TransactionManagement(TransactionManagementType.BEAN) @Interceptors({ SpringBeanAutowiringInterceptor.class }) public class StartupServiceImpl implements StartupService { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private UserRepository userDao; @Autowired private RoleRepository roleDao; private Role userRole; private User user; @PostConstruct public void init() { logger.info("StartupService#init()"); try { userRole = roleDao.findByRoleName("ROLE_ADMIN"); user = userDao.findByUsername("admin"); if (userRole == null && user == null) { createAdminUser(); } } catch (Exception e) { logger.error("Failed to deploy application.", e); } } /* A jelszó admin */ public void createAdminUser() { userRole = roleDao.save(new Role("ROLE_ADMIN")); logger.info("Create admin role : " + userRole.toString()); user = userDao.save(User.builder().username("admin") .password("$2a$04$sIC5RDGG8CESaA7JGmn4huaC2av5olRYp3D7Cyaxq3/JNhMSzqC1O").email("[email protected]") .remove(false).roles(Arrays.asList(userRole)).build()); logger.info("Create user : " + user.toString()); } }
First user password = admin Hotfix
boozepal/boozepal-service/src/main/java/hu/deik/boozepal/service/impl/StartupServiceImpl.java
First user password = admin Hotfix
<ide><path>oozepal/boozepal-service/src/main/java/hu/deik/boozepal/service/impl/StartupServiceImpl.java <ide> @Interceptors({ SpringBeanAutowiringInterceptor.class }) <ide> public class StartupServiceImpl implements StartupService { <ide> <add> /* password = admin */ <add> private static final String PASSWORD = "$2a$04$e9R7K4j5IYZRxOUB4.yVweDsguwUCdiqkd5kzJ0uO/0F7CQxJdjZ."; <add> <ide> private Logger logger = LoggerFactory.getLogger(this.getClass()); <ide> <ide> @Autowired <ide> user = userDao.findByUsername("admin"); <ide> if (userRole == null && user == null) { <ide> createAdminUser(); <add> } else { <add> user.setPassword(PASSWORD); <add> userDao.save(user); <ide> } <ide> } catch (Exception e) { <ide> logger.error("Failed to deploy application.", e); <ide> /* A jelszó admin */ <ide> public void createAdminUser() { <ide> userRole = roleDao.save(new Role("ROLE_ADMIN")); <del> logger.info("Create admin role : " + userRole.toString()); <del> user = userDao.save(User.builder().username("admin") <del> .password("$2a$04$sIC5RDGG8CESaA7JGmn4huaC2av5olRYp3D7Cyaxq3/JNhMSzqC1O").email("[email protected]") <del> .remove(false).roles(Arrays.asList(userRole)).build()); <del> logger.info("Create user : " + user.toString()); <add> logger.debug("Create admin role : " + userRole.toString()); <add> user = userDao.save(User.builder().username("admin").password(PASSWORD).email("[email protected]").remove(false) <add> .roles(Arrays.asList(userRole)).build()); <add> logger.debug("Create user : " + user.toString()); <ide> } <ide> }
JavaScript
mit
ee7d8f25960335aa206a8e0d68cfe12b49725bfe
0
chenclee/utacm_icpc_autojudge,chenclee/utacm_icpc_autojudge,ilinum/utacm_icpc_autojudge,ilinum/utacm_icpc_autojudge,ilinum/utacm_icpc_autojudge,chenclee/utacm_icpc_autojudge,ilinum/utacm_icpc_autojudge,ilinum/utacm_icpc_autojudge,chenclee/utacm_icpc_autojudge,chenclee/utacm_icpc_autojudge,ilinum/utacm_icpc_autojudge,chenclee/utacm_icpc_autojudge
var preContestControllers = angular.module('preContestControllers', []); preContestControllers.controller('MainCtrl', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout, $window) { function sync () { $http.get('api/v1/updates').success(function (data) { if ($scope.rawTime < parseInt(data['remaining_time'])) { $window.location.reload(); } $scope.rawTime = data['remaining_time']; $scope.remainingTime = moment($scope.rawTime); $timeout(sync, 5000); for (i = 1000; i <= 4000; i += 1000) { $timeout(tick, i); } }); } function tick () { $scope.rawTime -= 1; if ($scope.rawTime < 0) { $window.location.reload(); } else { $scope.remainingTime = moment($scope.rawTime); } } sync(); }]); preContestControllers.controller('HomeCtrl', ['$scope', '$http', function ($scope, $http) { }]); var contestControllers = angular.module('contestControllers', []); var probIds = []; contestControllers.controller('MainCtrl', ['$scope', '$http', '$interval', '$rootScope', function ($scope, $http, $interval, $rootScope, $window) { $http.get('api/v1/metadata').success(function (data) { $scope.probIds = probIds = data['prob_ids']; $scope.probContents = data['prob_contents']; $scope.remainingPermits = data['remaining_permit_counts']; $scope.solved = data['solved']; $scope.problemsTimeToSolve = data['problems_time_to_solve']; for (var i = 0; i < probIds.length; i++) { $scope.problemsTimeToSolve[probIds[i]] = momentMinutes($scope.problemsTimeToSolve[probIds[i]]); } }); $rootScope.syncUpdates = function () { $http.get('api/v1/updates').success(function (data) { if (typeof $rootScope.prevSync !== 'undefined') $interval.cancel($rootScope.prevSync); $rootScope.rawTime = data['remaining_time']; $scope.scoreboard = data['scoreboard']; $scope.clarifications = data['clarifications']; $rootScope.remainingTime = moment($rootScope.rawTime); $rootScope.prevSync = $interval($rootScope.clockTick, 1000, 29); }); } $rootScope.clockTick = function () { $rootScope.rawTime -= 1; if ($rootScope.rawTime >= 0) { $rootScope.remainingTime = moment($rootScope.rawTime); } } $rootScope.syncUpdates(); $interval($rootScope.syncUpdates, 30000); }]); contestControllers.controller('HomeCtrl', ['$scope', '$http', function ($scope, $http) { }]); var whitelist = []; var allClarifications = []; var radioModel = 'Active'; contestControllers.controller('AdminCtrl', ['$scope', '$rootScope', '$http', '$cookies', '$window', '$modal', '$interval', function ($scope, $rootScope, $http, $cookies, $window, $modal, $interval) { function sync () { $http.get('api/v1/admin/updates').success(function (data) { $scope.whitelist = data.whitelist; $scope.allClarifications = data.clarifs; $scope.boardIsFrozen = data.frozen; $scope.radioModel = $scope.boardIsFrozen ? 'Frozen' : 'Active'; }); } sync(); $interval(sync, 10000); $scope.rejudgeProblem = function(problemId) { submit_url = 'api/v1/admin/rejudge'; submit_data = { '_xsrf': $cookies._xsrf, 'probId': problemId }; $http({ method : 'POST', url : submit_url, data : $.param(submit_data), headers : { 'Content-Type': 'application/x-www-form-urlencoded' }, }).success(function(data) { $window.alert("Rejudging problem " + problemId); }); } $scope.processAddTimeInput = function(numMin) { submit_url = 'api/v1/admin/add_time'; submit_data = { '_xsrf': $cookies._xsrf, 'numMin': numMin }; $http({ method : 'POST', url : submit_url, data : $.param(submit_data), headers : { 'Content-Type': 'application/x-www-form-urlencoded' }, }).success(function(data) { $scope.addTimeTextBox = null; $rootScope.syncUpdates(); }); } $scope.processClarifResponse = function(respNum, clarifNum) { submit_url = 'api/v1/admin/clarifications'; var respString = ''; if(respNum == 2) { $scope.clarifRespModalOpen(respNum, clarifNum) } else { submit_data = { '_xsrf': $cookies._xsrf, 'respNum': respNum, 'clarifNum': clarifNum, 'respString': '' }; $http({ method : 'POST', url : submit_url, data : $.param(submit_data), headers : { 'Content-Type': 'application/x-www-form-urlencoded' }, }).success(function(data) { sync(); }); } } $scope.processAddAdminForm = function(newAdmin) { if (newAdmin == null) return; submit_url = 'api/v1/admin/whitelist'; submit_data = { '_xsrf': $cookies._xsrf, 'newAdmin': newAdmin }; $http({ method : 'POST', url : submit_url, data : $.param(submit_data), headers : { 'Content-Type': 'application/x-www-form-urlencoded' }, }).success(function(data) { $scope.addAdminTextBox = null; sync(); }); } $scope.changeState = function(state) { submit_url = 'api/v1/admin/frozen'; submit_data = { '_xsrf': $cookies._xsrf, 'state': state }; $http({ method : 'POST', url : submit_url, data : $.param(submit_data), headers : { 'Content-Type': 'application/x-www-form-urlencoded' }, }).success(function (data) {}); } $scope.clarifRespModalOpen = function(respNum, clarifNum) { var modalInstance = $modal.open({ templateUrl: 'clarifResponse.html', controller: 'ClarifRespModalCtrl', resolve: { respNum: function () { return respNum; }, clarifNum: function() { return clarifNum; } } }); modalInstance.result.then(function (response) { submit_url = 'api/v1/admin/clarifications' response['_xsrf'] = $cookies._xsrf; $http({ method : 'POST', url : submit_url, data : $.param(response), headers : { 'Content-Type': 'application/x-www-form-urlencoded' }, }).success(function(data) { sync(); }); }, function () { }); }; $scope.newClarification = function(index) { $scope.newClarifModalOpen($scope.probIds[index]) } $scope.newClarifModalOpen = function(probId) { var modalInstance = $modal.open({ templateUrl: 'newClarification.html', controller: 'NewClarifModalCtrl', resolve: { probId: function () { return probId; } } }); modalInstance.result.then(function (response) { submit_url = 'api/v1/admin/clarification' response['_xsrf'] = $cookies._xsrf; $http({ method : 'POST', url : submit_url, data : $.param(response), headers : { 'Content-Type': 'application/x-www-form-urlencoded' }, }).success(function(data) { sync(); }); }, function () { }); }; var tabClasses; function initTabs() { tabClasses = ["","","",""]; } $scope.getTabClass = function (tabNum) { return tabClasses[tabNum]; }; $scope.getTabPaneClass = function (tabNum) { return "tab-pane " + tabClasses[tabNum]; } $scope.setActiveTab = function (tabNum) { initTabs(); tabClasses[tabNum] = "active"; }; initTabs(); $scope.setActiveTab(1); }]); contestControllers.controller('ClarifRespModalCtrl', function ($scope, $modalInstance, respNum, clarifNum) { $scope.ok = function () { $modalInstance.close({ 'respNum': respNum, 'clarifNum': clarifNum, 'response': $scope.response, }); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }); contestControllers.controller('NewClarifModalCtrl', function ($scope, $modalInstance, probId) { $scope.ok = function () { $modalInstance.close({ 'probId': probId, 'response': $scope.newClarifResp, }); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }); contestControllers.controller('ProblemCtrl', ['$scope', '$http', '$rootScope', '$window', '$cookies', '$interval', function ($scope, $http, $rootScope, $window, $cookies, $interval) { var tabClasses; $scope.files = {}; $scope.files.output = []; $scope.files.source = []; i = 0; for (probId in probIds) { $scope.files.output.push(""); $scope.files.source.push(""); } if (typeof $rootScope.showSubmit == 'undefined') { $rootScope.showSubmit = []; $rootScope.ttl = []; $rootScope.ttlText = []; $rootScope.tick = []; for (probId in probIds) { $rootScope.showSubmit.push(false); $rootScope.ttl.push(-1); $rootScope.ttlText.push(""); $rootScope.tick.push(null); } } function initTabs() { tabClasses = []; $scope.open = []; for (probId in probIds) { tabClasses.push(""); $scope.open.push(false); } } $scope.getTabClass = function (tabNum) { if ($scope.solved[probIds[tabNum - 1]]) { return tabClasses[tabNum] + " panel-success"; } else if ($scope.remainingPermits[probIds[tabNum - 1]] == 0 && !$rootScope.showSubmit[tabNum - 1]) { return tabClasses[tabNum] + " panel-danger"; } else if ($rootScope.activeTab == tabNum) { return tabClasses[tabNum] + " panel-primary"; } }; $scope.getTabPaneClass = function (tabNum) { return "tab-pane " + tabClasses[tabNum]; }; $scope.setActiveTab = function (tabNum) { initTabs(); tabClasses[tabNum] = "active"; $rootScope.activeTab = tabNum; $scope.open[tabNum - 1] = true; }; if (typeof $rootScope.activeTab == 'undefined') { $scope.setActiveTab(1); } else { $scope.setActiveTab($rootScope.activeTab); } $scope.clarif = {} $scope.processClarifForm = function (index) { submitUrl = 'api/v1/submit/' + probIds[index] + '/clarification'; submitData = { '_xsrf': $cookies._xsrf, 'content': $scope.clarif[index] }; $http({ method : 'POST', url : submitUrl, data : $.param(submitData), headers : { 'Content-Type': 'application/x-www-form-urlencoded' }, }).success(function (data) { if (data) { $window.alert("Clarification submitted successfully!"); $scope.clarifications.push({ 'prob_id': probIds[index], 'message': $scope.clarif[index], }); $scope.clarif[index] = null; } }); }; function tick (index) { $rootScope.ttl[index] -= 1; $rootScope.ttlText[index] = momentMinutes($rootScope.ttl[index]); if ($rootScope.ttl[index] <= 0) { $rootScope.showSubmit[index] = false; if ($rootScope.tick[index] != null) { $interval.cancel($rootScope.tick[index]); $rootScope.tick[index] = null; } } } $scope.getPermit = function (index, create) { permitUrl = 'api/v1/permits'; permitData = { '_xsrf': $cookies._xsrf, 'content': probIds[index], 'create': create }; $http({ method : 'POST', url : permitUrl, data : $.param(permitData), headers : { 'Content-Type': 'application/x-www-form-urlencoded' }, }).success(function (data) { if (data == null && !create) return; if ($rootScope.tick[index] != null) { $interval.cancel($rootScope.tick[index]); $rootScope.tick[index] = null; } if (data === 'solved') { $scope.solved[probIds[index]] = true; return; } if (data.is_new) $scope.remainingPermits[probIds[index]]--; $rootScope.showSubmit[index] = true; $rootScope.ttl[index] = data.ttl; $rootScope.ttlText[index] = momentMinutes($rootScope.ttl[index]); $rootScope.tick[index] = $interval(function () { tick(index); }, 1000, data.ttl); }).error(function (data, status, headers, config) { if (create && status == 403) { $window.alert("You are out of permits!"); } }); }; var i = 0; for (probId in probIds) { $scope.getPermit(i, false); i++; } $scope.processSubmitForm = function (index) { submitUrl = 'api/v1/submit/' + probIds[index] + '/solution'; submitData = { '_xsrf': $cookies._xsrf, 'outputFile': $scope.files.output[index], 'sourceFile': $scope.files.source[index], }; $rootScope.showSubmit[index] = false; $rootScope.ttl[index] = 0; if ($rootScope.tick[index] != null) { $interval.cancel($rootScope.tick[index]); $rootScope.tick[index] = null; } $http({ method : 'POST', url : submitUrl, data : $.param(submitData), headers : { 'Content-Type': 'application/x-www-form-urlencoded' }, }).success(function (data) { if (data) { $scope.solved[probIds[index]] = true; setTimeout(function () { $window.alert("Solution accepted!"); }, 1000); } else { setTimeout(function () { $window.alert("Solution incorrect!"); }, 1000); } }); }; }]); contestControllers.controller('ScoreboardCtrl', ['$scope', '$http', function ($scope, $http) { }]);
static/js/controllers.js
var preContestControllers = angular.module('preContestControllers', []); preContestControllers.controller('MainCtrl', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout, $window) { function sync () { $http.get('api/v1/updates').success(function (data) { if ($scope.rawTime < parseInt(data['remaining_time'])) { $window.location.reload(); } $scope.rawTime = data['remaining_time']; $scope.remainingTime = moment($scope.rawTime); $timeout(sync, 5000); for (i = 1000; i <= 4000; i += 1000) { $timeout(tick, i); } }); } function tick () { $scope.rawTime -= 1; if ($scope.rawTime < 0) { $window.location.reload(); } else { $scope.remainingTime = moment($scope.rawTime); } } sync(); }]); preContestControllers.controller('HomeCtrl', ['$scope', '$http', function ($scope, $http) { }]); var contestControllers = angular.module('contestControllers', []); var probIds = []; contestControllers.controller('MainCtrl', ['$scope', '$http', '$interval', '$rootScope', function ($scope, $http, $interval, $rootScope, $window) { $http.get('api/v1/metadata').success(function (data) { $scope.probIds = probIds = data['prob_ids']; $scope.probContents = data['prob_contents']; $scope.remainingPermits = data['remaining_permit_counts']; $scope.solved = data['solved']; $scope.problemsTimeToSolve = data['problems_time_to_solve']; for (var i = 0; i < probIds.length; i++) { $scope.problemsTimeToSolve[probIds[i]] = momentMinutes($scope.problemsTimeToSolve[probIds[i]]); } }); $rootScope.syncUpdates = function () { $http.get('api/v1/updates').success(function (data) { if (typeof $rootScope.prevSync !== 'undefined') $interval.cancel($rootScope.prevSync); $rootScope.rawTime = data['remaining_time']; $scope.scoreboard = data['scoreboard']; $scope.clarifications = data['clarifications']; $rootScope.remainingTime = moment($rootScope.rawTime); $rootScope.prevSync = $interval($rootScope.clockTick, 1000, 29); }); } $rootScope.clockTick = function () { $rootScope.rawTime -= 1; if ($rootScope.rawTime >= 0) { $rootScope.remainingTime = moment($rootScope.rawTime); } } $rootScope.syncUpdates(); $interval($rootScope.syncUpdates, 30000); }]); contestControllers.controller('HomeCtrl', ['$scope', '$http', function ($scope, $http) { }]); var whitelist = []; var allClarifications = []; var radioModel = 'Active'; contestControllers.controller('AdminCtrl', ['$scope', '$rootScope', '$http', '$cookies', '$window', '$modal', '$interval', function ($scope, $rootScope, $http, $cookies, $window, $modal, $interval) { function sync () { $http.get('api/v1/admin/updates').success(function (data) { $scope.whitelist = data.whitelist; $scope.allClarifications = data.clarifs; $scope.boardIsFrozen = data.frozen; $scope.radioModel = $scope.boardIsFrozen ? 'Frozen' : 'Active'; }); } sync(); $interval(sync, 10000); $scope.rejudgeProblem = function(problemId) { submit_url = 'api/v1/admin/rejudge'; submit_data = { '_xsrf': $cookies._xsrf, 'probId': problemId }; $http({ method : 'POST', url : submit_url, data : $.param(submit_data), headers : { 'Content-Type': 'application/x-www-form-urlencoded' }, }).success(function(data) { $window.alert("Rejudging problem " + problemId); }); } $scope.processAddTimeInput = function(numMin) { submit_url = 'api/v1/admin/add_time'; submit_data = { '_xsrf': $cookies._xsrf, 'numMin': numMin }; $http({ method : 'POST', url : submit_url, data : $.param(submit_data), headers : { 'Content-Type': 'application/x-www-form-urlencoded' }, }).success(function(data) { $scope.addTimeTextBox = null; $rootScope.syncUpdates(); }); } $scope.processClarifResponse = function(respNum, clarifNum) { submit_url = 'api/v1/admin/clarifications'; var respString = ''; if(respNum == 2) { $scope.clarifRespModalOpen(respNum, clarifNum) } else { submit_data = { '_xsrf': $cookies._xsrf, 'respNum': respNum, 'clarifNum': clarifNum, 'respString': '' }; $http({ method : 'POST', url : submit_url, data : $.param(submit_data), headers : { 'Content-Type': 'application/x-www-form-urlencoded' }, }).success(function(data) { sync(); }); } } $scope.processAddAdminForm = function(newAdmin) { if (newAdmin == null) return; submit_url = 'api/v1/admin/whitelist'; submit_data = { '_xsrf': $cookies._xsrf, 'newAdmin': newAdmin }; $http({ method : 'POST', url : submit_url, data : $.param(submit_data), headers : { 'Content-Type': 'application/x-www-form-urlencoded' }, }).success(function(data) { $scope.addAdminTextBox = null; sync(); }); } $scope.changeState = function(state) { submit_url = 'api/v1/admin/frozen'; submit_data = { '_xsrf': $cookies._xsrf, 'state': state }; $http({ method : 'POST', url : submit_url, data : $.param(submit_data), headers : { 'Content-Type': 'application/x-www-form-urlencoded' }, }).success(function (data) {}); } $scope.clarifRespModalOpen = function(respNum, clarifNum) { var modalInstance = $modal.open({ templateUrl: 'clarifResponse.html', controller: 'ClarifRespModalCtrl', resolve: { respNum: function () { return respNum; }, clarifNum: function() { return clarifNum; } } }); modalInstance.result.then(function (response) { submit_url = 'api/v1/admin/clarifications' response['_xsrf'] = $cookies._xsrf; $http({ method : 'POST', url : submit_url, data : $.param(response), headers : { 'Content-Type': 'application/x-www-form-urlencoded' }, }).success(function(data) { sync(); }); }, function () { }); }; $scope.newClarification = function(index) { $scope.newClarifModalOpen($scope.probIds[index]) } $scope.newClarifModalOpen = function(probId) { var modalInstance = $modal.open({ templateUrl: 'newClarification.html', controller: 'NewClarifModalCtrl', resolve: { probId: function () { return probId; } } }); modalInstance.result.then(function (response) { submit_url = 'api/v1/admin/clarification' response['_xsrf'] = $cookies._xsrf; $http({ method : 'POST', url : submit_url, data : $.param(response), headers : { 'Content-Type': 'application/x-www-form-urlencoded' }, }).success(function(data) { sync(); }); }, function () { }); }; var tabClasses; function initTabs() { tabClasses = ["","","",""]; } $scope.getTabClass = function (tabNum) { return tabClasses[tabNum]; }; $scope.getTabPaneClass = function (tabNum) { return "tab-pane " + tabClasses[tabNum]; } $scope.setActiveTab = function (tabNum) { initTabs(); tabClasses[tabNum] = "active"; }; initTabs(); $scope.setActiveTab(1); }]); contestControllers.controller('ClarifRespModalCtrl', function ($scope, $modalInstance, respNum, clarifNum) { $scope.ok = function () { $modalInstance.close({ 'respNum': respNum, 'clarifNum': clarifNum, 'response': $scope.response, }); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }); contestControllers.controller('NewClarifModalCtrl', function ($scope, $modalInstance, probId) { $scope.ok = function () { $modalInstance.close({ 'probId': probId, 'response': $scope.newClarifResp, }); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }); contestControllers.controller('ProblemCtrl', ['$scope', '$http', '$rootScope', '$window', '$cookies', '$interval', function ($scope, $http, $rootScope, $window, $cookies, $interval) { var tabClasses; $scope.files = {}; $scope.files.output = []; $scope.files.source = []; i = 0; for (probId in probIds) { $scope.files.output.push(""); $scope.files.source.push(""); } if (typeof $rootScope.showSubmit == 'undefined') { $rootScope.showSubmit = []; $rootScope.ttl = []; $rootScope.ttlText = []; $rootScope.tick = []; for (probId in probIds) { $rootScope.showSubmit.push(false); $rootScope.ttl.push(-1); $rootScope.ttlText.push(""); $rootScope.tick.push(null); } } function initTabs() { tabClasses = []; $scope.open = []; for (probId in probIds) { tabClasses.push(""); $scope.open.push(false); } } $scope.getTabClass = function (tabNum) { if ($scope.solved[probIds[tabNum - 1]]) { return tabClasses[tabNum] + " panel-success"; } else if ($scope.remainingPermits[probIds[tabNum - 1]] == 0 && !$rootScope.showSubmit[tabNum - 1]) { return tabClasses[tabNum] + " panel-danger"; } else if ($rootScope.activeTab == tabNum) { return tabClasses[tabNum] + " panel-primary"; } }; $scope.getTabPaneClass = function (tabNum) { return "tab-pane " + tabClasses[tabNum]; }; $scope.setActiveTab = function (tabNum) { initTabs(); tabClasses[tabNum] = "active"; $rootScope.activeTab = tabNum; $scope.open[tabNum - 1] = true; }; if (typeof $rootScope.activeTab == 'undefined') { $scope.setActiveTab(1); } else { $scope.setActiveTab($rootScope.activeTab); } $scope.clarif = {} $scope.processClarifForm = function (index) { submitUrl = 'api/v1/submit/' + probIds[index] + '/clarification'; submitData = { '_xsrf': $cookies._xsrf, 'content': $scope.clarif[index] }; $http({ method : 'POST', url : submitUrl, data : $.param(submitData), headers : { 'Content-Type': 'application/x-www-form-urlencoded' }, }).success(function (data) { if (data) { $window.alert("Clarification submitted successfully!"); $scope.clarifications.push({ 'prob_id': probIds[index], 'message': $scope.clarif[index], }); $scope.clarif[index] = null; } }); }; function tick (index) { $rootScope.ttl[index] -= 1; $rootScope.ttlText[index] = momentMinutes($rootScope.ttl[index]); if ($rootScope.ttl[index] <= 0) { $rootScope.showSubmit[index] = false; if ($rootScope.tick[index] != null) { $interval.cancel($rootScope.tick[index]); $rootScope.tick[index] = null; } } } $scope.getPermit = function (index, create) { permitUrl = 'api/v1/permits'; permitData = { '_xsrf': $cookies._xsrf, 'content': probIds[index], 'create': create }; $http({ method : 'POST', url : permitUrl, data : $.param(permitData), headers : { 'Content-Type': 'application/x-www-form-urlencoded' }, }).success(function (data) { if (data == null && !create) return; if ($rootScope.tick[index] != null) { $interval.cancel($rootScope.tick[index]); $rootScope.tick[index] = null; } if (data === 'solved') { $scope.solved[probIds[index]] = true; return; } if (data.is_new) $scope.remainingPermits[probIds[index]]--; $rootScope.showSubmit[index] = true; $rootScope.ttl[index] = data.ttl; $rootScope.ttlText[index] = momentMinutes($rootScope.ttl[index]); $rootScope.tick[index] = $interval(function () { tick(index); }, 1000, data.ttl); }).error(function (data, status, headers, config) { if (create && status == 403) { $window.alert("You are out of permits!"); } }); }; var i = 0; for (probId in probIds) { $scope.getPermit(i, false); i++; } $scope.processSubmitForm = function (index) { submitUrl = 'api/v1/submit/' + probIds[index] + '/solution'; submitData = { '_xsrf': $cookies._xsrf, 'outputFile': $scope.files.output[index], 'sourceFile': $scope.files.source[index], }; $rootScope.showSubmit[index] = false; $rootScope.ttl[index] = 0; if ($rootScope.tick[index] != null) { $interval.cancel($rootScope.tick[index]); $rootScope.tick[index] = null; } $http({ method : 'POST', url : submitUrl, data : $.param(submitData), headers : { 'Content-Type': 'application/x-www-form-urlencoded' }, }).success(function (data) { if (data) { $scope.solved[probIds[index]] = true; $window.alert("Solution accepted!"); } else { $window.alert("Solution incorrect!"); } }); }; }]); contestControllers.controller('ScoreboardCtrl', ['$scope', '$http', function ($scope, $http) { }]);
delay alerts for correct/incorrect
static/js/controllers.js
delay alerts for correct/incorrect
<ide><path>tatic/js/controllers.js <ide> }).success(function (data) { <ide> if (data) { <ide> $scope.solved[probIds[index]] = true; <del> $window.alert("Solution accepted!"); <add> setTimeout(function () { <add> $window.alert("Solution accepted!"); <add> }, 1000); <ide> } else { <del> $window.alert("Solution incorrect!"); <add> setTimeout(function () { <add> $window.alert("Solution incorrect!"); <add> }, 1000); <ide> } <ide> }); <ide> };
JavaScript
isc
2a9e95bc6465af125d912e9be0af7fd183547511
0
mysimpleapp/mysimpleapp
const numCPUs = 1 module.exports = async function() { if (cluster.isMaster) { console.log(`Master ${process.pid} is running`) for (let i = 0; i < numCPUs; i++) { cluster.fork() } cluster.on('exit', (worker, code, signal) => { console.log(`worker ${worker.process.pid} died`); cluster.fork() }) } else { await startInstance() } } async function startInstance() { // create modules router Msa.modulesRouter = Msa.express.Router() // call msa modules msa_start.js const modules = Msa.params.modules for(let key in modules) await Msa.start(key, modules[key]) // require msa modules for(let key in Msa.Modules){ // get name of module const desc = Msa.Modules[key] const { name } = desc // determine dir of module const dir = await com.tryResolveDir(name) // require module (or create it in case module has no index.js) let mod = Msa.tryRequire(key) if(!mod) mod = desc.mod = new Msa.Module() // init await initMsaMod(key, mod, dir) } // create "msa" module const msaMod = new Msa.Module() Msa.Modules["msa"] = { name: "msa", mod: msaMod } await initMsaMod("msa", msaMod, Msa.dirname) // use main moduke Msa.app = Msa.require("$app").app // start server startServer() } async function initMsaMod(key, mod, dir) { mod.msaKey = key // static files if(mod.checkStaticDir !== false){ const staticDir = join(dir, "static") if(await fileExists(staticDir)) mod.app.use(Msa.express.static(staticDir)) } // use module Msa.modulesRouter.use('/'+key, mod.app) } const startedMods = {} Msa.start = async function(key, desc){ // prevent infinite loop let res = startedMods[key] if(res !== undefined) return res res = startedMods[key] = null // register msa module (as it may be needed by some msa_start.js) const pDesc = com.parseModDesc(desc), { name } = pDesc com.registerMsaModule(key, pDesc) // exec dependencies msa_start.js before const { deps } = await com.parsePackageFile(name, { key }) for(let depKey in deps) await Msa.start(depKey, deps[depKey]) // exec msa_start.js (if any) const dir = await com.tryResolveDir(name), msaStartPath = tryResolve( join(dir, "msa_start") ) if(msaStartPath) { const msaStartPrm = require(msaStartPath) res = await msaStartPrm() if(res !== undefined) startedMods[key] = res } return res } var startServer = function() { var paramsServer = Msa.params.server, isHttps = paramsServer.https.activated // create server if(isHttps) { var https = require('https') var cred = { key: fs.readFileSync(paramsServer.https.key), cert: fs.readFileSync(paramsServer.https.cert) } var server = https.createServer(cred, Msa.app) } else { var http = require('http') var server = http.createServer(Msa.app) } // determine port var port = paramsServer.port if(port=="dev") port = isHttps ? 8443 : 8080 if(port=="prd") port = isHttps ? 81 : 80 // start server server.listen(port) // log var prot = isHttps ? "https" : "http" console.log(`Worker ${process.pid} started`) console.log("Server ready: "+prot+"://localhost:"+port+"/") } // utils const { promisify:prm } = require('util') const { join, dirname } = require('path') const fs = require('fs'), access = prm(fs.access) const cluster = require('cluster') const com = require('./com') function tryResolve(name, kwargs) { let res = null try { res = require.resolve(name, kwargs) } catch(_) {} return res } async function fileExists(path) { try { await access(path) } catch(_) { return false } return true }
src/start.js
module.exports = async function() { // create modules router Msa.modulesRouter = Msa.express.Router() // call msa modules msa_start.js const modules = Msa.params.modules for(let key in modules) await Msa.start(key, modules[key]) // require msa modules for(let key in Msa.Modules){ // get name of module const desc = Msa.Modules[key] const { name } = desc // determine dir of module const dir = await com.tryResolveDir(name) // require module (or create it in case module has no index.js) let mod = Msa.tryRequire(key) if(!mod) mod = desc.mod = new Msa.Module() // init await initMsaMod(key, mod, dir) } // create "msa" module const msaMod = new Msa.Module() Msa.Modules["msa"] = { name: "msa", mod: msaMod } await initMsaMod("msa", msaMod, Msa.dirname) // use main moduke Msa.app = Msa.require("$app").app // start server startServer() } async function initMsaMod(key, mod, dir) { mod.msaKey = key // static files if(mod.checkStaticDir !== false){ const staticDir = join(dir, "static") if(await fileExists(staticDir)) mod.app.use(Msa.express.static(staticDir)) } // use module Msa.modulesRouter.use('/'+key, mod.app) } const startedMods = {} Msa.start = async function(key, desc){ // prevent infinite loop let res = startedMods[key] if(res !== undefined) return res res = startedMods[key] = null // register msa module (as it may be needed by some msa_start.js) const pDesc = com.parseModDesc(desc), { name } = pDesc com.registerMsaModule(key, pDesc) // exec dependencies msa_start.js before const { deps } = await com.parsePackageFile(name, { key }) for(let depKey in deps) await Msa.start(depKey, deps[depKey]) // exec msa_start.js (if any) const dir = await com.tryResolveDir(name), msaStartPath = tryResolve( join(dir, "msa_start") ) if(msaStartPath) { const msaStartPrm = require(msaStartPath) res = await msaStartPrm() if(res !== undefined) startedMods[key] = res } return res } var startServer = function() { var paramsServer = Msa.params.server, isHttps = paramsServer.https.activated // create server if(isHttps) { var https = require('https') var cred = { key: fs.readFileSync(paramsServer.https.key), cert: fs.readFileSync(paramsServer.https.cert) } var server = https.createServer(cred, Msa.app) } else { var http = require('http') var server = http.createServer(Msa.app) } // determine port var port = paramsServer.port if(port=="dev") port = isHttps ? 8443 : 8080 if(port=="prd") port = isHttps ? 81 : 80 // start server server.listen(port) // log var prot = isHttps ? "https" : "http" console.log("Server ready: "+prot+"://localhost:"+port+"/") } // utils const { promisify:prm } = require('util') const { join, dirname } = require('path') const fs = require('fs'), access = prm(fs.access) const com = require('./com') function tryResolve(name, kwargs) { let res = null try { res = require.resolve(name, kwargs) } catch(_) {} return res } async function fileExists(path) { try { await access(path) } catch(_) { return false } return true }
cluster
src/start.js
cluster
<ide><path>rc/start.js <add>const numCPUs = 1 <add> <ide> module.exports = async function() { <add> if (cluster.isMaster) { <add> console.log(`Master ${process.pid} is running`) <add> for (let i = 0; i < numCPUs; i++) { <add> cluster.fork() <add> } <add> cluster.on('exit', (worker, code, signal) => { <add> console.log(`worker ${worker.process.pid} died`); <add> cluster.fork() <add> }) <add> } else { <add> await startInstance() <add> } <add>} <add> <add>async function startInstance() { <ide> // create modules router <ide> Msa.modulesRouter = Msa.express.Router() <ide> // call msa modules msa_start.js <ide> server.listen(port) <ide> // log <ide> var prot = isHttps ? "https" : "http" <del> console.log("Server ready: "+prot+"://localhost:"+port+"/") <add> console.log(`Worker ${process.pid} started`) <add>console.log("Server ready: "+prot+"://localhost:"+port+"/") <ide> } <ide> <ide> <ide> const { join, dirname } = require('path') <ide> const fs = require('fs'), <ide> access = prm(fs.access) <add>const cluster = require('cluster') <ide> const com = require('./com') <ide> <ide> function tryResolve(name, kwargs) {
Java
mit
5ebef1272481c77d46e20c07214ae815c20fb842
0
Enthri/aprctsrpg
import java.util.Random; import ui.*; import ui.elem.*; import util.Assassin; import util.BattleHandler; import util.EntityCreature; import util.Item; import util.Tank; import util.Zombie; /* * This is the class where all the battles are handled */ public class StageBattle extends Stage { //initializing choices private Choice fightButton; private Choice ability0; private Choice ability1; private Choice ability2; private Choice ability3; private Choice runButton; //initializing the stats //the stats are located at the top and the bottom of the screen on the upper and lower right private Stat playerStat; private OpponentStat opponentStat; private Dialog mainDialog; private int scheduleCode = 0; private int selectedAbility = -1; private Item itemVar2; @Override public void init() { if(DataHandler.player == null) { this.setStage(1); return; } //if there is no player, then just start stage prologue for character creation itemVar2 = null; //sets the Item to null fightButton = new Choice("Attack"); //creates the important attack button ability0 = new Choice(DataHandler.player.getAbilitiesName(0)); //gets the abilities' name using a method that does just that and adds it as a new choice ability1 = new Choice(DataHandler.player.getAbilitiesName(1)); ability2 = new Choice(DataHandler.player.getAbilitiesName(2)); ability3 = new Choice(DataHandler.player.getAbilitiesName(3)); runButton = new Choice("Run!"); //the all powerful run method that never works playerStat = new Stat(); //creates the stat. The player's are on the top right and the opponent's are on the bottom right opponentStat = new OpponentStat(); mainDialog = new Dialog(); this.addElements(fightButton, ability0, ability1, ability2, ability3, runButton, playerStat, opponentStat, mainDialog); //the following methods check what picture should be put on the rightmost pane if(DataHandler.player instanceof Tank) this.addElements(new Sprite("tank.png", 0.5f)); else if(DataHandler.player instanceof Assassin) this.addElements(new Sprite("assassin.png", 0.5f)); else this.addElements(new Sprite("norm.png", 0.5f)); if(DataHandler.opponent instanceof Zombie) { if(new Random().nextInt(2) == 0) this.addElements(new Sprite("minion.png", 0.5f)); //a random conditional to determine which one will be added else this.addElements(new Sprite("minion2.png", 0.5f)); } else if(DataHandler.source instanceof StageMotherZombie) { switch(new Random().nextInt(3)) { //adding the appropriate sprite to the screen case 0: this.addElements(new Sprite("boss1.png", 0.5f)); break; case 1: this.addElements(new Sprite("boss2.png", 0.5f)); break; case 2: this.addElements(new Sprite("boss3.png", 0.5f)); break; default: this.addElements(new Sprite("guy.png", 0.5f)); break; } } else if(DataHandler.opponent instanceof EntityCreature) this.addElements(new Sprite("guy.png", 0.5f)); fightButton.setEnabled(false); runButton.setEnabled(false); playerTurn(); } @Override public void choiceClicked(Element elementVar) { if(itemVar2 == null) { fightButton.setEnabled(false); runButton.setEnabled(false); ability0.setEnabled(false); ability1.setEnabled(false); ability2.setEnabled(false); ability3.setEnabled(false); Choice choiceObject = (Choice)elementVar; if(choiceObject == fightButton) { boolean flag = BattleHandler.playerTurn(DataHandler.player, selectedAbility, DataHandler.opponent); updateStats();//a method to update the stats if(flag) mainDialog.appendText("\nYou dealt damage!"); else mainDialog.appendText("\nYour attack missed!"); scheduleCode = 2; this.scheduleTask(30); } else if(choiceObject == runButton){ if(BattleHandler.run(DataHandler.player, DataHandler.opponent) && !(DataHandler.source instanceof StageMotherZombie)) { scheduleCode = 1; mainDialog.appendText("\nYou got away safely.."); this.scheduleTask(30); } else { scheduleCode = 2; mainDialog.appendText("\nCan't escape!"); this.scheduleTask(30); } } else if(choiceObject == ability0) { fightButton.setEnabled(true); runButton.setEnabled(true); selectedAbility = 0; } else if(choiceObject == ability1) { fightButton.setEnabled(true); runButton.setEnabled(true); selectedAbility = 1; } else if(choiceObject == ability2) { fightButton.setEnabled(true); runButton.setEnabled(true); selectedAbility = 2; } else if(choiceObject == ability3) { fightButton.setEnabled(true); runButton.setEnabled(true); selectedAbility = 3; } } else { if(elementVar == fightButton) { DataHandler.player.addItem(itemVar2); endBattle(); } endBattle(); } } @Override public void taskPerformed() { if(scheduleCode == 1) { exitBattle(); } else if(scheduleCode == 2) { opponentTurn(); } else if(scheduleCode == 3) { playerTurn(); } } private void playerTurn() { if(DataHandler.opponent.getHealth() <= 0 || DataHandler.player.getHealth() <= 0){ exitBattle(); return; } updateStats(); fightButton.setEnabled(true); runButton.setEnabled(true); ability0.setEnabled(true); ability0.setToolTip(DataHandler.player.getAbilitiesDesc(0)); ability1.setEnabled(true); ability1.setToolTip(DataHandler.player.getAbilitiesDesc(1)); ability2.setEnabled(true); ability2.setToolTip(DataHandler.player.getAbilitiesDesc(2)); ability3.setEnabled(true); ability3.setToolTip(DataHandler.player.getAbilitiesDesc(3)); selectedAbility = -1; mainDialog.setText("What will you do next?"); } private void opponentTurn() { if(DataHandler.opponent.getHealth() <= 0 || DataHandler.player.getHealth() <= 0){ exitBattle(); return; } updateStats(); boolean flag = BattleHandler.creatureTurn(DataHandler.player, DataHandler.opponent); updateStats(); if(flag) mainDialog.setText("Your opponent dealt damage!"); else mainDialog.setText("Your opponent's attack missed!"); scheduleCode = 3; this.scheduleTask(20); } private void updateStats(){ playerStat.setText("PLAYER STATS - Level: " + ((int)(DataHandler.player.getLevel()*10))/10.0D + "\nHealth: " + ((int)(DataHandler.player.getHealth()*10))/10.0D); opponentStat.setText("OPPONENT STATS - Health: " + ((int)(DataHandler.opponent.getHealth()*10))/10.0D); } private void exitBattle() { DataHandler.battleCompleted = true; if(DataHandler.opponent.getHealth() <= 0){ DataHandler.player.leveling(DataHandler.opponent); giveItem(DataHandler.opponent.randomDrop()); return; } endBattle(); } private void endBattle() { if(DataHandler.player.getHealth() <= 0) this.setStage(9); else this.setStage(DataHandler.source.getID()); } private void giveItem(Item itemVar) { this.removeElements(ability0, ability1, ability2, ability3, playerStat, opponentStat); mainDialog.setText("YOU GOT A " + itemVar.getName().toUpperCase(), "Do you want it?"); itemVar2 = itemVar; fightButton.setLabel("Accept Item", true); runButton.setLabel("Reject Item", true); } }
StageBattle.java
import java.util.Random; import ui.*; import ui.elem.*; import util.Assassin; import util.BattleHandler; import util.EntityCreature; import util.Item; import util.Tank; import util.Zombie; /* * This is the class where all the battles are handled */ public class StageBattle extends Stage { //initializing choices private Choice fightButton; private Choice ability0; private Choice ability1; private Choice ability2; private Choice ability3; private Choice runButton; //initializing the stats //the stats are located at the top and the bottom of the screen on the upper and lower right private Stat playerStat; private OpponentStat opponentStat; private Dialog mainDialog; private int scheduleCode = 0; private int selectedAbility = -1; private Item itemVar2; @Override public void init() { if(DataHandler.player == null) { this.setStage(1); return; } //if there is no player, then just start stage prologue for character creation itemVar2 = null; //sets the Item to null fightButton = new Choice("Attack"); //creates the important attack button ability0 = new Choice(DataHandler.player.getAbilitiesName(0)); //gets the abilities' name using a method that does just that and adds it as a new choice ability1 = new Choice(DataHandler.player.getAbilitiesName(1)); ability2 = new Choice(DataHandler.player.getAbilitiesName(2)); ability3 = new Choice(DataHandler.player.getAbilitiesName(3)); runButton = new Choice("Run!"); //the all powerful run method that never works playerStat = new Stat(); //creates the stat. The player's are on the top right and the opponent's are on the bottom right opponentStat = new OpponentStat(); mainDialog = new Dialog(); this.addElements(fightButton, ability0, ability1, ability2, ability3, runButton, playerStat, opponentStat, mainDialog); //the following methods check what picture should be put on the rightmost pane if(DataHandler.player instanceof Tank) this.addElements(new Sprite("tank.png", 0.5f)); else if(DataHandler.player instanceof Assassin) this.addElements(new Sprite("assassin.png", 0.5f)); else this.addElements(new Sprite("norm.png", 0.5f)); if(DataHandler.opponent instanceof Zombie) { if(new Random().nextInt(2) == 0) this.addElements(new Sprite("minion.png", 0.5f)); //a random conditional to determine which one will be added else this.addElements(new Sprite("minion2.png", 0.5f)); } else if(DataHandler.source instanceof StageMotherZombie) { switch(new Random().nextInt(3)) { case 0: this.addElements(new Sprite("boss1.png", 0.5f)); break; case 1: this.addElements(new Sprite("boss2.png", 0.5f)); break; case 2: this.addElements(new Sprite("boss3.png", 0.5f)); break; default: this.addElements(new Sprite("guy.png", 0.5f)); break; } } else if(DataHandler.opponent instanceof EntityCreature) this.addElements(new Sprite("guy.png", 0.5f)); fightButton.setEnabled(false); runButton.setEnabled(false); playerTurn(); } @Override public void choiceClicked(Element elementVar) { if(itemVar2 == null) { fightButton.setEnabled(false); runButton.setEnabled(false); ability0.setEnabled(false); ability1.setEnabled(false); ability2.setEnabled(false); ability3.setEnabled(false); Choice choiceObject = (Choice)elementVar; if(choiceObject == fightButton) { boolean flag = BattleHandler.playerTurn(DataHandler.player, selectedAbility, DataHandler.opponent); updateStats();//a method to update the stats if(flag) mainDialog.appendText("\nYou dealt damage!"); else mainDialog.appendText("\nYour attack missed!"); scheduleCode = 2; this.scheduleTask(30); } else if(choiceObject == runButton){ if(BattleHandler.run(DataHandler.player, DataHandler.opponent) && !(DataHandler.source instanceof StageMotherZombie)) { scheduleCode = 1; mainDialog.appendText("\nYou got away safely.."); this.scheduleTask(30); } else { scheduleCode = 2; mainDialog.appendText("\nCan't escape!"); this.scheduleTask(30); } } else if(choiceObject == ability0) { fightButton.setEnabled(true); runButton.setEnabled(true); selectedAbility = 0; } else if(choiceObject == ability1) { fightButton.setEnabled(true); runButton.setEnabled(true); selectedAbility = 1; } else if(choiceObject == ability2) { fightButton.setEnabled(true); runButton.setEnabled(true); selectedAbility = 2; } else if(choiceObject == ability3) { fightButton.setEnabled(true); runButton.setEnabled(true); selectedAbility = 3; } } else { if(elementVar == fightButton) { DataHandler.player.addItem(itemVar2); endBattle(); } endBattle(); } } @Override public void taskPerformed() { if(scheduleCode == 1) { exitBattle(); } else if(scheduleCode == 2) { opponentTurn(); } else if(scheduleCode == 3) { playerTurn(); } } private void playerTurn() { if(DataHandler.opponent.getHealth() <= 0 || DataHandler.player.getHealth() <= 0){ exitBattle(); return; } updateStats(); fightButton.setEnabled(true); runButton.setEnabled(true); ability0.setEnabled(true); ability0.setToolTip(DataHandler.player.getAbilitiesDesc(0)); ability1.setEnabled(true); ability1.setToolTip(DataHandler.player.getAbilitiesDesc(1)); ability2.setEnabled(true); ability2.setToolTip(DataHandler.player.getAbilitiesDesc(2)); ability3.setEnabled(true); ability3.setToolTip(DataHandler.player.getAbilitiesDesc(3)); selectedAbility = -1; mainDialog.setText("What will you do next?"); } private void opponentTurn() { if(DataHandler.opponent.getHealth() <= 0 || DataHandler.player.getHealth() <= 0){ exitBattle(); return; } updateStats(); boolean flag = BattleHandler.creatureTurn(DataHandler.player, DataHandler.opponent); updateStats(); if(flag) mainDialog.setText("Your opponent dealt damage!"); else mainDialog.setText("Your opponent's attack missed!"); scheduleCode = 3; this.scheduleTask(20); } private void updateStats(){ playerStat.setText("PLAYER STATS - Level: " + ((int)(DataHandler.player.getLevel()*10))/10.0D + "\nHealth: " + ((int)(DataHandler.player.getHealth()*10))/10.0D); opponentStat.setText("OPPONENT STATS - Health: " + ((int)(DataHandler.opponent.getHealth()*10))/10.0D); } private void exitBattle() { DataHandler.battleCompleted = true; if(DataHandler.opponent.getHealth() <= 0){ DataHandler.player.leveling(DataHandler.opponent); giveItem(DataHandler.opponent.randomDrop()); return; } endBattle(); } private void endBattle() { if(DataHandler.player.getHealth() <= 0) this.setStage(9); else this.setStage(DataHandler.source.getID()); } private void giveItem(Item itemVar) { this.removeElements(ability0, ability1, ability2, ability3, playerStat, opponentStat); mainDialog.setText("YOU GOT A " + itemVar.getName().toUpperCase(), "Do you want it?"); itemVar2 = itemVar; fightButton.setLabel("Accept Item", true); runButton.setLabel("Reject Item", true); } }
Comment
StageBattle.java
Comment
<ide><path>tageBattle.java <ide> else this.addElements(new Sprite("minion2.png", 0.5f)); <ide> } else if(DataHandler.source instanceof StageMotherZombie) { <ide> switch(new Random().nextInt(3)) { <add> //adding the appropriate sprite to the screen <ide> case 0: this.addElements(new Sprite("boss1.png", 0.5f)); break; <ide> case 1: this.addElements(new Sprite("boss2.png", 0.5f)); break; <ide> case 2: this.addElements(new Sprite("boss3.png", 0.5f)); break;
Java
apache-2.0
984a9fb1c350b65759e5f86e6a1e82ef420ac3f1
0
chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq
/** * 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.kahadb.page; import java.io.*; import java.util.*; import org.apache.kahadb.page.PageFile.PageWrite; import org.apache.kahadb.util.*; /** * The class used to read/update a PageFile object. Using a transaction allows you to * do multiple update operations in a single unit of work. */ public class Transaction implements Iterable<Page> { private RandomAccessFile tmpFile; private File txFile; private int nextLocation = 0; /** * The PageOverflowIOException occurs when a page write is requested * and it's data is larger than what would fit into a single page. */ public class PageOverflowIOException extends IOException { public PageOverflowIOException(String message) { super(message); } } /** * The InvalidPageIOException is thrown if try to load/store a a page * with an invalid page id. */ public class InvalidPageIOException extends IOException { private final long page; public InvalidPageIOException(String message, long page) { super(message); this.page = page; } public long getPage() { return page; } } /** * This closure interface is intended for the end user implement callbacks for the Transaction.exectue() method. * * @param <T> The type of exceptions that operation will throw. */ public interface Closure <T extends Throwable> { public void execute(Transaction tx) throws T; } /** * This closure interface is intended for the end user implement callbacks for the Transaction.exectue() method. * * @param <R> The type of result that the closure produces. * @param <T> The type of exceptions that operation will throw. */ public interface CallableClosure<R, T extends Throwable> { public R execute(Transaction tx) throws T; } // The page file that this Transaction operates against. private final PageFile pageFile; // If this transaction is updating stuff.. this is the tx of private long writeTransactionId=-1; // List of pages that this transaction has modified. private TreeMap<Long, PageWrite> writes=new TreeMap<Long, PageWrite>(); // List of pages allocated in this transaction private final SequenceSet allocateList = new SequenceSet(); // List of pages freed in this transaction private final SequenceSet freeList = new SequenceSet(); private long maxTransactionSize = Long.parseLong(System.getProperty("maxKahaDBTxSize", "" + 10485760)); private long size = 0; Transaction(PageFile pageFile) { this.pageFile = pageFile; } /** * @return the page file that created this Transaction */ public PageFile getPageFile() { return this.pageFile; } /** * Allocates a free page that you can write data to. * * @return a newly allocated page. * @throws IOException * If an disk error occurred. * @throws IllegalStateException * if the PageFile is not loaded */ public <T> Page<T> allocate() throws IOException { return allocate(1); } /** * Allocates a block of free pages that you can write data to. * * @param count the number of sequential pages to allocate * @return the first page of the sequential set. * @throws IOException * If an disk error occurred. * @throws IllegalStateException * if the PageFile is not loaded */ public <T> Page<T> allocate(int count) throws IOException { // TODO: we need to track allocated pages so that they can be returned if the // transaction gets rolled back. Page<T> rc = pageFile.allocate(count); allocateList.add(new Sequence(rc.getPageId(), rc.getPageId()+count-1)); return rc; } /** * Frees up a previously allocated page so that it can be re-allocated again. * * @param pageId the page to free up * @throws IOException * If an disk error occurred. * @throws IllegalStateException * if the PageFile is not loaded */ public void free(long pageId) throws IOException { free(load(pageId, null)); } /** * Frees up a previously allocated sequence of pages so that it can be re-allocated again. * * @param pageId the initial page of the sequence that will be getting freed * @param count the number of pages in the sequence * * @throws IOException * If an disk error occurred. * @throws IllegalStateException * if the PageFile is not loaded */ public void free(long pageId, int count) throws IOException { free(load(pageId, null), count); } /** * Frees up a previously allocated sequence of pages so that it can be re-allocated again. * * @param page the initial page of the sequence that will be getting freed * @param count the number of pages in the sequence * * @throws IOException * If an disk error occurred. * @throws IllegalStateException * if the PageFile is not loaded */ public <T> void free(Page<T> page, int count) throws IOException { pageFile.assertLoaded(); long offsetPage = page.getPageId(); for (int i = 0; i < count; i++) { if (page == null) { page = load(offsetPage + i, null); } free(page); page = null; } } /** * Frees up a previously allocated page so that it can be re-allocated again. * * @param page the page to free up * @throws IOException * If an disk error occurred. * @throws IllegalStateException * if the PageFile is not loaded */ public <T> void free(Page<T> page) throws IOException { pageFile.assertLoaded(); // We may need loop to free up a page chain. while (page != null) { // Is it already free?? if (page.getType() == Page.PAGE_FREE_TYPE) { return; } Page<T> next = null; if (page.getType() == Page.PAGE_PART_TYPE) { next = load(page.getNext(), null); } page.makeFree(getWriteTransactionId()); // ensure free page is visible while write is pending pageFile.addToCache(page.copy()); DataByteArrayOutputStream out = new DataByteArrayOutputStream(pageFile.getPageSize()); page.write(out); write(page, out.getData()); freeList.add(page.getPageId()); page = next; } } /** * * @param page * the page to write. The Page object must be fully populated with a valid pageId, type, and data. * @param marshaller * the marshaler to use to load the data portion of the Page, may be null if you do not wish to write the data. * @param overflow * If true, then if the page data marshalls to a bigger size than can fit in one page, then additional * overflow pages are automatically allocated and chained to this page to store all the data. If false, * and the overflow condition would occur, then the PageOverflowIOException is thrown. * @throws IOException * If an disk error occurred. * @throws PageOverflowIOException * If the page data marshalls to size larger than maximum page size and overflow was false. * @throws IllegalStateException * if the PageFile is not loaded */ public <T> void store(Page<T> page, Marshaller<T> marshaller, final boolean overflow) throws IOException { DataByteArrayOutputStream out = (DataByteArrayOutputStream)openOutputStream(page, overflow); if (marshaller != null) { marshaller.writePayload(page.get(), out); } out.close(); } /** * @throws IOException */ public OutputStream openOutputStream(Page page, final boolean overflow) throws IOException { pageFile.assertLoaded(); // Copy to protect against the end user changing // the page instance while we are doing a write. final Page copy = page.copy(); pageFile.addToCache(copy); // // To support writing VERY large data, we override the output stream so // that we // we do the page writes incrementally while the data is being // marshalled. DataByteArrayOutputStream out = new DataByteArrayOutputStream(pageFile.getPageSize() * 2) { Page current = copy; @SuppressWarnings("unchecked") @Override protected void onWrite() throws IOException { // Are we at an overflow condition? final int pageSize = pageFile.getPageSize(); if (pos >= pageSize) { // If overflow is allowed if (overflow) { Page next; if (current.getType() == Page.PAGE_PART_TYPE) { next = load(current.getNext(), null); } else { next = allocate(); } next.txId = current.txId; // Write the page header int oldPos = pos; pos = 0; current.makePagePart(next.getPageId(), getWriteTransactionId()); current.write(this); // Do the page write.. byte[] data = new byte[pageSize]; System.arraycopy(buf, 0, data, 0, pageSize); Transaction.this.write(current, data); // Reset for the next page chunk pos = 0; // The page header marshalled after the data is written. skip(Page.PAGE_HEADER_SIZE); // Move the overflow data after the header. System.arraycopy(buf, pageSize, buf, pos, oldPos - pageSize); pos += oldPos - pageSize; current = next; } else { throw new PageOverflowIOException("Page overflow."); } } } @SuppressWarnings("unchecked") @Override public void close() throws IOException { super.close(); // We need to free up the rest of the page chain.. if (current.getType() == Page.PAGE_PART_TYPE) { free(current.getNext()); } current.makePageEnd(pos, getWriteTransactionId()); // Write the header.. pos = 0; current.write(this); Transaction.this.write(current, buf); } }; // The page header marshaled after the data is written. out.skip(Page.PAGE_HEADER_SIZE); return out; } /** * Loads a page from disk. * * @param pageId * the id of the page to load * @param marshaller * the marshaler to use to load the data portion of the Page, may be null if you do not wish to load the data. * @return The page with the given id * @throws IOException * If an disk error occurred. * @throws IllegalStateException * if the PageFile is not loaded */ public <T> Page<T> load(long pageId, Marshaller<T> marshaller) throws IOException { pageFile.assertLoaded(); Page<T> page = new Page<T>(pageId); load(page, marshaller); return page; } /** * Loads a page from disk. * * @param page - The pageId field must be properly set * @param marshaller * the marshaler to use to load the data portion of the Page, may be null if you do not wish to load the data. * @throws IOException * If an disk error occurred. * @throws InvalidPageIOException * If the page is is not valid. * @throws IllegalStateException * if the PageFile is not loaded */ @SuppressWarnings("unchecked") public <T> void load(Page<T> page, Marshaller<T> marshaller) throws IOException { pageFile.assertLoaded(); // Can't load invalid offsets... long pageId = page.getPageId(); if (pageId < 0) { throw new InvalidPageIOException("Page id is not valid", pageId); } // It might be a page this transaction has modified... PageWrite update = writes.get(pageId); if (update != null) { page.copy(update.getPage()); return; } // We may be able to get it from the cache... Page<T> t = pageFile.getFromCache(pageId); if (t != null) { page.copy(t); return; } if (marshaller != null) { // Full page read.. InputStream is = openInputStream(page); DataInputStream dataIn = new DataInputStream(is); page.set(marshaller.readPayload(dataIn)); is.close(); } else { // Page header read. DataByteArrayInputStream in = new DataByteArrayInputStream(new byte[Page.PAGE_HEADER_SIZE]); pageFile.readPage(pageId, in.getRawData()); page.read(in); page.set(null); } // Cache it. if (marshaller != null) { pageFile.addToCache(page); } } /** * @see org.apache.kahadb.page.Transaction#load(org.apache.kahadb.page.Page, * org.apache.kahadb.util.Marshaller) */ public InputStream openInputStream(final Page p) throws IOException { return new InputStream() { private ByteSequence chunk = new ByteSequence(new byte[pageFile.getPageSize()]); private Page page = readPage(p); private int pageCount = 1; private Page markPage; private ByteSequence markChunk; private Page readPage(Page page) throws IOException { // Read the page data pageFile.readPage(page.getPageId(), chunk.getData()); chunk.setOffset(0); chunk.setLength(pageFile.getPageSize()); DataByteArrayInputStream in = new DataByteArrayInputStream(chunk); page.read(in); chunk.setOffset(Page.PAGE_HEADER_SIZE); if (page.getType() == Page.PAGE_END_TYPE) { chunk.setLength((int)(page.getNext())); } if (page.getType() == Page.PAGE_FREE_TYPE) { throw new EOFException("Chunk stream does not exist, page: " + page.getPageId() + " is marked free"); } return page; } public int read() throws IOException { if (!atEOF()) { return chunk.data[chunk.offset++] & 0xff; } else { return -1; } } private boolean atEOF() throws IOException { if (chunk.offset < chunk.length) { return false; } if (page.getType() == Page.PAGE_END_TYPE) { return true; } fill(); return chunk.offset >= chunk.length; } private void fill() throws IOException { page = readPage(new Page(page.getNext())); pageCount++; } public int read(byte[] b) throws IOException { return read(b, 0, b.length); } public int read(byte b[], int off, int len) throws IOException { if (!atEOF()) { int rc = 0; while (!atEOF() && rc < len) { len = Math.min(len, chunk.length - chunk.offset); if (len > 0) { System.arraycopy(chunk.data, chunk.offset, b, off, len); chunk.offset += len; } rc += len; } return rc; } else { return -1; } } public long skip(long len) throws IOException { if (atEOF()) { int rc = 0; while (!atEOF() && rc < len) { len = Math.min(len, chunk.length - chunk.offset); if (len > 0) { chunk.offset += len; } rc += len; } return rc; } else { return -1; } } public int available() { return chunk.length - chunk.offset; } public boolean markSupported() { return true; } public void mark(int markpos) { markPage = page; byte data[] = new byte[pageFile.getPageSize()]; System.arraycopy(chunk.getData(), 0, data, 0, pageFile.getPageSize()); markChunk = new ByteSequence(data, chunk.getOffset(), chunk.getLength()); } public void reset() { page = markPage; chunk = markChunk; } }; } /** * Allows you to iterate through all active Pages in this object. Pages with type Page.FREE_TYPE are * not included in this iteration. * * Pages removed with Iterator.remove() will not actually get removed until the transaction commits. * * @throws IllegalStateException * if the PageFile is not loaded */ @SuppressWarnings("unchecked") public Iterator<Page> iterator() { return (Iterator<Page>)iterator(false); } /** * Allows you to iterate through all active Pages in this object. You can optionally include free pages in the pages * iterated. * * @param includeFreePages - if true, free pages are included in the iteration * @throws IllegalStateException * if the PageFile is not loaded */ public Iterator<Page> iterator(final boolean includeFreePages) { pageFile.assertLoaded(); return new Iterator<Page>() { long nextId; Page nextPage; Page lastPage; private void findNextPage() { if (!pageFile.isLoaded()) { throw new IllegalStateException("Cannot iterate the pages when the page file is not loaded"); } if (nextPage != null) { return; } try { while (nextId < pageFile.getPageCount()) { Page page = load(nextId, null); if (includeFreePages || page.getType() != Page.PAGE_FREE_TYPE) { nextPage = page; return; } else { nextId++; } } } catch (IOException e) { } } public boolean hasNext() { findNextPage(); return nextPage != null; } public Page next() { findNextPage(); if (nextPage != null) { lastPage = nextPage; nextPage = null; nextId++; return lastPage; } else { throw new NoSuchElementException(); } } @SuppressWarnings("unchecked") public void remove() { if (lastPage == null) { throw new IllegalStateException(); } try { free(lastPage); lastPage = null; } catch (IOException e) { new RuntimeException(e); } } }; } /////////////////////////////////////////////////////////////////// // Commit / Rollback related methods.. /////////////////////////////////////////////////////////////////// /** * Commits the transaction to the PageFile as a single 'Unit of Work'. Either all page updates associated * with the transaction are written to disk or none will. */ public void commit() throws IOException { if( writeTransactionId!=-1 ) { // Actually do the page writes... pageFile.write(writes.entrySet()); // Release the pages that were freed up in the transaction.. freePages(freeList); freeList.clear(); allocateList.clear(); writes.clear(); writeTransactionId = -1; if (tmpFile != null) { tmpFile.close(); if (!getTempFile().delete()) { throw new IOException("Can't delete temporary KahaDB transaction file:" + getTempFile()); } tmpFile = null; txFile = null; } } size = 0; } /** * Rolls back the transaction. */ public void rollback() throws IOException { if( writeTransactionId!=-1 ) { // Release the pages that were allocated in the transaction... freePages(allocateList); freeList.clear(); allocateList.clear(); writes.clear(); writeTransactionId = -1; if (tmpFile != null) { tmpFile.close(); if (getTempFile().delete()) { throw new IOException("Can't delete temporary KahaDB transaction file:" + getTempFile()); } tmpFile = null; txFile = null; } } size = 0; } private long getWriteTransactionId() { if( writeTransactionId==-1 ) { writeTransactionId = pageFile.getNextWriteTransactionId(); } return writeTransactionId; } protected File getTempFile() { if (txFile == null) { txFile = new File(getPageFile().getDirectory(), IOHelper.toFileSystemSafeName("tx-"+ Long.toString(getWriteTransactionId()) + "-" + Long.toString(System.currentTimeMillis()) + ".tmp")); } return txFile; } /** * Queues up a page write that should get done when commit() gets called. */ @SuppressWarnings("unchecked") private void write(final Page page, byte[] data) throws IOException { Long key = page.getPageId(); size += data.length; PageWrite write; if (size > maxTransactionSize) { if (tmpFile == null) { tmpFile = new RandomAccessFile(getTempFile(), "rw"); } int location = nextLocation; tmpFile.seek(nextLocation); tmpFile.write(data); nextLocation = location + data.length; write = new PageWrite(page, location, data.length, getTempFile()); } else { write = new PageWrite(page, data); } writes.put(key, write); } /** * @param list * @throws RuntimeException */ private void freePages(SequenceSet list) throws RuntimeException { Sequence seq = list.getHead(); while( seq!=null ) { seq.each(new Sequence.Closure<RuntimeException>(){ public void execute(long value) { pageFile.freePage(value); } }); seq = seq.getNext(); } } /** * @return true if there are no uncommitted page file updates associated with this transaction. */ public boolean isReadOnly() { return writeTransactionId==-1; } /////////////////////////////////////////////////////////////////// // Transaction closure helpers... /////////////////////////////////////////////////////////////////// /** * Executes a closure and if it does not throw any exceptions, then it commits the transaction. * If the closure throws an Exception, then the transaction is rolled back. * * @param <T> * @param closure - the work to get exectued. * @throws T if the closure throws it * @throws IOException If the commit fails. */ public <T extends Throwable> void execute(Closure<T> closure) throws T, IOException { boolean success = false; try { closure.execute(this); success = true; } finally { if (success) { commit(); } else { rollback(); } } } /** * Executes a closure and if it does not throw any exceptions, then it commits the transaction. * If the closure throws an Exception, then the transaction is rolled back. * * @param <T> * @param closure - the work to get exectued. * @throws T if the closure throws it * @throws IOException If the commit fails. */ public <R, T extends Throwable> R execute(CallableClosure<R, T> closure) throws T, IOException { boolean success = false; try { R rc = closure.execute(this); success = true; return rc; } finally { if (success) { commit(); } else { rollback(); } } } }
kahadb/src/main/java/org/apache/kahadb/page/Transaction.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.kahadb.page; import java.io.*; import java.util.*; import org.apache.kahadb.page.PageFile.PageWrite; import org.apache.kahadb.util.*; /** * The class used to read/update a PageFile object. Using a transaction allows you to * do multiple update operations in a single unit of work. */ public class Transaction implements Iterable<Page> { private RandomAccessFile tmpFile; private File txFile; private int nextLocation = 0; /** * The PageOverflowIOException occurs when a page write is requested * and it's data is larger than what would fit into a single page. */ public class PageOverflowIOException extends IOException { public PageOverflowIOException(String message) { super(message); } } /** * The InvalidPageIOException is thrown if try to load/store a a page * with an invalid page id. */ public class InvalidPageIOException extends IOException { private final long page; public InvalidPageIOException(String message, long page) { super(message); this.page = page; } public long getPage() { return page; } } /** * This closure interface is intended for the end user implement callbacks for the Transaction.exectue() method. * * @param <T> The type of exceptions that operation will throw. */ public interface Closure <T extends Throwable> { public void execute(Transaction tx) throws T; } /** * This closure interface is intended for the end user implement callbacks for the Transaction.exectue() method. * * @param <R> The type of result that the closure produces. * @param <T> The type of exceptions that operation will throw. */ public interface CallableClosure<R, T extends Throwable> { public R execute(Transaction tx) throws T; } // The page file that this Transaction operates against. private final PageFile pageFile; // If this transaction is updating stuff.. this is the tx of private long writeTransactionId=-1; // List of pages that this transaction has modified. private TreeMap<Long, PageWrite> writes=new TreeMap<Long, PageWrite>(); // List of pages allocated in this transaction private final SequenceSet allocateList = new SequenceSet(); // List of pages freed in this transaction private final SequenceSet freeList = new SequenceSet(); private long maxTransactionSize = Integer.parseInt(System.getProperty("maxKahaDBTxSize", "" + 10485760)); private long size = 0; Transaction(PageFile pageFile) { this.pageFile = pageFile; } /** * @return the page file that created this Transaction */ public PageFile getPageFile() { return this.pageFile; } /** * Allocates a free page that you can write data to. * * @return a newly allocated page. * @throws IOException * If an disk error occurred. * @throws IllegalStateException * if the PageFile is not loaded */ public <T> Page<T> allocate() throws IOException { return allocate(1); } /** * Allocates a block of free pages that you can write data to. * * @param count the number of sequential pages to allocate * @return the first page of the sequential set. * @throws IOException * If an disk error occurred. * @throws IllegalStateException * if the PageFile is not loaded */ public <T> Page<T> allocate(int count) throws IOException { // TODO: we need to track allocated pages so that they can be returned if the // transaction gets rolled back. Page<T> rc = pageFile.allocate(count); allocateList.add(new Sequence(rc.getPageId(), rc.getPageId()+count-1)); return rc; } /** * Frees up a previously allocated page so that it can be re-allocated again. * * @param pageId the page to free up * @throws IOException * If an disk error occurred. * @throws IllegalStateException * if the PageFile is not loaded */ public void free(long pageId) throws IOException { free(load(pageId, null)); } /** * Frees up a previously allocated sequence of pages so that it can be re-allocated again. * * @param pageId the initial page of the sequence that will be getting freed * @param count the number of pages in the sequence * * @throws IOException * If an disk error occurred. * @throws IllegalStateException * if the PageFile is not loaded */ public void free(long pageId, int count) throws IOException { free(load(pageId, null), count); } /** * Frees up a previously allocated sequence of pages so that it can be re-allocated again. * * @param page the initial page of the sequence that will be getting freed * @param count the number of pages in the sequence * * @throws IOException * If an disk error occurred. * @throws IllegalStateException * if the PageFile is not loaded */ public <T> void free(Page<T> page, int count) throws IOException { pageFile.assertLoaded(); long offsetPage = page.getPageId(); for (int i = 0; i < count; i++) { if (page == null) { page = load(offsetPage + i, null); } free(page); page = null; } } /** * Frees up a previously allocated page so that it can be re-allocated again. * * @param page the page to free up * @throws IOException * If an disk error occurred. * @throws IllegalStateException * if the PageFile is not loaded */ public <T> void free(Page<T> page) throws IOException { pageFile.assertLoaded(); // We may need loop to free up a page chain. while (page != null) { // Is it already free?? if (page.getType() == Page.PAGE_FREE_TYPE) { return; } Page<T> next = null; if (page.getType() == Page.PAGE_PART_TYPE) { next = load(page.getNext(), null); } page.makeFree(getWriteTransactionId()); // ensure free page is visible while write is pending pageFile.addToCache(page.copy()); DataByteArrayOutputStream out = new DataByteArrayOutputStream(pageFile.getPageSize()); page.write(out); write(page, out.getData()); freeList.add(page.getPageId()); page = next; } } /** * * @param page * the page to write. The Page object must be fully populated with a valid pageId, type, and data. * @param marshaller * the marshaler to use to load the data portion of the Page, may be null if you do not wish to write the data. * @param overflow * If true, then if the page data marshalls to a bigger size than can fit in one page, then additional * overflow pages are automatically allocated and chained to this page to store all the data. If false, * and the overflow condition would occur, then the PageOverflowIOException is thrown. * @throws IOException * If an disk error occurred. * @throws PageOverflowIOException * If the page data marshalls to size larger than maximum page size and overflow was false. * @throws IllegalStateException * if the PageFile is not loaded */ public <T> void store(Page<T> page, Marshaller<T> marshaller, final boolean overflow) throws IOException { DataByteArrayOutputStream out = (DataByteArrayOutputStream)openOutputStream(page, overflow); if (marshaller != null) { marshaller.writePayload(page.get(), out); } out.close(); } /** * @throws IOException */ public OutputStream openOutputStream(Page page, final boolean overflow) throws IOException { pageFile.assertLoaded(); // Copy to protect against the end user changing // the page instance while we are doing a write. final Page copy = page.copy(); pageFile.addToCache(copy); // // To support writing VERY large data, we override the output stream so // that we // we do the page writes incrementally while the data is being // marshalled. DataByteArrayOutputStream out = new DataByteArrayOutputStream(pageFile.getPageSize() * 2) { Page current = copy; @SuppressWarnings("unchecked") @Override protected void onWrite() throws IOException { // Are we at an overflow condition? final int pageSize = pageFile.getPageSize(); if (pos >= pageSize) { // If overflow is allowed if (overflow) { Page next; if (current.getType() == Page.PAGE_PART_TYPE) { next = load(current.getNext(), null); } else { next = allocate(); } next.txId = current.txId; // Write the page header int oldPos = pos; pos = 0; current.makePagePart(next.getPageId(), getWriteTransactionId()); current.write(this); // Do the page write.. byte[] data = new byte[pageSize]; System.arraycopy(buf, 0, data, 0, pageSize); Transaction.this.write(current, data); // Reset for the next page chunk pos = 0; // The page header marshalled after the data is written. skip(Page.PAGE_HEADER_SIZE); // Move the overflow data after the header. System.arraycopy(buf, pageSize, buf, pos, oldPos - pageSize); pos += oldPos - pageSize; current = next; } else { throw new PageOverflowIOException("Page overflow."); } } } @SuppressWarnings("unchecked") @Override public void close() throws IOException { super.close(); // We need to free up the rest of the page chain.. if (current.getType() == Page.PAGE_PART_TYPE) { free(current.getNext()); } current.makePageEnd(pos, getWriteTransactionId()); // Write the header.. pos = 0; current.write(this); Transaction.this.write(current, buf); } }; // The page header marshaled after the data is written. out.skip(Page.PAGE_HEADER_SIZE); return out; } /** * Loads a page from disk. * * @param pageId * the id of the page to load * @param marshaller * the marshaler to use to load the data portion of the Page, may be null if you do not wish to load the data. * @return The page with the given id * @throws IOException * If an disk error occurred. * @throws IllegalStateException * if the PageFile is not loaded */ public <T> Page<T> load(long pageId, Marshaller<T> marshaller) throws IOException { pageFile.assertLoaded(); Page<T> page = new Page<T>(pageId); load(page, marshaller); return page; } /** * Loads a page from disk. * * @param page - The pageId field must be properly set * @param marshaller * the marshaler to use to load the data portion of the Page, may be null if you do not wish to load the data. * @throws IOException * If an disk error occurred. * @throws InvalidPageIOException * If the page is is not valid. * @throws IllegalStateException * if the PageFile is not loaded */ @SuppressWarnings("unchecked") public <T> void load(Page<T> page, Marshaller<T> marshaller) throws IOException { pageFile.assertLoaded(); // Can't load invalid offsets... long pageId = page.getPageId(); if (pageId < 0) { throw new InvalidPageIOException("Page id is not valid", pageId); } // It might be a page this transaction has modified... PageWrite update = writes.get(pageId); if (update != null) { page.copy(update.getPage()); return; } // We may be able to get it from the cache... Page<T> t = pageFile.getFromCache(pageId); if (t != null) { page.copy(t); return; } if (marshaller != null) { // Full page read.. InputStream is = openInputStream(page); DataInputStream dataIn = new DataInputStream(is); page.set(marshaller.readPayload(dataIn)); is.close(); } else { // Page header read. DataByteArrayInputStream in = new DataByteArrayInputStream(new byte[Page.PAGE_HEADER_SIZE]); pageFile.readPage(pageId, in.getRawData()); page.read(in); page.set(null); } // Cache it. if (marshaller != null) { pageFile.addToCache(page); } } /** * @see org.apache.kahadb.page.Transaction#load(org.apache.kahadb.page.Page, * org.apache.kahadb.util.Marshaller) */ public InputStream openInputStream(final Page p) throws IOException { return new InputStream() { private ByteSequence chunk = new ByteSequence(new byte[pageFile.getPageSize()]); private Page page = readPage(p); private int pageCount = 1; private Page markPage; private ByteSequence markChunk; private Page readPage(Page page) throws IOException { // Read the page data pageFile.readPage(page.getPageId(), chunk.getData()); chunk.setOffset(0); chunk.setLength(pageFile.getPageSize()); DataByteArrayInputStream in = new DataByteArrayInputStream(chunk); page.read(in); chunk.setOffset(Page.PAGE_HEADER_SIZE); if (page.getType() == Page.PAGE_END_TYPE) { chunk.setLength((int)(page.getNext())); } if (page.getType() == Page.PAGE_FREE_TYPE) { throw new EOFException("Chunk stream does not exist, page: " + page.getPageId() + " is marked free"); } return page; } public int read() throws IOException { if (!atEOF()) { return chunk.data[chunk.offset++] & 0xff; } else { return -1; } } private boolean atEOF() throws IOException { if (chunk.offset < chunk.length) { return false; } if (page.getType() == Page.PAGE_END_TYPE) { return true; } fill(); return chunk.offset >= chunk.length; } private void fill() throws IOException { page = readPage(new Page(page.getNext())); pageCount++; } public int read(byte[] b) throws IOException { return read(b, 0, b.length); } public int read(byte b[], int off, int len) throws IOException { if (!atEOF()) { int rc = 0; while (!atEOF() && rc < len) { len = Math.min(len, chunk.length - chunk.offset); if (len > 0) { System.arraycopy(chunk.data, chunk.offset, b, off, len); chunk.offset += len; } rc += len; } return rc; } else { return -1; } } public long skip(long len) throws IOException { if (atEOF()) { int rc = 0; while (!atEOF() && rc < len) { len = Math.min(len, chunk.length - chunk.offset); if (len > 0) { chunk.offset += len; } rc += len; } return rc; } else { return -1; } } public int available() { return chunk.length - chunk.offset; } public boolean markSupported() { return true; } public void mark(int markpos) { markPage = page; byte data[] = new byte[pageFile.getPageSize()]; System.arraycopy(chunk.getData(), 0, data, 0, pageFile.getPageSize()); markChunk = new ByteSequence(data, chunk.getOffset(), chunk.getLength()); } public void reset() { page = markPage; chunk = markChunk; } }; } /** * Allows you to iterate through all active Pages in this object. Pages with type Page.FREE_TYPE are * not included in this iteration. * * Pages removed with Iterator.remove() will not actually get removed until the transaction commits. * * @throws IllegalStateException * if the PageFile is not loaded */ @SuppressWarnings("unchecked") public Iterator<Page> iterator() { return (Iterator<Page>)iterator(false); } /** * Allows you to iterate through all active Pages in this object. You can optionally include free pages in the pages * iterated. * * @param includeFreePages - if true, free pages are included in the iteration * @throws IllegalStateException * if the PageFile is not loaded */ public Iterator<Page> iterator(final boolean includeFreePages) { pageFile.assertLoaded(); return new Iterator<Page>() { long nextId; Page nextPage; Page lastPage; private void findNextPage() { if (!pageFile.isLoaded()) { throw new IllegalStateException("Cannot iterate the pages when the page file is not loaded"); } if (nextPage != null) { return; } try { while (nextId < pageFile.getPageCount()) { Page page = load(nextId, null); if (includeFreePages || page.getType() != Page.PAGE_FREE_TYPE) { nextPage = page; return; } else { nextId++; } } } catch (IOException e) { } } public boolean hasNext() { findNextPage(); return nextPage != null; } public Page next() { findNextPage(); if (nextPage != null) { lastPage = nextPage; nextPage = null; nextId++; return lastPage; } else { throw new NoSuchElementException(); } } @SuppressWarnings("unchecked") public void remove() { if (lastPage == null) { throw new IllegalStateException(); } try { free(lastPage); lastPage = null; } catch (IOException e) { new RuntimeException(e); } } }; } /////////////////////////////////////////////////////////////////// // Commit / Rollback related methods.. /////////////////////////////////////////////////////////////////// /** * Commits the transaction to the PageFile as a single 'Unit of Work'. Either all page updates associated * with the transaction are written to disk or none will. */ public void commit() throws IOException { if( writeTransactionId!=-1 ) { // Actually do the page writes... pageFile.write(writes.entrySet()); // Release the pages that were freed up in the transaction.. freePages(freeList); freeList.clear(); allocateList.clear(); writes.clear(); writeTransactionId = -1; if (tmpFile != null) { tmpFile.close(); if (!getTempFile().delete()) { throw new IOException("Can't delete temporary KahaDB transaction file:" + getTempFile()); } tmpFile = null; txFile = null; } } size = 0; } /** * Rolls back the transaction. */ public void rollback() throws IOException { if( writeTransactionId!=-1 ) { // Release the pages that were allocated in the transaction... freePages(allocateList); freeList.clear(); allocateList.clear(); writes.clear(); writeTransactionId = -1; if (tmpFile != null) { tmpFile.close(); if (getTempFile().delete()) { throw new IOException("Can't delete temporary KahaDB transaction file:" + getTempFile()); } tmpFile = null; txFile = null; } } size = 0; } private long getWriteTransactionId() { if( writeTransactionId==-1 ) { writeTransactionId = pageFile.getNextWriteTransactionId(); } return writeTransactionId; } protected File getTempFile() { if (txFile == null) { txFile = new File(getPageFile().getDirectory(), IOHelper.toFileSystemSafeName("tx-"+ Long.toString(getWriteTransactionId()) + "-" + Long.toString(System.currentTimeMillis()) + ".tmp")); } return txFile; } /** * Queues up a page write that should get done when commit() gets called. */ @SuppressWarnings("unchecked") private void write(final Page page, byte[] data) throws IOException { Long key = page.getPageId(); size += data.length; PageWrite write; if (size > maxTransactionSize) { if (tmpFile == null) { tmpFile = new RandomAccessFile(getTempFile(), "rw"); } int location = nextLocation; tmpFile.seek(nextLocation); tmpFile.write(data); nextLocation = location + data.length; write = new PageWrite(page, location, data.length, getTempFile()); } else { write = new PageWrite(page, data); } writes.put(key, write); } /** * @param list * @throws RuntimeException */ private void freePages(SequenceSet list) throws RuntimeException { Sequence seq = list.getHead(); while( seq!=null ) { seq.each(new Sequence.Closure<RuntimeException>(){ public void execute(long value) { pageFile.freePage(value); } }); seq = seq.getNext(); } } /** * @return true if there are no uncommitted page file updates associated with this transaction. */ public boolean isReadOnly() { return writeTransactionId==-1; } /////////////////////////////////////////////////////////////////// // Transaction closure helpers... /////////////////////////////////////////////////////////////////// /** * Executes a closure and if it does not throw any exceptions, then it commits the transaction. * If the closure throws an Exception, then the transaction is rolled back. * * @param <T> * @param closure - the work to get exectued. * @throws T if the closure throws it * @throws IOException If the commit fails. */ public <T extends Throwable> void execute(Closure<T> closure) throws T, IOException { boolean success = false; try { closure.execute(this); success = true; } finally { if (success) { commit(); } else { rollback(); } } } /** * Executes a closure and if it does not throw any exceptions, then it commits the transaction. * If the closure throws an Exception, then the transaction is rolled back. * * @param <T> * @param closure - the work to get exectued. * @throws T if the closure throws it * @throws IOException If the commit fails. */ public <R, T extends Throwable> R execute(CallableClosure<R, T> closure) throws T, IOException { boolean success = false; try { R rc = closure.execute(this); success = true; return rc; } finally { if (success) { commit(); } else { rollback(); } } } }
https://issues.apache.org/jira/browse/AMQ-3374 - long kahadb tx - parse long git-svn-id: d2a93f579bd4835921162e9a69396c846e49961c@1138449 13f79535-47bb-0310-9956-ffa450edef68
kahadb/src/main/java/org/apache/kahadb/page/Transaction.java
https://issues.apache.org/jira/browse/AMQ-3374 - long kahadb tx - parse long
<ide><path>ahadb/src/main/java/org/apache/kahadb/page/Transaction.java <ide> // List of pages freed in this transaction <ide> private final SequenceSet freeList = new SequenceSet(); <ide> <del> private long maxTransactionSize = Integer.parseInt(System.getProperty("maxKahaDBTxSize", "" + 10485760)); <add> private long maxTransactionSize = Long.parseLong(System.getProperty("maxKahaDBTxSize", "" + 10485760)); <ide> <ide> private long size = 0; <ide>
Java
mit
159cea342ffeb039beb0a1b6f4fdec90fe2e5e55
0
roccobarbi/geneticLearner01
/** * */ package geneticLearner01; /** * Engine for the evolution of the best algorithm. * It can be created out of a set of words, a single organism or a set of organisms * * @author WT-Rocco * */ public class EvolutionEngine { // Constants private static final int BEST_SIZE = 3; private static final int POP_SIZE = (int) Math.pow(2, BEST_SIZE) * 2; // Private fields private RuleOrganism winner; private RuleOrganism bestChoices[]; // Not needed if I order the population and take the first ones private RuleOrganism population[]; private boolean isActive; private TrainingItem trainingSet[]; private int filteredAmount; // How many items can be filtered private int trainingSize; // Total size of the training set // Accessors public void setTrainingSet(TrainingItem trainingItems[]){ trainingSize = trainingItems.length; filteredAmount = 0; trainingSet = new TrainingItem[trainingSize]; for(int i = 0; i < trainingSize; i++){ trainingSet[i] = new TrainingItem(trainingItems[i].getText(), trainingItems[i].getIsFiltered()); if(trainingSet[i].getIsFiltered()) filteredAmount++; } } // Default constructor public EvolutionEngine(){ isActive = false; bestChoices = new RuleOrganism[BEST_SIZE]; population = new RuleOrganism[POP_SIZE]; } // Basic constructor: word list public EvolutionEngine(String words[]){ this(); RuleItem basicRules[] = new RuleItem[words.length]; boolean isInclusive = true; boolean isActive = false; for(int i = 0; i < POP_SIZE; i++){ // Organisms are created randomly, favouring inactive and inclusive rules for(int k = 0; k < words.length; k++){ isInclusive = (int)(Math.random() * 3) == 0 ? false : true; isActive = (int)(Math.random() * 4) == 0 ? true : false; basicRules[i] = new RuleItem(words[k], isInclusive, isActive); } population[i] = new RuleOrganism(basicRules); } isActive = true; } // TODO: the other constructors /** * Run the evolution engine and return the best rule * @param target The desired % of filtered messages to be guessed * @param maxGenerations The maximum number of generations to be tested */ public RuleOrganism evolve(int target, int maxGenerations){ RuleOrganism winner = null; // Chech that the engine is active and there's a viable training set if(isActive && trainingSize > 0){ for(int g = 0; g < maxGenerations; g++){ // Test all the rules and assign the fitness scores // Order the set by fitness, in ascending order // The first n are the best of the set, spawn and mutate them } // Pick a winner } return winner; } }
EvolutionEngine.java
/** * */ package geneticLearner01; /** * Engine for the evolution of the best algorithm. * It can be created out of a set of words, a single organism or a set of organisms * * @author WT-Rocco * */ public class EvolutionEngine { // Constants private static final int BEST_SIZE = 3; private static final int POP_SIZE = (int) Math.pow(2, BEST_SIZE) * 2; // Private fields private RuleOrganism winner; private RuleOrganism bestChoices[]; // Not needed if I order the population and take the first ones private RuleOrganism population[]; private boolean isActive; // Default constructor public EvolutionEngine(){ isActive = false; bestChoices = new RuleOrganism[BEST_SIZE]; population = new RuleOrganism[POP_SIZE]; } // Basic constructor: word list public EvolutionEngine(String words[]){ this(); RuleItem basicRules[] = new RuleItem[words.length]; boolean isInclusive = true; boolean isActive = false; for(int i = 0; i < POP_SIZE; i++){ // Organisms are created randomly, favouring inactive and inclusive rules for(int k = 0; k < words.length; k++){ isInclusive = (int)(Math.random() * 3) == 0 ? false : true; isActive = (int)(Math.random() * 4) == 0 ? true : false; basicRules[i] = new RuleItem(words[k], isInclusive, isActive); } population[i] = new RuleOrganism(basicRules); } isActive = true; } // TODO: the other constructors /** * Run the evolution engine and return the best rule */ public RuleOrganism evolve(){ RuleOrganism winner = null; // Chech that the engine is active // Run the tests // Return the winner return winner; } }
trainingSet added and evolution logic schema
EvolutionEngine.java
trainingSet added and evolution logic schema
<ide><path>volutionEngine.java <ide> */ <ide> <ide> public class EvolutionEngine { <add> <ide> // Constants <ide> private static final int BEST_SIZE = 3; <ide> private static final int POP_SIZE = (int) Math.pow(2, BEST_SIZE) * 2; <ide> private RuleOrganism bestChoices[]; // Not needed if I order the population and take the first ones <ide> private RuleOrganism population[]; <ide> private boolean isActive; <add> <add> private TrainingItem trainingSet[]; <add> private int filteredAmount; // How many items can be filtered <add> private int trainingSize; // Total size of the training set <add> <add> // Accessors <add> public void setTrainingSet(TrainingItem trainingItems[]){ <add> trainingSize = trainingItems.length; <add> filteredAmount = 0; <add> trainingSet = new TrainingItem[trainingSize]; <add> for(int i = 0; i < trainingSize; i++){ <add> trainingSet[i] = new TrainingItem(trainingItems[i].getText(), trainingItems[i].getIsFiltered()); <add> if(trainingSet[i].getIsFiltered()) <add> filteredAmount++; <add> } <add> } <ide> <ide> // Default constructor <ide> public EvolutionEngine(){ <ide> <ide> /** <ide> * Run the evolution engine and return the best rule <add> * @param target The desired % of filtered messages to be guessed <add> * @param maxGenerations The maximum number of generations to be tested <ide> */ <del> public RuleOrganism evolve(){ <add> public RuleOrganism evolve(int target, int maxGenerations){ <ide> RuleOrganism winner = null; <del> // Chech that the engine is active <del> // Run the tests <del> // Return the winner <add> // Chech that the engine is active and there's a viable training set <add> if(isActive && trainingSize > 0){ <add> for(int g = 0; g < maxGenerations; g++){ <add> // Test all the rules and assign the fitness scores <add> // Order the set by fitness, in ascending order <add> // The first n are the best of the set, spawn and mutate them <add> } <add> // Pick a winner <add> } <ide> return winner; <ide> } <ide> }
Java
mit
3a1ed696f8fd72252f910acc6c745fa5c7233e41
0
hgl888/AndroidSliderPreference,olivergeith/android_BasicsPreference,jayschwa/AndroidSliderPreference
/* * Copyright 2012 Jay Weisskopf * * Licensed under the MIT License (see LICENSE.txt) */ package net.jayschwa.android.preference; import android.content.Context; import android.content.res.TypedArray; import android.preference.DialogPreference; import android.util.AttributeSet; import android.view.View; import android.widget.SeekBar; /** * @author Jay Weisskopf */ public class SliderPreference extends DialogPreference { protected final static float DEFAULT_VALUE = 0.5f; protected final static int SEEKBAR_RESOLUTION = 10000; protected float mValue = DEFAULT_VALUE; protected int mSeekBarValue; protected CharSequence[] mSummaries; /** * @param context * @param attrs */ public SliderPreference(Context context, AttributeSet attrs) { super(context, attrs); setup(context, attrs); } /** * @param context * @param attrs * @param defStyle */ public SliderPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setup(context, attrs); } private void setup(Context context, AttributeSet attrs) { setDialogLayoutResource(R.layout.slider_preference_dialog); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SliderPreference); try { setSummary(a.getTextArray(R.styleable.SliderPreference_android_summary)); } catch (Exception e) { // Do nothing } a.recycle(); } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return a.getFloat(index, DEFAULT_VALUE); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { setValue(restoreValue ? getPersistedFloat(mValue) : (Float) defaultValue); } @Override public CharSequence getSummary() { if (mSummaries != null && mSummaries.length > 0) { int index = (int) (mValue * mSummaries.length); index = Math.min(index, mSummaries.length - 1); return mSummaries[index]; } else { return super.getSummary(); } } public void setSummary(CharSequence[] summaries) { mSummaries = summaries; } @Override public void setSummary(CharSequence summary) { super.setSummary(summary); mSummaries = null; } @Override public void setSummary(int summaryResId) { try { setSummary(getContext().getResources().getStringArray(summaryResId)); } catch (Exception e) { super.setSummary(summaryResId); } } public float getValue() { return mValue; } public void setValue(float value) { value = Math.max(0, Math.min(value, 1)); // clamp to [0, 1] if (shouldPersist()) { persistFloat(value); } if (value != mValue) { mValue = value; notifyChanged(); } } @Override protected View onCreateDialogView() { mSeekBarValue = (int) (mValue * SEEKBAR_RESOLUTION); View view = super.onCreateDialogView(); SeekBar seekbar = (SeekBar) view.findViewById(R.id.slider_preference_seekbar); seekbar.setMax(SEEKBAR_RESOLUTION); seekbar.setProgress(mSeekBarValue); seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { SliderPreference.this.mSeekBarValue = progress; } } }); return view; } @Override protected void onDialogClosed(boolean positiveResult) { final float newValue = (float) mSeekBarValue / SEEKBAR_RESOLUTION; if (positiveResult && callChangeListener(newValue)) { setValue(newValue); } super.onDialogClosed(positiveResult); } // TODO: Save and restore preference state. }
src/net/jayschwa/android/preference/SliderPreference.java
/* * Copyright 2012 Jay Weisskopf * * Licensed under the MIT License (see LICENSE.txt) */ package net.jayschwa.android.preference; import android.content.Context; import android.content.res.TypedArray; import android.preference.DialogPreference; import android.util.AttributeSet; import android.view.View; import android.widget.SeekBar; /** * @author Jay Weisskopf */ public class SliderPreference extends DialogPreference { protected final static float DEFAULT_VALUE = 0.5f; protected final static int SEEKBAR_RESOLUTION = 10000; protected float mValue = DEFAULT_VALUE; protected int mSeekBarValue; protected CharSequence[] mSummaries; /** * @param context * @param attrs */ public SliderPreference(Context context, AttributeSet attrs) { super(context, attrs); setup(context, attrs); } /** * @param context * @param attrs * @param defStyle */ public SliderPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setup(context, attrs); } private void setup(Context context, AttributeSet attrs) { setDialogLayoutResource(R.layout.slider_preference_dialog); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SliderPreference); try { setSummary(a.getTextArray(R.styleable.SliderPreference_android_summary)); } catch (Exception e) { // Do nothing } a.recycle(); } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return a.getFloat(index, DEFAULT_VALUE); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { setValue(restoreValue ? getPersistedFloat(mValue) : (Float) defaultValue); } @Override public CharSequence getSummary() { if (mSummaries != null && mSummaries.length > 0) { int index = (int) (mValue * mSummaries.length); index = Math.min(index, mSummaries.length - 1); return mSummaries[index]; } else { return super.getSummary(); } } public void setSummary(CharSequence[] summaries) { mSummaries = summaries; } @Override public void setSummary(CharSequence summary) { super.setSummary(summary); mSummaries = null; } @Override public void setSummary(int summaryResId) { try { setSummary(getContext().getResources().getStringArray(summaryResId)); } catch (Exception e) { super.setSummary(summaryResId); } } public float getValue() { return mValue; } public void setValue(float value) { value = Math.max(0, Math.min(value, 1)); // clamp to [0, 1] if (shouldPersist()) { persistFloat(value); } if (value != mValue) { mValue = value; notifyChanged(); } } protected void setSeekBarValue(int value) { mSeekBarValue = value; } @Override protected View onCreateDialogView() { mSeekBarValue = (int) (mValue * SEEKBAR_RESOLUTION); View view = super.onCreateDialogView(); SeekBar seekbar = (SeekBar) view.findViewById(R.id.slider_preference_seekbar); seekbar.setMax(SEEKBAR_RESOLUTION); seekbar.setProgress(mSeekBarValue); seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { SliderPreference.this.setSeekBarValue(progress); } } }); return view; } @Override protected void onDialogClosed(boolean positiveResult) { final float newValue = (float) mSeekBarValue / SEEKBAR_RESOLUTION; if (positiveResult && callChangeListener(newValue)) { setValue(newValue); } super.onDialogClosed(positiveResult); } // TODO: Save and restore preference state. }
Remove method and access variable directly
src/net/jayschwa/android/preference/SliderPreference.java
Remove method and access variable directly
<ide><path>rc/net/jayschwa/android/preference/SliderPreference.java <ide> } <ide> } <ide> <del> protected void setSeekBarValue(int value) { <del> mSeekBarValue = value; <del> } <del> <ide> @Override <ide> protected View onCreateDialogView() { <ide> mSeekBarValue = (int) (mValue * SEEKBAR_RESOLUTION); <ide> @Override <ide> public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { <ide> if (fromUser) { <del> SliderPreference.this.setSeekBarValue(progress); <add> SliderPreference.this.mSeekBarValue = progress; <ide> } <ide> } <ide> });
JavaScript
mit
07522d71eeb9dd505ded32149d38868f7cecbea1
0
fabienvauchelles/scrapoxy,fabienvauchelles/scrapoxy,fabienvauchelles/scrapoxy
'use strict'; module.exports = { proxy: { port: 8888, statsSamplingDelay: 1000, }, commander: { port: 8889, }, instance: { checkDelay: 10 * 1000, // 10sec checkAliveDelay: 20 * 1000, // 20sec stopIfCrashedDelay: 2 * 60 * 1000, // 120sec, autoRestartDelay: 60 * 60 * 1000, // 1h, aliveMax: 10, autorestart: { minDelay: 1 * 60 * 60 * 1000, // 1h maxDelay: 12 * 60 * 60 * 1000, // 12h }, scaling: { downscaleDelay: 10 * 60 * 1000, // 10min }, }, test: { //mirror: 'http://91.121.178.196:13337', }, };
server/config.defaults.js
'use strict'; module.exports = { proxy: { port: 8888, statsSamplingDelay: 1000, }, commander: { port: 8889, }, instance: { checkDelay: 10 * 1000, // 10sec checkAliveDelay: 20 * 1000, // 20sec stopIfCrashedDelay: 2 * 60 * 1000, // 120sec, autoRestartDelay: 60 * 60 * 1000, // 1h, aliveMax: 2, autorestart: { minDelay: 1 * 60 * 60 * 1000, // 1h maxDelay: 12 * 60 * 60 * 1000, // 12h }, scaling: { downscaleDelay: 10 * 60 * 1000, // 10min }, }, test: { //mirror: 'http://91.121.178.196:13337', }, };
chore(aliveMax): change ping retry to 10
server/config.defaults.js
chore(aliveMax): change ping retry to 10
<ide><path>erver/config.defaults.js <ide> checkAliveDelay: 20 * 1000, // 20sec <ide> stopIfCrashedDelay: 2 * 60 * 1000, // 120sec, <ide> autoRestartDelay: 60 * 60 * 1000, // 1h, <del> aliveMax: 2, <add> aliveMax: 10, <ide> <ide> autorestart: { <ide> minDelay: 1 * 60 * 60 * 1000, // 1h
Java
apache-2.0
ed2f1e7382da732623c9674be030e8eca97ff400
0
marcrh/gwt-material,GwtMaterialDesign/gwt-material,GwtMaterialDesign/gwt-material,guibertjulien/gwt-material,marcrh/gwt-material,marcrh/gwt-material,GwtMaterialDesign/gwt-material,guibertjulien/gwt-material,guibertjulien/gwt-material
/* * #%L * GwtMaterial * %% * Copyright (C) 2015 - 2016 GwtMaterialDesign * %% * 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. * #L% */ package gwt.material.design.client.ui; import com.google.gwt.core.client.JsDate; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.ScriptInjector; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.logical.shared.*; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.DOM; import gwt.material.design.client.base.*; import gwt.material.design.client.base.mixin.CssNameMixin; import gwt.material.design.client.base.mixin.ErrorMixin; import gwt.material.design.client.base.mixin.ReadOnlyMixin; import gwt.material.design.client.constants.*; import gwt.material.design.client.js.JsDatePickerOptions; import gwt.material.design.client.ui.html.DateInput; import gwt.material.design.client.ui.html.Label; import java.util.Date; import static gwt.material.design.client.js.JsMaterialElement.$; //@formatter:off /** * Material Date Picker will provide a visual calendar to your apps. * <p/> * <h3>UiBinder Usage:</h3> * {@code * <m:MaterialDatePicker ui:field="datePicker"> * } * <h3>Java Usage:</h3> * {@code * datePicker.setDate(new Date()); * } * * @author kevzlou7979 * @author Ben Dol * @see <a href="http://gwtmaterialdesign.github.io/gwt-material-demo/#!pickers">Material Date Picker</a> */ //@formatter:on public class MaterialDatePicker extends AbstractValueWidget<Date> implements HasOrientation, HasPlaceholder, HasOpenHandlers<MaterialDatePicker>, HasCloseHandlers<MaterialDatePicker>, HasIcon, HasReadOnly { /** * Enum for identifying various selection types for the picker. */ public enum MaterialDatePickerType { DAY, MONTH_DAY, YEAR_MONTH_DAY, YEAR } private String placeholder; private Date date; private Date dateMin; private Date dateMax; private Date dateTemp; private String format = "dd mmmm yyyy"; private DateInput dateInput; private Label label = new Label(); private MaterialLabel lblPlaceholder = new MaterialLabel(); private Element pickatizedDateInput; private MaterialLabel lblError = new MaterialLabel(); private DatePickerLanguage language; private JsDatePickerOptions options; private MaterialDatePickerType selectionType = MaterialDatePickerType.DAY; private boolean initialized = false; private boolean autoClose = false; private HandlerRegistration autoCloseHandler; private MaterialIcon icon = new MaterialIcon(); private ErrorMixin<AbstractValueWidget, MaterialLabel> errorMixin = new ErrorMixin<>(this, lblError, dateInput, lblPlaceholder); private ReadOnlyMixin<MaterialDatePicker, DateInput> readOnlyMixin; private CssNameMixin<MaterialDatePicker, Orientation> orientationMixin = new CssNameMixin<>(this); public MaterialDatePicker() { super(Document.get().createDivElement(), CssName.INPUT_FIELD); dateInput = new DateInput(); add(dateInput); label.add(lblPlaceholder); add(label); add(lblError); } public MaterialDatePicker(String placeholder) { this(); setPlaceholder(placeholder); } public MaterialDatePicker(String placeholder, Date value) { this(placeholder); setDate(value); } public MaterialDatePicker(String placeholder, Date value, MaterialDatePickerType selectionType) { this(placeholder, value); setSelectionType(selectionType); } @Override public void onLoad() { super.onLoad(); if(!initialized) { initialize(); } } @Override public void onUnload() { super.onUnload(); dateTemp = getValue(); if (autoCloseHandler != null) { autoCloseHandler.removeHandler(); } } protected void initialize() { if(options == null) { options = new JsDatePickerOptions(); } options.container = "body"; options.format = getFormat(); switch (getSelectionType()) { case MONTH_DAY: options.selectMonths = true; break; case YEAR_MONTH_DAY: options.selectYears = true; options.selectMonths = true; break; case YEAR: options.selectYears = true; break; } pickatizedDateInput = $(dateInput.getElement()).pickadate(options).asElement(); label.getElement().setAttribute("for", getPickerId()); if(options.open == null) { options.open = this::onOpen; } if(options.close == null) { options.close = () -> { onClose(); $(pickatizedDateInput).blur(); }; } if(options.set == null) { options.set = thing -> { if (thing.hasOwnProperty("clear")) { clear(); } else if (thing.hasOwnProperty("select")) { select(); } }; } $(pickatizedDateInput).pickadate("picker") .off(options) .on(options); initialized = true; // Set up date specific settings. // These values require initialization. setDate(date); setDateMin(dateMin); setDateMax(dateMax); } /** * Reinitialize the datepicker. */ public void reinitialize() { Scheduler.get().scheduleDeferred(() -> { initialize(); if (pickatizedDateInput != null && dateTemp != null) { $(pickatizedDateInput).pickadate("picker").set("select", dateTemp, () -> { DOM.createFieldSet().setPropertyObject("muted", true); }); } }); } @Override public void clear() { clearErrorOrSuccess(); label.removeStyleName(CssName.ACTIVE); dateInput.removeStyleName(CssName.VALID); dateInput.clear(); } /** * Sets the type of selection options (date, month, year,...). * * @param type if <code>null</code>, {@link MaterialDatePickerType#DAY} will be used as fallback. */ public void setDateSelectionType(MaterialDatePickerType type) { if (type != null) { this.selectionType = type; } } protected void onClose() { CloseEvent.fire(this, this); fireEvent(new BlurEvent(){}); } protected void onOpen() { label.addStyleName(CssName.ACTIVE); dateInput.setFocus(true); OpenEvent.fire(this, this); fireEvent(new FocusEvent(){}); } /** * Programmatically close the date picker component */ public void close() { Scheduler.get().scheduleDeferred(() -> { $(pickatizedDateInput).pickadate("picker").close(); }); } /** * Programmatically open the date picker component */ public void open() { Scheduler.get().scheduleDeferred(() -> { $(pickatizedDateInput).pickadate("picker").open(); }); } protected void select() { label.addStyleName(CssName.ACTIVE); dateInput.addStyleName(CssName.VALID); // Ensure the value change event is // triggered on selecting a date. ValueChangeEvent.fire(this, getValue()); } public String getPickerId() { return $(pickatizedDateInput).pickadate("picker").get("id").toString(); } /** * Sets the current date of the picker. * * @param date - must not be <code>null</code> */ public void setDate(Date date) { setValue(date); } /** * Get the minimum date limit. */ public Date getDateMin() { return dateMin; } /** * Set the minimum date limit. */ public void setDateMin(Date dateMin) { this.dateMin = dateMin; if (initialized && dateMin != null) { $(pickatizedDateInput).pickadate("picker").set("min", JsDate.create((double) dateMin.getTime())); } } /** * Get the maximum date limit. */ public Date getDateMax() { return dateMax; } /** * Set the maximum date limit. */ public void setDateMax(Date dateMax) { this.dateMax = dateMax; if (initialized && dateMax != null) { $(pickatizedDateInput).pickadate("picker").set("max", JsDate.create((double) dateMax.getTime())); } } /** * Set the pickers date. */ public void setPickerDate(JsDate date, Element picker) { $(picker).pickadate("picker").set("select", date, () -> { DOM.createFieldSet().setPropertyObject("muted", true); }); } /** * Get the pickers date. */ protected Date getPickerDate() { try { JsDate pickerDate = $(pickatizedDateInput).pickadate("picker").get("select").obj; return new Date((long) pickerDate.getTime()); } catch (Exception e) { e.printStackTrace(); return null; } } public Date getDate() { return getPickerDate(); } /** * Clears the values of the picker field. */ public void clearValues() { if (pickatizedDateInput != null) { clearValues(pickatizedDateInput); } } public void clearValues(Element picker) { $(picker).pickadate("picker").clear(); } @Override public String getPlaceholder() { return placeholder; } @Override public void setPlaceholder(String placeholder) { this.placeholder = placeholder; if (placeholder != null) { lblPlaceholder.setText(placeholder); } } /** * Get the pickers selection type. */ public MaterialDatePickerType getSelectionType() { return selectionType; } /** * Set the pickers selection type. */ public void setSelectionType(MaterialDatePickerType selectionType) { this.selectionType = selectionType; } /** * @return the orientation */ @Override public Orientation getOrientation() { return orientationMixin.getCssName(); } /** * @param orientation the orientation to set : can be Vertical or Horizontal */ @Override public void setOrientation(Orientation orientation) { orientationMixin.setCssName(orientation); } @Override public void setError(String error) { super.setError(error); dateInput.addStyleName(CssName.INVALID); dateInput.removeStyleName(CssName.VALID); } @Override public void setSuccess(String success) { super.setSuccess(success); dateInput.addStyleName(CssName.VALID); dateInput.removeStyleName(CssName.INVALID); } @Override public void clearErrorOrSuccess() { super.clearErrorOrSuccess(); dateInput.removeStyleName(CssName.VALID); dateInput.removeStyleName(CssName.INVALID); } public String getFormat() { return format; } /** * To call before initialization. */ public void setFormat(String format) { this.format = format; } @Override public Date getValue() { return getPickerDate(); } @Override public void setValue(Date value, boolean fireEvents) { if (value == null) { return; } this.date = value; if (initialized) { setPickerDate(JsDate.create((double) value.getTime()), pickatizedDateInput); label.addStyleName(CssName.ACTIVE); } super.setValue(value, fireEvents); } @Override public HandlerRegistration addCloseHandler(final CloseHandler<MaterialDatePicker> handler) { return addHandler(handler, CloseEvent.getType()); } @Override public HandlerRegistration addOpenHandler(final OpenHandler<MaterialDatePicker> handler) { return addHandler(handler, OpenEvent.getType()); } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); dateInput.setEnabled(enabled); } public DatePickerLanguage getLanguage() { return language; } public void setLanguage(DatePickerLanguage language) { this.language = language; if (language.getJs() != null) { ScriptInjector.fromString(language.getJs().getText()).setWindow(ScriptInjector.TOP_WINDOW).inject(); } stop(); reinitialize(); } /** * Stop the datepicker instance. */ public void stop() { $(pickatizedDateInput).pickadate("picker").stop(); } protected void start() { $(pickatizedDateInput).pickadate("picker").start(); } @Override public MaterialIcon getIcon() { return icon; } @Override public void setIconType(IconType iconType) { icon.setIconType(iconType); icon.setIconPrefix(true); lblError.setPaddingLeft(44); insert(icon, 0); } @Override public void setIconPosition(IconPosition position) { icon.setIconPosition(position); } @Override public void setIconSize(IconSize size) { icon.setIconSize(size); } @Override public void setIconFontSize(double size, Style.Unit unit) { icon.setIconFontSize(size, unit); } @Override public void setIconColor(Color iconColor) { icon.setIconColor(iconColor); } @Override public void setIconPrefix(boolean prefix) { icon.setIconPrefix(prefix); } @Override public boolean isIconPrefix() { return icon.isIconPrefix(); } @Override protected ErrorMixin<AbstractValueWidget, MaterialLabel> getErrorMixin() { return errorMixin; } public ReadOnlyMixin<MaterialDatePicker, DateInput> getReadOnlyMixin() { if (readOnlyMixin == null) { readOnlyMixin = new ReadOnlyMixin<>(this, dateInput); } return readOnlyMixin; } @Override public void setReadOnly(boolean value) { getReadOnlyMixin().setReadOnly(value); } @Override public boolean isReadOnly() { return getReadOnlyMixin().isReadOnly(); } @Override public void setToggleReadOnly(boolean toggle) { getReadOnlyMixin().setToggleReadOnly(toggle); } @Override public boolean isToggleReadOnly() { return getReadOnlyMixin().isToggleReadOnly(); } public DateInput getDateInput() { return dateInput; } public boolean isAutoClose() { return autoClose; } /** * Provide a feature to autoClose the picker when picking value */ public void setAutoClose(boolean autoClose) { this.autoClose = autoClose; if (isAutoClose()) { autoCloseHandler = addValueChangeHandler(valueChangeEvent -> { close(); }); } else { autoCloseHandler.removeHandler(); } } }
gwt-material/src/main/java/gwt/material/design/client/ui/MaterialDatePicker.java
/* * #%L * GwtMaterial * %% * Copyright (C) 2015 - 2016 GwtMaterialDesign * %% * 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. * #L% */ package gwt.material.design.client.ui; import com.google.gwt.core.client.JsDate; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.ScriptInjector; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.logical.shared.*; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.DOM; import gwt.material.design.client.base.*; import gwt.material.design.client.base.mixin.CssNameMixin; import gwt.material.design.client.base.mixin.ErrorMixin; import gwt.material.design.client.base.mixin.ReadOnlyMixin; import gwt.material.design.client.constants.*; import gwt.material.design.client.js.JsDatePickerOptions; import gwt.material.design.client.ui.html.DateInput; import gwt.material.design.client.ui.html.Label; import java.util.Date; import static gwt.material.design.client.js.JsMaterialElement.$; //@formatter:off /** * Material Date Picker will provide a visual calendar to your apps. * <p/> * <h3>UiBinder Usage:</h3> * {@code * <m:MaterialDatePicker ui:field="datePicker"> * } * <h3>Java Usage:</h3> * {@code * datePicker.setDate(new Date()); * } * * @author kevzlou7979 * @author Ben Dol * @see <a href="http://gwtmaterialdesign.github.io/gwt-material-demo/#!pickers">Material Date Picker</a> */ //@formatter:on public class MaterialDatePicker extends AbstractValueWidget<Date> implements HasOrientation, HasPlaceholder, HasOpenHandlers<MaterialDatePicker>, HasCloseHandlers<MaterialDatePicker>, HasIcon, HasReadOnly { /** * Enum for identifying various selection types for the picker. */ public enum MaterialDatePickerType { DAY, MONTH_DAY, YEAR_MONTH_DAY, YEAR } private String placeholder; private Date date; private Date dateMin; private Date dateMax; private Date dateTemp; private String format = "dd mmmm yyyy"; private DateInput dateInput; private Label label = new Label(); private MaterialLabel lblPlaceholder = new MaterialLabel(); private Element pickatizedDateInput; private MaterialLabel lblError = new MaterialLabel(); private DatePickerLanguage language; private JsDatePickerOptions options; private MaterialDatePickerType selectionType = MaterialDatePickerType.DAY; private boolean initialized = false; private boolean autoClose = false; private HandlerRegistration autoCloseHandler; private MaterialIcon icon = new MaterialIcon(); private ErrorMixin<AbstractValueWidget, MaterialLabel> errorMixin = new ErrorMixin<>(this, lblError, dateInput, lblPlaceholder); private ReadOnlyMixin<MaterialDatePicker, DateInput> readOnlyMixin; private CssNameMixin<MaterialDatePicker, Orientation> orientationMixin = new CssNameMixin<>(this); public MaterialDatePicker() { super(Document.get().createDivElement(), CssName.INPUT_FIELD); dateInput = new DateInput(); add(dateInput); label.add(lblPlaceholder); add(label); add(lblError); } public MaterialDatePicker(String placeholder) { this(); setPlaceholder(placeholder); } public MaterialDatePicker(String placeholder, Date value) { this(placeholder); setDate(value); } public MaterialDatePicker(String placeholder, Date value, MaterialDatePickerType selectionType) { this(placeholder, value); setSelectionType(selectionType); } @Override public void onLoad() { super.onLoad(); if(!initialized) { initialize(); } } @Override public void onUnload() { super.onUnload(); dateTemp = getValue(); if (autoCloseHandler != null) { autoCloseHandler.removeHandler(); } } protected void initialize() { if(options == null) { options = new JsDatePickerOptions(); } options.container = "body"; options.format = getFormat(); switch (getSelectionType()) { case MONTH_DAY: options.selectMonths = true; break; case YEAR_MONTH_DAY: options.selectYears = true; options.selectMonths = true; break; case YEAR: options.selectYears = true; break; } pickatizedDateInput = $(dateInput.getElement()).pickadate(options).asElement(); label.getElement().setAttribute("for", getPickerId()); if(options.open == null) { options.open = this::onOpen; } if(options.close == null) { options.close = () -> { onClose(); $(pickatizedDateInput).blur(); }; } if(options.set == null) { options.set = thing -> { if (thing.hasOwnProperty("clear")) { clear(); } else if (thing.hasOwnProperty("select")) { select(); } }; } $(pickatizedDateInput).pickadate("picker") .off(options) .on(options); // Provide a feature to autoClose the picker when picking value if (isAutoClose()) { autoCloseHandler = addValueChangeHandler(valueChangeEvent -> { close(); }); } initialized = true; // Set up date specific settings. // These values require initialization. setDate(date); setDateMin(dateMin); setDateMax(dateMax); } /** * Reinitialize the datepicker. */ public void reinitialize() { Scheduler.get().scheduleDeferred(() -> { initialize(); if (pickatizedDateInput != null && dateTemp != null) { $(pickatizedDateInput).pickadate("picker").set("select", dateTemp, () -> { DOM.createFieldSet().setPropertyObject("muted", true); }); } }); } @Override public void clear() { clearErrorOrSuccess(); label.removeStyleName(CssName.ACTIVE); dateInput.removeStyleName(CssName.VALID); dateInput.clear(); } /** * Sets the type of selection options (date, month, year,...). * * @param type if <code>null</code>, {@link MaterialDatePickerType#DAY} will be used as fallback. */ public void setDateSelectionType(MaterialDatePickerType type) { if (type != null) { this.selectionType = type; } } protected void onClose() { CloseEvent.fire(this, this); fireEvent(new BlurEvent(){}); } protected void onOpen() { label.addStyleName(CssName.ACTIVE); dateInput.setFocus(true); OpenEvent.fire(this, this); fireEvent(new FocusEvent(){}); } /** * Programmatically close the date picker component */ public void close() { Scheduler.get().scheduleDeferred(() -> { $(pickatizedDateInput).pickadate("picker").close(); }); } /** * Programmatically open the date picker component */ public void open() { Scheduler.get().scheduleDeferred(() -> { $(pickatizedDateInput).pickadate("picker").open(); }); } protected void select() { label.addStyleName(CssName.ACTIVE); dateInput.addStyleName(CssName.VALID); // Ensure the value change event is // triggered on selecting a date. ValueChangeEvent.fire(this, getValue()); } public String getPickerId() { return $(pickatizedDateInput).pickadate("picker").get("id").toString(); } /** * Sets the current date of the picker. * * @param date - must not be <code>null</code> */ public void setDate(Date date) { setValue(date); } /** * Get the minimum date limit. */ public Date getDateMin() { return dateMin; } /** * Set the minimum date limit. */ public void setDateMin(Date dateMin) { this.dateMin = dateMin; if (initialized && dateMin != null) { $(pickatizedDateInput).pickadate("picker").set("min", JsDate.create((double) dateMin.getTime())); } } /** * Get the maximum date limit. */ public Date getDateMax() { return dateMax; } /** * Set the maximum date limit. */ public void setDateMax(Date dateMax) { this.dateMax = dateMax; if (initialized && dateMax != null) { $(pickatizedDateInput).pickadate("picker").set("max", JsDate.create((double) dateMax.getTime())); } } /** * Set the pickers date. */ public void setPickerDate(JsDate date, Element picker) { $(picker).pickadate("picker").set("select", date, () -> { DOM.createFieldSet().setPropertyObject("muted", true); }); } /** * Get the pickers date. */ protected Date getPickerDate() { try { JsDate pickerDate = $(pickatizedDateInput).pickadate("picker").get("select").obj; return new Date((long) pickerDate.getTime()); } catch (Exception e) { e.printStackTrace(); return null; } } public Date getDate() { return getPickerDate(); } /** * Clears the values of the picker field. */ public void clearValues() { if (pickatizedDateInput != null) { clearValues(pickatizedDateInput); } } public void clearValues(Element picker) { $(picker).pickadate("picker").clear(); } @Override public String getPlaceholder() { return placeholder; } @Override public void setPlaceholder(String placeholder) { this.placeholder = placeholder; if (placeholder != null) { lblPlaceholder.setText(placeholder); } } /** * Get the pickers selection type. */ public MaterialDatePickerType getSelectionType() { return selectionType; } /** * Set the pickers selection type. */ public void setSelectionType(MaterialDatePickerType selectionType) { this.selectionType = selectionType; } /** * @return the orientation */ @Override public Orientation getOrientation() { return orientationMixin.getCssName(); } /** * @param orientation the orientation to set : can be Vertical or Horizontal */ @Override public void setOrientation(Orientation orientation) { orientationMixin.setCssName(orientation); } @Override public void setError(String error) { super.setError(error); dateInput.addStyleName(CssName.INVALID); dateInput.removeStyleName(CssName.VALID); } @Override public void setSuccess(String success) { super.setSuccess(success); dateInput.addStyleName(CssName.VALID); dateInput.removeStyleName(CssName.INVALID); } @Override public void clearErrorOrSuccess() { super.clearErrorOrSuccess(); dateInput.removeStyleName(CssName.VALID); dateInput.removeStyleName(CssName.INVALID); } public String getFormat() { return format; } /** * To call before initialization. */ public void setFormat(String format) { this.format = format; } @Override public Date getValue() { return getPickerDate(); } @Override public void setValue(Date value, boolean fireEvents) { if (value == null) { return; } this.date = value; if (initialized) { setPickerDate(JsDate.create((double) value.getTime()), pickatizedDateInput); label.addStyleName(CssName.ACTIVE); } super.setValue(value, fireEvents); } @Override public HandlerRegistration addCloseHandler(final CloseHandler<MaterialDatePicker> handler) { return addHandler(handler, CloseEvent.getType()); } @Override public HandlerRegistration addOpenHandler(final OpenHandler<MaterialDatePicker> handler) { return addHandler(handler, OpenEvent.getType()); } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); dateInput.setEnabled(enabled); } public DatePickerLanguage getLanguage() { return language; } public void setLanguage(DatePickerLanguage language) { this.language = language; if (language.getJs() != null) { ScriptInjector.fromString(language.getJs().getText()).setWindow(ScriptInjector.TOP_WINDOW).inject(); } stop(); reinitialize(); } /** * Stop the datepicker instance. */ public void stop() { $(pickatizedDateInput).pickadate("picker").stop(); } protected void start() { $(pickatizedDateInput).pickadate("picker").start(); } @Override public MaterialIcon getIcon() { return icon; } @Override public void setIconType(IconType iconType) { icon.setIconType(iconType); icon.setIconPrefix(true); lblError.setPaddingLeft(44); insert(icon, 0); } @Override public void setIconPosition(IconPosition position) { icon.setIconPosition(position); } @Override public void setIconSize(IconSize size) { icon.setIconSize(size); } @Override public void setIconFontSize(double size, Style.Unit unit) { icon.setIconFontSize(size, unit); } @Override public void setIconColor(Color iconColor) { icon.setIconColor(iconColor); } @Override public void setIconPrefix(boolean prefix) { icon.setIconPrefix(prefix); } @Override public boolean isIconPrefix() { return icon.isIconPrefix(); } @Override protected ErrorMixin<AbstractValueWidget, MaterialLabel> getErrorMixin() { return errorMixin; } public ReadOnlyMixin<MaterialDatePicker, DateInput> getReadOnlyMixin() { if (readOnlyMixin == null) { readOnlyMixin = new ReadOnlyMixin<>(this, dateInput); } return readOnlyMixin; } @Override public void setReadOnly(boolean value) { getReadOnlyMixin().setReadOnly(value); } @Override public boolean isReadOnly() { return getReadOnlyMixin().isReadOnly(); } @Override public void setToggleReadOnly(boolean toggle) { getReadOnlyMixin().setToggleReadOnly(toggle); } @Override public boolean isToggleReadOnly() { return getReadOnlyMixin().isToggleReadOnly(); } public DateInput getDateInput() { return dateInput; } public boolean isAutoClose() { return autoClose; } public void setAutoClose(boolean autoClose) { this.autoClose = autoClose; } }
MaterialDatePicker - Fixed leaks on autoClose feature
gwt-material/src/main/java/gwt/material/design/client/ui/MaterialDatePicker.java
MaterialDatePicker - Fixed leaks on autoClose feature
<ide><path>wt-material/src/main/java/gwt/material/design/client/ui/MaterialDatePicker.java <ide> .off(options) <ide> .on(options); <ide> <del> // Provide a feature to autoClose the picker when picking value <del> if (isAutoClose()) { <del> autoCloseHandler = addValueChangeHandler(valueChangeEvent -> { <del> close(); <del> }); <del> } <del> <ide> initialized = true; <ide> <ide> // Set up date specific settings. <ide> return autoClose; <ide> } <ide> <add> /** <add> * Provide a feature to autoClose the picker when picking value <add> */ <ide> public void setAutoClose(boolean autoClose) { <ide> this.autoClose = autoClose; <add> if (isAutoClose()) { <add> autoCloseHandler = addValueChangeHandler(valueChangeEvent -> { <add> close(); <add> }); <add> } else { <add> autoCloseHandler.removeHandler(); <add> } <ide> } <ide> }
Java
lgpl-2.1
2a71b33564cb079546c93302a6d4d4d786fc105a
0
tgvaughan/beast2,Anaphory/beast2,CompEvol/beast2,Anaphory/beast2,CompEvol/beast2,tgvaughan/beast2,Anaphory/beast2,CompEvol/beast2,tgvaughan/beast2,tgvaughan/beast2,CompEvol/beast2,Anaphory/beast2
package beast.evolution.substitutionmodel; import beast.core.Description; import beast.core.Input; import beast.core.Input.Validate; import beast.core.parameter.RealParameter; import beast.core.util.Log; import beast.evolution.datatype.DataType; import beast.evolution.datatype.TwoStateCovarion; /** * <p/> * a the rate of the slow rate class * 1 the rate of the fast rate class * p0 the equilibrium frequency of zero states * p1 1 - p0, the equilibrium frequency of one states * f0 the equilibrium frequency of slow rate class * f1 1 - f0, the equilibrium frequency of fast rate class * s, s1, s2 the rate of switching * <p/> * then the (unnormalized) instantaneous rate matrix (unnormalized Q) should be (depending on mode) * <p/> * * mode = BEAST -- using classic BEAST implementation, reversible iff hfrequencies = (0.5, 0.5) * FLAGS: reversible = false, TSParameterisation = false * * [ -(a*p1)-s , a*p1 , s , 0 ] * [ a*p0 , -(a*p0)-s , 0 , s ] * [ s , 0 , -p1-s , p1 ] * [ 0 , s , p0 , -p0-s ] * * equilibrium frequencies * [ p0 * f0, p1, * f0, p0 * f1, p1, * f1 ] * * mode = REVERSIBLE -- brings in hfrequencies in rate matrix * reversible = true, TSParameterisation = false * [ - , a , s , 0 ] * [ a , - , 0 , s ] * [ s , 0 , - , 1 ] * [ 0 , s , 1 , - ] * * which with frequencies becomes * * [ -(a*p1*f0)-s*f0 , a*p1*f0 , s*f0 , 0 ] * [ a*p0*f0 , -(a*p0*f0)-s*f0 , 0 , s*f0 ] * [ s*f1 , 0 , -p1*f1-s*f1 , p1*f1 ] * [ 0 , s*f1 , p0*f1 , -p0*f1-s*f1 ] * * equilibrium frequencies * [ p0 * f0, p1, * f0, p0 * f1, p1, * f1 ] * * mode = TUFFLEYSTEEL uses alternative parameterisation: hfrequencies is ignored, and switch parameter is set to dimension = 2 * [ -(a*p1)-s1 , a*p1 , s1 , 0 ] * [ a*p0 , -(a*p0)-s1 , 0 , s1 ] * [ s2 , 0 , -p1-s2 , p1 ] * [ 0 , s2 , p0 , -p0-s2 ] * * equilibrium frequencies * [ f0 * s2/(s1+s2), f1, * s2/(s1+s2), f0 * s1/(s1+s2), f1, * s1/(s1+s2) ] * * * Note: to use Tuffley & Steel's methods, set a = 0. */ @Description("Covarion model for Binary data") public class BinaryCovarion extends GeneralSubstitutionModel { public Input<RealParameter> alphaInput = new Input<RealParameter>("alpha", "the rate of evolution in slow mode", Validate.REQUIRED); public Input<RealParameter> switchRateInput = new Input<RealParameter>("switchRate", "the rate of flipping between slow and fast modes", Validate.REQUIRED); public Input<RealParameter> frequenciesInput = new Input<RealParameter>("vfrequencies", "the frequencies of the visible states", Validate.REQUIRED); public Input<RealParameter> hfrequenciesInput = new Input<RealParameter>("hfrequencies", "the frequencies of the hidden rates"); public enum MODE {BEAST, REVERSIBLE, TUFFLEYSTEEL}; public Input<MODE> modeInput = new Input<>("mode","one of BEAST, REVERSIBLE, TUFFLESTEEL " + "BEAST = implementation as in BEAST 1 " + "REVERSIBLE = like BEAST 1 implementation, but using frequencies to make it reversible " + "TUFFLEYSTEEL = Tuffley & Steel (1996) impementation (no rates for ", MODE.BEAST,MODE.values()); private RealParameter alpha; private RealParameter switchRate; private RealParameter frequencies; private RealParameter hiddenFrequencies; protected double[][] unnormalizedQ; protected double[][] storedUnnormalizedQ; int stateCount; MODE mode = modeInput.get(); public BinaryCovarion() { ratesInput.setRule(Validate.OPTIONAL); frequenciesInput.setRule(Validate.OPTIONAL); } @Override public void initAndValidate() throws Exception { alpha = alphaInput.get(); switchRate = switchRateInput.get(); frequencies = frequenciesInput.get(); hiddenFrequencies = hfrequenciesInput.get(); if (mode.equals(MODE.BEAST) || mode.equals(MODE.REVERSIBLE)) { if (alpha.getDimension() != 1) { throw new Exception("alpha should have dimension 1"); } } else { if (alpha.getDimension() != 2) { throw new Exception("alpha should have dimension 2"); } } if (switchRate.getDimension() != 1) { throw new Exception("switchRate should have dimension 1"); } if (frequencies.getDimension() != 2) { throw new Exception("frequencies should have dimension 2"); } if (mode.equals(MODE.BEAST) || mode.equals(MODE.REVERSIBLE)) { if (hfrequenciesInput.get() == null) { throw new Exception("hiddenFrequenciesshould should be specified"); } if (hiddenFrequencies.getDimension() != 2) { throw new Exception("hiddenFrequenciesshould have dimension 2"); } } else { if (hfrequenciesInput.get() != null) { Log.warning.println("WARNING: hfrequencies is specified, but the BinaryCovarion model ignores it."); } } nrOfStates = 4; unnormalizedQ = new double[4][4]; storedUnnormalizedQ = new double[4][4]; updateMatrix = true; eigenSystem = createEigenSystem(); rateMatrix = new double[nrOfStates][nrOfStates]; relativeRates = new double[4 * 3]; storedRelativeRates = new double[4 * 3]; } @Override public boolean canHandleDataType(DataType dataType) { return dataType.getClass().equals(TwoStateCovarion.class); } @Override protected void setupRelativeRates() { } @Override protected void setupRateMatrix() { setupUnnormalizedQMatrix(); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { rateMatrix[i][j] = unnormalizedQ[i][j]; } } // bring in frequencies // for (int i = 0; i < m_nStates; i++) { // for (int j = i + 1; j < m_nStates; j++) { // m_rateMatrix[i][j] *= fFreqs[j]; // m_rateMatrix[j][i] *= fFreqs[i]; // } // } // set up diagonal for (int i = 0; i < nrOfStates; i++) { double fSum = 0.0; for (int j = 0; j < nrOfStates; j++) { if (i != j) fSum += rateMatrix[i][j]; } rateMatrix[i][i] = -fSum; } // normalise rate matrix to one expected substitution per unit time normalize(rateMatrix, getFrequencies()); } // setupRateMatrix @Override public double[] getFrequencies() { double[] fFreqs = new double[4]; if (mode.equals(MODE.BEAST) || mode.equals(MODE.REVERSIBLE)) { fFreqs[0] = frequencies.getValue(0) * hiddenFrequencies.getValue(0); fFreqs[1] = frequencies.getValue(1) * hiddenFrequencies.getValue(0); fFreqs[2] = frequencies.getValue(0) * hiddenFrequencies.getValue(1); fFreqs[3] = frequencies.getValue(1) * hiddenFrequencies.getValue(1); } else { double h0 = alpha.getValue(1) * (alpha.getValue(0) + alpha.getValue(1)); double h1 = alpha.getValue(0) * (alpha.getValue(0) + alpha.getValue(1)); fFreqs[0] = frequencies.getValue(0) * h0; fFreqs[1] = frequencies.getValue(1) * h0; fFreqs[2] = frequencies.getValue(0) * h1; fFreqs[3] = frequencies.getValue(1) * h1; } return fFreqs; } protected void setupUnnormalizedQMatrix() { switch (mode) { case BEAST: { double a = alpha.getValue(0); double s = switchRate.getValue(0); double f0 = hiddenFrequencies.getValue(0); double f1 = hiddenFrequencies.getValue(1); double p0 = frequencies.getValue(0); double p1 = frequencies.getValue(1); assert Math.abs(1.0 - f0 - f1) < 1e-8; assert Math.abs(1.0 - p0 - p1) < 1e-8; unnormalizedQ[0][1] = a * p1; unnormalizedQ[0][2] = s; unnormalizedQ[0][3] = 0.0; unnormalizedQ[1][0] = a * p0; unnormalizedQ[1][2] = 0.0; unnormalizedQ[1][3] = s; unnormalizedQ[2][0] = s; unnormalizedQ[2][1] = 0.0; unnormalizedQ[2][3] = p1; unnormalizedQ[3][0] = 0.0; unnormalizedQ[3][1] = s; unnormalizedQ[3][2] = p0; } break; case REVERSIBLE: { double a = alpha.getValue(0); double s = switchRate.getValue(0); double f0 = hiddenFrequencies.getValue(0); double f1 = hiddenFrequencies.getValue(1); double p0 = frequencies.getValue(0); double p1 = frequencies.getValue(1); assert Math.abs(1.0 - f0 - f1) < 1e-8; assert Math.abs(1.0 - p0 - p1) < 1e-8; unnormalizedQ[0][1] = a * p1 * f0; unnormalizedQ[0][2] = s * f0; unnormalizedQ[0][3] = 0.0; unnormalizedQ[1][0] = a * p0 * f0; unnormalizedQ[1][2] = 0.0; unnormalizedQ[1][3] = s * f0; unnormalizedQ[2][0] = s * f1; unnormalizedQ[2][1] = 0.0; unnormalizedQ[2][3] = p1 * f1; unnormalizedQ[3][0] = 0.0; unnormalizedQ[3][1] = s * f1; unnormalizedQ[3][2] = p0 * f1; } break; case TUFFLEYSTEEL: { double a = alpha.getValue(0); double s1 = switchRate.getValue(0); double s2 = switchRate.getValue(0); double p0 = frequencies.getValue(0); double p1 = frequencies.getValue(1); assert Math.abs(1.0 - p0 - p1) < 1e-8; unnormalizedQ[0][1] = a * p1; unnormalizedQ[0][2] = s1; unnormalizedQ[0][3] = 0.0; unnormalizedQ[1][0] = a * p0; unnormalizedQ[1][2] = 0.0; unnormalizedQ[1][3] = s1; unnormalizedQ[2][0] = s2; unnormalizedQ[2][1] = 0.0; unnormalizedQ[2][3] = p1; unnormalizedQ[3][0] = 0.0; unnormalizedQ[3][1] = s2; unnormalizedQ[3][2] = p0; } break; } } /** * Normalize rate matrix to one expected substitution per unit time * * @param matrix the matrix to normalize to one expected substitution * @param pi the equilibrium distribution of states */ private void normalize(double[][] matrix, double[] pi) { double subst = 0.0; int dimension = pi.length; for (int i = 0; i < dimension; i++) { subst += -matrix[i][i] * pi[i]; } // normalize, including switches for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { matrix[i][j] = matrix[i][j] / subst; } } double switchingProportion = 0.0; switchingProportion += matrix[0][2] * pi[2]; switchingProportion += matrix[2][0] * pi[0]; switchingProportion += matrix[1][3] * pi[3]; switchingProportion += matrix[3][1] * pi[1]; //System.out.println("switchingProportion=" + switchingProportion); // normalize, removing switches for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { matrix[i][j] = matrix[i][j] / (1.0 - switchingProportion); } } } }
src/beast/evolution/substitutionmodel/BinaryCovarion.java
package beast.evolution.substitutionmodel; import beast.core.Description; import beast.core.Input; import beast.core.Input.Validate; import beast.core.parameter.RealParameter; import beast.core.util.Log; import beast.evolution.datatype.DataType; import beast.evolution.datatype.TwoStateCovarion; /** * <p/> * a the rate of the slow rate class * 1 the rate of the fast rate class * p0 the equilibrium frequency of zero states * p1 1 - p0, the equilibrium frequency of one states * f0 the equilibrium frequency of slow rate class * f1 1 - f0, the equilibrium frequency of fast rate class * s, s1, s2 the rate of switching * <p/> * then the (unnormalized) instantaneous rate matrix (unnormalized Q) should be (depending on mode) * <p/> * * mode = BEAST -- using classic BEAST implementation, reversible iff hfrequencies = (0.5, 0.5) * FLAGS: reversible = false, TSParameterisation = false * * [ -(a*p1)-s , a*p1 , s , 0 ] * [ a*p0 , -(a*p0)-s , 0 , s ] * [ s , 0 , -p1-s , p1 ] * [ 0 , s , p0 , -p0-s ] * * equilibrium frequencies * [ p0 * f0, p1, * f0, p0 * f1, p1, * f1 ] * * mode = REVERSIBLE -- brings in hfrequencies in rate matrix * reversible = true, TSParameterisation = false * [ - , a , s , 0 ] * [ a , - , 0 , s ] * [ s , 0 , - , 1 ] * [ 0 , s , 1 , - ] * * which with frequencies becomes * * [ -(a*p1*f0)-s*f0 , a*p1*f0 , s*f0 , 0 ] * [ a*p0*f0 , -(a*p0*f0)-s*f0 , 0 , s*f0 ] * [ s*f1 , 0 , -p1*f1-s*f1 , p1*f1 ] * [ 0 , s*f1 , p0*f1 , -p0*f1-s*f1 ] * * equilibrium frequencies * [ p0 * f0, p1, * f0, p0 * f1, p1, * f1 ] * * mode = TUFFLEYSTEEL uses alternative parameterisation: hfrequencies is ignored, and switch parameter is set to dimension = 2 * [ -(a*p1)-s1 , a*p1 , s1 , 0 ] * [ a*p0 , -(a*p0)-s1 , 0 , s1 ] * [ s2 , 0 , -p1-s2 , p1 ] * [ 0 , s2 , p0 , -p0-s2 ] * * equilibrium frequencies * [ f0 * s2/(s1+s2), f1, * s2/(s1+s2), f0 * s1/(s1+s2), f1, * s1/(s1+s2) ] * * * Note: to use Tuffley & Steel's methods, set a = 0. */ @Description("Covarion model for Binary data") public class BinaryCovarion extends GeneralSubstitutionModel { public Input<RealParameter> alphaInput = new Input<RealParameter>("alpha", "the rate of evolution in slow mode", Validate.REQUIRED); public Input<RealParameter> switchRateInput = new Input<RealParameter>("switchRate", "the rate of flipping between slow and fast modes", Validate.REQUIRED); public Input<RealParameter> frequenciesInput = new Input<RealParameter>("vfrequencies", "the frequencies of the visible states", Validate.REQUIRED); public Input<RealParameter> hfrequenciesInput = new Input<RealParameter>("hfrequencies", "the frequencies of the hidden rates"); public enum MODE {BEAST, REVERSIBLE, TUFFLEYSTEEL}; public Input<MODE> modeInput = new Input<>("mode","one of BEAST, REVERSIBLE, TUFFLESTEEL " + "BEAST = implementation as in BEAST 1 " + "REVERSIBLE = like BEAST 1 implementation, but using frequencies to make it reversible " + "TUFFLEYSTEEL = Tuffley & Steel (1996) impementation (no rates for ", MODE.BEAST); private RealParameter alpha; private RealParameter switchRate; private RealParameter frequencies; private RealParameter hiddenFrequencies; protected double[][] unnormalizedQ; protected double[][] storedUnnormalizedQ; int stateCount; MODE mode = modeInput.get(); public BinaryCovarion() { ratesInput.setRule(Validate.OPTIONAL); frequenciesInput.setRule(Validate.OPTIONAL); } @Override public void initAndValidate() throws Exception { alpha = alphaInput.get(); switchRate = switchRateInput.get(); frequencies = frequenciesInput.get(); hiddenFrequencies = hfrequenciesInput.get(); if (mode.equals(MODE.BEAST) || mode.equals(MODE.REVERSIBLE)) { if (alpha.getDimension() != 1) { throw new Exception("alpha should have dimension 1"); } } else { if (alpha.getDimension() != 2) { throw new Exception("alpha should have dimension 2"); } } if (switchRate.getDimension() != 1) { throw new Exception("switchRate should have dimension 1"); } if (frequencies.getDimension() != 2) { throw new Exception("frequencies should have dimension 2"); } if (mode.equals(MODE.BEAST) || mode.equals(MODE.REVERSIBLE)) { if (hfrequenciesInput.get() == null) { throw new Exception("hiddenFrequenciesshould should be specified"); } if (hiddenFrequencies.getDimension() != 2) { throw new Exception("hiddenFrequenciesshould have dimension 2"); } } else { if (hfrequenciesInput.get() != null) { Log.warning.println("WARNING: hfrequencies is specified, but the BinaryCovarion model ignores it."); } } nrOfStates = 4; unnormalizedQ = new double[4][4]; storedUnnormalizedQ = new double[4][4]; updateMatrix = true; eigenSystem = createEigenSystem(); rateMatrix = new double[nrOfStates][nrOfStates]; relativeRates = new double[4 * 3]; storedRelativeRates = new double[4 * 3]; } @Override public boolean canHandleDataType(DataType dataType) { return dataType.getClass().equals(TwoStateCovarion.class); } @Override protected void setupRelativeRates() { } @Override protected void setupRateMatrix() { setupUnnormalizedQMatrix(); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { rateMatrix[i][j] = unnormalizedQ[i][j]; } } // bring in frequencies // for (int i = 0; i < m_nStates; i++) { // for (int j = i + 1; j < m_nStates; j++) { // m_rateMatrix[i][j] *= fFreqs[j]; // m_rateMatrix[j][i] *= fFreqs[i]; // } // } // set up diagonal for (int i = 0; i < nrOfStates; i++) { double fSum = 0.0; for (int j = 0; j < nrOfStates; j++) { if (i != j) fSum += rateMatrix[i][j]; } rateMatrix[i][i] = -fSum; } // normalise rate matrix to one expected substitution per unit time normalize(rateMatrix, getFrequencies()); } // setupRateMatrix @Override public double[] getFrequencies() { double[] fFreqs = new double[4]; if (mode.equals(MODE.BEAST) || mode.equals(MODE.REVERSIBLE)) { fFreqs[0] = frequencies.getValue(0) * hiddenFrequencies.getValue(0); fFreqs[1] = frequencies.getValue(1) * hiddenFrequencies.getValue(0); fFreqs[2] = frequencies.getValue(0) * hiddenFrequencies.getValue(1); fFreqs[3] = frequencies.getValue(1) * hiddenFrequencies.getValue(1); } else { double h0 = alpha.getValue(1) * (alpha.getValue(0) + alpha.getValue(1)); double h1 = alpha.getValue(0) * (alpha.getValue(0) + alpha.getValue(1)); fFreqs[0] = frequencies.getValue(0) * h0; fFreqs[1] = frequencies.getValue(1) * h0; fFreqs[2] = frequencies.getValue(0) * h1; fFreqs[3] = frequencies.getValue(1) * h1; } return fFreqs; } protected void setupUnnormalizedQMatrix() { switch (mode) { case BEAST: { double a = alpha.getValue(0); double s = switchRate.getValue(0); double f0 = hiddenFrequencies.getValue(0); double f1 = hiddenFrequencies.getValue(1); double p0 = frequencies.getValue(0); double p1 = frequencies.getValue(1); assert Math.abs(1.0 - f0 - f1) < 1e-8; assert Math.abs(1.0 - p0 - p1) < 1e-8; unnormalizedQ[0][1] = a * p1; unnormalizedQ[0][2] = s; unnormalizedQ[0][3] = 0.0; unnormalizedQ[1][0] = a * p0; unnormalizedQ[1][2] = 0.0; unnormalizedQ[1][3] = s; unnormalizedQ[2][0] = s; unnormalizedQ[2][1] = 0.0; unnormalizedQ[2][3] = p1; unnormalizedQ[3][0] = 0.0; unnormalizedQ[3][1] = s; unnormalizedQ[3][2] = p0; } break; case REVERSIBLE: { double a = alpha.getValue(0); double s = switchRate.getValue(0); double f0 = hiddenFrequencies.getValue(0); double f1 = hiddenFrequencies.getValue(1); double p0 = frequencies.getValue(0); double p1 = frequencies.getValue(1); assert Math.abs(1.0 - f0 - f1) < 1e-8; assert Math.abs(1.0 - p0 - p1) < 1e-8; unnormalizedQ[0][1] = a * p1 * f0; unnormalizedQ[0][2] = s * f0; unnormalizedQ[0][3] = 0.0; unnormalizedQ[1][0] = a * p0 * f0; unnormalizedQ[1][2] = 0.0; unnormalizedQ[1][3] = s * f0; unnormalizedQ[2][0] = s * f1; unnormalizedQ[2][1] = 0.0; unnormalizedQ[2][3] = p1 * f1; unnormalizedQ[3][0] = 0.0; unnormalizedQ[3][1] = s * f1; unnormalizedQ[3][2] = p0 * f1; } break; case TUFFLEYSTEEL: { double a = alpha.getValue(0); double s1 = switchRate.getValue(0); double s2 = switchRate.getValue(0); double p0 = frequencies.getValue(0); double p1 = frequencies.getValue(1); assert Math.abs(1.0 - p0 - p1) < 1e-8; unnormalizedQ[0][1] = a * p1; unnormalizedQ[0][2] = s1; unnormalizedQ[0][3] = 0.0; unnormalizedQ[1][0] = a * p0; unnormalizedQ[1][2] = 0.0; unnormalizedQ[1][3] = s1; unnormalizedQ[2][0] = s2; unnormalizedQ[2][1] = 0.0; unnormalizedQ[2][3] = p1; unnormalizedQ[3][0] = 0.0; unnormalizedQ[3][1] = s2; unnormalizedQ[3][2] = p0; } break; } } /** * Normalize rate matrix to one expected substitution per unit time * * @param matrix the matrix to normalize to one expected substitution * @param pi the equilibrium distribution of states */ private void normalize(double[][] matrix, double[] pi) { double subst = 0.0; int dimension = pi.length; for (int i = 0; i < dimension; i++) { subst += -matrix[i][i] * pi[i]; } // normalize, including switches for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { matrix[i][j] = matrix[i][j] / subst; } } double switchingProportion = 0.0; switchingProportion += matrix[0][2] * pi[2]; switchingProportion += matrix[2][0] * pi[0]; switchingProportion += matrix[1][3] * pi[3]; switchingProportion += matrix[3][1] * pi[1]; //System.out.println("switchingProportion=" + switchingProportion); // normalize, removing switches for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { matrix[i][j] = matrix[i][j] / (1.0 - switchingProportion); } } } }
issue #398 set up Input of BinaryCovarion properly
src/beast/evolution/substitutionmodel/BinaryCovarion.java
issue #398 set up Input of BinaryCovarion properly
<ide><path>rc/beast/evolution/substitutionmodel/BinaryCovarion.java <ide> public Input<MODE> modeInput = new Input<>("mode","one of BEAST, REVERSIBLE, TUFFLESTEEL " <ide> + "BEAST = implementation as in BEAST 1 " <ide> + "REVERSIBLE = like BEAST 1 implementation, but using frequencies to make it reversible " <del> + "TUFFLEYSTEEL = Tuffley & Steel (1996) impementation (no rates for ", MODE.BEAST); <add> + "TUFFLEYSTEEL = Tuffley & Steel (1996) impementation (no rates for ", MODE.BEAST,MODE.values()); <ide> <ide> private RealParameter alpha; <ide> private RealParameter switchRate;
Java
mit
b2de12d61cba182e07c80aa3748ef060cb4b449f
0
LightningDevStudios/CircuitCrawler
package com.lds.game.entity; import com.lds.Vector2f; public class TeleporterLinker { protected static Vector2f link1Pos, link2Pos, link3Pos; protected static Teleporter entTele1, entTele2, entTele3; protected static boolean oneWay, threeWay; public TeleporterLinker(Teleporter ent, Teleporter ent2, boolean isOneWay, boolean isThreeWay) { link1Pos = new Vector2f(ent.getPos()); link2Pos = new Vector2f(ent2.getPos()); entTele1 = ent; entTele2 = ent2; oneWay = isOneWay; threeWay = isThreeWay; } public TeleporterLinker(Teleporter ent, Teleporter ent2, Teleporter ent3, boolean isOneWay, boolean isThreeWay) { link1Pos = new Vector2f(ent.getPos()); link2Pos = new Vector2f(ent2.getPos()); link3Pos = new Vector2f(ent3.getPos()); entTele1 = ent; entTele2 = ent2; entTele3 = ent3; oneWay = isOneWay; threeWay = isThreeWay; } public static Vector2f getLinkedPos(Teleporter ent3) { if(ent3.equals(entTele1)) { entTele1.setActive(false); entTele2.setActive(true); return link2Pos; } else if(ent3.equals(entTele2)) { { if(oneWay) { entTele1.setActive(false); entTele2.setActive(true); return link2Pos; } else if(threeWay) { entTele1.setActive(false); entTele2.setActive(false); entTele3.setActive(true); return link3Pos; } else { entTele2.setActive(false); entTele1.setActive(true); return link1Pos; } } } else if(ent3.equals(entTele3)) { return link3Pos; } else {return null;} } public void setOneWay(boolean bool) { oneWay = bool; } public void setThreeWay(boolean bool) { threeWay = bool; } }
src/com/lds/game/entity/TeleporterLinker.java
package com.lds.game.entity; import com.lds.Vector2f; public class TeleporterLinker { protected static Vector2f link1Pos, link2Pos, link3Pos; protected static Teleporter entTele1, entTele2, entTele3; protected static boolean oneWay, threeWay; public TeleporterLinker(Teleporter ent, Teleporter ent2, boolean isOneWay, boolean isThreeWay) { link1Pos = new Vector2f(ent.getPos()); link2Pos = new Vector2f(ent2.getPos()); entTele1 = ent; entTele2 = ent2; oneWay = isOneWay; threeWay = isThreeWay; } public TeleporterLinker(Teleporter ent, Teleporter ent2, Teleporter ent3, boolean isOneWay, boolean isThreeWay) { link1Pos = new Vector2f(ent.getPos()); link2Pos = new Vector2f(ent2.getPos()); link3Pos = new Vector2f(ent3.getPos()); entTele1 = ent; entTele2 = ent2; entTele3 = ent3; oneWay = isOneWay; threeWay = isThreeWay; } public static Vector2f getLinkedPos(Teleporter ent3) { if(ent3.equals(entTele1)) { entTele1.setActive(false); entTele2.setActive(true); return link2Pos; } else if(ent3.equals(entTele2)) { { if(oneWay) { entTele1.setActive(false); entTele2.setActive(true); return link2Pos; } else if(threeWay) { entTele1.setActive(false); entTele2.setActive(false); entTele3.setActive(true); return link3Pos; } else { entTele2.setActive(false); entTele1.setActive(true); return link1Pos; } } } else if(ent3.equals(entTele3)) { return link3Pos; } else {return null;} } public void setOneWay(boolean bool) { oneWay = bool; } }
more fixes
src/com/lds/game/entity/TeleporterLinker.java
more fixes
<ide><path>rc/com/lds/game/entity/TeleporterLinker.java <ide> { <ide> oneWay = bool; <ide> } <add> <add> public void setThreeWay(boolean bool) <add> { <add> threeWay = bool; <add> } <ide> }
Java
mit
error: pathspec 'Craps.java' did not match any file(s) known to git
940e02d48a57805faacce28247c67ea461836a70
1
k8port/Java
/** A program to simulate a game of craps. This program does not require user * input and instead rolls the dice and plays 10,000 games. The number of * wins and the number of losses are added and probability of winning and * losing is output. * Rules of craps: * Two six-sided dice are rolled. The first roll is called the "come out * roll". If you roll 7 or 11 you automatically win, but if you roll 2, * 3, or 12 you automatically lose. Any other number rolled (4, 5, 6, 8 * 9, 10) becomes "the point". You will continue to roll the dice until * either the number 7 or "the point" is rolled. If you roll "the point" * than you win, but if you roll a 7 first, you lose. */ package craps; /** * * @author k8port */ import java.text.DecimalFormat; public class Craps { // number of rounds program plays private static final int GAMES = 10000; /** * @param args the command line arguments */ public static void main(String[] args) { // variable declarations /** The 2 dice and their sum*/ int die1, die2; /** The sum of the die in each round */ int round1, round2; /** Wins and losses count start at 0 */ int wins=0, losses=0; /** Object used to format percentages */ DecimalFormat formatter = new DecimalFormat("00.00%"); /** A flag to determine whether to roll again */ boolean roll; // Let's play! System.out.println("Let's play craps!"); for (int i = 1; i <= GAMES; i++) { System.out.println(""); System.out.printf("Game %d, Round 1:%n", i); die1 = (int) (Math.random() * 6) + 1; die2 = (int) (Math.random() * 6) + 1; round1 = die1 + die2; System.out.printf("You rolled a %d and a %d.%n", die1, die2); switch (round1) { case 2: case 3: case 12: System.out.printf("You rolled %d!%n", round1); System.out.println("You lose."); losses++; break; case 7: case 11: System.out.printf("You rolled %d!%n", round1); System.out.println("You win!"); wins++; break; default: System.out.printf("You rolled %d!%n", round1); System.out.println("This is the point for the next round."); System.out.println("Round 2: "); roll = true; // set roll again flag to true do { die1 = (int) (Math.random() * 6) + 1; die2 = (int) (Math.random() * 6) + 1; round2 = die1 + die2; System.out.printf("You rolled a %d and a %d.%n", die1, die2); // for debug /*System.out.printf("Round 1 roll: %d. Round 2 roll: %d.%n", round1, round2); System.out.println("Round 1 roll same as round 2? " + (round1 == round2));*/ if (round2 == round1 || round2 == 7) roll = false; } while (roll); switch (round2) { case 4: case 5: case 6: case 8: case 9: case 10: System.out.printf("You rolled %d!%n", round2); System.out.println("You rolled the point!"); System.out.println("You win!"); wins++; break; case 7: System.out.println("You rolled 7."); System.out.println("You lose."); losses++; break; default: System.out.println("Program error"); break; } // end round 2 switch break; } // end round 1 switch statement } // end of GAME // calculate probability System.out.printf("%nYou won %d times and lost %d times.%n", wins, losses); double probable_wins = (double) wins / (double) GAMES; double probable_losses = (double) losses/(double) GAMES; String win = formatter.format(probable_wins); String lose = formatter.format(probable_losses); System.out.println("You won " + win + " of the time."); System.out.println("You lost " + lose + " of the time."); if (probable_wins > probable_losses) System.out.println("You are a winner!"); else System.out.println("You are a loser!"); } // end main }
Craps.java
Create Craps.java A program to simulate 10000 games of craps. Odds are calculated and output based on results of 10000 rounds. Uses Math.random() to simulate random die rolls.
Craps.java
Create Craps.java
<ide><path>raps.java <add>/** A program to simulate a game of craps. This program does not require user <add> * input and instead rolls the dice and plays 10,000 games. The number of <add> * wins and the number of losses are added and probability of winning and <add> * losing is output. <add> * Rules of craps: <add> * Two six-sided dice are rolled. The first roll is called the "come out <add> * roll". If you roll 7 or 11 you automatically win, but if you roll 2, <add> * 3, or 12 you automatically lose. Any other number rolled (4, 5, 6, 8 <add> * 9, 10) becomes "the point". You will continue to roll the dice until <add> * either the number 7 or "the point" is rolled. If you roll "the point" <add> * than you win, but if you roll a 7 first, you lose. <add> */ <add> <add>package craps; <add> <add>/** <add> * <add> * @author k8port <add> */ <add>import java.text.DecimalFormat; <add> <add>public class Craps { <add> <add> // number of rounds program plays <add> private static final int GAMES = 10000; <add> /** <add> * @param args the command line arguments <add> */ <add> public static void main(String[] args) { <add> <add> // variable declarations <add> /** The 2 dice and their sum*/ <add> int die1, die2; <add> /** The sum of the die in each round */ <add> int round1, round2; <add> /** Wins and losses count start at 0 */ <add> int wins=0, losses=0; <add> /** Object used to format percentages */ <add> DecimalFormat formatter = new DecimalFormat("00.00%"); <add> /** A flag to determine whether to roll again */ <add> boolean roll; <add> <add> // Let's play! <add> System.out.println("Let's play craps!"); <add> for (int i = 1; i <= GAMES; i++) { <add> System.out.println(""); <add> System.out.printf("Game %d, Round 1:%n", i); <add> die1 = (int) (Math.random() * 6) + 1; <add> die2 = (int) (Math.random() * 6) + 1; <add> <add> round1 = die1 + die2; <add> System.out.printf("You rolled a %d and a %d.%n", die1, die2); <add> switch (round1) { <add> case 2: <add> case 3: <add> case 12: <add> System.out.printf("You rolled %d!%n", round1); <add> System.out.println("You lose."); <add> losses++; <add> break; <add> case 7: <add> case 11: <add> System.out.printf("You rolled %d!%n", round1); <add> System.out.println("You win!"); <add> wins++; <add> break; <add> default: <add> System.out.printf("You rolled %d!%n", round1); <add> System.out.println("This is the point for the next round."); <add> System.out.println("Round 2: "); <add> roll = true; // set roll again flag to true <add> do { <add> die1 = (int) (Math.random() * 6) + 1; <add> die2 = (int) (Math.random() * 6) + 1; <add> round2 = die1 + die2; <add> System.out.printf("You rolled a %d and a %d.%n", die1, die2); <add> // for debug <add> /*System.out.printf("Round 1 roll: %d. Round 2 roll: %d.%n", round1, round2); <add> System.out.println("Round 1 roll same as round 2? " + (round1 == round2));*/ <add> if (round2 == round1 || round2 == 7) <add> roll = false; <add> } while (roll); <add> switch (round2) { <add> case 4: <add> case 5: <add> case 6: <add> case 8: <add> case 9: <add> case 10: <add> System.out.printf("You rolled %d!%n", round2); <add> System.out.println("You rolled the point!"); <add> System.out.println("You win!"); <add> wins++; <add> break; <add> case 7: <add> System.out.println("You rolled 7."); <add> System.out.println("You lose."); <add> losses++; <add> break; <add> default: <add> System.out.println("Program error"); <add> break; <add> } // end round 2 switch <add> break; <add> } // end round 1 switch statement <add> } // end of GAME <add> <add> // calculate probability <add> System.out.printf("%nYou won %d times and lost %d times.%n", wins, losses); <add> double probable_wins = (double) wins / (double) GAMES; <add> double probable_losses = (double) losses/(double) GAMES; <add> <add> String win = formatter.format(probable_wins); <add> String lose = formatter.format(probable_losses); <add> System.out.println("You won " + win + " of the time."); <add> System.out.println("You lost " + lose + " of the time."); <add> if (probable_wins > probable_losses) <add> System.out.println("You are a winner!"); <add> else <add> System.out.println("You are a loser!"); <add> <add> <add> } // end main <add> <add>}
Java
bsd-2-clause
ea7f7a8b918846445d3a5e77b20a81cfd454e80c
0
malensek/galileo-net,malensek/elssa
/* Copyright (c) 2015, Colorado State University All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright holder or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. */ package io.elssa.nn; import java.net.InetSocketAddress; import java.net.SocketAddress; /** * Represents a TCP network endpoint; a host/port pair. * * @author malensek */ public class NetworkEndpoint { protected String hostname; protected int port; public NetworkEndpoint(String hostname, int port) { this.hostname = hostname; this.port = port; } public NetworkEndpoint(SocketAddress address) { if (address instanceof InetSocketAddress) { InetSocketAddress iAddress = (InetSocketAddress) address; this.hostname = iAddress.getHostName(); this.port = iAddress.getPort(); } } public String hostname() { return hostname; } public int port() { return port; } private String stringRepresentation() { return hostname + ":" + port; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((hostname == null) ? 0 : hostname.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } NetworkEndpoint other = (NetworkEndpoint) obj; return this.stringRepresentation().equals(other.stringRepresentation()); } @Override public String toString() { return stringRepresentation(); } }
src/main/java/io/elssa/nn/NetworkEndpoint.java
/* Copyright (c) 2015, Colorado State University All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright holder or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. */ package io.elssa.nn; /** * Represents a TCP network endpoint; a host/port pair. * * @author malensek */ public class NetworkEndpoint { protected String hostname; protected int port; public NetworkEndpoint(String hostname, int port) { this.hostname = hostname; this.port = port; } public String hostname() { return hostname; } public int port() { return port; } private String stringRepresentation() { return hostname + ":" + port; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((hostname == null) ? 0 : hostname.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } NetworkEndpoint other = (NetworkEndpoint) obj; return this.stringRepresentation().equals(other.stringRepresentation()); } @Override public String toString() { return stringRepresentation(); } }
Add SocketAddress-based constructor
src/main/java/io/elssa/nn/NetworkEndpoint.java
Add SocketAddress-based constructor
<ide><path>rc/main/java/io/elssa/nn/NetworkEndpoint.java <ide> <ide> package io.elssa.nn; <ide> <add>import java.net.InetSocketAddress; <add>import java.net.SocketAddress; <add> <ide> /** <ide> * Represents a TCP network endpoint; a host/port pair. <ide> * <ide> public NetworkEndpoint(String hostname, int port) { <ide> this.hostname = hostname; <ide> this.port = port; <add> } <add> <add> public NetworkEndpoint(SocketAddress address) { <add> if (address instanceof InetSocketAddress) { <add> InetSocketAddress iAddress = (InetSocketAddress) address; <add> this.hostname = iAddress.getHostName(); <add> this.port = iAddress.getPort(); <add> } <ide> } <ide> <ide> public String hostname() {
Java
apache-2.0
0ad561ace039bca90681bccfbcd4ee5912c33103
0
jagguli/intellij-community,consulo/consulo,vladmm/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,fitermay/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,caot/intellij-community,da1z/intellij-community,amith01994/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,diorcety/intellij-community,FHannes/intellij-community,retomerz/intellij-community,petteyg/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,ryano144/intellij-community,xfournet/intellij-community,clumsy/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,izonder/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,tmpgit/intellij-community,semonte/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,asedunov/intellij-community,signed/intellij-community,semonte/intellij-community,caot/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,samthor/intellij-community,allotria/intellij-community,adedayo/intellij-community,kool79/intellij-community,apixandru/intellij-community,ernestp/consulo,asedunov/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,retomerz/intellij-community,semonte/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,da1z/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,signed/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,consulo/consulo,fitermay/intellij-community,adedayo/intellij-community,ernestp/consulo,amith01994/intellij-community,ibinti/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,slisson/intellij-community,blademainer/intellij-community,ibinti/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,signed/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,samthor/intellij-community,izonder/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,slisson/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,robovm/robovm-studio,holmes/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,ibinti/intellij-community,hurricup/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,da1z/intellij-community,semonte/intellij-community,amith01994/intellij-community,petteyg/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,ryano144/intellij-community,fnouama/intellij-community,supersven/intellij-community,akosyakov/intellij-community,caot/intellij-community,clumsy/intellij-community,kool79/intellij-community,petteyg/intellij-community,signed/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,robovm/robovm-studio,diorcety/intellij-community,diorcety/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,signed/intellij-community,robovm/robovm-studio,kdwink/intellij-community,blademainer/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,adedayo/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,caot/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,retomerz/intellij-community,slisson/intellij-community,hurricup/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,allotria/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,semonte/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,holmes/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,izonder/intellij-community,slisson/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,ryano144/intellij-community,asedunov/intellij-community,FHannes/intellij-community,da1z/intellij-community,ryano144/intellij-community,izonder/intellij-community,hurricup/intellij-community,caot/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,hurricup/intellij-community,xfournet/intellij-community,diorcety/intellij-community,signed/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,jagguli/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,izonder/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,vladmm/intellij-community,hurricup/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,petteyg/intellij-community,blademainer/intellij-community,asedunov/intellij-community,amith01994/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,slisson/intellij-community,hurricup/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,supersven/intellij-community,Lekanich/intellij-community,holmes/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,signed/intellij-community,fnouama/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,da1z/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,allotria/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,apixandru/intellij-community,allotria/intellij-community,dslomov/intellij-community,da1z/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,izonder/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,apixandru/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,hurricup/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,dslomov/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,caot/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,signed/intellij-community,caot/intellij-community,FHannes/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,da1z/intellij-community,allotria/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,petteyg/intellij-community,supersven/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,signed/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,kool79/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,consulo/consulo,ftomassetti/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,hurricup/intellij-community,fnouama/intellij-community,caot/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,caot/intellij-community,wreckJ/intellij-community,semonte/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,consulo/consulo,ahb0327/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,samthor/intellij-community,FHannes/intellij-community,holmes/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,orekyuu/intellij-community,signed/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,izonder/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,caot/intellij-community,ryano144/intellij-community,kool79/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,ernestp/consulo,salguarnieri/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,consulo/consulo,allotria/intellij-community,xfournet/intellij-community,semonte/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,retomerz/intellij-community,retomerz/intellij-community,slisson/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,caot/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,allotria/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,semonte/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,kool79/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,izonder/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,ernestp/consulo,petteyg/intellij-community,semonte/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,samthor/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,fitermay/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,ernestp/consulo,gnuhub/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,kool79/intellij-community,izonder/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,slisson/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,caot/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,consulo/consulo,blademainer/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,retomerz/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,vladmm/intellij-community,samthor/intellij-community,robovm/robovm-studio,slisson/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,blademainer/intellij-community,slisson/intellij-community,ibinti/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,holmes/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,clumsy/intellij-community,ryano144/intellij-community,jagguli/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,vvv1559/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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.intellij.ide.actions; import com.intellij.ide.impl.ProjectUtil; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.components.StorageScheme; import com.intellij.openapi.components.impl.stores.IProjectStore; import com.intellij.openapi.components.impl.stores.StateStorageManager; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ex.ProjectEx; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; /** * @author spleaner */ public class SaveAsDirectoryBasedFormatAction extends AnAction implements DumbAware { public void actionPerformed(AnActionEvent e) { final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext()); if (project instanceof ProjectEx) { final IProjectStore projectStore = ((ProjectEx)project).getStateStore(); if (StorageScheme.DIRECTORY_BASED != projectStore.getStorageScheme()) { final int result = Messages.showOkCancelDialog(project, "Project will be saved and reopened in new Directory-Based format.\nAre you sure you want to continue?", "Save project to Directory-Based format", Messages.getWarningIcon()); if (result == 0) { final VirtualFile baseDir = project.getBaseDir(); assert baseDir != null; File ideaDir = new File(baseDir.getPath(), ProjectEx.DIRECTORY_STORE_FOLDER + File.separatorChar); final boolean ok = (ideaDir.exists() && ideaDir.isDirectory()) || createDir(ideaDir); if (ok) { LocalFileSystem.getInstance().refreshAndFindFileByIoFile(ideaDir); final StateStorageManager storageManager = projectStore.getStateStorageManager(); final Collection<String> storageFileNames = new ArrayList<String>(storageManager.getStorageFileNames()); for (String file : storageFileNames) { storageManager.clearStateStorage(file); } projectStore.setProjectFilePath(baseDir.getPath()); project.save(); ProjectUtil.closeAndDispose(project); ProjectUtil.openProject(baseDir.getPath(), null, false); } else { Messages.showErrorDialog(project, String.format("Unable to create '.idea' directory (%s)", ideaDir), "Error saving project!"); } } } } } private boolean createDir(File ideaDir) { try { VfsUtil.createDirectories(ideaDir.getPath()); return true; } catch (IOException e) { return false; } } @Override public void update(AnActionEvent e) { final Presentation presentation = e.getPresentation(); final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext()); boolean visible = project != null; if (project instanceof ProjectEx) { visible = ((ProjectEx)project).getStateStore().getStorageScheme() != StorageScheme.DIRECTORY_BASED; } presentation.setVisible(visible); } }
platform/platform-impl/src/com/intellij/ide/actions/SaveAsDirectoryBasedFormatAction.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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.intellij.ide.actions; import com.intellij.ide.impl.ProjectUtil; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.components.StorageScheme; import com.intellij.openapi.components.impl.stores.IProjectStore; import com.intellij.openapi.components.impl.stores.StateStorageManager; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ex.ProjectEx; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import java.io.File; import java.io.IOException; /** * @author spleaner */ public class SaveAsDirectoryBasedFormatAction extends AnAction implements DumbAware { public void actionPerformed(AnActionEvent e) { final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext()); if (project instanceof ProjectEx) { final IProjectStore projectStore = ((ProjectEx)project).getStateStore(); if (StorageScheme.DIRECTORY_BASED != projectStore.getStorageScheme()) { final int result = Messages.showOkCancelDialog(project, "Project will be saved and reopened in new Directory-Based format.\nAre you sure you want to continue?", "Save project to Directory-Based format", Messages.getWarningIcon()); if (result == 0) { final VirtualFile baseDir = project.getBaseDir(); assert baseDir != null; File ideaDir = new File(baseDir.getPath(), ProjectEx.DIRECTORY_STORE_FOLDER + File.separatorChar); final boolean ok = (ideaDir.exists() && ideaDir.isDirectory()) || createDir(ideaDir); if (ok) { LocalFileSystem.getInstance().refreshAndFindFileByIoFile(ideaDir); final StateStorageManager storageManager = projectStore.getStateStorageManager(); for (String file : storageManager.getStorageFileNames()) { storageManager.clearStateStorage(file); } projectStore.setProjectFilePath(baseDir.getPath()); project.save(); ProjectUtil.closeAndDispose(project); ProjectUtil.openProject(baseDir.getPath(), null, false); } else { Messages.showErrorDialog(project, String.format("Unable to create '.idea' directory (%s)", ideaDir), "Error saving project!"); } } } } } private boolean createDir(File ideaDir) { try { VfsUtil.createDirectories(ideaDir.getPath()); return true; } catch (IOException e) { return false; } } @Override public void update(AnActionEvent e) { final Presentation presentation = e.getPresentation(); final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext()); boolean visible = project != null; if (project instanceof ProjectEx) { visible = ((ProjectEx)project).getStateStore().getStorageScheme() != StorageScheme.DIRECTORY_BASED; } presentation.setVisible(visible); } }
ConcurrentModificationException
platform/platform-impl/src/com/intellij/ide/actions/SaveAsDirectoryBasedFormatAction.java
ConcurrentModificationException
<ide><path>latform/platform-impl/src/com/intellij/ide/actions/SaveAsDirectoryBasedFormatAction.java <ide> <ide> import java.io.File; <ide> import java.io.IOException; <add>import java.util.ArrayList; <add>import java.util.Collection; <ide> <ide> /** <ide> * @author spleaner <ide> <ide> <ide> final StateStorageManager storageManager = projectStore.getStateStorageManager(); <del> for (String file : storageManager.getStorageFileNames()) { <add> final Collection<String> storageFileNames = new ArrayList<String>(storageManager.getStorageFileNames()); <add> for (String file : storageFileNames) { <ide> storageManager.clearStateStorage(file); <ide> } <ide>
JavaScript
apache-2.0
7465cc1ff9d4b227f1baf588105a588c7ec4e0c8
0
SQCLabs/openui5,cschuff/openui5,SAP/openui5,cschuff/openui5,SQCLabs/openui5,cschuff/openui5,SAP/openui5,nzamani/openui5,SAP/openui5,SAP/openui5,nzamani/openui5,SQCLabs/openui5,nzamani/openui5
sap.ui.define([ "sap/ui/core/UIComponent" ], function(UIComponent) { "use strict"; var Component = UIComponent.extend("sap.m.sample.UploadCollectionFolderHierarchy.Component", { metadata: { rootView: "sap.m.sample.UploadCollectionFolderHierarchy.Page", dependencies: { libs: ["sap.m", "sap.ui.unified"] }, config: { sample: { stretch: true, files: [ "Page.view.xml", "Page.controller.js", "UploadCollectionData.json" ] } } } }); return Component; });
src/sap.m/test/sap/m/demokit/sample/UploadCollectionFolderHierarchy/Component.js
sap.ui.define([ "sap/ui/core/UIComponent" ], function(UIComponent) { "use strict"; var Component = UIComponent.extend("sap.m.sample.UploadCollectionFolderHierarchy.Component", { metadata: { rootView: "sap.m.sample.UploadCollectionFolderHierarchy.Page", dependencies: { libs: ["sap.m", "sap.ui.unified"] }, config: { sample: { stretch: true, files: [ "Page.view.xml", "Page.controller.js" ] } } } }); return Component; });
[INTERNAL] sap.m.UploadCollection: JSON file added to Folder Hierarchy Explored sample Change-Id: I70830f4ef579f29880cf7a0afc1072efc60289da
src/sap.m/test/sap/m/demokit/sample/UploadCollectionFolderHierarchy/Component.js
[INTERNAL] sap.m.UploadCollection: JSON file added to Folder Hierarchy Explored sample
<ide><path>rc/sap.m/test/sap/m/demokit/sample/UploadCollectionFolderHierarchy/Component.js <ide> stretch: true, <ide> files: [ <ide> "Page.view.xml", <del> "Page.controller.js" <add> "Page.controller.js", <add> "UploadCollectionData.json" <ide> ] <ide> } <ide> }
Java
apache-2.0
f1b346522f53ff82ca88cc7c16e22d8f0c3da89a
0
Yaliang/presto,RobinUS2/presto,sopel39/presto,prestodb/presto,facebook/presto,troels/nz-presto,sumitkgec/presto,shixuan-fan/presto,mvp/presto,svstanev/presto,aramesh117/presto,svstanev/presto,electrum/presto,ptkool/presto,wagnermarkd/presto,miniway/presto,arhimondr/presto,11xor6/presto,electrum/presto,erichwang/presto,twitter-forks/presto,troels/nz-presto,mbeitchman/presto,ebyhr/presto,elonazoulay/presto,prateek1306/presto,hgschmie/presto,Yaliang/presto,Teradata/presto,Teradata/presto,hgschmie/presto,Yaliang/presto,troels/nz-presto,prestodb/presto,stewartpark/presto,treasure-data/presto,treasure-data/presto,ptkool/presto,miniway/presto,11xor6/presto,stewartpark/presto,wagnermarkd/presto,yuananf/presto,jxiang/presto,stewartpark/presto,mandusm/presto,twitter-forks/presto,nezihyigitbasi/presto,11xor6/presto,erichwang/presto,electrum/presto,yuananf/presto,elonazoulay/presto,nezihyigitbasi/presto,aramesh117/presto,sumitkgec/presto,sopel39/presto,miniway/presto,treasure-data/presto,elonazoulay/presto,troels/nz-presto,raghavsethi/presto,mandusm/presto,dain/presto,mbeitchman/presto,bloomberg/presto,prestodb/presto,troels/nz-presto,youngwookim/presto,erichwang/presto,facebook/presto,sopel39/presto,haozhun/presto,stewartpark/presto,zzhao0/presto,ebyhr/presto,mvp/presto,youngwookim/presto,losipiuk/presto,nezihyigitbasi/presto,RobinUS2/presto,haozhun/presto,raghavsethi/presto,arhimondr/presto,stewartpark/presto,nezihyigitbasi/presto,shixuan-fan/presto,svstanev/presto,Yaliang/presto,Praveen2112/presto,sumitkgec/presto,EvilMcJerkface/presto,zzhao0/presto,sumitkgec/presto,jiangyifangh/presto,elonazoulay/presto,jiangyifangh/presto,RobinUS2/presto,jiangyifangh/presto,dain/presto,gh351135612/presto,losipiuk/presto,youngwookim/presto,mbeitchman/presto,treasure-data/presto,damiencarol/presto,zzhao0/presto,EvilMcJerkface/presto,shixuan-fan/presto,losipiuk/presto,wagnermarkd/presto,aramesh117/presto,arhimondr/presto,mandusm/presto,arhimondr/presto,damiencarol/presto,mvp/presto,smartnews/presto,aramesh117/presto,youngwookim/presto,treasure-data/presto,shixuan-fan/presto,jxiang/presto,bloomberg/presto,martint/presto,martint/presto,wyukawa/presto,facebook/presto,haozhun/presto,facebook/presto,mandusm/presto,smartnews/presto,ptkool/presto,Praveen2112/presto,RobinUS2/presto,twitter-forks/presto,twitter-forks/presto,ptkool/presto,haozhun/presto,aramesh117/presto,arhimondr/presto,sopel39/presto,ebyhr/presto,shixuan-fan/presto,treasure-data/presto,youngwookim/presto,prestodb/presto,sopel39/presto,EvilMcJerkface/presto,miniway/presto,facebook/presto,Praveen2112/presto,prestodb/presto,bloomberg/presto,haozhun/presto,smartnews/presto,Teradata/presto,zzhao0/presto,yuananf/presto,wagnermarkd/presto,prestodb/presto,miniway/presto,prateek1306/presto,EvilMcJerkface/presto,mbeitchman/presto,elonazoulay/presto,smartnews/presto,gh351135612/presto,Yaliang/presto,wyukawa/presto,jiangyifangh/presto,Teradata/presto,damiencarol/presto,Praveen2112/presto,hgschmie/presto,prateek1306/presto,losipiuk/presto,prateek1306/presto,wagnermarkd/presto,dain/presto,EvilMcJerkface/presto,svstanev/presto,ebyhr/presto,martint/presto,losipiuk/presto,zzhao0/presto,gh351135612/presto,electrum/presto,smartnews/presto,jxiang/presto,raghavsethi/presto,jiangyifangh/presto,jxiang/presto,gh351135612/presto,Teradata/presto,svstanev/presto,nezihyigitbasi/presto,wyukawa/presto,mvp/presto,damiencarol/presto,yuananf/presto,wyukawa/presto,jxiang/presto,11xor6/presto,bloomberg/presto,mvp/presto,Praveen2112/presto,11xor6/presto,hgschmie/presto,ebyhr/presto,ptkool/presto,wyukawa/presto,martint/presto,hgschmie/presto,martint/presto,twitter-forks/presto,erichwang/presto,gh351135612/presto,damiencarol/presto,raghavsethi/presto,dain/presto,raghavsethi/presto,RobinUS2/presto,dain/presto,erichwang/presto,mandusm/presto,bloomberg/presto,prateek1306/presto,yuananf/presto,sumitkgec/presto,mbeitchman/presto,electrum/presto
/* * 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.facebook.presto.hive.metastore; import com.facebook.presto.hadoop.HadoopFileStatus; import com.facebook.presto.hive.HdfsEnvironment; import com.facebook.presto.hive.HiveType; import com.facebook.presto.hive.PartitionNotFoundException; import com.facebook.presto.hive.TableAlreadyExistsException; import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.SchemaTableName; import com.facebook.presto.spi.StandardErrorCode; import com.facebook.presto.spi.TableNotFoundException; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import io.airlift.concurrent.MoreFutures; import io.airlift.log.Logger; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import javax.annotation.concurrent.GuardedBy; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import static com.facebook.presto.hive.HiveErrorCode.HIVE_FILESYSTEM_ERROR; import static com.facebook.presto.hive.HiveErrorCode.HIVE_METASTORE_ERROR; import static com.facebook.presto.hive.HiveErrorCode.HIVE_PATH_ALREADY_EXISTS; import static com.facebook.presto.hive.HiveMetadata.PRESTO_QUERY_ID_NAME; import static com.facebook.presto.hive.HiveUtil.toPartitionValues; import static com.facebook.presto.hive.HiveWriteUtils.createDirectory; import static com.facebook.presto.hive.HiveWriteUtils.pathExists; import static com.facebook.presto.hive.metastore.HivePrivilegeInfo.HivePrivilege.OWNERSHIP; import static com.facebook.presto.spi.StandardErrorCode.ALREADY_EXISTS; import static com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED; import static com.facebook.presto.spi.StandardErrorCode.TRANSACTION_CONFLICT; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Verify.verify; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static org.apache.hadoop.hive.common.FileUtils.makePartName; import static org.apache.hadoop.hive.metastore.TableType.MANAGED_TABLE; public class SemiTransactionalHiveMetastore { private static final Logger log = Logger.get(SemiTransactionalHiveMetastore.class); private static final int PARTITION_COMMIT_BATCH_SIZE = 8; private final ExtendedHiveMetastore delegate; private final HdfsEnvironment hdfsEnvironment; private final Executor renameExecutor; private final boolean skipDeletionForAlter; @GuardedBy("this") private final Map<SchemaTableName, Action<TableAndMore>> tableActions = new HashMap<>(); @GuardedBy("this") private final Map<SchemaTableName, Map<List<String>, Action<PartitionAndMore>>> partitionActions = new HashMap<>(); @GuardedBy("this") private final List<DeclaredIntentionToWrite> declaredIntentionsToWrite = new ArrayList<>(); @GuardedBy("this") private ExclusiveOperation bufferedExclusiveOperation; @GuardedBy("this") private State state = State.EMPTY; private boolean throwOnCleanupFailure = false; public SemiTransactionalHiveMetastore(HdfsEnvironment hdfsEnvironment, ExtendedHiveMetastore delegate, Executor renameExecutor, boolean skipDeletionForAlter) { this.hdfsEnvironment = requireNonNull(hdfsEnvironment, "hdfsEnvironment is null"); this.delegate = requireNonNull(delegate, "delegate is null"); this.renameExecutor = requireNonNull(renameExecutor, "renameExecutor is null"); this.skipDeletionForAlter = requireNonNull(skipDeletionForAlter, "skipDeletionForAlter is null"); } public synchronized List<String> getAllDatabases() { checkReadable(); return delegate.getAllDatabases(); } public synchronized Optional<Database> getDatabase(String databaseName) { checkReadable(); return delegate.getDatabase(databaseName); } public synchronized Optional<List<String>> getAllTables(String databaseName) { checkReadable(); if (!tableActions.isEmpty()) { throw new UnsupportedOperationException("Listing all tables after adding/dropping/altering tables/views in a transaction is not supported"); } return delegate.getAllTables(databaseName); } public synchronized Optional<Table> getTable(String databaseName, String tableName) { checkReadable(); Action<TableAndMore> tableAction = tableActions.get(new SchemaTableName(databaseName, tableName)); if (tableAction == null) { return delegate.getTable(databaseName, tableName); } switch (tableAction.getType()) { case ADD: case ALTER: case INSERT_EXISTING: return Optional.of(tableAction.getData().getTable()); case DROP: return Optional.empty(); default: throw new IllegalStateException("Unknown action type"); } } /** * This method can only be called when the table is known to exist */ @GuardedBy("this") private TableSource getTableSource(String databaseName, String tableName) { checkHoldsLock(); checkReadable(); Action<TableAndMore> tableAction = tableActions.get(new SchemaTableName(databaseName, tableName)); if (tableAction == null) { return TableSource.PRE_EXISTING_TABLE; } switch (tableAction.getType()) { case ADD: return TableSource.CREATED_IN_THIS_TRANSACTION; case ALTER: throw new IllegalStateException("Tables are never altered in the current implementation"); case DROP: throw new TableNotFoundException(new SchemaTableName(databaseName, tableName)); case INSERT_EXISTING: return TableSource.PRE_EXISTING_TABLE; default: throw new IllegalStateException("Unknown action type"); } } public synchronized HivePageSinkMetadata generatePageSinkMetadata(SchemaTableName schemaTableName) { checkReadable(); Optional<Table> table = getTable(schemaTableName.getSchemaName(), schemaTableName.getTableName()); if (!table.isPresent()) { return new HivePageSinkMetadata(schemaTableName, Optional.empty(), ImmutableMap.of()); } Map<List<String>, Action<PartitionAndMore>> partitionActionMap = partitionActions.get(schemaTableName); Map<List<String>, Optional<Partition>> modifiedPartitionMap; if (partitionActionMap == null) { modifiedPartitionMap = ImmutableMap.of(); } else { ImmutableMap.Builder<List<String>, Optional<Partition>> modifiedPartitionMapBuilder = ImmutableMap.builder(); for (Map.Entry<List<String>, Action<PartitionAndMore>> entry : partitionActionMap.entrySet()) { modifiedPartitionMapBuilder.put(entry.getKey(), getPartitionFromPartitionAction(entry.getValue())); } modifiedPartitionMap = modifiedPartitionMapBuilder.build(); } return new HivePageSinkMetadata( schemaTableName, table, modifiedPartitionMap); } public synchronized Optional<List<String>> getAllViews(String databaseName) { checkReadable(); if (!tableActions.isEmpty()) { throw new UnsupportedOperationException("Listing all tables after adding/dropping/altering tables/views in a transaction is not supported"); } return delegate.getAllViews(databaseName); } public synchronized void createDatabase(Database database) { setExclusive((delegate, hdfsEnvironment) -> delegate.createDatabase(database)); } public synchronized void dropDatabase(String schemaName) { setExclusive((delegate, hdfsEnvironment) -> delegate.dropDatabase(schemaName)); } public synchronized void renameDatabase(String source, String target) { setExclusive((delegate, hdfsEnvironment) -> delegate.renameDatabase(source, target)); } /** * {@code currentLocation} needs to be supplied if a writePath exists for the table. */ public synchronized void createTable(ConnectorSession session, Table table, PrincipalPrivileges principalPrivileges, Optional<Path> currentPath) { setShared(); // When creating a table, it should never have partition actions. This is just a sanity check. checkNoPartitionAction(table.getDatabaseName(), table.getTableName()); SchemaTableName schemaTableName = new SchemaTableName(table.getDatabaseName(), table.getTableName()); Action<TableAndMore> oldTableAction = tableActions.get(schemaTableName); TableAndMore tableAndMore = new TableAndMore(table, Optional.of(principalPrivileges), currentPath, Optional.empty()); if (oldTableAction == null) { tableActions.put(schemaTableName, new Action<>(ActionType.ADD, tableAndMore, session.getUser(), session.getQueryId())); return; } switch (oldTableAction.getType()) { case DROP: throw new PrestoException(TRANSACTION_CONFLICT, "Dropping and then recreating the same table in a transaction is not supported"); case ADD: case ALTER: case INSERT_EXISTING: throw new TableAlreadyExistsException(schemaTableName); default: throw new IllegalStateException("Unknown action type"); } } public synchronized void dropTable(ConnectorSession session, String databaseName, String tableName) { setShared(); // Dropping table with partition actions requires cleaning up staging data, which is not implemented yet. checkNoPartitionAction(databaseName, tableName); SchemaTableName schemaTableName = new SchemaTableName(databaseName, tableName); Action<TableAndMore> oldTableAction = tableActions.get(schemaTableName); if (oldTableAction == null || oldTableAction.getType() == ActionType.ALTER) { tableActions.put(schemaTableName, new Action<>(ActionType.DROP, null, session.getUser(), session.getQueryId())); return; } switch (oldTableAction.getType()) { case DROP: throw new TableNotFoundException(schemaTableName); case ADD: case ALTER: case INSERT_EXISTING: throw new UnsupportedOperationException("dropping a table added/modified in the same transaction is not supported"); default: throw new IllegalStateException("Unknown action type"); } } public synchronized void replaceView(String databaseName, String tableName, Table table, PrincipalPrivileges principalPrivileges) { setExclusive((delegate, hdfsEnvironment) -> delegate.replaceTable(databaseName, tableName, table, principalPrivileges)); } public synchronized void renameTable(String databaseName, String tableName, String newDatabaseName, String newTableName) { setExclusive((delegate, hdfsEnvironment) -> delegate.renameTable(databaseName, tableName, newDatabaseName, newTableName)); } public synchronized void addColumn(String databaseName, String tableName, String columnName, HiveType columnType, String columnComment) { setExclusive((delegate, hdfsEnvironment) -> delegate.addColumn(databaseName, tableName, columnName, columnType, columnComment)); } public synchronized void renameColumn(String databaseName, String tableName, String oldColumnName, String newColumnName) { setExclusive((delegate, hdfsEnvironment) -> delegate.renameColumn(databaseName, tableName, oldColumnName, newColumnName)); } public synchronized void finishInsertIntoExistingTable(ConnectorSession session, String databaseName, String tableName, Path currentLocation, List<String> fileNames) { // Data can only be inserted into partitions and unpartitioned tables. They can never be inserted into a partitioned table. // Therefore, this method assumes that the table is unpartitioned. setShared(); SchemaTableName schemaTableName = new SchemaTableName(databaseName, tableName); Action<TableAndMore> oldTableAction = tableActions.get(schemaTableName); if (oldTableAction == null) { Optional<Table> table = delegate.getTable(databaseName, tableName); if (!table.isPresent()) { throw new TableNotFoundException(schemaTableName); } tableActions.put( schemaTableName, new Action<>( ActionType.INSERT_EXISTING, new TableAndMore(table.get(), Optional.empty(), Optional.of(currentLocation), Optional.of(fileNames)), session.getUser(), session.getQueryId())); return; } switch (oldTableAction.getType()) { case DROP: throw new TableNotFoundException(schemaTableName); case ADD: case ALTER: case INSERT_EXISTING: throw new UnsupportedOperationException("Inserting into an unpartitioned table that were added, altered, or inserted into in the same transaction is not supported"); default: throw new IllegalStateException("Unknown action type"); } } public synchronized void truncateUnpartitionedTable(ConnectorSession session, String databaseName, String tableName) { checkReadable(); Optional<Table> table = getTable(databaseName, tableName); SchemaTableName schemaTableName = new SchemaTableName(databaseName, tableName); if (!table.isPresent()) { throw new TableNotFoundException(schemaTableName); } if (!table.get().getTableType().equals(MANAGED_TABLE.toString())) { throw new PrestoException(NOT_SUPPORTED, "Cannot delete from non-managed Hive table"); } if (!table.get().getPartitionColumns().isEmpty()) { throw new IllegalArgumentException("Table is partitioned"); } Path path = new Path(table.get().getStorage().getLocation()); String user = session.getUser(); setExclusive((delegate, hdfsEnvironment) -> { RecursiveDeleteResult recursiveDeleteResult = recursiveDeleteFiles(hdfsEnvironment, user, path, ImmutableList.of(""), false); if (!recursiveDeleteResult.getNotDeletedEligibleItems().isEmpty()) { throw new PrestoException(HIVE_FILESYSTEM_ERROR, format( "Error deleting from unpartitioned table %s. These items can not be deleted: %s", schemaTableName, recursiveDeleteResult.getNotDeletedEligibleItems())); } }); } public synchronized Optional<List<String>> getPartitionNames(String databaseName, String tableName) { return doGetPartitionNames(databaseName, tableName, Optional.empty()); } public synchronized Optional<List<String>> getPartitionNamesByParts(String databaseName, String tableName, List<String> parts) { return doGetPartitionNames(databaseName, tableName, Optional.of(parts)); } @GuardedBy("this") private Optional<List<String>> doGetPartitionNames(String databaseName, String tableName, Optional<List<String>> parts) { checkHoldsLock(); checkReadable(); Optional<Table> table = getTable(databaseName, tableName); if (!table.isPresent()) { return Optional.empty(); } List<String> partitionNames; TableSource tableSource = getTableSource(databaseName, tableName); switch (tableSource) { case CREATED_IN_THIS_TRANSACTION: partitionNames = ImmutableList.of(); break; case PRE_EXISTING_TABLE: { Optional<List<String>> partitionNameResult; if (parts.isPresent()) { partitionNameResult = delegate.getPartitionNamesByParts(databaseName, tableName, parts.get()); } else { partitionNameResult = delegate.getPartitionNames(databaseName, tableName); } if (!partitionNameResult.isPresent()) { throw new PrestoException(TRANSACTION_CONFLICT, "Table %s.%s was dropped by another transaction"); } partitionNames = partitionNameResult.get(); break; } default: throw new UnsupportedOperationException("Unknown table source"); } Map<List<String>, Action<PartitionAndMore>> partitionActionsOfTable = partitionActions.computeIfAbsent(new SchemaTableName(databaseName, tableName), k -> new HashMap<>()); ImmutableList.Builder<String> resultBuilder = ImmutableList.builder(); // alter/remove newly-altered/dropped partitions from the results from underlying metastore for (String partitionName : partitionNames) { List<String> partitionValues = toPartitionValues(partitionName); Action<PartitionAndMore> partitionAction = partitionActionsOfTable.get(partitionValues); if (partitionAction == null) { resultBuilder.add(partitionName); continue; } switch (partitionAction.getType()) { case ADD: throw new PrestoException(TRANSACTION_CONFLICT, format("Another transaction created partition %s in table %s.%s", partitionValues, databaseName, tableName)); case DROP: // do nothing break; case ALTER: case INSERT_EXISTING: resultBuilder.add(partitionName); break; default: throw new IllegalStateException("Unknown action type"); } } // add newly-added partitions to the results from underlying metastore if (!partitionActionsOfTable.isEmpty()) { List<String> columnNames = table.get().getPartitionColumns().stream().map(Column::getName).collect(Collectors.toList()); for (Action<PartitionAndMore> partitionAction : partitionActionsOfTable.values()) { if (partitionAction.getType() == ActionType.ADD) { List<String> values = partitionAction.getData().getPartition().getValues(); if (!parts.isPresent() || partitionValuesMatch(values, parts.get())) { resultBuilder.add(makePartName(columnNames, values)); } } } } return Optional.of(resultBuilder.build()); } private static boolean partitionValuesMatch(List<String> values, List<String> pattern) { checkArgument(values.size() == pattern.size()); for (int i = 0; i < values.size(); i++) { if (pattern.get(i).isEmpty()) { // empty string match everything continue; } if (values.get(i).equals(pattern.get(i))) { return false; } } return true; } public synchronized Optional<Partition> getPartition(String databaseName, String tableName, List<String> partitionValues) { checkReadable(); TableSource tableSource = getTableSource(databaseName, tableName); Map<List<String>, Action<PartitionAndMore>> partitionActionsOfTable = partitionActions.computeIfAbsent(new SchemaTableName(databaseName, tableName), k -> new HashMap<>()); Action<PartitionAndMore> partitionAction = partitionActionsOfTable.get(partitionValues); if (partitionAction != null) { return getPartitionFromPartitionAction(partitionAction); } switch (tableSource) { case PRE_EXISTING_TABLE: return delegate.getPartition(databaseName, tableName, partitionValues); case CREATED_IN_THIS_TRANSACTION: return Optional.empty(); default: throw new UnsupportedOperationException("unknown table source"); } } public synchronized Map<String, Optional<Partition>> getPartitionsByNames(String databaseName, String tableName, List<String> partitionNames) { checkReadable(); TableSource tableSource = getTableSource(databaseName, tableName); Map<List<String>, Action<PartitionAndMore>> partitionActionsOfTable = partitionActions.computeIfAbsent(new SchemaTableName(databaseName, tableName), k -> new HashMap<>()); ImmutableList.Builder<String> partitionNamesToQuery = ImmutableList.builder(); ImmutableMap.Builder<String, Optional<Partition>> resultBuilder = ImmutableMap.builder(); for (String partitionName : partitionNames) { List<String> partitionValues = toPartitionValues(partitionName); Action<PartitionAndMore> partitionAction = partitionActionsOfTable.get(partitionValues); if (partitionAction == null) { switch (tableSource) { case PRE_EXISTING_TABLE: partitionNamesToQuery.add(partitionName); break; case CREATED_IN_THIS_TRANSACTION: resultBuilder.put(partitionName, Optional.empty()); break; default: throw new UnsupportedOperationException("unknown table source"); } } else { resultBuilder.put(partitionName, getPartitionFromPartitionAction(partitionAction)); } } Map<String, Optional<Partition>> delegateResult = delegate.getPartitionsByNames(databaseName, tableName, partitionNamesToQuery.build()); resultBuilder.putAll(delegateResult); return resultBuilder.build(); } private static Optional<Partition> getPartitionFromPartitionAction(Action<PartitionAndMore> partitionAction) { switch (partitionAction.getType()) { case ADD: case ALTER: case INSERT_EXISTING: return Optional.of(partitionAction.getData().getAugmentedPartitionForInTransactionRead()); case DROP: return Optional.empty(); default: throw new IllegalStateException("Unknown action type"); } } public synchronized void addPartition(ConnectorSession session, String databaseName, String tableName, Partition partition, Path currentLocation) { setShared(); checkArgument(getPrestoQueryId(partition).isPresent()); Map<List<String>, Action<PartitionAndMore>> partitionActionsOfTable = partitionActions.computeIfAbsent(new SchemaTableName(databaseName, tableName), k -> new HashMap<>()); Action<PartitionAndMore> oldPartitionAction = partitionActionsOfTable.get(partition.getValues()); if (oldPartitionAction == null) { partitionActionsOfTable.put( partition.getValues(), new Action<>(ActionType.ADD, new PartitionAndMore(partition, currentLocation, Optional.empty()), session.getUser(), session.getQueryId())); return; } switch (oldPartitionAction.getType()) { case DROP: { if (!oldPartitionAction.getUser().equals(session.getUser())) { throw new PrestoException(TRANSACTION_CONFLICT, "Operation on the same partition with different user in the same transaction is not supported"); } partitionActionsOfTable.put( partition.getValues(), new Action<>(ActionType.ALTER, new PartitionAndMore(partition, currentLocation, Optional.empty()), session.getUser(), session.getQueryId())); break; } case ADD: case ALTER: case INSERT_EXISTING: throw new PrestoException(ALREADY_EXISTS, format("Partition already exists for table '%s.%s': %s", databaseName, tableName, partition.getValues())); default: throw new IllegalStateException("Unknown action type"); } } public synchronized void dropPartition(ConnectorSession session, String databaseName, String tableName, List<String> partitionValues) { setShared(); Map<List<String>, Action<PartitionAndMore>> partitionActionsOfTable = partitionActions.computeIfAbsent(new SchemaTableName(databaseName, tableName), k -> new HashMap<>()); Action<PartitionAndMore> oldPartitionAction = partitionActionsOfTable.get(partitionValues); if (oldPartitionAction == null) { partitionActionsOfTable.put(partitionValues, new Action<>(ActionType.DROP, null, session.getUser(), session.getQueryId())); return; } switch (oldPartitionAction.getType()) { case DROP: throw new PartitionNotFoundException(new SchemaTableName(databaseName, tableName), partitionValues); case ADD: case ALTER: case INSERT_EXISTING: throw new PrestoException( NOT_SUPPORTED, format("dropping a partition added in the same transaction is not supported: %s %s %s", databaseName, tableName, partitionValues)); default: throw new IllegalStateException("Unknown action type"); } } public synchronized void finishInsertIntoExistingPartition(ConnectorSession session, String databaseName, String tableName, List<String> partitionValues, Path currentLocation, List<String> fileNames) { setShared(); SchemaTableName schemaTableName = new SchemaTableName(databaseName, tableName); Map<List<String>, Action<PartitionAndMore>> partitionActionsOfTable = partitionActions.computeIfAbsent(schemaTableName, k -> new HashMap<>()); Action<PartitionAndMore> oldPartitionAction = partitionActionsOfTable.get(partitionValues); if (oldPartitionAction == null) { Optional<Partition> partition = delegate.getPartition(databaseName, tableName, partitionValues); if (!partition.isPresent()) { throw new PartitionNotFoundException(schemaTableName, partitionValues); } partitionActionsOfTable.put( partitionValues, new Action<>(ActionType.INSERT_EXISTING, new PartitionAndMore(partition.get(), currentLocation, Optional.of(fileNames)), session.getUser(), session.getQueryId())); return; } switch (oldPartitionAction.getType()) { case DROP: throw new PartitionNotFoundException(schemaTableName, partitionValues); case ADD: case ALTER: case INSERT_EXISTING: throw new UnsupportedOperationException("Inserting into a partition that were added, altered, or inserted into in the same transaction is not supported"); default: throw new IllegalStateException("Unknown action type"); } } public synchronized Set<String> getRoles(String user) { checkReadable(); return delegate.getRoles(user); } public synchronized Set<HivePrivilegeInfo> getDatabasePrivileges(String user, String databaseName) { checkReadable(); return delegate.getDatabasePrivileges(user, databaseName); } public synchronized Set<HivePrivilegeInfo> getTablePrivileges(String user, String databaseName, String tableName) { checkReadable(); SchemaTableName schemaTableName = new SchemaTableName(databaseName, tableName); Action<TableAndMore> tableAction = tableActions.get(schemaTableName); if (tableAction == null) { return delegate.getTablePrivileges(user, databaseName, tableName); } switch (tableAction.getType()) { case ADD: case ALTER: { if (!user.equals(tableAction.getData().getTable().getOwner())) { throw new PrestoException(NOT_SUPPORTED, "Cannot access a table newly created in the transaction with a different user"); } Collection<HivePrivilegeInfo> privileges = tableAction.getData().getPrincipalPrivileges().getUserPrivileges().get(user); return ImmutableSet.<HivePrivilegeInfo>builder() .addAll(privileges) .add(new HivePrivilegeInfo(OWNERSHIP, true)) .build(); } case INSERT_EXISTING: return delegate.getTablePrivileges(user, databaseName, tableName); case DROP: throw new TableNotFoundException(schemaTableName); default: throw new IllegalStateException("Unknown action type"); } } public synchronized void grantTablePrivileges(String databaseName, String tableName, String grantee, Set<HivePrivilegeInfo> privileges) { setExclusive((delegate, hdfsEnvironment) -> delegate.grantTablePrivileges(databaseName, tableName, grantee, privileges)); } public synchronized void revokeTablePrivileges(String databaseName, String tableName, String grantee, Set<HivePrivilegeInfo> privileges) { setExclusive((delegate, hdfsEnvironment) -> delegate.revokeTablePrivileges(databaseName, tableName, grantee, privileges)); } public synchronized void declareIntentionToWrite(ConnectorSession session, WriteMode writeMode, Path stagingPathRoot, String filePrefix, SchemaTableName schemaTableName) { setShared(); if (writeMode == WriteMode.DIRECT_TO_TARGET_EXISTING_DIRECTORY) { Map<List<String>, Action<PartitionAndMore>> partitionActionsOfTable = partitionActions.get(schemaTableName); if (partitionActionsOfTable != null && !partitionActionsOfTable.isEmpty()) { throw new PrestoException(NOT_SUPPORTED, "Can not insert into a table with a partition that has been modified in the same transaction when Presto is configured to skip temporary directories."); } } declaredIntentionsToWrite.add(new DeclaredIntentionToWrite(writeMode, session.getUser(), stagingPathRoot, filePrefix, schemaTableName)); } public synchronized void commit() { try { switch (state) { case EMPTY: break; case SHARED_OPERATION_BUFFERED: commitShared(); break; case EXCLUSIVE_OPERATION_BUFFERED: requireNonNull(bufferedExclusiveOperation, "bufferedExclusiveOperation is null"); bufferedExclusiveOperation.execute(delegate, hdfsEnvironment); break; case FINISHED: throw new IllegalStateException("Tried to commit buffered metastore operations after transaction has been committed/aborted"); default: throw new IllegalStateException("Unknown state"); } } finally { state = State.FINISHED; } } public synchronized void rollback() { try { switch (state) { case EMPTY: case EXCLUSIVE_OPERATION_BUFFERED: break; case SHARED_OPERATION_BUFFERED: rollbackShared(); break; case FINISHED: throw new IllegalStateException("Tried to rollback buffered metastore operations after transaction has been committed/aborted"); default: throw new IllegalStateException("Unknown state"); } } finally { state = State.FINISHED; } } @GuardedBy("this") private void commitShared() { checkHoldsLock(); Committer committer = new Committer(); try { for (Map.Entry<SchemaTableName, Action<TableAndMore>> entry : tableActions.entrySet()) { SchemaTableName schemaTableName = entry.getKey(); Action<TableAndMore> action = entry.getValue(); switch (action.getType()) { case DROP: committer.prepareDropTable(schemaTableName); break; case ALTER: committer.prepareAlterTable(); break; case ADD: committer.prepareAddTable(action.getUser(), action.getData()); break; case INSERT_EXISTING: committer.prepareInsertExistingTable(action.getUser(), action.getData()); break; default: throw new IllegalStateException("Unknown action type"); } } for (Map.Entry<SchemaTableName, Map<List<String>, Action<PartitionAndMore>>> tableEntry : partitionActions.entrySet()) { SchemaTableName schemaTableName = tableEntry.getKey(); for (Map.Entry<List<String>, Action<PartitionAndMore>> partitionEntry : tableEntry.getValue().entrySet()) { List<String> partitionValues = partitionEntry.getKey(); Action<PartitionAndMore> action = partitionEntry.getValue(); switch (action.getType()) { case DROP: committer.prepareDropPartition(schemaTableName, partitionValues); break; case ALTER: committer.prepareAlterPartition(action.getQueryId(), action.getUser(), action.getData()); break; case ADD: committer.prepareAddPartition(action.getUser(), action.getData()); break; case INSERT_EXISTING: committer.prepareInsertExistingPartition(action.getUser(), action.getData()); break; default: throw new IllegalStateException("Unknown action type"); } } } // Wait for all renames submitted for "INSERT_EXISTING" action to finish committer.waitForAsyncRenames(); // At this point, all file system operations, whether asynchronously issued or not, have completed successfully. // We are moving on to metastore operations now. committer.executeAddTableOperations(); committer.executeAlterPartitionOperations(); committer.executeAddPartitionOperations(); } catch (Throwable t) { committer.cancelUnstartedAsyncRenames(); committer.undoAddPartitionOperations(); committer.undoAddTableOperations(); committer.waitForAsyncRenamesSuppressThrowables(); // fileRenameFutures must all come back before any file system cleanups are carried out. // Otherwise, files that should be deleted may be created after cleanup is done. committer.executeCleanupTasksForAbort(committer.extractFilePrefixes(declaredIntentionsToWrite)); committer.executeRenameTasksForAbort(); // Partition directory must be put back before relevant metastore operation can be undone committer.undoAlterPartitionOperations(); rollbackShared(); throw t; } try { // After this line, operations are no longer reversible. // The next section will deal with "dropping table/partition". Commit may still fail in // this section. Even if commit fails, cleanups, instead of rollbacks, will be executed. committer.executeIrreversibleMetastoreOperations(); // If control flow reached this point, this commit is considered successful no matter // what happens later. The only kind of operations that haven't been carried out yet // are cleanups. // The program control flow will go to finally next. And cleanup will run because // moveForwardInFinally has been set to false. } finally { // In this method, all operations are best-effort clean up operations. // If any operation fails, the error will be logged and ignored. // Additionally, other clean up operations should still be attempted. // Execute deletion tasks committer.executeDeletionTasksForFinish(); // Clean up empty staging directories (that may recursively contain empty directories) committer.deleteEmptyStagingDirectories(declaredIntentionsToWrite); } } private class Committer { private final AtomicBoolean fileRenameCancelled = new AtomicBoolean(false); private final List<CompletableFuture<?>> fileRenameFutures = new ArrayList<>(); // File system // For file system changes, only operations outside of writing paths (as specified in declared intentions to write) // need to MOVE_BACKWARD tasks scheduled. Files in writing paths are handled by rollbackShared(). private final List<DirectoryDeletionTask> deletionTasksForFinish = new ArrayList<>(); private final List<DirectoryCleanUpTask> cleanUpTasksForAbort = new ArrayList<>(); private final List<DirectoryRenameTask> renameTasksForAbort = new ArrayList<>(); // Metastore private final List<CreateTableOperation> addTableOperations = new ArrayList<>(); private final Map<SchemaTableName, PartitionAdder> partitionAdders = new HashMap<>(); private final List<AlterPartitionOperation> alterPartitionOperations = new ArrayList<>(); private final List<IrreversibleMetastoreOperation> metastoreDeleteOperations = new ArrayList<>(); private void prepareDropTable(SchemaTableName schemaTableName) { metastoreDeleteOperations.add(new IrreversibleMetastoreOperation( format("drop table %s", schemaTableName), () -> delegate.dropTable(schemaTableName.getSchemaName(), schemaTableName.getTableName(), true))); } private void prepareAlterTable() { // Currently, ALTER action is never constructed for tables. Dropping a table and then re-creating it // in the same transaction is not supported now. The following line should be replaced with actual // implementation when create after drop support is introduced for a table. throw new UnsupportedOperationException("Dropping and then creating a table with the same name is not supported"); } private void prepareAddTable(String user, TableAndMore tableAndMore) { Table table = tableAndMore.getTable(); if (table.getTableType().equals(MANAGED_TABLE.name())) { String targetLocation = table.getStorage().getLocation(); checkArgument(!targetLocation.isEmpty(), "target location is empty"); Optional<Path> currentPath = tableAndMore.getCurrentLocation(); Path targetPath = new Path(targetLocation); if (table.getPartitionColumns().isEmpty() && currentPath.isPresent()) { // CREATE TABLE AS SELECT unpartitioned table if (targetPath.equals(currentPath.get())) { // Target path and current path are the same. Therefore, directory move is not needed. } else { renameDirectory( user, hdfsEnvironment, currentPath.get(), targetPath, () -> cleanUpTasksForAbort.add(new DirectoryCleanUpTask(user, targetPath, true))); } } else { // CREATE TABLE AS SELECT partitioned table, or // CREATE TABLE partitioned/unpartitioned table (without data) if (pathExists(user, hdfsEnvironment, targetPath)) { if (currentPath.isPresent() && currentPath.get().equals(targetPath)) { // It is okay to skip directory creation when currentPath is equal to targetPath // because the directory may have been created when creating partition directories. // However, it is important to note that the two being equal does not guarantee // a directory had been created. } else { throw new PrestoException( HIVE_PATH_ALREADY_EXISTS, format("Unable to create directory %s: target directory already exists", targetPath)); } } else { cleanUpTasksForAbort.add(new DirectoryCleanUpTask(user, targetPath, true)); createDirectory(user, hdfsEnvironment, targetPath); } } } addTableOperations.add(new CreateTableOperation(table, tableAndMore.getPrincipalPrivileges())); } private void prepareInsertExistingTable(String user, TableAndMore tableAndMore) { Table table = tableAndMore.getTable(); Path targetPath = new Path(table.getStorage().getLocation()); Path currentPath = tableAndMore.getCurrentLocation().get(); cleanUpTasksForAbort.add(new DirectoryCleanUpTask(user, targetPath, false)); if (!targetPath.equals(currentPath)) { asyncRename(hdfsEnvironment, renameExecutor, fileRenameCancelled, fileRenameFutures, user, currentPath, targetPath, tableAndMore.getFileNames().get()); } } private void prepareDropPartition(SchemaTableName schemaTableName, List<String> partitionValues) { metastoreDeleteOperations.add(new IrreversibleMetastoreOperation( format("drop partition %s.%s %s", schemaTableName, schemaTableName.getTableName(), partitionValues), () -> delegate.dropPartition(schemaTableName.getSchemaName(), schemaTableName.getTableName(), partitionValues, true))); } private void prepareAlterPartition(String queryId, String user, PartitionAndMore partitionAndMore) { Partition partition = partitionAndMore.getPartition(); String targetLocation = partition.getStorage().getLocation(); Optional<Partition> oldPartition = delegate.getPartition(partition.getDatabaseName(), partition.getTableName(), partition.getValues()); if (!oldPartition.isPresent()) { throw new PrestoException( TRANSACTION_CONFLICT, format("The partition that this transaction modified was deleted in another transaction. %s %s", partition.getTableName(), partition.getValues())); } String oldPartitionLocation = oldPartition.get().getStorage().getLocation(); Path oldPartitionPath = new Path(oldPartitionLocation); // Location of the old partition and the new partition can be different because we allow arbitrary directories through LocationService. // If the location of the old partition is the same as the location of the new partition: // * Rename the old data directory to a temporary path with a special suffix // * Remember we will need to delete that directory at the end if transaction successfully commits // * Remember we will need to undo the rename if transaction aborts // Otherwise, // * Remember we will need to delete the location of the old partition at the end if transaction successfully commits if (targetLocation.equals(oldPartitionLocation)) { Path oldPartitionStagingPath = new Path(oldPartitionPath.getParent(), "_temp_" + oldPartitionPath.getName() + "_" + queryId); renameDirectory( user, hdfsEnvironment, oldPartitionPath, oldPartitionStagingPath, () -> renameTasksForAbort.add(new DirectoryRenameTask(user, oldPartitionStagingPath, oldPartitionPath))); if (!skipDeletionForAlter) { deletionTasksForFinish.add(new DirectoryDeletionTask(user, oldPartitionStagingPath)); } } else { if (!skipDeletionForAlter) { deletionTasksForFinish.add(new DirectoryDeletionTask(user, oldPartitionPath)); } } Path currentPath = partitionAndMore.getCurrentLocation(); Path targetPath = new Path(targetLocation); if (!targetPath.equals(currentPath)) { renameDirectory( user, hdfsEnvironment, currentPath, targetPath, () -> cleanUpTasksForAbort.add(new DirectoryCleanUpTask(user, targetPath, true))); } // Partition alter must happen regardless of whether original and current location is the same // because metadata might change: e.g. storage format, column types, etc alterPartitionOperations.add(new AlterPartitionOperation(partition, oldPartition.get())); } private void prepareAddPartition(String user, PartitionAndMore partitionAndMore) { Partition partition = partitionAndMore.getPartition(); String targetLocation = partition.getStorage().getLocation(); Path currentPath = partitionAndMore.getCurrentLocation(); Path targetPath = new Path(targetLocation); SchemaTableName schemaTableName = new SchemaTableName(partition.getDatabaseName(), partition.getTableName()); PartitionAdder partitionAdder = partitionAdders.computeIfAbsent( schemaTableName, ignored -> new PartitionAdder(partition.getDatabaseName(), partition.getTableName(), delegate, PARTITION_COMMIT_BATCH_SIZE)); if (!targetPath.equals(currentPath)) { renameDirectory( user, hdfsEnvironment, currentPath, targetPath, () -> cleanUpTasksForAbort.add(new DirectoryCleanUpTask(user, targetPath, true))); } partitionAdder.addPartition(partition); } private void prepareInsertExistingPartition(String user, PartitionAndMore partitionAndMore) { Partition partition = partitionAndMore.getPartition(); Path targetPath = new Path(partition.getStorage().getLocation()); Path currentPath = partitionAndMore.getCurrentLocation(); cleanUpTasksForAbort.add(new DirectoryCleanUpTask(user, targetPath, false)); if (!targetPath.equals(currentPath)) { asyncRename(hdfsEnvironment, renameExecutor, fileRenameCancelled, fileRenameFutures, user, currentPath, targetPath, partitionAndMore.getFileNames()); } } private void executeCleanupTasksForAbort(List<String> filePrefixes) { for (DirectoryCleanUpTask cleanUpTask : cleanUpTasksForAbort) { recursiveDeleteFilesAndLog(cleanUpTask.getUser(), cleanUpTask.getPath(), filePrefixes, cleanUpTask.isDeleteEmptyDirectory(), "temporary directory commit abort"); } } private void executeDeletionTasksForFinish() { for (DirectoryDeletionTask deletionTask : deletionTasksForFinish) { if (!deleteRecursivelyIfExists(deletionTask.getUser(), hdfsEnvironment, deletionTask.getPath())) { logCleanupFailure("Error deleting directory %s", deletionTask.getPath().toString()); } } } private void executeRenameTasksForAbort() { for (DirectoryRenameTask directoryRenameTask : renameTasksForAbort) { try { // Ignore the task if the source directory doesn't exist. // This is probably because the original rename that we are trying to undo here never succeeded. if (pathExists(directoryRenameTask.getUser(), hdfsEnvironment, directoryRenameTask.getRenameFrom())) { renameDirectory(directoryRenameTask.getUser(), hdfsEnvironment, directoryRenameTask.getRenameFrom(), directoryRenameTask.getRenameTo(), () -> { }); } } catch (Throwable throwable) { logCleanupFailure(throwable, "failed to undo rename of partition directory: %s to %s", directoryRenameTask.getRenameFrom(), directoryRenameTask.getRenameTo()); } } } private void deleteEmptyStagingDirectories(List<DeclaredIntentionToWrite> declaredIntentionsToWrite) { for (DeclaredIntentionToWrite declaredIntentionToWrite : declaredIntentionsToWrite) { if (declaredIntentionToWrite.getMode() != WriteMode.STAGE_AND_MOVE_TO_TARGET_DIRECTORY) { continue; } Path path = declaredIntentionToWrite.getRootPath(); recursiveDeleteFilesAndLog(declaredIntentionToWrite.getUser(), path, ImmutableList.of(), true, "staging directory cleanup"); } } private void waitForAsyncRenames() { for (CompletableFuture<?> fileRenameFuture : fileRenameFutures) { MoreFutures.getFutureValue(fileRenameFuture, PrestoException.class); } } private void waitForAsyncRenamesSuppressThrowables() { for (CompletableFuture<?> future : fileRenameFutures) { try { future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Throwable t) { // ignore } } } private void cancelUnstartedAsyncRenames() { fileRenameCancelled.set(true); } private void executeAddTableOperations() { for (CreateTableOperation addTableOperation : addTableOperations) { addTableOperation.run(delegate); } } private void executeAlterPartitionOperations() { for (AlterPartitionOperation alterPartitionOperation : alterPartitionOperations) { alterPartitionOperation.run(delegate); } } private void executeAddPartitionOperations() { for (PartitionAdder partitionAdder : partitionAdders.values()) { partitionAdder.execute(); } } private void undoAddPartitionOperations() { for (PartitionAdder partitionAdder : partitionAdders.values()) { List<List<String>> partitionsFailedToRollback = partitionAdder.rollback(); if (!partitionsFailedToRollback.isEmpty()) { logCleanupFailure("Failed to rollback: add_partition for partitions %s.%s %s", partitionAdder.getSchemaName(), partitionAdder.getTableName(), partitionsFailedToRollback.stream()); } } } private void undoAddTableOperations() { for (CreateTableOperation addTableOperation : addTableOperations) { try { addTableOperation.undo(delegate); } catch (Throwable throwable) { logCleanupFailure(throwable, "failed to rollback: %s", addTableOperation.getDescription()); } } } private void undoAlterPartitionOperations() { for (AlterPartitionOperation alterPartitionOperation : alterPartitionOperations) { try { alterPartitionOperation.undo(delegate); } catch (Throwable throwable) { logCleanupFailure(throwable, "failed to rollback: %s", alterPartitionOperation.getDescription()); } } } private void executeIrreversibleMetastoreOperations() { List<String> failedIrreversibleOperationDescriptions = new ArrayList<>(); List<Throwable> suppressedExceptions = new ArrayList<>(); for (IrreversibleMetastoreOperation irreversibleMetastoreOperation : metastoreDeleteOperations) { try { irreversibleMetastoreOperation.run(); } catch (Throwable t) { failedIrreversibleOperationDescriptions.add(irreversibleMetastoreOperation.getDescription()); // A limit is needed to avoid having a huge exception object. 5 was chosen arbitrarily. if (suppressedExceptions.size() < 5) { suppressedExceptions.add(t); } } } if (!suppressedExceptions.isEmpty()) { PrestoException prestoException = new PrestoException( HIVE_METASTORE_ERROR, format( "The transaction didn't commit cleanly. Failed to execute some metastore delete operations: %s", failedIrreversibleOperationDescriptions.stream() .collect(Collectors.joining("; ")))); suppressedExceptions.forEach(prestoException::addSuppressed); throw prestoException; } } private List<String> extractFilePrefixes(List<DeclaredIntentionToWrite> declaredIntentionsToWrite) { Set<String> filePrefixSet = new HashSet<>(); for (DeclaredIntentionToWrite declaredIntentionToWrite : declaredIntentionsToWrite) { filePrefixSet.add(declaredIntentionToWrite.getFilePrefix()); } return ImmutableList.copyOf(filePrefixSet); } } @GuardedBy("this") private void rollbackShared() { checkHoldsLock(); for (DeclaredIntentionToWrite declaredIntentionToWrite : declaredIntentionsToWrite) { switch (declaredIntentionToWrite.getMode()) { case STAGE_AND_MOVE_TO_TARGET_DIRECTORY: case DIRECT_TO_TARGET_NEW_DIRECTORY: { // Note: there is no need to cleanup the target directory as it will only be written // to during the commit call and the commit call cleans up after failures. Path rootPath = declaredIntentionToWrite.getRootPath(); // In the case of DIRECT_TO_TARGET_NEW_DIRECTORY, if the directory is not guaranteed to be unique // for the query, it is possible that another query or compute engine may see the directory, wrote // data to it, and exported it through metastore. Therefore it may be argued that cleanup of staging // directories must be carried out conservatively. To be safe, we only delete files that start with // the unique prefix for queries in this transaction. recursiveDeleteFilesAndLog( declaredIntentionToWrite.getUser(), rootPath, ImmutableList.of(declaredIntentionToWrite.getFilePrefix()), true, format("staging/target_new directory rollback for table %s", declaredIntentionToWrite.getSchemaTableName())); break; } case DIRECT_TO_TARGET_EXISTING_DIRECTORY: { Set<Path> pathsToClean = new HashSet<>(); // Check the base directory of the declared intention // * existing partition may also be in this directory // * this is where new partitions are created Path baseDirectory = declaredIntentionToWrite.getRootPath(); pathsToClean.add(baseDirectory); SchemaTableName schemaTableName = declaredIntentionToWrite.getSchemaTableName(); Optional<Table> table = delegate.getTable(schemaTableName.getSchemaName(), schemaTableName.getTableName()); if (table.isPresent()) { // check every existing partition that is outside for the base directory if (!table.get().getPartitionColumns().isEmpty()) { List<String> partitionNames = delegate.getPartitionNames(schemaTableName.getSchemaName(), schemaTableName.getTableName()) .orElse(ImmutableList.of()); for (List<String> partitionNameBatch : Iterables.partition(partitionNames, 10)) { Collection<Optional<Partition>> partitions = delegate.getPartitionsByNames(schemaTableName.getSchemaName(), schemaTableName.getTableName(), partitionNameBatch).values(); partitions.stream() .filter(Optional::isPresent) .map(Optional::get) .map(partition -> partition.getStorage().getLocation()) .map(Path::new) .filter(path -> !isSameOrParent(baseDirectory, path)) .forEach(pathsToClean::add); } } } else { logCleanupFailure( "Error rolling back write to table %s.%s. Data directory may contain temporary data. Table was dropped in another transaction.", schemaTableName.getSchemaName(), schemaTableName.getTableName()); } // delete any file that starts with the unique prefix of this query for (Path path : pathsToClean) { // TODO: It is a known deficiency that some empty directory does not get cleaned up in S3. // We can not delete any of the directories here since we do not know who created them. recursiveDeleteFilesAndLog( declaredIntentionToWrite.getUser(), path, ImmutableList.of(declaredIntentionToWrite.getFilePrefix()), false, format("target_existing directory rollback for table %s", schemaTableName)); } break; } default: throw new UnsupportedOperationException("Unknown write mode"); } } } @VisibleForTesting public synchronized void testOnlyCheckIsReadOnly() { if (state != State.EMPTY) { throw new AssertionError("Test did not commit or rollback"); } } @VisibleForTesting public void testOnlyThrowOnCleanupFailures() { throwOnCleanupFailure = true; } @GuardedBy("this") private void checkReadable() { checkHoldsLock(); switch (state) { case EMPTY: case SHARED_OPERATION_BUFFERED: return; case EXCLUSIVE_OPERATION_BUFFERED: throw new PrestoException(NOT_SUPPORTED, "Unsupported combination of operations in a single transaction"); case FINISHED: throw new IllegalStateException("Tried to access metastore after transaction has been committed/aborted"); } } @GuardedBy("this") private void setShared() { checkHoldsLock(); checkReadable(); state = State.SHARED_OPERATION_BUFFERED; } @GuardedBy("this") private void setExclusive(ExclusiveOperation exclusiveOperation) { checkHoldsLock(); if (state != State.EMPTY) { throw new PrestoException(StandardErrorCode.NOT_SUPPORTED, "Unsupported combination of operations in a single transaction"); } state = State.EXCLUSIVE_OPERATION_BUFFERED; bufferedExclusiveOperation = exclusiveOperation; } @GuardedBy("this") private void checkNoPartitionAction(String databaseName, String tableName) { checkHoldsLock(); Map<List<String>, Action<PartitionAndMore>> partitionActionsOfTable = partitionActions.get(new SchemaTableName(databaseName, tableName)); if (partitionActionsOfTable != null && !partitionActionsOfTable.isEmpty()) { throw new PrestoException(NOT_SUPPORTED, "Cannot make schema changes to a table/view with modified partitions in the same transaction"); } } private static boolean isSameOrParent(Path parent, Path child) { int parentDepth = parent.depth(); int childDepth = child.depth(); if (parentDepth > childDepth) { return false; } for (int i = childDepth; i > parentDepth; i--) { child = child.getParent(); } return parent.equals(child); } private void logCleanupFailure(String format, Object... args) { if (throwOnCleanupFailure) { throw new RuntimeException(format(format, args)); } log.warn(format, args); } private void logCleanupFailure(Throwable t, String format, Object... args) { if (throwOnCleanupFailure) { throw new RuntimeException(format(format, args), t); } log.warn(t, format, args); } private static void asyncRename( HdfsEnvironment hdfsEnvironment, Executor executor, AtomicBoolean cancelled, List<CompletableFuture<?>> fileRenameFutures, String user, Path currentPath, Path targetPath, List<String> fileNames) { FileSystem fileSystem; try { fileSystem = hdfsEnvironment.getFileSystem(user, currentPath); } catch (IOException e) { throw new PrestoException(HIVE_FILESYSTEM_ERROR, format("Error moving data files to final location. Error listing directory %s", currentPath), e); } for (String fileName : fileNames) { Path source = new Path(currentPath, fileName); Path target = new Path(targetPath, fileName); fileRenameFutures.add(CompletableFuture.runAsync(() -> { if (cancelled.get()) { return; } try { if (fileSystem.exists(target) || !fileSystem.rename(source, target)) { throw new PrestoException(HIVE_FILESYSTEM_ERROR, format("Error moving data files from %s to final location %s", source, target)); } } catch (IOException e) { throw new PrestoException(HIVE_FILESYSTEM_ERROR, format("Error moving data files from %s to final location %s", source, target), e); } }, executor)); } } private void recursiveDeleteFilesAndLog(String user, Path directory, List<String> filePrefixes, boolean deleteEmptyDirectories, String reason) { RecursiveDeleteResult recursiveDeleteResult = recursiveDeleteFiles( hdfsEnvironment, user, directory, filePrefixes, deleteEmptyDirectories); if (!recursiveDeleteResult.getNotDeletedEligibleItems().isEmpty()) { logCleanupFailure( "Error deleting directory %s for %s. Some eligible items can not be deleted: %s.", directory.toString(), reason, recursiveDeleteResult.getNotDeletedEligibleItems()); } else if (deleteEmptyDirectories && !recursiveDeleteResult.isDirectoryNoLongerExists()) { logCleanupFailure( "Error deleting directory %s for %s. Can not delete the directory.", directory.toString(), reason); } } /** * Attempt to recursively remove eligible files and/or directories in {@code directory}. * * When {@code filePrefixes} is not present, all files (but not necessarily directories) will be * ineligible. If all files shall be deleted, you can use an empty string as {@code filePrefixes}. * * When {@code deleteEmptySubDirectory} is true, any empty directory (including directories that * were originally empty, and directories that become empty after files prefixed with * {@code filePrefixes} are deleted) will be eligible. * * This method will not delete anything that's neither a directory nor a file. * * @param filePrefixes prefix of files that should be deleted * @param deleteEmptyDirectories whether empty directories should be deleted */ private static RecursiveDeleteResult recursiveDeleteFiles(HdfsEnvironment hdfsEnvironment, String user, Path directory, List<String> filePrefixes, boolean deleteEmptyDirectories) { FileSystem fileSystem; try { fileSystem = hdfsEnvironment.getFileSystem(user, directory); if (!fileSystem.exists(directory)) { return new RecursiveDeleteResult(true, ImmutableList.of()); } } catch (IOException e) { ImmutableList.Builder<String> notDeletedItems = ImmutableList.builder(); notDeletedItems.add(directory.toString() + "/**"); return new RecursiveDeleteResult(false, notDeletedItems.build()); } return doRecursiveDeleteFiles(fileSystem, directory, filePrefixes, deleteEmptyDirectories); } private static RecursiveDeleteResult doRecursiveDeleteFiles(FileSystem fileSystem, Path directory, List<String> filePrefixes, boolean deleteEmptyDirectories) { // don't delete hidden presto directories if (directory.getName().startsWith(".presto")) { return new RecursiveDeleteResult(false, ImmutableList.of()); } FileStatus[] allFiles; try { allFiles = fileSystem.listStatus(directory); } catch (IOException e) { ImmutableList.Builder<String> notDeletedItems = ImmutableList.builder(); notDeletedItems.add(directory.toString() + "/**"); return new RecursiveDeleteResult(false, notDeletedItems.build()); } boolean allDescendentsDeleted = true; ImmutableList.Builder<String> notDeletedEligibleItems = ImmutableList.builder(); for (FileStatus fileStatus : allFiles) { if (HadoopFileStatus.isFile(fileStatus)) { Path filePath = fileStatus.getPath(); String fileName = filePath.getName(); boolean eligible = false; // never delete presto dot files if (!fileName.startsWith(".presto")) { eligible = filePrefixes.stream().anyMatch(fileName::startsWith); } if (eligible) { if (!deleteIfExists(fileSystem, filePath, false)) { allDescendentsDeleted = false; notDeletedEligibleItems.add(filePath.toString()); } } else { allDescendentsDeleted = false; } } else if (HadoopFileStatus.isDirectory(fileStatus)) { RecursiveDeleteResult subResult = doRecursiveDeleteFiles(fileSystem, fileStatus.getPath(), filePrefixes, deleteEmptyDirectories); if (!subResult.isDirectoryNoLongerExists()) { allDescendentsDeleted = false; } if (!subResult.getNotDeletedEligibleItems().isEmpty()) { notDeletedEligibleItems.addAll(subResult.getNotDeletedEligibleItems()); } } else { allDescendentsDeleted = false; notDeletedEligibleItems.add(fileStatus.getPath().toString()); } } if (allDescendentsDeleted && deleteEmptyDirectories) { verify(notDeletedEligibleItems.build().isEmpty()); if (!deleteIfExists(fileSystem, directory, false)) { return new RecursiveDeleteResult(false, ImmutableList.of(directory.toString() + "/")); } return new RecursiveDeleteResult(true, ImmutableList.of()); } return new RecursiveDeleteResult(false, notDeletedEligibleItems.build()); } /** * Attempts to remove the file or empty directory. * * @return true if the location no longer exists */ private static boolean deleteIfExists(FileSystem fileSystem, Path path, boolean recursive) { try { // attempt to delete the path if (fileSystem.delete(path, recursive)) { return true; } // delete failed // check if path still exists return !fileSystem.exists(path); } catch (FileNotFoundException ignored) { // path was already removed or never existed return true; } catch (IOException ignored) { } return false; } /** * Attempts to remove the file or empty directory. * * @return true if the location no longer exists */ private static boolean deleteRecursivelyIfExists(String user, HdfsEnvironment hdfsEnvironment, Path path) { FileSystem fileSystem; try { fileSystem = hdfsEnvironment.getFileSystem(user, path); } catch (IOException ignored) { return false; } return deleteIfExists(fileSystem, path, true); } private static void renameDirectory(String user, HdfsEnvironment hdfsEnvironment, Path source, Path target, Runnable runWhenPathDoesntExist) { if (pathExists(user, hdfsEnvironment, target)) { throw new PrestoException(HIVE_PATH_ALREADY_EXISTS, format("Unable to rename from %s to %s: target directory already exists", source, target)); } if (!pathExists(user, hdfsEnvironment, target.getParent())) { createDirectory(user, hdfsEnvironment, target.getParent()); } // The runnable will assume that if rename fails, it will be okay to delete the directory (if the directory is empty). // This is not technically true because a race condition still exists. runWhenPathDoesntExist.run(); try { if (!hdfsEnvironment.getFileSystem(user, source).rename(source, target)) { throw new PrestoException(HIVE_FILESYSTEM_ERROR, format("Failed to rename %s to %s: rename returned false", source, target)); } } catch (IOException e) { throw new PrestoException(HIVE_FILESYSTEM_ERROR, format("Failed to rename %s to %s", source, target), e); } } private static Optional<String> getPrestoQueryId(Table table) { return Optional.ofNullable(table.getParameters().get(PRESTO_QUERY_ID_NAME)); } private static Optional<String> getPrestoQueryId(Partition partition) { return Optional.ofNullable(partition.getParameters().get(PRESTO_QUERY_ID_NAME)); } private void checkHoldsLock() { // This method serves a similar purpose at runtime as GuardedBy on method serves during static analysis. // This method should not have significant performance impact. If it does, it may be reasonably to remove this method. // This intentionally does not use checkState. if (!Thread.holdsLock(this)) { throw new IllegalStateException(format("Thread must hold a lock on the %s", getClass().getSimpleName())); } } private enum State { EMPTY, SHARED_OPERATION_BUFFERED, EXCLUSIVE_OPERATION_BUFFERED, FINISHED, } public enum WriteMode { STAGE_AND_MOVE_TO_TARGET_DIRECTORY, // common mode for new table or existing table (both new and existing partition) DIRECT_TO_TARGET_NEW_DIRECTORY, // for new table in S3 DIRECT_TO_TARGET_EXISTING_DIRECTORY, // for existing table in S3 (both new and existing partition) // NOTE: Insert overwrite simulation (partition drops and partition additions in the same // transaction get merged and become one or more partition alterations, and get submitted to // metastore in close succession of each other) is not supported for S3. S3 uses the last // mode for insert into existing table. This is hard to support because the directory // containing the old data cannot be deleted until commit. Nor can the old data be moved // (assuming Hive HDFS directory naming convention shall not be violated). As a result, // subsequent insertion will have to write to directory belonging to existing partition. // This undermines the benefit of having insert overwrite simulation. This also makes // dropping of old partition at commit time hard because data added after the logical // "drop" time was added to the directories to be dropped. } private enum ActionType { DROP, ADD, ALTER, INSERT_EXISTING } private enum TableSource { CREATED_IN_THIS_TRANSACTION, PRE_EXISTING_TABLE, // RECREATED_IN_THIS_TRANSACTION is a possible case, but it is not supported with the current implementation } public static class Action<T> { private final ActionType type; private final T data; private final String user; private final String queryId; @JsonCreator public Action(@JsonProperty("type") ActionType type, @JsonProperty("data") T data, @JsonProperty("user") String user, @JsonProperty("queryId") String queryId) { this.type = requireNonNull(type, "type is null"); if (type == ActionType.DROP) { checkArgument(data == null, "data is not null"); } else { requireNonNull(data, "data is null"); } this.data = data; this.user = requireNonNull(user, "user is null"); this.queryId = requireNonNull(queryId, "queryId is null"); } @JsonProperty public ActionType getType() { return type; } public T getData() { checkState(type != ActionType.DROP); return data; } @JsonProperty("data") public T getJsonSerializableData() { return data; } @JsonProperty public String getUser() { return user; } @JsonProperty public String getQueryId() { return queryId; } @Override public String toString() { return toStringHelper(this) .add("type", type) .add("data", data) .toString(); } } private static class TableAndMore { private final Table table; private final Optional<PrincipalPrivileges> principalPrivileges; private final Optional<Path> currentLocation; // unpartitioned table only private final Optional<List<String>> fileNames; public TableAndMore(Table table, Optional<PrincipalPrivileges> principalPrivileges, Optional<Path> currentLocation, Optional<List<String>> fileNames) { this.table = requireNonNull(table, "table is null"); this.principalPrivileges = requireNonNull(principalPrivileges, "principalPrivileges is null"); this.currentLocation = requireNonNull(currentLocation, "currentLocation is null"); this.fileNames = requireNonNull(fileNames, "fileNames is null"); checkArgument(!table.getStorage().getLocation().isEmpty() || !currentLocation.isPresent(), "currentLocation can not be supplied for table without location"); checkArgument(!fileNames.isPresent() || currentLocation.isPresent(), "fileNames can be supplied only when currentLocation is supplied"); } public Table getTable() { return table; } public PrincipalPrivileges getPrincipalPrivileges() { checkState(principalPrivileges.isPresent()); return principalPrivileges.get(); } public Optional<Path> getCurrentLocation() { return currentLocation; } public Optional<List<String>> getFileNames() { return fileNames; } @Override public String toString() { return toStringHelper(this) .add("table", table) .add("principalPrivileges", principalPrivileges) .add("currentLocation", currentLocation) .toString(); } } public static class PartitionAndMore { private final Partition partition; private final Path currentLocation; private final Optional<List<String>> fileNames; public PartitionAndMore(Partition partition, Path currentLocation, Optional<List<String>> fileNames) { this.partition = requireNonNull(partition, "partition is null"); this.currentLocation = requireNonNull(currentLocation, "currentLocation is null"); this.fileNames = requireNonNull(fileNames, "fileNames is null"); } @JsonCreator public PartitionAndMore jsonCreator(@JsonProperty("partition") Partition partition, @JsonProperty("currentLocation") Path currentLocation) { return new PartitionAndMore(partition, currentLocation, Optional.empty()); } @JsonProperty public Partition getPartition() { return partition; } Partition getAugmentedPartitionForInTransactionRead() { // This method augments the location field of the partition to the staging location. // This way, if the partition is accessed in an ongoing transaction, staged data // can be found and accessed. Partition partition = this.partition; String currentLocation = this.currentLocation.toString(); if (!currentLocation.equals(partition.getStorage().getLocation())) { partition = Partition.builder(partition) .withStorage(storage -> storage.setLocation(currentLocation)) .build(); } return partition; } @JsonProperty public Path getCurrentLocation() { return currentLocation; } public List<String> getFileNames() { checkState(fileNames.isPresent()); return fileNames.get(); } } private static class DeclaredIntentionToWrite { private final WriteMode mode; private final String user; private final String filePrefix; private final Path rootPath; private final SchemaTableName schemaTableName; public DeclaredIntentionToWrite(WriteMode mode, String user, Path stagingPathRoot, String filePrefix, SchemaTableName schemaTableName) { this.mode = requireNonNull(mode, "mode is null"); this.user = requireNonNull(user, "user is null"); this.rootPath = requireNonNull(stagingPathRoot, "stagingPathRoot is null"); this.filePrefix = requireNonNull(filePrefix, "filePrefix is null"); this.schemaTableName = requireNonNull(schemaTableName, "schemaTableName is null"); } public WriteMode getMode() { return mode; } public String getUser() { return user; } public String getFilePrefix() { return filePrefix; } public Path getRootPath() { return rootPath; } public SchemaTableName getSchemaTableName() { return schemaTableName; } @Override public String toString() { return toStringHelper(this) .add("mode", mode) .add("user", user) .add("filePrefix", filePrefix) .add("rootPath", rootPath) .add("schemaTableName", schemaTableName) .toString(); } } private static class DirectoryCleanUpTask { private final String user; private final Path path; private final boolean deleteEmptyDirectory; public DirectoryCleanUpTask(String user, Path path, boolean deleteEmptyDirectory) { this.user = user; this.path = path; this.deleteEmptyDirectory = deleteEmptyDirectory; } public String getUser() { return user; } public Path getPath() { return path; } public boolean isDeleteEmptyDirectory() { return deleteEmptyDirectory; } @Override public String toString() { return toStringHelper(this) .add("user", user) .add("path", path) .add("deleteEmptyDirectory", deleteEmptyDirectory) .toString(); } } private static class DirectoryDeletionTask { private final String user; private final Path path; public DirectoryDeletionTask(String user, Path path) { this.user = user; this.path = path; } public String getUser() { return user; } public Path getPath() { return path; } @Override public String toString() { return toStringHelper(this) .add("user", user) .add("path", path) .toString(); } } private static class DirectoryRenameTask { private final String user; private final Path renameFrom; private final Path renameTo; public DirectoryRenameTask(String user, Path renameFrom, Path renameTo) { this.user = requireNonNull(user, "user is null"); this.renameFrom = requireNonNull(renameFrom, "renameFrom is null"); this.renameTo = requireNonNull(renameTo, "renameTo is null"); } public String getUser() { return user; } public Path getRenameFrom() { return renameFrom; } public Path getRenameTo() { return renameTo; } @Override public String toString() { return toStringHelper(this) .add("user", user) .add("renameFrom", renameFrom) .add("renameTo", renameTo) .toString(); } } private static class IrreversibleMetastoreOperation { private final String description; private final Runnable action; public IrreversibleMetastoreOperation(String description, Runnable action) { this.description = requireNonNull(description, "description is null"); this.action = requireNonNull(action, "action is null"); } public String getDescription() { return description; } public void run() { action.run(); } } private static class CreateTableOperation { private final Table table; private final PrincipalPrivileges privileges; private boolean done; public CreateTableOperation(Table table, PrincipalPrivileges privileges) { requireNonNull(table, "table is null"); checkArgument(getPrestoQueryId(table).isPresent()); this.table = table; this.privileges = requireNonNull(privileges, "privileges is null"); } public String getDescription() { return format("add table %s.%s", table.getDatabaseName(), table.getTableName()); } public void run(ExtendedHiveMetastore metastore) { try { metastore.createTable(table, privileges); done = true; } catch (RuntimeException e) { try { Optional<Table> remoteTable = metastore.getTable(table.getDatabaseName(), table.getTableName()); // getPrestoQueryId(partition) is guaranteed to be non-empty. It is asserted in the constructor. if (remoteTable.isPresent() && getPrestoQueryId(remoteTable.get()).equals(getPrestoQueryId(table))) { done = true; } } catch (RuntimeException ignored) { // When table could not be fetched from metastore, it is not known whether the table was added. // Deleting the table when aborting commit has the risk of deleting table not added in this transaction. // Not deleting the table may leave garbage behind. The former is much more dangerous than the latter. // Therefore, the table is not considered added. } if (!done) { throw e; } } } public void undo(ExtendedHiveMetastore metastore) { if (!done) { return; } metastore.dropTable(table.getDatabaseName(), table.getTableName(), false); } } private static class AlterPartitionOperation { private final Partition newPartition; private final Partition oldPartition; private boolean done; public AlterPartitionOperation(Partition newPartition, Partition oldPartition) { this.newPartition = requireNonNull(newPartition, "newPartition is null"); this.oldPartition = requireNonNull(oldPartition, "oldPartition is null"); checkArgument(newPartition.getDatabaseName().equals(oldPartition.getDatabaseName())); checkArgument(newPartition.getTableName().equals(oldPartition.getTableName())); checkArgument(newPartition.getValues().equals(oldPartition.getValues())); } public String getDescription() { return format("alter partition %s.%s %s", newPartition.getDatabaseName(), newPartition.getTableName(), newPartition.getValues()); } public void run(ExtendedHiveMetastore metastore) { metastore.alterPartition(newPartition.getDatabaseName(), newPartition.getTableName(), newPartition); done = true; } public void undo(ExtendedHiveMetastore metastore) { if (!done) { return; } metastore.alterPartition(oldPartition.getDatabaseName(), oldPartition.getTableName(), oldPartition); } } private static class PartitionAdder { private final String schemaName; private final String tableName; private final ExtendedHiveMetastore metastore; private final int batchSize; private final List<Partition> partitions; private List<List<String>> createdPartitionValues = new ArrayList<>(); public PartitionAdder(String schemaName, String tableName, ExtendedHiveMetastore metastore, int batchSize) { this.schemaName = schemaName; this.tableName = tableName; this.metastore = metastore; this.batchSize = batchSize; this.partitions = new ArrayList<>(batchSize); } public String getSchemaName() { return schemaName; } public String getTableName() { return tableName; } public void addPartition(Partition partition) { checkArgument(getPrestoQueryId(partition).isPresent()); partitions.add(partition); } public void execute() { List<List<Partition>> batchedPartitions = Lists.partition(partitions, batchSize); for (List<Partition> batch : batchedPartitions) { try { metastore.addPartitions(schemaName, tableName, batch); for (Partition partition : batch) { createdPartitionValues.add(partition.getValues()); } } catch (Throwable t) { // Add partition to the created list conservatively. // Some metastore implementations are known to violate the "all or none" guarantee for add_partitions call. boolean batchCompletelyAdded = true; for (Partition partition : batch) { try { Optional<Partition> remotePartition = metastore.getPartition(schemaName, tableName, partition.getValues()); // getPrestoQueryId(partition) is guaranteed to be non-empty. It is asserted in PartitionAdder.addPartition. if (remotePartition.isPresent() && getPrestoQueryId(remotePartition.get()).equals(getPrestoQueryId(partition))) { createdPartitionValues.add(partition.getValues()); } else { batchCompletelyAdded = false; } } catch (Throwable ignored) { // When partition could not be fetched from metastore, it is not known whether the partition was added. // Deleting the partition when aborting commit has the risk of deleting partition not added in this transaction. // Not deleting the partition may leave garbage behind. The former is much more dangerous than the latter. // Therefore, the partition is not added to the createdPartitionValues list here. batchCompletelyAdded = false; } } // If all the partitions were added successfully, the add_partition operation was actually successful. // For some reason, it threw an exception (communication failure, retry failure after communication failure, etc). // But we would consider it successful anyways. if (!batchCompletelyAdded) { throw t; } } } partitions.clear(); } public List<List<String>> rollback() { // drop created partitions List<List<String>> partitionsFailedToRollback = new ArrayList<>(); for (List<String> createdPartitionValue : createdPartitionValues) { try { metastore.dropPartition(schemaName, tableName, createdPartitionValue, false); } catch (PartitionNotFoundException e) { // Maybe some one deleted the partition we added. // Anyways, we are good because the partition is not there anymore. } catch (Throwable t) { partitionsFailedToRollback.add(createdPartitionValue); } } createdPartitionValues = partitionsFailedToRollback; return partitionsFailedToRollback; } } private static class RecursiveDeleteResult { private final boolean directoryNoLongerExists; private final List<String> notDeletedEligibleItems; public RecursiveDeleteResult(boolean directoryNoLongerExists, List<String> notDeletedEligibleItems) { this.directoryNoLongerExists = directoryNoLongerExists; this.notDeletedEligibleItems = notDeletedEligibleItems; } public boolean isDirectoryNoLongerExists() { return directoryNoLongerExists; } public List<String> getNotDeletedEligibleItems() { return notDeletedEligibleItems; } } private interface ExclusiveOperation { void execute(ExtendedHiveMetastore delegate, HdfsEnvironment hdfsEnvironment); } }
presto-hive/src/main/java/com/facebook/presto/hive/metastore/SemiTransactionalHiveMetastore.java
/* * 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.facebook.presto.hive.metastore; import com.facebook.presto.hadoop.HadoopFileStatus; import com.facebook.presto.hive.HdfsEnvironment; import com.facebook.presto.hive.HiveType; import com.facebook.presto.hive.PartitionNotFoundException; import com.facebook.presto.hive.TableAlreadyExistsException; import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.SchemaTableName; import com.facebook.presto.spi.StandardErrorCode; import com.facebook.presto.spi.TableNotFoundException; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import io.airlift.concurrent.MoreFutures; import io.airlift.log.Logger; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import javax.annotation.concurrent.GuardedBy; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import static com.facebook.presto.hive.HiveErrorCode.HIVE_FILESYSTEM_ERROR; import static com.facebook.presto.hive.HiveErrorCode.HIVE_METASTORE_ERROR; import static com.facebook.presto.hive.HiveErrorCode.HIVE_PATH_ALREADY_EXISTS; import static com.facebook.presto.hive.HiveMetadata.PRESTO_QUERY_ID_NAME; import static com.facebook.presto.hive.HiveUtil.toPartitionValues; import static com.facebook.presto.hive.HiveWriteUtils.createDirectory; import static com.facebook.presto.hive.HiveWriteUtils.pathExists; import static com.facebook.presto.hive.metastore.HivePrivilegeInfo.HivePrivilege.OWNERSHIP; import static com.facebook.presto.spi.StandardErrorCode.ALREADY_EXISTS; import static com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED; import static com.facebook.presto.spi.StandardErrorCode.TRANSACTION_CONFLICT; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Verify.verify; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static org.apache.hadoop.hive.common.FileUtils.makePartName; import static org.apache.hadoop.hive.metastore.TableType.MANAGED_TABLE; public class SemiTransactionalHiveMetastore { private static final Logger log = Logger.get(SemiTransactionalHiveMetastore.class); private static final int PARTITION_COMMIT_BATCH_SIZE = 8; private final ExtendedHiveMetastore delegate; private final HdfsEnvironment hdfsEnvironment; private final Executor renameExecutor; private final boolean skipDeletionForAlter; @GuardedBy("this") private final Map<SchemaTableName, Action<TableAndMore>> tableActions = new HashMap<>(); @GuardedBy("this") private final Map<SchemaTableName, Map<List<String>, Action<PartitionAndMore>>> partitionActions = new HashMap<>(); @GuardedBy("this") private final List<DeclaredIntentionToWrite> declaredIntentionsToWrite = new ArrayList<>(); @GuardedBy("this") private ExclusiveOperation bufferedExclusiveOperation; @GuardedBy("this") private State state = State.EMPTY; private boolean throwOnCleanupFailure = false; public SemiTransactionalHiveMetastore(HdfsEnvironment hdfsEnvironment, ExtendedHiveMetastore delegate, Executor renameExecutor, boolean skipDeletionForAlter) { this.hdfsEnvironment = requireNonNull(hdfsEnvironment, "hdfsEnvironment is null"); this.delegate = requireNonNull(delegate, "delegate is null"); this.renameExecutor = requireNonNull(renameExecutor, "renameExecutor is null"); this.skipDeletionForAlter = requireNonNull(skipDeletionForAlter, "skipDeletionForAlter is null"); } public synchronized List<String> getAllDatabases() { checkReadable(); return delegate.getAllDatabases(); } public synchronized Optional<Database> getDatabase(String databaseName) { checkReadable(); return delegate.getDatabase(databaseName); } public synchronized Optional<List<String>> getAllTables(String databaseName) { checkReadable(); if (!tableActions.isEmpty()) { throw new UnsupportedOperationException("Listing all tables after adding/dropping/altering tables/views in a transaction is not supported"); } return delegate.getAllTables(databaseName); } public synchronized Optional<Table> getTable(String databaseName, String tableName) { checkReadable(); Action<TableAndMore> tableAction = tableActions.get(new SchemaTableName(databaseName, tableName)); if (tableAction == null) { return delegate.getTable(databaseName, tableName); } switch (tableAction.getType()) { case ADD: case ALTER: case INSERT_EXISTING: return Optional.of(tableAction.getData().getTable()); case DROP: return Optional.empty(); default: throw new IllegalStateException("Unknown action type"); } } /** * This method can only be called when the table is known to exist */ @GuardedBy("this") private TableSource getTableSource(String databaseName, String tableName) { checkHoldsLock(); checkReadable(); Action<TableAndMore> tableAction = tableActions.get(new SchemaTableName(databaseName, tableName)); if (tableAction == null) { return TableSource.PRE_EXISTING_TABLE; } switch (tableAction.getType()) { case ADD: return TableSource.CREATED_IN_THIS_TRANSACTION; case ALTER: throw new IllegalStateException("Tables are never altered in the current implementation"); case DROP: throw new TableNotFoundException(new SchemaTableName(databaseName, tableName)); case INSERT_EXISTING: return TableSource.PRE_EXISTING_TABLE; default: throw new IllegalStateException("Unknown action type"); } } public synchronized HivePageSinkMetadata generatePageSinkMetadata(SchemaTableName schemaTableName) { checkReadable(); Optional<Table> table = getTable(schemaTableName.getSchemaName(), schemaTableName.getTableName()); if (!table.isPresent()) { return new HivePageSinkMetadata(schemaTableName, Optional.empty(), ImmutableMap.of()); } Map<List<String>, Action<PartitionAndMore>> partitionActionMap = partitionActions.get(schemaTableName); Map<List<String>, Optional<Partition>> modifiedPartitionMap; if (partitionActionMap == null) { modifiedPartitionMap = ImmutableMap.of(); } else { ImmutableMap.Builder<List<String>, Optional<Partition>> modifiedPartitionMapBuilder = ImmutableMap.builder(); for (Map.Entry<List<String>, Action<PartitionAndMore>> entry : partitionActionMap.entrySet()) { modifiedPartitionMapBuilder.put(entry.getKey(), getPartitionFromPartitionAction(entry.getValue())); } modifiedPartitionMap = modifiedPartitionMapBuilder.build(); } return new HivePageSinkMetadata( schemaTableName, table, modifiedPartitionMap); } public synchronized Optional<List<String>> getAllViews(String databaseName) { checkReadable(); if (!tableActions.isEmpty()) { throw new UnsupportedOperationException("Listing all tables after adding/dropping/altering tables/views in a transaction is not supported"); } return delegate.getAllViews(databaseName); } public synchronized void createDatabase(Database database) { setExclusive((delegate, hdfsEnvironment) -> delegate.createDatabase(database)); } public synchronized void dropDatabase(String schemaName) { setExclusive((delegate, hdfsEnvironment) -> delegate.dropDatabase(schemaName)); } public synchronized void renameDatabase(String source, String target) { setExclusive((delegate, hdfsEnvironment) -> delegate.renameDatabase(source, target)); } /** * {@code currentLocation} needs to be supplied if a writePath exists for the table. */ public synchronized void createTable(ConnectorSession session, Table table, PrincipalPrivileges principalPrivileges, Optional<Path> currentPath) { setShared(); // When creating a table, it should never have partition actions. This is just a sanity check. checkNoPartitionAction(table.getDatabaseName(), table.getTableName()); SchemaTableName schemaTableName = new SchemaTableName(table.getDatabaseName(), table.getTableName()); Action<TableAndMore> oldTableAction = tableActions.get(schemaTableName); TableAndMore tableAndMore = new TableAndMore(table, Optional.of(principalPrivileges), currentPath, Optional.empty()); if (oldTableAction == null) { tableActions.put(schemaTableName, new Action<>(ActionType.ADD, tableAndMore, session.getUser(), session.getQueryId())); return; } switch (oldTableAction.getType()) { case DROP: throw new PrestoException(TRANSACTION_CONFLICT, "Dropping and then recreating the same table in a transaction is not supported"); case ADD: case ALTER: case INSERT_EXISTING: throw new TableAlreadyExistsException(schemaTableName); default: throw new IllegalStateException("Unknown action type"); } } public synchronized void dropTable(ConnectorSession session, String databaseName, String tableName) { setShared(); // Dropping table with partition actions requires cleaning up staging data, which is not implemented yet. checkNoPartitionAction(databaseName, tableName); SchemaTableName schemaTableName = new SchemaTableName(databaseName, tableName); Action<TableAndMore> oldTableAction = tableActions.get(schemaTableName); if (oldTableAction == null || oldTableAction.getType() == ActionType.ALTER) { tableActions.put(schemaTableName, new Action<>(ActionType.DROP, null, session.getUser(), session.getQueryId())); return; } switch (oldTableAction.getType()) { case DROP: throw new TableNotFoundException(schemaTableName); case ADD: case ALTER: case INSERT_EXISTING: throw new UnsupportedOperationException("dropping a table added/modified in the same transaction is not supported"); default: throw new IllegalStateException("Unknown action type"); } } public synchronized void replaceView(String databaseName, String tableName, Table table, PrincipalPrivileges principalPrivileges) { setExclusive((delegate, hdfsEnvironment) -> delegate.replaceTable(databaseName, tableName, table, principalPrivileges)); } public synchronized void renameTable(String databaseName, String tableName, String newDatabaseName, String newTableName) { setExclusive((delegate, hdfsEnvironment) -> delegate.renameTable(databaseName, tableName, newDatabaseName, newTableName)); } public synchronized void addColumn(String databaseName, String tableName, String columnName, HiveType columnType, String columnComment) { setExclusive((delegate, hdfsEnvironment) -> delegate.addColumn(databaseName, tableName, columnName, columnType, columnComment)); } public synchronized void renameColumn(String databaseName, String tableName, String oldColumnName, String newColumnName) { setExclusive((delegate, hdfsEnvironment) -> delegate.renameColumn(databaseName, tableName, oldColumnName, newColumnName)); } public synchronized void finishInsertIntoExistingTable(ConnectorSession session, String databaseName, String tableName, Path currentLocation, List<String> fileNames) { // Data can only be inserted into partitions and unpartitioned tables. They can never be inserted into a partitioned table. // Therefore, this method assumes that the table is unpartitioned. setShared(); SchemaTableName schemaTableName = new SchemaTableName(databaseName, tableName); Action<TableAndMore> oldTableAction = tableActions.get(schemaTableName); if (oldTableAction == null) { Optional<Table> table = delegate.getTable(databaseName, tableName); if (!table.isPresent()) { throw new TableNotFoundException(schemaTableName); } tableActions.put( schemaTableName, new Action<>( ActionType.INSERT_EXISTING, new TableAndMore(table.get(), Optional.empty(), Optional.of(currentLocation), Optional.of(fileNames)), session.getUser(), session.getQueryId())); return; } switch (oldTableAction.getType()) { case DROP: throw new TableNotFoundException(schemaTableName); case ADD: case ALTER: case INSERT_EXISTING: throw new UnsupportedOperationException("Inserting into an unpartitioned table that were added, altered, or inserted into in the same transaction is not supported"); default: throw new IllegalStateException("Unknown action type"); } } public synchronized void truncateUnpartitionedTable(ConnectorSession session, String databaseName, String tableName) { checkReadable(); Optional<Table> table = getTable(databaseName, tableName); SchemaTableName schemaTableName = new SchemaTableName(databaseName, tableName); if (!table.isPresent()) { throw new TableNotFoundException(schemaTableName); } if (!table.get().getTableType().equals(MANAGED_TABLE.toString())) { throw new PrestoException(NOT_SUPPORTED, "Cannot delete from non-managed Hive table"); } if (!table.get().getPartitionColumns().isEmpty()) { throw new IllegalArgumentException("Table is partitioned"); } Path path = new Path(table.get().getStorage().getLocation()); String user = session.getUser(); setExclusive((delegate, hdfsEnvironment) -> { RecursiveDeleteResult recursiveDeleteResult = recursiveDeleteFiles(hdfsEnvironment, user, path, ImmutableList.of(""), false); if (!recursiveDeleteResult.getNotDeletedEligibleItems().isEmpty()) { throw new PrestoException(HIVE_FILESYSTEM_ERROR, format( "Error deleting from unpartitioned table %s. These items can not be deleted: %s", schemaTableName, recursiveDeleteResult.getNotDeletedEligibleItems())); } }); } public synchronized Optional<List<String>> getPartitionNames(String databaseName, String tableName) { return doGetPartitionNames(databaseName, tableName, Optional.empty()); } public synchronized Optional<List<String>> getPartitionNamesByParts(String databaseName, String tableName, List<String> parts) { return doGetPartitionNames(databaseName, tableName, Optional.of(parts)); } @GuardedBy("this") private Optional<List<String>> doGetPartitionNames(String databaseName, String tableName, Optional<List<String>> parts) { checkHoldsLock(); checkReadable(); Optional<Table> table = getTable(databaseName, tableName); if (!table.isPresent()) { return Optional.empty(); } List<String> partitionNames; TableSource tableSource = getTableSource(databaseName, tableName); switch (tableSource) { case CREATED_IN_THIS_TRANSACTION: partitionNames = ImmutableList.of(); break; case PRE_EXISTING_TABLE: { Optional<List<String>> partitionNameResult; if (parts.isPresent()) { partitionNameResult = delegate.getPartitionNamesByParts(databaseName, tableName, parts.get()); } else { partitionNameResult = delegate.getPartitionNames(databaseName, tableName); } if (!partitionNameResult.isPresent()) { throw new PrestoException(TRANSACTION_CONFLICT, "Table %s.%s was dropped by another transaction"); } partitionNames = partitionNameResult.get(); break; } default: throw new UnsupportedOperationException("Unknown table source"); } Map<List<String>, Action<PartitionAndMore>> partitionActionsOfTable = partitionActions.computeIfAbsent(new SchemaTableName(databaseName, tableName), k -> new HashMap<>()); ImmutableList.Builder<String> resultBuilder = ImmutableList.builder(); // alter/remove newly-altered/dropped partitions from the results from underlying metastore for (String partitionName : partitionNames) { List<String> partitionValues = toPartitionValues(partitionName); Action<PartitionAndMore> partitionAction = partitionActionsOfTable.get(partitionValues); if (partitionAction == null) { resultBuilder.add(partitionName); continue; } switch (partitionAction.getType()) { case ADD: throw new PrestoException(TRANSACTION_CONFLICT, format("Another transaction created partition %s in table %s.%s", partitionValues, databaseName, tableName)); case DROP: // do nothing break; case ALTER: case INSERT_EXISTING: resultBuilder.add(partitionName); break; default: throw new IllegalStateException("Unknown action type"); } } // add newly-added partitions to the results from underlying metastore if (!partitionActionsOfTable.isEmpty()) { List<String> columnNames = table.get().getPartitionColumns().stream().map(Column::getName).collect(Collectors.toList()); for (Action<PartitionAndMore> partitionAction : partitionActionsOfTable.values()) { if (partitionAction.getType() == ActionType.ADD) { List<String> values = partitionAction.getData().getPartition().getValues(); if (!parts.isPresent() || partitionValuesMatch(values, parts.get())) { resultBuilder.add(makePartName(columnNames, values)); } } } } return Optional.of(resultBuilder.build()); } private static boolean partitionValuesMatch(List<String> values, List<String> pattern) { checkArgument(values.size() == pattern.size()); for (int i = 0; i < values.size(); i++) { if (pattern.get(i).isEmpty()) { // empty string match everything continue; } if (values.get(i).equals(pattern.get(i))) { return false; } } return true; } public synchronized Optional<Partition> getPartition(String databaseName, String tableName, List<String> partitionValues) { checkReadable(); TableSource tableSource = getTableSource(databaseName, tableName); Map<List<String>, Action<PartitionAndMore>> partitionActionsOfTable = partitionActions.computeIfAbsent(new SchemaTableName(databaseName, tableName), k -> new HashMap<>()); Action<PartitionAndMore> partitionAction = partitionActionsOfTable.get(partitionValues); if (partitionAction != null) { return getPartitionFromPartitionAction(partitionAction); } switch (tableSource) { case PRE_EXISTING_TABLE: return delegate.getPartition(databaseName, tableName, partitionValues); case CREATED_IN_THIS_TRANSACTION: return Optional.empty(); default: throw new UnsupportedOperationException("unknown table source"); } } public synchronized Map<String, Optional<Partition>> getPartitionsByNames(String databaseName, String tableName, List<String> partitionNames) { checkReadable(); TableSource tableSource = getTableSource(databaseName, tableName); Map<List<String>, Action<PartitionAndMore>> partitionActionsOfTable = partitionActions.computeIfAbsent(new SchemaTableName(databaseName, tableName), k -> new HashMap<>()); ImmutableList.Builder<String> partitionNamesToQuery = ImmutableList.builder(); ImmutableMap.Builder<String, Optional<Partition>> resultBuilder = ImmutableMap.builder(); for (String partitionName : partitionNames) { List<String> partitionValues = toPartitionValues(partitionName); Action<PartitionAndMore> partitionAction = partitionActionsOfTable.get(partitionValues); if (partitionAction == null) { switch (tableSource) { case PRE_EXISTING_TABLE: partitionNamesToQuery.add(partitionName); break; case CREATED_IN_THIS_TRANSACTION: resultBuilder.put(partitionName, Optional.empty()); break; default: throw new UnsupportedOperationException("unknown table source"); } } else { resultBuilder.put(partitionName, getPartitionFromPartitionAction(partitionAction)); } } Map<String, Optional<Partition>> delegateResult = delegate.getPartitionsByNames(databaseName, tableName, partitionNamesToQuery.build()); resultBuilder.putAll(delegateResult); return resultBuilder.build(); } private static Optional<Partition> getPartitionFromPartitionAction(Action<PartitionAndMore> partitionAction) { switch (partitionAction.getType()) { case ADD: case ALTER: case INSERT_EXISTING: return Optional.of(partitionAction.getData().getAugmentedPartitionForInTransactionRead()); case DROP: return Optional.empty(); default: throw new IllegalStateException("Unknown action type"); } } public synchronized void addPartition(ConnectorSession session, String databaseName, String tableName, Partition partition, Path currentLocation) { setShared(); checkArgument(getPrestoQueryId(partition).isPresent()); Map<List<String>, Action<PartitionAndMore>> partitionActionsOfTable = partitionActions.computeIfAbsent(new SchemaTableName(databaseName, tableName), k -> new HashMap<>()); Action<PartitionAndMore> oldPartitionAction = partitionActionsOfTable.get(partition.getValues()); if (oldPartitionAction == null) { partitionActionsOfTable.put( partition.getValues(), new Action<>(ActionType.ADD, new PartitionAndMore(partition, currentLocation, Optional.empty()), session.getUser(), session.getQueryId())); return; } switch (oldPartitionAction.getType()) { case DROP: { if (!oldPartitionAction.getUser().equals(session.getUser())) { throw new PrestoException(TRANSACTION_CONFLICT, "Operation on the same partition with different user in the same transaction is not supported"); } partitionActionsOfTable.put( partition.getValues(), new Action<>(ActionType.ALTER, new PartitionAndMore(partition, currentLocation, Optional.empty()), session.getUser(), session.getQueryId())); break; } case ADD: case ALTER: case INSERT_EXISTING: throw new PrestoException(ALREADY_EXISTS, format("Partition already exists for table '%s.%s': %s", databaseName, tableName, partition.getValues())); default: throw new IllegalStateException("Unknown action type"); } } public synchronized void dropPartition(ConnectorSession session, String databaseName, String tableName, List<String> partitionValues) { setShared(); Map<List<String>, Action<PartitionAndMore>> partitionActionsOfTable = partitionActions.computeIfAbsent(new SchemaTableName(databaseName, tableName), k -> new HashMap<>()); Action<PartitionAndMore> oldPartitionAction = partitionActionsOfTable.get(partitionValues); if (oldPartitionAction == null) { partitionActionsOfTable.put(partitionValues, new Action<>(ActionType.DROP, null, session.getUser(), session.getQueryId())); return; } switch (oldPartitionAction.getType()) { case DROP: throw new PartitionNotFoundException(new SchemaTableName(databaseName, tableName), partitionValues); case ADD: case ALTER: case INSERT_EXISTING: throw new PrestoException( NOT_SUPPORTED, format("dropping a partition added in the same transaction is not supported: %s %s %s", databaseName, tableName, partitionValues)); default: throw new IllegalStateException("Unknown action type"); } } public synchronized void finishInsertIntoExistingPartition(ConnectorSession session, String databaseName, String tableName, List<String> partitionValues, Path currentLocation, List<String> fileNames) { setShared(); SchemaTableName schemaTableName = new SchemaTableName(databaseName, tableName); Map<List<String>, Action<PartitionAndMore>> partitionActionsOfTable = partitionActions.computeIfAbsent(schemaTableName, k -> new HashMap<>()); Action<PartitionAndMore> oldPartitionAction = partitionActionsOfTable.get(partitionValues); if (oldPartitionAction == null) { Optional<Partition> partition = delegate.getPartition(databaseName, tableName, partitionValues); if (!partition.isPresent()) { throw new PartitionNotFoundException(schemaTableName, partitionValues); } partitionActionsOfTable.put( partitionValues, new Action<>(ActionType.INSERT_EXISTING, new PartitionAndMore(partition.get(), currentLocation, Optional.of(fileNames)), session.getUser(), session.getQueryId())); return; } switch (oldPartitionAction.getType()) { case DROP: throw new PartitionNotFoundException(schemaTableName, partitionValues); case ADD: case ALTER: case INSERT_EXISTING: throw new UnsupportedOperationException("Inserting into a partition that were added, altered, or inserted into in the same transaction is not supported"); default: throw new IllegalStateException("Unknown action type"); } } public synchronized Set<String> getRoles(String user) { checkReadable(); return delegate.getRoles(user); } public synchronized Set<HivePrivilegeInfo> getDatabasePrivileges(String user, String databaseName) { checkReadable(); return delegate.getDatabasePrivileges(user, databaseName); } public synchronized Set<HivePrivilegeInfo> getTablePrivileges(String user, String databaseName, String tableName) { checkReadable(); SchemaTableName schemaTableName = new SchemaTableName(databaseName, tableName); Action<TableAndMore> tableAction = tableActions.get(schemaTableName); if (tableAction == null) { return delegate.getTablePrivileges(user, databaseName, tableName); } switch (tableAction.getType()) { case ADD: case ALTER: { if (!user.equals(tableAction.getData().getTable().getOwner())) { throw new PrestoException(NOT_SUPPORTED, "Cannot access a table newly created in the transaction with a different user"); } Collection<HivePrivilegeInfo> privileges = tableAction.getData().getPrincipalPrivileges().getUserPrivileges().get(user); return ImmutableSet.<HivePrivilegeInfo>builder() .addAll(privileges) .add(new HivePrivilegeInfo(OWNERSHIP, true)) .build(); } case INSERT_EXISTING: return delegate.getTablePrivileges(user, databaseName, tableName); case DROP: throw new TableNotFoundException(schemaTableName); default: throw new IllegalStateException("Unknown action type"); } } public synchronized void grantTablePrivileges(String databaseName, String tableName, String grantee, Set<HivePrivilegeInfo> privileges) { setExclusive((delegate, hdfsEnvironment) -> delegate.grantTablePrivileges(databaseName, tableName, grantee, privileges)); } public synchronized void revokeTablePrivileges(String databaseName, String tableName, String grantee, Set<HivePrivilegeInfo> privileges) { setExclusive((delegate, hdfsEnvironment) -> delegate.revokeTablePrivileges(databaseName, tableName, grantee, privileges)); } public synchronized void declareIntentionToWrite(ConnectorSession session, WriteMode writeMode, Path stagingPathRoot, String filePrefix, SchemaTableName schemaTableName) { setShared(); if (writeMode == WriteMode.DIRECT_TO_TARGET_EXISTING_DIRECTORY) { Map<List<String>, Action<PartitionAndMore>> partitionActionsOfTable = partitionActions.get(schemaTableName); if (partitionActionsOfTable != null && !partitionActionsOfTable.isEmpty()) { throw new PrestoException(NOT_SUPPORTED, "Can not insert into a table with a partition that has been modified in the same transaction when Presto is configured to skip temporary directories."); } } declaredIntentionsToWrite.add(new DeclaredIntentionToWrite(writeMode, session.getUser(), stagingPathRoot, filePrefix, schemaTableName)); } public synchronized void commit() { try { switch (state) { case EMPTY: break; case SHARED_OPERATION_BUFFERED: commitShared(); break; case EXCLUSIVE_OPERATION_BUFFERED: requireNonNull(bufferedExclusiveOperation, "bufferedExclusiveOperation is null"); bufferedExclusiveOperation.execute(delegate, hdfsEnvironment); break; case FINISHED: throw new IllegalStateException("Tried to commit buffered metastore operations after transaction has been committed/aborted"); default: throw new IllegalStateException("Unknown state"); } } finally { state = State.FINISHED; } } public synchronized void rollback() { try { switch (state) { case EMPTY: case EXCLUSIVE_OPERATION_BUFFERED: break; case SHARED_OPERATION_BUFFERED: rollbackShared(); break; case FINISHED: throw new IllegalStateException("Tried to rollback buffered metastore operations after transaction has been committed/aborted"); default: throw new IllegalStateException("Unknown state"); } } finally { state = State.FINISHED; } } @GuardedBy("this") private void commitShared() { checkHoldsLock(); Committer committer = new Committer(); try { for (Map.Entry<SchemaTableName, Action<TableAndMore>> entry : tableActions.entrySet()) { SchemaTableName schemaTableName = entry.getKey(); Action<TableAndMore> action = entry.getValue(); switch (action.getType()) { case DROP: committer.prepareDropTable(schemaTableName); break; case ALTER: committer.prepareAlterTable(); break; case ADD: committer.prepareAddTable(action.getUser(), action.getData()); break; case INSERT_EXISTING: committer.prepareInsertExistingTable(action.getUser(), action.getData()); break; default: throw new IllegalStateException("Unknown action type"); } } for (Map.Entry<SchemaTableName, Map<List<String>, Action<PartitionAndMore>>> tableEntry : partitionActions.entrySet()) { SchemaTableName schemaTableName = tableEntry.getKey(); for (Map.Entry<List<String>, Action<PartitionAndMore>> partitionEntry : tableEntry.getValue().entrySet()) { List<String> partitionValues = partitionEntry.getKey(); Action<PartitionAndMore> action = partitionEntry.getValue(); switch (action.getType()) { case DROP: committer.prepareDropPartition(schemaTableName, partitionValues); break; case ALTER: committer.prepareAlterPartition(action.getQueryId(), action.getUser(), action.getData()); break; case ADD: committer.prepareAddPartition(action.getUser(), action.getData()); break; case INSERT_EXISTING: committer.prepareInsertExistingPartition(action.getUser(), action.getData()); break; default: throw new IllegalStateException("Unknown action type"); } } } // Wait for all renames submitted for "INSERT_EXISTING" action to finish committer.waitForAsyncRenames(); // At this point, all file system operations, whether asynchronously issued or not, have completed successfully. // We are moving on to metastore operations now. committer.executeAddTableOperations(); committer.executeAlterPartitionOperations(); committer.executeAddPartitionOperations(); } catch (Throwable t) { committer.cancelUnstartedAsyncRenames(); committer.undoAddPartitionOperations(); committer.undoAddTableOperations(); committer.waitForAsyncRenamesSuppressThrowables(); // fileRenameFutures must all come back before any file system cleanups are carried out. // Otherwise, files that should be deleted may be created after cleanup is done. committer.executeCleanupTasksForAbort(committer.extractFilePrefixes(declaredIntentionsToWrite)); committer.executeRenameTasksForAbort(); // Partition directory must be put back before relevant metastore operation can be undone committer.undoAlterPartitionOperations(); rollbackShared(); throw t; } try { // After this line, operations are no longer reversible. // The next section will deal with "dropping table/partition". Commit may still fail in // this section. Even if commit fails, cleanups, instead of rollbacks, will be executed. committer.executeIrreversibleMetastoreOperations(); // If control flow reached this point, this commit is considered successful no matter // what happens later. The only kind of operations that haven't been carried out yet // are cleanups. // The program control flow will go to finally next. And cleanup will run because // moveForwardInFinally has been set to false. } finally { // In this method, all operations are best-effort clean up operations. // If any operation fails, the error will be logged and ignored. // Additionally, other clean up operations should still be attempted. // Execute deletion tasks committer.executeDeletionTasksForFinish(); // Clean up empty staging directories (that may recursively contain empty directories) committer.deleteEmptyStagingDirectories(declaredIntentionsToWrite); } } private class Committer { private final AtomicBoolean fileRenameCancelled = new AtomicBoolean(false); private final List<CompletableFuture<?>> fileRenameFutures = new ArrayList<>(); // File system // For file system changes, only operations outside of writing paths (as specified in declared intentions to write) // need to MOVE_BACKWARD tasks scheduled. Files in writing paths are handled by rollbackShared(). private final List<DirectoryDeletionTask> deletionTasksForFinish = new ArrayList<>(); private final List<DirectoryCleanUpTask> cleanUpTasksForAbort = new ArrayList<>(); private final List<DirectoryRenameTask> renameTasksForAbort = new ArrayList<>(); // Metastore private final List<CreateTableOperation> addTableOperations = new ArrayList<>(); private final Map<SchemaTableName, PartitionAdder> partitionAdders = new HashMap<>(); private final List<AlterPartitionOperation> alterPartitionOperations = new ArrayList<>(); private final List<IrreversibleMetastoreOperation> metastoreDeleteOperations = new ArrayList<>(); private void prepareDropTable(SchemaTableName schemaTableName) { metastoreDeleteOperations.add(new IrreversibleMetastoreOperation( format("drop table %s", schemaTableName), () -> delegate.dropTable(schemaTableName.getSchemaName(), schemaTableName.getTableName(), true))); } private void prepareAlterTable() { // Currently, ALTER action is never constructed for tables. Dropping a table and then re-creating it // in the same transaction is not supported now. The following line should be replaced with actual // implementation when create after drop support is introduced for a table. throw new UnsupportedOperationException("Dropping and then creating a table with the same name is not supported"); } private void prepareAddTable(String user, TableAndMore tableAndMore) { Table table = tableAndMore.getTable(); if (table.getTableType().equals(MANAGED_TABLE.name())) { String targetLocation = table.getStorage().getLocation(); checkArgument(!targetLocation.isEmpty(), "target location is empty"); Optional<Path> currentPath = tableAndMore.getCurrentLocation(); Path targetPath = new Path(targetLocation); if (table.getPartitionColumns().isEmpty() && currentPath.isPresent()) { // CREATE TABLE AS SELECT unpartitioned table if (targetPath.equals(currentPath.get())) { // Target path and current path are the same. Therefore, directory move is not needed. } else { renameDirectory( user, hdfsEnvironment, currentPath.get(), targetPath, () -> cleanUpTasksForAbort.add(new DirectoryCleanUpTask(user, targetPath, true))); } } else { // CREATE TABLE AS SELECT partitioned table, or // CREATE TABLE partitioned/unpartitioned table (without data) if (pathExists(user, hdfsEnvironment, targetPath)) { if (currentPath.isPresent() && currentPath.get().equals(targetPath)) { // It is okay to skip directory creation when currentPath is equal to targetPath // because the directory may have been created when creating partition directories. // However, it is important to note that the two being equal does not guarantee // a directory had been created. } else { throw new PrestoException( HIVE_PATH_ALREADY_EXISTS, format("Unable to create directory %s: target directory already exists", targetPath)); } } else { cleanUpTasksForAbort.add(new DirectoryCleanUpTask(user, targetPath, true)); createDirectory(user, hdfsEnvironment, targetPath); } } } addTableOperations.add(new CreateTableOperation(table, tableAndMore.getPrincipalPrivileges())); } private void prepareInsertExistingTable(String user, TableAndMore tableAndMore) { Table table = tableAndMore.getTable(); Path targetPath = new Path(table.getStorage().getLocation()); Path currentPath = tableAndMore.getCurrentLocation().get(); cleanUpTasksForAbort.add(new DirectoryCleanUpTask(user, targetPath, false)); if (!targetPath.equals(currentPath)) { asyncRename(hdfsEnvironment, renameExecutor, fileRenameCancelled, fileRenameFutures, user, currentPath, targetPath, tableAndMore.getFileNames().get()); } } private void prepareDropPartition(SchemaTableName schemaTableName, List<String> partitionValues) { metastoreDeleteOperations.add(new IrreversibleMetastoreOperation( format("drop partition %s.%s %s", schemaTableName, schemaTableName.getTableName(), partitionValues), () -> delegate.dropPartition(schemaTableName.getSchemaName(), schemaTableName.getTableName(), partitionValues, true))); } private void prepareAlterPartition(String queryId, String user, PartitionAndMore partitionAndMore) { Partition partition = partitionAndMore.getPartition(); String targetLocation = partition.getStorage().getLocation(); Optional<Partition> oldPartition = delegate.getPartition(partition.getDatabaseName(), partition.getTableName(), partition.getValues()); if (!oldPartition.isPresent()) { throw new PrestoException( TRANSACTION_CONFLICT, format("The partition that this transaction modified was deleted in another transaction. %s %s", partition.getTableName(), partition.getValues())); } String oldPartitionLocation = oldPartition.get().getStorage().getLocation(); Path oldPartitionPath = new Path(oldPartitionLocation); // Location of the old partition and the new partition can be different because we allow arbitrary directories through LocationService. // If the location of the old partition is the same as the location of the new partition: // * Rename the old data directory to a temporary path with a special suffix // * Remember we will need to delete that directory at the end if transaction successfully commits // * Remember we will need to undo the rename if transaction aborts // Otherwise, // * Remember we will need to delete the location of the old partition at the end if transaction successfully commits if (targetLocation.equals(oldPartitionLocation)) { Path oldPartitionStagingPath = new Path(oldPartitionPath.getParent(), "_temp_" + oldPartitionPath.getName() + "_" + queryId); renameDirectory( user, hdfsEnvironment, oldPartitionPath, oldPartitionStagingPath, () -> renameTasksForAbort.add(new DirectoryRenameTask(user, oldPartitionStagingPath, oldPartitionPath))); if (!skipDeletionForAlter) { deletionTasksForFinish.add(new DirectoryDeletionTask(user, oldPartitionStagingPath)); } } else { if (!skipDeletionForAlter) { deletionTasksForFinish.add(new DirectoryDeletionTask(user, oldPartitionPath)); } } Path currentPath = partitionAndMore.getCurrentLocation(); Path targetPath = new Path(targetLocation); if (!targetPath.equals(currentPath)) { renameDirectory( user, hdfsEnvironment, currentPath, targetPath, () -> cleanUpTasksForAbort.add(new DirectoryCleanUpTask(user, targetPath, true))); } // Partition alter must happen regardless of whether original and current location is the same // because metadata might change: e.g. storage format, column types, etc alterPartitionOperations.add(new AlterPartitionOperation(partition, oldPartition.get())); } private void prepareAddPartition(String user, PartitionAndMore partitionAndMore) { Partition partition = partitionAndMore.getPartition(); String targetLocation = partition.getStorage().getLocation(); Path currentPath = partitionAndMore.getCurrentLocation(); Path targetPath = new Path(targetLocation); SchemaTableName schemaTableName = new SchemaTableName(partition.getDatabaseName(), partition.getTableName()); PartitionAdder partitionAdder = partitionAdders.computeIfAbsent( schemaTableName, ignored -> new PartitionAdder(partition.getDatabaseName(), partition.getTableName(), delegate, PARTITION_COMMIT_BATCH_SIZE)); if (!targetPath.equals(currentPath)) { renameDirectory( user, hdfsEnvironment, currentPath, targetPath, () -> cleanUpTasksForAbort.add(new DirectoryCleanUpTask(user, targetPath, true))); } partitionAdder.addPartition(partition); } private void prepareInsertExistingPartition(String user, PartitionAndMore partitionAndMore) { Partition partition = partitionAndMore.getPartition(); Path targetPath = new Path(partition.getStorage().getLocation()); Path currentPath = partitionAndMore.getCurrentLocation(); cleanUpTasksForAbort.add(new DirectoryCleanUpTask(user, targetPath, false)); if (!targetPath.equals(currentPath)) { asyncRename(hdfsEnvironment, renameExecutor, fileRenameCancelled, fileRenameFutures, user, currentPath, targetPath, partitionAndMore.getFileNames()); } } private void executeCleanupTasksForAbort(List<String> filePrefixes) { for (DirectoryCleanUpTask cleanUpTask : cleanUpTasksForAbort) { recursiveDeleteFilesAndLog(cleanUpTask.getUser(), cleanUpTask.getPath(), filePrefixes, cleanUpTask.isDeleteEmptyDirectory(), "temporary directory commit abort"); } } private void executeDeletionTasksForFinish() { for (DirectoryDeletionTask deletionTask : deletionTasksForFinish) { if (!deleteRecursivelyIfExists(deletionTask.getUser(), hdfsEnvironment, deletionTask.getPath())) { logCleanupFailure("Error deleting directory %s", deletionTask.getPath().toString()); } } } private void executeRenameTasksForAbort() { for (DirectoryRenameTask directoryRenameTask : renameTasksForAbort) { try { // Ignore the task if the source directory doesn't exist. // This is probably because the original rename that we are trying to undo here never succeeded. if (pathExists(directoryRenameTask.getUser(), hdfsEnvironment, directoryRenameTask.getRenameFrom())) { renameDirectory(directoryRenameTask.getUser(), hdfsEnvironment, directoryRenameTask.getRenameFrom(), directoryRenameTask.getRenameTo(), () -> { }); } } catch (Throwable throwable) { logCleanupFailure(throwable, "failed to undo rename of partition directory: %s to %s", directoryRenameTask.getRenameFrom(), directoryRenameTask.getRenameTo()); } } } private void deleteEmptyStagingDirectories(List<DeclaredIntentionToWrite> declaredIntentionsToWrite) { for (DeclaredIntentionToWrite declaredIntentionToWrite : declaredIntentionsToWrite) { if (declaredIntentionToWrite.getMode() != WriteMode.STAGE_AND_MOVE_TO_TARGET_DIRECTORY) { continue; } Path path = declaredIntentionToWrite.getRootPath(); recursiveDeleteFilesAndLog(declaredIntentionToWrite.getUser(), path, ImmutableList.of(), true, "staging directory cleanup"); } } private void waitForAsyncRenames() { for (CompletableFuture<?> fileRenameFuture : fileRenameFutures) { MoreFutures.getFutureValue(fileRenameFuture, PrestoException.class); } } private void waitForAsyncRenamesSuppressThrowables() { for (CompletableFuture<?> future : fileRenameFutures) { try { future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Throwable t) { // ignore } } } private void cancelUnstartedAsyncRenames() { fileRenameCancelled.set(true); } private void executeAddTableOperations() { for (CreateTableOperation addTableOperation : addTableOperations) { addTableOperation.run(delegate); } } private void executeAlterPartitionOperations() { for (AlterPartitionOperation alterPartitionOperation : alterPartitionOperations) { alterPartitionOperation.run(delegate); } } private void executeAddPartitionOperations() { for (PartitionAdder partitionAdder : partitionAdders.values()) { partitionAdder.execute(); } } private void undoAddPartitionOperations() { for (PartitionAdder partitionAdder : partitionAdders.values()) { List<List<String>> partitionsFailedToRollback = partitionAdder.rollback(); if (!partitionsFailedToRollback.isEmpty()) { logCleanupFailure("Failed to rollback: add_partition for partitions %s.%s %s", partitionAdder.getSchemaName(), partitionAdder.getTableName(), partitionsFailedToRollback.stream()); } } } private void undoAddTableOperations() { for (CreateTableOperation addTableOperation : addTableOperations) { try { addTableOperation.undo(delegate); } catch (Throwable throwable) { logCleanupFailure(throwable, "failed to rollback: %s", addTableOperation.getDescription()); } } } private void undoAlterPartitionOperations() { for (AlterPartitionOperation alterPartitionOperation : alterPartitionOperations) { try { alterPartitionOperation.undo(delegate); } catch (Throwable throwable) { logCleanupFailure(throwable, "failed to rollback: %s", alterPartitionOperation.getDescription()); } } } private void executeIrreversibleMetastoreOperations() { List<String> failedIrreversibleOperationDescriptions = new ArrayList<>(); List<Throwable> suppressedExceptions = new ArrayList<>(); for (IrreversibleMetastoreOperation irreversibleMetastoreOperation : metastoreDeleteOperations) { try { irreversibleMetastoreOperation.run(); } catch (Throwable t) { failedIrreversibleOperationDescriptions.add(irreversibleMetastoreOperation.getDescription()); // A limit is needed to avoid having a huge exception object. 5 was chosen arbitrarily. if (suppressedExceptions.size() < 5) { suppressedExceptions.add(t); } } } if (!suppressedExceptions.isEmpty()) { PrestoException prestoException = new PrestoException( HIVE_METASTORE_ERROR, format( "The transaction didn't commit cleanly. Failed to execute some metastore delete operations: %s", failedIrreversibleOperationDescriptions.stream() .collect(Collectors.joining("; ")))); suppressedExceptions.forEach(prestoException::addSuppressed); throw prestoException; } } private List<String> extractFilePrefixes(List<DeclaredIntentionToWrite> declaredIntentionsToWrite) { Set<String> filePrefixSet = new HashSet<>(); for (DeclaredIntentionToWrite declaredIntentionToWrite : declaredIntentionsToWrite) { filePrefixSet.add(declaredIntentionToWrite.getFilePrefix()); } return ImmutableList.copyOf(filePrefixSet); } } @GuardedBy("this") private void rollbackShared() { checkHoldsLock(); for (DeclaredIntentionToWrite declaredIntentionToWrite : declaredIntentionsToWrite) { switch (declaredIntentionToWrite.getMode()) { case STAGE_AND_MOVE_TO_TARGET_DIRECTORY: case DIRECT_TO_TARGET_NEW_DIRECTORY: { // Note: there is no need to cleanup the target directory as it will only be written // to during the commit call and the commit call cleans up after failures. Path rootPath = declaredIntentionToWrite.getRootPath(); // In the case of DIRECT_TO_TARGET_NEW_DIRECTORY, if the directory is not guaranteed to be unique // for the query, it is possible that another query or compute engine may see the directory, wrote // data to it, and exported it through metastore. Therefore it may be argued that cleanup of staging // directories must be carried out conservatively. To be safe, we only delete files that start with // the unique prefix for queries in this transaction. recursiveDeleteFilesAndLog( declaredIntentionToWrite.getUser(), rootPath, ImmutableList.of(declaredIntentionToWrite.getFilePrefix()), true, format("staging/target_new directory rollback for table %s", declaredIntentionToWrite.getSchemaTableName())); break; } case DIRECT_TO_TARGET_EXISTING_DIRECTORY: { Set<Path> pathsToClean = new HashSet<>(); // Check the base directory of the declared intention // * existing partition may also be in this directory // * this is where new partitions are created Path baseDirectory = declaredIntentionToWrite.getRootPath(); pathsToClean.add(baseDirectory); SchemaTableName schemaTableName = declaredIntentionToWrite.getSchemaTableName(); Optional<Table> table = delegate.getTable(schemaTableName.getSchemaName(), schemaTableName.getTableName()); if (table.isPresent()) { // check every existing partition that is outside for the base directory if (!table.get().getPartitionColumns().isEmpty()) { List<String> partitionNames = delegate.getPartitionNames(schemaTableName.getSchemaName(), schemaTableName.getTableName()) .orElse(ImmutableList.of()); for (List<String> partitionNameBatch : Iterables.partition(partitionNames, 10)) { Collection<Optional<Partition>> partitions = delegate.getPartitionsByNames(schemaTableName.getSchemaName(), schemaTableName.getTableName(), partitionNameBatch).values(); partitions.stream() .filter(Optional::isPresent) .map(Optional::get) .map(partition -> partition.getStorage().getLocation()) .map(Path::new) .filter(path -> !isSameOrParent(baseDirectory, path)) .forEach(pathsToClean::add); } } } else { logCleanupFailure( "Error rolling back write to table %s.%s. Data directory may contain temporary data. Table was dropped in another transaction.", schemaTableName.getSchemaName(), schemaTableName.getTableName()); } // delete any file that starts with the unique prefix of this query for (Path path : pathsToClean) { // TODO: It is a known deficiency that some empty directory does not get cleaned up in S3. // We can not delete any of the directories here since we do not know who created them. recursiveDeleteFilesAndLog( declaredIntentionToWrite.getUser(), path, ImmutableList.of(declaredIntentionToWrite.getFilePrefix()), false, format("target_existing directory rollback for table %s", schemaTableName)); } break; } default: throw new UnsupportedOperationException("Unknown write mode"); } } } @VisibleForTesting public synchronized void testOnlyCheckIsReadOnly() { if (state != State.EMPTY) { throw new AssertionError("Test did not commit or rollback"); } } @VisibleForTesting public void testOnlyThrowOnCleanupFailures() { throwOnCleanupFailure = true; } @GuardedBy("this") private void checkReadable() { checkHoldsLock(); switch (state) { case EMPTY: case SHARED_OPERATION_BUFFERED: return; case EXCLUSIVE_OPERATION_BUFFERED: throw new PrestoException(NOT_SUPPORTED, "Unsupported combination of operations in a single transaction"); case FINISHED: throw new IllegalStateException("Tried to access metastore after transaction has been committed/aborted"); } } @GuardedBy("this") private void setShared() { checkHoldsLock(); checkReadable(); state = State.SHARED_OPERATION_BUFFERED; } @GuardedBy("this") private void setExclusive(ExclusiveOperation exclusiveOperation) { checkHoldsLock(); if (state != State.EMPTY) { throw new PrestoException(StandardErrorCode.NOT_SUPPORTED, "Unsupported combination of operations in a single transaction"); } state = State.EXCLUSIVE_OPERATION_BUFFERED; bufferedExclusiveOperation = exclusiveOperation; } @GuardedBy("this") private void checkNoPartitionAction(String databaseName, String tableName) { checkHoldsLock(); Map<List<String>, Action<PartitionAndMore>> partitionActionsOfTable = partitionActions.get(new SchemaTableName(databaseName, tableName)); if (partitionActionsOfTable != null && !partitionActionsOfTable.isEmpty()) { throw new PrestoException(NOT_SUPPORTED, "Cannot make schema changes to a table/view with modified partitions in the same transaction"); } } private static boolean isSameOrParent(Path parent, Path child) { int parentDepth = parent.depth(); int childDepth = child.depth(); if (parentDepth > childDepth) { return false; } for (int i = childDepth; i > parentDepth; i--) { child = child.getParent(); } return parent.equals(child); } private void logCleanupFailure(String format, Object... args) { if (throwOnCleanupFailure) { throw new RuntimeException(format(format, args)); } log.warn(format, args); } private void logCleanupFailure(Throwable t, String format, Object... args) { if (throwOnCleanupFailure) { throw new RuntimeException(format(format, args), t); } log.warn(t, format, args); } private static void asyncRename( HdfsEnvironment hdfsEnvironment, Executor executor, AtomicBoolean cancelled, List<CompletableFuture<?>> fileRenameFutures, String user, Path currentPath, Path targetPath, List<String> fileNames) { FileSystem fileSystem; try { fileSystem = hdfsEnvironment.getFileSystem(user, currentPath); } catch (IOException e) { throw new PrestoException(HIVE_FILESYSTEM_ERROR, format("Error moving data files to final location. Error listing directory %s", currentPath), e); } for (String fileName : fileNames) { Path source = new Path(currentPath, fileName); Path target = new Path(targetPath, fileName); fileRenameFutures.add(CompletableFuture.runAsync(() -> { if (cancelled.get()) { return; } try { if (fileSystem.exists(target) || !fileSystem.rename(source, target)) { throw new PrestoException(HIVE_FILESYSTEM_ERROR, format("Error moving data files from %s to final location %s", source, target)); } } catch (IOException e) { throw new PrestoException(HIVE_FILESYSTEM_ERROR, format("Error moving data files from %s to final location %s", source, target), e); } }, executor)); } } private void recursiveDeleteFilesAndLog(String user, Path directory, List<String> filePrefixes, boolean deleteEmptyDirectories, String reason) { RecursiveDeleteResult recursiveDeleteResult = recursiveDeleteFiles( hdfsEnvironment, user, directory, filePrefixes, deleteEmptyDirectories); if (!recursiveDeleteResult.getNotDeletedEligibleItems().isEmpty()) { logCleanupFailure( "Error deleting directory %s for %s. Some eligible items can not be deleted: %s.", directory.toString(), reason, recursiveDeleteResult.getNotDeletedEligibleItems()); } else if (deleteEmptyDirectories && !recursiveDeleteResult.isDirectoryNoLongerExists()) { logCleanupFailure( "Error deleting directory %s for %s. Can not delete the directory.", directory.toString(), reason); } } /** * Attempt to recursively remove eligible files and/or directories in {@code directory}. * * When {@code filePrefixes} is not present, all files (but not necessarily directories) will be * ineligible. If all files shall be deleted, you can use an empty string as {@code filePrefixes}. * * When {@code deleteEmptySubDirectory} is true, any empty directory (including directories that * were originally empty, and directories that become empty after files prefixed with * {@code filePrefixes} are deleted) will be eligible. * * This method will not delete anything that's neither a directory nor a file. * * @param filePrefixes prefix of files that should be deleted * @param deleteEmptyDirectories whether empty directories should be deleted */ private static RecursiveDeleteResult recursiveDeleteFiles(HdfsEnvironment hdfsEnvironment, String user, Path directory, List<String> filePrefixes, boolean deleteEmptyDirectories) { FileSystem fileSystem; try { fileSystem = hdfsEnvironment.getFileSystem(user, directory); if (!fileSystem.exists(directory)) { return new RecursiveDeleteResult(true, ImmutableList.of()); } } catch (IOException e) { ImmutableList.Builder<String> notDeletedItems = ImmutableList.builder(); notDeletedItems.add(directory.toString() + "/**"); return new RecursiveDeleteResult(false, notDeletedItems.build()); } return doRecursiveDeleteFiles(fileSystem, directory, filePrefixes, deleteEmptyDirectories); } private static RecursiveDeleteResult doRecursiveDeleteFiles(FileSystem fileSystem, Path directory, List<String> filePrefixes, boolean deleteEmptyDirectories) { // don't delete hidden presto directories if (directory.getName().startsWith(".presto")) { return new RecursiveDeleteResult(false, ImmutableList.of()); } FileStatus[] allFiles; try { allFiles = fileSystem.listStatus(directory); } catch (IOException e) { ImmutableList.Builder<String> notDeletedItems = ImmutableList.builder(); notDeletedItems.add(directory.toString() + "/**"); return new RecursiveDeleteResult(false, notDeletedItems.build()); } boolean allDescendentsDeleted = true; ImmutableList.Builder<String> notDeletedEligibleItems = ImmutableList.builder(); for (FileStatus fileStatus : allFiles) { if (HadoopFileStatus.isFile(fileStatus)) { Path filePath = fileStatus.getPath(); String fileName = filePath.getName(); boolean eligible = false; // never delete presto dot files if (!fileName.startsWith(".presto")) { eligible = filePrefixes.stream().anyMatch(fileName::startsWith); } if (eligible) { if (!deleteIfExists(fileSystem, filePath, false)) { allDescendentsDeleted = false; notDeletedEligibleItems.add(filePath.toString()); } } else { allDescendentsDeleted = false; } } else if (HadoopFileStatus.isDirectory(fileStatus)) { RecursiveDeleteResult subResult = doRecursiveDeleteFiles(fileSystem, fileStatus.getPath(), filePrefixes, deleteEmptyDirectories); if (!subResult.isDirectoryNoLongerExists()) { allDescendentsDeleted = false; } if (!subResult.getNotDeletedEligibleItems().isEmpty()) { notDeletedEligibleItems.addAll(subResult.getNotDeletedEligibleItems()); } } else { allDescendentsDeleted = false; notDeletedEligibleItems.add(fileStatus.getPath().toString()); } } if (allDescendentsDeleted && deleteEmptyDirectories) { verify(notDeletedEligibleItems.build().isEmpty()); if (!deleteIfExists(fileSystem, directory, false)) { return new RecursiveDeleteResult(false, ImmutableList.of(directory.toString() + "/")); } return new RecursiveDeleteResult(true, ImmutableList.of()); } return new RecursiveDeleteResult(false, notDeletedEligibleItems.build()); } /** * Attempts to remove the file or empty directory. * * @return true if the location no longer exists */ private static boolean deleteIfExists(FileSystem fileSystem, Path path, boolean recursive) { try { // attempt to delete the path if (fileSystem.delete(path, recursive)) { return true; } // delete failed // check if path still exists return !fileSystem.exists(path); } catch (FileNotFoundException ignored) { // path was already removed or never existed return true; } catch (IOException ignored) { } return false; } /** * Attempts to remove the file or empty directory. * * @return true if the location no longer exists */ private static boolean deleteRecursivelyIfExists(String user, HdfsEnvironment hdfsEnvironment, Path path) { FileSystem fileSystem; try { fileSystem = hdfsEnvironment.getFileSystem(user, path); } catch (IOException ignored) { return false; } return deleteIfExists(fileSystem, path, true); } private static void renameDirectory(String user, HdfsEnvironment hdfsEnvironment, Path source, Path target, Runnable runWhenPathDoesntExist) { if (pathExists(user, hdfsEnvironment, target)) { throw new PrestoException(HIVE_PATH_ALREADY_EXISTS, format("Unable to rename from %s to %s: target directory already exists", source, target)); } if (!pathExists(user, hdfsEnvironment, target.getParent())) { createDirectory(user, hdfsEnvironment, target.getParent()); } // The runnable will assume that if rename fails, it will be okay to delete the directory (if the directory is empty). // This is not technically true because a race condition still exists. runWhenPathDoesntExist.run(); try { if (!hdfsEnvironment.getFileSystem(user, source).rename(source, target)) { throw new PrestoException(HIVE_FILESYSTEM_ERROR, format("Failed to rename %s to %s: rename returned false", source, target)); } } catch (IOException e) { throw new PrestoException(HIVE_FILESYSTEM_ERROR, format("Failed to rename %s to %s", source, target), e); } } private static Optional<String> getPrestoQueryId(Partition partition) { return Optional.ofNullable(partition.getParameters().get(PRESTO_QUERY_ID_NAME)); } private void checkHoldsLock() { // This method serves a similar purpose at runtime as GuardedBy on method serves during static analysis. // This method should not have significant performance impact. If it does, it may be reasonably to remove this method. // This intentionally does not use checkState. if (!Thread.holdsLock(this)) { throw new IllegalStateException(format("Thread must hold a lock on the %s", getClass().getSimpleName())); } } private enum State { EMPTY, SHARED_OPERATION_BUFFERED, EXCLUSIVE_OPERATION_BUFFERED, FINISHED, } public enum WriteMode { STAGE_AND_MOVE_TO_TARGET_DIRECTORY, // common mode for new table or existing table (both new and existing partition) DIRECT_TO_TARGET_NEW_DIRECTORY, // for new table in S3 DIRECT_TO_TARGET_EXISTING_DIRECTORY, // for existing table in S3 (both new and existing partition) // NOTE: Insert overwrite simulation (partition drops and partition additions in the same // transaction get merged and become one or more partition alterations, and get submitted to // metastore in close succession of each other) is not supported for S3. S3 uses the last // mode for insert into existing table. This is hard to support because the directory // containing the old data cannot be deleted until commit. Nor can the old data be moved // (assuming Hive HDFS directory naming convention shall not be violated). As a result, // subsequent insertion will have to write to directory belonging to existing partition. // This undermines the benefit of having insert overwrite simulation. This also makes // dropping of old partition at commit time hard because data added after the logical // "drop" time was added to the directories to be dropped. } private enum ActionType { DROP, ADD, ALTER, INSERT_EXISTING } private enum TableSource { CREATED_IN_THIS_TRANSACTION, PRE_EXISTING_TABLE, // RECREATED_IN_THIS_TRANSACTION is a possible case, but it is not supported with the current implementation } public static class Action<T> { private final ActionType type; private final T data; private final String user; private final String queryId; @JsonCreator public Action(@JsonProperty("type") ActionType type, @JsonProperty("data") T data, @JsonProperty("user") String user, @JsonProperty("queryId") String queryId) { this.type = requireNonNull(type, "type is null"); if (type == ActionType.DROP) { checkArgument(data == null, "data is not null"); } else { requireNonNull(data, "data is null"); } this.data = data; this.user = requireNonNull(user, "user is null"); this.queryId = requireNonNull(queryId, "queryId is null"); } @JsonProperty public ActionType getType() { return type; } public T getData() { checkState(type != ActionType.DROP); return data; } @JsonProperty("data") public T getJsonSerializableData() { return data; } @JsonProperty public String getUser() { return user; } @JsonProperty public String getQueryId() { return queryId; } @Override public String toString() { return toStringHelper(this) .add("type", type) .add("data", data) .toString(); } } private static class TableAndMore { private final Table table; private final Optional<PrincipalPrivileges> principalPrivileges; private final Optional<Path> currentLocation; // unpartitioned table only private final Optional<List<String>> fileNames; public TableAndMore(Table table, Optional<PrincipalPrivileges> principalPrivileges, Optional<Path> currentLocation, Optional<List<String>> fileNames) { this.table = requireNonNull(table, "table is null"); this.principalPrivileges = requireNonNull(principalPrivileges, "principalPrivileges is null"); this.currentLocation = requireNonNull(currentLocation, "currentLocation is null"); this.fileNames = requireNonNull(fileNames, "fileNames is null"); checkArgument(!table.getStorage().getLocation().isEmpty() || !currentLocation.isPresent(), "currentLocation can not be supplied for table without location"); checkArgument(!fileNames.isPresent() || currentLocation.isPresent(), "fileNames can be supplied only when currentLocation is supplied"); } public Table getTable() { return table; } public PrincipalPrivileges getPrincipalPrivileges() { checkState(principalPrivileges.isPresent()); return principalPrivileges.get(); } public Optional<Path> getCurrentLocation() { return currentLocation; } public Optional<List<String>> getFileNames() { return fileNames; } @Override public String toString() { return toStringHelper(this) .add("table", table) .add("principalPrivileges", principalPrivileges) .add("currentLocation", currentLocation) .toString(); } } public static class PartitionAndMore { private final Partition partition; private final Path currentLocation; private final Optional<List<String>> fileNames; public PartitionAndMore(Partition partition, Path currentLocation, Optional<List<String>> fileNames) { this.partition = requireNonNull(partition, "partition is null"); this.currentLocation = requireNonNull(currentLocation, "currentLocation is null"); this.fileNames = requireNonNull(fileNames, "fileNames is null"); } @JsonCreator public PartitionAndMore jsonCreator(@JsonProperty("partition") Partition partition, @JsonProperty("currentLocation") Path currentLocation) { return new PartitionAndMore(partition, currentLocation, Optional.empty()); } @JsonProperty public Partition getPartition() { return partition; } Partition getAugmentedPartitionForInTransactionRead() { // This method augments the location field of the partition to the staging location. // This way, if the partition is accessed in an ongoing transaction, staged data // can be found and accessed. Partition partition = this.partition; String currentLocation = this.currentLocation.toString(); if (!currentLocation.equals(partition.getStorage().getLocation())) { partition = Partition.builder(partition) .withStorage(storage -> storage.setLocation(currentLocation)) .build(); } return partition; } @JsonProperty public Path getCurrentLocation() { return currentLocation; } public List<String> getFileNames() { checkState(fileNames.isPresent()); return fileNames.get(); } } private static class DeclaredIntentionToWrite { private final WriteMode mode; private final String user; private final String filePrefix; private final Path rootPath; private final SchemaTableName schemaTableName; public DeclaredIntentionToWrite(WriteMode mode, String user, Path stagingPathRoot, String filePrefix, SchemaTableName schemaTableName) { this.mode = requireNonNull(mode, "mode is null"); this.user = requireNonNull(user, "user is null"); this.rootPath = requireNonNull(stagingPathRoot, "stagingPathRoot is null"); this.filePrefix = requireNonNull(filePrefix, "filePrefix is null"); this.schemaTableName = requireNonNull(schemaTableName, "schemaTableName is null"); } public WriteMode getMode() { return mode; } public String getUser() { return user; } public String getFilePrefix() { return filePrefix; } public Path getRootPath() { return rootPath; } public SchemaTableName getSchemaTableName() { return schemaTableName; } @Override public String toString() { return toStringHelper(this) .add("mode", mode) .add("user", user) .add("filePrefix", filePrefix) .add("rootPath", rootPath) .add("schemaTableName", schemaTableName) .toString(); } } private static class DirectoryCleanUpTask { private final String user; private final Path path; private final boolean deleteEmptyDirectory; public DirectoryCleanUpTask(String user, Path path, boolean deleteEmptyDirectory) { this.user = user; this.path = path; this.deleteEmptyDirectory = deleteEmptyDirectory; } public String getUser() { return user; } public Path getPath() { return path; } public boolean isDeleteEmptyDirectory() { return deleteEmptyDirectory; } @Override public String toString() { return toStringHelper(this) .add("user", user) .add("path", path) .add("deleteEmptyDirectory", deleteEmptyDirectory) .toString(); } } private static class DirectoryDeletionTask { private final String user; private final Path path; public DirectoryDeletionTask(String user, Path path) { this.user = user; this.path = path; } public String getUser() { return user; } public Path getPath() { return path; } @Override public String toString() { return toStringHelper(this) .add("user", user) .add("path", path) .toString(); } } private static class DirectoryRenameTask { private final String user; private final Path renameFrom; private final Path renameTo; public DirectoryRenameTask(String user, Path renameFrom, Path renameTo) { this.user = requireNonNull(user, "user is null"); this.renameFrom = requireNonNull(renameFrom, "renameFrom is null"); this.renameTo = requireNonNull(renameTo, "renameTo is null"); } public String getUser() { return user; } public Path getRenameFrom() { return renameFrom; } public Path getRenameTo() { return renameTo; } @Override public String toString() { return toStringHelper(this) .add("user", user) .add("renameFrom", renameFrom) .add("renameTo", renameTo) .toString(); } } private static class IrreversibleMetastoreOperation { private final String description; private final Runnable action; public IrreversibleMetastoreOperation(String description, Runnable action) { this.description = requireNonNull(description, "description is null"); this.action = requireNonNull(action, "action is null"); } public String getDescription() { return description; } public void run() { action.run(); } } private static class CreateTableOperation { private final Table table; private final PrincipalPrivileges privileges; private boolean done; public CreateTableOperation(Table table, PrincipalPrivileges privileges) { this.table = requireNonNull(table, "table is null"); this.privileges = requireNonNull(privileges, "privileges is null"); } public String getDescription() { return format("add table %s.%s", table.getDatabaseName(), table.getTableName()); } public void run(ExtendedHiveMetastore metastore) { metastore.createTable(table, privileges); done = true; } public void undo(ExtendedHiveMetastore metastore) { if (!done) { return; } metastore.dropTable(table.getDatabaseName(), table.getTableName(), false); } } private static class AlterPartitionOperation { private final Partition newPartition; private final Partition oldPartition; private boolean done; public AlterPartitionOperation(Partition newPartition, Partition oldPartition) { this.newPartition = requireNonNull(newPartition, "newPartition is null"); this.oldPartition = requireNonNull(oldPartition, "oldPartition is null"); checkArgument(newPartition.getDatabaseName().equals(oldPartition.getDatabaseName())); checkArgument(newPartition.getTableName().equals(oldPartition.getTableName())); checkArgument(newPartition.getValues().equals(oldPartition.getValues())); } public String getDescription() { return format("alter partition %s.%s %s", newPartition.getDatabaseName(), newPartition.getTableName(), newPartition.getValues()); } public void run(ExtendedHiveMetastore metastore) { metastore.alterPartition(newPartition.getDatabaseName(), newPartition.getTableName(), newPartition); done = true; } public void undo(ExtendedHiveMetastore metastore) { if (!done) { return; } metastore.alterPartition(oldPartition.getDatabaseName(), oldPartition.getTableName(), oldPartition); } } private static class PartitionAdder { private final String schemaName; private final String tableName; private final ExtendedHiveMetastore metastore; private final int batchSize; private final List<Partition> partitions; private List<List<String>> createdPartitionValues = new ArrayList<>(); public PartitionAdder(String schemaName, String tableName, ExtendedHiveMetastore metastore, int batchSize) { this.schemaName = schemaName; this.tableName = tableName; this.metastore = metastore; this.batchSize = batchSize; this.partitions = new ArrayList<>(batchSize); } public String getSchemaName() { return schemaName; } public String getTableName() { return tableName; } public void addPartition(Partition partition) { checkArgument(getPrestoQueryId(partition).isPresent()); partitions.add(partition); } public void execute() { List<List<Partition>> batchedPartitions = Lists.partition(partitions, batchSize); for (List<Partition> batch : batchedPartitions) { try { metastore.addPartitions(schemaName, tableName, batch); for (Partition partition : batch) { createdPartitionValues.add(partition.getValues()); } } catch (Throwable t) { // Add partition to the created list conservatively. // Some metastore implementations are known to violate the "all or none" guarantee for add_partitions call. boolean batchCompletelyAdded = true; for (Partition partition : batch) { try { Optional<Partition> remotePartition = metastore.getPartition(schemaName, tableName, partition.getValues()); // getPrestoQueryId(partition) is guaranteed to be non-empty. It is asserted in PartitionAdder.addPartition. if (remotePartition.isPresent() && getPrestoQueryId(remotePartition.get()).equals(getPrestoQueryId(partition))) { createdPartitionValues.add(partition.getValues()); } else { batchCompletelyAdded = false; } } catch (Throwable ignored) { // When partition could not be fetched from metastore, it is not known whether the partition was added. // Deleting the partition when aborting commit has the risk of deleting partition not added in this transaction. // Not deleting the partition may leave garbage behind. The former is much more dangerous than the latter. // Therefore, the partition is not added to the createdPartitionValues list here. batchCompletelyAdded = false; } } // If all the partitions were added successfully, the add_partition operation was actually successful. // For some reason, it threw an exception (communication failure, retry failure after communication failure, etc). // But we would consider it successful anyways. if (!batchCompletelyAdded) { throw t; } } } partitions.clear(); } public List<List<String>> rollback() { // drop created partitions List<List<String>> partitionsFailedToRollback = new ArrayList<>(); for (List<String> createdPartitionValue : createdPartitionValues) { try { metastore.dropPartition(schemaName, tableName, createdPartitionValue, false); } catch (PartitionNotFoundException e) { // Maybe some one deleted the partition we added. // Anyways, we are good because the partition is not there anymore. } catch (Throwable t) { partitionsFailedToRollback.add(createdPartitionValue); } } createdPartitionValues = partitionsFailedToRollback; return partitionsFailedToRollback; } } private static class RecursiveDeleteResult { private final boolean directoryNoLongerExists; private final List<String> notDeletedEligibleItems; public RecursiveDeleteResult(boolean directoryNoLongerExists, List<String> notDeletedEligibleItems) { this.directoryNoLongerExists = directoryNoLongerExists; this.notDeletedEligibleItems = notDeletedEligibleItems; } public boolean isDirectoryNoLongerExists() { return directoryNoLongerExists; } public List<String> getNotDeletedEligibleItems() { return notDeletedEligibleItems; } } private interface ExclusiveOperation { void execute(ExtendedHiveMetastore delegate, HdfsEnvironment hdfsEnvironment); } }
Handle create_table failures in Hive metastore more robustly When Hive metastore responds with failure for create_table calls, it might have succeeded. For example, first create_partition timed out, but the table was actually added. The second call (retry) fails with TableAlreadyExists. This commit changes the behavior so that Presto checks with metastore to see if the table was actually created when failure is encountered. When it was, Presto considers the operation successful.
presto-hive/src/main/java/com/facebook/presto/hive/metastore/SemiTransactionalHiveMetastore.java
Handle create_table failures in Hive metastore more robustly
<ide><path>resto-hive/src/main/java/com/facebook/presto/hive/metastore/SemiTransactionalHiveMetastore.java <ide> } <ide> } <ide> <add> private static Optional<String> getPrestoQueryId(Table table) <add> { <add> return Optional.ofNullable(table.getParameters().get(PRESTO_QUERY_ID_NAME)); <add> } <add> <ide> private static Optional<String> getPrestoQueryId(Partition partition) <ide> { <ide> return Optional.ofNullable(partition.getParameters().get(PRESTO_QUERY_ID_NAME)); <ide> <ide> public CreateTableOperation(Table table, PrincipalPrivileges privileges) <ide> { <del> this.table = requireNonNull(table, "table is null"); <add> requireNonNull(table, "table is null"); <add> checkArgument(getPrestoQueryId(table).isPresent()); <add> this.table = table; <ide> this.privileges = requireNonNull(privileges, "privileges is null"); <ide> } <ide> <ide> <ide> public void run(ExtendedHiveMetastore metastore) <ide> { <del> metastore.createTable(table, privileges); <del> done = true; <add> try { <add> metastore.createTable(table, privileges); <add> done = true; <add> } <add> catch (RuntimeException e) { <add> try { <add> Optional<Table> remoteTable = metastore.getTable(table.getDatabaseName(), table.getTableName()); <add> // getPrestoQueryId(partition) is guaranteed to be non-empty. It is asserted in the constructor. <add> if (remoteTable.isPresent() && getPrestoQueryId(remoteTable.get()).equals(getPrestoQueryId(table))) { <add> done = true; <add> } <add> } <add> catch (RuntimeException ignored) { <add> // When table could not be fetched from metastore, it is not known whether the table was added. <add> // Deleting the table when aborting commit has the risk of deleting table not added in this transaction. <add> // Not deleting the table may leave garbage behind. The former is much more dangerous than the latter. <add> // Therefore, the table is not considered added. <add> } <add> if (!done) { <add> throw e; <add> } <add> } <ide> } <ide> <ide> public void undo(ExtendedHiveMetastore metastore)
Java
mit
12e8e16205d7314b91ae1c7b6e5f9db550e09ab6
0
pardiralli-dev/pardiralli,pardiralli-dev/pardiralli,pardiralli-dev/pardiralli
package ee.pardiralli.domain; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class Search { private String itemId; private String buyersEmail; private String ownersFirstName; private String ownersLastName; private String ownersPhoneNr; }
src/main/java/ee/pardiralli/domain/Search.java
package ee.pardiralli.domain; import lombok.*; @Data @NoArgsConstructor @AllArgsConstructor public class Search { private String itemId; private String buyersEmail; private String ownersFirstName; private String ownersLastName; private String ownersPhoneNr; }
refactor Search, #21
src/main/java/ee/pardiralli/domain/Search.java
refactor Search, #21
<ide><path>rc/main/java/ee/pardiralli/domain/Search.java <ide> package ee.pardiralli.domain; <ide> <del>import lombok.*; <add>import lombok.AllArgsConstructor; <add>import lombok.Data; <add>import lombok.NoArgsConstructor; <ide> <ide> @Data <ide> @NoArgsConstructor
Java
apache-2.0
39f42919190548212298e96a6a94c5bfa4ee6367
0
brianwhu/xillium,brianwhu/xillium,brianwhu/xillium
package org.xillium.core.util; import java.io.*; import java.lang.reflect.*; import java.net.*; import java.util.*; import java.util.logging.*; import org.xillium.base.util.Bytes; import org.xillium.data.DataObject; import org.xillium.data.DataBinder; import org.xillium.data.CachedResultSet; import org.xillium.core.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.deser.std.*; import com.fasterxml.jackson.databind.jsontype.TypeDeserializer; /** * An interface to a remote Xillium service. */ public class RemoteService { private static final Logger _logger = Logger.getLogger(RemoteService.class.getName()); private static final ObjectMapper _mapper = new ObjectMapper() .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .registerModule(new SimpleModule("PureStringDeserializerModule").addDeserializer(String.class, new PureStringDeserializer())); /** * This class represents a response from a remote Xillium service. */ public static class Response { public Map<String, String> params; public Map<String, Object> values; public Map<String, CachedResultSet> tables; public transient byte[] body; Response setResponseBody(byte[] body) { this.body = body; return this; } /** * Stores a String value from <code>params</code> into a DataBinder under a new name. */ public Response store(DataBinder binder, String target, String original) { String value = params.get(original); if (value != null) { binder.put(target, value); } return this; } /** * Stores the content of this response into a DataBinder. */ public Response store(DataBinder binder) { try { for (Map.Entry<String, String> entry: params.entrySet()) { binder.put(entry.getKey(), entry.getValue()); } if (values != null) for (Map.Entry<String, Object> entry: values.entrySet()) { binder.put(entry.getKey(), "json:" + _mapper.writeValueAsString(entry.getValue())); } for (Map.Entry<String, CachedResultSet> entry: tables.entrySet()) { binder.putResultSet(entry.getKey(), entry.getValue()); } } catch (JsonProcessingException x) { throw new RuntimeException(x.getMessage(), x); } return this; } } /** * Calls a remote service with non-static member values in the given DataObject as arguments. */ public static Response call(String server, String service, DataObject data, String... params) { return call(server, service, false, data, params); } /** * Calls a remote service with non-static member values in the given DataObject as arguments. */ public static Response call(String server, String service, boolean suppress, DataObject data, String... params) { List<String> list = new ArrayList<String>(Arrays.asList(params)); for (Field field: data.getClass().getFields()) { if (Modifier.isStatic(field.getModifiers())) continue; field.setAccessible(true); try { Object value = field.get(data); if (value == null) value = ""; try { list.add(field.getName() + '=' + URLEncoder.encode(value.toString(), "UTF-8")); } catch (UnsupportedEncodingException x) { _logger.log(Level.WARNING, value.toString(), x); } } catch (IllegalAccessException x) {} } return call(server, service, suppress, list.toArray(new String[list.size()])); } /** * Calls a remote service with parameters in the given DataBinder as well as in an String list. * * Note: parameters in the data binder whose names start with '_' or '#' are NOT passed to the remote service. */ public static Response call(String server, String service, DataBinder binder, String... params) { return call(server, service, false, binder, params); } /** * Calls a remote service with parameters in the given DataBinder as well as in an String list. * * Note: parameters in the data binder whose names start with '_' or '#' are NOT passed to the remote service. */ public static Response call(String server, String service, boolean suppress, DataBinder binder, String... params) { List<String> list = new ArrayList<String>(Arrays.asList(params)); for (Map.Entry<String, String> entry: binder.entrySet()) { String name = entry.getKey(); if (name.charAt(0) == '_' || name.charAt(0) == '#') continue; try { list.add(name + '=' + URLEncoder.encode(entry.getValue(), "UTF-8")); } catch (UnsupportedEncodingException x) { _logger.log(Level.WARNING, entry.getValue(), x); } } return call(server, service, suppress, list.toArray(new String[list.size()])); } /** * Calls a remote service with a list of "name=value" string values as arguments. */ public static Response call(String server, String service, String... params) { return call(server, service, false, params); } /** * Calls a remote service with a list of "name=value" string values as arguments. */ public static Response call(String server, String service, boolean suppress, String... params) { try { URL url = new URL(server + '/' + service); URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); PrintWriter pw = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "utf-8")); for (String param: params) { _logger.fine(param); pw.print(param); pw.print('&'); } pw.close(); InputStream in = connection.getInputStream(); try { byte[] bytes = Bytes.read(in); try { Response response = _mapper.readValue(bytes, Response.class).setResponseBody(bytes); if (response.params == null) { throw new ServiceException("***ProtocolErrorMissingParams"); } else if (!suppress) { String message = response.params.get(Service.FAILURE_MESSAGE); if (message != null && message.length() > 0) { throw new RemoteServiceException(message); } } return response; } catch (JsonProcessingException x) { _logger.log(Level.WARNING, new String(bytes, "UTF-8")); throw x; } } finally { in.close(); } } catch (RuntimeException x) { throw x; } catch (Exception x) { throw new ServiceException("***RemoteServiceCallFailure", x); } } /*# * A PureStringDeserializer is a Jackson string deserializer that ignores and skips any non-string JSON specifications. */ private static class PureStringDeserializer extends StdScalarDeserializer<String> { private static final UntypedObjectDeserializer _utod = new UntypedObjectDeserializer(); PureStringDeserializer() { super(String.class); } @Override public String deserialize(JsonParser parser, DeserializationContext context) throws IOException { try { return StringDeserializer.instance.deserialize(parser, context); } catch (JsonMappingException x) { _utod.deserialize(parser, context); return null; } } @Override public String deserializeWithType(JsonParser parser, DeserializationContext context, TypeDeserializer deserializer) throws IOException { return deserialize(parser, context); } private static final long serialVersionUID = 5045214689420593104L; } }
core/src/main/java/org/xillium/core/util/RemoteService.java
package org.xillium.core.util; import java.io.*; import java.lang.reflect.*; import java.net.*; import java.util.*; import java.util.logging.*; import org.xillium.base.util.Bytes; import org.xillium.data.DataObject; import org.xillium.data.DataBinder; import org.xillium.data.CachedResultSet; import org.xillium.core.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.deser.std.*; import com.fasterxml.jackson.databind.jsontype.TypeDeserializer; /** * An interface to a remote Xillium service. */ public class RemoteService { private static final Logger _logger = Logger.getLogger(RemoteService.class.getName()); private static final ObjectMapper _mapper = new ObjectMapper() .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .registerModule(new SimpleModule("PureStringDeserializerModule").addDeserializer(String.class, new PureStringDeserializer())); /** * This class represents a response from a remote Xillium service. */ public static class Response { public Map<String, String> params; public Map<String, Object> values; public Map<String, CachedResultSet> tables; public transient byte[] body; Response setResponseBody(byte[] body) { this.body = body; return this; } /** * Stores a String value from <code>params</code> into a DataBinder under a new name. */ public Response store(DataBinder binder, String target, String original) { String value = params.get(original); if (value != null) { binder.put(target, value); } return this; } /** * Stores the content of this response into a DataBinder. */ public Response store(DataBinder binder) { try { for (Map.Entry<String, String> entry: params.entrySet()) { binder.put(entry.getKey(), entry.getValue()); } if (values != null) for (Map.Entry<String, Object> entry: values.entrySet()) { binder.put(entry.getKey(), "json:" + _mapper.writeValueAsString(entry.getValue())); } for (Map.Entry<String, CachedResultSet> entry: tables.entrySet()) { binder.putResultSet(entry.getKey(), entry.getValue()); } } catch (JsonProcessingException x) { throw new RuntimeException(x.getMessage(), x); } return this; } } /** * Calls a remote service with non-static member values in the given DataObject as arguments. */ public static Response call(String server, String service, DataObject data, String... params) { return call(server, service, false, data, params); } /** * Calls a remote service with non-static member values in the given DataObject as arguments. */ public static Response call(String server, String service, boolean suppress, DataObject data, String... params) { List<String> list = new ArrayList<String>(Arrays.asList(params)); for (Field field: data.getClass().getFields()) { if (Modifier.isStatic(field.getModifiers())) continue; field.setAccessible(true); try { Object value = field.get(data); if (value == null) value = ""; list.add(field.getName() + '=' + value); } catch (IllegalAccessException x) {} } return call(server, service, suppress, list.toArray(new String[list.size()])); } /** * Calls a remote service with parameters in the given DataBinder as well as in an String list. * * Note: parameters in the data binder whose names start with '_' or '#' are NOT passed to the remote service. */ public static Response call(String server, String service, DataBinder binder, String... params) { return call(server, service, false, binder, params); } /** * Calls a remote service with parameters in the given DataBinder as well as in an String list. * * Note: parameters in the data binder whose names start with '_' or '#' are NOT passed to the remote service. */ public static Response call(String server, String service, boolean suppress, DataBinder binder, String... params) { List<String> list = new ArrayList<String>(Arrays.asList(params)); for (Map.Entry<String, String> entry: binder.entrySet()) { String name = entry.getKey(); if (name.charAt(0) == '_' || name.charAt(0) == '#') continue; list.add(name + '=' + entry.getValue()); } return call(server, service, suppress, list.toArray(new String[list.size()])); } /** * Calls a remote service with a list of "name=value" string values as arguments. */ public static Response call(String server, String service, String... params) { return call(server, service, false, params); } /** * Calls a remote service with a list of "name=value" string values as arguments. */ public static Response call(String server, String service, boolean suppress, String... params) { try { URL url = new URL(server + '/' + service); URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); PrintWriter pw = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "utf-8")); for (String param: params) { _logger.fine(param); pw.print(param); pw.print('&'); } pw.close(); InputStream in = connection.getInputStream(); try { byte[] bytes = Bytes.read(in); try { Response response = _mapper.readValue(bytes, Response.class).setResponseBody(bytes); if (response.params == null) { throw new ServiceException("***ProtocolErrorMissingParams"); } else if (!suppress) { String message = response.params.get(Service.FAILURE_MESSAGE); if (message != null && message.length() > 0) { throw new RemoteServiceException(message); } } return response; } catch (JsonProcessingException x) { _logger.log(Level.WARNING, new String(bytes, "UTF-8")); throw x; } } finally { in.close(); } } catch (RuntimeException x) { throw x; } catch (Exception x) { throw new ServiceException("***RemoteServiceCallFailure", x); } } /*# * A PureStringDeserializer is a Jackson string deserializer that ignores and skips any non-string JSON specifications. */ private static class PureStringDeserializer extends StdScalarDeserializer<String> { private static final UntypedObjectDeserializer _utod = new UntypedObjectDeserializer(); PureStringDeserializer() { super(String.class); } @Override public String deserialize(JsonParser parser, DeserializationContext context) throws IOException { try { return StringDeserializer.instance.deserialize(parser, context); } catch (JsonMappingException x) { _utod.deserialize(parser, context); return null; } } @Override public String deserializeWithType(JsonParser parser, DeserializationContext context, TypeDeserializer deserializer) throws IOException { return deserialize(parser, context); } private static final long serialVersionUID = 5045214689420593104L; } }
encoding remote call parameters from DataObject/DataBinder
core/src/main/java/org/xillium/core/util/RemoteService.java
encoding remote call parameters from DataObject/DataBinder
<ide><path>ore/src/main/java/org/xillium/core/util/RemoteService.java <ide> try { <ide> Object value = field.get(data); <ide> if (value == null) value = ""; <del> list.add(field.getName() + '=' + value); <add> try { <add> list.add(field.getName() + '=' + URLEncoder.encode(value.toString(), "UTF-8")); <add> } catch (UnsupportedEncodingException x) { <add> _logger.log(Level.WARNING, value.toString(), x); <add> } <ide> } catch (IllegalAccessException x) {} <ide> } <ide> return call(server, service, suppress, list.toArray(new String[list.size()])); <ide> for (Map.Entry<String, String> entry: binder.entrySet()) { <ide> String name = entry.getKey(); <ide> if (name.charAt(0) == '_' || name.charAt(0) == '#') continue; <del> list.add(name + '=' + entry.getValue()); <add> try { <add> list.add(name + '=' + URLEncoder.encode(entry.getValue(), "UTF-8")); <add> } catch (UnsupportedEncodingException x) { <add> _logger.log(Level.WARNING, entry.getValue(), x); <add> } <ide> } <ide> return call(server, service, suppress, list.toArray(new String[list.size()])); <ide> }
JavaScript
mit
f6ffef23d4ce105cc6673c43d2396e8f5f0efd8b
0
kevinchappell/formBuilder,kevinchappell/formBuilder
const { exec } = require('child_process') const pkg = require('../package.json') const commands = [ `cd ${process.env.FORMBUILDER_WEBSITE_DIR || 'site'}/`, `npm version ${pkg.version}`, 'git push origin master', ] // try to deploy the demo try { exec(commands.join(' && '), err => !err && console.log('Site successfully deployed')) } catch (e) { console.error(e) }
tools/deploy-site.js
const { exec } = require('child_process') const pkg = require('../package.json') const commands = [ `npm version ${pkg.version}`, 'git push origin master', ] const cwd = process.env.FORMBUILDER_WEBSITE_DIR || 'site' // try to deploy the demo try { exec(commands.join(' && '), { cwd }, err => !err && console.log('Site successfully deployed')) } catch (e) { console.error(e) }
update deploy-site
tools/deploy-site.js
update deploy-site
<ide><path>ools/deploy-site.js <ide> const pkg = require('../package.json') <ide> <ide> const commands = [ <add> `cd ${process.env.FORMBUILDER_WEBSITE_DIR || 'site'}/`, <ide> `npm version ${pkg.version}`, <ide> 'git push origin master', <ide> ] <ide> <del>const cwd = process.env.FORMBUILDER_WEBSITE_DIR || 'site' <del> <ide> // try to deploy the demo <ide> try { <del> exec(commands.join(' && '), { cwd }, err => !err && console.log('Site successfully deployed')) <add> exec(commands.join(' && '), err => !err && console.log('Site successfully deployed')) <ide> } catch (e) { <ide> console.error(e) <ide> }
Java
agpl-3.0
3fc22b8c4befbc1edb38375302990f820c4be19a
0
VietOpenCPS/opencps-v2,VietOpenCPS/opencps-v2
package org.opencps.statistic.rest.util; import com.liferay.petra.string.StringPool; import com.liferay.portal.kernel.dao.orm.QueryUtil; import com.liferay.portal.kernel.json.JSONObject; import com.liferay.portal.kernel.model.Company; import com.liferay.portal.kernel.search.Document; import com.liferay.portal.kernel.search.Field; import com.liferay.portal.kernel.search.SearchContext; import com.liferay.portal.kernel.search.Sort; import com.liferay.portal.kernel.search.SortFactoryUtil; import com.liferay.portal.kernel.service.CompanyLocalServiceUtil; import com.liferay.portal.kernel.service.ServiceContext; import com.liferay.portal.kernel.util.GetterUtil; import com.liferay.portal.kernel.util.PropsKeys; import com.liferay.portal.kernel.util.PropsUtil; import com.liferay.portal.kernel.util.Validator; import java.time.LocalDate; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import org.opencps.auth.utils.APIDateTimeUtils; import org.opencps.datamgt.action.DictcollectionInterface; import org.opencps.datamgt.action.impl.DictCollectionActions; import org.opencps.datamgt.constants.DictItemTerm; import org.opencps.statistic.rest.dto.GetPersonData; import org.opencps.statistic.rest.dto.GetPersonRequest; import org.opencps.statistic.rest.dto.GetPersonResponse; import org.opencps.statistic.rest.dto.GetVotingResultData; import org.opencps.statistic.rest.dto.GetVotingResultRequest; import org.opencps.statistic.rest.dto.GetVotingResultResponse; import org.opencps.statistic.rest.dto.ServiceDomainData; import org.opencps.statistic.rest.dto.ServiceDomainRequest; import org.opencps.statistic.rest.dto.ServiceDomainResponse; import org.opencps.usermgt.model.Employee; import org.opencps.usermgt.service.EmployeeLocalServiceUtil; import backend.feedback.action.VotingActions; import backend.feedback.action.impl.VotingActionsImpl; import backend.feedback.constants.VotingResultTerm; import backend.feedback.constants.VotingTerm; public class StatisticDataUtil { public static ServiceDomainResponse getLocalServiceDomain(ServiceDomainRequest payload) { ServiceDomainResponse response = new ServiceDomainResponse(); try { Company company = CompanyLocalServiceUtil.getCompanyByMx(PropsUtil.get(PropsKeys.COMPANY_DEFAULT_WEB_ID)); DictcollectionInterface dictItemDataUtil = new DictCollectionActions(); SearchContext searchContext = new SearchContext(); searchContext.setCompanyId(company.getCompanyId()); long groupId = GetterUtil.getLong(payload.getGroupId()); LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>(); if ("ADMINISTRATIVE_REGION".equalsIgnoreCase(DossierStatisticConstants.SERVICE_DOMAIN_CODE)) groupId = 0; params.put("groupId", groupId); params.put("keywords", StringPool.BLANK); params.put("itemLv", StringPool.BLANK); params.put(DictItemTerm.PARENT_ITEM_CODE, StringPool.BLANK); params.put(DictItemTerm.DICT_COLLECTION_CODE, DossierStatisticConstants.SERVICE_DOMAIN_CODE); Sort[] sorts = null; sorts = new Sort[] { SortFactoryUtil.create(DictItemTerm.SIBLING_SEARCH + "_Number_sortable", Sort.INT_TYPE, false) }; JSONObject jsonData = dictItemDataUtil.getDictItems(-1, company.getCompanyId(), groupId, params, sorts, QueryUtil.ALL_POS, QueryUtil.ALL_POS, new ServiceContext()); response.setTotal(jsonData.getInt("total")); List<Document> lstDocs = (List<Document>) jsonData.get("data"); List<ServiceDomainData> lstSDatas = new ArrayList<>(); for (Document doc : lstDocs) { ServiceDomainData sd = new ServiceDomainData(); sd.setItemCode(doc.get(DictItemTerm.ITEM_CODE)); sd.setItemName(doc.get(DictItemTerm.ITEM_NAME)); lstSDatas.add(sd); } response.setData(lstSDatas); } catch (Exception e) { } return response; } public static GetPersonResponse getLocalPersonResponse(GetPersonRequest payload) { GetPersonResponse response = new GetPersonResponse(); VotingActions actions = new VotingActionsImpl(); long groupId = payload.getGroupId(); LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>(); params.put("groupId", String.valueOf(groupId)); try { Company company = CompanyLocalServiceUtil.getCompanyByMx(PropsUtil.get(PropsKeys.COMPANY_DEFAULT_WEB_ID)); if (payload.isCalculate()) { if (payload.getMonth() != null) { params.put("month", payload.getMonth()); } else { params.put("month", Integer.toString(LocalDate.now().getMonthValue())); } if (payload.getYear() != null) { params.put("year", payload.getYear()); } else { params.put("year", Integer.toString(LocalDate.now().getYear())); } } else { if (Validator.isNotNull(payload.getFromStatisticDate())) { params.put(VotingResultTerm.FROM_VOTING_DATE, payload.getFromStatisticDate()); } if (Validator.isNotNull(payload.getToStatisticDate())) { params.put(VotingResultTerm.TO_VOTING_DATE, payload.getToStatisticDate()); } } if (Validator.isNotNull(payload.getGovAgencyCode())) { params.put(VotingTerm.GOV_AGENCY_CODE, payload.getGovAgencyCode()); } params.put(VotingTerm.CLASS_NAME, "employee"); Sort[] sorts = new Sort[] { SortFactoryUtil.create("treeIndex_sortable", Sort.STRING_TYPE, false) }; JSONObject jsonData = actions.getVotingResultStatistic(-1, company.getCompanyId(), groupId, params, sorts, QueryUtil.ALL_POS, QueryUtil.ALL_POS, new ServiceContext()); response.setTotal(jsonData.getInt("total")); List<Document> lstDocs = (List<Document>) jsonData.get("data"); List<GetPersonData> lstDatas = new ArrayList<>(); for (Document doc : lstDocs) { GetPersonData data = new GetPersonData(); data.setUserId(Long.valueOf(doc.get(VotingResultTerm.USER_ID))); data.setGroupId(Long.valueOf(doc.get(Field.GROUP_ID))); try { data.setCreateDate(APIDateTimeUtils.convertDateToString(doc.getDate(VotingResultTerm.CREATE_DATE), APIDateTimeUtils._NORMAL_PARTTERN)); data.setModifiedDate(APIDateTimeUtils.convertDateToString(doc.getDate(Field.MODIFIED_DATE), APIDateTimeUtils._NORMAL_PARTTERN)); } catch (Exception e) { } data.setSelected(GetterUtil.get(doc.get(VotingResultTerm.SELECTED), 0)); data.setClassName(doc.get(VotingTerm.CLASS_NAME)); data.setClassPK(doc.get(VotingTerm.CLASS_PK)); Long employeeId = GetterUtil.getLong(doc.get(VotingTerm.CLASS_PK)); if (employeeId > 0) { Employee employee = EmployeeLocalServiceUtil.fetchEmployee(employeeId); if (employee != null) { data.setEmployeeId(employee.getEmployeeId()); data.setEmployeeName(employee.getFullName()); } } data.setGovAgencyCode(doc.get(VotingTerm.GOV_AGENCY_CODE)); data.setGovAgencyName(doc.get(VotingTerm.GOV_AGENCY_NAME)); data.setVotingCode(doc.get(VotingTerm.VOTING_CODE)); data.setVotingSubject(doc.get(VotingTerm.VOTING_SUBJECT)); lstDatas.add(data); } response.setData(lstDatas); } catch (Exception e) { } return response; } public static GetVotingResultResponse getLocalVotingResponse(GetVotingResultRequest payload) { GetVotingResultResponse response = new GetVotingResultResponse(); VotingActions actions = new VotingActionsImpl(); long groupId = payload.getGroupId(); LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>(); params.put("groupId", String.valueOf(groupId)); try { Company company = CompanyLocalServiceUtil.getCompanyByMx(PropsUtil.get(PropsKeys.COMPANY_DEFAULT_WEB_ID)); if (payload.isCalculate()) { if (payload.getMonth() != null) { params.put("month", payload.getMonth()); } else { params.put("month", Integer.toString(LocalDate.now().getMonthValue())); } if (payload.getYear() != null) { params.put("year", payload.getYear()); } else { params.put("year", Integer.toString(LocalDate.now().getYear())); } } else { if (Validator.isNotNull(payload.getFromVotingDate())) { params.put(VotingResultTerm.FROM_VOTING_DATE, payload.getFromVotingDate()); } if (Validator.isNotNull(payload.getToVotingDate())) { params.put(VotingResultTerm.TO_VOTING_DATE, payload.getFromVotingDate()); } } params.put(VotingTerm.CLASS_NAME, "dossier"); Sort[] sorts = new Sort[] { SortFactoryUtil.create("treeIndex_sortable", Sort.STRING_TYPE, false) }; JSONObject jsonData = actions.getVotingResultStatistic(-1, company.getCompanyId(), groupId, params, sorts, QueryUtil.ALL_POS, QueryUtil.ALL_POS, new ServiceContext()); response.setTotal(jsonData.getInt("total")); List<Document> lstDocs = (List<Document>) jsonData.get("data"); List<GetVotingResultData> lstDatas = new ArrayList<>(); for (Document doc : lstDocs) { GetVotingResultData data = new GetVotingResultData(); data.setUserId(Long.valueOf(doc.get(VotingResultTerm.USER_ID))); data.setGroupId(Long.valueOf(doc.get(Field.GROUP_ID))); try { data.setCreateDate(APIDateTimeUtils.convertDateToString(doc.getDate(VotingResultTerm.CREATE_DATE), APIDateTimeUtils._NORMAL_PARTTERN)); data.setModifiedDate(APIDateTimeUtils.convertDateToString(doc.getDate(Field.MODIFIED_DATE), APIDateTimeUtils._NORMAL_PARTTERN)); } catch (Exception e) { } data.setSelected(GetterUtil.get(doc.get(VotingResultTerm.SELECTED), 0)); data.setClassName(doc.get(VotingTerm.CLASS_NAME)); data.setClassPK(doc.get(VotingTerm.CLASS_PK)); data.setGovAgencyCode(doc.get(VotingTerm.GOV_AGENCY_CODE)); data.setGovAgencyName(doc.get(VotingTerm.GOV_AGENCY_NAME)); data.setVotingCode(doc.get(VotingTerm.VOTING_CODE)); data.setVotingSubject(doc.get(VotingTerm.VOTING_SUBJECT)); data.setDomain(doc.get(VotingTerm.DOMAIN_CODE)); data.setDomainName(doc.get(VotingTerm.DOMAIN_NAME)); lstDatas.add(data); } response.setData(lstDatas); } catch (Exception e) { } return response; } }
modules/backend-statistic-rest/src/main/java/org/opencps/statistic/rest/util/StatisticDataUtil.java
package org.opencps.statistic.rest.util; import com.liferay.petra.string.StringPool; import com.liferay.portal.kernel.dao.orm.QueryUtil; import com.liferay.portal.kernel.json.JSONObject; import com.liferay.portal.kernel.model.Company; import com.liferay.portal.kernel.search.Document; import com.liferay.portal.kernel.search.Field; import com.liferay.portal.kernel.search.SearchContext; import com.liferay.portal.kernel.search.Sort; import com.liferay.portal.kernel.search.SortFactoryUtil; import com.liferay.portal.kernel.service.CompanyLocalServiceUtil; import com.liferay.portal.kernel.service.ServiceContext; import com.liferay.portal.kernel.util.GetterUtil; import com.liferay.portal.kernel.util.PropsKeys; import com.liferay.portal.kernel.util.PropsUtil; import com.liferay.portal.kernel.util.Validator; import java.time.LocalDate; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import org.opencps.auth.utils.APIDateTimeUtils; import org.opencps.datamgt.action.DictcollectionInterface; import org.opencps.datamgt.action.impl.DictCollectionActions; import org.opencps.datamgt.constants.DictItemTerm; import org.opencps.statistic.rest.dto.GetPersonData; import org.opencps.statistic.rest.dto.GetPersonRequest; import org.opencps.statistic.rest.dto.GetPersonResponse; import org.opencps.statistic.rest.dto.GetVotingResultData; import org.opencps.statistic.rest.dto.GetVotingResultRequest; import org.opencps.statistic.rest.dto.GetVotingResultResponse; import org.opencps.statistic.rest.dto.ServiceDomainData; import org.opencps.statistic.rest.dto.ServiceDomainRequest; import org.opencps.statistic.rest.dto.ServiceDomainResponse; import org.opencps.usermgt.model.Employee; import org.opencps.usermgt.service.EmployeeLocalServiceUtil; import backend.feedback.action.VotingActions; import backend.feedback.action.impl.VotingActionsImpl; import backend.feedback.constants.VotingResultTerm; import backend.feedback.constants.VotingTerm; public class StatisticDataUtil { public static ServiceDomainResponse getLocalServiceDomain(ServiceDomainRequest payload) { ServiceDomainResponse response = new ServiceDomainResponse(); try { Company company = CompanyLocalServiceUtil.getCompanyByMx(PropsUtil.get(PropsKeys.COMPANY_DEFAULT_WEB_ID)); DictcollectionInterface dictItemDataUtil = new DictCollectionActions(); SearchContext searchContext = new SearchContext(); searchContext.setCompanyId(company.getCompanyId()); long groupId = GetterUtil.getLong(payload.getGroupId()); LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>(); if ("ADMINISTRATIVE_REGION".equalsIgnoreCase(DossierStatisticConstants.SERVICE_DOMAIN_CODE)) groupId = 0; params.put("groupId", groupId); params.put("keywords", StringPool.BLANK); params.put("itemLv", StringPool.BLANK); params.put(DictItemTerm.PARENT_ITEM_CODE, StringPool.BLANK); params.put(DictItemTerm.DICT_COLLECTION_CODE, DossierStatisticConstants.SERVICE_DOMAIN_CODE); Sort[] sorts = null; sorts = new Sort[] { SortFactoryUtil.create(DictItemTerm.SIBLING_SEARCH + "_Number_sortable", Sort.INT_TYPE, false) }; JSONObject jsonData = dictItemDataUtil.getDictItems(-1, company.getCompanyId(), groupId, params, sorts, QueryUtil.ALL_POS, QueryUtil.ALL_POS, new ServiceContext()); response.setTotal(jsonData.getInt("total")); List<Document> lstDocs = (List<Document>) jsonData.get("data"); List<ServiceDomainData> lstSDatas = new ArrayList<>(); for (Document doc : lstDocs) { ServiceDomainData sd = new ServiceDomainData(); sd.setItemCode(doc.get(DictItemTerm.ITEM_CODE)); sd.setItemName(doc.get(DictItemTerm.ITEM_NAME)); lstSDatas.add(sd); } response.setData(lstSDatas); } catch (Exception e) { } return response; } public static GetPersonResponse getLocalPersonResponse(GetPersonRequest payload) { GetPersonResponse response = new GetPersonResponse(); VotingActions actions = new VotingActionsImpl(); long groupId = payload.getGroupId(); LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>(); params.put("groupId", String.valueOf(groupId)); try { Company company = CompanyLocalServiceUtil.getCompanyByMx(PropsUtil.get(PropsKeys.COMPANY_DEFAULT_WEB_ID)); if (payload.isCalculate()) { if (payload.getMonth() != null) { params.put("month", payload.getMonth()); } else { params.put("month", Integer.toString(LocalDate.now().getMonthValue())); } if (payload.getYear() != null) { params.put("year", payload.getYear()); } else { params.put("year", Integer.toString(LocalDate.now().getYear())); } } else { if (Validator.isNotNull(payload.getFromStatisticDate())) { params.put(VotingResultTerm.FROM_VOTING_DATE, payload.getFromStatisticDate()); } if (Validator.isNotNull(payload.getToStatisticDate())) { params.put(VotingResultTerm.TO_VOTING_DATE, payload.getToStatisticDate()); } } if (Validator.isNotNull(payload.getGovAgencyCode())) { params.put(VotingTerm.GOV_AGENCY_CODE, payload.getGovAgencyCode()); } params.put(VotingTerm.CLASS_NAME, "employee"); Sort[] sorts = new Sort[] { SortFactoryUtil.create("treeIndex_sortable", Sort.STRING_TYPE, false) }; JSONObject jsonData = actions.getVotingResultStatistic(-1, company.getCompanyId(), groupId, params, sorts, QueryUtil.ALL_POS, QueryUtil.ALL_POS, new ServiceContext()); response.setTotal(jsonData.getInt("total")); List<Document> lstDocs = (List<Document>) jsonData.get("data"); List<GetPersonData> lstDatas = new ArrayList<>(); for (Document doc : lstDocs) { GetPersonData data = new GetPersonData(); data.setUserId(Long.valueOf(doc.get(VotingResultTerm.USER_ID))); data.setGroupId(Long.valueOf(doc.get(Field.GROUP_ID))); try { data.setCreateDate(APIDateTimeUtils.convertDateToString(doc.getDate(VotingResultTerm.CREATE_DATE), APIDateTimeUtils._NORMAL_PARTTERN)); data.setModifiedDate(APIDateTimeUtils.convertDateToString(doc.getDate(Field.MODIFIED_DATE), APIDateTimeUtils._NORMAL_PARTTERN)); } catch (Exception e) { } data.setSelected(GetterUtil.get(doc.get(VotingResultTerm.SELECTED), 0)); data.setClassName(doc.get(VotingTerm.CLASS_NAME)); data.setClassPK(doc.get(VotingTerm.CLASS_PK)); Long employeeId = GetterUtil.getLong(doc.get(VotingTerm.CLASS_PK)); if (employeeId > 0) { Employee employee = EmployeeLocalServiceUtil.fetchEmployee(employeeId); if (employee != null) { data.setEmployeeId(employee.getEmployeeId()); data.setEmployeeName(employee.getFullName()); } } data.setGovAgencyCode(doc.get(VotingTerm.GOV_AGENCY_CODE)); data.setGovAgencyName(doc.get(VotingTerm.GOV_AGENCY_NAME)); data.setVotingCode(doc.get(VotingTerm.VOTING_CODE)); data.setVotingSubject(doc.get(VotingTerm.VOTING_SUBJECT)); lstDatas.add(data); } response.setData(lstDatas); } catch (Exception e) { } return response; } public static GetVotingResultResponse getLocalVotingResponse(GetVotingResultRequest payload) { GetVotingResultResponse response = new GetVotingResultResponse(); VotingActions actions = new VotingActionsImpl(); long groupId = payload.getGroupId(); LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>(); params.put("groupId", String.valueOf(groupId)); try { Company company = CompanyLocalServiceUtil.getCompanyByMx(PropsUtil.get(PropsKeys.COMPANY_DEFAULT_WEB_ID)); if (payload.isCalculate()) { if (payload.getMonth() != null) { params.put("month", payload.getMonth()); } else { params.put("month", Integer.toString(LocalDate.now().getMonthValue())); } if (payload.getYear() != null) { params.put("year", payload.getYear()); } else { params.put("year", Integer.toString(LocalDate.now().getYear())); } } else { if (Validator.isNotNull(payload.getFromVotingDate())) { params.put(VotingResultTerm.FROM_VOTING_DATE, payload.getFromVotingDate()); } if (Validator.isNotNull(payload.getToVotingDate())) { params.put(VotingResultTerm.TO_VOTING_DATE, payload.getFromVotingDate()); } } params.put(VotingTerm.CLASS_NAME, "dossier"); Sort[] sorts = new Sort[] { SortFactoryUtil.create("treeIndex_sortable", Sort.STRING_TYPE, false) }; JSONObject jsonData = actions.getVotingResultStatistic(-1, company.getCompanyId(), groupId, params, sorts, QueryUtil.ALL_POS, QueryUtil.ALL_POS, new ServiceContext()); response.setTotal(jsonData.getInt("total")); List<Document> lstDocs = (List<Document>) jsonData.get("data"); List<GetVotingResultData> lstDatas = new ArrayList<>(); for (Document doc : lstDocs) { GetVotingResultData data = new GetVotingResultData(); data.setUserId(Long.valueOf(doc.get(VotingResultTerm.USER_ID))); data.setGroupId(Long.valueOf(doc.get(Field.GROUP_ID))); try { data.setCreateDate(APIDateTimeUtils.convertDateToString(doc.getDate(VotingResultTerm.CREATE_DATE), APIDateTimeUtils._NORMAL_PARTTERN)); data.setModifiedDate(APIDateTimeUtils.convertDateToString(doc.getDate(Field.MODIFIED_DATE), APIDateTimeUtils._NORMAL_PARTTERN)); } catch (Exception e) { } data.setSelected(GetterUtil.get(doc.get(VotingResultTerm.SELECTED), 0)); data.setClassName(doc.get(VotingTerm.CLASS_NAME)); data.setClassPK(doc.get(VotingTerm.CLASS_PK)); data.setGovAgencyCode(doc.get(VotingTerm.GOV_AGENCY_CODE)); data.setGovAgencyName(doc.get(VotingTerm.GOV_AGENCY_NAME)); data.setVotingCode(doc.get(VotingTerm.VOTING_CODE)); data.setVotingSubject(doc.get(VotingTerm.VOTING_SUBJECT)); lstDatas.add(data); } response.setData(lstDatas); } catch (Exception e) { } return response; } }
Update voting statistic
modules/backend-statistic-rest/src/main/java/org/opencps/statistic/rest/util/StatisticDataUtil.java
Update voting statistic
<ide><path>odules/backend-statistic-rest/src/main/java/org/opencps/statistic/rest/util/StatisticDataUtil.java <ide> data.setGovAgencyName(doc.get(VotingTerm.GOV_AGENCY_NAME)); <ide> data.setVotingCode(doc.get(VotingTerm.VOTING_CODE)); <ide> data.setVotingSubject(doc.get(VotingTerm.VOTING_SUBJECT)); <add> data.setDomain(doc.get(VotingTerm.DOMAIN_CODE)); <add> data.setDomainName(doc.get(VotingTerm.DOMAIN_NAME)); <add> <ide> lstDatas.add(data); <ide> } <ide>
Java
lgpl-2.1
12b6c4ced1244a8be72abd2fac0aa1f891f2e09d
0
shuiblue/JDimeForCpp,shuiblue/JDimeForCpp,shuiblue/JDimeForCpp
/******************************************************************************* * Copyright (c) 2013 Olaf Lessenich. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: * Olaf Lessenich - initial API and implementation ******************************************************************************/ /** * */ package de.fosd.jdime.common; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.Set; import org.apache.log4j.Logger; import AST.ASTNode; import AST.BytecodeParser; import AST.CompilationUnit; import AST.ConstructorDecl; import AST.FieldDecl; import AST.FieldDeclaration; import AST.ImportDecl; import AST.InterfaceDecl; import AST.JavaParser; import AST.MethodDecl; import AST.Program; import de.fosd.jdime.common.operations.ConflictOperation; import de.fosd.jdime.common.operations.MergeOperation; import de.fosd.jdime.matcher.Color; import de.fosd.jdime.matcher.Matching; import de.fosd.jdime.strategy.ASTNodeStrategy; import de.fosd.jdime.strategy.MergeStrategy; /** * @author Olaf Lessenich * */ public class ASTNodeArtifact extends Artifact<ASTNodeArtifact> { /** * Logger. */ private static final Logger LOG = Logger.getLogger(ASTNodeArtifact.class); /** * Initializes parser. * * @param p * program */ private static void initParser(final Program p) { p.initJavaParser(new JavaParser() { @Override public CompilationUnit parse(final java.io.InputStream is, final String fileName) throws java.io.IOException, beaver.Parser.Exception { return new parser.JavaParser().parse(is, fileName); } }); } /** * Initializes a program. * * @return program */ private static Program initProgram() { Program program = new Program(); program.state().reset(); program.initBytecodeReader(new BytecodeParser()); initParser(program); return program; } /** * Encapsulated ASTNode. */ private ASTNode<?> astnode = null; /** * Constructor class. */ public ASTNodeArtifact() { } /** * @param astnode * astnode */ public ASTNodeArtifact(final ASTNode<?> astnode) { assert (astnode != null); this.astnode = astnode; } /** * Constructs an ASTNodeArtifact from a FileArtifact. * * @param artifact * file artifact */ public ASTNodeArtifact(final FileArtifact artifact) { assert (artifact != null); setRevision(artifact.getRevision()); ASTNode<?> astnode = null; if (artifact.isEmptyDummy()) { astnode = new ASTNode<>(); setEmptyDummy(true); } else { Program p = initProgram(); p.addSourceFile(artifact.getPath()); astnode = p; } assert (astnode != null); this.astnode = astnode; renumber(1, this); } /* * (non-Javadoc) * * @see * de.fosd.jdime.common.Artifact#addChild(de.fosd.jdime.common.Artifact) */ @Override public final ASTNodeArtifact addChild(final ASTNodeArtifact child) throws IOException { if (child.isConflict()) { child.setParent(this); children.add(child); return child; } ASTNodeArtifact myChild; try { myChild = new ASTNodeArtifact((ASTNode<?>) child.astnode.clone()); myChild.deleteChildren(); myChild.setRevision(child.getRevision()); myChild.setParent(this); myChild.astnode.setParent(astnode); myChild.setRevision(child.getRevision()); myChild.setNumber(child.getNumber()); myChild.cloneMatches(child); if (children == null) { initializeChildren(); } children.add(myChild); // astnode.flushCaches(); if (LOG.isTraceEnabled()) { LOG.trace("Added child " + myChild.getId() + " to parent node " + getId()); } return myChild; } catch (CloneNotSupportedException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new NotYetImplementedException(); } } @Override public final int compareTo(final ASTNodeArtifact o) { if (hasUniqueLabels()) { return astnode.dumpString().compareTo(o.astnode.dumpString()); } else { throw new RuntimeException("This artifact is not comparable."); } } /* * (non-Javadoc) * * @see * de.fosd.jdime.common.Artifact#copyArtifact(de.fosd.jdime.common.Artifact) */ @Override public final void copyArtifact(final ASTNodeArtifact destination) throws IOException { ASTNodeArtifact copy = destination.addChild(this); if (!isConflict() && hasChildren()) { for (ASTNodeArtifact child : getChildren()) { child.copyArtifact(copy); } } } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#createArtifact(boolean) */ @Override public final void createArtifact(final boolean isLeaf) throws IOException { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#createEmptyDummy() */ @Override public final ASTNodeArtifact createEmptyDummy() throws FileNotFoundException { ASTNodeArtifact dummy = new ASTNodeArtifact(); dummy.astnode = new ASTNode<>(); dummy.setEmptyDummy(true); dummy.setRevision(getRevision()); return dummy; } /** * */ public final void deleteChildren() { while (hasChildren()) { ASTNodeArtifact child = getChild(0); child.astnode = null; child = null; children.remove(0); } } /** * Returns the AST in dot-format. * * @param includeNumbers * include node number in label if true * @return AST in dot-format. */ public final String dumpGraphvizTree(final boolean includeNumbers) { assert (astnode != null); StringBuffer sb = new StringBuffer(); sb.append(getNumber() + "[label=\""); // node label if (includeNumbers) { sb.append("(" + getNumber() + ") "); } sb.append(astnode.dumpString()); sb.append("\""); if (hasMatches()) { sb.append(", fillcolor = green, style = filled"); } sb.append("];"); sb.append(System.lineSeparator()); // children for (ASTNodeArtifact child : getChildren()) { sb.append(child.dumpGraphvizTree(includeNumbers)); // edge sb.append(getNumber() + "->" + child.getNumber() + ";" + System.lineSeparator()); } return sb.toString(); } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#dumpTree(java.lang.String) */ @Override protected final String dumpTree(final String indent) { assert (astnode != null); StringBuffer sb = new StringBuffer(); // node itself Matching<ASTNodeArtifact> m = null; // color if (!isConflict() && hasMatches()) { Set<Revision> matchingRevisions = matches.keySet(); // print color code String color = ""; for (Revision rev : matchingRevisions) { m = getMatching(rev); color = m.getColor().toShell(); } sb.append(color); } if (isConflict()) { sb.append(Color.RED.toShell()); sb.append(indent + "(" + getId() + ") "); sb.append(this); sb.append(System.lineSeparator()); sb.append(Color.RED.toShell()); sb.append("<<<<<<< "); sb.append(System.lineSeparator()); // children if (left != null) { sb.append(left.dumpTree(indent)); } sb.append(Color.RED.toShell()); sb.append("======= "); sb.append(System.lineSeparator()); // children if (right != null) { sb.append(right.dumpTree(indent)); } sb.append(Color.RED.toShell()); sb.append(">>>>>>> "); sb.append(System.lineSeparator()); } else { sb.append(indent + "(" + getId() + ") "); sb.append(this); if (hasMatches()) { assert (m != null); sb.append(" <=> (" + m.getMatchingArtifact(this).getId() + ")"); sb.append(Color.DEFAULT.toShell()); } sb.append(System.lineSeparator()); // children for (ASTNodeArtifact child : getChildren()) { sb.append(child.dumpTree(indent + " ")); } } return sb.toString(); } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ // @Override // public final boolean equals(final Object obj) { // assert (astnode != null); // assert (obj != null); // assert (obj instanceof ASTNodeArtifact); // return astnode.dumpString().equals( // ((ASTNodeArtifact) obj).astnode.dumpString()); // } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#exists() */ @Override public final boolean exists() { return astnode != null; } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#getId() */ @Override public final String getId() { return getRevision() + ":" + getNumber(); } @Override public final String getStatsKey(final MergeContext context) { return "nodes"; } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#hashCode() */ @Override public final int hashCode() { return astnode.dumpString().hashCode(); } @Override public final boolean hasUniqueLabels() { if (astnode instanceof ImportDecl) { return true; } return false; } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#initializeChildren() */ @Override public final void initializeChildren() { assert (astnode != null); ArtifactList<ASTNodeArtifact> children = new ArtifactList<ASTNodeArtifact>(); for (int i = 0; i < astnode.getNumChildNoTransform(); i++) { ASTNodeArtifact child = new ASTNodeArtifact(astnode.getChild(i)); child.setParent(this); child.setRevision(getRevision()); children.add(child); } setChildren(children); } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#isEmpty() */ @Override public final boolean isEmpty() { return !hasChildren(); } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#isLeaf() */ @Override public final boolean isLeaf() { // TODO Auto-generated method stub return false; } /** * Returns whether declaration order is significant for this node. * * @return whether declaration order is significant for this node */ public final boolean isOrdered() { if (astnode instanceof CompilationUnit || astnode instanceof ConstructorDecl || astnode instanceof MethodDecl || astnode instanceof InterfaceDecl || astnode instanceof FieldDecl || astnode instanceof FieldDeclaration || astnode instanceof ImportDecl) { return false; } return true; } /** * Returns whether a node matches another node. * * @param other * node to compare with. * @return true if the node matches another node. */ public final boolean matches(final ASTNodeArtifact other) { assert (astnode != null); assert (other != null); assert (other.astnode != null); if (astnode instanceof ImportDecl && other.astnode instanceof ImportDecl) { return astnode.toString().equals(other.astnode.toString()); } return astnode.dumpString().equals(other.astnode.dumpString()); } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#merge(de.fosd.jdime.common.operations. * MergeOperation, de.fosd.jdime.common.MergeContext) */ @Override public final void merge(final MergeOperation<ASTNodeArtifact> operation, final MergeContext context) throws IOException, InterruptedException { assert (operation != null); assert (context != null); MergeStrategy<ASTNodeArtifact> strategy = new ASTNodeStrategy(); if (LOG.isDebugEnabled()) { LOG.debug("Using strategy: " + strategy.toString()); } MergeTriple<ASTNodeArtifact> triple = operation.getMergeTriple(); assert (triple != null); ASTNodeArtifact left, right, target; left = triple.getLeft(); right = triple.getRight(); target = operation.getTarget(); boolean safeMerge = true; try { if (!isRoot() && target.astnode.getClass().newInstance() .getNumChildNoTransform() > 0) { // this language element has a fixed number of children // we need to be careful with this one boolean leftChanges = left.hasChanges(false); boolean rightChanges = right.hasChanges(false); if (leftChanges || rightChanges) { if (LOG.isTraceEnabled()) { LOG.trace("target " + target.getId() + " expects a fixed amount of children."); LOG.trace("changes in " + left.getId() + ": " + leftChanges); LOG.trace("changes in " + right.getId() + ": " + rightChanges); LOG.trace("We will report a conflict instead of performing the merge"); } safeMerge = false; // to be safe, we will report a conflict instead of merging ASTNodeArtifact targetParent = target.getParent(); targetParent.removeChild(target); ConflictOperation conflictOp = new ConflictOperation<>( left, left, right, targetParent); conflictOp.apply(context); } } } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(); } if (safeMerge) { strategy.merge(operation, context); } if (!context.isQuiet() && context.hasOutput()) { System.out.println(context.getStdIn()); } } public final void removeChild(ASTNodeArtifact child) { if (LOG.isTraceEnabled()) { LOG.trace("[" + getId() + "] removing child " + child.getId()); LOG.trace("children before removal: " + getChildren()); } Iterator<ASTNodeArtifact> it = children.iterator(); ASTNodeArtifact elem; while (it.hasNext()) { elem = it.next(); if (elem == child) { it.remove(); } } if (LOG.isTraceEnabled()) { LOG.trace("children after removal: " + getChildren()); } } /** * Pretty-prints the AST to source code. * * @return Pretty-printed AST (source code) */ public final String prettyPrint() { assert (astnode != null); rebuildAST(); astnode.flushCaches(); if (LOG.isDebugEnabled()) { System.out.println(dumpTree()); } return astnode.prettyPrint(); } /** * Rebuild the encapsulated ASTNode tree top down. This should be only * called at the root node */ public final void rebuildAST() { if (isConflict()) { astnode.isConflict = true; astnode.jdimeId = getId(); if (left != null) { left.rebuildAST(); astnode.left = left.astnode; } if (right != null) { right.rebuildAST(); astnode.right= right.astnode; } } ASTNode<?>[] newchildren = new ASTNode[getNumChildren()]; for (int i = 0; i < getNumChildren(); i++) { ASTNodeArtifact child = getChild(i); newchildren[i] = child.astnode; newchildren[i].setParent(astnode); child.rebuildAST(); } astnode.jdimeChanges = hasChanges(); astnode.jdimeId = getId(); astnode.setChildren(newchildren); if (LOG.isTraceEnabled()) { if (getNumChildren() != astnode.getNumChildNoTransform()) { LOG.trace("ASTNodeArtifact has " + getNumChildren() + " children: {" + getChildren() + "}"); StringBuilder sb = new StringBuilder(); sb.append("astnode has " + astnode.getNumChildNoTransform() + " children: {"); ASTNode[] astnodechildren = new ASTNode[astnode.getNumChild()]; for (int i = 0; i < astnode.getNumChild(); i++) { astnodechildren[i] = astnode.getChild(i); } sb.append(Arrays.toString(astnodechildren)); sb.append("}"); LOG.trace(sb); } } assert (isConflict() || getNumChildren() == astnode .getNumChildNoTransform()); } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#toString() */ @Override public final String toString() { assert (astnode != null); return astnode.dumpString(); } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#write(java.lang.String) */ @Override public final void write(final String str) throws IOException { // TODO Auto-generated method stub } /** * @param artifact * artifact to create program from * @return ASTNodeArtifact */ public static ASTNodeArtifact createProgram(final ASTNodeArtifact artifact) { assert (artifact.astnode != null); assert (artifact.astnode instanceof Program); Program program = (Program) artifact.astnode.copy(); // Iterator<CompilationUnit> it = program.compilationUnitIterator(); // while (it.hasNext()) { // CompilationUnit cu = it.next(); // for (int i = 0; i < cu.getNumChild(); i++) { // cu.getImportDeclList().removeChildren(); // cu.getTypeDeclList().removeChildren(); // } // } ASTNodeArtifact p = new ASTNodeArtifact(program); p.deleteChildren(); return p; } @Override public final ASTNodeArtifact createConflictDummy( final ASTNodeArtifact type, final ASTNodeArtifact left, final ASTNodeArtifact right) throws FileNotFoundException { ASTNodeArtifact conflict; conflict = new ASTNodeArtifact(type.astnode.fullCopy()); conflict.setConflict(left, right); return conflict; } }
src/de/fosd/jdime/common/ASTNodeArtifact.java
/******************************************************************************* * Copyright (c) 2013 Olaf Lessenich. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: * Olaf Lessenich - initial API and implementation ******************************************************************************/ /** * */ package de.fosd.jdime.common; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.Set; import org.apache.log4j.Logger; import AST.ASTNode; import AST.BytecodeParser; import AST.CompilationUnit; import AST.ConstructorDecl; import AST.FieldDecl; import AST.FieldDeclaration; import AST.ImportDecl; import AST.InterfaceDecl; import AST.JavaParser; import AST.MethodDecl; import AST.Program; import de.fosd.jdime.common.operations.ConflictOperation; import de.fosd.jdime.common.operations.MergeOperation; import de.fosd.jdime.matcher.Color; import de.fosd.jdime.matcher.Matching; import de.fosd.jdime.strategy.ASTNodeStrategy; import de.fosd.jdime.strategy.MergeStrategy; /** * @author Olaf Lessenich * */ public class ASTNodeArtifact extends Artifact<ASTNodeArtifact> { /** * Logger. */ private static final Logger LOG = Logger.getLogger(ASTNodeArtifact.class); /** * Initializes parser. * * @param p * program */ private static void initParser(final Program p) { p.initJavaParser(new JavaParser() { @Override public CompilationUnit parse(final java.io.InputStream is, final String fileName) throws java.io.IOException, beaver.Parser.Exception { return new parser.JavaParser().parse(is, fileName); } }); } /** * Initializes a program. * * @return program */ private static Program initProgram() { Program program = new Program(); program.state().reset(); program.initBytecodeReader(new BytecodeParser()); initParser(program); return program; } /** * Encapsulated ASTNode. */ private ASTNode<?> astnode = null; /** * Constructor class. */ public ASTNodeArtifact() { } /** * @param astnode * astnode */ public ASTNodeArtifact(final ASTNode<?> astnode) { assert (astnode != null); this.astnode = astnode; } /** * Constructs an ASTNodeArtifact from a FileArtifact. * * @param artifact * file artifact */ public ASTNodeArtifact(final FileArtifact artifact) { assert (artifact != null); setRevision(artifact.getRevision()); ASTNode<?> astnode = null; if (artifact.isEmptyDummy()) { astnode = new ASTNode<>(); setEmptyDummy(true); } else { Program p = initProgram(); p.addSourceFile(artifact.getPath()); astnode = p; } assert (astnode != null); this.astnode = astnode; renumber(1, this); } /* * (non-Javadoc) * * @see * de.fosd.jdime.common.Artifact#addChild(de.fosd.jdime.common.Artifact) */ @Override public final ASTNodeArtifact addChild(final ASTNodeArtifact child) throws IOException { if (child.isConflict()) { child.setParent(this); children.add(child); return child; } ASTNodeArtifact myChild; try { myChild = new ASTNodeArtifact((ASTNode<?>) child.astnode.clone()); myChild.deleteChildren(); myChild.setRevision(child.getRevision()); myChild.setParent(this); myChild.astnode.setParent(astnode); myChild.setRevision(child.getRevision()); myChild.setNumber(child.getNumber()); myChild.cloneMatches(child); if (children == null) { initializeChildren(); } children.add(myChild); // astnode.flushCaches(); if (LOG.isTraceEnabled()) { LOG.trace("Added child " + myChild.getId() + " to parent node " + getId()); } return myChild; } catch (CloneNotSupportedException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new NotYetImplementedException(); } } @Override public final int compareTo(final ASTNodeArtifact o) { if (hasUniqueLabels()) { return astnode.dumpString().compareTo(o.astnode.dumpString()); } else { throw new RuntimeException("This artifact is not comparable."); } } /* * (non-Javadoc) * * @see * de.fosd.jdime.common.Artifact#copyArtifact(de.fosd.jdime.common.Artifact) */ @Override public final void copyArtifact(final ASTNodeArtifact destination) throws IOException { ASTNodeArtifact copy = destination.addChild(this); if (!isConflict() && hasChildren()) { for (ASTNodeArtifact child : getChildren()) { child.copyArtifact(copy); } } } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#createArtifact(boolean) */ @Override public final void createArtifact(final boolean isLeaf) throws IOException { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#createEmptyDummy() */ @Override public final ASTNodeArtifact createEmptyDummy() throws FileNotFoundException { ASTNodeArtifact dummy = new ASTNodeArtifact(); dummy.astnode = new ASTNode<>(); dummy.setEmptyDummy(true); dummy.setRevision(getRevision()); return dummy; } /** * */ public final void deleteChildren() { while (hasChildren()) { ASTNodeArtifact child = getChild(0); child.astnode = null; child = null; children.remove(0); } } /** * Returns the AST in dot-format. * * @param includeNumbers * include node number in label if true * @return AST in dot-format. */ public final String dumpGraphvizTree(final boolean includeNumbers) { assert (astnode != null); StringBuffer sb = new StringBuffer(); sb.append(getNumber() + "[label=\""); // node label if (includeNumbers) { sb.append("(" + getNumber() + ") "); } sb.append(astnode.dumpString()); sb.append("\""); if (hasMatches()) { sb.append(", fillcolor = green, style = filled"); } sb.append("];"); sb.append(System.lineSeparator()); // children for (ASTNodeArtifact child : getChildren()) { sb.append(child.dumpGraphvizTree(includeNumbers)); // edge sb.append(getNumber() + "->" + child.getNumber() + ";" + System.lineSeparator()); } return sb.toString(); } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#dumpTree(java.lang.String) */ @Override protected final String dumpTree(final String indent) { assert (astnode != null); StringBuffer sb = new StringBuffer(); // node itself Matching<ASTNodeArtifact> m = null; // color if (!isConflict() && hasMatches()) { Set<Revision> matchingRevisions = matches.keySet(); // print color code String color = ""; for (Revision rev : matchingRevisions) { m = getMatching(rev); color = m.getColor().toShell(); } sb.append(color); } if (isConflict()) { sb.append(Color.RED.toShell()); sb.append(indent + "(" + getId() + ") "); sb.append(this); sb.append(System.lineSeparator()); sb.append(Color.RED.toShell()); sb.append("<<<<<<< "); sb.append(System.lineSeparator()); // children if (left != null) { sb.append(left.dumpTree(indent)); } sb.append(Color.RED.toShell()); sb.append("======= "); sb.append(System.lineSeparator()); // children if (right != null) { sb.append(right.dumpTree(indent)); } sb.append(Color.RED.toShell()); sb.append(">>>>>>> "); sb.append(System.lineSeparator()); } else { sb.append(indent + "(" + getId() + ") "); sb.append(this); if (hasMatches()) { assert (m != null); sb.append(" <=> (" + m.getMatchingArtifact(this).getId() + ")"); sb.append(Color.DEFAULT.toShell()); } sb.append(System.lineSeparator()); // children for (ASTNodeArtifact child : getChildren()) { sb.append(child.dumpTree(indent + " ")); } } return sb.toString(); } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ // @Override // public final boolean equals(final Object obj) { // assert (astnode != null); // assert (obj != null); // assert (obj instanceof ASTNodeArtifact); // return astnode.dumpString().equals( // ((ASTNodeArtifact) obj).astnode.dumpString()); // } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#exists() */ @Override public final boolean exists() { return astnode != null; } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#getId() */ @Override public final String getId() { return getRevision() + ":" + getNumber(); } @Override public final String getStatsKey(final MergeContext context) { return "nodes"; } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#hashCode() */ @Override public final int hashCode() { return astnode.dumpString().hashCode(); } @Override public final boolean hasUniqueLabels() { return false; } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#initializeChildren() */ @Override public final void initializeChildren() { assert (astnode != null); ArtifactList<ASTNodeArtifact> children = new ArtifactList<ASTNodeArtifact>(); for (int i = 0; i < astnode.getNumChildNoTransform(); i++) { ASTNodeArtifact child = new ASTNodeArtifact(astnode.getChild(i)); child.setParent(this); child.setRevision(getRevision()); children.add(child); } setChildren(children); } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#isEmpty() */ @Override public final boolean isEmpty() { return !hasChildren(); } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#isLeaf() */ @Override public final boolean isLeaf() { // TODO Auto-generated method stub return false; } /** * Returns whether declaration order is significant for this node. * * @return whether declaration order is significant for this node */ public final boolean isOrdered() { if (astnode instanceof CompilationUnit || astnode instanceof ConstructorDecl || astnode instanceof MethodDecl || astnode instanceof InterfaceDecl || astnode instanceof FieldDecl || astnode instanceof FieldDeclaration || astnode instanceof ImportDecl) { return false; } return true; } /** * Returns whether a node matches another node. * * @param other * node to compare with. * @return true if the node matches another node. */ public final boolean matches(final ASTNodeArtifact other) { assert (astnode != null); assert (other != null); assert (other.astnode != null); if (astnode instanceof ImportDecl && other.astnode instanceof ImportDecl) { return astnode.toString().equals(other.astnode.toString()); } return astnode.dumpString().equals(other.astnode.dumpString()); } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#merge(de.fosd.jdime.common.operations. * MergeOperation, de.fosd.jdime.common.MergeContext) */ @Override public final void merge(final MergeOperation<ASTNodeArtifact> operation, final MergeContext context) throws IOException, InterruptedException { assert (operation != null); assert (context != null); MergeStrategy<ASTNodeArtifact> strategy = new ASTNodeStrategy(); if (LOG.isDebugEnabled()) { LOG.debug("Using strategy: " + strategy.toString()); } MergeTriple<ASTNodeArtifact> triple = operation.getMergeTriple(); assert (triple != null); ASTNodeArtifact left, right, target; left = triple.getLeft(); right = triple.getRight(); target = operation.getTarget(); boolean safeMerge = true; try { if (!isRoot() && target.astnode.getClass().newInstance() .getNumChildNoTransform() > 0) { // this language element has a fixed number of children // we need to be careful with this one boolean leftChanges = left.hasChanges(false); boolean rightChanges = right.hasChanges(false); if (leftChanges || rightChanges) { if (LOG.isTraceEnabled()) { LOG.trace("target " + target.getId() + " expects a fixed amount of children."); LOG.trace("changes in " + left.getId() + ": " + leftChanges); LOG.trace("changes in " + right.getId() + ": " + rightChanges); LOG.trace("We will report a conflict instead of performing the merge"); } safeMerge = false; // to be safe, we will report a conflict instead of merging ASTNodeArtifact targetParent = target.getParent(); targetParent.removeChild(target); ConflictOperation conflictOp = new ConflictOperation<>( left, left, right, targetParent); conflictOp.apply(context); } } } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(); } if (safeMerge) { strategy.merge(operation, context); } if (!context.isQuiet() && context.hasOutput()) { System.out.println(context.getStdIn()); } } public final void removeChild(ASTNodeArtifact child) { if (LOG.isTraceEnabled()) { LOG.trace("[" + getId() + "] removing child " + child.getId()); LOG.trace("children before removal: " + getChildren()); } Iterator<ASTNodeArtifact> it = children.iterator(); ASTNodeArtifact elem; while (it.hasNext()) { elem = it.next(); if (elem == child) { it.remove(); } } if (LOG.isTraceEnabled()) { LOG.trace("children after removal: " + getChildren()); } } /** * Pretty-prints the AST to source code. * * @return Pretty-printed AST (source code) */ public final String prettyPrint() { assert (astnode != null); rebuildAST(); astnode.flushCaches(); if (LOG.isDebugEnabled()) { System.out.println(dumpTree()); } return astnode.prettyPrint(); } /** * Rebuild the encapsulated ASTNode tree top down. This should be only * called at the root node */ public final void rebuildAST() { if (isConflict()) { astnode.isConflict = true; astnode.jdimeId = getId(); if (left != null) { left.rebuildAST(); astnode.left = left.astnode; } if (right != null) { right.rebuildAST(); astnode.right= right.astnode; } } ASTNode<?>[] newchildren = new ASTNode[getNumChildren()]; for (int i = 0; i < getNumChildren(); i++) { ASTNodeArtifact child = getChild(i); newchildren[i] = child.astnode; newchildren[i].setParent(astnode); child.rebuildAST(); } astnode.jdimeChanges = hasChanges(); astnode.jdimeId = getId(); astnode.setChildren(newchildren); if (LOG.isTraceEnabled()) { if (getNumChildren() != astnode.getNumChildNoTransform()) { LOG.trace("ASTNodeArtifact has " + getNumChildren() + " children: {" + getChildren() + "}"); StringBuilder sb = new StringBuilder(); sb.append("astnode has " + astnode.getNumChildNoTransform() + " children: {"); ASTNode[] astnodechildren = new ASTNode[astnode.getNumChild()]; for (int i = 0; i < astnode.getNumChild(); i++) { astnodechildren[i] = astnode.getChild(i); } sb.append(Arrays.toString(astnodechildren)); sb.append("}"); LOG.trace(sb); } } assert (isConflict() || getNumChildren() == astnode .getNumChildNoTransform()); } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#toString() */ @Override public final String toString() { assert (astnode != null); return astnode.dumpString(); } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#write(java.lang.String) */ @Override public final void write(final String str) throws IOException { // TODO Auto-generated method stub } /** * @param artifact * artifact to create program from * @return ASTNodeArtifact */ public static ASTNodeArtifact createProgram(final ASTNodeArtifact artifact) { assert (artifact.astnode != null); assert (artifact.astnode instanceof Program); Program program = (Program) artifact.astnode.copy(); // Iterator<CompilationUnit> it = program.compilationUnitIterator(); // while (it.hasNext()) { // CompilationUnit cu = it.next(); // for (int i = 0; i < cu.getNumChild(); i++) { // cu.getImportDeclList().removeChildren(); // cu.getTypeDeclList().removeChildren(); // } // } ASTNodeArtifact p = new ASTNodeArtifact(program); p.deleteChildren(); return p; } @Override public final ASTNodeArtifact createConflictDummy( final ASTNodeArtifact type, final ASTNodeArtifact left, final ASTNodeArtifact right) throws FileNotFoundException { ASTNodeArtifact conflict; conflict = new ASTNodeArtifact(type.astnode.fullCopy()); conflict.setConflict(left, right); return conflict; } }
Speed up matching import statements.
src/de/fosd/jdime/common/ASTNodeArtifact.java
Speed up matching import statements.
<ide><path>rc/de/fosd/jdime/common/ASTNodeArtifact.java <ide> <ide> @Override <ide> public final boolean hasUniqueLabels() { <add> if (astnode instanceof ImportDecl) { <add> return true; <add> } <add> <ide> return false; <ide> } <ide>
Java
bsd-3-clause
a5b29cc3f976d8b2c1788efbf0efa7ca219df504
0
FIRST-FRC-Team-2028/2013
package com.PhoebusHighSchool.PhoebusRobotics.UltimateAscent; import com.sun.squawk.util.MathUtils; import edu.wpi.first.wpilibj.PIDSource; import edu.wpi.first.wpilibj.camera.*; import edu.wpi.first.wpilibj.image.*; /* */ public class AimingSystem implements PIDSource { final int XMAXSIZE = 24; final int XMINSIZE = 24; final int YMAXSIZE = 24; final int YMINSIZE = 48; final double xMax[] = {1, 1, 1, 1, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, 1, 1, 1, 1}; final double xMin[] = {.4, .6, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, 0.6, 0}; final double yMax[] = {1, 1, 1, 1, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, 1, 1, 1, 1}; final double yMin[] = {.4, .6, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .6, 0}; final int RECTANGULARITY_LIMIT = 60; final int ASPECT_RATIO_LIMIT = 75; final int X_EDGE_LIMIT = 40; final int Y_EDGE_LIMIT = 60; final int IMAGE_WIDTH = 320; protected UltimateAscentBot robot; public AxisCamera camera; public Ultrasonic ultrasonicSensor; CriteriaCollection cc; ColorImage image; BinaryImage thresholdImage; BinaryImage convexHullImage; BinaryImage filteredImage; ParticleAnalysisReport r; Target[] highTargets; Target[] middleTargets; Target target; public AimingSystem() { camera = AxisCamera.getInstance(Parameters.cameraIP); camera.writeResolution(AxisCamera.ResolutionT.k320x240); camera.writeExposurePriority(AxisCamera.ExposurePriorityT.imageQuality); camera.writeExposureControl(AxisCamera.ExposureT.hold); camera.writeWhiteBalance(AxisCamera.WhiteBalanceT.fixedIndoor); cc = new CriteriaCollection(); cc.addCriteria(NIVision.MeasurementType.IMAQ_MT_AREA, 500, 65535, false); ultrasonicSensor = new Ultrasonic(Parameters.UltrasonicAnalogChannel); } public class Scores { double rectangularity; double aspectRatioHigh; double aspectRatioMiddle; double xEdge; double yEdge; } public class Target { double aspectRatio; double center_mass_x; } /** * This method will find the target we are aiming at, and it's center of * mass in the x axis. */ public void processImage(boolean middle) { try { image = camera.getImage(); thresholdImage = image.thresholdHSV(110, 150, 200, 255, 240, 255); convexHullImage = thresholdImage.convexHull(true); filteredImage = convexHullImage.particleFilter(cc); Scores scores[] = new Scores[filteredImage.getNumberParticles()]; int nHigh = 0; int nMiddle = 0; for (int i = 0; i < scores.length; i++) { r = filteredImage.getParticleAnalysisReport(i); scores[i] = new Scores(); scores[i].rectangularity = scoreRectangularity(r); scores[i].aspectRatioHigh = scoreAspectRatio(filteredImage, r, i, false); scores[i].aspectRatioMiddle = scoreAspectRatio(filteredImage, r, i, true); scores[i].xEdge = scoreXEdge(thresholdImage, r); scores[i].yEdge = scoreYEdge(thresholdImage, r); if (scoreCompare(scores[i], false)) { highTargets[nHigh].aspectRatio = scores[i].aspectRatioHigh; highTargets[nHigh].center_mass_x = r.center_mass_x; nHigh++; } else if (scoreCompare(scores[i], true)) { middleTargets[nMiddle].aspectRatio = scores[i].aspectRatioMiddle; middleTargets[nMiddle].center_mass_x = r.center_mass_x; nMiddle++; } } target = TargetCompare(highTargets, middleTargets, middle); filteredImage.free(); convexHullImage.free(); thresholdImage.free(); image.free(); } catch (NIVisionException e) { } catch (AxisCameraException e) { } } /** * scoreRectangularity() * * This method scores a particle from 0 - 100 based on the ratio of the area * of the particle to the area of the rectangle that bounds it. A score of * 100 means that the particle is perfectly rectangular. * * @param r the analysis report for the particle, used to determine the area * of the bounding rectangle. * @return the score of the particle. */ public double scoreRectangularity(ParticleAnalysisReport r) { if ((r.boundingRectHeight * r.boundingRectWidth) != 0.0) { return 100 * (r.particleArea / (r.boundingRectHeight * r.boundingRectWidth)); } else { return 0.0; } } /** * scoreAspectRatio() * * This method scores the particle from 0 - 100 based on how similar its * aspect ratio is to the aspect ratio of either the high target or the * middle target. A score of 100 means that the target has an aspect ratio * identical to either the middle or high target. * * @param image the image from which the particle originates. * @param report the analysis of the particle * @param middle true if aspect ratio to be compared to is the middle * target, false if it is the high target. * @return the score of the particle, from 0 - 100 * @throws NIVisionException */ public double scoreAspectRatio(BinaryImage image, ParticleAnalysisReport report, int particleNumber, boolean middle) throws NIVisionException { double rectLong, rectShort, aspectRatio, idealAspectRatio; rectLong = NIVision.MeasureParticle(image.image, particleNumber, false, NIVision.MeasurementType.IMAQ_MT_EQUIVALENT_RECT_LONG_SIDE); rectShort = NIVision.MeasureParticle(image.image, particleNumber, false, NIVision.MeasurementType.IMAQ_MT_EQUIVALENT_RECT_SHORT_SIDE); if (middle) { idealAspectRatio = 62 / 29; } else { idealAspectRatio = 62 / 20; } if (report.boundingRectWidth > report.boundingRectHeight) { aspectRatio = 100 * (1 - Math.abs((1 - ((rectLong / rectShort) / idealAspectRatio)))); } else { aspectRatio = 100 * (1 - Math.abs((1 - ((rectShort / rectLong) / idealAspectRatio)))); } return Math.max(0, Math.min(aspectRatio, 100.0)); } /** * scoreXEdge() * * This method scores the particle from 0 - 100 based on how solid the * vertical edges are and how hollow the center of the particle are. * * @param image the image from which the particle originated, needs to be pre convex hull * @param report the analysis of the particle * @return the score of the particle from 0 - 100 * @throws NIVisionException */ public double scoreXEdge(BinaryImage image, ParticleAnalysisReport report) throws NIVisionException { double total = 0; LinearAverages averages; NIVision.Rect rect = new NIVision.Rect(report.boundingRectTop, report.boundingRectLeft, report.boundingRectHeight, report.boundingRectWidth); averages = NIVision.getLinearAverages(image.image, LinearAverages.LinearAveragesMode.IMAQ_COLUMN_AVERAGES, rect); float columnAverages[] = averages.getColumnAverages(); for (int i = 0; i < (columnAverages.length); i++) { if (xMin[(i * (XMINSIZE - 1) / columnAverages.length)] < columnAverages[i] && columnAverages[i] < xMax[i * (XMAXSIZE - 1) / columnAverages.length]) { total++; } } total = 100 * total / (columnAverages.length); return total; } /** * scoreYEdge() * * This method scores the particle from 0 - 100 based on how solid the * horizontal edges are and how hollow the center of the particle are. * * @param image the image from which the particle originated, needs to be pre convex hull * @param report the analysis of the particle * @return the score of the particle from 0 -100 * @throws NIVisionException */ public double scoreYEdge(BinaryImage image, ParticleAnalysisReport report) throws NIVisionException { double total = 0; LinearAverages averages; NIVision.Rect rect = new NIVision.Rect(report.boundingRectTop, report.boundingRectLeft, report.boundingRectHeight, report.boundingRectWidth); averages = NIVision.getLinearAverages(image.image, LinearAverages.LinearAveragesMode.IMAQ_ROW_AVERAGES, rect); float rowAverages[] = averages.getRowAverages(); for (int i = 0; i < (rowAverages.length); i++) { if (yMin[(i * (YMINSIZE - 1) / rowAverages.length)] < rowAverages[i] && rowAverages[i] < yMax[i * (YMAXSIZE - 1) / rowAverages.length]) { total++; } } total = 100 * total / (rowAverages.length); return total; } /** * scoreCompare() * * This method determines if a particle is a target based on if the * particles score compared to an given value. * * @param scores the score of the particle to be compared to * @param middle true if the score to be compared to is the middle target, * false if it is the high target * @return returns true if it qualifies as a target */ boolean scoreCompare(Scores scores, boolean middle) { boolean isTarget = true; isTarget &= scores.rectangularity > RECTANGULARITY_LIMIT; if (middle) { isTarget &= scores.aspectRatioMiddle > ASPECT_RATIO_LIMIT; } else { isTarget &= scores.aspectRatioHigh > ASPECT_RATIO_LIMIT; } isTarget &= scores.xEdge > X_EDGE_LIMIT; isTarget &= scores.yEdge > Y_EDGE_LIMIT; return isTarget; } /** * TargetCompare() * * This method identifies which target of all the targets scoreCompare() * identified is actually the target we are shooting at. if the aspect ratio * score of the current particle is larger than the former particle the * current particle is substituted for the former. *note: even thought there * are two middle targets, based on how the particles are analyzed the * target on our current side of the pyramid will be the better target. * * @param highT the list of all targets determined to be high targets * @param middleT the list of all targets determined to be middle targets * @param middle true if the target that we are shooting at is the middle * target, false if the target we are shooting at is the high target. * @return the target we are shooting at. */ Target TargetCompare(Target[] highT, Target[] middleT, boolean middle) { Target t = null; if (middle) { for (int i = 0; i < middleT.length; i++) { if (t == null) { t.aspectRatio = middleT[i].aspectRatio; t.center_mass_x = middleT[i].center_mass_x; } else if (t.aspectRatio < middleT[i].aspectRatio) { t.aspectRatio = middleT[i].aspectRatio; t.center_mass_x = middleT[i].center_mass_x; } } } else { for (int i = 0; i < highT.length; i++) { if (t == null) { t.aspectRatio = highT[i].aspectRatio; t.center_mass_x = highT[i].center_mass_x; } else if (t.aspectRatio < highT[i].aspectRatio) { t.aspectRatio = highT[i].aspectRatio; t.center_mass_x = highT[i].center_mass_x; } } } return t; } /** * This method returns true if the target is +/- x degree of the camera's * center, and false otherwise. */ public boolean isAimedAtTarget() { if (getDegreesToTarget() < 1.0 && getDegreesToTarget() > -1.0) { return true; } return false; } public double pidGet() { return 0.0; } public double getDegreesToTarget() { double offset = 0.0; if (r != null) { offset = target.center_mass_x - (IMAGE_WIDTH / 2); offset = MathUtils.atan(offset / 367.97488075578); } return ConvertRadiansToDegrees(offset); } public double ConvertRadiansToDegrees(double radians) { return (radians * 180.0) / 3.1415926535898; } public double getDistance() { return ultrasonicSensor.getDistance(); } }
src/com/phoebushighschool/phoebusrobotics/ultimateascent/AimingSystem.java
package com.PhoebusHighSchool.PhoebusRobotics.UltimateAscent; import com.sun.squawk.util.MathUtils; import edu.wpi.first.wpilibj.PIDSource; import edu.wpi.first.wpilibj.camera.*; import edu.wpi.first.wpilibj.image.*; /* */ public class AimingSystem implements PIDSource { final int XMAXSIZE = 24; final int XMINSIZE = 24; final int YMAXSIZE = 24; final int YMINSIZE = 48; final double xMax[] = {1, 1, 1, 1, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, 1, 1, 1, 1}; final double xMin[] = {.4, .6, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, 0.6, 0}; final double yMax[] = {1, 1, 1, 1, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, 1, 1, 1, 1}; final double yMin[] = {.4, .6, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .6, 0}; final int RECTANGULARITY_LIMIT = 60; final int ASPECT_RATIO_LIMIT = 75; final int X_EDGE_LIMIT = 40; final int Y_EDGE_LIMIT = 60; final int IMAGE_WIDTH = 320; protected UltimateAscentBot robot; public AxisCamera camera; public Ultrasonic ultrasonicSensor; CriteriaCollection cc; ColorImage image; BinaryImage thresholdImage; BinaryImage convexHullImage; BinaryImage filteredImage; ParticleAnalysisReport r; Target[] highTargets; Target[] middleTargets; Target target; public AimingSystem() { camera = AxisCamera.getInstance(Parameters.cameraIP); camera.writeResolution(AxisCamera.ResolutionT.k320x240); camera.writeExposurePriority(AxisCamera.ExposurePriorityT.imageQuality); camera.writeExposureControl(AxisCamera.ExposureT.hold); camera.writeWhiteBalance(AxisCamera.WhiteBalanceT.fixedIndoor); cc = new CriteriaCollection(); cc.addCriteria(NIVision.MeasurementType.IMAQ_MT_AREA, 500, 65535, false); ultrasonicSensor = new Ultrasonic(Parameters.UltrasonicAnalogChannel); } public class Scores { double rectangularity; double aspectRatioHigh; double aspectRatioMiddle; double xEdge; double yEdge; } public class Target { double aspectRatio; double center_mass_x; } /** * This method will find the target we are aiming at, and it's center of * mass in the x axis. */ public void processImage(boolean middle) { try { image = camera.getImage(); thresholdImage = image.thresholdHSV(110, 150, 200, 255, 240, 255); convexHullImage = thresholdImage.convexHull(true); filteredImage = convexHullImage.particleFilter(cc); Scores scores[] = new Scores[filteredImage.getNumberParticles()]; int nHigh = 0; int nMiddle = 0; for (int i = 0; i < scores.length; i++) { r = filteredImage.getParticleAnalysisReport(i); scores[i] = new Scores(); scores[i].rectangularity = scoreRectangularity(r); scores[i].aspectRatioHigh = scoreAspectRatio(filteredImage, r, i, false); scores[i].aspectRatioMiddle = scoreAspectRatio(filteredImage, r, i, true); scores[i].xEdge = scoreXEdge(filteredImage, r); scores[i].yEdge = scoreYEdge(filteredImage, r); if (scoreCompare(scores[i], false)) { highTargets[nHigh].aspectRatio = scores[i].aspectRatioHigh; highTargets[nHigh].center_mass_x = r.center_mass_x; nHigh++; } else if (scoreCompare(scores[i], true)) { middleTargets[nMiddle].aspectRatio = scores[i].aspectRatioMiddle; middleTargets[nMiddle].center_mass_x = r.center_mass_x; nMiddle++; } } target = TargetCompare(highTargets, middleTargets, middle); filteredImage.free(); convexHullImage.free(); thresholdImage.free(); image.free(); } catch (NIVisionException e) { } catch (AxisCameraException e) { } } /** * scoreRectangularity() * * This method scores a particle from 0 - 100 based on the ratio of the area * of the particle to the area of the rectangle that bounds it. A score of * 100 means that the particle is perfectly rectangular. * * @param r the analysis report for the particle, used to determine the area * of the bounding rectangle. * @return the score of the particle. */ public double scoreRectangularity(ParticleAnalysisReport r) { if ((r.boundingRectHeight * r.boundingRectWidth) != 0.0) { return 100 * (r.particleArea / (r.boundingRectHeight * r.boundingRectWidth)); } else { return 0.0; } } /** * scoreAspectRatio() * * This method scores the particle from 0 - 100 based on how similar its * aspect ratio is to the aspect ratio of either the high target or the * middle target. A score of 100 means that the target has an aspect ratio * identical to either the middle or high target. * * @param image the image from which the particle originates. * @param report the analysis of the particle * @param middle true if aspect ratio to be compared to is the middle * target, false if it is the high target. * @return the score of the particle, from 0 - 100 * @throws NIVisionException */ public double scoreAspectRatio(BinaryImage image, ParticleAnalysisReport report, int particleNumber, boolean middle) throws NIVisionException { double rectLong, rectShort, aspectRatio, idealAspectRatio; rectLong = NIVision.MeasureParticle(image.image, particleNumber, false, NIVision.MeasurementType.IMAQ_MT_EQUIVALENT_RECT_LONG_SIDE); rectShort = NIVision.MeasureParticle(image.image, particleNumber, false, NIVision.MeasurementType.IMAQ_MT_EQUIVALENT_RECT_SHORT_SIDE); if (middle) { idealAspectRatio = 62 / 29; } else { idealAspectRatio = 62 / 20; } if (report.boundingRectWidth > report.boundingRectHeight) { aspectRatio = 100 * (1 - Math.abs((1 - ((rectLong / rectShort) / idealAspectRatio)))); } else { aspectRatio = 100 * (1 - Math.abs((1 - ((rectShort / rectLong) / idealAspectRatio)))); } return Math.max(0, Math.min(aspectRatio, 100.0)); } /** * scoreXEdge() * * This method scores the particle from 0 - 100 based on how solid the * vertical edges are and how hollow the center of the particle are. * * @param image the image from which the particle originated * @param report the analysis of the particle * @return the score of the particle from 0 - 100 * @throws NIVisionException */ public double scoreXEdge(BinaryImage image, ParticleAnalysisReport report) throws NIVisionException { double total = 0; LinearAverages averages; NIVision.Rect rect = new NIVision.Rect(report.boundingRectTop, report.boundingRectLeft, report.boundingRectHeight, report.boundingRectWidth); averages = NIVision.getLinearAverages(image.image, LinearAverages.LinearAveragesMode.IMAQ_COLUMN_AVERAGES, rect); float columnAverages[] = averages.getColumnAverages(); for (int i = 0; i < (columnAverages.length); i++) { if (xMin[(i * (XMINSIZE - 1) / columnAverages.length)] < columnAverages[i] && columnAverages[i] < xMax[i * (XMAXSIZE - 1) / columnAverages.length]) { total++; } } total = 100 * total / (columnAverages.length); return total; } /** * scoreYEdge() * * This method scores the particle from 0 - 100 based on how solid the * horizontal edges are and how hollow the center of the particle are. * * @param image the image from which the particle originated * @param report the analysis of the particle * @return the score of the particle from 0 -100 * @throws NIVisionException */ public double scoreYEdge(BinaryImage image, ParticleAnalysisReport report) throws NIVisionException { double total = 0; LinearAverages averages; NIVision.Rect rect = new NIVision.Rect(report.boundingRectTop, report.boundingRectLeft, report.boundingRectHeight, report.boundingRectWidth); averages = NIVision.getLinearAverages(image.image, LinearAverages.LinearAveragesMode.IMAQ_ROW_AVERAGES, rect); float rowAverages[] = averages.getRowAverages(); for (int i = 0; i < (rowAverages.length); i++) { if (yMin[(i * (YMINSIZE - 1) / rowAverages.length)] < rowAverages[i] && rowAverages[i] < yMax[i * (YMAXSIZE - 1) / rowAverages.length]) { total++; } } total = 100 * total / (rowAverages.length); return total; } /** * scoreCompare() * * This method determines if a particle is a target based on if the * particles score compared to an given value. * * @param scores the score of the particle to be compared to * @param middle true if the score to be compared to is the middle target, * false if it is the high target * @return returns true if it qualifies as a target */ boolean scoreCompare(Scores scores, boolean middle) { boolean isTarget = true; isTarget &= scores.rectangularity > RECTANGULARITY_LIMIT; if (middle) { isTarget &= scores.aspectRatioMiddle > ASPECT_RATIO_LIMIT; } else { isTarget &= scores.aspectRatioHigh > ASPECT_RATIO_LIMIT; } isTarget &= scores.xEdge > X_EDGE_LIMIT; isTarget &= scores.yEdge > Y_EDGE_LIMIT; return isTarget; } /** * TargetCompare() * * This method identifies which target of all the targets scoreCompare() * identified is actually the target we are shooting at. if the aspect ratio * score of the current particle is larger than the former particle the * current particle is substituted for the former. *note: even thought there * are two middle targets, based on how the particles are analyzed the * target on our current side of the pyramid will be the better target. * * @param highT the list of all targets determined to be high targets * @param middleT the list of all targets determined to be middle targets * @param middle true if the target that we are shooting at is the middle * target, false if the target we are shooting at is the high target. * @return the target we are shooting at. */ Target TargetCompare(Target[] highT, Target[] middleT, boolean middle) { Target t = null; if (middle) { for (int i = 0; i < middleT.length; i++) { if (t == null) { t.aspectRatio = middleT[i].aspectRatio; t.center_mass_x = middleT[i].center_mass_x; } else if (t.aspectRatio < middleT[i].aspectRatio) { t.aspectRatio = middleT[i].aspectRatio; t.center_mass_x = middleT[i].center_mass_x; } } } else { for (int i = 0; i < highT.length; i++) { if (t == null) { t.aspectRatio = highT[i].aspectRatio; t.center_mass_x = highT[i].center_mass_x; } else if (t.aspectRatio < highT[i].aspectRatio) { t.aspectRatio = highT[i].aspectRatio; t.center_mass_x = highT[i].center_mass_x; } } } return t; } /** * This method returns true if the target is +/- x degree of the camera's * center, and false otherwise. */ public boolean isAimedAtTarget() { if (getDegreesToTarget() < 1.0 && getDegreesToTarget() > -1.0) { return true; } return false; } public double pidGet() { return 0.0; } public double getDegreesToTarget() { double offset = 0.0; if (r != null) { offset = target.center_mass_x - (IMAGE_WIDTH / 2); offset = MathUtils.atan(offset / 367.97488075578); } return ConvertRadiansToDegrees(offset); } public double ConvertRadiansToDegrees(double radians) { return (radians * 180.0) / 3.1415926535898; } public double getDistance() { return ultrasonicSensor.getDistance(); } }
last change
src/com/phoebushighschool/phoebusrobotics/ultimateascent/AimingSystem.java
last change
<ide><path>rc/com/phoebushighschool/phoebusrobotics/ultimateascent/AimingSystem.java <ide> scores[i].rectangularity = scoreRectangularity(r); <ide> scores[i].aspectRatioHigh = scoreAspectRatio(filteredImage, r, i, false); <ide> scores[i].aspectRatioMiddle = scoreAspectRatio(filteredImage, r, i, true); <del> scores[i].xEdge = scoreXEdge(filteredImage, r); <del> scores[i].yEdge = scoreYEdge(filteredImage, r); <add> scores[i].xEdge = scoreXEdge(thresholdImage, r); <add> scores[i].yEdge = scoreYEdge(thresholdImage, r); <ide> <ide> if (scoreCompare(scores[i], false)) { <ide> highTargets[nHigh].aspectRatio = scores[i].aspectRatioHigh; <ide> * This method scores the particle from 0 - 100 based on how solid the <ide> * vertical edges are and how hollow the center of the particle are. <ide> * <del> * @param image the image from which the particle originated <add> * @param image the image from which the particle originated, needs to be pre convex hull <ide> * @param report the analysis of the particle <ide> * @return the score of the particle from 0 - 100 <ide> * @throws NIVisionException <ide> * This method scores the particle from 0 - 100 based on how solid the <ide> * horizontal edges are and how hollow the center of the particle are. <ide> * <del> * @param image the image from which the particle originated <add> * @param image the image from which the particle originated, needs to be pre convex hull <ide> * @param report the analysis of the particle <ide> * @return the score of the particle from 0 -100 <ide> * @throws NIVisionException
JavaScript
mit
3c9037a7d2a2c89ad8ed2b4a13ec6f3283b7accf
0
lucalianas/ProMort,crs4/ProMort,crs4/ProMort,lucalianas/ProMort,lucalianas/ProMort,crs4/ProMort
(function () { 'use strict'; angular .module('promort.viewer.services') .factory('ViewerService', ViewerService) .factory('AnnotationsViewerService', AnnotationsViewerService); ViewerService.$inject = ['$http']; function ViewerService($http) { var ViewerService = { getOMEBaseURLs: getOMEBaseURLs, getSlideInfo: getSlideInfo }; return ViewerService; function getOMEBaseURLs() { return $http.get('api/utils/omeseadragon_base_urls/'); } function getSlideInfo(slide_id) { return $http.get('api/slides/' + slide_id + '/'); } } function AnnotationsViewerService() { var AnnotationsViewerService = { registerComponents: registerComponents, checkComponents: checkComponents, drawShape: drawShape, selectShape: selectShape, deselectShape: deselectShape, extendPolygonConfig: extendPolygonConfig, extendPathConfig: extendPathConfig, extendRulerConfig: extendRulerConfig, startPolygonsTool: startPolygonsTool, disableActiveTool: disableActiveTool, saveTemporaryPolygon: saveTemporaryPolygon, clearTemporaryPolygon: clearTemporaryPolygon, startFreehandDrawingTool: startFreehandDrawingTool, setFreehandToolLabelPrefix: setFreehandToolLabelPrefix, deleteShape: deleteShape, clear: clear, deleteShapes: deleteShapes, getCanvasLabel: getCanvasLabel, getShapeJSON: getShapeJSON, getShapeArea: getShapeArea, focusOnShape: focusOnShape, checkContainment: checkContainment, adaptToContainer: adaptToContainer, createRulerBindings: createRulerBindings, clearRuler: clearRuler, createAreaRulerBindings: createAreaRulerBindings, clearAreaRuler: clearAreaRuler, bindAreaRulerToShape: bindAreaRulerToShape, getAreaCoverage: getAreaCoverage, setShapeStrokeColor: setShapeStrokeColor }; return AnnotationsViewerService; function registerComponents(viewer_manager, rois_manager, tools_manager) { this.viewerManager = viewer_manager; this.roisManager = rois_manager; this.toolsManager = tools_manager; } function checkComponents() { console.log('Viewer Manager: ' + this.viewerManager); console.log('ROIs Manager: ' + this.roisManager); console.log('Tools Manager: ' + this.toolsManager); } function drawShape(shape_json) { this.roisManager.drawShapeFromJSON(shape_json); } function selectShape(shape_id) { this.roisManager.selectShape(shape_id, true, true); } function deselectShape(shape_id) { this.roisManager.deselectShape(shape_id, true); } function extendPolygonConfig(polygon_config) { this.roisManager.extendPolygonConfig(polygon_config); } function extendPathConfig(path_config) { this.roisManager.extendPathConfig(path_config); } function extendRulerConfig(ruler_config) { this.roisManager.extendRulerConfig(ruler_config); } function startPolygonsTool() { this.toolsManager.activateTool(AnnotationsEventsController.POLYGON_DRAWING_TOOL); } function disableActiveTool() { this.roisManager.disableMouseEvents(); } function saveTemporaryPolygon(label_prefix) { console.log('Saving temporary polygon'); this.roisManager.saveTemporaryPolygon(label_prefix); } function clearTemporaryPolygon() { this.roisManager.clearTemporaryPolygon(); } function startFreehandDrawingTool() { this.toolsManager.activateTool(AnnotationsEventsController.FREEHAND_DRAWING_TOOL); } function setFreehandToolLabelPrefix(label_prefix) { this.roisManager.setFreehandPathLabelPrefix(label_prefix); } function deleteShape(shape_id) { this.roisManager.deleteShape(shape_id); } function clear() { this.roisManager.clear(); } function deleteShapes(shapes_id) { this.roisManager.deleteShapes(shapes_id); } function getCanvasLabel() { return this.roisManager.canvas_id; } function getShapeJSON(shape_id) { return this.roisManager.getShapeJSON(shape_id); } function getShapeArea(shape_id) { return this.roisManager.getShapeDimensions(shape_id).area; } function focusOnShape(shape_id) { this.viewerManager.jumpToShape(shape_id, true); } function checkContainment(container_label, contained_label) { var container = this.roisManager.getShape(container_label); var contained = this.roisManager.getShape(contained_label); return (container.containsShape(contained) || container.intersectsShape(contained)); } function adaptToContainer(container_label, contained_label) { var container = this.roisManager.getShape(container_label); var contained = this.roisManager.getShape(contained_label); this.roisManager.intersectShapes(container, contained, false, true, true); } function createRulerBindings(on_switch, off_switch, output) { this.roisManager.bindToRuler(on_switch, off_switch, output); } function clearRuler() { this.roisManager.clearRuler(true); } function createAreaRulerBindings(on_switch, output) { this.roisManager.bindToAreaRuler(on_switch, output); } function bindAreaRulerToShape(shape_id) { this.roisManager.bindAreaRulerToShape(shape_id); } function clearAreaRuler() { this.roisManager.clearAreaRuler(true); } function getAreaCoverage(shape_1_label, shape_2_label) { var shape_1 = this.roisManager.getShape(shape_1_label); var shape_2 = this.roisManager.getShape(shape_2_label); return Number(shape_1.getCoveragePercentage(shape_2).toFixed(2)); } function setShapeStrokeColor(shape_id, color, alpha) { var shape = this.roisManager.getShape(shape_id); shape.setStrokeColor(color, alpha); } } })();
promort/src/js/ome_seadragon_viewer/viewer.services.js
(function () { 'use strict'; angular .module('promort.viewer.services') .factory('ViewerService', ViewerService) .factory('AnnotationsViewerService', AnnotationsViewerService); ViewerService.$inject = ['$http']; function ViewerService($http) { var ViewerService = { getOMEBaseURLs: getOMEBaseURLs, getSlideInfo: getSlideInfo }; return ViewerService; function getOMEBaseURLs() { return $http.get('api/utils/omeseadragon_base_urls/'); } function getSlideInfo(slide_id) { return $http.get('api/slides/' + slide_id + '/'); } } function AnnotationsViewerService() { var AnnotationsViewerService = { registerComponents: registerComponents, checkComponents: checkComponents, drawShape: drawShape, selectShape: selectShape, deselectShape: deselectShape, extendPolygonConfig: extendPolygonConfig, extendPathConfig: extendPathConfig, extendRulerConfig: extendRulerConfig, startPolygonsTool: startPolygonsTool, disableActiveTool: disableActiveTool, saveTemporaryPolygon: saveTemporaryPolygon, clearTemporaryPolygon: clearTemporaryPolygon, startFreehandDrawingTool: startFreehandDrawingTool, setFreehandToolLabelPrefix: setFreehandToolLabelPrefix, deleteShape: deleteShape, clear: clear, deleteShapes: deleteShapes, getCanvasLabel: getCanvasLabel, getShapeJSON: getShapeJSON, getShapeArea: getShapeArea, focusOnShape: focusOnShape, checkContainment: checkContainment, createRulerBindings: createRulerBindings, clearRuler: clearRuler, createAreaRulerBindings: createAreaRulerBindings, clearAreaRuler: clearAreaRuler, bindAreaRulerToShape: bindAreaRulerToShape, getAreaCoverage: getAreaCoverage, setShapeStrokeColor: setShapeStrokeColor }; return AnnotationsViewerService; function registerComponents(viewer_manager, rois_manager, tools_manager) { this.viewerManager = viewer_manager; this.roisManager = rois_manager; this.toolsManager = tools_manager; } function checkComponents() { console.log('Viewer Manager: ' + this.viewerManager); console.log('ROIs Manager: ' + this.roisManager); console.log('Tools Manager: ' + this.toolsManager); } function drawShape(shape_json) { this.roisManager.drawShapeFromJSON(shape_json); } function selectShape(shape_id) { this.roisManager.selectShape(shape_id, true, true); } function deselectShape(shape_id) { this.roisManager.deselectShape(shape_id, true); } function extendPolygonConfig(polygon_config) { this.roisManager.extendPolygonConfig(polygon_config); } function extendPathConfig(path_config) { this.roisManager.extendPathConfig(path_config); } function extendRulerConfig(ruler_config) { this.roisManager.extendRulerConfig(ruler_config); } function startPolygonsTool() { this.toolsManager.activateTool(AnnotationsEventsController.POLYGON_DRAWING_TOOL); } function disableActiveTool() { this.roisManager.disableMouseEvents(); } function saveTemporaryPolygon(label_prefix) { console.log('Saving temporary polygon'); this.roisManager.saveTemporaryPolygon(label_prefix); } function clearTemporaryPolygon() { this.roisManager.clearTemporaryPolygon(); } function startFreehandDrawingTool() { this.toolsManager.activateTool(AnnotationsEventsController.FREEHAND_DRAWING_TOOL); } function setFreehandToolLabelPrefix(label_prefix) { this.roisManager.setFreehandPathLabelPrefix(label_prefix); } function deleteShape(shape_id) { this.roisManager.deleteShape(shape_id); } function clear() { this.roisManager.clear(); } function deleteShapes(shapes_id) { this.roisManager.deleteShapes(shapes_id); } function getCanvasLabel() { return this.roisManager.canvas_id; } function getShapeJSON(shape_id) { return this.roisManager.getShapeJSON(shape_id); } function getShapeArea(shape_id) { return this.roisManager.getShapeDimensions(shape_id).area; } function focusOnShape(shape_id) { this.viewerManager.jumpToShape(shape_id, true); } function checkContainment(container_label, contained_label) { var container = this.roisManager.getShape(container_label); var contained = this.roisManager.getShape(contained_label); return container.containsShape(contained); } function createRulerBindings(on_switch, off_switch, output) { this.roisManager.bindToRuler(on_switch, off_switch, output); } function clearRuler() { this.roisManager.clearRuler(true); } function createAreaRulerBindings(on_switch, output) { this.roisManager.bindToAreaRuler(on_switch, output); } function bindAreaRulerToShape(shape_id) { this.roisManager.bindAreaRulerToShape(shape_id); } function clearAreaRuler() { this.roisManager.clearAreaRuler(true); } function getAreaCoverage(shape_1_label, shape_2_label) { var shape_1 = this.roisManager.getShape(shape_1_label); var shape_2 = this.roisManager.getShape(shape_2_label); return Number(shape_1.getCoveragePercentage(shape_2).toFixed(2)); } function setShapeStrokeColor(shape_id, color, alpha) { var shape = this.roisManager.getShape(shape_id); shape.setStrokeColor(color, alpha); } } })();
adapt ROIs to its container
promort/src/js/ome_seadragon_viewer/viewer.services.js
adapt ROIs to its container
<ide><path>romort/src/js/ome_seadragon_viewer/viewer.services.js <ide> getShapeArea: getShapeArea, <ide> focusOnShape: focusOnShape, <ide> checkContainment: checkContainment, <add> adaptToContainer: adaptToContainer, <ide> createRulerBindings: createRulerBindings, <ide> clearRuler: clearRuler, <ide> createAreaRulerBindings: createAreaRulerBindings, <ide> function checkContainment(container_label, contained_label) { <ide> var container = this.roisManager.getShape(container_label); <ide> var contained = this.roisManager.getShape(contained_label); <del> return container.containsShape(contained); <add> return (container.containsShape(contained) || container.intersectsShape(contained)); <add> } <add> <add> function adaptToContainer(container_label, contained_label) { <add> var container = this.roisManager.getShape(container_label); <add> var contained = this.roisManager.getShape(contained_label); <add> this.roisManager.intersectShapes(container, contained, false, true, true); <ide> } <ide> <ide> function createRulerBindings(on_switch, off_switch, output) {
JavaScript
mit
6f464b80094457fc437b42136c5e9fb658f38dc1
0
hideoussquid/aur-copay,bitjson/copay,matiu/copay,Bitcoin-com/Wallet,msalcala11/copay,cmgustavo/copay,Groestlcoin/GroestlPay,msalcala11/copay,bitchk-wallet/copay,JDonadio/copay,dabura667/copay,javierbitpay/copay,bitjson/copay,bitjson/copay,dabura667/copay,tanojaja/copay,ajp8164/copay,javierbitpay/copay,janko33bd/copay,Groestlcoin/GroestlPay,gabrielbazan7/copay,ObsidianCryptoVault/copay,tanojaja/copay,tanojaja/copay,cobit-wallet/cobit,JDonadio/copay,matiu/copay,cmgustavo/copay,Kirvx/copay,Bitcoin-com/Wallet,mpolci/copay,Groestlcoin/GroestlPay,bitjson/copay,fr34k8/copay,JDonadio/copay,ObsidianCryptoVault/copay,cobit-wallet/cobit,Kirvx/copay,javierbitpay/copay,fr34k8/copay,JDonadio/copay,janko33bd/copay,hideoussquid/aur-copay,cobit-wallet/cobit,gabrielbazan7/copay,gabrielbazan7/copay,Bitcoin-com/Wallet,ajp8164/copay,Kirvx/copay,ObsidianCryptoVault/copay,cmgustavo/copay,matiu/copay,hideoussquid/aur-copay,ObsidianCryptoVault/copay,mpolci/copay,tanojaja/copay,cmgustavo/copay,Groestlcoin/GroestlPay,mpolci/copay,bitchk-wallet/copay,ajp8164/copay,mpolci/copay,matiu/copay,Bitcoin-com/Wallet,msalcala11/copay,janko33bd/copay,bitchk-wallet/copay,Kirvx/copay,gabrielbazan7/copay,msalcala11/copay,javierbitpay/copay,hideoussquid/aur-copay,fr34k8/copay,dabura667/copay,fr34k8/copay
'use strict'; angular.module('copayApp.controllers').controller('walletHomeController', function($scope, $rootScope, $interval, $timeout, $filter, $modal, $log, notification, txStatus, isCordova, isMobile, profileService, lodash, configService, rateService, storageService, bitcore, isChromeApp, gettext, gettextCatalog, nodeWebkit, addressService, ledger, bwsError, confirmDialog, txFormatService, animationService, addressbookService, go, feeService, txService) { var self = this; window.ignoreMobilePause = false; $rootScope.shouldHideMenuBar = false; $rootScope.wpInputFocused = false; var config = configService.getSync(); var configWallet = config.wallet; var walletSettings = configWallet.settings; var ret = {}; // INIT. Global value ret.unitToSatoshi = walletSettings.unitToSatoshi; ret.satToUnit = 1 / ret.unitToSatoshi; ret.unitName = walletSettings.unitName; ret.alternativeIsoCode = walletSettings.alternativeIsoCode; ret.alternativeName = walletSettings.alternativeName; ret.alternativeAmount = 0; ret.unitDecimals = walletSettings.unitDecimals; ret.isCordova = isCordova; ret.addresses = []; ret.isMobile = isMobile.any(); ret.isWindowsPhoneApp = isMobile.Windows() && isCordova; ret.countDown = null; var vanillaScope = ret; var disableScannerListener = $rootScope.$on('dataScanned', function(event, data) { self.setForm(data); $rootScope.$emit('Local/SetTab', 'send'); var form = $scope.sendForm; if (form.address.$invalid && !self.blockUx) { self.resetForm(); self.error = gettext('Could not recognize a valid Bitcoin QR Code'); } }); var disablePaymentUriListener = $rootScope.$on('paymentUri', function(event, uri) { $rootScope.$emit('Local/SetTab', 'send'); $timeout(function() { self.setForm(uri); }, 100); }); var disableAddrListener = $rootScope.$on('Local/AddressIsUsed', function() { self.setAddress(true); }); var disableFocusListener = $rootScope.$on('Local/NewFocusedWalletReady', function() { self.addr = null; self.resetForm(); $scope.search = ''; if (profileService.focusedClient && profileService.focusedClient.isComplete()) { self.setAddress(); self.setSendFormInputs(); } $log.debug('Cleaning WalletHome Instance'); lodash.each(self, function(v, k) { if (lodash.isFunction(v)) return; if (vanillaScope[k]) { self[k] = vanillaScope[k]; return; } if (k == 'isRateAvailable') return; delete self[k]; }); }); var disableResumeListener = $rootScope.$on('Local/Resume', function() { // This is needed then the apps go to sleep self.bindTouchDown(); }); var disableTabListener = $rootScope.$on('Local/TabChanged', function(e, tab) { // This will slow down switch, do not add things here! switch (tab) { case 'receive': // just to be sure we have an address self.setAddress(); break; case 'send': self.resetError(); }; }); var disableOngoingProcessListener = $rootScope.$on('Addon/OngoingProcess', function(e, name) { self.setOngoingProcess(name); }); $scope.$on('$destroy', function() { disableAddrListener(); disableScannerListener(); disablePaymentUriListener(); disableTabListener(); disableFocusListener(); disableResumeListener(); disableOngoingProcessListener(); $rootScope.shouldHideMenuBar = false; }); this.onQrCodeScanned = function(data) { if (data) go.send(); $rootScope.$emit('dataScanned', data); }; rateService.whenAvailable(function() { self.isRateAvailable = true; $rootScope.$digest(); }); var getClipboard = function(cb) { if (!isCordova || isMobile.Windows()) return cb(); window.cordova.plugins.clipboard.paste(function(value) { var fc = profileService.focusedClient; var Address = bitcore.Address; var networkName = fc.credentials.network; if (Address.isValid(value, networkName) && !$scope.newAddress) { return cb(value); } }); }; var accept_msg = gettextCatalog.getString('Accept'); var cancel_msg = gettextCatalog.getString('Cancel'); var confirm_msg = gettextCatalog.getString('Confirm'); this.openDestinationAddressModal = function(wallets, address) { $rootScope.modalOpened = true; var fc = profileService.focusedClient; self.lockAddress = false; self._address = null; var ModalInstanceCtrl = function($scope, $modalInstance) { $scope.wallets = wallets; $scope.editAddressbook = false; $scope.addAddressbookEntry = false; $scope.selectedAddressbook = {}; $scope.newAddress = address; $scope.walletName = fc.credentials.walletName; $scope.color = fc.backgroundColor; $scope.addressbook = { 'address': ($scope.newAddress || ''), 'label': '' }; $scope.checkClipboard = function() { if (!$scope.newAddress) { getClipboard(function(value) { $scope.newAddress = value; }); } }; $scope.beforeQrCodeScann = function() { $scope.error = null; $scope.addAddressbookEntry = true; $scope.editAddressbook = false; }; $scope.onQrCodeScanned = function(data, addressbookForm) { $timeout(function() { var form = addressbookForm; if (data && form) { data = data.replace('bitcoin:', ''); form.address.$setViewValue(data); form.address.$isValid = true; form.address.$render(); } $scope.$digest(); }, 100); }; $scope.selectAddressbook = function(addr) { $modalInstance.close(addr); }; $scope.toggleEditAddressbook = function() { $scope.editAddressbook = !$scope.editAddressbook; $scope.selectedAddressbook = {}; $scope.addAddressbookEntry = false; }; $scope.toggleSelectAddressbook = function(addr) { $scope.selectedAddressbook[addr] = $scope.selectedAddressbook[addr] ? false : true; }; $scope.toggleAddAddressbookEntry = function() { $scope.error = null; $scope.addressbook = { 'address': ($scope.newAddress || ''), 'label': '' }; $scope.addAddressbookEntry = !$scope.addAddressbookEntry; }; $scope.list = function() { $scope.error = null; addressbookService.list(function(err, ab) { if (err) { $scope.error = err; return; } $scope.list = ab; }); }; $scope.add = function(addressbook) { $scope.error = null; $timeout(function() { addressbookService.add(addressbook, function(err, ab) { if (err) { $scope.error = err; return; } $rootScope.$emit('Local/AddressbookUpdated', ab); $scope.list = ab; $scope.editAddressbook = true; $scope.toggleEditAddressbook(); $scope.$digest(); }); }, 100); }; $scope.remove = function(addr) { $scope.error = null; $timeout(function() { addressbookService.remove(addr, function(err, ab) { if (err) { $scope.error = err; return; } $rootScope.$emit('Local/AddressbookUpdated', ab); $scope.list = ab; $scope.$digest(); }); }, 100); }; $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; $scope.selectWallet = function(walletId, walletName) { profileService.isBackupNeeded(walletId, function(needsBackup) { $scope.needsBackup = {}; $scope.needsBackup[walletId] = needsBackup; if (needsBackup) return; $scope.gettingAddress = true; $scope.selectedWalletName = walletName; $timeout(function() { $scope.$apply(); }); addressService.getAddress(walletId, false, function(err, addr) { $scope.gettingAddress = false; if (err) { self.error = err; $modalInstance.dismiss('cancel'); return; } $modalInstance.close(addr); }); }); }; }; var modalInstance = $modal.open({ templateUrl: 'views/modals/destination-address.html', windowClass: animationService.modalAnimated.slideUp, controller: ModalInstanceCtrl, }); var disableCloseModal = $rootScope.$on('closeModal', function() { modalInstance.dismiss('cancel'); }); modalInstance.result.finally(function() { $rootScope.modalOpened = false; disableCloseModal(); var m = angular.element(document.getElementsByClassName('reveal-modal')); m.addClass(animationService.modalAnimated.slideOutDown); }); modalInstance.result.then(function(addr) { if (addr) { self.setForm(addr); } }, function() { // onRejected self.resetForm(); }); }; var GLIDERA_LOCK_TIME = 6 * 60 * 60; // isGlidera flag is a security measure so glidera status is not // only determined by the tx.message this.openTxpModal = function(tx, copayers, isGlidera) { $rootScope.modalOpened = true; var self = this; var fc = profileService.focusedClient; var currentSpendUnconfirmed = configWallet.spendUnconfirmed; var ModalInstanceCtrl = function($scope, $modalInstance) { $scope.paymentExpired = null; checkPaypro(); $scope.error = null; $scope.copayers = copayers $scope.copayerId = fc.credentials.copayerId; $scope.canSign = fc.canSign() || fc.isPrivKeyExternal(); $scope.loading = null; $scope.color = fc.backgroundColor; $scope.isShared = fc.credentials.n > 1; var now = Math.floor(Date.now() / 1000); // ToDo: use tx.customData instead of tx.message if (tx.message === 'Glidera transaction' && isGlidera) { tx.isGlidera = true; if (tx.canBeRemoved) { tx.canBeRemoved = (Date.now() / 1000 - (tx.ts || tx.createdOn)) > GLIDERA_LOCK_TIME; } } $scope.tx = tx; $scope.currentSpendUnconfirmed = currentSpendUnconfirmed; $scope.getShortNetworkName = function() { return fc.credentials.networkName.substring(0, 4); }; function checkPaypro() { if (tx.payProUrl && !isChromeApp) { fc.fetchPayPro({ payProUrl: tx.payProUrl, }, function(err, paypro) { if (err) return; tx.paypro = paypro; paymentTimeControl(tx.paypro.expires); }); } }; function paymentTimeControl(expirationTime) { $scope.paymentExpired = false; setExpirationTime(); self.countDown = $interval(function() { setExpirationTime(); }, 1000); function setExpirationTime() { var now = Math.floor(Date.now() / 1000); if (now > expirationTime) { $scope.paymentExpired = true; if (self.countDown) $interval.cancel(self.countDown); return; } var totalSecs = expirationTime - now; var m = Math.floor(totalSecs / 60); var s = totalSecs % 60; $scope.expires = ('0' + m).slice(-2) + ":" + ('0' + s).slice(-2); }; }; lodash.each(['TxProposalRejectedBy', 'TxProposalAcceptedBy', 'transactionProposalRemoved', 'TxProposalRemoved', 'NewOutgoingTx', 'UpdateTx'], function(eventName) { $rootScope.$on(eventName, function() { fc.getTx($scope.tx.id, function(err, tx) { if (err) { if (err.message && err.message == 'TX_NOT_FOUND' && (eventName == 'transactionProposalRemoved' || eventName == 'TxProposalRemoved')) { $scope.tx.removed = true; $scope.tx.canBeRemoved = false; $scope.tx.pendingForUs = false; $scope.$apply(); return; } return; } var action = lodash.find(tx.actions, { copayerId: fc.credentials.copayerId }); $scope.tx = txFormatService.processTx(tx); if (!action && tx.status == 'pending') $scope.tx.pendingForUs = true; $scope.updateCopayerList(); $scope.$apply(); }); }); }); $scope.updateCopayerList = function() { lodash.map($scope.copayers, function(cp) { lodash.each($scope.tx.actions, function(ac) { if (cp.id == ac.copayerId) { cp.action = ac.type; } }); }); }; $scope.sign = function(txp) { var fc = profileService.focusedClient; $scope.error = null; $scope.loading = true; txService.prepareAndSignAndBroadcast(txp, { reporterFn: self.setOngoingProcess.bind(self) }, function(err, txp) { $scope.loading = false; $scope.$emit('UpdateTx'); if (err) { $scope.error = err; $timeout(function() { $scope.$digest(); }); return; } $modalInstance.close(txp); return; }); }; $scope.reject = function(txp) { self.setOngoingProcess(gettextCatalog.getString('Rejecting payment')); $scope.loading = true; $scope.error = null; $timeout(function() { fc.rejectTxProposal(txp, null, function(err, txpr) { self.setOngoingProcess(); $scope.loading = false; if (err) { $scope.$emit('UpdateTx'); $scope.error = bwsError.msg(err, gettextCatalog.getString('Could not reject payment')); $scope.$digest(); } else { $modalInstance.close(txpr); } }); }, 100); }; $scope.remove = function(txp) { self.setOngoingProcess(gettextCatalog.getString('Deleting payment')); $scope.loading = true; $scope.error = null; $timeout(function() { fc.removeTxProposal(txp, function(err, txpb) { self.setOngoingProcess(); $scope.loading = false; // Hacky: request tries to parse an empty response if (err && !(err.message && err.message.match(/Unexpected/))) { $scope.$emit('UpdateTx'); $scope.error = bwsError.msg(err, gettextCatalog.getString('Could not delete payment proposal')); $scope.$digest(); return; } $modalInstance.close(); }); }, 100); }; $scope.broadcast = function(txp) { self.setOngoingProcess(gettextCatalog.getString('Broadcasting Payment')); $scope.loading = true; $scope.error = null; $timeout(function() { fc.broadcastTxProposal(txp, function(err, txpb, memo) { self.setOngoingProcess(); $scope.loading = false; if (err) { $scope.error = bwsError.msg(err, gettextCatalog.getString('Could not broadcast payment')); $scope.$digest(); } else { if (memo) $log.info(memo); $modalInstance.close(txpb); } }); }, 100); }; $scope.copyToClipboard = function(addr) { if (!addr) return; self.copyToClipboard(addr); }; $scope.cancel = lodash.debounce(function() { $modalInstance.dismiss('cancel'); }, 0, 1000); }; var modalInstance = $modal.open({ templateUrl: 'views/modals/txp-details.html', windowClass: animationService.modalAnimated.slideRight, controller: ModalInstanceCtrl, }); var disableCloseModal = $rootScope.$on('closeModal', function() { modalInstance.dismiss('cancel'); }); modalInstance.result.finally(function() { $rootScope.modalOpened = false; disableCloseModal(); var m = angular.element(document.getElementsByClassName('reveal-modal')); m.addClass(animationService.modalAnimated.slideOutRight); }); modalInstance.result.then(function(txp) { self.setOngoingProcess(); if (txp) { txStatus.notify(txp, function() { $scope.$emit('Local/TxProposalAction', txp.status == 'broadcasted'); }); } else { $timeout(function() { $scope.$emit('Local/TxProposalAction'); }, 100); } }); }; this.setAddress = function(forceNew) { self.addrError = null; var fc = profileService.focusedClient; if (!fc) return; // Address already set? if (!forceNew && self.addr) { return; } self.generatingAddress = true; $timeout(function() { addressService.getAddress(fc.credentials.walletId, forceNew, function(err, addr) { self.generatingAddress = false; if (err) { self.addrError = err; } else { if (addr) self.addr = addr; } $scope.$digest(); }); }); }; this.copyToClipboard = function(addr) { if (isCordova) { window.cordova.plugins.clipboard.copy(addr); window.plugins.toast.showShortCenter(gettextCatalog.getString('Copied to clipboard')); } else if (nodeWebkit.isDefined()) { nodeWebkit.writeToClipboard(addr); } }; this.shareAddress = function(addr) { if (isCordova) { if (isMobile.Android() || isMobile.Windows()) { window.ignoreMobilePause = true; } window.plugins.socialsharing.share('bitcoin:' + addr, null, null, null); } }; this.openCustomizedAmountModal = function(addr) { $rootScope.modalOpened = true; var self = this; var fc = profileService.focusedClient; var ModalInstanceCtrl = function($scope, $modalInstance) { $scope.addr = addr; $scope.color = fc.backgroundColor; $scope.unitName = self.unitName; $scope.alternativeAmount = self.alternativeAmount; $scope.alternativeName = self.alternativeName; $scope.alternativeIsoCode = self.alternativeIsoCode; $scope.isRateAvailable = self.isRateAvailable; $scope.unitToSatoshi = self.unitToSatoshi; $scope.unitDecimals = self.unitDecimals; var satToUnit = 1 / self.unitToSatoshi; $scope.showAlternative = false; $scope.isCordova = isCordova; Object.defineProperty($scope, "_customAlternative", { get: function() { return $scope.customAlternative; }, set: function(newValue) { $scope.customAlternative = newValue; if (typeof(newValue) === 'number' && $scope.isRateAvailable) { $scope.customAmount = parseFloat((rateService.fromFiat(newValue, $scope.alternativeIsoCode) * satToUnit).toFixed($scope.unitDecimals), 10); } else { $scope.customAmount = null; } }, enumerable: true, configurable: true }); Object.defineProperty($scope, "_customAmount", { get: function() { return $scope.customAmount; }, set: function(newValue) { $scope.customAmount = newValue; if (typeof(newValue) === 'number' && $scope.isRateAvailable) { $scope.customAlternative = parseFloat((rateService.toFiat(newValue * $scope.unitToSatoshi, $scope.alternativeIsoCode)).toFixed(2), 10); } else { $scope.customAlternative = null; } $scope.alternativeAmount = $scope.customAlternative; }, enumerable: true, configurable: true }); $scope.submitForm = function(form) { var satToBtc = 1 / 100000000; var amount = form.amount.$modelValue; var amountSat = parseInt((amount * $scope.unitToSatoshi).toFixed(0)); $timeout(function() { $scope.customizedAmountUnit = amount + ' ' + $scope.unitName; $scope.customizedAlternativeUnit = $filter('noFractionNumber')(form.alternative.$modelValue, 2) + ' ' + $scope.alternativeIsoCode; if ($scope.unitName == 'bits') { amount = (amountSat * satToBtc).toFixed(8); } $scope.customizedAmountBtc = amount; }, 1); }; $scope.toggleAlternative = function() { $scope.showAlternative = !$scope.showAlternative; }; $scope.shareAddress = function(uri) { if (isCordova) { if (isMobile.Android() || isMobile.Windows()) { window.ignoreMobilePause = true; } window.plugins.socialsharing.share(uri, null, null, null); } }; $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; }; var modalInstance = $modal.open({ templateUrl: 'views/modals/customized-amount.html', windowClass: animationService.modalAnimated.slideUp, controller: ModalInstanceCtrl, }); var disableCloseModal = $rootScope.$on('closeModal', function() { modalInstance.dismiss('cancel'); }); modalInstance.result.finally(function() { $rootScope.modalOpened = false; disableCloseModal(); var m = angular.element(document.getElementsByClassName('reveal-modal')); m.addClass(animationService.modalAnimated.slideOutDown); }); }; // Send this.canShowAlternative = function() { return $scope.showAlternative; }; this.showAlternative = function() { $scope.showAlternative = true; }; this.hideAlternative = function() { $scope.showAlternative = false; }; this.resetError = function() { this.error = this.success = null; }; this.bindTouchDown = function(tries) { var self = this; tries = tries || 0; if (tries > 5) return; var e = document.getElementById('menu-walletHome'); if (!e) return $timeout(function() { self.bindTouchDown(++tries); }, 500); // on touchdown elements $log.debug('Binding touchstart elements...'); ['hamburger', 'menu-walletHome', 'menu-send', 'menu-receive'].forEach(function(id) { var e = document.getElementById(id); if (e) e.addEventListener('touchstart', function() { try { event.preventDefault(); } catch (e) {}; angular.element(e).triggerHandler('click'); }, true); }); } this.hideMenuBar = lodash.debounce(function(hide) { if (hide) { $rootScope.shouldHideMenuBar = true; this.bindTouchDown(); } else { $rootScope.shouldHideMenuBar = false; } $rootScope.$digest(); }, 100); this.formFocus = function(what) { if (isCordova && !this.isWindowsPhoneApp) { this.hideMenuBar(what); } var self = this; if (isCordova && !this.isWindowsPhoneApp && what == 'address') { getClipboard(function(value) { if (value) { document.getElementById("amount").focus(); $timeout(function() { window.plugins.toast.showShortCenter(gettextCatalog.getString('Pasted from clipboard')); self.setForm(value); }, 100); } }); } if (!this.isWindowsPhoneApp) return if (!what) { this.hideAddress = false; this.hideAmount = false; } else { if (what == 'amount') { this.hideAddress = true; } else if (what == 'msg') { this.hideAddress = true; this.hideAmount = true; } } $timeout(function() { $rootScope.$digest(); }, 1); }; this.setSendFormInputs = function() { var unitToSat = this.unitToSatoshi; var satToUnit = 1 / unitToSat; /** * Setting the two related amounts as properties prevents an infinite * recursion for watches while preserving the original angular updates * */ Object.defineProperty($scope, "_alternative", { get: function() { return $scope.__alternative; }, set: function(newValue) { $scope.__alternative = newValue; if (typeof(newValue) === 'number' && self.isRateAvailable) { $scope._amount = parseFloat((rateService.fromFiat(newValue, self.alternativeIsoCode) * satToUnit).toFixed(self.unitDecimals), 10); } else { $scope.__amount = null; } }, enumerable: true, configurable: true }); Object.defineProperty($scope, "_amount", { get: function() { return $scope.__amount; }, set: function(newValue) { $scope.__amount = newValue; if (typeof(newValue) === 'number' && self.isRateAvailable) { $scope.__alternative = parseFloat((rateService.toFiat(newValue * self.unitToSatoshi, self.alternativeIsoCode)).toFixed(2), 10); } else { $scope.__alternative = null; } self.alternativeAmount = $scope.__alternative; self.resetError(); }, enumerable: true, configurable: true }); Object.defineProperty($scope, "_address", { get: function() { return $scope.__address; }, set: function(newValue) { $scope.__address = self.onAddressChange(newValue); if ($scope.sendForm && $scope.sendForm.address.$valid) { self.lockAddress = true; } }, enumerable: true, configurable: true }); var fc = profileService.focusedClient; // ToDo: use a credential's (or fc's) function for this this.hideNote = !fc.credentials.sharedEncryptingKey; }; this.setSendError = function(err) { var fc = profileService.focusedClient; var prefix = fc.credentials.m > 1 ? gettextCatalog.getString('Could not create payment proposal') : gettextCatalog.getString('Could not send payment'); this.error = bwsError.msg(err, prefix); $timeout(function() { $scope.$digest(); }, 1); }; // subscription this.setOngoingProcess = function(name) { var self = this; self.blockUx = !!name; if (isCordova) { if (name) { window.plugins.spinnerDialog.hide(); window.plugins.spinnerDialog.show(null, name + '...', true); } else { window.plugins.spinnerDialog.hide(); } } else { self.onGoingProcess = name; $timeout(function() { $rootScope.$apply(); }); }; }; this.submitForm = function() { if (!$scope._amount || !$scope._address) return; var fc = profileService.focusedClient; var unitToSat = this.unitToSatoshi; var currentSpendUnconfirmed = configWallet.spendUnconfirmed; var outputs = []; this.resetError(); if (isCordova && this.isWindowsPhoneApp) { this.hideAddress = false; this.hideAmount = false; } var form = $scope.sendForm; var comment = form.comment.$modelValue; // ToDo: use a credential's (or fc's) function for this if (comment && !fc.credentials.sharedEncryptingKey) { var msg = 'Could not add message to imported wallet without shared encrypting key'; $log.warn(msg); return self.setSendError(gettext(msg)); } $timeout(function() { var paypro = self._paypro; var address, amount; address = form.address.$modelValue; amount = parseInt((form.amount.$modelValue * unitToSat).toFixed(0)); outputs.push({ 'toAddress': address, 'amount': amount, 'message': comment }); var opts = { toAddress: address, amount: amount, outputs: outputs, message: comment, payProUrl: paypro ? paypro.url : null, lockedCurrentFeePerKb: self.lockedCurrentFeePerKb }; self.setOngoingProcess(gettextCatalog.getString('Creating transaction')); txService.createTx(opts, function(err, txp) { self.setOngoingProcess(); if (err) { return self.setSendError(err); } if (!fc.canSign() && !fc.isPrivKeyExternal()) { self.setOngoingProcess(); $log.info('No signing proposal: No private key'); self.resetForm(); txStatus.notify(txp, function() { return $scope.$emit('Local/TxProposalAction'); }); return; } else { $rootScope.$emit('Local/NeedsConfirmation', txp, function(accept) { if (accept) self.confirmTx(txp); else self.resetForm(); }); } }); }, 100); }; this.confirmTx = function(txp) { var self = this; txService.prepare(function(err) { if (err) { return self.setSendError(err); } self.setOngoingProcess(gettextCatalog.getString('Sending transaction')); txService.publishTx(txp, function(err, txpPublished) { if (err) { self.setOngoingProcess(); self.setSendError(err); } else { txService.signAndBroadcast(txpPublished, { reporterFn: self.setOngoingProcess.bind(self) }, function(err, txp) { self.resetForm(); if (err) { self.error = err.message ? err.message : gettext('The payment was created but could not be completed. Please try again from home screen'); $scope.$emit('Local/TxProposalAction'); $timeout(function() { $scope.$digest(); }, 1); } else { go.walletHome(); txStatus.notify(txp, function() { $scope.$emit('Local/TxProposalAction', txp.status == 'broadcasted'); }); } }); } }); }); }; this.setForm = function(to, amount, comment) { var form = $scope.sendForm; if (to) { form.address.$setViewValue(to); form.address.$isValid = true; form.address.$render(); this.lockAddress = true; } if (amount) { form.amount.$setViewValue("" + amount); form.amount.$isValid = true; form.amount.$render(); this.lockAmount = true; } if (comment) { form.comment.$setViewValue(comment); form.comment.$isValid = true; form.comment.$render(); } }; this.resetForm = function() { this.resetError(); if (this.countDown) $interval.cancel(this.countDown); this._paypro = null; this.lockedCurrentFeePerKb = null; this.lockAddress = false; this.lockAmount = false; this._amount = this._address = null; var form = $scope.sendForm; if (form && form.amount) { form.amount.$pristine = true; form.amount.$setViewValue(''); form.amount.$render(); form.comment.$setViewValue(''); form.comment.$render(); form.$setPristine(); if (form.address) { form.address.$pristine = true; form.address.$setViewValue(''); form.address.$render(); } } $timeout(function() { $rootScope.$digest(); }, 1); }; this.openPPModal = function(paypro) { $rootScope.modalOpened = true; var ModalInstanceCtrl = function($scope, $modalInstance) { var fc = profileService.focusedClient; var satToUnit = 1 / self.unitToSatoshi; $scope.paypro = paypro; $scope.alternative = self.alternativeAmount; $scope.alternativeIsoCode = self.alternativeIsoCode; $scope.isRateAvailable = self.isRateAvailable; $scope.unitTotal = (paypro.amount * satToUnit).toFixed(self.unitDecimals); $scope.unitName = self.unitName; $scope.color = fc.backgroundColor; $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; }; var modalInstance = $modal.open({ templateUrl: 'views/modals/paypro.html', windowClass: animationService.modalAnimated.slideUp, controller: ModalInstanceCtrl, }); var disableCloseModal = $rootScope.$on('closeModal', function() { modalInstance.dismiss('cancel'); }); modalInstance.result.finally(function() { $rootScope.modalOpened = false; disableCloseModal(); var m = angular.element(document.getElementsByClassName('reveal-modal')); m.addClass(animationService.modalAnimated.slideOutDown); }); }; this.setFromPayPro = function(uri, cb) { if (!cb) cb = function() {}; var fc = profileService.focusedClient; if (isChromeApp) { this.error = gettext('Payment Protocol not supported on Chrome App'); return cb(true); } var satToUnit = 1 / this.unitToSatoshi; var self = this; /// Get information of payment if using Payment Protocol self.setOngoingProcess(gettextCatalog.getString('Fetching Payment Information')); $log.debug('Fetch PayPro Request...', uri); $timeout(function() { fc.fetchPayPro({ payProUrl: uri, }, function(err, paypro) { self.setOngoingProcess(); if (err) { $log.warn('Could not fetch payment request:', err); self.resetForm(); var msg = err.toString(); if (msg.match('HTTP')) { msg = gettext('Could not fetch payment information'); } self.error = msg; $timeout(function() { $rootScope.$digest(); }, 1); return cb(true); } if (!paypro.verified) { self.resetForm(); $log.warn('Failed to verify payment protocol signatures'); self.error = gettext('Payment Protocol Invalid'); $timeout(function() { $rootScope.$digest(); }, 1); return cb(true); } self._paypro = paypro; self.setForm(paypro.toAddress, (paypro.amount * satToUnit).toFixed(self.unitDecimals), paypro.memo); _paymentTimeControl(paypro.expires); return cb(); }); }, 1); }; function _paymentTimeControl(expirationTime) { self.paymentExpired = false; setExpirationTime(); self.countDown = $interval(function() { setExpirationTime(); }, 1000); function setExpirationTime() { var now = Math.floor(Date.now() / 1000); if (now > expirationTime) { setExpiredValues(); return; } var totalSecs = expirationTime - now; var m = Math.floor(totalSecs / 60); var s = totalSecs % 60; self.remainingTimeStr = ('0' + m).slice(-2) + ":" + ('0' + s).slice(-2); }; function setExpiredValues() { self.paymentExpired = true; self.remainingTimeStr = null; self._paypro = null; self.error = gettext('Cannot sign: The payment request has expired'); if (self.countDown) $interval.cancel(self.countDown); }; }; this.setFromUri = function(uri) { var self = this; function sanitizeUri(uri) { // Fixes when a region uses comma to separate decimals var regex = /[\?\&]amount=(\d+([\,\.]\d+)?)/i; var match = regex.exec(uri); if (!match || match.length === 0) { return uri; } var value = match[0].replace(',', '.'); var newUri = uri.replace(regex, value); return newUri; }; var satToUnit = 1 / this.unitToSatoshi; // URI extensions for Payment Protocol with non-backwards-compatible request if ((/^bitcoin:\?r=[\w+]/).exec(uri)) { uri = decodeURIComponent(uri.replace('bitcoin:?r=', '')); this.setFromPayPro(uri, function(err) { if (err) { return err; } }); } else { uri = sanitizeUri(uri); if (!bitcore.URI.isValid(uri)) { return uri; } var parsed = new bitcore.URI(uri); var addr = parsed.address ? parsed.address.toString() : ''; var message = parsed.message; var amount = parsed.amount ? (parsed.amount.toFixed(0) * satToUnit).toFixed(this.unitDecimals) : 0; if (parsed.r) { this.setFromPayPro(parsed.r, function(err) { if (err && addr && amount) { self.setForm(addr, amount, message); return addr; } }); } else { this.setForm(addr, amount, message); return addr; } } }; this.onAddressChange = function(value) { this.resetError(); if (!value) return ''; if (this._paypro) return value; if (value.indexOf('bitcoin:') === 0) { return this.setFromUri(value); } else if (/^https?:\/\//.test(value)) { return this.setFromPayPro(value); } else { return value; } }; // History function strip(number) { return (parseFloat(number.toPrecision(12))); } this.getUnitName = function() { return this.unitName; }; this.getAlternativeIsoCode = function() { return this.alternativeIsoCode; }; this.openTxModal = function(tx) { $rootScope.$emit('Local/TxModal', tx); }; this.hasAction = function(actions, action) { return actions.hasOwnProperty('create'); }; this._doSendAll = function(amount) { this.setForm(null, amount, null); }; this.sendAll = function(totalBytesToSendMax, availableBalanceSat) { var self = this; var availableMaxBalance; var feeToSendMaxStr; this.error = null; this.setOngoingProcess(gettextCatalog.getString('Calculating fee')); feeService.getCurrentFeeValue(function(err, feePerKb) { self.setOngoingProcess(); if (err || lodash.isNull(feePerKb)) { self.error = gettext('Could not get fee value'); return; } var feeToSendMaxSat = parseInt(((totalBytesToSendMax * feePerKb) / 1000.).toFixed(0)); if (availableBalanceSat > feeToSendMaxSat) { self.lockedCurrentFeePerKb = feePerKb; availableMaxBalance = strip((availableBalanceSat - feeToSendMaxSat) * self.satToUnit); feeToSendMaxStr = profileService.formatAmount(feeToSendMaxSat) + ' ' + self.unitName; } else { self.error = gettext('Not enought funds for fee'); return; } var msg = gettextCatalog.getString("{{fee}} will be deducted for bitcoin networking fees", { fee: feeToSendMaxStr }); $scope.$apply(); confirmDialog.show(msg, function(confirmed) { if (confirmed) { self._doSendAll(availableMaxBalance); } else { self.resetForm(); } }); }); }; /* Start setup */ lodash.assign(self, vanillaScope); this.bindTouchDown(); if (profileService.focusedClient) { this.setAddress(); this.setSendFormInputs(); } });
src/js/controllers/walletHome.js
'use strict'; angular.module('copayApp.controllers').controller('walletHomeController', function($scope, $rootScope, $interval, $timeout, $filter, $modal, $log, notification, txStatus, isCordova, isMobile, profileService, lodash, configService, rateService, storageService, bitcore, isChromeApp, gettext, gettextCatalog, nodeWebkit, addressService, ledger, bwsError, confirmDialog, txFormatService, animationService, addressbookService, go, feeService, txService) { var self = this; window.ignoreMobilePause = false; $rootScope.shouldHideMenuBar = false; $rootScope.wpInputFocused = false; var config = configService.getSync(); var configWallet = config.wallet; var walletSettings = configWallet.settings; var ret = {}; // INIT. Global value ret.unitToSatoshi = walletSettings.unitToSatoshi; ret.satToUnit = 1 / ret.unitToSatoshi; ret.unitName = walletSettings.unitName; ret.alternativeIsoCode = walletSettings.alternativeIsoCode; ret.alternativeName = walletSettings.alternativeName; ret.alternativeAmount = 0; ret.unitDecimals = walletSettings.unitDecimals; ret.isCordova = isCordova; ret.addresses = []; ret.isMobile = isMobile.any(); ret.isWindowsPhoneApp = isMobile.Windows() && isCordova; ret.countDown = null; var vanillaScope = ret; var disableScannerListener = $rootScope.$on('dataScanned', function(event, data) { self.setForm(data); $rootScope.$emit('Local/SetTab', 'send'); var form = $scope.sendForm; if (form.address.$invalid && !self.blockUx) { self.resetForm(); self.error = gettext('Could not recognize a valid Bitcoin QR Code'); } }); var disablePaymentUriListener = $rootScope.$on('paymentUri', function(event, uri) { $rootScope.$emit('Local/SetTab', 'send'); $timeout(function() { self.setForm(uri); }, 100); }); var disableAddrListener = $rootScope.$on('Local/AddressIsUsed', function() { self.setAddress(true); }); var disableFocusListener = $rootScope.$on('Local/NewFocusedWalletReady', function() { self.addr = null; self.resetForm(); $scope.search = ''; if (profileService.focusedClient && profileService.focusedClient.isComplete()) { self.setAddress(); self.setSendFormInputs(); } $log.debug('Cleaning WalletHome Instance'); lodash.each(self, function(v, k) { if (lodash.isFunction(v)) return; if (vanillaScope[k]) { self[k] = vanillaScope[k]; return; } if (k == 'isRateAvailable') return; delete self[k]; }); }); var disableResumeListener = $rootScope.$on('Local/Resume', function() { // This is needed then the apps go to sleep self.bindTouchDown(); }); var disableTabListener = $rootScope.$on('Local/TabChanged', function(e, tab) { // This will slow down switch, do not add things here! switch (tab) { case 'receive': // just to be sure we have an address self.setAddress(); break; case 'send': self.resetError(); }; }); var disableOngoingProcessListener = $rootScope.$on('Addon/OngoingProcess', function(e, name) { self.setOngoingProcess(name); }); $scope.$on('$destroy', function() { disableAddrListener(); disableScannerListener(); disablePaymentUriListener(); disableTabListener(); disableFocusListener(); disableResumeListener(); disableOngoingProcessListener(); $rootScope.shouldHideMenuBar = false; }); this.onQrCodeScanned = function(data) { if (data) go.send(); $rootScope.$emit('dataScanned', data); }; rateService.whenAvailable(function() { self.isRateAvailable = true; $rootScope.$digest(); }); var getClipboard = function(cb) { if (!isCordova || isMobile.Windows()) return cb(); window.cordova.plugins.clipboard.paste(function(value) { var fc = profileService.focusedClient; var Address = bitcore.Address; var networkName = fc.credentials.network; if (Address.isValid(value, networkName) && !$scope.newAddress) { return cb(value); } }); }; var accept_msg = gettextCatalog.getString('Accept'); var cancel_msg = gettextCatalog.getString('Cancel'); var confirm_msg = gettextCatalog.getString('Confirm'); this.openDestinationAddressModal = function(wallets, address) { $rootScope.modalOpened = true; var fc = profileService.focusedClient; self.lockAddress = false; self._address = null; var ModalInstanceCtrl = function($scope, $modalInstance) { $scope.wallets = wallets; $scope.editAddressbook = false; $scope.addAddressbookEntry = false; $scope.selectedAddressbook = {}; $scope.newAddress = address; $scope.walletName = fc.credentials.walletName; $scope.color = fc.backgroundColor; $scope.addressbook = { 'address': ($scope.newAddress || ''), 'label': '' }; $scope.checkClipboard = function() { if (!$scope.newAddress) { getClipboard(function(value) { $scope.newAddress = value; }); } }; $scope.beforeQrCodeScann = function() { $scope.error = null; $scope.addAddressbookEntry = true; $scope.editAddressbook = false; }; $scope.onQrCodeScanned = function(data, addressbookForm) { $timeout(function() { var form = addressbookForm; if (data && form) { data = data.replace('bitcoin:', ''); form.address.$setViewValue(data); form.address.$isValid = true; form.address.$render(); } $scope.$digest(); }, 100); }; $scope.selectAddressbook = function(addr) { $modalInstance.close(addr); }; $scope.toggleEditAddressbook = function() { $scope.editAddressbook = !$scope.editAddressbook; $scope.selectedAddressbook = {}; $scope.addAddressbookEntry = false; }; $scope.toggleSelectAddressbook = function(addr) { $scope.selectedAddressbook[addr] = $scope.selectedAddressbook[addr] ? false : true; }; $scope.toggleAddAddressbookEntry = function() { $scope.error = null; $scope.addressbook = { 'address': ($scope.newAddress || ''), 'label': '' }; $scope.addAddressbookEntry = !$scope.addAddressbookEntry; }; $scope.list = function() { $scope.error = null; addressbookService.list(function(err, ab) { if (err) { $scope.error = err; return; } $scope.list = ab; }); }; $scope.add = function(addressbook) { $scope.error = null; $timeout(function() { addressbookService.add(addressbook, function(err, ab) { if (err) { $scope.error = err; return; } $rootScope.$emit('Local/AddressbookUpdated', ab); $scope.list = ab; $scope.editAddressbook = true; $scope.toggleEditAddressbook(); $scope.$digest(); }); }, 100); }; $scope.remove = function(addr) { $scope.error = null; $timeout(function() { addressbookService.remove(addr, function(err, ab) { if (err) { $scope.error = err; return; } $rootScope.$emit('Local/AddressbookUpdated', ab); $scope.list = ab; $scope.$digest(); }); }, 100); }; $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; $scope.selectWallet = function(walletId, walletName) { profileService.isBackupNeeded(walletId, function(needsBackup) { $scope.needsBackup = {}; $scope.needsBackup[walletId] = needsBackup; if (needsBackup) return; $scope.gettingAddress = true; $scope.selectedWalletName = walletName; $timeout(function() { $scope.$apply(); }); addressService.getAddress(walletId, false, function(err, addr) { $scope.gettingAddress = false; if (err) { self.error = err; $modalInstance.dismiss('cancel'); return; } $modalInstance.close(addr); }); }); }; }; var modalInstance = $modal.open({ templateUrl: 'views/modals/destination-address.html', windowClass: animationService.modalAnimated.slideUp, controller: ModalInstanceCtrl, }); var disableCloseModal = $rootScope.$on('closeModal', function() { modalInstance.dismiss('cancel'); }); modalInstance.result.finally(function() { $rootScope.modalOpened = false; disableCloseModal(); var m = angular.element(document.getElementsByClassName('reveal-modal')); m.addClass(animationService.modalAnimated.slideOutDown); }); modalInstance.result.then(function(addr) { if (addr) { self.setForm(addr); } }, function() { // onRejected self.resetForm(); }); }; var GLIDERA_LOCK_TIME = 6 * 60 * 60; // isGlidera flag is a security measure so glidera status is not // only determined by the tx.message this.openTxpModal = function(tx, copayers, isGlidera) { $rootScope.modalOpened = true; var self = this; var fc = profileService.focusedClient; var currentSpendUnconfirmed = configWallet.spendUnconfirmed; var ModalInstanceCtrl = function($scope, $modalInstance) { $scope.paymentExpired = null; checkPaypro(); $scope.error = null; $scope.copayers = copayers $scope.copayerId = fc.credentials.copayerId; $scope.canSign = fc.canSign() || fc.isPrivKeyExternal(); $scope.loading = null; $scope.color = fc.backgroundColor; $scope.isShared = fc.credentials.n > 1; var now = Math.floor(Date.now() / 1000); // ToDo: use tx.customData instead of tx.message if (tx.message === 'Glidera transaction' && isGlidera) { tx.isGlidera = true; if (tx.canBeRemoved) { tx.canBeRemoved = (Date.now() / 1000 - (tx.ts || tx.createdOn)) > GLIDERA_LOCK_TIME; } } $scope.tx = tx; $scope.currentSpendUnconfirmed = currentSpendUnconfirmed; $scope.getShortNetworkName = function() { return fc.credentials.networkName.substring(0, 4); }; function checkPaypro() { if (tx.payProUrl && !isChromeApp) { fc.fetchPayPro({ payProUrl: tx.payProUrl, }, function(err, paypro) { if (err) return; tx.paypro = paypro; paymentTimeControl(tx.paypro.expires); }); } }; function paymentTimeControl(expirationTime) { $scope.paymentExpired = false; setExpirationTime(); self.countDown = $interval(function() { setExpirationTime(); }, 1000); function setExpirationTime() { if (moment().isAfter(expirationTime * 1000)) { $scope.paymentExpired = true; if (self.countDown) $interval.cancel(self.countDown); } $scope.expires = moment(expirationTime * 1000).fromNow(); }; }; lodash.each(['TxProposalRejectedBy', 'TxProposalAcceptedBy', 'transactionProposalRemoved', 'TxProposalRemoved', 'NewOutgoingTx', 'UpdateTx'], function(eventName) { $rootScope.$on(eventName, function() { fc.getTx($scope.tx.id, function(err, tx) { if (err) { if (err.message && err.message == 'TX_NOT_FOUND' && (eventName == 'transactionProposalRemoved' || eventName == 'TxProposalRemoved')) { $scope.tx.removed = true; $scope.tx.canBeRemoved = false; $scope.tx.pendingForUs = false; $scope.$apply(); return; } return; } var action = lodash.find(tx.actions, { copayerId: fc.credentials.copayerId }); $scope.tx = txFormatService.processTx(tx); if (!action && tx.status == 'pending') $scope.tx.pendingForUs = true; $scope.updateCopayerList(); $scope.$apply(); }); }); }); $scope.updateCopayerList = function() { lodash.map($scope.copayers, function(cp) { lodash.each($scope.tx.actions, function(ac) { if (cp.id == ac.copayerId) { cp.action = ac.type; } }); }); }; $scope.sign = function(txp) { var fc = profileService.focusedClient; $scope.error = null; $scope.loading = true; txService.prepareAndSignAndBroadcast(txp, { reporterFn: self.setOngoingProcess.bind(self) }, function(err, txp) { $scope.loading = false; $scope.$emit('UpdateTx'); if (err) { $scope.error = err; $timeout(function() { $scope.$digest(); }); return; } $modalInstance.close(txp); return; }); }; $scope.reject = function(txp) { self.setOngoingProcess(gettextCatalog.getString('Rejecting payment')); $scope.loading = true; $scope.error = null; $timeout(function() { fc.rejectTxProposal(txp, null, function(err, txpr) { self.setOngoingProcess(); $scope.loading = false; if (err) { $scope.$emit('UpdateTx'); $scope.error = bwsError.msg(err, gettextCatalog.getString('Could not reject payment')); $scope.$digest(); } else { $modalInstance.close(txpr); } }); }, 100); }; $scope.remove = function(txp) { self.setOngoingProcess(gettextCatalog.getString('Deleting payment')); $scope.loading = true; $scope.error = null; $timeout(function() { fc.removeTxProposal(txp, function(err, txpb) { self.setOngoingProcess(); $scope.loading = false; // Hacky: request tries to parse an empty response if (err && !(err.message && err.message.match(/Unexpected/))) { $scope.$emit('UpdateTx'); $scope.error = bwsError.msg(err, gettextCatalog.getString('Could not delete payment proposal')); $scope.$digest(); return; } $modalInstance.close(); }); }, 100); }; $scope.broadcast = function(txp) { self.setOngoingProcess(gettextCatalog.getString('Broadcasting Payment')); $scope.loading = true; $scope.error = null; $timeout(function() { fc.broadcastTxProposal(txp, function(err, txpb, memo) { self.setOngoingProcess(); $scope.loading = false; if (err) { $scope.error = bwsError.msg(err, gettextCatalog.getString('Could not broadcast payment')); $scope.$digest(); } else { if (memo) $log.info(memo); $modalInstance.close(txpb); } }); }, 100); }; $scope.copyToClipboard = function(addr) { if (!addr) return; self.copyToClipboard(addr); }; $scope.cancel = lodash.debounce(function() { $modalInstance.dismiss('cancel'); }, 0, 1000); }; var modalInstance = $modal.open({ templateUrl: 'views/modals/txp-details.html', windowClass: animationService.modalAnimated.slideRight, controller: ModalInstanceCtrl, }); var disableCloseModal = $rootScope.$on('closeModal', function() { modalInstance.dismiss('cancel'); }); modalInstance.result.finally(function() { $rootScope.modalOpened = false; disableCloseModal(); var m = angular.element(document.getElementsByClassName('reveal-modal')); m.addClass(animationService.modalAnimated.slideOutRight); }); modalInstance.result.then(function(txp) { self.setOngoingProcess(); if (txp) { txStatus.notify(txp, function() { $scope.$emit('Local/TxProposalAction', txp.status == 'broadcasted'); }); } else { $timeout(function() { $scope.$emit('Local/TxProposalAction'); }, 100); } }); }; this.setAddress = function(forceNew) { self.addrError = null; var fc = profileService.focusedClient; if (!fc) return; // Address already set? if (!forceNew && self.addr) { return; } self.generatingAddress = true; $timeout(function() { addressService.getAddress(fc.credentials.walletId, forceNew, function(err, addr) { self.generatingAddress = false; if (err) { self.addrError = err; } else { if (addr) self.addr = addr; } $scope.$digest(); }); }); }; this.copyToClipboard = function(addr) { if (isCordova) { window.cordova.plugins.clipboard.copy(addr); window.plugins.toast.showShortCenter(gettextCatalog.getString('Copied to clipboard')); } else if (nodeWebkit.isDefined()) { nodeWebkit.writeToClipboard(addr); } }; this.shareAddress = function(addr) { if (isCordova) { if (isMobile.Android() || isMobile.Windows()) { window.ignoreMobilePause = true; } window.plugins.socialsharing.share('bitcoin:' + addr, null, null, null); } }; this.openCustomizedAmountModal = function(addr) { $rootScope.modalOpened = true; var self = this; var fc = profileService.focusedClient; var ModalInstanceCtrl = function($scope, $modalInstance) { $scope.addr = addr; $scope.color = fc.backgroundColor; $scope.unitName = self.unitName; $scope.alternativeAmount = self.alternativeAmount; $scope.alternativeName = self.alternativeName; $scope.alternativeIsoCode = self.alternativeIsoCode; $scope.isRateAvailable = self.isRateAvailable; $scope.unitToSatoshi = self.unitToSatoshi; $scope.unitDecimals = self.unitDecimals; var satToUnit = 1 / self.unitToSatoshi; $scope.showAlternative = false; $scope.isCordova = isCordova; Object.defineProperty($scope, "_customAlternative", { get: function() { return $scope.customAlternative; }, set: function(newValue) { $scope.customAlternative = newValue; if (typeof(newValue) === 'number' && $scope.isRateAvailable) { $scope.customAmount = parseFloat((rateService.fromFiat(newValue, $scope.alternativeIsoCode) * satToUnit).toFixed($scope.unitDecimals), 10); } else { $scope.customAmount = null; } }, enumerable: true, configurable: true }); Object.defineProperty($scope, "_customAmount", { get: function() { return $scope.customAmount; }, set: function(newValue) { $scope.customAmount = newValue; if (typeof(newValue) === 'number' && $scope.isRateAvailable) { $scope.customAlternative = parseFloat((rateService.toFiat(newValue * $scope.unitToSatoshi, $scope.alternativeIsoCode)).toFixed(2), 10); } else { $scope.customAlternative = null; } $scope.alternativeAmount = $scope.customAlternative; }, enumerable: true, configurable: true }); $scope.submitForm = function(form) { var satToBtc = 1 / 100000000; var amount = form.amount.$modelValue; var amountSat = parseInt((amount * $scope.unitToSatoshi).toFixed(0)); $timeout(function() { $scope.customizedAmountUnit = amount + ' ' + $scope.unitName; $scope.customizedAlternativeUnit = $filter('noFractionNumber')(form.alternative.$modelValue, 2) + ' ' + $scope.alternativeIsoCode; if ($scope.unitName == 'bits') { amount = (amountSat * satToBtc).toFixed(8); } $scope.customizedAmountBtc = amount; }, 1); }; $scope.toggleAlternative = function() { $scope.showAlternative = !$scope.showAlternative; }; $scope.shareAddress = function(uri) { if (isCordova) { if (isMobile.Android() || isMobile.Windows()) { window.ignoreMobilePause = true; } window.plugins.socialsharing.share(uri, null, null, null); } }; $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; }; var modalInstance = $modal.open({ templateUrl: 'views/modals/customized-amount.html', windowClass: animationService.modalAnimated.slideUp, controller: ModalInstanceCtrl, }); var disableCloseModal = $rootScope.$on('closeModal', function() { modalInstance.dismiss('cancel'); }); modalInstance.result.finally(function() { $rootScope.modalOpened = false; disableCloseModal(); var m = angular.element(document.getElementsByClassName('reveal-modal')); m.addClass(animationService.modalAnimated.slideOutDown); }); }; // Send this.canShowAlternative = function() { return $scope.showAlternative; }; this.showAlternative = function() { $scope.showAlternative = true; }; this.hideAlternative = function() { $scope.showAlternative = false; }; this.resetError = function() { this.error = this.success = null; }; this.bindTouchDown = function(tries) { var self = this; tries = tries || 0; if (tries > 5) return; var e = document.getElementById('menu-walletHome'); if (!e) return $timeout(function() { self.bindTouchDown(++tries); }, 500); // on touchdown elements $log.debug('Binding touchstart elements...'); ['hamburger', 'menu-walletHome', 'menu-send', 'menu-receive'].forEach(function(id) { var e = document.getElementById(id); if (e) e.addEventListener('touchstart', function() { try { event.preventDefault(); } catch (e) {}; angular.element(e).triggerHandler('click'); }, true); }); } this.hideMenuBar = lodash.debounce(function(hide) { if (hide) { $rootScope.shouldHideMenuBar = true; this.bindTouchDown(); } else { $rootScope.shouldHideMenuBar = false; } $rootScope.$digest(); }, 100); this.formFocus = function(what) { if (isCordova && !this.isWindowsPhoneApp) { this.hideMenuBar(what); } var self = this; if (isCordova && !this.isWindowsPhoneApp && what == 'address') { getClipboard(function(value) { if (value) { document.getElementById("amount").focus(); $timeout(function() { window.plugins.toast.showShortCenter(gettextCatalog.getString('Pasted from clipboard')); self.setForm(value); }, 100); } }); } if (!this.isWindowsPhoneApp) return if (!what) { this.hideAddress = false; this.hideAmount = false; } else { if (what == 'amount') { this.hideAddress = true; } else if (what == 'msg') { this.hideAddress = true; this.hideAmount = true; } } $timeout(function() { $rootScope.$digest(); }, 1); }; this.setSendFormInputs = function() { var unitToSat = this.unitToSatoshi; var satToUnit = 1 / unitToSat; /** * Setting the two related amounts as properties prevents an infinite * recursion for watches while preserving the original angular updates * */ Object.defineProperty($scope, "_alternative", { get: function() { return $scope.__alternative; }, set: function(newValue) { $scope.__alternative = newValue; if (typeof(newValue) === 'number' && self.isRateAvailable) { $scope._amount = parseFloat((rateService.fromFiat(newValue, self.alternativeIsoCode) * satToUnit).toFixed(self.unitDecimals), 10); } else { $scope.__amount = null; } }, enumerable: true, configurable: true }); Object.defineProperty($scope, "_amount", { get: function() { return $scope.__amount; }, set: function(newValue) { $scope.__amount = newValue; if (typeof(newValue) === 'number' && self.isRateAvailable) { $scope.__alternative = parseFloat((rateService.toFiat(newValue * self.unitToSatoshi, self.alternativeIsoCode)).toFixed(2), 10); } else { $scope.__alternative = null; } self.alternativeAmount = $scope.__alternative; self.resetError(); }, enumerable: true, configurable: true }); Object.defineProperty($scope, "_address", { get: function() { return $scope.__address; }, set: function(newValue) { $scope.__address = self.onAddressChange(newValue); if ($scope.sendForm && $scope.sendForm.address.$valid) { self.lockAddress = true; } }, enumerable: true, configurable: true }); var fc = profileService.focusedClient; // ToDo: use a credential's (or fc's) function for this this.hideNote = !fc.credentials.sharedEncryptingKey; }; this.setSendError = function(err) { var fc = profileService.focusedClient; var prefix = fc.credentials.m > 1 ? gettextCatalog.getString('Could not create payment proposal') : gettextCatalog.getString('Could not send payment'); this.error = bwsError.msg(err, prefix); $timeout(function() { $scope.$digest(); }, 1); }; // subscription this.setOngoingProcess = function(name) { var self = this; self.blockUx = !!name; if (isCordova) { if (name) { window.plugins.spinnerDialog.hide(); window.plugins.spinnerDialog.show(null, name + '...', true); } else { window.plugins.spinnerDialog.hide(); } } else { self.onGoingProcess = name; $timeout(function() { $rootScope.$apply(); }); }; }; this.submitForm = function() { if (!$scope._amount || !$scope._address) return; var fc = profileService.focusedClient; var unitToSat = this.unitToSatoshi; var currentSpendUnconfirmed = configWallet.spendUnconfirmed; var outputs = []; this.resetError(); if (isCordova && this.isWindowsPhoneApp) { this.hideAddress = false; this.hideAmount = false; } var form = $scope.sendForm; var comment = form.comment.$modelValue; // ToDo: use a credential's (or fc's) function for this if (comment && !fc.credentials.sharedEncryptingKey) { var msg = 'Could not add message to imported wallet without shared encrypting key'; $log.warn(msg); return self.setSendError(gettext(msg)); } $timeout(function() { var paypro = self._paypro; var address, amount; address = form.address.$modelValue; amount = parseInt((form.amount.$modelValue * unitToSat).toFixed(0)); outputs.push({ 'toAddress': address, 'amount': amount, 'message': comment }); var opts = { toAddress: address, amount: amount, outputs: outputs, message: comment, payProUrl: paypro ? paypro.url : null, lockedCurrentFeePerKb: self.lockedCurrentFeePerKb }; self.setOngoingProcess(gettextCatalog.getString('Creating transaction')); txService.createTx(opts, function(err, txp) { self.setOngoingProcess(); if (err) { return self.setSendError(err); } if (!fc.canSign() && !fc.isPrivKeyExternal()) { self.setOngoingProcess(); $log.info('No signing proposal: No private key'); self.resetForm(); txStatus.notify(txp, function() { return $scope.$emit('Local/TxProposalAction'); }); return; } else { $rootScope.$emit('Local/NeedsConfirmation', txp, function(accept) { if (accept) self.confirmTx(txp); else self.resetForm(); }); } }); }, 100); }; this.confirmTx = function(txp) { var self = this; txService.prepare(function(err) { if (err) { return self.setSendError(err); } self.setOngoingProcess(gettextCatalog.getString('Sending transaction')); txService.publishTx(txp, function(err, txpPublished) { if (err) { self.setOngoingProcess(); self.setSendError(err); } else { txService.signAndBroadcast(txpPublished, { reporterFn: self.setOngoingProcess.bind(self) }, function(err, txp) { self.resetForm(); if (err) { self.error = err.message ? err.message : gettext('The payment was created but could not be completed. Please try again from home screen'); $scope.$emit('Local/TxProposalAction'); $timeout(function() { $scope.$digest(); }, 1); } else { go.walletHome(); txStatus.notify(txp, function() { $scope.$emit('Local/TxProposalAction', txp.status == 'broadcasted'); }); } }); } }); }); }; this.setForm = function(to, amount, comment) { var form = $scope.sendForm; if (to) { form.address.$setViewValue(to); form.address.$isValid = true; form.address.$render(); this.lockAddress = true; } if (amount) { form.amount.$setViewValue("" + amount); form.amount.$isValid = true; form.amount.$render(); this.lockAmount = true; } if (comment) { form.comment.$setViewValue(comment); form.comment.$isValid = true; form.comment.$render(); } }; this.resetForm = function() { this.resetError(); if (this.countDown) $interval.cancel(this.countDown); this._paypro = null; this.lockedCurrentFeePerKb = null; this.lockAddress = false; this.lockAmount = false; this._amount = this._address = null; var form = $scope.sendForm; if (form && form.amount) { form.amount.$pristine = true; form.amount.$setViewValue(''); form.amount.$render(); form.comment.$setViewValue(''); form.comment.$render(); form.$setPristine(); if (form.address) { form.address.$pristine = true; form.address.$setViewValue(''); form.address.$render(); } } $timeout(function() { $rootScope.$digest(); }, 1); }; this.openPPModal = function(paypro) { $rootScope.modalOpened = true; var ModalInstanceCtrl = function($scope, $modalInstance) { var fc = profileService.focusedClient; var satToUnit = 1 / self.unitToSatoshi; $scope.paypro = paypro; $scope.alternative = self.alternativeAmount; $scope.alternativeIsoCode = self.alternativeIsoCode; $scope.isRateAvailable = self.isRateAvailable; $scope.unitTotal = (paypro.amount * satToUnit).toFixed(self.unitDecimals); $scope.unitName = self.unitName; $scope.color = fc.backgroundColor; $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; }; var modalInstance = $modal.open({ templateUrl: 'views/modals/paypro.html', windowClass: animationService.modalAnimated.slideUp, controller: ModalInstanceCtrl, }); var disableCloseModal = $rootScope.$on('closeModal', function() { modalInstance.dismiss('cancel'); }); modalInstance.result.finally(function() { $rootScope.modalOpened = false; disableCloseModal(); var m = angular.element(document.getElementsByClassName('reveal-modal')); m.addClass(animationService.modalAnimated.slideOutDown); }); }; this.setFromPayPro = function(uri, cb) { if (!cb) cb = function() {}; var fc = profileService.focusedClient; if (isChromeApp) { this.error = gettext('Payment Protocol not supported on Chrome App'); return cb(true); } var satToUnit = 1 / this.unitToSatoshi; var self = this; /// Get information of payment if using Payment Protocol self.setOngoingProcess(gettextCatalog.getString('Fetching Payment Information')); $log.debug('Fetch PayPro Request...', uri); $timeout(function() { fc.fetchPayPro({ payProUrl: uri, }, function(err, paypro) { self.setOngoingProcess(); if (err) { $log.warn('Could not fetch payment request:', err); self.resetForm(); var msg = err.toString(); if (msg.match('HTTP')) { msg = gettext('Could not fetch payment information'); } self.error = msg; $timeout(function() { $rootScope.$digest(); }, 1); return cb(true); } if (!paypro.verified) { self.resetForm(); $log.warn('Failed to verify payment protocol signatures'); self.error = gettext('Payment Protocol Invalid'); $timeout(function() { $rootScope.$digest(); }, 1); return cb(true); } self._paypro = paypro; self.setForm(paypro.toAddress, (paypro.amount * satToUnit).toFixed(self.unitDecimals), paypro.memo); _paymentTimeControl(paypro.expires); return cb(); }); }, 1); }; function _paymentTimeControl(expirationTime) { self.paymentExpired = false; setExpirationTime(); self.countDown = $interval(function() { setExpirationTime(); }, 1000); function setExpirationTime() { var now = Math.floor(Date.now() / 1000); if (now > expirationTime) { setExpiredValues(); return; } var totalSecs = expirationTime - now; var m = Math.floor(totalSecs / 60); var s = totalSecs % 60; self.remainingTimeStr = ('0' + m).slice(-2) + ":" + ('0' + s).slice(-2); }; function setExpiredValues() { self.paymentExpired = true; self.remainingTimeStr = null; self._paypro = null; self.error = gettext('Cannot sign: The payment request has expired'); if (self.countDown) $interval.cancel(self.countDown); }; }; this.setFromUri = function(uri) { var self = this; function sanitizeUri(uri) { // Fixes when a region uses comma to separate decimals var regex = /[\?\&]amount=(\d+([\,\.]\d+)?)/i; var match = regex.exec(uri); if (!match || match.length === 0) { return uri; } var value = match[0].replace(',', '.'); var newUri = uri.replace(regex, value); return newUri; }; var satToUnit = 1 / this.unitToSatoshi; // URI extensions for Payment Protocol with non-backwards-compatible request if ((/^bitcoin:\?r=[\w+]/).exec(uri)) { uri = decodeURIComponent(uri.replace('bitcoin:?r=', '')); this.setFromPayPro(uri, function(err) { if (err) { return err; } }); } else { uri = sanitizeUri(uri); if (!bitcore.URI.isValid(uri)) { return uri; } var parsed = new bitcore.URI(uri); var addr = parsed.address ? parsed.address.toString() : ''; var message = parsed.message; var amount = parsed.amount ? (parsed.amount.toFixed(0) * satToUnit).toFixed(this.unitDecimals) : 0; if (parsed.r) { this.setFromPayPro(parsed.r, function(err) { if (err && addr && amount) { self.setForm(addr, amount, message); return addr; } }); } else { this.setForm(addr, amount, message); return addr; } } }; this.onAddressChange = function(value) { this.resetError(); if (!value) return ''; if (this._paypro) return value; if (value.indexOf('bitcoin:') === 0) { return this.setFromUri(value); } else if (/^https?:\/\//.test(value)) { return this.setFromPayPro(value); } else { return value; } }; // History function strip(number) { return (parseFloat(number.toPrecision(12))); } this.getUnitName = function() { return this.unitName; }; this.getAlternativeIsoCode = function() { return this.alternativeIsoCode; }; this.openTxModal = function(tx) { $rootScope.$emit('Local/TxModal', tx); }; this.hasAction = function(actions, action) { return actions.hasOwnProperty('create'); }; this._doSendAll = function(amount) { this.setForm(null, amount, null); }; this.sendAll = function(totalBytesToSendMax, availableBalanceSat) { var self = this; var availableMaxBalance; var feeToSendMaxStr; this.error = null; this.setOngoingProcess(gettextCatalog.getString('Calculating fee')); feeService.getCurrentFeeValue(function(err, feePerKb) { self.setOngoingProcess(); if (err || lodash.isNull(feePerKb)) { self.error = gettext('Could not get fee value'); return; } var feeToSendMaxSat = parseInt(((totalBytesToSendMax * feePerKb) / 1000.).toFixed(0)); if (availableBalanceSat > feeToSendMaxSat) { self.lockedCurrentFeePerKb = feePerKb; availableMaxBalance = strip((availableBalanceSat - feeToSendMaxSat) * self.satToUnit); feeToSendMaxStr = profileService.formatAmount(feeToSendMaxSat) + ' ' + self.unitName; } else { self.error = gettext('Not enought funds for fee'); return; } var msg = gettextCatalog.getString("{{fee}} will be deducted for bitcoin networking fees", { fee: feeToSendMaxStr }); $scope.$apply(); confirmDialog.show(msg, function(confirmed) { if (confirmed) { self._doSendAll(availableMaxBalance); } else { self.resetForm(); } }); }); }; /* Start setup */ lodash.assign(self, vanillaScope); this.bindTouchDown(); if (profileService.focusedClient) { this.setAddress(); this.setSendFormInputs(); } });
apply timer in proposal details
src/js/controllers/walletHome.js
apply timer in proposal details
<ide><path>rc/js/controllers/walletHome.js <ide> }, 1000); <ide> <ide> function setExpirationTime() { <del> if (moment().isAfter(expirationTime * 1000)) { <add> var now = Math.floor(Date.now() / 1000); <add> if (now > expirationTime) { <ide> $scope.paymentExpired = true; <ide> if (self.countDown) $interval.cancel(self.countDown); <add> return; <ide> } <del> $scope.expires = moment(expirationTime * 1000).fromNow(); <add> var totalSecs = expirationTime - now; <add> var m = Math.floor(totalSecs / 60); <add> var s = totalSecs % 60; <add> $scope.expires = ('0' + m).slice(-2) + ":" + ('0' + s).slice(-2); <ide> }; <ide> }; <ide>
JavaScript
mit
8de4e0c4ca9f7762d7ca8daf123c877654a85645
0
spiralnebula/table,spiralnebula/table
(function ( window, module ) { if ( window.define && window.define.amd ) { define(module) } else { var current_scripts, this_script, module_name current_scripts = document.getElementsByTagName("script") this_script = current_scripts[current_scripts.length-1] module_name = this_script.getAttribute("data-module-name") || "url_parser" window[module_name] = module } })( window, { define : { allow : "*", require : [ "morph" ], }, get_paramaters_of_url : function ( url ) { var self, paramater_string, object_of_paramaters self = this object_of_paramaters = {} paramater_string = url.split("?") if ( paramater_string.length > 1 ) { object_of_paramaters = this.library.morph.index_loop({ subject : paramater_string[1].split("&"), into : {}, else_do : function ( loop ) { var split_paramater_string, paramater_key, paramater_value, paramater_value_is_uri_encoded split_paramater_string = loop.indexed.split("=") paramater_key = split_paramater_string[0] paramater_value = split_paramater_string[1] paramater_value_is_uri_encoded = self.is_string_a_uri_component({ string : paramater_value }) if ( paramater_value_is_uri_encoded ) { var paramater_value_is_json paramater_value = window.decodeURIComponent( paramater_value ) paramater_value_is_json = self.is_string_json({ string : paramater_value }) if ( paramater_value_is_json ) { paramater_value = JSON.parse( paramater_value ) } } loop.into[paramater_key] = paramater_value return loop.into } }) } return { paramaters : object_of_paramaters } }, is_string_a_uri_component : function ( given ) { var symbol_to_encoding, number_of_matched_symbols symbol_to_encoding = { "{" : "%7B", ":" : "%3A", "/" : "%2F", "}" : "%7D", ";" : "%3B", "space" : "%20", } number_of_matched_symbols = this.library.morph.index_loop({ subject : this.library.morph.get_the_values_of_an_object( symbol_to_encoding ), into : 0, else_do : function ( loop ) { if ( given.string.match( loop.indexed ) ) { return loop.into + 1 } return loop.into } }) return ( number_of_matched_symbols > 0 ) }, is_string_json : function ( given ) { try { JSON.parse( given.string ) } catch ( exception ) { return false } return true } } )
library/url_parser.js
(function ( window, module ) { if ( window.define && window.define.amd ) { define(module) } else { var current_scripts, this_script, module_name current_scripts = document.getElementsByTagName("script") this_script = current_scripts[current_scripts.length-1] module_name = this_script.getAttribute("data-module-name") || "url_parser" window[module_name] = module } })( window, { define : { allow : "*", require : [ "morph" ], }, get_paramaters_of_url : function ( url ) { var self, paramater_string, object_of_paramaters self = this object_of_paramaters = {} paramater_string = url.split("?") if ( paramater_string.length > 1 ) { object_of_paramaters = this.library.morph.index_loop({ subject : paramater_string[1].split("&"), into : {}, else_do : function ( loop ) { var split_paramater_string, paramater_key, paramater_value, paramater_value_is_uri_encoded split_paramater_string = loop.indexed.split("=") paramater_key = split_paramater_string[0] paramater_value = split_paramater_string[1] paramater_value_is_uri_encoded = self.is_string_a_uri_component({ string : paramater_value }) if ( paramater_value_is_uri_encoded ) { var paramater_value_is_json paramater_value = window.decodeURIComponent( paramater_value ) paramater_value_is_json = self.is_string_json({ string : paramater_value }) if ( paramater_value_is_json ) { paramater_value = JSON.parse( paramater_value ) } } loop.into[paramater_key] = paramater_value return loop.into } }) } return { paramater : object_of_paramaters } }, is_string_a_uri_component : function ( given ) { var symbol_to_encoding, number_of_matched_symbols symbol_to_encoding = { "{" : "%7B", ":" : "%3A", "/" : "%2F", "}" : "%7D", ";" : "%3B", "space" : "%20", } number_of_matched_symbols = this.library.morph.index_loop({ subject : this.library.morph.get_the_values_of_an_object( symbol_to_encoding ), into : 0, else_do : function ( loop ) { if ( given.string.match( loop.indexed ) ) { return loop.into + 1 } return loop.into } }) return ( number_of_matched_symbols > 0 ) }, is_string_json : function ( given ) { try { JSON.parse( given.string ) } catch ( exception ) { return false } return true } } )
Url parser has paramater change
library/url_parser.js
Url parser has paramater change
<ide><path>ibrary/url_parser.js <ide> } <ide> <ide> return { <del> paramater : object_of_paramaters <add> paramaters : object_of_paramaters <ide> } <ide> }, <ide>
JavaScript
mit
7933cdb6fb5d1dd577ecd065a3bbd77eb7108718
0
StreetSupport/streetsupport-admin,StreetSupport/streetsupport-admin
var Spinner = require('spin.js') var redirect = function (url) { window.location = url } var dataLoaded = function () { var dynamicElements = document.getElementsByClassName('awaiting-data') Array.from(dynamicElements).forEach(element => { element.className = element.className.replace(/(?:^|\s)awaiting-data(?!\S)/g, '') }) } var loaderAnim var getLoader = function () { if (loaderAnim === undefined) { loaderAnim = new Spinner() } return loaderAnim } var loading = function () { getLoader().spin(document.getElementById('spin')) } var loaded = function () { getLoader().stop() } var trackEvent = function (src, action, description) { ga('send', 'event', src, action, description) } module.exports = { redirect: redirect, loading: loading, loaded: loaded, trackEvent: trackEvent, dataLoaded: dataLoaded // deprecated }
src/js/browser.js
var _ = require('lodash') var Spinner = require('spin.js') var redirect = function (url) { window.location = url } var dataLoaded = function () { var dynamicElements = document.getElementsByClassName('awaiting-data') _.forEach(dynamicElements, function (element) { element.className = element.className.replace(/(?:^|\s)awaiting-data(?!\S)/g, '') }) } var loaderAnim var getLoader = function () { if (loaderAnim === undefined) { loaderAnim = new Spinner() } return loaderAnim } var loading = function () { getLoader().spin(document.getElementById('spin')) } var loaded = function () { getLoader().stop() } var trackEvent = function (src, action, description) { ga('send', 'event', src, action, description) } module.exports = { redirect: redirect, loading: loading, loaded: loaded, trackEvent: trackEvent, dataLoaded: dataLoaded // deprecated }
fix removal of 'awaiting-data' class
src/js/browser.js
fix removal of 'awaiting-data' class
<ide><path>rc/js/browser.js <del>var _ = require('lodash') <ide> var Spinner = require('spin.js') <ide> <ide> var redirect = function (url) { <ide> <ide> var dataLoaded = function () { <ide> var dynamicElements = document.getElementsByClassName('awaiting-data') <del> _.forEach(dynamicElements, function (element) { <add> Array.from(dynamicElements).forEach(element => { <ide> element.className = element.className.replace(/(?:^|\s)awaiting-data(?!\S)/g, '') <ide> }) <ide> }
JavaScript
mit
6c5ed7c87b6b78c0a0966d0ddbb2aed392f66dda
0
magicmonkey/lifxjs,ryanj/lifxjs,wiegraff13/lifxjs,WigWagCo/lifxjs,ppelleti/lifxjs,ppelleti/lifxjs,magicmonkey/lifxjs,sinnottj/lifxjs,ninjablocks/lifxjs,ryanj/lifxjs,sinnottj/lifxjs,WigWagCo/lifxjs,wiegraff13/lifxjs
var dgram = require('dgram'); var net = require('net'); var util = require('util'); var UDPClient = dgram.createSocket("udp4"); var port = 56700; var found = false; module.exports = { discover: function(cb) { UDPClient.on("error", function (err) { console.log("UDP error " + err); }); UDPClient.on("message", function (msg, rinfo) { console.log(" U- " + msg.toString("hex")); if (msg.length > 4 && msg[3] == 0x54) { if (!found) { found = true; cb(null, {address:rinfo.address, port:rinfo.port, family:rinfo.family} ); } } }); UDPClient.bind(port, function() { UDPClient.setBroadcast(true); var intervalID; // Now send the discovery packets intervalID = setInterval(function() { if (found) { clearInterval(intervalID); } else { var message = new Buffer([0x24, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00]); console.log(" U+ " + message.toString("hex")); UDPClient.send(message, 0, message.length, port, "255.255.255.255", function(err, bytes) { if (err) { cb(err); } }); } }, 300); }); }, init: function(addr, cb) { var b = new bulb(addr); cb(null, b); }, discoverAndInit: function(cb) { module.exports.discover(function(err, addr) { if (err) { cb(err); } else { module.exports.init(addr, cb); } }); }, }; function bulb(addr) { this.address = null; this.port = null; var client = null; if (typeof addr == 'object' && typeof addr.address == 'string' && typeof addr.port == 'number') { this.address = addr.address; this.port = addr.port; } function connect() { client = net.connect(56700, '10.1.0.80', function() { //'connect' listener //console.log('client connected'); }); } connect(); client.on('data', function(data) { console.log(" T- " + data.toString("hex")); // // 5800005400000000d073d500239d0000d073d500239d000000000000000000006b0000009ed400008396f00a000000004b6576696e2773207369646500000000000000000000000000000000000000000000000000000000 // Bulb status // 5800005400000000d073d5001ba90000d073d500239d000000000000000000006b0000009ed400008396f00a000000004c6f726e612773207369646500000000000000000000000000000000000000000000000000000000 // 5800005400000000d073d500239d0000d073d500239d000000000000000000006b00000015ccffff8f02ac0d0000ffff4b6576696e2773207369646500000000000000000000000000000000000000000000000000000000 // 2600005400000000d073d5001ba90000d073d500239d00000000000000000000160000000000 // Lights off // 2600005400000000d073d500239d0000d073d500239d0000000000000000000016000000ffff // Lights on switch (data[32]) { case 0x6b: console.log(" * Found a bulb: " + data.slice(48).toString("ascii")); break; case 0x16: if (data[37] == 0xff) { console.log(" * Light is on"); } else { console.log(" * Light is off"); } break; } }); client.on('end', function() { console.log('TCP client disconnected'); //connect(); }); var self = this; var standardPrefix = new Buffer([0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x73, 0xd5, 0x00, 0x23, 0x9d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); this.sendRawPacket = function(message) { var bLen = new Buffer([message.length + standardPrefix.length + 1]); var sendBuf = Buffer.concat([ bLen, standardPrefix, message ]); console.log(" T+ " + sendBuf.toString("hex")); client.write(sendBuf); }; this.lightsOn = function() { self.sendRawPacket(new Buffer([0x15, 0x00, 0x00, 0x00, 0x01, 0x00])); }; this.lightsOff = function() { self.sendRawPacket(new Buffer([0x15, 0x00, 0x00, 0x00, 0x00, 0x00])); }; this.red = function() { self.sendRawPacket(new Buffer([0x66, 0x00, 0x00, 0x00, 0x00, 0x9e, 0xd4, 0xff, 0xff, 0x8f, 0x02, 0xac, 0x0d, 0x13, 0x05, 0x00, 0x00])); }; this.purple = function() { self.sendRawPacket(new Buffer([0x66, 0x00, 0x00, 0x00, 0x00, 0x15, 0xcc, 0xff, 0xff, 0x8f, 0x02, 0xac, 0x0d, 0x13, 0x05, 0x00, 0x00])); }; this.brightWhite = function() { self.sendRawPacket(new Buffer([0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x83, 0x96, 0xf0, 0x0a, 0x90, 0x01, 0x00, 0x00])); }; this.getInfo = function() { self.sendRawPacket(new Buffer([0x65, 0x00, 0x00, 0x00])); }; this.close = function() { UDPClient.close(); client.end(); }; }
lifx.js
var dgram = require('dgram'); var net = require('net'); var util = require('util'); var UDPClient = dgram.createSocket("udp4"); var port = 56700; var found = false; module.exports = { discover: function(cb) { UDPClient.on("error", function (err) { console.log("UDP error " + err); }); UDPClient.on("message", function (msg, rinfo) { if (msg.length > 4 && msg[3] == 0x54) { if (!found) { found = true; cb(null, {address:rinfo.address, port:rinfo.port, family:rinfo.family} ); } } }); UDPClient.bind(port, function() { UDPClient.setBroadcast(true); var intervalID; // Now send the discovery packets intervalID = setInterval(function() { if (found) { clearInterval(intervalID); } else { var message = new Buffer([0x24, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00]); UDPClient.send(message, 0, message.length, port, "255.255.255.255", function(err, bytes) { if (err) { cb(err); } }); } }, 300); }); }, init: function(addr, cb) { var b = new bulb(addr); cb(null, b); }, discoverAndInit: function(cb) { module.exports.discover(function(err, addr) { if (err) { cb(err); } else { module.exports.init(addr, cb); } }); }, }; function bulb(addr) { this.address = null; this.port = null; var client = null; if (typeof addr == 'object' && typeof addr.address == 'string' && typeof addr.port == 'number') { this.address = addr.address; this.port = addr.port; } client = net.connect(56700, '10.1.0.80', function() { //'connect' listener //console.log('client connected'); }); client.on('data', function(data) { //console.log(" - " + "TCP got data (" + data.length + " bytes)"); console.log(" - " + data.toString("hex")); //console.log(" - " + data.toString("ascii")); // // 5800005400000000d073d500239d0000d073d500239d000000000000000000006b0000009ed400008396f00a000000004b6576696e2773207369646500000000000000000000000000000000000000000000000000000000 // Bulb status // 5800005400000000d073d5001ba90000d073d500239d000000000000000000006b0000009ed400008396f00a000000004c6f726e612773207369646500000000000000000000000000000000000000000000000000000000 // 5800005400000000d073d500239d0000d073d500239d000000000000000000006b00000015ccffff8f02ac0d0000ffff4b6576696e2773207369646500000000000000000000000000000000000000000000000000000000 // 2600005400000000d073d5001ba90000d073d500239d00000000000000000000160000000000 // Lights off // 2600005400000000d073d500239d0000d073d500239d0000000000000000000016000000ffff // Lights on switch (data[32]) { case 0x6b: console.log(" * Found a bulb: " + data.slice(48).toString("ascii")); break; case 0x16: if (data[37] == 0xff) { console.log(" * Light is on"); } else { console.log(" * Light is off"); } break; } }); client.on('end', function() { console.log('TCP client disconnected'); }); var self = this; var standardPrefix = new Buffer([0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x73, 0xd5, 0x00, 0x23, 0x9d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); this.sendRawPacket = function(message) { var bLen = new Buffer([message.length + standardPrefix.length + 1]); var sendBuf = Buffer.concat([ bLen, standardPrefix, message ]); console.log(" + " + sendBuf.toString("hex")); client.write(sendBuf); }; this.lightsOn = function() { self.sendRawPacket(new Buffer([0x15, 0x00, 0x00, 0x00, 0x01, 0x00])); }; this.lightsOff = function() { self.sendRawPacket(new Buffer([0x15, 0x00, 0x00, 0x00, 0x00, 0x00])); }; this.red = function() { self.sendRawPacket(new Buffer([0x66, 0x00, 0x00, 0x00, 0x00, 0x9e, 0xd4, 0xff, 0xff, 0x8f, 0x02, 0xac, 0x0d, 0x13, 0x05, 0x00, 0x00])); }; this.purple = function() { self.sendRawPacket(new Buffer([0x66, 0x00, 0x00, 0x00, 0x00, 0x15, 0xcc, 0xff, 0xff, 0x8f, 0x02, 0xac, 0x0d, 0x13, 0x05, 0x00, 0x00])); }; this.brightWhite = function() { self.sendRawPacket(new Buffer([0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x83, 0x96, 0xf0, 0x0a, 0x90, 0x01, 0x00, 0x00])); }; this.getInfo = function() { self.sendRawPacket(new Buffer([0x65, 0x00, 0x00, 0x00])); }; this.close = function() { UDPClient.close(); client.end(); }; }
Dumping the network bytes to the screen in an easy-to-read format to aid figuring out what they are
lifx.js
Dumping the network bytes to the screen in an easy-to-read format to aid figuring out what they are
<ide><path>ifx.js <ide> }); <ide> <ide> UDPClient.on("message", function (msg, rinfo) { <add> <add> console.log(" U- " + msg.toString("hex")); <ide> if (msg.length > 4 && msg[3] == 0x54) { <ide> if (!found) { <ide> found = true; <ide> clearInterval(intervalID); <ide> } else { <ide> var message = new Buffer([0x24, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00]); <add> console.log(" U+ " + message.toString("hex")); <ide> UDPClient.send(message, 0, message.length, port, "255.255.255.255", function(err, bytes) { <ide> if (err) { <ide> cb(err); <ide> this.port = addr.port; <ide> } <ide> <del> client = net.connect(56700, '10.1.0.80', function() { //'connect' listener <del> //console.log('client connected'); <del> }); <add> function connect() { <add> client = net.connect(56700, '10.1.0.80', function() { //'connect' listener <add> //console.log('client connected'); <add> }); <add> } <add> <add> connect(); <add> <ide> client.on('data', function(data) { <del> //console.log(" - " + "TCP got data (" + data.length + " bytes)"); <del> console.log(" - " + data.toString("hex")); <del> //console.log(" - " + data.toString("ascii")); <add> console.log(" T- " + data.toString("hex")); <ide> // <ide> // 5800005400000000d073d500239d0000d073d500239d000000000000000000006b0000009ed400008396f00a000000004b6576696e2773207369646500000000000000000000000000000000000000000000000000000000 // Bulb status <ide> // 5800005400000000d073d5001ba90000d073d500239d000000000000000000006b0000009ed400008396f00a000000004c6f726e612773207369646500000000000000000000000000000000000000000000000000000000 <ide> }); <ide> client.on('end', function() { <ide> console.log('TCP client disconnected'); <add> //connect(); <ide> }); <ide> <ide> var self = this; <ide> standardPrefix, <ide> message <ide> ]); <del> console.log(" + " + sendBuf.toString("hex")); <add> console.log(" T+ " + sendBuf.toString("hex")); <ide> client.write(sendBuf); <ide> }; <ide>
JavaScript
apache-2.0
15a9553fbe4278fd9cea37e8c3ced67eff121f1d
0
jessenie-intel/websensor-videocapture,jessenie-intel/websensor-videocapture
/* * Websensor video stabilization project * https://github.com/jessenie-intel/websensor-video * * Copyright (c) 2017 Jesse Nieminen * * 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. * */ 'use strict'; var constraints = {audio: true,video: { width: { min: 640, ideal: 640, max: 640 }, height: { min: 480, ideal: 480, max: 480 }}}; var mediaRecorder = null; var chunks = []; var videoData = null; var interval = null; var accel_sensor = null; var orientation_sensor = null; var gyroscope = null; var sensorfreq = 60; var selectedSensor = null; //var roll = null; //var pitch = null; //var yaw = null; var accel = {"x": null, "y": null, "z": null}; var accel_last = {"x": null, "y": null, "z": null}; var accelNoG = {"x": null, "y": null, "z": null}; var accel_filtered = null; var aVel = {"x": null, "y": null, "z": null}; var ori = {"roll": null, "pitch": null, "yaw": null, "time": null}; var ori_filtered = null; var oriInitial = {"roll": null, "pitch": null, "yaw": null, "time": null}; var initialoriobtained = false; var orientationData = []; //array to store all the orientation data var aVelData = []; var frameData = {"data": null, "time": null, "ori": null, "aVel": null, "accel": null, "accelnog": null}; var dataArray = []; //array to store all the combined data var dataArray2 = []; //array to store all the combined data var velocity = {"x": 0, "y": 0, "z": 0}; var alpha = 0; var beta = 0; var gamma = 0; var accl = null; var timeInitial = null; var time = null; var timestamp = null; var timestamps = []; var timeAtStart = null; var nFrame = 0; //frame number with which we can combine timestamp and frame data var prevFrame = null; //previous frame var delay = 5; var sensorframeTimeDiff = 0; //time difference between sensor and frame data in ms - this is how much the timestamps differ //canvas var canvas = document.getElementById('myCanvas'); var canvas2 = document.getElementById('myCanvas2'); //CSS.elementSources.set("pfcanvas", canvas); var ctx = canvas.getContext('2d'); var ctx2 = canvas2.getContext('2d'); //var ctx = document.getCSSCanvasContext("2d", "name_of_canvas", 100, 100); - polyfill from https://css-tricks.com/media-fragments-uri-spatial-dimension/ //video element var videoElement = document.querySelector('video'); videoElement.controls = false; var videoURLBase = null; var duration = null; var ref = null; var extraFrames = 0; var x = 0; var y = 0; //position for the square var angle = 0; var cameraPath = []; //array of canvas coordinates describing the camera path var cameraCoord = {"x": null, "y": null, "time": null}; //Sliders var slider_delay = document.getElementById("slider_delay"); var slider_delay_div = document.getElementById("slider_delay_amount"); slider_delay.onchange = () => { delay = slider_delay.value; slider_delay_div.innerHTML = delay; console.log("Delay:", delay); }; class HighPassFilterData { //https://w3c.github.io/motion-sensors/#pass-filters constructor(reading, cutoffFrequency) { Object.assign(this, { x: reading.x, y: reading.y, z: reading.z }); this.cutoff = cutoffFrequency; this.timestamp = reading.timestamp; } update(reading) { let dt = reading.timestamp - this.timestamp / 1000; this.timestamp = reading.timestamp; for (let i of ["x", "y", "z"]) { let alpha = this.cutoff / (this.cutoff + dt); this[i] = this[i] + alpha * (reading[i] - this[i]); } } }; class LowPassFilterData { //https://w3c.github.io/motion-sensors/#pass-filters constructor(reading, bias) { Object.assign(this, { x: reading.x, y: reading.y, z: reading.z }); this.bias = bias; } update(reading) { this.x = this.x * this.bias + reading.x * (1 - this.bias); this.y = this.y * this.bias + reading.y * (1 - this.bias); this.z = this.z * this.bias + reading.z * (1 - this.bias); } }; class LowPassFilterOrientation { constructor(reading, bias) { Object.assign(this, { roll: reading.roll, pitch: reading.pitch, yaw: reading.yaw }); this.bias = bias; } update(reading) { this.roll = this.roll * this.bias + reading.roll * (1 - this.bias); this.pitch = this.pitch * this.bias + reading.pitch * (1 - this.bias); this.yaw = this.yaw * this.bias + reading.yaw * (1 - this.bias); } }; class KalmanFilter { constructor() { this.Q_angle = 0.01; this.Q_gyro = 0.0003; this.R_angle = 0.01; this.reset(); } reset() { this.angle = 0.0; this.bias = 0; this.P00 = 0; this.P01 = 0; this.P10 = 0; this.P11 = 0; } filter(accAngle, gyroRate, dt) { this.angle += dt * (gyroRate - this.bias); this.P00 += -dt * (this.P10 + this.P01) + this.Q_angle * dt; this.P01 += -dt * this.P11; this.P10 += -dt * this.P11; this.P11 += + this.Q_gyro * dt; let axis = accAngle - this.angle; let S = this.P00 + this.R_angle; let K0 = this.P00 / S; let K1 = this.P10 / S; this.angle += K0 * axis; this.bias += K1 * axis; this.P00 -= K0 * this.P00; this.P01 -= K0 * this.P01; this.P10 -= K1 * this.P00; this.P11 -= K1 * this.P01; return this.angle; } }; class OriSensor { constructor() { const sensor = new RelativeOrientationSensor({ frequency: sensorfreq }); const mat4 = new Float32Array(16); const euler = new Float32Array(3); sensor.onreading = () => { sensor.populateMatrix(mat4); toEulerianAngle(sensor.quaternion, euler); //From quaternion to Eulerian angles this.roll = euler[0]; this.pitch = euler[1]; this.yaw = euler[2]; this.timestamp = sensor.timestamp; if (this.onreading) this.onreading(); }; sensor.onactivate = () => { if (this.onactivate) this.onactivate(); }; const start = () => sensor.start(); Object.assign(this, { start }); } } function magnitude(vector) //Calculate the magnitude of a vector { return Math.sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z); } function update_debug() { document.getElementById("ori").textContent = `Orientation: ${ori.roll} ${ori.pitch} ${ori.yaw}`; document.getElementById("accel").textContent = `Acceleration: ${accel.x} ${accel.y} ${accel.z}, M ${magnitude(accel).toFixed(3)}`; document.getElementById("accelnog").textContent = `Linear acceleration (no gravity): ${accelNoG.x} ${accelNoG.y} ${accelNoG.z}, M ${magnitude(accelNoG).toFixed(3)}`; document.getElementById("rrate").textContent = `Rotation rate: ${aVel.x} ${aVel.y} ${aVel.z}, M ${magnitude(aVel).toFixed(3)} and alpha ${alpha} beta ${beta} gamma ${gamma}`; document.getElementById("selectedSensor").textContent = `${selectedSensor}`; } function selectSensor() { selectedSensor = document.getElementById("selectSensor").value; console.log(selectedSensor, "selected"); } function buildCameraPath(dataArray) { //Build the shaky camera path from the sensor measurements (convert to canvas coordinates) using projection for (let i=0; i<dataArray.length; i++) { let ori = dataArray[i].ori; let oriDiff = null; if(ori !== undefined) { oriDiff = {"roll": ori.roll-oriInitial.roll, "pitch": ori.pitch-oriInitial.pitch, "yaw": ori.yaw-oriInitial.yaw}; console.log(canvas.width, canvas.height); cameraCoord.x = (1/2) * canvas.width + (1/2)*Math.sin(oriDiff.yaw) * canvas.width; cameraCoord.y = (1/2) * canvas.height + (1/2)*Math.sin(oriDiff.roll) * canvas.height; var b = new Object; //need to push by value Object.assign(b, cameraCoord); cameraPath.push(b); } } } //WINDOWS 10 HAS DIFFERENT CONVENTION: Yaw z, pitch x, roll y function toEulerianAngle(quat, out) { const ysqr = quat[1] ** 2; // Roll (x-axis rotation). const t0 = 2 * (quat[3] * quat[0] + quat[1] * quat[2]); const t1 = 1 - 2 * (ysqr + quat[0] ** 2); out[0] = Math.atan2(t0, t1); // Pitch (y-axis rotation). let t2 = 2 * (quat[3] * quat[1] - quat[2] * quat[0]); t2 = t2 > 1 ? 1 : t2; t2 = t2 < -1 ? -1 : t2; out[1] = Math.asin(t2); // Yaw (z-axis rotation). const t3 = 2 * (quat[3] * quat[2] + quat[0] * quat[1]); const t4 = 1 - 2 * (ysqr + quat[2] ** 2); out[2] = Math.atan2(t3, t4); return out; } function errorCallback(error){ console.log("error: ", error); } function startDemo () { navigator.getUserMedia(constraints, startRecording, errorCallback); } function startSensors() { try { timeInitial = Date.now(); const bias = 0.98; //Initialize sensors accel_sensor = new Accelerometer({frequency: sensorfreq}); // Remove drift with a high pass filter. const accel_filtered = new HighPassFilterData(accel_sensor, 0.8); //console.log(accel_filtered); //null, null, null accel_sensor.onreading = () => { accel = {"x": accel_sensor.x, "y": accel_sensor.y, "z": accel_sensor.z, "time": accel_sensor.timestamp}; //accel = {"x": (1/2)*(accel_last.x + accel_sensor.x), "y": (1/2)*(accel_last.y + accel_sensor.y), "z": (1/2)*(accel_last.z + accel_sensor.z)}; //accel_last = accel; //for smoothing the data //accel_filtered.update(accel_sensor); //accel = accel_filtered; //accelNoG = {x:accel.x - gravity.x, y:accel.y - gravity.y, z:accel.z - gravity.z}; }; accel_sensor.onactivate = () => { }; accel_sensor.start(); gyroscope = new Gyroscope({frequency: sensorfreq}); //accl = new Accelerometer({frequency: sensorfreq}); const gyro_filtered = new LowPassFilterData(gyroscope, 0.1); gyroscope.onreading = () => { //console.log(Date.now()); gyro_filtered.update(gyroscope); //aVel = {x:gyro_data.x, y:gyro_data.y, z:gyro_data.z}; //aVel = {x:gyroscope.x, y:gyroscope.y, z:gyroscope.z, alpha: alpha}; //Determine orientation with accelerometer and gyroscope. Below from https://w3c.github.io/motion-sensors/#complementary-filters let dt = timestamp ? (gyroscope.timestamp - timestamp) / 1000 : 0; timestamp = gyroscope.timestamp; // Treat the acceleration vector as an orientation vector by normalizing it. // Keep in mind that the if the device is flipped, the vector will just be // pointing in the other direction, so we have no way to know from the // accelerometer data which way the device is oriented. const norm = Math.sqrt(accel_sensor.x ** 2 + accel_sensor.y ** 2 + accel_sensor.z ** 2); // As we only can cover half (PI rad) of the full spectrum (2*PI rad) we multiply // the unit vector with values from [-1, 1] with PI/2, covering [-PI/2, PI/2]. const scale = Math.PI / 2; const zeroBias = 0.02; //console.log(accel_sensor.timestamp, gyroscope.timestamp, accel_sensor.timestamp - gyroscope.timestamp); //alpha = (1 - zeroBias) * (alpha + gyroscope.z * dt); alpha = alpha + gyro_filtered.z * dt; beta = bias * (beta + gyroscope.x * dt) + (1.0 - bias) * (accel_sensor.x * scale / norm); gamma = bias * (gamma + gyro_filtered.y * dt) + (1.0 - bias) * (accel_sensor.y * -scale / norm); //gamma = (gamma + gyro_filtered.y * dt); aVel = {x:gyroscope.x, y:gyroscope.y, z:gyroscope.z, alpha: alpha, beta: beta, gamma: gamma}; //console.log(Date.now()); }; gyroscope.onactivate = () => { }; gyroscope.start(); orientation_sensor = new OriSensor({frequency: sensorfreq}); //Low-pass filter the orientation data. Cannot initialize normally because undefined const ori_filtered = new LowPassFilterOrientation({"roll":null, "pitch":null, "yaw":null}, 0.9); //console.log(ori_filtered); orientation_sensor.onreading = () => { let roll = orientation_sensor.roll; let pitch = orientation_sensor.pitch; let yaw = orientation_sensor.yaw; //time = orientation_sensor.timestamp; time = Date.now(); if(!initialoriobtained) //obtain initial orientation { oriInitial = {"roll": orientation_sensor.roll, "pitch": orientation_sensor.pitch, "yaw": orientation_sensor.yaw, "time": Date.now()}; //timeAtStart = orientation_sensor.timestamp; timeAtStart = Date.now(); initialoriobtained = true; sensorframeTimeDiff = timeAtStart - timeInitial; console.log(sensorframeTimeDiff); } ori = {"roll": orientation_sensor.roll, "pitch": orientation_sensor.pitch, "yaw": orientation_sensor.yaw, "time": orientation_sensor.timestamp}; //console.log(orientation_sensor); ori_filtered.update(ori); //console.log(ori_filtered); //ori = ori_filtered; //ori.roll = ori_filtered.roll; //ori.pitch = ori_filtered.pitch; //ori.yaw = ori_filtered.yaw; //ori.time = orientation_sensor.timestamp; //console.log(ori_filtered); }; orientation_sensor.onactivate = () => { }; orientation_sensor.start(); } catch(err) { console.log(err.message); console.log("Your browser doesn't seem to support generic sensors. If you are running Chrome, please enable it in about:flags."); //this.innerHTML = "Your browser doesn't seem to support generic sensors. If you are running Chrome, please enable it in about:flags"; } } document.addEventListener('DOMContentLoaded', function() { startSensors(); //start sensors instantly to avoid gyro drift }, false); function startRecording(stream) { interval=window.setInterval(update_debug,100); //var options = {mimeType: 'video/webm;codecs=vp9'}; //mediaRecorder = new MediaRecorder(stream, options); mediaRecorder = new MediaRecorder(stream); mediaRecorder.start(10); var url = window.URL; videoElement.src = url ? url.createObjectURL(stream) : stream; //videoElement.play(); mediaRecorder.ondataavailable = function(e) { //console.log("Data available", e); //console.log(time); timestamps.push(time); frameData.time = time; chunks.push(e.data); frameData.data = e.data; orientationData.push(ori); aVelData.push(aVel); frameData.ori = ori; frameData.aVel = aVel; frameData.accel = accel; //frameData.accelnog = accelNoG; //dataArray.push(frameData); var b = new Object; //need to push by value Object.assign(b, frameData); dataArray.push(b); frameData = {"data": null, "time": null, "ori": null, "aVel": null, "accel": null, "accelnog": null}; }; mediaRecorder.onerror = function(e){ console.log('Error: ', e); }; mediaRecorder.onstart = function(){ console.log("Recording started", mediaRecorder.state); }; mediaRecorder.onstop = function(){ var blob = new Blob(chunks, {type: "video/webm"}); chunks = []; videoURLBase = window.URL.createObjectURL(blob); videoElement.src = videoURLBase + "#xywh=pixel:0,0,320,240"; videoElement.load(); //resize canvas videoElement.addEventListener('loadedmetadata', function() { console.log("Loaded metadata"); canvas.width = videoElement.videoWidth; canvas.height = videoElement.videoHeight; //canvas.style.display="none"; canvas2.width = videoElement.videoWidth; canvas2.height = videoElement.videoHeight; ctx.save(); //save canvas state for later restoration //duration = videoElement.duration; }); /* videoElement.addEventListener('durationchange', function() { duration = videoElement.duration; }); */ duration = (dataArray[dataArray.length-1].time - dataArray[0].time)/1000; //duration in s //videoElement.play(); videoElement.addEventListener('play', function() { videoElement.play(); nFrame = 0; let durationPerFrame = duration*1000/dataArray.length; //frame duration in ms //delay = Math.floor(sensorframeTimeDiff/durationPerFrame); //console.log("Delay", delay); buildCameraPath(dataArray); //build camera path readFrameData(blob, orientationData, cameraPath); //reads the video into dataArray2 }, false); /*//Read blob data so we can stabilize the video var reader = new FileReader(); reader.onload = function(event){ let text = reader.result; console.log(text); }; reader.readAsText(blob, "video/webm");*/ //console.log(orientationData); //console.log(timestamps); //console.log(dataArray); /* var blobUrl = URL.createObjectURL(blob); var x = new XMLHttpRequest(); // set x.responseType = 'blob' if you want to get a Blob object: // x.responseType = 'blob'; x.onload = function() { alert(x.responseText); }; console.log(x.open('get', blobUrl));*/ //readFrameData(blob, orientationData); //reads the video into dataArray2 //console.log(dataArray); /*videoElement.onended = function() { alert("The video has ended"); cancelAnimationFrame(ref); };*/ //ctx.clearRect(0, 0, canvas.width, canvas.height); //stabilize(dataArray2); //now we can operate on it }; mediaRecorder.onpause = function(){ } mediaRecorder.onresume = function(){ } mediaRecorder.onwarning = function(e){ }; } function stopRecording(){ mediaRecorder.stop(); //Now stabilize videoElement.controls = true; } //Idea: copy video to canvas, operate on the video, and then use the canvas with the stabilized video as source for the video element function readFrameData(blob, oriArray, cameraPath) { //Read video data from blob to object form with pixel data we can operate on //TODO: sensor readings and frame data in desync - frame data too late/sensor data ahead //console.log("frame"); nFrame = videoElement.webkitDecodedFrameCount - extraFrames; //console.log(prevFrame, nFrame); //let x = 0; //let y = 0; let dx = 0; let dy = 0; //let delay = -10; var timeFromStart = null; var cameraPos = null; let frameDataL = (nFrame-delay >=0 && nFrame-delay <= dataArray.length) ? dataArray[nFrame - delay] : dataArray[nFrame]; if(nFrame === 0) { //console.log(dataArray); //timeAtStart = frameDataL.ori.time; } else if(nFrame !== 0 && nFrame !== prevFrame && frameDataL !== undefined && cameraPath !== undefined) //all subsequent frames { //console.log(nFrame); //console.log(dataL); timeFromStart = frameDataL.time - timeAtStart; //time since recording start (in ms) //console.log(timeFromStart); //console.log(frameDataL); //console.log(nFrame); //console.log(videoElement.webkitDecodedFrameCount); //only works in webkit browsers //console.log(timestamps[nFrame] - timestamps[0], videoElement.currentTime); //while(!videoElement.ended) //{ //if(cameraPath !== undefined) //{ //} let oriDiff = null; let deltaT = frameDataL.time - dataArray[nFrame-1].time; //console.log(deltaT); let acceleration_filtered = null; //if(magnitude(frameDataL.accel) > 0.5) //filter out small values in acceleration (noise) //{ acceleration_filtered = frameDataL.accel; /*} else { acceleration_filtered = {"x":0, "y":0, "z": 0}; }*/ velocity = {"x": velocity.x + acceleration_filtered.x * deltaT/1000, "y": velocity.y + acceleration_filtered.y * deltaT/1000, "z": velocity.z + acceleration_filtered.z * deltaT/1000}; //velocity per second TODO: add friction //console.log(velocity); /*if(dataL === undefined) { var dataL = new Object; //need to push by value Object.assign(dataL, dataArray); }*/ //console.log(dataL); //videoElement.playbackRate = 0.5; //fix playback being too fast let ori = orientationData[nFrame]; //ori = dataArrayL[nFrame].ori; let aVel = frameDataL.aVel; //console.log(nFrame, ori, aVel); if(ori !== undefined) { oriDiff = {"roll": ori.roll-oriInitial.roll, "pitch": ori.pitch-oriInitial.pitch, "yaw": ori.yaw-oriInitial.yaw}; } //accelerometer not taken into account atm //dx = -(videoElement.videoWidth*(aVel.y/(2)) + 0*videoElement.videoWidth*velocity.x)*deltaT/1000; //dy = (-videoElement.videoHeight*(aVel.x/(2)) + 0*videoElement.videoHeight*velocity.y)*deltaT/1000; //x = x + dx; //y = y + dy; //x = 100*oriDiff.yaw; //y = 100*oriDiff.roll; //x = videoElement.videoWidth*(oriDiff.yaw/(Math.PI)); //y = -videoElement.videoHeight*(oriDiff.roll/(Math.PI)); //each 2pi means 1 video height //angle = oriDiff.yaw; angle = {"alpha":frameDataL.aVel.alpha - dataArray[0].aVel.alpha, "beta":frameDataL.aVel.beta, "gamma":frameDataL.aVel.gamma - dataArray[0].aVel.gamma}; //console.log(x, y, angle); //Modifying canvas size, we can show only the desired part of the video TODO: modify according to stabilization box //canvas.width = videoElement.videoWidth; //canvas.height = videoElement.videoHeight; //let cTime = (nFrame/dataArray.length); //console.log(cTime, duration); //videoElement.pause(); //videoElement.currentTime = timeFromStart/1000; /*var timer = setInterval(function() { if (videoElement.readyState ==4 || !videoElement.paused) { videoElement.play(); //render video and rect let widthR = 0.8*canvas.width; let heightR = 0.8*canvas.height; //let videoURL = videoURLBase + "#xywh=pixel:0,0,320,240"; //videoElement.currentTime = timeFromStart/1000; //TODO: fix currentTime //videoElement.currentTime = (nFrame/dataArray.length)*videoElement.duration; //videoElement.currentTime = parseFloat(videoElement.duration * Math.random().toFixed(3)); //videoElement.src = videoURL; //videoElement.load(); //videoElement.play(); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(videoElement,0,0, videoElement.videoWidth, videoElement.videoHeight); ctx.beginPath(); ctx.rect(x+0.1*canvas.width,y+0.1*canvas.height,widthR,heightR); ctx.stroke(); clearInterval(timer); } }, 50);*/ //console.log(videoElement.currentTime); //} //console.log(x, y); //ctx.drawImage(videoElement, 0, 0); //let imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); /*let pixeldataArray = []; //loop through every pixel for(let i=0; i<imageData.data.length; i = i+4) { let pixeldata = {"red": imageData.data[i], "green":imageData.data[i+1], "blue": imageData.data[i+2], "alpha":imageData.data[i+3]}; //pixeldataArray.push(pixeldata); } //pixeldataArray.push(imageData);*/ //if(ori !== undefined) { //let timestamp = dataArray[nFrame].time; //let frameData2 = {"imagedata": imageData, "time": timestamp, "oridiff": oriDiff}; //dataArray2.push(frameData2); //console.log(pixeldataArray); //newImageData.data = data; // Draw the pixels onto the visible canvas //ctx.putImageData(newImageData,0,0); //ctx.putImageData(imageData, 0, 0) //xD //} //} /* if(dataArray2.length === timestamps.length) //now we have read the whole blob - should use callback here instead of if condition { console.log("ended"); cancelAnimationFrame(ref); console.log(dataArray2); stabilize(dataArray2); } */ cameraPos = {"x": cameraPath[nFrame].x, "y": cameraPath[nFrame].y} console.log(cameraPos.x, cameraPos.y); //render video and rect let widthR = 0.6*videoElement.videoWidth; let heightR = 0.6*videoElement.videoHeight; //let trans = {"x": x+0.1*canvas.width + widthR/2, "y": y+0.1*canvas.height + heightR/2}; ctx.clearRect(0, 0, canvas.width, canvas.height); //ctx.translate(videoElement.videoWidth/2 + videoElement.videoWidth * (2*angle.gamma/(Math.PI)), videoElement.videoHeight/2); ctx.translate(videoElement.videoWidth/2 + (1/4) * videoElement.videoWidth * Math.sin(angle.gamma), videoElement.videoHeight/2); ctx.rotate(angle.alpha); ctx.drawImage(videoElement,-videoElement.videoWidth/2,-videoElement.videoHeight/2, videoElement.videoWidth, videoElement.videoHeight); ctx.rotate(-angle.alpha); //ctx.translate(-(videoElement.videoWidth/2 + videoElement.videoWidth * (2*angle.gamma/(Math.PI)), -videoElement.videoHeight/2); ctx.translate(-(videoElement.videoWidth/2 + (1/4) * videoElement.videoWidth * Math.sin(angle.gamma)), -videoElement.videoHeight/2); ctx.beginPath(); for(let i=0; i<nFrame; i++) { ctx.fillRect(cameraPath[i].x,cameraPath[i].y,3,3); console.log(cameraPath.x, cameraPath.y); } ctx.rect((canvas.width-widthR)/2,(canvas.height-heightR)/2,widthR,heightR); var imgData=ctx.getImageData((canvas.width-widthR)/2,(canvas.height-heightR)/2,widthR,heightR); ctx.stroke(); //ctx2.scale(1/0.8, 1/0.8); //ctx2.translate(-videoElement.videoWidth/2 - videoElement.videoWidth * (1.5*angle.gamma/(Math.PI)), 0); ctx2.putImageData(imgData, 0, 0, 0, 0, canvas2.width, canvas2.height); } if(videoElement.ended) { //x = 0; //y = 0; console.log("ended"); cancelAnimationFrame(ref); } if(nFrame >= orientationData.length-1) { //x = 0; //y = 0; extraFrames = extraFrames + nFrame; prevFrame = null; nFrame = 0; cancelAnimationFrame(ref); } prevFrame = nFrame; //nFrame = nFrame + 1; ref = requestAnimationFrame(readFrameData); } function stabilize(dataArrayArg) { //Create a stabilized video from the pixel data given as input let frame = dataArrayArg[0]; //first frame console.log(frame); //ctx.drawImage(frame.imagedata,0,0, videoElement.videoWidth, videoElement.videoHeight); //ctx.putImageData(frame.imagedata, 0, 0); }
script.js
/* * Websensor video stabilization project * https://github.com/jessenie-intel/websensor-video * * Copyright (c) 2017 Jesse Nieminen * * 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. * */ 'use strict'; var constraints = {audio: true,video: { width: { min: 640, ideal: 640, max: 640 }, height: { min: 480, ideal: 480, max: 480 }}}; var mediaRecorder = null; var chunks = []; var videoData = null; var interval = null; var accel_sensor = null; var orientation_sensor = null; var gyroscope = null; var sensorfreq = 60; var selectedSensor = null; //var roll = null; //var pitch = null; //var yaw = null; var accel = {"x": null, "y": null, "z": null}; var accel_last = {"x": null, "y": null, "z": null}; var accelNoG = {"x": null, "y": null, "z": null}; var accel_filtered = null; var aVel = {"x": null, "y": null, "z": null}; var ori = {"roll": null, "pitch": null, "yaw": null, "time": null}; var ori_filtered = null; var oriInitial = {"roll": null, "pitch": null, "yaw": null, "time": null}; var initialoriobtained = false; var orientationData = []; //array to store all the orientation data var aVelData = []; var frameData = {"data": null, "time": null, "ori": null, "aVel": null, "accel": null, "accelnog": null}; var dataArray = []; //array to store all the combined data var dataArray2 = []; //array to store all the combined data var velocity = {"x": 0, "y": 0, "z": 0}; var alpha = 0; var beta = 0; var gamma = 0; var accl = null; var timeInitial = null; var time = null; var timestamp = null; var timestamps = []; var timeAtStart = null; var nFrame = 0; //frame number with which we can combine timestamp and frame data var prevFrame = null; //previous frame var delay = 5; var sensorframeTimeDiff = 0; //time difference between sensor and frame data in ms - this is how much the timestamps differ //canvas var canvas = document.getElementById('myCanvas'); var canvas2 = document.getElementById('myCanvas2'); //CSS.elementSources.set("pfcanvas", canvas); var ctx = canvas.getContext('2d'); var ctx2 = canvas2.getContext('2d'); //var ctx = document.getCSSCanvasContext("2d", "name_of_canvas", 100, 100); - polyfill from https://css-tricks.com/media-fragments-uri-spatial-dimension/ //video element var videoElement = document.querySelector('video'); videoElement.controls = false; var videoURLBase = null; var duration = null; var ref = null; var extraFrames = 0; var x = 0; var y = 0; //position for the square var angle = 0; var cameraPath = []; //array of canvas coordinates describing the camera path var cameraCoord = {"x": null, "y": null, "time": null}; //Sliders var slider_delay = document.getElementById("slider_delay"); var slider_delay_div = document.getElementById("slider_delay_amount"); slider_delay.onchange = () => { delay = slider_delay.value; slider_delay_div.innerHTML = delay; console.log("Delay:", delay); }; class HighPassFilterData { //https://w3c.github.io/motion-sensors/#pass-filters constructor(reading, cutoffFrequency) { Object.assign(this, { x: reading.x, y: reading.y, z: reading.z }); this.cutoff = cutoffFrequency; this.timestamp = reading.timestamp; } update(reading) { let dt = reading.timestamp - this.timestamp / 1000; this.timestamp = reading.timestamp; for (let i of ["x", "y", "z"]) { let alpha = this.cutoff / (this.cutoff + dt); this[i] = this[i] + alpha * (reading[i] - this[i]); } } }; class LowPassFilterData { //https://w3c.github.io/motion-sensors/#pass-filters constructor(reading, bias) { Object.assign(this, { x: reading.x, y: reading.y, z: reading.z }); this.bias = bias; } update(reading) { this.x = this.x * this.bias + reading.x * (1 - this.bias); this.y = this.y * this.bias + reading.y * (1 - this.bias); this.z = this.z * this.bias + reading.z * (1 - this.bias); } }; class LowPassFilterOrientation { constructor(reading, bias) { Object.assign(this, { roll: reading.roll, pitch: reading.pitch, yaw: reading.yaw }); this.bias = bias; } update(reading) { this.roll = this.roll * this.bias + reading.roll * (1 - this.bias); this.pitch = this.pitch * this.bias + reading.pitch * (1 - this.bias); this.yaw = this.yaw * this.bias + reading.yaw * (1 - this.bias); } }; class KalmanFilter { constructor() { this.Q_angle = 0.01; this.Q_gyro = 0.0003; this.R_angle = 0.01; this.reset(); } reset() { this.angle = 0.0; this.bias = 0; this.P00 = 0; this.P01 = 0; this.P10 = 0; this.P11 = 0; } filter(accAngle, gyroRate, dt) { this.angle += dt * (gyroRate - this.bias); this.P00 += -dt * (this.P10 + this.P01) + this.Q_angle * dt; this.P01 += -dt * this.P11; this.P10 += -dt * this.P11; this.P11 += + this.Q_gyro * dt; let axis = accAngle - this.angle; let S = this.P00 + this.R_angle; let K0 = this.P00 / S; let K1 = this.P10 / S; this.angle += K0 * axis; this.bias += K1 * axis; this.P00 -= K0 * this.P00; this.P01 -= K0 * this.P01; this.P10 -= K1 * this.P00; this.P11 -= K1 * this.P01; return this.angle; } }; class OriSensor { constructor() { const sensor = new RelativeOrientationSensor({ frequency: sensorfreq }); const mat4 = new Float32Array(16); const euler = new Float32Array(3); sensor.onreading = () => { sensor.populateMatrix(mat4); toEulerianAngle(sensor.quaternion, euler); //From quaternion to Eulerian angles this.roll = euler[0]; this.pitch = euler[1]; this.yaw = euler[2]; this.timestamp = sensor.timestamp; if (this.onreading) this.onreading(); }; sensor.onactivate = () => { if (this.onactivate) this.onactivate(); }; const start = () => sensor.start(); Object.assign(this, { start }); } } function magnitude(vector) //Calculate the magnitude of a vector { return Math.sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z); } function update_debug() { document.getElementById("ori").textContent = `Orientation: ${ori.roll} ${ori.pitch} ${ori.yaw}`; document.getElementById("accel").textContent = `Acceleration: ${accel.x} ${accel.y} ${accel.z}, M ${magnitude(accel).toFixed(3)}`; document.getElementById("accelnog").textContent = `Linear acceleration (no gravity): ${accelNoG.x} ${accelNoG.y} ${accelNoG.z}, M ${magnitude(accelNoG).toFixed(3)}`; document.getElementById("rrate").textContent = `Rotation rate: ${aVel.x} ${aVel.y} ${aVel.z}, M ${magnitude(aVel).toFixed(3)} and alpha ${alpha} beta ${beta} gamma ${gamma}`; document.getElementById("selectedSensor").textContent = `${selectedSensor}`; } function selectSensor() { selectedSensor = document.getElementById("selectSensor").value; console.log(selectedSensor, "selected"); } function buildCameraPath(dataArray) { //Build the shaky camera path from the sensor measurements (convert to canvas coordinates) using projection for (let i=0; i<dataArray.length; i++) { let ori = dataArray[i].ori; let oriDiff = null; if(ori !== undefined) { oriDiff = {"roll": ori.roll-oriInitial.roll, "pitch": ori.pitch-oriInitial.pitch, "yaw": ori.yaw-oriInitial.yaw}; console.log(canvas.width, canvas.height); cameraCoord.x = (1/2) * canvas.width + (1/2)*Math.sin(oriDiff.yaw) * canvas.width; cameraCoord.y = (1/2) * canvas.height + (1/2)*Math.sin(oriDiff.roll) * canvas.height; var b = new Object; //need to push by value Object.assign(b, cameraCoord); cameraPath.push(b); } } } //WINDOWS 10 HAS DIFFERENT CONVENTION: Yaw z, pitch x, roll y function toEulerianAngle(quat, out) { const ysqr = quat[1] ** 2; // Roll (x-axis rotation). const t0 = 2 * (quat[3] * quat[0] + quat[1] * quat[2]); const t1 = 1 - 2 * (ysqr + quat[0] ** 2); out[0] = Math.atan2(t0, t1); // Pitch (y-axis rotation). let t2 = 2 * (quat[3] * quat[1] - quat[2] * quat[0]); t2 = t2 > 1 ? 1 : t2; t2 = t2 < -1 ? -1 : t2; out[1] = Math.asin(t2); // Yaw (z-axis rotation). const t3 = 2 * (quat[3] * quat[2] + quat[0] * quat[1]); const t4 = 1 - 2 * (ysqr + quat[2] ** 2); out[2] = Math.atan2(t3, t4); return out; } function errorCallback(error){ console.log("error: ", error); } function startDemo () { navigator.getUserMedia(constraints, startRecording, errorCallback); } function startSensors() { try { timeInitial = Date.now(); const bias = 0.98; //Initialize sensors accel_sensor = new Accelerometer({frequency: sensorfreq}); // Remove drift with a high pass filter. const accel_filtered = new HighPassFilterData(accel_sensor, 0.8); //console.log(accel_filtered); //null, null, null accel_sensor.onreading = () => { accel = {"x": accel_sensor.x, "y": accel_sensor.y, "z": accel_sensor.z, "time": accel_sensor.timestamp}; //accel = {"x": (1/2)*(accel_last.x + accel_sensor.x), "y": (1/2)*(accel_last.y + accel_sensor.y), "z": (1/2)*(accel_last.z + accel_sensor.z)}; //accel_last = accel; //for smoothing the data //accel_filtered.update(accel_sensor); //accel = accel_filtered; //accelNoG = {x:accel.x - gravity.x, y:accel.y - gravity.y, z:accel.z - gravity.z}; }; accel_sensor.onactivate = () => { }; accel_sensor.start(); gyroscope = new Gyroscope({frequency: sensorfreq}); //accl = new Accelerometer({frequency: sensorfreq}); const gyro_filtered = new LowPassFilterData(gyroscope, 0.1); gyroscope.onreading = () => { //console.log(Date.now()); gyro_filtered.update(gyroscope); //aVel = {x:gyro_data.x, y:gyro_data.y, z:gyro_data.z}; //aVel = {x:gyroscope.x, y:gyroscope.y, z:gyroscope.z, alpha: alpha}; //Determine orientation with accelerometer and gyroscope. Below from https://w3c.github.io/motion-sensors/#complementary-filters let dt = timestamp ? (gyroscope.timestamp - timestamp) / 1000 : 0; timestamp = gyroscope.timestamp; // Treat the acceleration vector as an orientation vector by normalizing it. // Keep in mind that the if the device is flipped, the vector will just be // pointing in the other direction, so we have no way to know from the // accelerometer data which way the device is oriented. const norm = Math.sqrt(accel_sensor.x ** 2 + accel_sensor.y ** 2 + accel_sensor.z ** 2); // As we only can cover half (PI rad) of the full spectrum (2*PI rad) we multiply // the unit vector with values from [-1, 1] with PI/2, covering [-PI/2, PI/2]. const scale = Math.PI / 2; const zeroBias = 0.02; //console.log(accel_sensor.timestamp, gyroscope.timestamp, accel_sensor.timestamp - gyroscope.timestamp); //alpha = (1 - zeroBias) * (alpha + gyroscope.z * dt); alpha = alpha + gyro_filtered.z * dt; beta = bias * (beta + gyroscope.x * dt) + (1.0 - bias) * (accel_sensor.x * scale / norm); gamma = bias * (gamma + gyro_filtered.y * dt) + (1.0 - bias) * (accel_sensor.y * -scale / norm); //gamma = (gamma + gyro_filtered.y * dt); aVel = {x:gyroscope.x, y:gyroscope.y, z:gyroscope.z, alpha: alpha, beta: beta, gamma: gamma}; //console.log(Date.now()); }; gyroscope.onactivate = () => { }; gyroscope.start(); orientation_sensor = new OriSensor({frequency: sensorfreq}); //Low-pass filter the orientation data. Cannot initialize normally because undefined const ori_filtered = new LowPassFilterOrientation({"roll":null, "pitch":null, "yaw":null}, 0.9); //console.log(ori_filtered); orientation_sensor.onreading = () => { let roll = orientation_sensor.roll; let pitch = orientation_sensor.pitch; let yaw = orientation_sensor.yaw; //time = orientation_sensor.timestamp; time = Date.now(); if(!initialoriobtained) //obtain initial orientation { oriInitial = {"roll": orientation_sensor.roll, "pitch": orientation_sensor.pitch, "yaw": orientation_sensor.yaw, "time": Date.now()}; //timeAtStart = orientation_sensor.timestamp; timeAtStart = Date.now(); initialoriobtained = true; sensorframeTimeDiff = timeAtStart - timeInitial; console.log(sensorframeTimeDiff); } ori = {"roll": orientation_sensor.roll, "pitch": orientation_sensor.pitch, "yaw": orientation_sensor.yaw, "time": orientation_sensor.timestamp}; //console.log(orientation_sensor); ori_filtered.update(ori); //console.log(ori_filtered); //ori = ori_filtered; //ori.roll = ori_filtered.roll; //ori.pitch = ori_filtered.pitch; //ori.yaw = ori_filtered.yaw; //ori.time = orientation_sensor.timestamp; //console.log(ori_filtered); }; orientation_sensor.onactivate = () => { }; orientation_sensor.start(); } catch(err) { console.log(err.message); console.log("Your browser doesn't seem to support generic sensors. If you are running Chrome, please enable it in about:flags."); //this.innerHTML = "Your browser doesn't seem to support generic sensors. If you are running Chrome, please enable it in about:flags"; } } document.addEventListener('DOMContentLoaded', function() { startSensors(); //start sensors instantly to avoid gyro drift }, false); function startRecording(stream) { interval=window.setInterval(update_debug,100); //var options = {mimeType: 'video/webm;codecs=vp9'}; //mediaRecorder = new MediaRecorder(stream, options); mediaRecorder = new MediaRecorder(stream); mediaRecorder.start(10); var url = window.URL; videoElement.src = url ? url.createObjectURL(stream) : stream; //videoElement.play(); mediaRecorder.ondataavailable = function(e) { //console.log("Data available", e); //console.log(time); timestamps.push(time); frameData.time = time; chunks.push(e.data); frameData.data = e.data; orientationData.push(ori); aVelData.push(aVel); frameData.ori = ori; frameData.aVel = aVel; frameData.accel = accel; //frameData.accelnog = accelNoG; //dataArray.push(frameData); var b = new Object; //need to push by value Object.assign(b, frameData); dataArray.push(b); frameData = {"data": null, "time": null, "ori": null, "aVel": null, "accel": null, "accelnog": null}; }; mediaRecorder.onerror = function(e){ console.log('Error: ', e); }; mediaRecorder.onstart = function(){ console.log("Recording started", mediaRecorder.state); }; mediaRecorder.onstop = function(){ var blob = new Blob(chunks, {type: "video/webm"}); chunks = []; videoURLBase = window.URL.createObjectURL(blob); videoElement.src = videoURLBase + "#xywh=pixel:0,0,320,240"; videoElement.load(); //resize canvas videoElement.addEventListener('loadedmetadata', function() { console.log("Loaded metadata"); canvas.width = videoElement.videoWidth; canvas.height = videoElement.videoHeight; //canvas.style.display="none"; canvas2.width = videoElement.videoWidth; canvas2.height = videoElement.videoHeight; ctx.save(); //save canvas state for later restoration //duration = videoElement.duration; }); /* videoElement.addEventListener('durationchange', function() { duration = videoElement.duration; }); */ duration = (dataArray[dataArray.length-1].time - dataArray[0].time)/1000; //duration in s //videoElement.play(); videoElement.addEventListener('play', function() { videoElement.play(); nFrame = 0; let durationPerFrame = duration*1000/dataArray.length; //frame duration in ms //delay = Math.floor(sensorframeTimeDiff/durationPerFrame); //console.log("Delay", delay); buildCameraPath(dataArray); //build camera path readFrameData(blob, orientationData, cameraPath); //reads the video into dataArray2 }, false); /*//Read blob data so we can stabilize the video var reader = new FileReader(); reader.onload = function(event){ let text = reader.result; console.log(text); }; reader.readAsText(blob, "video/webm");*/ //console.log(orientationData); //console.log(timestamps); //console.log(dataArray); /* var blobUrl = URL.createObjectURL(blob); var x = new XMLHttpRequest(); // set x.responseType = 'blob' if you want to get a Blob object: // x.responseType = 'blob'; x.onload = function() { alert(x.responseText); }; console.log(x.open('get', blobUrl));*/ //readFrameData(blob, orientationData); //reads the video into dataArray2 //console.log(dataArray); /*videoElement.onended = function() { alert("The video has ended"); cancelAnimationFrame(ref); };*/ //ctx.clearRect(0, 0, canvas.width, canvas.height); //stabilize(dataArray2); //now we can operate on it }; mediaRecorder.onpause = function(){ } mediaRecorder.onresume = function(){ } mediaRecorder.onwarning = function(e){ }; } function stopRecording(){ mediaRecorder.stop(); //Now stabilize videoElement.controls = true; } //Idea: copy video to canvas, operate on the video, and then use the canvas with the stabilized video as source for the video element function readFrameData(blob, oriArray, cameraPath) { //Read video data from blob to object form with pixel data we can operate on //TODO: sensor readings and frame data in desync - frame data too late/sensor data ahead //console.log("frame"); nFrame = videoElement.webkitDecodedFrameCount - extraFrames; //console.log(prevFrame, nFrame); //let x = 0; //let y = 0; let dx = 0; let dy = 0; //let delay = -10; var timeFromStart = null; var cameraPos = null; let frameDataL = (nFrame-delay >=0 && nFrame-delay <= dataArray.length) ? dataArray[nFrame - delay] : dataArray[nFrame]; if(nFrame === 0) { //console.log(dataArray); //timeAtStart = frameDataL.ori.time; } else if(nFrame !== 0 && nFrame !== prevFrame && frameDataL !== undefined && cameraPath !== undefined) //all subsequent frames { //console.log(nFrame); //console.log(dataL); timeFromStart = frameDataL.time - timeAtStart; //time since recording start (in ms) //console.log(timeFromStart); //console.log(frameDataL); //console.log(nFrame); //console.log(videoElement.webkitDecodedFrameCount); //only works in webkit browsers //console.log(timestamps[nFrame] - timestamps[0], videoElement.currentTime); //while(!videoElement.ended) //{ //if(cameraPath !== undefined) //{ //} let oriDiff = null; let deltaT = frameDataL.time - dataArray[nFrame-1].time; //console.log(deltaT); let acceleration_filtered = null; //if(magnitude(frameDataL.accel) > 0.5) //filter out small values in acceleration (noise) //{ acceleration_filtered = frameDataL.accel; /*} else { acceleration_filtered = {"x":0, "y":0, "z": 0}; }*/ velocity = {"x": velocity.x + acceleration_filtered.x * deltaT/1000, "y": velocity.y + acceleration_filtered.y * deltaT/1000, "z": velocity.z + acceleration_filtered.z * deltaT/1000}; //velocity per second TODO: add friction //console.log(velocity); /*if(dataL === undefined) { var dataL = new Object; //need to push by value Object.assign(dataL, dataArray); }*/ //console.log(dataL); //videoElement.playbackRate = 0.5; //fix playback being too fast let ori = orientationData[nFrame]; //ori = dataArrayL[nFrame].ori; let aVel = frameDataL.aVel; //console.log(nFrame, ori, aVel); if(ori !== undefined) { oriDiff = {"roll": ori.roll-oriInitial.roll, "pitch": ori.pitch-oriInitial.pitch, "yaw": ori.yaw-oriInitial.yaw}; } //accelerometer not taken into account atm //dx = -(videoElement.videoWidth*(aVel.y/(2)) + 0*videoElement.videoWidth*velocity.x)*deltaT/1000; //dy = (-videoElement.videoHeight*(aVel.x/(2)) + 0*videoElement.videoHeight*velocity.y)*deltaT/1000; //x = x + dx; //y = y + dy; //x = 100*oriDiff.yaw; //y = 100*oriDiff.roll; //x = videoElement.videoWidth*(oriDiff.yaw/(Math.PI)); //y = -videoElement.videoHeight*(oriDiff.roll/(Math.PI)); //each 2pi means 1 video height //angle = oriDiff.yaw; angle = {"alpha":frameDataL.aVel.alpha - dataArray[0].aVel.alpha, "beta":frameDataL.aVel.beta, "gamma":frameDataL.aVel.gamma - dataArray[0].aVel.gamma}; //console.log(x, y, angle); //Modifying canvas size, we can show only the desired part of the video TODO: modify according to stabilization box //canvas.width = videoElement.videoWidth; //canvas.height = videoElement.videoHeight; //let cTime = (nFrame/dataArray.length); //console.log(cTime, duration); //videoElement.pause(); //videoElement.currentTime = timeFromStart/1000; /*var timer = setInterval(function() { if (videoElement.readyState ==4 || !videoElement.paused) { videoElement.play(); //render video and rect let widthR = 0.8*canvas.width; let heightR = 0.8*canvas.height; //let videoURL = videoURLBase + "#xywh=pixel:0,0,320,240"; //videoElement.currentTime = timeFromStart/1000; //TODO: fix currentTime //videoElement.currentTime = (nFrame/dataArray.length)*videoElement.duration; //videoElement.currentTime = parseFloat(videoElement.duration * Math.random().toFixed(3)); //videoElement.src = videoURL; //videoElement.load(); //videoElement.play(); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(videoElement,0,0, videoElement.videoWidth, videoElement.videoHeight); ctx.beginPath(); ctx.rect(x+0.1*canvas.width,y+0.1*canvas.height,widthR,heightR); ctx.stroke(); clearInterval(timer); } }, 50);*/ //console.log(videoElement.currentTime); //} //console.log(x, y); //ctx.drawImage(videoElement, 0, 0); //let imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); /*let pixeldataArray = []; //loop through every pixel for(let i=0; i<imageData.data.length; i = i+4) { let pixeldata = {"red": imageData.data[i], "green":imageData.data[i+1], "blue": imageData.data[i+2], "alpha":imageData.data[i+3]}; //pixeldataArray.push(pixeldata); } //pixeldataArray.push(imageData);*/ //if(ori !== undefined) { //let timestamp = dataArray[nFrame].time; //let frameData2 = {"imagedata": imageData, "time": timestamp, "oridiff": oriDiff}; //dataArray2.push(frameData2); //console.log(pixeldataArray); //newImageData.data = data; // Draw the pixels onto the visible canvas //ctx.putImageData(newImageData,0,0); //ctx.putImageData(imageData, 0, 0) //xD //} //} /* if(dataArray2.length === timestamps.length) //now we have read the whole blob - should use callback here instead of if condition { console.log("ended"); cancelAnimationFrame(ref); console.log(dataArray2); stabilize(dataArray2); } */ cameraPos = {"x": cameraPath[nFrame].x, "y": cameraPath[nFrame].y} console.log(cameraPos.x, cameraPos.y); //render video and rect let widthR = 0.6*videoElement.videoWidth; let heightR = 0.6*videoElement.videoHeight; //let trans = {"x": x+0.1*canvas.width + widthR/2, "y": y+0.1*canvas.height + heightR/2}; ctx.clearRect(0, 0, canvas.width, canvas.height); //ctx.translate(videoElement.videoWidth/2 + videoElement.videoWidth * (2*angle.gamma/(Math.PI)), videoElement.videoHeight/2); ctx.translate(videoElement.videoWidth/2 + (1/4) * videoElement.videoWidth * Math.sin(angle.gamma), videoElement.videoHeight/2); ctx.rotate(angle.alpha); ctx.drawImage(videoElement,-videoElement.videoWidth/2,-videoElement.videoHeight/2, videoElement.videoWidth, videoElement.videoHeight); ctx.rotate(-angle.alpha); //ctx.translate(-(videoElement.videoWidth/2 + videoElement.videoWidth * (2*angle.gamma/(Math.PI)), -videoElement.videoHeight/2); ctx.translate(-(videoElement.videoWidth/2 + (1/4) * videoElement.videoWidth * Math.sin(angle.gamma)), -videoElement.videoHeight/2); ctx.beginPath(); for(let i=0; i<nFrame; i++) { ctx.fillRect(cameraPath[i].x,cameraPath[i].y,3,3); } ctx.rect((canvas.width-widthR)/2,(canvas.height-heightR)/2,widthR,heightR); var imgData=ctx.getImageData((canvas.width-widthR)/2,(canvas.height-heightR)/2,widthR,heightR); ctx.stroke(); //ctx2.scale(1/0.8, 1/0.8); //ctx2.translate(-videoElement.videoWidth/2 - videoElement.videoWidth * (1.5*angle.gamma/(Math.PI)), 0); ctx2.putImageData(imgData, 0, 0, 0, 0, canvas2.width, canvas2.height); } if(videoElement.ended) { //x = 0; //y = 0; console.log("ended"); cancelAnimationFrame(ref); } if(nFrame >= orientationData.length-1) { //x = 0; //y = 0; extraFrames = extraFrames + nFrame; prevFrame = null; nFrame = 0; cancelAnimationFrame(ref); } prevFrame = nFrame; //nFrame = nFrame + 1; ref = requestAnimationFrame(readFrameData); } function stabilize(dataArrayArg) { //Create a stabilized video from the pixel data given as input let frame = dataArrayArg[0]; //first frame console.log(frame); //ctx.drawImage(frame.imagedata,0,0, videoElement.videoWidth, videoElement.videoHeight); //ctx.putImageData(frame.imagedata, 0, 0); }
Build camera path
script.js
Build camera path
<ide><path>cript.js <ide> for(let i=0; i<nFrame; i++) <ide> { <ide> ctx.fillRect(cameraPath[i].x,cameraPath[i].y,3,3); <add> console.log(cameraPath.x, cameraPath.y); <ide> } <ide> ctx.rect((canvas.width-widthR)/2,(canvas.height-heightR)/2,widthR,heightR); <ide> var imgData=ctx.getImageData((canvas.width-widthR)/2,(canvas.height-heightR)/2,widthR,heightR);
Java
apache-2.0
f6b03944ff44d41528e7f6c8189652579427931c
0
opensingular/singular-core,opensingular/singular-core,opensingular/singular-core,opensingular/singular-core
package br.net.mirante.singular.wicket; import java.util.Locale; import java.util.logging.Logger; import org.apache.wicket.RuntimeConfigurationType; import org.apache.wicket.Session; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.protocol.http.WebApplication; import org.apache.wicket.request.Request; import org.apache.wicket.request.Response; import org.apache.wicket.request.http.WebRequest; import org.apache.wicket.spring.injection.annot.SpringComponentInjector; import br.net.mirante.singular.view.page.dashboard.DashboardPage; import br.net.mirante.singular.view.page.processo.ProcessosPage; import javax.servlet.http.HttpServletRequest; public class UIAdminApplication extends WebApplication { @Override public Class<? extends WebPage> getHomePage() { return DashboardPage.class; } @Override public void init() { super.init(); Locale.setDefault(new Locale("pt", "BR")); // add your configuration here getMarkupSettings().setStripWicketTags(true); getMarkupSettings().setStripComments(true); getMarkupSettings().setDefaultMarkupEncoding("UTF-8"); getComponentInstantiationListeners().add(new SpringComponentInjector(this)); mountPage("processos", ProcessosPage.class); } @Override public Session newSession(Request request, Response response) { return new UIAdminSession(request, response); } @Override public RuntimeConfigurationType getConfigurationType() { if (System.getProperty("singular.production") != null) { return RuntimeConfigurationType.DEPLOYMENT; } else { return RuntimeConfigurationType.DEVELOPMENT; } } }
flow/ui-admin/src/main/java/br/net/mirante/singular/wicket/UIAdminApplication.java
package br.net.mirante.singular.wicket; import java.util.Locale; import org.apache.wicket.Session; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.protocol.http.WebApplication; import org.apache.wicket.request.Request; import org.apache.wicket.request.Response; import org.apache.wicket.request.http.WebRequest; import org.apache.wicket.spring.injection.annot.SpringComponentInjector; import br.net.mirante.singular.view.page.dashboard.DashboardPage; import br.net.mirante.singular.view.page.processo.ProcessosPage; import javax.servlet.http.HttpServletRequest; public class UIAdminApplication extends WebApplication { @Override public Class<? extends WebPage> getHomePage() { return DashboardPage.class; } @Override public void init() { super.init(); Locale.setDefault(new Locale("pt", "BR")); // add your configuration here getMarkupSettings().setStripWicketTags(true); getMarkupSettings().setStripComments(true); getMarkupSettings().setDefaultMarkupEncoding("UTF-8"); getComponentInstantiationListeners().add(new SpringComponentInjector(this)); mountPage("processos", ProcessosPage.class); } @Override public Session newSession(Request request, Response response) { return new UIAdminSession(request, response); } }
ajustando para modo produção configurável
flow/ui-admin/src/main/java/br/net/mirante/singular/wicket/UIAdminApplication.java
ajustando para modo produção configurável
<ide><path>low/ui-admin/src/main/java/br/net/mirante/singular/wicket/UIAdminApplication.java <ide> package br.net.mirante.singular.wicket; <ide> <ide> import java.util.Locale; <add>import java.util.logging.Logger; <ide> <add>import org.apache.wicket.RuntimeConfigurationType; <ide> import org.apache.wicket.Session; <ide> import org.apache.wicket.markup.html.WebPage; <ide> import org.apache.wicket.protocol.http.WebApplication; <ide> public Session newSession(Request request, Response response) { <ide> return new UIAdminSession(request, response); <ide> } <add> <add> @Override <add> public RuntimeConfigurationType getConfigurationType() { <add> if (System.getProperty("singular.production") != null) { <add> return RuntimeConfigurationType.DEPLOYMENT; <add> } else { <add> return RuntimeConfigurationType.DEVELOPMENT; <add> } <add> } <ide> }
Java
apache-2.0
5c5b30d48abaae7aadccbf880349e7f116f4db54
0
flyersa/MuninMX
/* * MuninMX * Copyright (c) 2014 * www.clavain.com * */ package com.clavain.utils; import com.clavain.jobs.CustomJob; import com.clavain.jobs.MuninJob; import com.clavain.json.ScheduledJob; import com.clavain.munin.MuninNode; import com.clavain.munin.MuninPlugin; import static org.quartz.SimpleScheduleBuilder.simpleSchedule; import org.quartz.Trigger; import static com.clavain.muninmxcd.logger; import static com.clavain.muninmxcd.sched; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.quartz.impl.matchers.GroupMatcher; import org.quartz.JobDetail; import org.quartz.SchedulerException; import static org.quartz.JobBuilder.*; import org.quartz.JobKey; import static org.quartz.TriggerBuilder.newTrigger; import static org.quartz.impl.matchers.GroupMatcher.groupEquals; import static com.clavain.utils.Database.getMuninPluginForCustomJobFromDb; import static com.clavain.utils.Generic.getStampFromTimeAndZone; import static com.clavain.utils.Generic.getMuninPluginForCustomJob; import java.text.SimpleDateFormat; import java.util.TimeZone; import org.quartz.CronScheduleBuilder; /** * * @author enricokern */ public class Quartz { // schedule a new check public static boolean scheduleJob(MuninNode mn) { boolean l_retVal = false; String uid = mn.getUser_id().toString(); Trigger trigger = newTrigger().withIdentity("trigger", uid + mn.getNode_id() + System.currentTimeMillis()).startNow().withSchedule(simpleSchedule().withIntervalInMinutes(mn.getQueryInterval()) .repeatForever().withMisfireHandlingInstructionFireNow()).build(); JobDetail job = newJob(MuninJob.class).withIdentity(mn.getNode_id().toString(), mn.getUser_id().toString()).usingJobData("nodeId", mn.getNode_id()).build(); try { sched.scheduleJob(job, trigger); logger.info("Scheduled Job for Node: " + mn.getHostname() + " with interval: " + mn.getQueryInterval() + " minutes"); l_retVal = true; } catch (Exception ex) { logger.error("Unable to Schedule Job for Node: " + mn.getHostname()); logger.error(ex); } return l_retVal; } public static boolean isScheduled(Integer p_nodeid, Integer p_user_id) { boolean l_retVal = false; String jobSearch = p_user_id + "." + p_nodeid; try { // enumerate each job group for(String group: com.clavain.muninmxcd.sched.getJobGroupNames()) { // enumerate each job in group for(JobKey jobKey : com.clavain.muninmxcd.sched.getJobKeys((GroupMatcher<JobKey>) groupEquals(group))) { if(jobKey.toString().equals(jobSearch)) { l_retVal = true; } } } } catch (SchedulerException ex) { logger.error("Error in isScheduled: " + ex.getLocalizedMessage()); } return l_retVal; } public static boolean isJobScheduled(int p_nodeid) { boolean retval = false; String match = p_nodeid+""; for(ScheduledJob sj : getScheduledJobs()) { if(sj.getJobName().equals(match)) { return true; } } return retval; } public static boolean unscheduleCheck(String p_nodeid, String p_uid) { boolean l_retVal = false; JobKey jk = new JobKey(p_nodeid,p_uid); try { com.clavain.muninmxcd.sched.deleteJob(jk); l_retVal = true; } catch (SchedulerException ex) { logger.error("Error in unscheduleCheck: " + ex.getLocalizedMessage()); } return l_retVal; } public static boolean isCustomJobScheduled(int p_cid) { boolean retval = false; String match = p_cid+""; for(ScheduledJob sj : getScheduledCustomJobs()) { if(sj.getJobName().equals(match)) { return true; } } return retval; } public static boolean unscheduleCustomJob(String p_cid, String p_uid) { boolean l_retVal = false; JobKey jk = new JobKey(p_cid,p_uid); try { com.clavain.muninmxcd.sched_custom.deleteJob(jk); com.clavain.muninmxcd.v_cinterval_plugins.remove(getMuninPluginForCustomJob(Integer.parseInt(p_cid))); l_retVal = true; } catch (SchedulerException ex) { logger.error("Error in unscheduleCustomCheck: " + ex.getLocalizedMessage()); } return l_retVal; } // schedule a custom interval check public static boolean scheduleCustomIntervalJob(Integer p_cid) { boolean retval = false; MuninPlugin l_mp = getMuninPluginForCustomJobFromDb(p_cid); if(l_mp != null) { String uid = l_mp.getUser_id().toString(); String cinterval = ""; // build trigger Trigger trigger; // crontab trigger if(!l_mp.getCrontab().equals("false")) { // fixed start/end ? if(l_mp.getFrom_time() == 0) { trigger = newTrigger().withIdentity("trigger", uid + l_mp.getCustomId() + System.currentTimeMillis()).withSchedule(CronScheduleBuilder.cronSchedule(l_mp.getCrontab()).withMisfireHandlingInstructionFireAndProceed().inTimeZone(TimeZone.getTimeZone(l_mp.getTimezone()))).build(); cinterval = " every " + l_mp.getQuery_interval() + " seconds with crontab: " + l_mp.getCrontab(); } else { long a = l_mp.getFrom_time(); long b = l_mp.getTo_time(); Date startDate = new Date(a*1000L); Date endDate = new Date(b*1000L); trigger = newTrigger().withIdentity("trigger", uid + l_mp.getCustomId() + System.currentTimeMillis()).startAt(startDate).withSchedule(CronScheduleBuilder.cronSchedule(l_mp.getCrontab()).withMisfireHandlingInstructionFireAndProceed().inTimeZone(TimeZone.getTimeZone(l_mp.getTimezone()))).endAt(endDate).build(); cinterval = " every " + l_mp.getQuery_interval() + " seconds with crontab: " + l_mp.getCrontab() + " from " + startDate + " to " + endDate; } } else { // standard repeat forever trigger if(l_mp.getFrom_time() == 0) { trigger = newTrigger().withIdentity("trigger", uid + l_mp.getCustomId() + System.currentTimeMillis()).startNow().withSchedule(simpleSchedule().withIntervalInSeconds(l_mp.getQuery_interval()).repeatForever().withMisfireHandlingInstructionFireNow()).build(); cinterval = " every " + l_mp.getQuery_interval() + " seconds"; } // daterange trigger, ignore missfire else { long a = l_mp.getFrom_time(); long b = l_mp.getTo_time(); Date startDate = new Date(a*1000L); Date endDate = new Date(b*1000L); long cur = (System.currentTimeMillis() / 1000L); trigger = newTrigger().withIdentity("trigger", uid + l_mp.getCustomId() + System.currentTimeMillis()).startAt(startDate).withSchedule(simpleSchedule().withIntervalInSeconds(l_mp.getQuery_interval()).repeatForever().withMisfireHandlingInstructionIgnoreMisfires()).endAt(endDate).build(); cinterval = " every " + l_mp.getQuery_interval() + " seconds from " + startDate + " to " + endDate; } } //Trigger trigger = newTrigger().withIdentity("trigger", uid + l_mp.get_NodeId() + System.currentTimeMillis()).startNow().withSchedule(simpleSchedule().withIntervalInMinutes(l_mp.get .repeatForever().withMisfireHandlingInstructionFireNow()).build(); JobDetail job = newJob(CustomJob.class).withIdentity(l_mp.getCustomId() + "", l_mp.getUser_id().toString()).usingJobData("customId", l_mp.getCustomId()).build(); try { com.clavain.muninmxcd.sched_custom.scheduleJob(job, trigger); logger.info("Scheduled CustomJob for custom interval: " + l_mp.getCustomId() + " with interval " + cinterval); retval = true; com.clavain.muninmxcd.v_cinterval_plugins.add(l_mp); } catch (Exception ex) { logger.error("Unable to Schedule Job for custom interval:" + l_mp.getCustomId() + " with interval " + cinterval); logger.error(ex.getLocalizedMessage()); } } return retval; } public static ArrayList<ScheduledJob> getScheduledJobs() { ArrayList<ScheduledJob> retval = new ArrayList<>(); try { for (String groupName : com.clavain.muninmxcd.sched.getJobGroupNames()) { for (JobKey jobKey : com.clavain.muninmxcd.sched.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) { String jobName = jobKey.getName(); String jobGroup = jobKey.getGroup(); //get job's trigger List<Trigger> triggers = (List<Trigger>) com.clavain.muninmxcd.sched.getTriggersOfJob(jobKey); Date nextFireTime = triggers.get(0).getNextFireTime(); ScheduledJob sj = new ScheduledJob(); sj.setJobName(jobName); sj.setGroupName(jobGroup); sj.setNextFireTime(nextFireTime.toString()); retval.add(sj); } } } catch (SchedulerException ex) { logger.error("Error in getScheduledJobs(): " + ex.getLocalizedMessage()); } return retval; } public static ArrayList<ScheduledJob> getScheduledCustomJobs() { ArrayList<ScheduledJob> retval = new ArrayList<>(); try { for (String groupName : com.clavain.muninmxcd.sched_custom.getJobGroupNames()) { for (JobKey jobKey : com.clavain.muninmxcd.sched_custom.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) { String jobName = jobKey.getName(); String jobGroup = jobKey.getGroup(); //get job's trigger List<Trigger> triggers = (List<Trigger>) com.clavain.muninmxcd.sched_custom.getTriggersOfJob(jobKey); Date nextFireTime = triggers.get(0).getNextFireTime(); ScheduledJob sj = new ScheduledJob(); sj.setJobName(jobName); sj.setGroupName(jobGroup); sj.setNextFireTime(nextFireTime.toString()); retval.add(sj); } } } catch (SchedulerException ex) { logger.error("Error in getScheduledJobs(): " + ex.getLocalizedMessage()); } return retval; } }
src/com/clavain/utils/Quartz.java
/* * MuninMX * Copyright (c) 2014 * www.clavain.com * */ package com.clavain.utils; import com.clavain.jobs.CustomJob; import com.clavain.jobs.MuninJob; import com.clavain.json.ScheduledJob; import com.clavain.munin.MuninNode; import com.clavain.munin.MuninPlugin; import static org.quartz.SimpleScheduleBuilder.simpleSchedule; import org.quartz.Trigger; import static com.clavain.muninmxcd.logger; import static com.clavain.muninmxcd.sched; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.quartz.impl.matchers.GroupMatcher; import org.quartz.JobDetail; import org.quartz.SchedulerException; import static org.quartz.JobBuilder.*; import org.quartz.JobKey; import static org.quartz.TriggerBuilder.newTrigger; import static org.quartz.impl.matchers.GroupMatcher.groupEquals; import static com.clavain.utils.Database.getMuninPluginForCustomJobFromDb; import static com.clavain.utils.Generic.getStampFromTimeAndZone; import static com.clavain.utils.Generic.getMuninPluginForCustomJob; import java.text.SimpleDateFormat; import java.util.TimeZone; import org.quartz.CronScheduleBuilder; /** * * @author enricokern */ public class Quartz { // schedule a new check public static boolean scheduleJob(MuninNode mn) { boolean l_retVal = false; String uid = mn.getUser_id().toString(); Trigger trigger = newTrigger().withIdentity("trigger", uid + mn.getNode_id() + System.currentTimeMillis()).startNow().withSchedule(simpleSchedule().withIntervalInMinutes(mn.getQueryInterval()) .repeatForever().withMisfireHandlingInstructionFireNow()).build(); JobDetail job = newJob(MuninJob.class).withIdentity(mn.getNode_id().toString(), mn.getUser_id().toString()).usingJobData("nodeId", mn.getNode_id()).build(); try { sched.scheduleJob(job, trigger); logger.info("Scheduled Job for Node: " + mn.getHostname() + " with interval: " + mn.getQueryInterval() + " minutes"); l_retVal = true; } catch (Exception ex) { logger.error("Unable to Schedule Job for Node: " + mn.getHostname()); logger.error(ex); } return l_retVal; } public static boolean isScheduled(Integer p_nodeid, Integer p_user_id) { boolean l_retVal = false; String jobSearch = p_user_id + "." + p_nodeid; try { // enumerate each job group for(String group: com.clavain.muninmxcd.sched.getJobGroupNames()) { // enumerate each job in group for(JobKey jobKey : com.clavain.muninmxcd.sched.getJobKeys((GroupMatcher<JobKey>) groupEquals(group))) { if(jobKey.toString().equals(jobSearch)) { l_retVal = true; } } } } catch (SchedulerException ex) { logger.error("Error in isScheduled: " + ex.getLocalizedMessage()); } return l_retVal; } public static boolean isJobScheduled(int p_nodeid) { boolean retval = false; String match = p_nodeid+""; for(ScheduledJob sj : getScheduledJobs()) { if(sj.getJobName().equals(match)) { return true; } } return retval; } public static boolean unscheduleCheck(String p_nodeid, String p_uid) { boolean l_retVal = false; JobKey jk = new JobKey(p_nodeid,p_uid); try { com.clavain.muninmxcd.sched.deleteJob(jk); l_retVal = true; } catch (SchedulerException ex) { logger.error("Error in unscheduleCheck: " + ex.getLocalizedMessage()); } return l_retVal; } public static boolean isCustomJobScheduled(int p_cid) { boolean retval = false; String match = p_cid+""; for(ScheduledJob sj : getScheduledCustomJobs()) { if(sj.getJobName().equals(match)) { return true; } } return retval; } public static boolean unscheduleCustomJob(String p_cid, String p_uid) { boolean l_retVal = false; JobKey jk = new JobKey(p_cid,p_uid); try { com.clavain.muninmxcd.sched_custom.deleteJob(jk); com.clavain.muninmxcd.v_cinterval_plugins.remove(getMuninPluginForCustomJob(Integer.parseInt(p_cid))); l_retVal = true; } catch (SchedulerException ex) { logger.error("Error in unscheduleCustomCheck: " + ex.getLocalizedMessage()); } return l_retVal; } // schedule a custom interval check public static boolean scheduleCustomIntervalJob(Integer p_cid) { boolean retval = false; MuninPlugin l_mp = getMuninPluginForCustomJobFromDb(p_cid); if(l_mp != null) { String uid = l_mp.getUser_id().toString(); String cinterval = ""; // build trigger Trigger trigger; // crontab trigger if(!l_mp.getCrontab().equals("false")) { trigger = newTrigger().withIdentity("trigger", uid + l_mp.getCustomId() + System.currentTimeMillis()).withSchedule(CronScheduleBuilder.cronSchedule(l_mp.getCrontab()).withMisfireHandlingInstructionFireAndProceed().inTimeZone(TimeZone.getTimeZone(l_mp.getTimezone()))).build(); } else { // standard repeat forever trigger if(l_mp.getFrom_time() == 0) { trigger = newTrigger().withIdentity("trigger", uid + l_mp.getCustomId() + System.currentTimeMillis()).startNow().withSchedule(simpleSchedule().withIntervalInSeconds(l_mp.getQuery_interval()).repeatForever().withMisfireHandlingInstructionFireNow()).build(); cinterval = " every " + l_mp.getQuery_interval() + " seconds"; } // daterange trigger, ignore missfire else { long a = l_mp.getFrom_time(); long b = l_mp.getTo_time(); Date startDate = new Date(a*1000L); Date endDate = new Date(b*1000L); long cur = (System.currentTimeMillis() / 1000L); trigger = newTrigger().withIdentity("trigger", uid + l_mp.getCustomId() + System.currentTimeMillis()).startAt(startDate).withSchedule(simpleSchedule().withIntervalInSeconds(l_mp.getQuery_interval()).repeatForever().withMisfireHandlingInstructionIgnoreMisfires()).endAt(endDate).build(); cinterval = " every " + l_mp.getQuery_interval() + " seconds from " + startDate + " to " + endDate; } } //Trigger trigger = newTrigger().withIdentity("trigger", uid + l_mp.get_NodeId() + System.currentTimeMillis()).startNow().withSchedule(simpleSchedule().withIntervalInMinutes(l_mp.get .repeatForever().withMisfireHandlingInstructionFireNow()).build(); JobDetail job = newJob(CustomJob.class).withIdentity(l_mp.getCustomId() + "", l_mp.getUser_id().toString()).usingJobData("customId", l_mp.getCustomId()).build(); try { com.clavain.muninmxcd.sched_custom.scheduleJob(job, trigger); logger.info("Scheduled CustomJob for custom interval: " + l_mp.getCustomId() + " with interval " + cinterval); retval = true; com.clavain.muninmxcd.v_cinterval_plugins.add(l_mp); } catch (Exception ex) { logger.error("Unable to Schedule Job for custom interval:" + l_mp.getCustomId() + " with interval " + cinterval); logger.error(ex); } } return retval; } public static ArrayList<ScheduledJob> getScheduledJobs() { ArrayList<ScheduledJob> retval = new ArrayList<>(); try { for (String groupName : com.clavain.muninmxcd.sched.getJobGroupNames()) { for (JobKey jobKey : com.clavain.muninmxcd.sched.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) { String jobName = jobKey.getName(); String jobGroup = jobKey.getGroup(); //get job's trigger List<Trigger> triggers = (List<Trigger>) com.clavain.muninmxcd.sched.getTriggersOfJob(jobKey); Date nextFireTime = triggers.get(0).getNextFireTime(); ScheduledJob sj = new ScheduledJob(); sj.setJobName(jobName); sj.setGroupName(jobGroup); sj.setNextFireTime(nextFireTime.toString()); retval.add(sj); } } } catch (SchedulerException ex) { logger.error("Error in getScheduledJobs(): " + ex.getLocalizedMessage()); } return retval; } public static ArrayList<ScheduledJob> getScheduledCustomJobs() { ArrayList<ScheduledJob> retval = new ArrayList<>(); try { for (String groupName : com.clavain.muninmxcd.sched_custom.getJobGroupNames()) { for (JobKey jobKey : com.clavain.muninmxcd.sched_custom.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) { String jobName = jobKey.getName(); String jobGroup = jobKey.getGroup(); //get job's trigger List<Trigger> triggers = (List<Trigger>) com.clavain.muninmxcd.sched_custom.getTriggersOfJob(jobKey); Date nextFireTime = triggers.get(0).getNextFireTime(); ScheduledJob sj = new ScheduledJob(); sj.setJobName(jobName); sj.setGroupName(jobGroup); sj.setNextFireTime(nextFireTime.toString()); retval.add(sj); } } } catch (SchedulerException ex) { logger.error("Error in getScheduledJobs(): " + ex.getLocalizedMessage()); } return retval; } }
fixed refresh bug reported by levent
src/com/clavain/utils/Quartz.java
fixed refresh bug reported by levent
<ide><path>rc/com/clavain/utils/Quartz.java <ide> // crontab trigger <ide> if(!l_mp.getCrontab().equals("false")) <ide> { <del> trigger = newTrigger().withIdentity("trigger", uid + l_mp.getCustomId() + System.currentTimeMillis()).withSchedule(CronScheduleBuilder.cronSchedule(l_mp.getCrontab()).withMisfireHandlingInstructionFireAndProceed().inTimeZone(TimeZone.getTimeZone(l_mp.getTimezone()))).build(); <add> // fixed start/end ? <add> if(l_mp.getFrom_time() == 0) <add> { <add> trigger = newTrigger().withIdentity("trigger", uid + l_mp.getCustomId() + System.currentTimeMillis()).withSchedule(CronScheduleBuilder.cronSchedule(l_mp.getCrontab()).withMisfireHandlingInstructionFireAndProceed().inTimeZone(TimeZone.getTimeZone(l_mp.getTimezone()))).build(); <add> cinterval = " every " + l_mp.getQuery_interval() + " seconds with crontab: " + l_mp.getCrontab(); <add> } <add> else <add> { <add> long a = l_mp.getFrom_time(); <add> long b = l_mp.getTo_time(); <add> <add> Date startDate = new Date(a*1000L); <add> Date endDate = new Date(b*1000L); <add> trigger = newTrigger().withIdentity("trigger", uid + l_mp.getCustomId() + System.currentTimeMillis()).startAt(startDate).withSchedule(CronScheduleBuilder.cronSchedule(l_mp.getCrontab()).withMisfireHandlingInstructionFireAndProceed().inTimeZone(TimeZone.getTimeZone(l_mp.getTimezone()))).endAt(endDate).build(); <add> cinterval = " every " + l_mp.getQuery_interval() + " seconds with crontab: " + l_mp.getCrontab() + " from " + startDate + " to " + endDate; <add> <add> } <ide> } <ide> else <ide> { <ide> } catch (Exception ex) <ide> { <ide> logger.error("Unable to Schedule Job for custom interval:" + l_mp.getCustomId() + " with interval " + cinterval); <del> logger.error(ex); <add> logger.error(ex.getLocalizedMessage()); <ide> } <ide> <ide> } <ide> String jobGroup = jobKey.getGroup(); <ide> <ide> //get job's trigger <add> <ide> List<Trigger> triggers = (List<Trigger>) com.clavain.muninmxcd.sched.getTriggersOfJob(jobKey); <ide> Date nextFireTime = triggers.get(0).getNextFireTime(); <ide> ScheduledJob sj = new ScheduledJob();
Java
apache-2.0
d6b989819e702bcc9628f06ba6bbaf96928f3b75
0
ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE
package uk.ac.ebi.quickgo.annotation.controller; import uk.ac.ebi.quickgo.annotation.AnnotationREST; import uk.ac.ebi.quickgo.annotation.common.AnnotationRepository; import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocMocker; import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocument; import uk.ac.ebi.quickgo.annotation.service.search.SearchServiceConfig; import uk.ac.ebi.quickgo.common.solr.TemporarySolrDataStore; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static uk.ac.ebi.quickgo.annotation.controller.ResponseVerifier.*; import static uk.ac.ebi.quickgo.annotation.model.AnnotationRequest.DEFAULT_ENTRIES_PER_PAGE; /** * RESTful end point for Annotations * @author Tony Wardell * Date: 26/04/2016 * Time: 14:21 * Created with IntelliJ IDEA. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = {AnnotationREST.class}) @WebAppConfiguration public class AnnotationControllerIT { // temporary data store for solr's data, which is automatically cleaned on exit @ClassRule public static final TemporarySolrDataStore solrDataStore = new TemporarySolrDataStore(); private static final int NUMBER_OF_GENERIC_DOCS = 3; private static final String ASSIGNED_BY_PARAM = "assignedBy"; private static final String GO_EVIDENCE_PARAM = "goEvidence"; private static final String ECO_ID = "ecoId"; private static final String PAGE_PARAM = "page"; private static final String LIMIT_PARAM = "limit"; private static final String TAXON_ID_PARAM = "taxon"; private static final String UNAVAILABLE_ASSIGNED_BY = "ZZZZZ"; private MockMvc mockMvc; private List<AnnotationDocument> genericDocs; private static final String RESOURCE_URL = "/QuickGO/services/annotation"; @Autowired private WebApplicationContext webApplicationContext; @Autowired private AnnotationRepository repository; @Before public void setup() { repository.deleteAll(); mockMvc = MockMvcBuilders. webAppContextSetup(webApplicationContext) .build(); genericDocs = createGenericDocs(NUMBER_OF_GENERIC_DOCS); repository.save(genericDocs); } //ASSIGNED BY @Test public void lookupAnnotationFilterByAssignedBySuccessfully() throws Exception { String geneProductId = "P99999"; String assignedBy = "ASPGD"; AnnotationDocument document = createDocWithAssignedBy(geneProductId, assignedBy); repository.save(document); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, assignedBy)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId)); } @Test public void lookupAnnotationFilterByMultipleAssignedBySuccessfully() throws Exception { String geneProductId1 = "P99999"; String assignedBy1 = "ASPGD"; AnnotationDocument document1 = createDocWithAssignedBy(geneProductId1, assignedBy1); repository.save(document1); String geneProductId2 = "P99998"; String assignedBy2 = "BHF-UCL"; AnnotationDocument document2 = createDocWithAssignedBy(geneProductId2, assignedBy2); repository.save(document2); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, assignedBy1 + "," + assignedBy2)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(2)) .andExpect(fieldsInAllResultsExist(2)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId1, geneProductId2)); } @Test public void lookupAnnotationFilterByRepetitionOfParmsSuccessfully() throws Exception { String geneProductId1 = "P99999"; String assignedBy1 = "ASPGD"; AnnotationDocument document1 = createDocWithAssignedBy(geneProductId1, assignedBy1); repository.save(document1); String geneProductId2 = "P99998"; String assignedBy2 = "BHF-UCL"; AnnotationDocument document2 = createDocWithAssignedBy(geneProductId2, assignedBy2); repository.save(document2); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(ASSIGNED_BY_PARAM, assignedBy1) .param(ASSIGNED_BY_PARAM, assignedBy2)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(2)) .andExpect(fieldsInAllResultsExist(2)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId1, geneProductId2)); } @Test public void lookupAnnotationFilterByInvalidAssignedBy() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, UNAVAILABLE_ASSIGNED_BY)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(0)); } @Test public void lookupAnnotationFilterByMultipleAssignedByOneCorrectAndOneUnavailable() throws Exception { String geneProductId = "P99999"; String assignedBy = "ASPGD"; AnnotationDocument document = createDocWithAssignedBy(geneProductId, assignedBy); repository.save(document); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, UNAVAILABLE_ASSIGNED_BY + "," + assignedBy)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId)); } @Test public void invalidAssignedByThrowsAnError() throws Exception { String invalidAssignedBy = "_ASPGD"; ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, invalidAssignedBy)); response.andDo(print()) .andExpect(status().isBadRequest()); } //TAXON ID @Test public void lookupAnnotationFilterByTaxonIdSuccessfully() throws Exception { String geneProductId = "P99999"; int taxonId = 2; AnnotationDocument document = createDocWithTaxonId(geneProductId, taxonId); repository.save(document); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(TAXON_ID_PARAM, "2")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId)); } @Test public void lookupAnnotationFilterByMultipleTaxonIdsSuccessfully() throws Exception { String geneProductId1 = "P99999"; int taxonId1 = 2; AnnotationDocument document1 = createDocWithTaxonId(geneProductId1, taxonId1); repository.save(document1); String geneProductId2 = "P99998"; int taxonId2 = 3; AnnotationDocument document2 = createDocWithTaxonId(geneProductId2, taxonId2); repository.save(document2); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(TAXON_ID_PARAM, String.valueOf(taxonId1)) .param(TAXON_ID_PARAM, String.valueOf(taxonId2))); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(2)) .andExpect(fieldsInAllResultsExist(2)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId1, geneProductId2)); } @Test public void invalidTaxIdThrowsError() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(TAXON_ID_PARAM, "-2")); response.andDo(print()) .andExpect(status().isBadRequest()); } //---------- GoEvidence related tests. @Test public void lookupAnnotationFilterByGoEvidenceCodeBySuccessfully() throws Exception { String goEvidenceCode = "IEA"; ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM, goEvidenceCode)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(genericDocs.size())) .andExpect(fieldsInAllResultsExist(genericDocs.size())) .andExpect(atLeastOneResultHasItem(GO_EVIDENCE_FIELD, goEvidenceCode)); } @Test public void lookupAnnotationFilterByLowercaseGoEvidenceCodeBySuccessfully() throws Exception { String goEvidenceCode = "iea"; ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM, goEvidenceCode)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(genericDocs.size())) .andExpect(fieldsInAllResultsExist(genericDocs.size())) .andExpect(atLeastOneResultHasItem(GO_EVIDENCE_FIELD, goEvidenceCode.toUpperCase())); } @Test public void lookupAnnotationFilterByNonExistentGoEvidenceCodeReturnsNothing() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM, "ZZZ")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(0)); } @Test public void filterAnnotationsUsingMultipleGoEvidenceCodesSuccessfully() throws Exception { String goEvidenceCode = "IEA"; String goEvidenceCode1 = "BSS"; AnnotationDocument annoDoc1 = AnnotationDocMocker.createAnnotationDoc(createId(999)); annoDoc1.goEvidence = goEvidenceCode1; repository.save(annoDoc1); String goEvidenceCode2 = "AWE"; AnnotationDocument annoDoc2 = AnnotationDocMocker.createAnnotationDoc(createId(998)); annoDoc2.goEvidence = goEvidenceCode2; repository.save(annoDoc2); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM, "IEA,BSS,AWE,PEG")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(genericDocs.size()+2)) .andExpect(fieldsInAllResultsExist(genericDocs.size()+2)) .andExpect(itemExistsExpectedTimes(GO_EVIDENCE_FIELD, goEvidenceCode1, 1)) .andExpect(itemExistsExpectedTimes(GO_EVIDENCE_FIELD, goEvidenceCode2, 1)) .andExpect(itemExistsExpectedTimes(GO_EVIDENCE_FIELD, goEvidenceCode, genericDocs.size())); } @Test public void invalidGoEvidenceThrowsException() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM, "BlahBlah")); response.andExpect(status().isBadRequest()) .andExpect(contentTypeToBeJson()); } //---------- ECO id @Test public void filterByEcoIdBySuccessfully() throws Exception { String ecoID = "ECO:0000256"; ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ECO_ID, ecoID)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(genericDocs.size())) .andExpect(fieldsInAllResultsExist(genericDocs.size())) .andExpect(atLeastOneResultHasItem(ECO_ID, ecoID)); } @Test public void filterByNonExistentEcoIdReturnsZeroResults() throws Exception { String ecoID = "ECO:0000999"; ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ECO_ID, ecoID)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(0)); } //---------- Page related tests. @Test public void retrievesSecondPageOfAllEntriesRequest() throws Exception { int totalEntries = 60; repository.deleteAll(); repository.save(createGenericDocs(totalEntries)); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(PAGE_PARAM, "2")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(totalEntries)) .andExpect(resultsInPage(DEFAULT_ENTRIES_PER_PAGE)) .andExpect( pageInfoMatches( 2, totalPages(totalEntries, DEFAULT_ENTRIES_PER_PAGE), DEFAULT_ENTRIES_PER_PAGE) ); } @Test public void pageRequestEqualToAvailablePagesReturns200() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(PAGE_PARAM, "1")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(genericDocs.size())) .andExpect( pageInfoMatches( 1, totalPages(genericDocs.size(), DEFAULT_ENTRIES_PER_PAGE), DEFAULT_ENTRIES_PER_PAGE) ); } @Test public void pageRequestOfZeroAndResultsAvailableReturns400() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(PAGE_PARAM, "0")); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void pageRequestHigherThanAvailablePagesReturns400() throws Exception { repository.deleteAll(); int existingPages = 4; createGenericDocs(SearchServiceConfig.MAX_PAGE_RESULTS * existingPages); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(PAGE_PARAM, String.valueOf(existingPages + 1))); response.andDo(print()) .andExpect(status().isBadRequest()); } //---------- Limit related tests. @Test public void limitForPageExceedsMaximumAllowed() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(LIMIT_PARAM, "101")); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void limitForPageWithinMaximumAllowed() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(LIMIT_PARAM, "100")); response.andExpect(status().isOk()) .andExpect(totalNumOfResults(genericDocs.size())) .andExpect(pageInfoMatches(1, 1, 100)); } @Test public void limitForPageThrowsErrorWhenNegative() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search") .param(LIMIT_PARAM, "-20")); response.andDo(print()) .andExpect(status().isBadRequest()); } private AnnotationDocument createDocWithAssignedBy(String geneProductId, String assignedBy) { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId); doc.assignedBy = assignedBy; return doc; } private AnnotationDocument createDocWithTaxonId(String geneProductId, int taxonId) { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId); doc.taxonId = taxonId; return doc; } private List<AnnotationDocument> createGenericDocs(int n) { return IntStream.range(0, n) .mapToObj(i -> AnnotationDocMocker.createAnnotationDoc(createId(i))).collect (Collectors.toList()); } private String createId(int idNum) { return String.format("A0A%03d", idNum); } private int totalPages(int totalEntries, int resultsPerPage) { return (int) Math.ceil(totalEntries / resultsPerPage) + 1; } }
annotation-rest/src/test/java/uk/ac/ebi/quickgo/annotation/controller/AnnotationControllerIT.java
package uk.ac.ebi.quickgo.annotation.controller; import uk.ac.ebi.quickgo.annotation.AnnotationREST; import uk.ac.ebi.quickgo.annotation.common.AnnotationRepository; import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocMocker; import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocument; import uk.ac.ebi.quickgo.annotation.service.search.SearchServiceConfig; import uk.ac.ebi.quickgo.common.solr.TemporarySolrDataStore; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static uk.ac.ebi.quickgo.annotation.controller.ResponseVerifier.*; import static uk.ac.ebi.quickgo.annotation.model.AnnotationRequest.DEFAULT_ENTRIES_PER_PAGE; /** * RESTful end point for Annotations * @author Tony Wardell * Date: 26/04/2016 * Time: 14:21 * Created with IntelliJ IDEA. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = {AnnotationREST.class}) @WebAppConfiguration public class AnnotationControllerIT { // temporary data store for solr's data, which is automatically cleaned on exit @ClassRule public static final TemporarySolrDataStore solrDataStore = new TemporarySolrDataStore(); private static final int NUMBER_OF_GENERIC_DOCS = 3; private static final String ASSIGNED_BY_PARAM = "assignedBy"; private static final String GO_EVIDENCE_PARAM = "goEvidence"; private static final String PAGE_PARAM = "page"; private static final String LIMIT_PARAM = "limit"; private static final String TAXON_ID_PARAM = "taxon"; private static final String UNAVAILABLE_ASSIGNED_BY = "ZZZZZ"; private MockMvc mockMvc; private List<AnnotationDocument> genericDocs; private static final String RESOURCE_URL = "/QuickGO/services/annotation"; @Autowired private WebApplicationContext webApplicationContext; @Autowired private AnnotationRepository repository; @Before public void setup() { repository.deleteAll(); mockMvc = MockMvcBuilders. webAppContextSetup(webApplicationContext) .build(); genericDocs = createGenericDocs(NUMBER_OF_GENERIC_DOCS); repository.save(genericDocs); } //ASSIGNED BY @Test public void lookupAnnotationFilterByAssignedBySuccessfully() throws Exception { String geneProductId = "P99999"; String assignedBy = "ASPGD"; AnnotationDocument document = createDocWithAssignedBy(geneProductId, assignedBy); repository.save(document); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, assignedBy)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId)); } @Test public void lookupAnnotationFilterByMultipleAssignedBySuccessfully() throws Exception { String geneProductId1 = "P99999"; String assignedBy1 = "ASPGD"; AnnotationDocument document1 = createDocWithAssignedBy(geneProductId1, assignedBy1); repository.save(document1); String geneProductId2 = "P99998"; String assignedBy2 = "BHF-UCL"; AnnotationDocument document2 = createDocWithAssignedBy(geneProductId2, assignedBy2); repository.save(document2); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, assignedBy1 + "," + assignedBy2)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(2)) .andExpect(fieldsInAllResultsExist(2)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId1, geneProductId2)); } @Test public void lookupAnnotationFilterByRepetitionOfParmsSuccessfully() throws Exception { String geneProductId1 = "P99999"; String assignedBy1 = "ASPGD"; AnnotationDocument document1 = createDocWithAssignedBy(geneProductId1, assignedBy1); repository.save(document1); String geneProductId2 = "P99998"; String assignedBy2 = "BHF-UCL"; AnnotationDocument document2 = createDocWithAssignedBy(geneProductId2, assignedBy2); repository.save(document2); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(ASSIGNED_BY_PARAM, assignedBy1) .param(ASSIGNED_BY_PARAM, assignedBy2)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(2)) .andExpect(fieldsInAllResultsExist(2)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId1, geneProductId2)); } @Test public void lookupAnnotationFilterByInvalidAssignedBy() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, UNAVAILABLE_ASSIGNED_BY)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(0)); } @Test public void lookupAnnotationFilterByMultipleAssignedByOneCorrectAndOneUnavailable() throws Exception { String geneProductId = "P99999"; String assignedBy = "ASPGD"; AnnotationDocument document = createDocWithAssignedBy(geneProductId, assignedBy); repository.save(document); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, UNAVAILABLE_ASSIGNED_BY + "," + assignedBy)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId)); } @Test public void invalidAssignedByThrowsAnError() throws Exception { String invalidAssignedBy = "_ASPGD"; ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, invalidAssignedBy)); response.andDo(print()) .andExpect(status().isBadRequest()); } //TAXON ID @Test public void lookupAnnotationFilterByTaxonIdSuccessfully() throws Exception { String geneProductId = "P99999"; int taxonId = 2; AnnotationDocument document = createDocWithTaxonId(geneProductId, taxonId); repository.save(document); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(TAXON_ID_PARAM, "2")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId)); } @Test public void lookupAnnotationFilterByMultipleTaxonIdsSuccessfully() throws Exception { String geneProductId1 = "P99999"; int taxonId1 = 2; AnnotationDocument document1 = createDocWithTaxonId(geneProductId1, taxonId1); repository.save(document1); String geneProductId2 = "P99998"; int taxonId2 = 3; AnnotationDocument document2 = createDocWithTaxonId(geneProductId2, taxonId2); repository.save(document2); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(TAXON_ID_PARAM, String.valueOf(taxonId1)) .param(TAXON_ID_PARAM, String.valueOf(taxonId2))); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(2)) .andExpect(fieldsInAllResultsExist(2)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId1, geneProductId2)); } @Test public void invalidTaxIdThrowsError() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(TAXON_ID_PARAM, "-2")); response.andDo(print()) .andExpect(status().isBadRequest()); } //---------- GoEvidence related tests. @Test public void lookupAnnotationFilterByGoEvidenceCodeBySuccessfully() throws Exception { String goEvidenceCode = "IEA"; ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM, goEvidenceCode)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(genericDocs.size())) .andExpect(fieldsInAllResultsExist(genericDocs.size())) .andExpect(atLeastOneResultHasItem(GO_EVIDENCE_FIELD, goEvidenceCode)); } @Test public void lookupAnnotationFilterByLowercaseGoEvidenceCodeBySuccessfully() throws Exception { String goEvidenceCode = "iea"; ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM, goEvidenceCode)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(genericDocs.size())) .andExpect(fieldsInAllResultsExist(genericDocs.size())) .andExpect(atLeastOneResultHasItem(GO_EVIDENCE_FIELD, goEvidenceCode.toUpperCase())); } @Test public void lookupAnnotationFilterByNonExistentGoEvidenceCodeReturnsNothing() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM, "ZZZ")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(0)); } @Test public void filterAnnotationsUsingMultipleGoEvidenceCodesSuccessfully() throws Exception { String goEvidenceCode = "IEA"; String goEvidenceCode1 = "BSS"; AnnotationDocument annoDoc1 = AnnotationDocMocker.createAnnotationDoc(createId(999)); annoDoc1.goEvidence = goEvidenceCode1; repository.save(annoDoc1); String goEvidenceCode2 = "AWE"; AnnotationDocument annoDoc2 = AnnotationDocMocker.createAnnotationDoc(createId(998)); annoDoc2.goEvidence = goEvidenceCode2; repository.save(annoDoc2); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM, "IEA,BSS,AWE,PEG")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(genericDocs.size()+2)) .andExpect(fieldsInAllResultsExist(genericDocs.size()+2)) .andExpect(itemExistsExpectedTimes(GO_EVIDENCE_FIELD, goEvidenceCode1, 1)) .andExpect(itemExistsExpectedTimes(GO_EVIDENCE_FIELD, goEvidenceCode2, 1)) .andExpect(itemExistsExpectedTimes(GO_EVIDENCE_FIELD, goEvidenceCode, genericDocs.size())); } @Test public void invalidGoEvidenceThrowsException() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM, "BlahBlah")); response.andExpect(status().isBadRequest()) .andExpect(contentTypeToBeJson()); } //---------- Page related tests. @Test public void retrievesSecondPageOfAllEntriesRequest() throws Exception { int totalEntries = 60; repository.deleteAll(); repository.save(createGenericDocs(totalEntries)); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(PAGE_PARAM, "2")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(totalEntries)) .andExpect(resultsInPage(DEFAULT_ENTRIES_PER_PAGE)) .andExpect( pageInfoMatches( 2, totalPages(totalEntries, DEFAULT_ENTRIES_PER_PAGE), DEFAULT_ENTRIES_PER_PAGE) ); } @Test public void pageRequestEqualToAvailablePagesReturns200() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(PAGE_PARAM, "1")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(genericDocs.size())) .andExpect( pageInfoMatches( 1, totalPages(genericDocs.size(), DEFAULT_ENTRIES_PER_PAGE), DEFAULT_ENTRIES_PER_PAGE) ); } @Test public void pageRequestOfZeroAndResultsAvailableReturns400() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(PAGE_PARAM, "0")); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void pageRequestHigherThanAvailablePagesReturns400() throws Exception { repository.deleteAll(); int existingPages = 4; createGenericDocs(SearchServiceConfig.MAX_PAGE_RESULTS * existingPages); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(PAGE_PARAM, String.valueOf(existingPages + 1))); response.andDo(print()) .andExpect(status().isBadRequest()); } //---------- Limit related tests. @Test public void limitForPageExceedsMaximumAllowed() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(LIMIT_PARAM, "101")); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void limitForPageWithinMaximumAllowed() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(LIMIT_PARAM, "100")); response.andExpect(status().isOk()) .andExpect(totalNumOfResults(genericDocs.size())) .andExpect(pageInfoMatches(1, 1, 100)); } @Test public void limitForPageThrowsErrorWhenNegative() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search") .param(LIMIT_PARAM, "-20")); response.andDo(print()) .andExpect(status().isBadRequest()); } private AnnotationDocument createDocWithAssignedBy(String geneProductId, String assignedBy) { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId); doc.assignedBy = assignedBy; return doc; } private AnnotationDocument createDocWithTaxonId(String geneProductId, int taxonId) { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId); doc.taxonId = taxonId; return doc; } private List<AnnotationDocument> createGenericDocs(int n) { return IntStream.range(0, n) .mapToObj(i -> AnnotationDocMocker.createAnnotationDoc(createId(i))).collect (Collectors.toList()); } private String createId(int idNum) { return String.format("A0A%03d", idNum); } private int totalPages(int totalEntries, int resultsPerPage) { return (int) Math.ceil(totalEntries / resultsPerPage) + 1; } }
Add Eco Id.
annotation-rest/src/test/java/uk/ac/ebi/quickgo/annotation/controller/AnnotationControllerIT.java
Add Eco Id.
<ide><path>nnotation-rest/src/test/java/uk/ac/ebi/quickgo/annotation/controller/AnnotationControllerIT.java <ide> <ide> private static final String ASSIGNED_BY_PARAM = "assignedBy"; <ide> private static final String GO_EVIDENCE_PARAM = "goEvidence"; <add> private static final String ECO_ID = "ecoId"; <ide> private static final String PAGE_PARAM = "page"; <ide> private static final String LIMIT_PARAM = "limit"; <ide> private static final String TAXON_ID_PARAM = "taxon"; <ide> response.andExpect(status().isBadRequest()) <ide> .andExpect(contentTypeToBeJson()); <ide> <add> } <add> <add> //---------- ECO id <add> <add> @Test <add> public void filterByEcoIdBySuccessfully() throws Exception { <add> String ecoID = "ECO:0000256"; <add> ResultActions response = mockMvc.perform( <add> get(RESOURCE_URL + "/search").param(ECO_ID, ecoID)); <add> <add> response.andExpect(status().isOk()) <add> .andExpect(contentTypeToBeJson()) <add> .andExpect(totalNumOfResults(genericDocs.size())) <add> .andExpect(fieldsInAllResultsExist(genericDocs.size())) <add> .andExpect(atLeastOneResultHasItem(ECO_ID, ecoID)); <add> } <add> <add> <add> @Test <add> public void filterByNonExistentEcoIdReturnsZeroResults() throws Exception { <add> String ecoID = "ECO:0000999"; <add> ResultActions response = mockMvc.perform( <add> get(RESOURCE_URL + "/search").param(ECO_ID, ecoID)); <add> <add> response.andDo(print()) <add> .andExpect(status().isOk()) <add> .andExpect(contentTypeToBeJson()) <add> .andExpect(totalNumOfResults(0)); <ide> } <ide> <ide> //---------- Page related tests.
Java
mit
9ba806a5b20a3d0dcb522c75c00475f7afbbe441
0
mrkamel/spelling,mrkamel/spelling
package com.flakks.spelling; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; class Connection extends Thread { private Socket socket; public Connection(Socket socket) { this.socket = socket; } public void run() { try { try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream(), "UTF-8"); writer.write(new RequestHandler(bufferedReader.readLine()).process()); writer.write("\n"); writer.flush(); } finally { socket.close(); } } catch(IOException e) { System.out.println(e); e.printStackTrace(); } } } public class Server { ServerSocket serverSocket; public void start() throws IOException { serverSocket = new ServerSocket(12182, 1024, InetAddress.getByName("127.0.0.1")); while(true) { new Connection(serverSocket.accept()).start(); } } }
src/main/java/com/flakks/spelling/Server.java
package com.flakks.spelling; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; class Connection extends Thread { private Socket socket; public Connection(Socket socket) { this.socket = socket; } public void run() { try { try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream()); writer.write(new RequestHandler(bufferedReader.readLine()).process()); writer.write("\n"); writer.flush(); } finally { socket.close(); } } catch(IOException e) { System.out.println(e); e.printStackTrace(); } } } public class Server { ServerSocket serverSocket; public void start() throws IOException { serverSocket = new ServerSocket(12182, 1024, InetAddress.getByName("127.0.0.1")); while(true) { new Connection(serverSocket.accept()).start(); } } }
Encoding fixes
src/main/java/com/flakks/spelling/Server.java
Encoding fixes
<ide><path>rc/main/java/com/flakks/spelling/Server.java <ide> public void run() { <ide> try { <ide> try { <del> BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); <del> OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream()); <add> BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); <add> OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream(), "UTF-8"); <ide> <ide> writer.write(new RequestHandler(bufferedReader.readLine()).process()); <ide> writer.write("\n");
Java
apache-2.0
ff6dd39aab4e5c9359ceaaab688b1bd2fedb6ee2
0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
/* * Copyright 2016-2018 shardingsphere.io. * <p> * 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. * </p> */ package io.shardingsphere.core.parsing.antlr.extractor.statement.handler; import com.google.common.base.Optional; import io.shardingsphere.core.parsing.antlr.extractor.statement.handler.result.ExtractResult; import io.shardingsphere.core.parsing.antlr.extractor.statement.handler.result.SQLTokenExtractResult; import io.shardingsphere.core.parsing.antlr.extractor.statement.util.ASTUtils; import io.shardingsphere.core.parsing.parser.sql.SQLStatement; import io.shardingsphere.core.parsing.parser.token.IndexToken; import io.shardingsphere.core.util.SQLUtil; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; /** * Rename index extract handler. * * @author duhongjun */ public final class RenameIndexExtractHandler implements ASTExtractHandler,ASTExtractHandler1 { @Override public void extract(final ParserRuleContext ancestorNode, final SQLStatement statement) { Optional<ParserRuleContext> renameIndexNode = ASTUtils.findFirstChildNode(ancestorNode, RuleName.RENAME_INDEX); if (!renameIndexNode.isPresent() || 4 > renameIndexNode.get().getChildCount()) { return; } ParseTree oldIndexNode = renameIndexNode.get().getChild(2); if (!(oldIndexNode instanceof ParserRuleContext)) { return; } ParseTree newIndexNode = renameIndexNode.get().getChild(4); if (!(newIndexNode instanceof ParserRuleContext)) { return; } statement.getSQLTokens().add(getIndexToken(statement, (ParserRuleContext) oldIndexNode)); statement.getSQLTokens().add(getIndexToken(statement, (ParserRuleContext) newIndexNode)); } private IndexToken getIndexToken(final SQLStatement statement, final ParserRuleContext indexNode) { return new IndexToken(indexNode.getStop().getStartIndex(), SQLUtil.getNameWithoutSchema(indexNode.getText()), statement.getTables().getSingleTableName()); } @Override public ExtractResult extract(ParserRuleContext ancestorNode) { Optional<ParserRuleContext> renameIndexNode = ASTUtils.findFirstChildNode(ancestorNode, RuleName.RENAME_INDEX); if (!renameIndexNode.isPresent() || 4 > renameIndexNode.get().getChildCount()) { return null; } ParseTree oldIndexNode = renameIndexNode.get().getChild(2); if (!(oldIndexNode instanceof ParserRuleContext)) { return null; } ParseTree newIndexNode = renameIndexNode.get().getChild(4); if (!(newIndexNode instanceof ParserRuleContext)) { return null; } SQLTokenExtractResult extractResult = new SQLTokenExtractResult(); extractResult.getSqlTokens().add(getIndexToken((ParserRuleContext) oldIndexNode)); extractResult.getSqlTokens().add(getIndexToken((ParserRuleContext) newIndexNode)); return extractResult; } private IndexToken getIndexToken(final ParserRuleContext indexNode) { return new IndexToken(indexNode.getStop().getStartIndex(), SQLUtil.getNameWithoutSchema(indexNode.getText()), null); } }
sharding-core/src/main/java/io/shardingsphere/core/parsing/antlr/extractor/statement/handler/RenameIndexExtractHandler.java
/* * Copyright 2016-2018 shardingsphere.io. * <p> * 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. * </p> */ package io.shardingsphere.core.parsing.antlr.extractor.statement.handler; import com.google.common.base.Optional; import io.shardingsphere.core.parsing.antlr.extractor.statement.handler.result.ExtractResult; import io.shardingsphere.core.parsing.antlr.extractor.statement.handler.result.SQLTokenExtractResult; import io.shardingsphere.core.parsing.antlr.extractor.statement.util.ASTUtils; import io.shardingsphere.core.parsing.parser.sql.SQLStatement; import io.shardingsphere.core.parsing.parser.token.IndexToken; import io.shardingsphere.core.util.SQLUtil; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; /** * Rename index extract handler. * * @author duhongjun */ public final class RenameIndexExtractHandler implements ASTExtractHandler,ASTExtractHandler1 { @Override public void extract(final ParserRuleContext ancestorNode, final SQLStatement statement) { Optional<ParserRuleContext> renameIndexNode = ASTUtils.findFirstChildNode(ancestorNode, RuleName.RENAME_INDEX); if (!renameIndexNode.isPresent() || 4 > renameIndexNode.get().getChildCount()) { return; } ParseTree oldIndexNode = renameIndexNode.get().getChild(2); if (!(oldIndexNode instanceof ParserRuleContext)) { return; } ParseTree newIndexNode = renameIndexNode.get().getChild(4); if (!(newIndexNode instanceof ParserRuleContext)) { return; } statement.getSQLTokens().add(getIndexToken(statement, (ParserRuleContext) oldIndexNode)); statement.getSQLTokens().add(getIndexToken(statement, (ParserRuleContext) newIndexNode)); } private IndexToken getIndexToken(final SQLStatement statement, final ParserRuleContext indexNode) { return new IndexToken(indexNode.getStop().getStartIndex(), SQLUtil.getNameWithoutSchema(indexNode.getText()), statement.getTables().getSingleTableName()); } @Override public ExtractResult extract(ParserRuleContext ancestorNode) { SQLTokenExtractResult extractResult = new SQLTokenExtractResult(); Optional<ParserRuleContext> renameIndexNode = ASTUtils.findFirstChildNode(ancestorNode, RuleName.RENAME_INDEX); if (!renameIndexNode.isPresent() || 4 > renameIndexNode.get().getChildCount()) { return extractResult; } ParseTree oldIndexNode = renameIndexNode.get().getChild(2); if (!(oldIndexNode instanceof ParserRuleContext)) { return extractResult; } ParseTree newIndexNode = renameIndexNode.get().getChild(4); if (!(newIndexNode instanceof ParserRuleContext)) { return extractResult; } extractResult.getSqlTokens().add(getIndexToken((ParserRuleContext) oldIndexNode)); extractResult.getSqlTokens().add(getIndexToken((ParserRuleContext) newIndexNode)); return extractResult; } private IndexToken getIndexToken(final ParserRuleContext indexNode) { return new IndexToken(indexNode.getStop().getStartIndex(), SQLUtil.getNameWithoutSchema(indexNode.getText()), null); } }
extract nothing return null
sharding-core/src/main/java/io/shardingsphere/core/parsing/antlr/extractor/statement/handler/RenameIndexExtractHandler.java
extract nothing return null
<ide><path>harding-core/src/main/java/io/shardingsphere/core/parsing/antlr/extractor/statement/handler/RenameIndexExtractHandler.java <ide> <ide> @Override <ide> public ExtractResult extract(ParserRuleContext ancestorNode) { <del> SQLTokenExtractResult extractResult = new SQLTokenExtractResult(); <ide> Optional<ParserRuleContext> renameIndexNode = ASTUtils.findFirstChildNode(ancestorNode, RuleName.RENAME_INDEX); <ide> if (!renameIndexNode.isPresent() || 4 > renameIndexNode.get().getChildCount()) { <del> return extractResult; <add> return null; <ide> } <ide> ParseTree oldIndexNode = renameIndexNode.get().getChild(2); <ide> if (!(oldIndexNode instanceof ParserRuleContext)) { <del> return extractResult; <add> return null; <ide> } <ide> ParseTree newIndexNode = renameIndexNode.get().getChild(4); <ide> if (!(newIndexNode instanceof ParserRuleContext)) { <del> return extractResult; <add> return null; <ide> } <add> SQLTokenExtractResult extractResult = new SQLTokenExtractResult(); <ide> extractResult.getSqlTokens().add(getIndexToken((ParserRuleContext) oldIndexNode)); <ide> extractResult.getSqlTokens().add(getIndexToken((ParserRuleContext) newIndexNode)); <ide> return extractResult;
Java
mit
3b948a3f9a9e41bea92927fd18b2e9dbf163bd64
0
gitpitch/gitpitch,gitpitch/gitpitch,gitpitch/gitpitch
/* * MIT License * * Copyright (c) 2016 David Russell * * 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 com.gitpitch.models; import com.gitpitch.models.SlideshowModel; import com.gitpitch.utils.*; import com.gitpitch.services.ImageService; import com.gitpitch.services.VideoService; import com.gitpitch.services.GISTService; import com.gitpitch.services.ShortcutsService; import org.apache.commons.io.FilenameUtils; import com.google.inject.assistedinject.Assisted; import javax.annotation.Nullable; import play.Logger; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.inject.*; /* * Rendering model for PITCHME.md markdown. */ public class MarkdownModel implements Markdown { private final Logger.ALogger log = Logger.of(this.getClass()); private final ImageService imageService; private final VideoService videoService; private final GISTService gistService; private final ShortcutsService shortcutsService; private final MarkdownRenderer mrndr; private final String markdown; private String hSlideDelim = HSLIDE_DELIM_DEFAULT; private String vSlideDelim = VSLIDE_DELIM_DEFAULT; @Inject public MarkdownModel(ImageService imageService, VideoService videoService, GISTService gistService, ShortcutsService shortcutsService, @Nullable @Assisted MarkdownRenderer mrndr) { this.imageService = imageService; this.videoService = videoService; this.gistService = gistService; this.shortcutsService = shortcutsService; this.mrndr = mrndr; String consumed = null; if(mrndr != null) { String gitRawBase = mrndr.gitRawBase(); Path mdPath = mrndr.filePath(PITCHME_MD); File mdFile = mdPath.toFile(); if (mdFile.exists()) { Optional<SlideshowModel> ssmo = mrndr.ssm(); final PitchParams pp = ssmo.isPresent() ? ssmo.get().params() : null; final YAMLOptions yOpts = ssmo.isPresent() ? ssmo.get().options() : null; if(yOpts != null) { hSlideDelim = yOpts.hasHorzDelim(pp) ? yOpts.fetchHorzDelim(pp) : HSLIDE_DELIM_DEFAULT; vSlideDelim = yOpts.hasVertDelim(pp) ? yOpts.fetchVertDelim(pp) : VSLIDE_DELIM_DEFAULT; } try (Stream<String> stream = Files.lines(mdPath)) { consumed = stream.map(md -> { return process(md, pp, yOpts, gitRawBase); }).map(md -> { return processAnchors(md); }).collect(Collectors.joining("\n")); consumed = postProcess(consumed, pp, yOpts, gitRawBase); } catch (Exception mex) { log.warn("Markdown processing ex={}", mex); consumed = "PITCHME.md could not be parsed."; } } else { log.warn("Markdown file does not exist, {}", mdFile); } } this.markdown = consumed; } /* * Process text, image, video and gist content * in PITCHME.md for online viewing. */ private String process(String md, PitchParams pp, YAMLOptions yOpts, String gitRawBase) { md = processBackwardCompatDelim(md); if (slideDelimFound(md)) { /* * Clean only delimiter fragments of whitespace * noise before processing. Preserve end-of-line * characters on all non-delimiter fragments. */ md = md.trim(); if (videoDelimFound(md)) { /* * Inject slide specific video background: * * <!-- .slide: data-background-video="vidUrl" --> */ String videoBgUrl = videoService.extractBgUrl(md, gitRawBase, this); return new StringBuffer(delimiter(md)) .append(videoService.buildBackground(videoBgUrl)) .toString(); } else if (imageDelimFound(md)) { /* * Inject slide specific image background: * * <!-- .slide: data-background-image="imgUrl" --> */ String imageBgUrl = imageService.extractBgUrl(md, gitRawBase, this); String bgSize = (yOpts != null) ? yOpts.fetchImageBgSize(pp) : YAMLOptions.DEFAULT_BG_SIZE; return new StringBuffer(delimiter(md)) .append(imageService.buildBackground(pp, imageBgUrl, bgSize)) .toString(); } else if (gistDelimFound(md)) { String gist = new StringBuffer(gistService.build(md, pp, yOpts, this)).toString(); return gist; } if (yOpts != null && yOpts.hasImageBg()) { /* * Inject slideshow-wide background: * * <!-- .slide: data-background-image="imgUrl" --> */ return new StringBuffer(md) .append(imageService.buildBackground(pp, yOpts)) .toString(); } else { /* * No customization on slide delimiter or background, * return unmodified. */ return md; } } else if (markdownLinkFound(md)) { /* * Link found in markdown fragment, process. */ int delim = md.indexOf(MD_LINK_DELIM); if (delim == NOT_FOUND) { /* * Valid link syntax not found, return unmodified. */ return md; } else { /* * Valid link syntax found, now process link to * handle absolute, (GitHub) relative and video links. */ String splitLeft = md.substring(0, delim + 2); String splitRight = md.substring(delim + 2); /* * Clone and clean splitRight string to begin * extraction of the pitchLink. */ String pitchLink = cloneLink(splitRight); pitchLink = extractLink(pitchLink, gitRawBase); if (videoService.isVideo(pitchLink)) { return videoService.buildVideo(pitchLink); } else if (linkAbsolute(splitRight)) { return md; } else { return splitLeft + gitRawBase + splitRight; } } } else if(imageService.tagFound(md)) { String tagLink = imageService.tagLink(md); if (linkAbsolute(tagLink)) { return md; } else { String absTagLink = gitRawBase + tagLink; return md.replace(tagLink, absTagLink); } } else if(shortcutsService.fragmentFound(md)) { return shortcutsService.expandFragment(md); } else { /* * Link-free markdown, return unmodified. */ return md; } } public String produce() { return markdown; } /* * Process text, image, video and gist content * in PITCHME.md for offline viewing. */ public String offline(String md) { if (videoService.found(md)) { return videoService.offline(); } else if (gistMarkdown(md)) { return gistService.offline(); } else if (imageService.background(md)) { return imageService.buildBackgroundOffline(md); } else if (imageService.inline(md)) { /* * Link found in markdown fragment, process. */ int delim = md.indexOf(MD_LINK_DELIM); if (delim == NOT_FOUND) { /* * Valid link syntax not found, return unmodified. */ return md; } else { /* * Valid link syntax found, now process link to * handle absolute, (GitHub) relative and video links. */ String splitLeft = md.substring(0, delim + 2); String splitRight = md.substring(delim + 2); /* * Clone and clean splitRight string to begin * extraction of the pitchLink. */ String pitchLink = cloneLink(splitRight); pitchLink = extractLink(pitchLink, null); String imageName = FilenameUtils.getName(pitchLink); return imageService.buildInlineOffline(imageName); } } else if(imageService.tagFound(md)) { return imageService.buildTagOffline(md); } else { /* * Link-free markdown, return unmodified. */ return md; } } /* * Return image asset URL from Markdown fragment. */ public String offlineAssets(String md) { if (imageService.background(md)) { String frag = md.substring(MD_IMAGE_OPEN.length()); String url = frag.substring(0, frag.indexOf("\"")); return url; } else if (imageService.inline(md)) { /* * Link found in markdown fragment, process. */ int delim = md.indexOf(MD_LINK_DELIM); if (delim == NOT_FOUND) { /* * Valid link syntax not found, return unmodified. */ return null; } else { /* * Valid link syntax found, now process link to * handle absolute, (GitHub) relative and video links. */ String splitLeft = md.substring(0, delim + 2); String splitRight = md.substring(delim + 2); /* * Clone and clean splitRight string to begin * extraction of the pitchLink. */ String pitchLink = cloneLink(splitRight); int spaceIdx = pitchLink.indexOf(MD_LINK_SPACE); int brcktIdx = pitchLink.indexOf(MD_LINK_BRCKT); String origLink = null; if (spaceIdx == NOT_FOUND || spaceIdx > brcktIdx) { origLink = pitchLink.substring(0, brcktIdx); } else { origLink = pitchLink.substring(0, spaceIdx); } return origLink; } } if(imageService.tagFound(md)) { /* * Img tag found in markdown fragment, process. */ return imageService.tagLink(md); } else { return null; } } private boolean imageDelimFound(String md) { return md.startsWith(horizImageDelim()) || md.startsWith(vertImageDelim()); } private boolean videoDelimFound(String md) { return md.startsWith(horizVideoDelim()) || md.startsWith(vertVideoDelim()); } private boolean gistDelimFound(String md) { return md.startsWith(horizGISTDelim()) || md.startsWith(vertGISTDelim()); } private String delimiter(String md) { return (md.startsWith(hSlideDelim)) ? horizDelim() : vertDelim(); } private boolean slideDelimFound(String md) { return md.startsWith(horizDelim()) || md.startsWith(vertDelim()); } private boolean markdownLinkFound(String md) { return md.startsWith(MD_LINK_OPEN); } private boolean gistMarkdown(String md) { return md.contains(DATA_GIST_ATTR); } private String cloneLink(String link) { String cloned = new String(link); /* * Strip slash prefix from relative links. */ if (cloned.startsWith(MD_LINK_SLASH)) { return cloned.substring(1); } else { return cloned; } } private String extractLink(String link, String gitRawBase) { try { int spaceIdx = link.indexOf(MD_LINK_SPACE); int brcktIdx = link.indexOf(MD_LINK_BRCKT); String origLink = null; if (spaceIdx == NOT_FOUND || spaceIdx > brcktIdx) { origLink = link.substring(0, brcktIdx); } else { origLink = link.substring(0, spaceIdx); } if (linkAbsolute(link)) { link = origLink; } else { link = gitRawBase + origLink; } return link; } catch (Exception lex) { log.warn("extractLink: link={}, ex={}", link, lex); } return null; } /* * Ensure all regular Markdown links are upgraded to * HTML anchors with target=_blank in order to * open from within embedded GitPitch iFrame. */ private String processAnchors(String md) { try { if(linkAbsolute(md)) { return buildAnchor(md.trim(), md.trim()); } else { boolean moreAnchors = md.contains(MD_ANCHOR_OPEN); while(moreAnchors) { if(md.contains(MD_ANCHOR_OPEN)) { int anchorStart = md.indexOf(MD_ANCHOR_OPEN); int anchorDelim = md.indexOf(MD_LINK_DELIM, anchorStart); // Regular Markdown Link not Markdown Image Link. if(anchorDelim != -1 && (anchorStart == 0 || !md.substring(anchorStart-1) .startsWith(MD_LINK_OPEN))) { int anchorEnd = md.indexOf(MD_LINK_BRCKT, anchorDelim); String title = md.substring(anchorStart+1, anchorDelim); String link = md.substring(anchorDelim+2, anchorEnd); String anchor = buildAnchor(title, link); String mdLeft = md.substring(0, anchorStart); String mdRight = md.substring(anchorEnd + 1); md = mdLeft + anchor + mdRight; } else { moreAnchors = false; } } else { moreAnchors = false; } } } } catch(Exception tex) { return md; } return md; } private String buildAnchor(String title, String link) { return new StringBuffer(HTML_ANCHOR_OPEN) .append(link) .append(HTML_ANCHOR_MID) .append(title) .append(HTML_ANCHOR_CLOSE) .toString(); } private String postProcess(String md, PitchParams pp, YAMLOptions yOpts, String gitRawBase) { if (yOpts != null && yOpts.hasImageBg()) { if (!delimOnFirstSlide(md)) { /* * Inject slideshow-wide background for * implicit delim on first slide in the slideshow. */ md = imageService.buildBackground(pp, yOpts) + md; } } if (delimOnFirstSlide(md)) { int nIndex = md.indexOf(MD_SPACER); if (nIndex > 0) { String slimMd = md.substring(nIndex); md = slimMd; } } return md; } private boolean delimOnFirstSlide(String md) { return (md.startsWith(horizDelim()) || md.startsWith(vertDelim())); } public boolean isHorizontal(String md) { return (md.startsWith(horizDelim())) ? true : false; } public boolean linkAbsolute(String link) { return link.startsWith(MD_LINK_ABS); } public String extractImageDelim(String md) { return isHorizontal(md) ? horizImageDelim() : vertImageDelim(); } public String extractVideoDelim(String md) { return isHorizontal(md) ? horizVideoDelim() : vertVideoDelim(); } public String extractGISTDelim(String md) { return isHorizontal(md) ? horizGISTDelim() : vertGISTDelim(); } /* * Generate a key for querying the cache for matching MarkdownModel. */ public static String genKey(PitchParams pp) { return new StringBuffer(MODEL_ID).append(SLASH) .append(pp.grs) .append(SLASH) .append(pp.user) .append(SLASH) .append(pp.repo) .append(PARAM_BRANCH) .append(pp.branch) .append(PARAM_PITCHME) .append(pp.pitchme) .toString(); } public String horizDelim() { return hSlideDelim; } public String vertDelim() { return vSlideDelim; } public String horizImageDelim() { return horizDelim() + MD_HSLIDE_IMAGE; } public String vertImageDelim() { return vertDelim() + MD_VSLIDE_IMAGE; } public String horizVideoDelim() { return horizDelim() + MD_HSLIDE_VIDEO; } public String vertVideoDelim() { return vertDelim() + MD_VSLIDE_VIDEO; } public String horizGISTDelim() { return horizDelim() + MD_HSLIDE_GIST; } public String vertGISTDelim() { return vertDelim() + MD_VSLIDE_GIST; } /* * The initial releases of GitPitch used #HSLIDE and #VSLIDE * as default delimiters. To provide backwards compatability * for older presentations, when these old delimters are * detected within PITCHME.md we auto-translate these old * delimiters to the current defaults HSLIDE|VSLIDE_DELIM_DEFAULT. */ private String processBackwardCompatDelim(String md) { try { if(md.startsWith(HSLIDE_DELIM_BACK_COMPAT)) { md = md.replaceFirst(HSLIDE_DELIM_BACK_COMPAT, HSLIDE_DELIM_DEFAULT); } else if(md.startsWith(VSLIDE_DELIM_BACK_COMPAT)) { md = md.replaceFirst(VSLIDE_DELIM_BACK_COMPAT, VSLIDE_DELIM_DEFAULT); } } catch(Exception bcex) { return md; } return md; } /* * Markdown Parsing Identifiers | Delimiters. */ public static final String HSLIDE_DELIM_DEFAULT = "---"; public static final String VSLIDE_DELIM_DEFAULT = "+++"; public static final String HSLIDE_REGEX_DEFAULT = null; public static final String VSLIDE_REGEX_DEFAULT = "\\+\\+\\+"; public static final String HSLIDE_DELIM_BACK_COMPAT = "#HSLIDE"; public static final String VSLIDE_DELIM_BACK_COMPAT = "#VSLIDE"; public static final String MD_LINK_OPEN = "!["; public static final String MD_ANCHOR_OPEN = "["; public static final String MD_IMAGE_OPEN = "<!-- .slide: data-background-image=\""; public static final String MD_VIDEO_OPEN = "<!-- .slide: data-background-video=\""; public static final String MD_IFRAME_OPEN = "<!-- .slide: data-background-iframe=\""; public static final String MD_IMAGE_SIZE = "\" data-background-size=\""; public static final String MD_CLOSER = "\" -->"; public static final String MD_SPACER = "\n"; public static final String DATA_IMAGE_ATTR = "data-background-image="; public static final String MD_FRAG_OPEN = "- "; public static final String MD_FRAG_CLOSE = "|"; private static final String MD_HSLIDE_IMAGE = "?image="; private static final String MD_VSLIDE_IMAGE = "?image="; private static final String MD_HSLIDE_VIDEO = "?video="; private static final String MD_VSLIDE_VIDEO = "?video="; private static final String MD_HSLIDE_GIST = "?gist="; private static final String MD_VSLIDE_GIST = "?gist="; private static final String SLASH = "/"; private static final String PARAM_BRANCH = "?b="; private static final String PARAM_PITCHME = "&p="; private static final String MD_LINK_DELIM = "]("; private static final String MD_LINK_ABS = "http"; private static final String MD_LINK_SLASH = "/"; private static final String MD_LINK_SPACE = " "; private static final String MD_LINK_BRCKT = ")"; private static final String MD_LINK_MP4 = "mp4"; private static final String DATA_GIST_ATTR = "data-gist="; private static final String HTML_ANCHOR_OPEN = "<a target=\"_blank\" href=\""; private static final String HTML_ANCHOR_MID = "\">"; private static final String HTML_ANCHOR_CLOSE = "</a>"; private static final int NOT_FOUND = -1; /* * Model prefix identifier for cache key generator. */ private static final String MODEL_ID = "MDM:"; private static final String PITCHME_MD = "PITCHME.md"; }
app/com/gitpitch/models/MarkdownModel.java
/* * MIT License * * Copyright (c) 2016 David Russell * * 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 com.gitpitch.models; import com.gitpitch.models.SlideshowModel; import com.gitpitch.utils.*; import com.gitpitch.services.ImageService; import com.gitpitch.services.VideoService; import com.gitpitch.services.GISTService; import com.gitpitch.services.ShortcutsService; import org.apache.commons.io.FilenameUtils; import com.google.inject.assistedinject.Assisted; import javax.annotation.Nullable; import play.Logger; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.inject.*; /* * Rendering model for PITCHME.md markdown. */ public class MarkdownModel implements Markdown { private final Logger.ALogger log = Logger.of(this.getClass()); private final ImageService imageService; private final VideoService videoService; private final GISTService gistService; private final ShortcutsService shortcutsService; private final MarkdownRenderer mrndr; private final String markdown; private String hSlideDelim = HSLIDE_DELIM_DEFAULT; private String vSlideDelim = VSLIDE_DELIM_DEFAULT; @Inject public MarkdownModel(ImageService imageService, VideoService videoService, GISTService gistService, ShortcutsService shortcutsService, @Nullable @Assisted MarkdownRenderer mrndr) { this.imageService = imageService; this.videoService = videoService; this.gistService = gistService; this.shortcutsService = shortcutsService; this.mrndr = mrndr; String consumed = null; if(mrndr != null) { String gitRawBase = mrndr.gitRawBase(); Path mdPath = mrndr.filePath(PITCHME_MD); File mdFile = mdPath.toFile(); if (mdFile.exists()) { Optional<SlideshowModel> ssmo = mrndr.ssm(); final PitchParams pp = ssmo.isPresent() ? ssmo.get().params() : null; final YAMLOptions yOpts = ssmo.isPresent() ? ssmo.get().options() : null; if(yOpts != null) { hSlideDelim = yOpts.hasHorzDelim(pp) ? yOpts.fetchHorzDelim(pp) : HSLIDE_DELIM_DEFAULT; vSlideDelim = yOpts.hasVertDelim(pp) ? yOpts.fetchVertDelim(pp) : VSLIDE_DELIM_DEFAULT; } try (Stream<String> stream = Files.lines(mdPath)) { consumed = stream.map(md -> { return process(md, pp, yOpts, gitRawBase); }).map(md -> { return processAnchors(md); }).collect(Collectors.joining("\n")); consumed = postProcess(consumed, pp, yOpts, gitRawBase); } catch (Exception mex) { log.warn("Markdown processing ex={}", mex); consumed = "PITCHME.md could not be parsed."; } } else { log.warn("Markdown file does not exist, {}", mdFile); } } this.markdown = consumed; } /* * Process text, image, video and gist content * in PITCHME.md for online viewing. */ private String process(String md, PitchParams pp, YAMLOptions yOpts, String gitRawBase) { md = processBackwardCompatDelim(md); if (slideDelimFound(md)) { /* * Clean only delimiter fragments of whitespace * noise before processing. Preserve end-of-line * characters on all non-delimiter fragments. */ md = md.trim(); if (videoDelimFound(md)) { /* * Inject slide specific video background: * * <!-- .slide: data-background-video="vidUrl" --> */ String videoBgUrl = videoService.extractBgUrl(md, gitRawBase, this); return new StringBuffer(delimiter(md)) .append(videoService.buildBackground(videoBgUrl)) .toString(); } else if (imageDelimFound(md)) { /* * Inject slide specific image background: * * <!-- .slide: data-background-image="imgUrl" --> */ String imageBgUrl = imageService.extractBgUrl(md, gitRawBase, this); String bgSize = (yOpts != null) ? yOpts.fetchImageBgSize(pp) : YAMLOptions.DEFAULT_BG_SIZE; return new StringBuffer(delimiter(md)) .append(imageService.buildBackground(pp, imageBgUrl, bgSize)) .toString(); } else if (gistDelimFound(md)) { String gist = new StringBuffer(gistService.build(md, pp, yOpts, this)).toString(); return gist; } if (yOpts != null && yOpts.hasImageBg()) { /* * Inject slideshow-wide background: * * <!-- .slide: data-background-image="imgUrl" --> */ return new StringBuffer(md) .append(imageService.buildBackground(pp, yOpts)) .toString(); } else { /* * No customization on slide delimiter or background, * return unmodified. */ return md; } } else if (markdownLinkFound(md)) { /* * Link found in markdown fragment, process. */ int delim = md.indexOf(MD_LINK_DELIM); if (delim == NOT_FOUND) { /* * Valid link syntax not found, return unmodified. */ return md; } else { /* * Valid link syntax found, now process link to * handle absolute, (GitHub) relative and video links. */ String splitLeft = md.substring(0, delim + 2); String splitRight = md.substring(delim + 2); /* * Clone and clean splitRight string to begin * extraction of the pitchLink. */ String pitchLink = cloneLink(splitRight); pitchLink = extractLink(pitchLink, gitRawBase); if (videoService.isVideo(pitchLink)) { return videoService.buildVideo(pitchLink); } else if (linkAbsolute(splitRight)) { return md; } else { return splitLeft + gitRawBase + splitRight; } } } else if(imageService.tagFound(md)) { String tagLink = imageService.tagLink(md); if (linkAbsolute(tagLink)) { return md; } else { String absTagLink = gitRawBase + tagLink; return md.replace(tagLink, absTagLink); } } else if(shortcutsService.fragmentFound(md)) { return shortcutsService.expandFragment(md); } else { /* * Link-free markdown, return unmodified. */ return md; } } public String produce() { return markdown; } /* * Process text, image, video and gist content * in PITCHME.md for offline viewing. */ public String offline(String md) { if (videoService.found(md)) { return videoService.offline(); } else if (gistMarkdown(md)) { return gistService.offline(); } else if (imageService.background(md)) { return imageService.buildBackgroundOffline(md); } else if (imageService.inline(md)) { /* * Link found in markdown fragment, process. */ int delim = md.indexOf(MD_LINK_DELIM); if (delim == NOT_FOUND) { /* * Valid link syntax not found, return unmodified. */ return md; } else { /* * Valid link syntax found, now process link to * handle absolute, (GitHub) relative and video links. */ String splitLeft = md.substring(0, delim + 2); String splitRight = md.substring(delim + 2); /* * Clone and clean splitRight string to begin * extraction of the pitchLink. */ String pitchLink = cloneLink(splitRight); pitchLink = extractLink(pitchLink, null); String imageName = FilenameUtils.getName(pitchLink); return imageService.buildInlineOffline(imageName); } } else if(imageService.tagFound(md)) { return imageService.buildTagOffline(md); } else { /* * Link-free markdown, return unmodified. */ return md; } } /* * Return image asset URL from Markdown fragment. */ public String offlineAssets(String md) { if (imageService.background(md)) { String frag = md.substring(MD_IMAGE_OPEN.length()); String url = frag.substring(0, frag.indexOf("\"")); return url; } else if (imageService.inline(md)) { /* * Link found in markdown fragment, process. */ int delim = md.indexOf(MD_LINK_DELIM); if (delim == NOT_FOUND) { /* * Valid link syntax not found, return unmodified. */ return null; } else { /* * Valid link syntax found, now process link to * handle absolute, (GitHub) relative and video links. */ String splitLeft = md.substring(0, delim + 2); String splitRight = md.substring(delim + 2); /* * Clone and clean splitRight string to begin * extraction of the pitchLink. */ String pitchLink = cloneLink(splitRight); int spaceIdx = pitchLink.indexOf(MD_LINK_SPACE); int brcktIdx = pitchLink.indexOf(MD_LINK_BRCKT); String origLink = null; if (spaceIdx == NOT_FOUND || spaceIdx > brcktIdx) { origLink = pitchLink.substring(0, brcktIdx); } else { origLink = pitchLink.substring(0, spaceIdx); } return origLink; } } if(imageService.tagFound(md)) { /* * Img tag found in markdown fragment, process. */ return imageService.tagLink(md); } else { return null; } } private boolean imageDelimFound(String md) { return md.startsWith(horizImageDelim()) || md.startsWith(vertImageDelim()); } private boolean videoDelimFound(String md) { return md.startsWith(horizVideoDelim()) || md.startsWith(vertVideoDelim()); } private boolean gistDelimFound(String md) { return md.startsWith(horizGISTDelim()) || md.startsWith(vertGISTDelim()); } private String delimiter(String md) { return (md.startsWith(hSlideDelim)) ? horizDelim() : vertDelim(); } private boolean slideDelimFound(String md) { return md.startsWith(horizDelim()) || md.startsWith(vertDelim()); } private boolean markdownLinkFound(String md) { return md.startsWith(MD_LINK_OPEN); } private boolean gistMarkdown(String md) { return md.contains(DATA_GIST_ATTR); } private String cloneLink(String link) { String cloned = new String(link); /* * Strip slash prefix from relative links. */ if (cloned.startsWith(MD_LINK_SLASH)) { return cloned.substring(1); } else { return cloned; } } private String extractLink(String link, String gitRawBase) { try { int spaceIdx = link.indexOf(MD_LINK_SPACE); int brcktIdx = link.indexOf(MD_LINK_BRCKT); String origLink = null; if (spaceIdx == NOT_FOUND || spaceIdx > brcktIdx) { origLink = link.substring(0, brcktIdx); } else { origLink = link.substring(0, spaceIdx); } if (linkAbsolute(link)) { link = origLink; } else { link = gitRawBase + origLink; } return link; } catch (Exception lex) { log.warn("extractLink: link={}, ex={}", link, lex); } return null; } /* * Ensure all regular Markdown links are upgraded to * HTML anchors with target=_blank in order to * open from within embedded GitPitch iFrame. */ private String processAnchors(String md) { try { boolean moreAnchors = md.contains(MD_ANCHOR_OPEN); while(moreAnchors) { if(md.contains(MD_ANCHOR_OPEN)) { int anchorStart = md.indexOf(MD_ANCHOR_OPEN); int anchorDelim = md.indexOf(MD_LINK_DELIM, anchorStart); // Regular Markdown Link not Markdown Image Link. if(anchorDelim != -1 && (anchorStart == 0 || !md.substring(anchorStart-1) .startsWith(MD_LINK_OPEN))) { int anchorEnd = md.indexOf(MD_LINK_BRCKT, anchorDelim); String title = md.substring(anchorStart+1, anchorDelim); String link = md.substring(anchorDelim+2, anchorEnd); String anchor = new StringBuffer(HTML_ANCHOR_OPEN) .append(link) .append(HTML_ANCHOR_MID) .append(title) .append(HTML_ANCHOR_CLOSE) .toString(); String mdLeft = md.substring(0, anchorStart); String mdRight = md.substring(anchorEnd + 1); md = mdLeft + anchor + mdRight; } else { moreAnchors = false; } } else { moreAnchors = false; } } } catch(Exception tex) { return md; } return md; } private String postProcess(String md, PitchParams pp, YAMLOptions yOpts, String gitRawBase) { if (yOpts != null && yOpts.hasImageBg()) { if (!delimOnFirstSlide(md)) { /* * Inject slideshow-wide background for * implicit delim on first slide in the slideshow. */ md = imageService.buildBackground(pp, yOpts) + md; } } if (delimOnFirstSlide(md)) { int nIndex = md.indexOf(MD_SPACER); if (nIndex > 0) { String slimMd = md.substring(nIndex); md = slimMd; } } return md; } private boolean delimOnFirstSlide(String md) { return (md.startsWith(horizDelim()) || md.startsWith(vertDelim())); } public boolean isHorizontal(String md) { return (md.startsWith(horizDelim())) ? true : false; } public boolean linkAbsolute(String link) { return link.startsWith(MD_LINK_ABS); } public String extractImageDelim(String md) { return isHorizontal(md) ? horizImageDelim() : vertImageDelim(); } public String extractVideoDelim(String md) { return isHorizontal(md) ? horizVideoDelim() : vertVideoDelim(); } public String extractGISTDelim(String md) { return isHorizontal(md) ? horizGISTDelim() : vertGISTDelim(); } /* * Generate a key for querying the cache for matching MarkdownModel. */ public static String genKey(PitchParams pp) { return new StringBuffer(MODEL_ID).append(SLASH) .append(pp.grs) .append(SLASH) .append(pp.user) .append(SLASH) .append(pp.repo) .append(PARAM_BRANCH) .append(pp.branch) .append(PARAM_PITCHME) .append(pp.pitchme) .toString(); } public String horizDelim() { return hSlideDelim; } public String vertDelim() { return vSlideDelim; } public String horizImageDelim() { return horizDelim() + MD_HSLIDE_IMAGE; } public String vertImageDelim() { return vertDelim() + MD_VSLIDE_IMAGE; } public String horizVideoDelim() { return horizDelim() + MD_HSLIDE_VIDEO; } public String vertVideoDelim() { return vertDelim() + MD_VSLIDE_VIDEO; } public String horizGISTDelim() { return horizDelim() + MD_HSLIDE_GIST; } public String vertGISTDelim() { return vertDelim() + MD_VSLIDE_GIST; } /* * The initial releases of GitPitch used #HSLIDE and #VSLIDE * as default delimiters. To provide backwards compatability * for older presentations, when these old delimters are * detected within PITCHME.md we auto-translate these old * delimiters to the current defaults HSLIDE|VSLIDE_DELIM_DEFAULT. */ private String processBackwardCompatDelim(String md) { try { if(md.startsWith(HSLIDE_DELIM_BACK_COMPAT)) { md = md.replaceFirst(HSLIDE_DELIM_BACK_COMPAT, HSLIDE_DELIM_DEFAULT); } else if(md.startsWith(VSLIDE_DELIM_BACK_COMPAT)) { md = md.replaceFirst(VSLIDE_DELIM_BACK_COMPAT, VSLIDE_DELIM_DEFAULT); } } catch(Exception bcex) { return md; } return md; } /* * Markdown Parsing Identifiers | Delimiters. */ public static final String HSLIDE_DELIM_DEFAULT = "---"; public static final String VSLIDE_DELIM_DEFAULT = "+++"; public static final String HSLIDE_REGEX_DEFAULT = null; public static final String VSLIDE_REGEX_DEFAULT = "\\+\\+\\+"; public static final String HSLIDE_DELIM_BACK_COMPAT = "#HSLIDE"; public static final String VSLIDE_DELIM_BACK_COMPAT = "#VSLIDE"; public static final String MD_LINK_OPEN = "!["; public static final String MD_ANCHOR_OPEN = "["; public static final String MD_IMAGE_OPEN = "<!-- .slide: data-background-image=\""; public static final String MD_VIDEO_OPEN = "<!-- .slide: data-background-video=\""; public static final String MD_IFRAME_OPEN = "<!-- .slide: data-background-iframe=\""; public static final String MD_IMAGE_SIZE = "\" data-background-size=\""; public static final String MD_CLOSER = "\" -->"; public static final String MD_SPACER = "\n"; public static final String DATA_IMAGE_ATTR = "data-background-image="; public static final String MD_FRAG_OPEN = "- "; public static final String MD_FRAG_CLOSE = "|"; private static final String MD_HSLIDE_IMAGE = "?image="; private static final String MD_VSLIDE_IMAGE = "?image="; private static final String MD_HSLIDE_VIDEO = "?video="; private static final String MD_VSLIDE_VIDEO = "?video="; private static final String MD_HSLIDE_GIST = "?gist="; private static final String MD_VSLIDE_GIST = "?gist="; private static final String SLASH = "/"; private static final String PARAM_BRANCH = "?b="; private static final String PARAM_PITCHME = "&p="; private static final String MD_LINK_DELIM = "]("; private static final String MD_LINK_ABS = "http"; private static final String MD_LINK_SLASH = "/"; private static final String MD_LINK_SPACE = " "; private static final String MD_LINK_BRCKT = ")"; private static final String MD_LINK_MP4 = "mp4"; private static final String DATA_GIST_ATTR = "data-gist="; private static final String HTML_ANCHOR_OPEN = "<a target=\"_blank\" href=\""; private static final String HTML_ANCHOR_MID = "\">"; private static final String HTML_ANCHOR_CLOSE = "</a>"; private static final int NOT_FOUND = -1; /* * Model prefix identifier for cache key generator. */ private static final String MODEL_ID = "MDM:"; private static final String PITCHME_MD = "PITCHME.md"; }
Updated preprocessing for implicit markdown links.
app/com/gitpitch/models/MarkdownModel.java
Updated preprocessing for implicit markdown links.
<ide><path>pp/com/gitpitch/models/MarkdownModel.java <ide> */ <ide> private String processAnchors(String md) { <ide> try { <del> boolean moreAnchors = md.contains(MD_ANCHOR_OPEN); <del> while(moreAnchors) { <del> <del> if(md.contains(MD_ANCHOR_OPEN)) { <del> <del> int anchorStart = md.indexOf(MD_ANCHOR_OPEN); <del> int anchorDelim = md.indexOf(MD_LINK_DELIM, anchorStart); <del> <del> // Regular Markdown Link not Markdown Image Link. <del> if(anchorDelim != -1 && <del> (anchorStart == 0 || !md.substring(anchorStart-1) <add> <add> if(linkAbsolute(md)) { <add> return buildAnchor(md.trim(), md.trim()); <add> } else { <add> <add> boolean moreAnchors = md.contains(MD_ANCHOR_OPEN); <add> while(moreAnchors) { <add> <add> if(md.contains(MD_ANCHOR_OPEN)) { <add> <add> int anchorStart = md.indexOf(MD_ANCHOR_OPEN); <add> int anchorDelim = <add> md.indexOf(MD_LINK_DELIM, anchorStart); <add> <add> // Regular Markdown Link not Markdown Image Link. <add> if(anchorDelim != -1 && <add> (anchorStart == 0 || <add> !md.substring(anchorStart-1) <ide> .startsWith(MD_LINK_OPEN))) { <ide> <del> int anchorEnd = md.indexOf(MD_LINK_BRCKT, anchorDelim); <del> <del> String title = md.substring(anchorStart+1, anchorDelim); <del> String link = md.substring(anchorDelim+2, anchorEnd); <del> <del> String anchor = <del> new StringBuffer(HTML_ANCHOR_OPEN) <del> .append(link) <del> .append(HTML_ANCHOR_MID) <del> .append(title) <del> .append(HTML_ANCHOR_CLOSE) <del> .toString(); <del> <del> String mdLeft = md.substring(0, anchorStart); <del> String mdRight = md.substring(anchorEnd + 1); <del> md = mdLeft + anchor + mdRight; <del> <add> int anchorEnd = <add> md.indexOf(MD_LINK_BRCKT, anchorDelim); <add> <add> String title = <add> md.substring(anchorStart+1, anchorDelim); <add> String link = <add> md.substring(anchorDelim+2, anchorEnd); <add> <add> String anchor = buildAnchor(title, link); <add> <add> String mdLeft = md.substring(0, anchorStart); <add> String mdRight = md.substring(anchorEnd + 1); <add> md = mdLeft + anchor + mdRight; <add> <add> } else { <add> moreAnchors = false; <add> } <ide> } else { <ide> moreAnchors = false; <ide> } <del> } else { <del> moreAnchors = false; <ide> } <ide> } <ide> } catch(Exception tex) { <ide> return md; <ide> } <ide> return md; <add> } <add> <add> private String buildAnchor(String title, String link) { <add> return new StringBuffer(HTML_ANCHOR_OPEN) <add> .append(link) <add> .append(HTML_ANCHOR_MID) <add> .append(title) <add> .append(HTML_ANCHOR_CLOSE) <add> .toString(); <ide> } <ide> <ide> private String postProcess(String md,
Java
apache-2.0
00d636b0f3ba5e023e0c2c559c01674779ffc666
0
WANdisco/gerrit,MerritCR/merrit,gcoders/gerrit,gerrit-review/gerrit,MerritCR/merrit,thinkernel/gerrit,netroby/gerrit,bpollack/gerrit,dwhipstock/gerrit,quyixia/gerrit,thesamet/gerrit,pkdevbox/gerrit,midnightradio/gerrit,joshuawilson/merrit,renchaorevee/gerrit,Overruler/gerrit,joshuawilson/merrit,WANdisco/gerrit,thinkernel/gerrit,jackminicloud/test,joshuawilson/merrit,jackminicloud/test,bootstraponline-archive/gerrit-mirror,hdost/gerrit,WANdisco/gerrit,dwhipstock/gerrit,pkdevbox/gerrit,bpollack/gerrit,TonyChai24/test,GerritCodeReview/gerrit,jackminicloud/test,dwhipstock/gerrit,Saulis/gerrit,MerritCR/merrit,Overruler/gerrit,gcoders/gerrit,MerritCR/merrit,Team-OctOS/host_gerrit,Saulis/gerrit,joshuawilson/merrit,dwhipstock/gerrit,Team-OctOS/host_gerrit,gerrit-review/gerrit,dwhipstock/gerrit,TonyChai24/test,WANdisco/gerrit,TonyChai24/test,WANdisco/gerrit,netroby/gerrit,supriyantomaftuh/gerrit,midnightradio/gerrit,TonyChai24/test,Seinlin/gerrit,thinkernel/gerrit,hdost/gerrit,supriyantomaftuh/gerrit,thesamet/gerrit,renchaorevee/gerrit,qtproject/qtqa-gerrit,hdost/gerrit,Saulis/gerrit,joshuawilson/merrit,pkdevbox/gerrit,netroby/gerrit,supriyantomaftuh/gerrit,anminhsu/gerrit,gcoders/gerrit,pkdevbox/gerrit,hdost/gerrit,GerritCodeReview/gerrit,thinkernel/gerrit,midnightradio/gerrit,renchaorevee/gerrit,dwhipstock/gerrit,anminhsu/gerrit,bootstraponline-archive/gerrit-mirror,Saulis/gerrit,Overruler/gerrit,midnightradio/gerrit,renchaorevee/gerrit,quyixia/gerrit,bootstraponline-archive/gerrit-mirror,Distrotech/gerrit,thinkernel/gerrit,GerritCodeReview/gerrit,quyixia/gerrit,Seinlin/gerrit,gerrit-review/gerrit,Overruler/gerrit,netroby/gerrit,WANdisco/gerrit,Seinlin/gerrit,midnightradio/gerrit,quyixia/gerrit,Seinlin/gerrit,jackminicloud/test,quyixia/gerrit,GerritCodeReview/gerrit,Team-OctOS/host_gerrit,hdost/gerrit,thesamet/gerrit,Seinlin/gerrit,gcoders/gerrit,midnightradio/gerrit,thesamet/gerrit,thesamet/gerrit,thesamet/gerrit,Seinlin/gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,thinkernel/gerrit,qtproject/qtqa-gerrit,Distrotech/gerrit,renchaorevee/gerrit,GerritCodeReview/gerrit,jackminicloud/test,bpollack/gerrit,bpollack/gerrit,bpollack/gerrit,Overruler/gerrit,netroby/gerrit,quyixia/gerrit,Distrotech/gerrit,Team-OctOS/host_gerrit,gerrit-review/gerrit,MerritCR/merrit,joshuawilson/merrit,MerritCR/merrit,renchaorevee/gerrit,supriyantomaftuh/gerrit,GerritCodeReview/gerrit,jackminicloud/test,WANdisco/gerrit,pkdevbox/gerrit,Saulis/gerrit,Team-OctOS/host_gerrit,Saulis/gerrit,Team-OctOS/host_gerrit,hdost/gerrit,MerritCR/merrit,qtproject/qtqa-gerrit,bootstraponline-archive/gerrit-mirror,dwhipstock/gerrit,bootstraponline-archive/gerrit-mirror,netroby/gerrit,qtproject/qtqa-gerrit,gcoders/gerrit,Overruler/gerrit,MerritCR/merrit,renchaorevee/gerrit,Distrotech/gerrit,supriyantomaftuh/gerrit,pkdevbox/gerrit,GerritCodeReview/gerrit,pkdevbox/gerrit,Distrotech/gerrit,thesamet/gerrit,joshuawilson/merrit,joshuawilson/merrit,gcoders/gerrit,supriyantomaftuh/gerrit,netroby/gerrit,Distrotech/gerrit,anminhsu/gerrit,bootstraponline-archive/gerrit-mirror,Team-OctOS/host_gerrit,anminhsu/gerrit,TonyChai24/test,Seinlin/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,TonyChai24/test,gerrit-review/gerrit,thinkernel/gerrit,GerritCodeReview/gerrit,anminhsu/gerrit,quyixia/gerrit,gcoders/gerrit,Distrotech/gerrit,anminhsu/gerrit,jackminicloud/test,TonyChai24/test,gerrit-review/gerrit,bpollack/gerrit,supriyantomaftuh/gerrit,anminhsu/gerrit,hdost/gerrit
// Copyright (C) 2009 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. public final class Main { // We don't do any real work here because we need to import // the archive lookup code and we cannot import a class in // the default package. So this is just a tiny springboard // to jump into the real main code. // public static void main(final String argv[]) throws Exception { if (onSupportedJavaVersion()) { com.google.gerrit.launcher.GerritLauncher.main(argv); } else { System.exit(1); } } private static boolean onSupportedJavaVersion() { final String version = System.getProperty("java.specification.version"); if (1.7 <= parse(version)) { return true; } else { System.err.println("fatal: Gerrit Code Review requires Java 7 or later"); System.err.println(" (trying to run on Java " + version + ")"); return false; } } private static double parse(String version) { if (version == null || version.length() == 0) { return 0.0; } try { final int fd = version.indexOf('.'); final int sd = version.indexOf('.', fd + 1); if (0 < sd) { version = version.substring(0, sd); } return Double.parseDouble(version); } catch (NumberFormatException e) { return 0.0; } } private Main() { } }
gerrit-main/src/main/java/Main.java
// Copyright (C) 2009 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. public final class Main { // We don't do any real work here because we need to import // the archive lookup code and we cannot import a class in // the default package. So this is just a tiny springboard // to jump into the real main code. // public static void main(final String argv[]) throws Exception { if (onSupportedJavaVersion()) { com.google.gerrit.launcher.GerritLauncher.main(argv); } else { System.exit(1); } } private static boolean onSupportedJavaVersion() { final String version = System.getProperty("java.specification.version"); if (1.6 <= parse(version)) { return true; } else { System.err.println("fatal: Gerrit Code Review requires Java 6 or later"); System.err.println(" (trying to run on Java " + version + ")"); return false; } } private static double parse(String version) { if (version == null || version.length() == 0) { return 0.0; } try { final int fd = version.indexOf('.'); final int sd = version.indexOf('.', fd + 1); if (0 < sd) { version = version.substring(0, sd); } return Double.parseDouble(version); } catch (NumberFormatException e) { return 0.0; } } private Main() { } }
Add startup check for Java 7 Change-Id: I0ebcc126b46d0c948c1d249188bf95f0a8564c9e
gerrit-main/src/main/java/Main.java
Add startup check for Java 7
<ide><path>errit-main/src/main/java/Main.java <ide> <ide> private static boolean onSupportedJavaVersion() { <ide> final String version = System.getProperty("java.specification.version"); <del> if (1.6 <= parse(version)) { <add> if (1.7 <= parse(version)) { <ide> return true; <ide> <ide> } else { <del> System.err.println("fatal: Gerrit Code Review requires Java 6 or later"); <add> System.err.println("fatal: Gerrit Code Review requires Java 7 or later"); <ide> System.err.println(" (trying to run on Java " + version + ")"); <ide> return false; <ide> }
Java
mit
error: pathspec 'src/main/java/de/ehex/foss/gematik/specifications/gemSpec_Sich_DS/AFOs.java' did not match any file(s) known to git
385d3059d8e7abf89aa57261e1eef84bd2166025
1
eHealthExperts/gematik-specifications,ghostcity/gematik-specifications
package de.ehex.foss.gematik.specifications.gemSpec_Sich_DS; import static de.ehex.foss.gematik.specifications.AFOType.MUST; import static java.util.Objects.nonNull; import de.ehex.foss.gematik.specifications.AFO; import de.ehex.foss.gematik.specifications.AFOType; /** * Enumeration of all &ndash;&nbsp;currently considered&nbsp;&ndash; {@link AFO}s of {@code [gemSpec_Sich_DS]}. * * @author Stefan Gasterst&auml;dt * @since September 21st, 2016 */ public enum AFOs implements AFO { // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2012("GS-A_2012", "Verantwortung der Anbieter und Betreiber für Einhaltung der Anforderungen Datenschutz und Informationssicherheit"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2021("GS-A_2021", "Anwendung der einheitlichen Methoden der Informationssicherheit durch Betreiber und Anbieter"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2046("GS-A_2046", "Umsetzung der Anforderungen aus [gemSpec_SiBetrUmg] durch Anbieter von zentralen Produkten"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2047("GS-A_2047", "Gestaltung der Umgebung von zentralen Produkten durch Betreiber für Schutzbedarf \"mittel\""), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2065("GS-A_2065", "Beschlagnahmeschutz bei Anbietern und Betreibern"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2070("GS-A_2070", "Datenschutzkontrolle durch BfDI und gematik"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2071("GS-A_2071", "Unterstützung bei der Datenschutzkontrolle durch BfDI und gematik"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2072("GS-A_2072", "Bereitstellung von Datenschutz-Audits zur Datenschutzkontrolle durch BfDI und gematik"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2073("GS-A_2073", "Anordnung von Maßnahmen des Datenschutzes durch BfDI und gematik"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2074("GS-A_2074", "Umsetzung der durch BfDI und gematik angeordneten Maßnahmen"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2075("GS-A_2075", "Untersagen von Verfahren durch BfDI und gematik"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2076("GS-A_2076", "Datenschutzmanagement nach BSI für Betreiber"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2087("GS-A_2087", "Information für Betroffene über Produkte durch Anbieter und Betreiber"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2156("GS-A_2156", "Auditierungen der Zulassungsnehmer"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2174("GS-A_2174", "Inhalte des Sicherheitsgutachtens aus Sicht des Datenschutzes"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2177("GS-A_2177", "Anbieter müssen Pflichten der Auftragsdatenverarbeitung erfüllen"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2213("GS-A_2213", "Wahrnehmung der Betroffenenrechte beim Anbieter"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2214("GS-A_2214", "Anbieter müssen jährlich die Betreiber kontrollieren."), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2309("GS-A_2309", "ISM der Beteiligten: Rollen und Verantwortlichkeiten"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2326("GS-A_2326", "ISM der Beteiligten: Etablierung"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2328("GS-A_2328", "ISM der Beteiligten: Pflege und Fortschreibung der Sicherheitskonzepte"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2329("GS-A_2329", "ISM der Beteiligten: Umsetzung der Sicherheitskonzepte"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2330("GS-A_2330", "ISM der Beteiligten: Schwachstellen-Management"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2331("GS-A_2331", "ISM der Beteiligten: Sicherheitsvorfalls-Management"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2332("GS-A_2332", "ISM der Beteiligten: Notfallmanagement"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2333("GS-A_2333", "ISM der Beteiligten: Meldung an das koordinierende ISM"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2339("GS-A_2339", "ISM der Beteiligten: regelmäßige Reviews"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2343("GS-A_2343", "ISM der Beteiligten: eigene Audits"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2345("GS-A_2345", "ISM der Beteiligten: Reviews und Trendanalysen"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2347("GS-A_2347", "ISM der Beteiligten: Grundlagen neuer Planungsphasen"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2354("GS-A_2354", "Produktunterstützung mit geeigneten Sicherheits-Technologien"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2355("GS-A_2355", "ISM der Beteiligten: Nutzung des Problem-ManagementProzesses"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2356("GS-A_2356", "ISM der Beteiligten: Nutzung des Incident-ManagementProzesses"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2357("GS-A_2357", "ISM der Beteiligten: Nutzung der Prozesse und Reports des Betriebs"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2359("GS-A_2359", "ISM der Beteiligten: Nutzung der Sicherheits-Technologien des koordinierenden ISM"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2360("GS-A_2360", "ISM der Beteiligten: Meldung von Restrisiken"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2361("GS-A_2361", "ISM der Beteiligten: Vorfallsmanagement"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2362("GS-A_2362", "ISM der Beteiligten: Bericht lokaler Sicherheitsvorfälle"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2363("GS-A_2363", "ISM der Beteiligten: Meldung schwerwiegender Sicherheitsvorfälle"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2366("GS-A_2366", "ISM der Beteiligten: Notfallbewältigung"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2524("GS-A_2524", "Produktunterstützung: Nutzung des Problem-ManagementProzesses"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2525("GS-A_2525", "Hersteller: Schließen von Schwachstellen"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_3078("GS-A_3078", "Anbieter einer Schlüsselverwaltung: verpflichtende Migrationsstrategie bei Schwächung kryptographischer Primitive"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_3125("GS-A_3125", "Schlüsselinstallation und Verteilung: Dokumentation gemäß Minimalitätsprinzip"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_3130("GS-A_3130", "Krypto_Schlüssel_Installation: Dokumentation der Schlüsselinstallation gemäß Minimalitätsprinzip"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_3139("GS-A_3139", "Krypto_Schlüssel: Dienst Schlüsselableitung"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_3141("GS-A_3141", "Krypto_Schlüssel_Ableitung: Maßnahmen bei Bekanntwerden von Schwächen in der Schlüsselableitungsfunktion"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_3149("GS-A_3149", "Krypto_Schlüssel_Archivierung: Dokumentation der Schlüsselarchivierung gemäß Minimalitätsprinzip"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_4944("GS-A_4944", "Produktentwicklung: Behebung von Sicherheitsmängeln"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_4945("GS-A_4945", "Produktentwicklung: Qualitätssicherung"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_4946("GS-A_4946", "Produktentwicklung: sichere Programmierung"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_4947("GS-A_4947", "Produktentwicklung: Schutz der Vertraulichkeit und Integrität"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_5017("GS-A_5017", "ISM der Beteiligten: Schließen von Schwachstellen"), // TODO: AFO-Typ klären derzeit implizit MUSS-AFO GS_A_2350("GS-A_2350", "Produktunterstützung der Hersteller"), ; private AFOs(final String afoID, final String title) { this(afoID, title, MUST); } private AFOs(final String afoID, final String title, final AFOType level) { assert nonNull(afoID) : "There must be a non-null AFO id!"; assert !afoID.isEmpty() : "There must be a non-empty AFO id!"; assert nonNull(title) : "There must be a non-null AFO title!"; assert !title.isEmpty() : "There must be a non-empty AFO title!"; assert nonNull(level) : "There must be a non-null AFO type!"; this.afoID = afoID; this.title = title; this.level = level; } private final String afoID; @Override public String getAfoId() { assert nonNull(this.afoID) : "Class invariant violation!"; assert !this.afoID.isEmpty() : "Class invariant violation!"; return this.afoID; } private final String title; @Override public String getLabel() { assert nonNull(this.title) : "Class invariant violation!"; assert !this.title.isEmpty() : "Class invariant violation!"; return this.title; } private final AFOType level; @Override public AFOType getType() { assert nonNull(this.level) : "Class invariant violation!"; return this.level; } }
src/main/java/de/ehex/foss/gematik/specifications/gemSpec_Sich_DS/AFOs.java
Neu: Bislang benötigte AFOs aus [gemSpec_Sich_DS]
src/main/java/de/ehex/foss/gematik/specifications/gemSpec_Sich_DS/AFOs.java
Neu: Bislang benötigte AFOs aus [gemSpec_Sich_DS]
<ide><path>rc/main/java/de/ehex/foss/gematik/specifications/gemSpec_Sich_DS/AFOs.java <add>package de.ehex.foss.gematik.specifications.gemSpec_Sich_DS; <add> <add>import static de.ehex.foss.gematik.specifications.AFOType.MUST; <add>import static java.util.Objects.nonNull; <add> <add>import de.ehex.foss.gematik.specifications.AFO; <add>import de.ehex.foss.gematik.specifications.AFOType; <add> <add>/** <add> * Enumeration of all &ndash;&nbsp;currently considered&nbsp;&ndash; {@link AFO}s of {@code [gemSpec_Sich_DS]}. <add> * <add> * @author Stefan Gasterst&auml;dt <add> * @since September 21st, 2016 <add> */ <add>public enum AFOs implements AFO { <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2012("GS-A_2012", "Verantwortung der Anbieter und Betreiber für Einhaltung der Anforderungen Datenschutz und Informationssicherheit"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2021("GS-A_2021", "Anwendung der einheitlichen Methoden der Informationssicherheit durch Betreiber und Anbieter"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2046("GS-A_2046", "Umsetzung der Anforderungen aus [gemSpec_SiBetrUmg] durch Anbieter von zentralen Produkten"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2047("GS-A_2047", "Gestaltung der Umgebung von zentralen Produkten durch Betreiber für Schutzbedarf \"mittel\""), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2065("GS-A_2065", "Beschlagnahmeschutz bei Anbietern und Betreibern"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2070("GS-A_2070", "Datenschutzkontrolle durch BfDI und gematik"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2071("GS-A_2071", "Unterstützung bei der Datenschutzkontrolle durch BfDI und gematik"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2072("GS-A_2072", "Bereitstellung von Datenschutz-Audits zur Datenschutzkontrolle durch BfDI und gematik"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2073("GS-A_2073", "Anordnung von Maßnahmen des Datenschutzes durch BfDI und gematik"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2074("GS-A_2074", "Umsetzung der durch BfDI und gematik angeordneten Maßnahmen"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2075("GS-A_2075", "Untersagen von Verfahren durch BfDI und gematik"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2076("GS-A_2076", "Datenschutzmanagement nach BSI für Betreiber"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2087("GS-A_2087", "Information für Betroffene über Produkte durch Anbieter und Betreiber"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2156("GS-A_2156", "Auditierungen der Zulassungsnehmer"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2174("GS-A_2174", "Inhalte des Sicherheitsgutachtens aus Sicht des Datenschutzes"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2177("GS-A_2177", "Anbieter müssen Pflichten der Auftragsdatenverarbeitung erfüllen"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2213("GS-A_2213", "Wahrnehmung der Betroffenenrechte beim Anbieter"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2214("GS-A_2214", "Anbieter müssen jährlich die Betreiber kontrollieren."), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2309("GS-A_2309", "ISM der Beteiligten: Rollen und Verantwortlichkeiten"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2326("GS-A_2326", "ISM der Beteiligten: Etablierung"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2328("GS-A_2328", "ISM der Beteiligten: Pflege und Fortschreibung der Sicherheitskonzepte"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2329("GS-A_2329", "ISM der Beteiligten: Umsetzung der Sicherheitskonzepte"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2330("GS-A_2330", "ISM der Beteiligten: Schwachstellen-Management"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2331("GS-A_2331", "ISM der Beteiligten: Sicherheitsvorfalls-Management"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2332("GS-A_2332", "ISM der Beteiligten: Notfallmanagement"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2333("GS-A_2333", "ISM der Beteiligten: Meldung an das koordinierende ISM"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2339("GS-A_2339", "ISM der Beteiligten: regelmäßige Reviews"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2343("GS-A_2343", "ISM der Beteiligten: eigene Audits"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2345("GS-A_2345", "ISM der Beteiligten: Reviews und Trendanalysen"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2347("GS-A_2347", "ISM der Beteiligten: Grundlagen neuer Planungsphasen"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2354("GS-A_2354", "Produktunterstützung mit geeigneten Sicherheits-Technologien"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2355("GS-A_2355", "ISM der Beteiligten: Nutzung des Problem-ManagementProzesses"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2356("GS-A_2356", "ISM der Beteiligten: Nutzung des Incident-ManagementProzesses"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2357("GS-A_2357", "ISM der Beteiligten: Nutzung der Prozesse und Reports des Betriebs"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2359("GS-A_2359", "ISM der Beteiligten: Nutzung der Sicherheits-Technologien des koordinierenden ISM"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2360("GS-A_2360", "ISM der Beteiligten: Meldung von Restrisiken"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2361("GS-A_2361", "ISM der Beteiligten: Vorfallsmanagement"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2362("GS-A_2362", "ISM der Beteiligten: Bericht lokaler Sicherheitsvorfälle"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2363("GS-A_2363", "ISM der Beteiligten: Meldung schwerwiegender Sicherheitsvorfälle"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2366("GS-A_2366", "ISM der Beteiligten: Notfallbewältigung"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2524("GS-A_2524", "Produktunterstützung: Nutzung des Problem-ManagementProzesses"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2525("GS-A_2525", "Hersteller: Schließen von Schwachstellen"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_3078("GS-A_3078", "Anbieter einer Schlüsselverwaltung: verpflichtende Migrationsstrategie bei Schwächung kryptographischer Primitive"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_3125("GS-A_3125", "Schlüsselinstallation und Verteilung: Dokumentation gemäß Minimalitätsprinzip"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_3130("GS-A_3130", "Krypto_Schlüssel_Installation: Dokumentation der Schlüsselinstallation gemäß Minimalitätsprinzip"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_3139("GS-A_3139", "Krypto_Schlüssel: Dienst Schlüsselableitung"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_3141("GS-A_3141", "Krypto_Schlüssel_Ableitung: Maßnahmen bei Bekanntwerden von Schwächen in der Schlüsselableitungsfunktion"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_3149("GS-A_3149", "Krypto_Schlüssel_Archivierung: Dokumentation der Schlüsselarchivierung gemäß Minimalitätsprinzip"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_4944("GS-A_4944", "Produktentwicklung: Behebung von Sicherheitsmängeln"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_4945("GS-A_4945", "Produktentwicklung: Qualitätssicherung"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_4946("GS-A_4946", "Produktentwicklung: sichere Programmierung"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_4947("GS-A_4947", "Produktentwicklung: Schutz der Vertraulichkeit und Integrität"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_5017("GS-A_5017", "ISM der Beteiligten: Schließen von Schwachstellen"), <add> <add> // TODO: AFO-Typ klären derzeit implizit MUSS-AFO <add> GS_A_2350("GS-A_2350", "Produktunterstützung der Hersteller"), <add> <add> ; <add> <add> private AFOs(final String afoID, final String title) { <add> this(afoID, title, MUST); <add> } <add> <add> private AFOs(final String afoID, final String title, final AFOType level) { <add> assert nonNull(afoID) : "There must be a non-null AFO id!"; <add> assert !afoID.isEmpty() : "There must be a non-empty AFO id!"; <add> assert nonNull(title) : "There must be a non-null AFO title!"; <add> assert !title.isEmpty() : "There must be a non-empty AFO title!"; <add> assert nonNull(level) : "There must be a non-null AFO type!"; <add> <add> this.afoID = afoID; <add> this.title = title; <add> this.level = level; <add> } <add> <add> private final String afoID; <add> <add> @Override <add> public String getAfoId() { <add> assert nonNull(this.afoID) : "Class invariant violation!"; <add> assert !this.afoID.isEmpty() : "Class invariant violation!"; <add> <add> return this.afoID; <add> } <add> <add> private final String title; <add> <add> @Override <add> public String getLabel() { <add> assert nonNull(this.title) : "Class invariant violation!"; <add> assert !this.title.isEmpty() : "Class invariant violation!"; <add> <add> return this.title; <add> } <add> <add> private final AFOType level; <add> <add> @Override <add> public AFOType getType() { <add> assert nonNull(this.level) : "Class invariant violation!"; <add> <add> return this.level; <add> } <add> <add>}
Java
apache-2.0
019c8c9fc5ccce03c76a40e81427cf7444022bd1
0
Mishiranu/Dashchan,Mishiranu/Dashchan,Mishiranu/Dashchan,Mishiranu/Dashchan
package com.mishiranu.dashchan.ui.gallery; import android.app.AlertDialog; import android.content.Context; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Point; import android.graphics.Rect; import android.net.Uri; import android.view.Gravity; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.fragment.app.FragmentManager; import chan.content.Chan; import chan.util.StringUtils; import com.mishiranu.dashchan.C; import com.mishiranu.dashchan.R; import com.mishiranu.dashchan.content.AdvancedPreferences; import com.mishiranu.dashchan.content.Preferences; import com.mishiranu.dashchan.content.async.ReadVideoTask; import com.mishiranu.dashchan.content.model.ErrorItem; import com.mishiranu.dashchan.graphics.BaseDrawable; import com.mishiranu.dashchan.media.VideoPlayer; import com.mishiranu.dashchan.ui.InstanceDialog; import com.mishiranu.dashchan.util.AnimationUtils; import com.mishiranu.dashchan.util.AudioFocus; import com.mishiranu.dashchan.util.ConcurrentUtils; import com.mishiranu.dashchan.util.ResourceUtils; import com.mishiranu.dashchan.util.ViewUtils; import com.mishiranu.dashchan.widget.SummaryLayout; import java.io.File; import java.io.IOException; import java.util.Locale; import java.util.Map; public class VideoUnit { private final PagerInstance instance; private final LinearLayout controlsView; private final AudioFocus audioFocus; private int layoutConfiguration = -1; private LinearLayout configurationView; private TextView timeTextView; private TextView totalTimeTextView; private SeekBar seekBar; private ImageButton playPauseButton; private VideoPlayer player; private BackgroundDrawable backgroundDrawable; private boolean initialized; private boolean wasPlaying; private boolean pausedByTransientLossOfFocus; private boolean finishedPlayback; private boolean trackingNow; private boolean hideSurfaceOnInit; private ReadVideoCallback readVideoCallback; public VideoUnit(PagerInstance instance) { this.instance = instance; controlsView = new LinearLayout(instance.galleryInstance.context); controlsView.setOrientation(LinearLayout.VERTICAL); controlsView.setVisibility(View.GONE); audioFocus = new AudioFocus(instance.galleryInstance.context, change -> { switch (change) { case LOSS: { setPlaying(false, false); updatePlayState(); break; } case LOSS_TRANSIENT: { boolean playing = player.isPlaying(); setPlaying(false, false); if (playing) { pausedByTransientLossOfFocus = true; } updatePlayState(); break; } case GAIN: { if (pausedByTransientLossOfFocus) { setPlaying(true, false); } updatePlayState(); break; } } }); } public void addViews(FrameLayout frameLayout) { frameLayout.addView(controlsView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM)); } public void onResume() { if (player != null && initialized) { setPlaying(wasPlaying, true); updatePlayState(); } else { wasPlaying = true; } } public void onPause() { if (player != null && initialized) { wasPlaying = player.isPlaying(); setPlaying(false, true); } else { wasPlaying = false; } } public void onConfigurationChanged(Configuration newConfig) { if (newConfig.orientation != Configuration.ORIENTATION_UNDEFINED) { if (layoutConfiguration != -1) { recreateVideoControls(); } } } public void onApplyWindowInsets(int left, int right, int bottom) { if (C.API_LOLLIPOP) { controlsView.setPadding(left, 0, right, bottom); } } public boolean isInitialized() { return initialized; } public boolean isCreated() { return player != null; } public void interrupt() { if (readVideoCallback != null) { readVideoCallback.cancel(); readVideoCallback = null; } if (initialized) { audioFocus.release(); initialized = false; } invalidateControlsVisibility(); if (player != null) { player.destroy(); player = null; instance.currentHolder.progressBar.setVisible(false, false); } if (backgroundDrawable != null) { backgroundDrawable.recycle(); backgroundDrawable = null; } interruptHolder(instance.leftHolder); interruptHolder(instance.currentHolder); interruptHolder(instance.rightHolder); } private void interruptHolder(PagerInstance.ViewHolder holder) { if (holder != null) { holder.surfaceParent.removeAllViews(); } } public void forcePause() { if (initialized) { wasPlaying = false; setPlaying(false, true); } } public void applyVideo(Uri uri, File file, boolean reload) { wasPlaying = true; finishedPlayback = false; hideSurfaceOnInit = false; boolean seekAnyFrame = Preferences.isVideoSeekAnyFrame(); VideoPlayer player = new VideoPlayer(playerListener, seekAnyFrame); boolean loadedFromFile = false; if (!reload && file.exists()) { try { player.init(file, null); loadedFromFile = true; } catch (IOException e) { // Player was consumed, create a new one and try to download a new video file player = new VideoPlayer(playerListener, seekAnyFrame); } } this.player = player; if (loadedFromFile) { initializePlayer(); seekBar.setSecondaryProgress(seekBar.getMax()); if (instance.currentHolder.mediaSummary.updateSize(file.length())) { instance.galleryInstance.callback.updateTitle(); } instance.currentHolder.loadState = PagerInstance.LoadState.COMPLETE; instance.galleryInstance.callback.invalidateOptionsMenu(); } else { instance.currentHolder.progressBar.setIndeterminate(true); instance.currentHolder.progressBar.setVisible(true, false); readVideoCallback = new ReadVideoCallback(player, instance.currentHolder, instance.galleryInstance.chanName, uri); } } private boolean setPlaying(boolean playing, boolean resetFocus) { if (player.isPlaying() != playing) { if (resetFocus && player.isAudioPresent()) { if (playing) { if (!audioFocus.acquire()) { return false; } } else { audioFocus.release(); } } player.setPlaying(playing); pausedByTransientLossOfFocus = false; } return true; } private void initializePlayer() { PagerInstance.ViewHolder holder = instance.currentHolder; holder.progressBar.setVisible(false, false); Point dimensions = player.getDimensions(); if (holder.mediaSummary.updateDimensions(dimensions.x, dimensions.y)) { instance.galleryInstance.callback.updateTitle(); } backgroundDrawable = new BackgroundDrawable(); backgroundDrawable.width = dimensions.x; backgroundDrawable.height = dimensions.y; holder.recyclePhotoView(); holder.photoView.setImage(backgroundDrawable, false, true, false); View videoView = player.getVideoView(instance.galleryInstance.context); holder.surfaceParent.addView(videoView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT, Gravity.CENTER)); recreateVideoControls(); playPauseButton.setEnabled(true); seekBar.setEnabled(true); initialized = true; pausedByTransientLossOfFocus = false; if (hideSurfaceOnInit) { showHideVideoView(false); } invalidateControlsVisibility(); setPlaying(wasPlaying, true); updatePlayState(); } private void recreateVideoControls() { Context context = instance.galleryInstance.context; float density = ResourceUtils.obtainDensity(context); int targetLayoutCounfiguration = ResourceUtils.isTabletOrLandscape(context.getResources() .getConfiguration()) ? 1 : 0; if (targetLayoutCounfiguration != layoutConfiguration) { boolean firstTimeLayout = layoutConfiguration < 0; layoutConfiguration = targetLayoutCounfiguration; boolean longLayout = targetLayoutCounfiguration == 1; controlsView.removeAllViews(); if (seekBar != null) { seekBar.removeCallbacks(progressRunnable); } trackingNow = false; configurationView = new LinearLayout(context); configurationView.setOrientation(LinearLayout.HORIZONTAL); configurationView.setGravity(Gravity.END); configurationView.setPadding((int) (8f * density), 0, (int) (8f * density), 0); controlsView.addView(configurationView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); LinearLayout controls = new LinearLayout(context); controls.setOrientation(longLayout ? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL); controls.setBackgroundColor(instance.galleryInstance.actionBarColor); controls.setPadding((int) (8f * density), longLayout ? 0 : (int) (8f * density), (int) (8f * density), 0); controls.setClickable(true); controlsView.addView(controls, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); CharSequence oldTimeText = timeTextView != null ? timeTextView.getText() : null; timeTextView = new TextView(context, null, android.R.attr.textAppearanceListItem); ViewUtils.setTextSizeScaled(timeTextView, 14); timeTextView.setGravity(Gravity.CENTER_HORIZONTAL); if (C.API_LOLLIPOP) { timeTextView.setTypeface(ResourceUtils.TYPEFACE_MEDIUM); } if (oldTimeText != null) { timeTextView.setText(oldTimeText); } totalTimeTextView = new TextView(context, null, android.R.attr.textAppearanceListItem); ViewUtils.setTextSizeScaled(totalTimeTextView, 14); totalTimeTextView.setGravity(Gravity.CENTER_HORIZONTAL); if (C.API_LOLLIPOP) { totalTimeTextView.setTypeface(ResourceUtils.TYPEFACE_MEDIUM); } int oldSecondaryProgress = seekBar != null ? seekBar.getSecondaryProgress() : -1; seekBar = new SeekBar(context); seekBar.setOnSeekBarChangeListener(seekBarListener); if (oldSecondaryProgress >= 0) { seekBar.setSecondaryProgress(oldSecondaryProgress); } playPauseButton = new ImageButton(context, null, android.R.attr.borderlessButtonStyle); playPauseButton.setScaleType(ImageButton.ScaleType.CENTER); playPauseButton.setOnClickListener(playPauseClickListener); if (longLayout) { controls.setGravity(Gravity.CENTER_VERTICAL); controls.addView(timeTextView, (int) (48f * density), LinearLayout.LayoutParams.WRAP_CONTENT); controls.addView(seekBar, new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)); controls.addView(playPauseButton, (int) (80f * density), LinearLayout.LayoutParams.WRAP_CONTENT); controls.addView(totalTimeTextView, (int) (48f * density), LinearLayout.LayoutParams.WRAP_CONTENT); } else { LinearLayout controls1 = new LinearLayout(context); controls1.setOrientation(LinearLayout.HORIZONTAL); controls1.setGravity(Gravity.CENTER_VERTICAL); controls1.setPadding(0, (int) (8f * density), 0, (int) (8f * density)); LinearLayout controls2 = new LinearLayout(context); controls2.setOrientation(LinearLayout.HORIZONTAL); controls2.setGravity(Gravity.CENTER_VERTICAL); controls.addView(controls1, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); controls.addView(controls2, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); controls1.addView(seekBar, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); controls2.addView(timeTextView, new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)); controls2.addView(playPauseButton, (int) (80f * density), LinearLayout.LayoutParams.WRAP_CONTENT); controls2.addView(totalTimeTextView, new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)); } if (firstTimeLayout) { AnimationUtils.measureDynamicHeight(controlsView); controlsView.setTranslationY(controlsView.getMeasuredHeight()); controlsView.setAlpha(0f); } } if (player != null) { configurationView.removeAllViews(); if (!player.isAudioPresent()) { ImageView imageView = new ImageView(context); imageView.setImageDrawable(ResourceUtils.getDrawable(context, R.attr.iconActionVolumeOff, 0)); imageView.setScaleType(ImageView.ScaleType.CENTER); if (C.API_LOLLIPOP) { imageView.setImageAlpha(0x99); } configurationView.addView(imageView, (int) (48f * density), (int) (48f * density)); } long duration = player.getDuration(); totalTimeTextView.setText(formatVideoTime(duration)); seekBar.setMax((int) duration); } seekBar.removeCallbacks(progressRunnable); seekBar.post(progressRunnable); updatePlayState(); } private static String formatVideoTime(long position) { position /= 1000; int m = (int) (position / 60 % 60); int s = (int) (position % 60); return String.format(Locale.US, "%02d:%02d", m, s); } private final View.OnClickListener playPauseClickListener = new View.OnClickListener() { @Override public void onClick(View v) { if (initialized) { if (finishedPlayback) { finishedPlayback = false; player.setPosition(0); setPlaying(true, true); } else { boolean playing = !player.isPlaying(); setPlaying(playing, true); } updatePlayState(); } } }; private final Runnable progressRunnable = new Runnable() { @Override public void run() { if (initialized) { int position; if (trackingNow) { position = seekBar.getProgress(); } else { position = (int) player.getPosition(); seekBar.setProgress(position); } timeTextView.setText(formatVideoTime(position)); } seekBar.postDelayed(this, 200); } }; private final SeekBar.OnSeekBarChangeListener seekBarListener = new SeekBar.OnSeekBarChangeListener() { private int nextSeekPosition; @Override public void onStopTrackingTouch(SeekBar seekBar) { trackingNow = false; seekBar.removeCallbacks(progressRunnable); if (nextSeekPosition != -1) { seekBar.setProgress(nextSeekPosition); player.setPosition(nextSeekPosition); seekBar.postDelayed(progressRunnable, 250); if (finishedPlayback) { finishedPlayback = false; updatePlayState(); } } else { progressRunnable.run(); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { trackingNow = true; seekBar.removeCallbacks(progressRunnable); nextSeekPosition = -1; } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { nextSeekPosition = progress; } } }; private void updatePlayState() { if (player != null) { boolean playing = player.isPlaying(); playPauseButton.setImageResource(ResourceUtils .getResourceId(instance.galleryInstance.context, finishedPlayback ? R.attr.iconButtonRefresh : playing ? R.attr.iconButtonPause : R.attr.iconButtonPlay, 0)); instance.galleryInstance.callback.setScreenOnFixed(!finishedPlayback && playing); } } public void viewTechnicalInfo() { if (initialized) { Map<String, String> technicalInfo = player.getTechnicalInfo(); showTechnicalInfo(instance.galleryInstance.callback.getChildFragmentManager(), technicalInfo); } } private static void showTechnicalInfo(FragmentManager fragmentManager, Map<String, String> technicalInfo) { new InstanceDialog(fragmentManager, null, provider -> { Context context = GalleryInstance.getCallback(provider).getWindow().getContext(); AlertDialog dialog = new AlertDialog.Builder(context) .setTitle(R.string.technical_info) .setPositiveButton(android.R.string.ok, null) .create(); SummaryLayout layout = new SummaryLayout(dialog); String videoFormat = technicalInfo.get("video_format"); String width = technicalInfo.get("width"); String height = technicalInfo.get("height"); String frameRate = technicalInfo.get("frame_rate"); String pixelFormat = technicalInfo.get("pixel_format"); String surfaceFormat = technicalInfo.get("surface_format"); String frameConversion = technicalInfo.get("frame_conversion"); String audioFormat = technicalInfo.get("audio_format"); String channels = technicalInfo.get("channels"); String sampleRate = technicalInfo.get("sample_rate"); String encoder = technicalInfo.get("encoder"); String title = technicalInfo.get("title"); if (videoFormat != null) { layout.add("Video", videoFormat); } if (width != null && height != null) { layout.add("Resolution", width + '×' + height); } if (frameRate != null) { layout.add("Frame rate", StringUtils.stripTrailingZeros(frameRate) + " FPS"); } if (pixelFormat != null) { layout.add("Pixels", pixelFormat); } if (surfaceFormat != null) { layout.add("Surface", surfaceFormat); } if (frameConversion != null) { layout.add("Frame conversion", frameConversion); } layout.addDivider(); if (audioFormat != null) { layout.add("Audio", audioFormat); } if (channels != null) { layout.add("Channels", channels); } if (sampleRate != null) { layout.add("Sample rate", sampleRate + " Hz"); } layout.addDivider(); if (encoder != null) { layout.add("Encoder", encoder); } if (!StringUtils.isEmptyOrWhitespace(title)) { layout.add("Title", title); } return dialog; }); } private boolean controlsVisible = false; public void invalidateControlsVisibility() { boolean visible = initialized && instance.galleryInstance.callback.isSystemUiVisible(); if (layoutConfiguration >= 0 && controlsVisible != visible) { controlsView.animate().cancel(); if (visible) { controlsView.setVisibility(View.VISIBLE); controlsView.animate().alpha(1f).translationY(0f).setDuration(250).setListener(null) .setInterpolator(AnimationUtils.DECELERATE_INTERPOLATOR).start(); } else { controlsView.animate().alpha(0f).translationY(controlsView.getHeight() - configurationView.getHeight()).setDuration(350) .setListener(new AnimationUtils.VisibilityListener(controlsView, View.GONE)) .setInterpolator(AnimationUtils.ACCELERATE_DECELERATE_INTERPOLATOR).start(); } controlsVisible = visible; } } private final VideoPlayer.Listener playerListener = new VideoPlayer.Listener() { @Override public void onComplete(VideoPlayer player) { switch (Preferences.getVideoCompletionMode()) { case NOTHING: { finishedPlayback = true; updatePlayState(); break; } case LOOP: { player.setPosition(0L); break; } default: { throw new IllegalStateException(); } } } @Override public void onBusyStateChange(VideoPlayer player, boolean busy) { if (initialized) { PagerInstance.ViewHolder holder = instance.currentHolder; if (busy) { holder.progressBar.setIndeterminate(true); } holder.progressBar.setVisible(busy, false); } } @Override public void onDimensionChange(VideoPlayer player) { if (backgroundDrawable != null) { backgroundDrawable.recycle(); Point dimensions = player.getDimensions(); backgroundDrawable.width = dimensions.x; backgroundDrawable.height = dimensions.y; instance.currentHolder.photoView.resetScale(); } } }; public void showHideVideoView(boolean show) { if (initialized) { View videoView = player.getVideoView(instance.galleryInstance.context); if (show) { backgroundDrawable.recycle(); videoView.setVisibility(View.VISIBLE); } else { backgroundDrawable.setFrame(player.getCurrentFrame()); videoView.setVisibility(View.GONE); } } } public void handleSwipingContent(boolean swiping, boolean hideSurface) { if (initialized) { playPauseButton.setEnabled(!swiping); seekBar.setEnabled(!swiping); if (swiping) { wasPlaying = player.isPlaying(); setPlaying(false, true); if (hideSurface) { showHideVideoView(false); } } else { setPlaying(wasPlaying, true); if (hideSurface) { showHideVideoView(true); } updatePlayState(); } } else if (player != null) { wasPlaying = !swiping; hideSurfaceOnInit = hideSurface && swiping; } } private class ReadVideoCallback implements ReadVideoTask.Callback, VideoPlayer.RangeCallback { private final VideoPlayer workPlayer; private final PagerInstance.ViewHolder holder; private final String chanName; private final Uri uri; private ReadVideoTask downloadTask; private ReadVideoTask rangeTask; private boolean allowRangeRequests; public ReadVideoCallback(VideoPlayer player, PagerInstance.ViewHolder holder, String chanName, Uri uri) { this.workPlayer = player; this.holder = holder; this.chanName = chanName; this.uri = uri; allowRangeRequests = !AdvancedPreferences.isSingleConnection(chanName); Chan chan = Chan.getPreferred(chanName, uri); downloadTask = new ReadVideoTask(this, chan, uri, 0); downloadTask.execute(ConcurrentUtils.PARALLEL_EXECUTOR); } public void cancel() { if (downloadTask != null) { downloadTask.cancel(); downloadTask = null; } if (rangeTask != null) { rangeTask.cancel(); rangeTask = null; } } @Override public void onReadVideoInit(File partialFile) { if (workPlayer == player) { new Thread(() -> { boolean success; try { workPlayer.init(partialFile, ReadVideoCallback.this); success = true; } catch (VideoPlayer.InitializationException e) { e.printStackTrace(); success = false; } catch (IOException e) { success = false; } boolean successFinal = success; ConcurrentUtils.HANDLER.post(() -> { if (workPlayer == player) { holder.progressBar.setVisible(false, false); if (successFinal) { initializePlayer(); if (downloadTask == null) { seekBar.setSecondaryProgress(seekBar.getMax()); holder.loadState = PagerInstance.LoadState.COMPLETE; } instance.galleryInstance.callback.invalidateOptionsMenu(); } else { if (downloadTask != null) { if (!downloadTask.isError()) { downloadTask.cancel(); downloadTask = null; } else { return; } } if (rangeTask != null) { rangeTask.cancel(); rangeTask = null; } instance.callback.showError(holder, instance.galleryInstance.context .getString(R.string.playback_error)); } } }); }).start(); } } @Override public void onReadVideoProgressUpdate(long progress, long progressMax) { if (workPlayer == player) { workPlayer.setDownloadRange(progress, progressMax); if (instance.currentHolder.mediaSummary.updateSize(progressMax)) { instance.galleryInstance.callback.updateTitle(); } if (initialized) { int max = seekBar.getMax(); if (max > 0 && progressMax > 0) { int newProgress = (int) (max * progress / progressMax); seekBar.setSecondaryProgress(newProgress); } } } } @Override public void onReadVideoRangeUpdate(long start, long end) { if (workPlayer == player) { workPlayer.setPartRange(start, end); } } @Override public void onReadVideoSuccess(boolean partial, File file) { if (workPlayer == player) { if (partial) { rangeTask = null; } else { downloadTask = null; long length = file.length(); workPlayer.setDownloadRange(length, length); if (instance.currentHolder.mediaSummary.updateSize(length)) { instance.galleryInstance.callback.updateTitle(); } if (initialized) { seekBar.setSecondaryProgress(seekBar.getMax()); holder.loadState = PagerInstance.LoadState.COMPLETE; instance.galleryInstance.callback.invalidateOptionsMenu(); } } } } @Override public void onReadVideoFail(boolean partial, ErrorItem errorItem, boolean disallowRangeRequests) { if (workPlayer == player) { if (partial) { rangeTask = null; if (disallowRangeRequests) { allowRangeRequests = false; } } else { holder.progressBar.setVisible(false, false); instance.callback.showError(holder, errorItem.toString()); } } } @Override public void requestPartFromPosition(long start) { if (rangeTask != null) { rangeTask.cancel(); rangeTask = null; } if (allowRangeRequests && start > 0) { Chan chan = Chan.getPreferred(chanName, uri); rangeTask = new ReadVideoTask(this, chan, uri, start); rangeTask.execute(ConcurrentUtils.PARALLEL_EXECUTOR); } } } private static class BackgroundDrawable extends BaseDrawable { public int width; public int height; private Bitmap frame; private boolean draw = false; public void setFrame(Bitmap frame) { recycleInternal(); this.frame = frame; draw = true; invalidateSelf(); } public void recycle() { recycleInternal(); if (draw) { draw = false; invalidateSelf(); } } private void recycleInternal() { if (frame != null) { frame.recycle(); frame = null; } } private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG); @Override public void draw(@NonNull Canvas canvas) { if (draw) { Rect bounds = getBounds(); paint.setColor(Color.BLACK); canvas.drawRect(bounds, paint); if (frame != null) { canvas.drawBitmap(frame, null, bounds, paint); } } } @Override public int getOpacity() { return PixelFormat.TRANSPARENT; } @Override public int getIntrinsicWidth() { return width; } @Override public int getIntrinsicHeight() { return height; } } }
src/com/mishiranu/dashchan/ui/gallery/VideoUnit.java
package com.mishiranu.dashchan.ui.gallery; import android.app.AlertDialog; import android.content.Context; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Point; import android.graphics.Rect; import android.net.Uri; import android.view.Gravity; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.fragment.app.FragmentManager; import chan.content.Chan; import chan.util.StringUtils; import com.mishiranu.dashchan.C; import com.mishiranu.dashchan.R; import com.mishiranu.dashchan.content.AdvancedPreferences; import com.mishiranu.dashchan.content.Preferences; import com.mishiranu.dashchan.content.async.ReadVideoTask; import com.mishiranu.dashchan.content.model.ErrorItem; import com.mishiranu.dashchan.graphics.BaseDrawable; import com.mishiranu.dashchan.media.VideoPlayer; import com.mishiranu.dashchan.ui.InstanceDialog; import com.mishiranu.dashchan.util.AnimationUtils; import com.mishiranu.dashchan.util.AudioFocus; import com.mishiranu.dashchan.util.ConcurrentUtils; import com.mishiranu.dashchan.util.ResourceUtils; import com.mishiranu.dashchan.util.ViewUtils; import com.mishiranu.dashchan.widget.SummaryLayout; import java.io.File; import java.io.IOException; import java.util.Locale; import java.util.Map; public class VideoUnit { private final PagerInstance instance; private final LinearLayout controlsView; private final AudioFocus audioFocus; private int layoutConfiguration = -1; private LinearLayout configurationView; private TextView timeTextView; private TextView totalTimeTextView; private SeekBar seekBar; private ImageButton playPauseButton; private VideoPlayer player; private BackgroundDrawable backgroundDrawable; private boolean initialized; private boolean wasPlaying; private boolean pausedByTransientLossOfFocus; private boolean finishedPlayback; private boolean trackingNow; private boolean hideSurfaceOnInit; private ReadVideoCallback readVideoCallback; public VideoUnit(PagerInstance instance) { this.instance = instance; controlsView = new LinearLayout(instance.galleryInstance.context); controlsView.setOrientation(LinearLayout.VERTICAL); controlsView.setVisibility(View.GONE); audioFocus = new AudioFocus(instance.galleryInstance.context, change -> { switch (change) { case LOSS: { setPlaying(false, false); updatePlayState(); break; } case LOSS_TRANSIENT: { boolean playing = player.isPlaying(); setPlaying(false, false); if (playing) { pausedByTransientLossOfFocus = true; } updatePlayState(); break; } case GAIN: { if (pausedByTransientLossOfFocus) { setPlaying(true, false); } updatePlayState(); break; } } }); } public void addViews(FrameLayout frameLayout) { frameLayout.addView(controlsView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM)); } public void onResume() { if (player != null && initialized) { setPlaying(wasPlaying, true); updatePlayState(); } else { wasPlaying = true; } } public void onPause() { if (player != null && initialized) { wasPlaying = player.isPlaying(); setPlaying(false, true); } else { wasPlaying = false; } } public void onConfigurationChanged(Configuration newConfig) { if (newConfig.orientation != Configuration.ORIENTATION_UNDEFINED) { if (layoutConfiguration != -1) { recreateVideoControls(); } } } public void onApplyWindowInsets(int left, int right, int bottom) { if (C.API_LOLLIPOP) { controlsView.setPadding(left, 0, right, bottom); } } public boolean isInitialized() { return initialized; } public boolean isCreated() { return player != null; } public void interrupt() { if (readVideoCallback != null) { readVideoCallback.cancel(); readVideoCallback = null; } if (initialized) { audioFocus.release(); initialized = false; } invalidateControlsVisibility(); if (player != null) { player.destroy(); player = null; instance.currentHolder.progressBar.setVisible(false, false); } if (backgroundDrawable != null) { backgroundDrawable.recycle(); backgroundDrawable = null; } interruptHolder(instance.leftHolder); interruptHolder(instance.currentHolder); interruptHolder(instance.rightHolder); } private void interruptHolder(PagerInstance.ViewHolder holder) { if (holder != null) { holder.surfaceParent.removeAllViews(); } } public void forcePause() { if (initialized) { wasPlaying = false; setPlaying(false, true); } } public void applyVideo(Uri uri, File file, boolean reload) { wasPlaying = true; finishedPlayback = false; hideSurfaceOnInit = false; boolean seekAnyFrame = Preferences.isVideoSeekAnyFrame(); VideoPlayer player = new VideoPlayer(playerListener, seekAnyFrame); boolean loadedFromFile = false; if (!reload && file.exists()) { try { player.init(file, null); loadedFromFile = true; } catch (IOException e) { // Player was consumed, create a new one and try to download a new video file player = new VideoPlayer(playerListener, seekAnyFrame); } } this.player = player; if (loadedFromFile) { initializePlayer(); seekBar.setSecondaryProgress(seekBar.getMax()); if (instance.currentHolder.mediaSummary.updateSize(file.length())) { instance.galleryInstance.callback.updateTitle(); } instance.currentHolder.loadState = PagerInstance.LoadState.COMPLETE; instance.galleryInstance.callback.invalidateOptionsMenu(); } else { instance.currentHolder.progressBar.setIndeterminate(true); instance.currentHolder.progressBar.setVisible(true, false); readVideoCallback = new ReadVideoCallback(player, instance.currentHolder, instance.galleryInstance.chanName, uri); } } private boolean setPlaying(boolean playing, boolean resetFocus) { if (player.isPlaying() != playing) { if (resetFocus && player.isAudioPresent()) { if (playing) { if (!audioFocus.acquire()) { return false; } } else { audioFocus.release(); } } player.setPlaying(playing); pausedByTransientLossOfFocus = false; } return true; } private void initializePlayer() { PagerInstance.ViewHolder holder = instance.currentHolder; holder.progressBar.setVisible(false, false); Point dimensions = player.getDimensions(); if (holder.mediaSummary.updateDimensions(dimensions.x, dimensions.y)) { instance.galleryInstance.callback.updateTitle(); } backgroundDrawable = new BackgroundDrawable(); backgroundDrawable.width = dimensions.x; backgroundDrawable.height = dimensions.y; holder.recyclePhotoView(); holder.photoView.setImage(backgroundDrawable, false, true, false); View videoView = player.getVideoView(instance.galleryInstance.context); holder.surfaceParent.addView(videoView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT, Gravity.CENTER)); recreateVideoControls(); playPauseButton.setEnabled(true); seekBar.setEnabled(true); initialized = true; pausedByTransientLossOfFocus = false; if (hideSurfaceOnInit) { showHideVideoView(false); } invalidateControlsVisibility(); setPlaying(wasPlaying, true); updatePlayState(); } private void recreateVideoControls() { Context context = instance.galleryInstance.context; float density = ResourceUtils.obtainDensity(context); int targetLayoutCounfiguration = ResourceUtils.isTabletOrLandscape(context.getResources() .getConfiguration()) ? 1 : 0; if (targetLayoutCounfiguration != layoutConfiguration) { boolean firstTimeLayout = layoutConfiguration < 0; layoutConfiguration = targetLayoutCounfiguration; boolean longLayout = targetLayoutCounfiguration == 1; controlsView.removeAllViews(); if (seekBar != null) { seekBar.removeCallbacks(progressRunnable); } trackingNow = false; configurationView = new LinearLayout(context); configurationView.setOrientation(LinearLayout.HORIZONTAL); configurationView.setGravity(Gravity.END); configurationView.setPadding((int) (8f * density), 0, (int) (8f * density), 0); controlsView.addView(configurationView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); LinearLayout controls = new LinearLayout(context); controls.setOrientation(longLayout ? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL); controls.setBackgroundColor(instance.galleryInstance.actionBarColor); controls.setPadding((int) (8f * density), longLayout ? 0 : (int) (8f * density), (int) (8f * density), 0); controls.setClickable(true); controlsView.addView(controls, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); CharSequence oldTimeText = timeTextView != null ? timeTextView.getText() : null; timeTextView = new TextView(context, null, android.R.attr.textAppearanceListItem); ViewUtils.setTextSizeScaled(timeTextView, 14); timeTextView.setGravity(Gravity.CENTER_HORIZONTAL); if (C.API_LOLLIPOP) { timeTextView.setTypeface(ResourceUtils.TYPEFACE_MEDIUM); } if (oldTimeText != null) { timeTextView.setText(oldTimeText); } totalTimeTextView = new TextView(context, null, android.R.attr.textAppearanceListItem); ViewUtils.setTextSizeScaled(totalTimeTextView, 14); totalTimeTextView.setGravity(Gravity.CENTER_HORIZONTAL); if (C.API_LOLLIPOP) { totalTimeTextView.setTypeface(ResourceUtils.TYPEFACE_MEDIUM); } int oldSecondaryProgress = seekBar != null ? seekBar.getSecondaryProgress() : -1; seekBar = new SeekBar(context); seekBar.setOnSeekBarChangeListener(seekBarListener); if (oldSecondaryProgress >= 0) { seekBar.setSecondaryProgress(oldSecondaryProgress); } playPauseButton = new ImageButton(context, null, android.R.attr.borderlessButtonStyle); playPauseButton.setScaleType(ImageButton.ScaleType.CENTER); playPauseButton.setOnClickListener(playPauseClickListener); if (longLayout) { controls.setGravity(Gravity.CENTER_VERTICAL); controls.addView(timeTextView, (int) (48f * density), LinearLayout.LayoutParams.WRAP_CONTENT); controls.addView(seekBar, new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)); controls.addView(playPauseButton, (int) (80f * density), LinearLayout.LayoutParams.WRAP_CONTENT); controls.addView(totalTimeTextView, (int) (48f * density), LinearLayout.LayoutParams.WRAP_CONTENT); } else { LinearLayout controls1 = new LinearLayout(context); controls1.setOrientation(LinearLayout.HORIZONTAL); controls1.setGravity(Gravity.CENTER_VERTICAL); controls1.setPadding(0, (int) (8f * density), 0, (int) (8f * density)); LinearLayout controls2 = new LinearLayout(context); controls2.setOrientation(LinearLayout.HORIZONTAL); controls2.setGravity(Gravity.CENTER_VERTICAL); controls.addView(controls1, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); controls.addView(controls2, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); controls1.addView(seekBar, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); controls2.addView(timeTextView, new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)); controls2.addView(playPauseButton, (int) (80f * density), LinearLayout.LayoutParams.WRAP_CONTENT); controls2.addView(totalTimeTextView, new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)); } if (firstTimeLayout) { AnimationUtils.measureDynamicHeight(controlsView); controlsView.setTranslationY(controlsView.getMeasuredHeight()); controlsView.setAlpha(0f); } } if (player != null) { configurationView.removeAllViews(); if (!player.isAudioPresent()) { ImageView imageView = new ImageView(context); imageView.setImageDrawable(ResourceUtils.getDrawable(context, R.attr.iconActionVolumeOff, 0)); imageView.setScaleType(ImageView.ScaleType.CENTER); if (C.API_LOLLIPOP) { imageView.setImageAlpha(0x99); } configurationView.addView(imageView, (int) (48f * density), (int) (48f * density)); } long duration = player.getDuration(); totalTimeTextView.setText(formatVideoTime(duration)); seekBar.setMax((int) duration); } seekBar.removeCallbacks(progressRunnable); seekBar.post(progressRunnable); updatePlayState(); } private static String formatVideoTime(long position) { position /= 1000; int m = (int) (position / 60 % 60); int s = (int) (position % 60); return String.format(Locale.US, "%02d:%02d", m, s); } private final View.OnClickListener playPauseClickListener = new View.OnClickListener() { @Override public void onClick(View v) { if (initialized) { if (finishedPlayback) { finishedPlayback = false; player.setPosition(0); setPlaying(true, true); } else { boolean playing = !player.isPlaying(); setPlaying(playing, true); } updatePlayState(); } } }; private final Runnable progressRunnable = new Runnable() { @Override public void run() { if (initialized) { int position; if (trackingNow) { position = seekBar.getProgress(); } else { position = (int) player.getPosition(); seekBar.setProgress(position); } timeTextView.setText(formatVideoTime(position)); } seekBar.postDelayed(this, 200); } }; private final SeekBar.OnSeekBarChangeListener seekBarListener = new SeekBar.OnSeekBarChangeListener() { private int nextSeekPosition; @Override public void onStopTrackingTouch(SeekBar seekBar) { trackingNow = false; seekBar.removeCallbacks(progressRunnable); if (nextSeekPosition != -1) { seekBar.setProgress(nextSeekPosition); player.setPosition(nextSeekPosition); seekBar.postDelayed(progressRunnable, 250); if (finishedPlayback) { finishedPlayback = false; updatePlayState(); } } else { progressRunnable.run(); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { trackingNow = true; seekBar.removeCallbacks(progressRunnable); nextSeekPosition = -1; } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { nextSeekPosition = progress; } } }; private void updatePlayState() { if (player != null) { boolean playing = player.isPlaying(); playPauseButton.setImageResource(ResourceUtils .getResourceId(instance.galleryInstance.context, finishedPlayback ? R.attr.iconButtonRefresh : playing ? R.attr.iconButtonPause : R.attr.iconButtonPlay, 0)); instance.galleryInstance.callback.setScreenOnFixed(!finishedPlayback && playing); } } public void viewTechnicalInfo() { if (initialized) { Map<String, String> technicalInfo = player.getTechnicalInfo(); showTechnicalInfo(instance.galleryInstance.callback.getChildFragmentManager(), technicalInfo); } } private static void showTechnicalInfo(FragmentManager fragmentManager, Map<String, String> technicalInfo) { new InstanceDialog(fragmentManager, null, provider -> { Context context = GalleryInstance.getCallback(provider).getWindow().getContext(); AlertDialog dialog = new AlertDialog.Builder(context) .setTitle(R.string.technical_info) .setPositiveButton(android.R.string.ok, null) .create(); SummaryLayout layout = new SummaryLayout(dialog); String videoFormat = technicalInfo.get("video_format"); String width = technicalInfo.get("width"); String height = technicalInfo.get("height"); String frameRate = technicalInfo.get("frame_rate"); String pixelFormat = technicalInfo.get("pixel_format"); String surfaceFormat = technicalInfo.get("surface_format"); String frameConversion = technicalInfo.get("frame_conversion"); String audioFormat = technicalInfo.get("audio_format"); String channels = technicalInfo.get("channels"); String sampleRate = technicalInfo.get("sample_rate"); String encoder = technicalInfo.get("encoder"); String title = technicalInfo.get("title"); if (videoFormat != null) { layout.add("Video", videoFormat); } if (width != null && height != null) { layout.add("Resolution", width + '×' + height); } if (frameRate != null) { layout.add("Frame rate", StringUtils.stripTrailingZeros(frameRate) + " FPS"); } if (pixelFormat != null) { layout.add("Pixels", pixelFormat); } if (surfaceFormat != null) { layout.add("Surface", surfaceFormat); } if (frameConversion != null) { layout.add("Frame conversion", frameConversion); } layout.addDivider(); if (audioFormat != null) { layout.add("Audio", audioFormat); } if (channels != null) { layout.add("Channels", channels); } if (sampleRate != null) { layout.add("Sample rate", sampleRate + " Hz"); } layout.addDivider(); if (encoder != null) { layout.add("Encoder", encoder); } if (!StringUtils.isEmptyOrWhitespace(title)) { layout.add("Title", title); } return dialog; }); } private boolean controlsVisible = false; public void invalidateControlsVisibility() { boolean visible = initialized && instance.galleryInstance.callback.isSystemUiVisible(); if (layoutConfiguration >= 0 && controlsVisible != visible) { controlsView.animate().cancel(); if (visible) { controlsView.setVisibility(View.VISIBLE); controlsView.animate().alpha(1f).translationY(0f).setDuration(250).setListener(null) .setInterpolator(AnimationUtils.DECELERATE_INTERPOLATOR).start(); } else { controlsView.animate().alpha(0f).translationY(controlsView.getHeight() - configurationView.getHeight()).setDuration(350) .setListener(new AnimationUtils.VisibilityListener(controlsView, View.GONE)) .setInterpolator(AnimationUtils.ACCELERATE_DECELERATE_INTERPOLATOR).start(); } controlsVisible = visible; } } private final VideoPlayer.Listener playerListener = new VideoPlayer.Listener() { @Override public void onComplete(VideoPlayer player) { switch (Preferences.getVideoCompletionMode()) { case NOTHING: { finishedPlayback = true; updatePlayState(); break; } case LOOP: { player.setPosition(0L); break; } default: { throw new IllegalStateException(); } } } @Override public void onBusyStateChange(VideoPlayer player, boolean busy) { if (initialized) { PagerInstance.ViewHolder holder = instance.currentHolder; if (busy) { holder.progressBar.setIndeterminate(true); } holder.progressBar.setVisible(busy, false); } } @Override public void onDimensionChange(VideoPlayer player) { if (backgroundDrawable != null) { backgroundDrawable.recycle(); Point dimensions = player.getDimensions(); backgroundDrawable.width = dimensions.x; backgroundDrawable.height = dimensions.y; instance.currentHolder.photoView.resetScale(); } } }; public void showHideVideoView(boolean show) { if (initialized) { View videoView = player.getVideoView(instance.galleryInstance.context); if (show) { backgroundDrawable.recycle(); videoView.setVisibility(View.VISIBLE); } else { backgroundDrawable.setFrame(player.getCurrentFrame()); videoView.setVisibility(View.GONE); } } } public void handleSwipingContent(boolean swiping, boolean hideSurface) { if (initialized) { playPauseButton.setEnabled(!swiping); seekBar.setEnabled(!swiping); if (swiping) { wasPlaying = player.isPlaying(); setPlaying(false, true); if (hideSurface) { showHideVideoView(false); } } else { setPlaying(wasPlaying, true); if (hideSurface) { showHideVideoView(true); } updatePlayState(); } } else if (player != null) { wasPlaying = !swiping; hideSurfaceOnInit = hideSurface && swiping; } } private class ReadVideoCallback implements ReadVideoTask.Callback, VideoPlayer.RangeCallback { private final VideoPlayer workPlayer; private final PagerInstance.ViewHolder holder; private final String chanName; private final Uri uri; private ReadVideoTask downloadTask; private ReadVideoTask rangeTask; private boolean allowRangeRequests; public ReadVideoCallback(VideoPlayer player, PagerInstance.ViewHolder holder, String chanName, Uri uri) { this.workPlayer = player; this.holder = holder; this.chanName = chanName; this.uri = uri; allowRangeRequests = !AdvancedPreferences.isSingleConnection(chanName); Chan chan = Chan.getPreferred(chanName, uri); downloadTask = new ReadVideoTask(this, chan, uri, 0); downloadTask.execute(ConcurrentUtils.PARALLEL_EXECUTOR); } public void cancel() { if (downloadTask != null) { downloadTask.cancel(); downloadTask = null; } if (rangeTask != null) { rangeTask.cancel(); rangeTask = null; } } @Override public void onReadVideoInit(File partialFile) { if (workPlayer == player) { new Thread(() -> { boolean success; try { workPlayer.init(partialFile, ReadVideoCallback.this); success = true; } catch (VideoPlayer.InitializationException e) { e.printStackTrace(); success = false; } catch (IOException e) { success = false; } boolean successFinal = success; ConcurrentUtils.HANDLER.post(() -> { if (workPlayer == player) { holder.progressBar.setVisible(false, false); if (successFinal) { initializePlayer(); instance.galleryInstance.callback.invalidateOptionsMenu(); if (downloadTask == null) { seekBar.setSecondaryProgress(seekBar.getMax()); } } else { if (downloadTask != null) { if (!downloadTask.isError()) { downloadTask.cancel(); downloadTask = null; } else { return; } } if (rangeTask != null) { rangeTask.cancel(); rangeTask = null; } instance.callback.showError(holder, instance.galleryInstance.context .getString(R.string.playback_error)); } } }); }).start(); } } @Override public void onReadVideoProgressUpdate(long progress, long progressMax) { if (workPlayer == player) { workPlayer.setDownloadRange(progress, progressMax); if (instance.currentHolder.mediaSummary.updateSize(progressMax)) { instance.galleryInstance.callback.updateTitle(); } if (initialized) { int max = seekBar.getMax(); if (max > 0 && progressMax > 0) { int newProgress = (int) (max * progress / progressMax); seekBar.setSecondaryProgress(newProgress); } } } } @Override public void onReadVideoRangeUpdate(long start, long end) { if (workPlayer == player) { workPlayer.setPartRange(start, end); } } @Override public void onReadVideoSuccess(boolean partial, File file) { if (workPlayer == player) { if (partial) { rangeTask = null; } else { downloadTask = null; long length = file.length(); workPlayer.setDownloadRange(length, length); if (instance.currentHolder.mediaSummary.updateSize(length)) { instance.galleryInstance.callback.updateTitle(); } if (initialized) { seekBar.setSecondaryProgress(seekBar.getMax()); holder.loadState = PagerInstance.LoadState.COMPLETE; instance.galleryInstance.callback.invalidateOptionsMenu(); } } } } @Override public void onReadVideoFail(boolean partial, ErrorItem errorItem, boolean disallowRangeRequests) { if (workPlayer == player) { if (partial) { rangeTask = null; if (disallowRangeRequests) { allowRangeRequests = false; } } else { holder.progressBar.setVisible(false, false); instance.callback.showError(holder, errorItem.toString()); } } } @Override public void requestPartFromPosition(long start) { if (rangeTask != null) { rangeTask.cancel(); rangeTask = null; } if (allowRangeRequests && start > 0) { Chan chan = Chan.getPreferred(chanName, uri); rangeTask = new ReadVideoTask(this, chan, uri, start); rangeTask.execute(ConcurrentUtils.PARALLEL_EXECUTOR); } } } private static class BackgroundDrawable extends BaseDrawable { public int width; public int height; private Bitmap frame; private boolean draw = false; public void setFrame(Bitmap frame) { recycleInternal(); this.frame = frame; draw = true; invalidateSelf(); } public void recycle() { recycleInternal(); if (draw) { draw = false; invalidateSelf(); } } private void recycleInternal() { if (frame != null) { frame.recycle(); frame = null; } } private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG); @Override public void draw(@NonNull Canvas canvas) { if (draw) { Rect bounds = getBounds(); paint.setColor(Color.BLACK); canvas.drawRect(bounds, paint); if (frame != null) { canvas.drawBitmap(frame, null, bounds, paint); } } } @Override public int getOpacity() { return PixelFormat.TRANSPARENT; } @Override public int getIntrinsicWidth() { return width; } @Override public int getIntrinsicHeight() { return height; } } }
Fix missing "save" button for short videos
src/com/mishiranu/dashchan/ui/gallery/VideoUnit.java
Fix missing "save" button for short videos
<ide><path>rc/com/mishiranu/dashchan/ui/gallery/VideoUnit.java <ide> holder.progressBar.setVisible(false, false); <ide> if (successFinal) { <ide> initializePlayer(); <del> instance.galleryInstance.callback.invalidateOptionsMenu(); <ide> if (downloadTask == null) { <ide> seekBar.setSecondaryProgress(seekBar.getMax()); <add> holder.loadState = PagerInstance.LoadState.COMPLETE; <ide> } <add> instance.galleryInstance.callback.invalidateOptionsMenu(); <ide> } else { <ide> if (downloadTask != null) { <ide> if (!downloadTask.isError()) {
Java
apache-2.0
6d997ca26ebaa6993b0786183fb5023acf339947
0
MER-GROUP/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,da1z/intellij-community,ibinti/intellij-community,kool79/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,caot/intellij-community,da1z/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,kool79/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,kdwink/intellij-community,slisson/intellij-community,petteyg/intellij-community,semonte/intellij-community,slisson/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,izonder/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,kool79/intellij-community,ryano144/intellij-community,slisson/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,ernestp/consulo,alphafoobar/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,supersven/intellij-community,petteyg/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,allotria/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,caot/intellij-community,hurricup/intellij-community,samthor/intellij-community,blademainer/intellij-community,holmes/intellij-community,signed/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,signed/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,consulo/consulo,semonte/intellij-community,da1z/intellij-community,vladmm/intellij-community,asedunov/intellij-community,izonder/intellij-community,Lekanich/intellij-community,holmes/intellij-community,petteyg/intellij-community,fnouama/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,kool79/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,semonte/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,robovm/robovm-studio,fitermay/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,diorcety/intellij-community,asedunov/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,izonder/intellij-community,slisson/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,semonte/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,holmes/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,amith01994/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,caot/intellij-community,fitermay/intellij-community,samthor/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,jagguli/intellij-community,dslomov/intellij-community,blademainer/intellij-community,hurricup/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,gnuhub/intellij-community,caot/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,adedayo/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,nicolargo/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,amith01994/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,adedayo/intellij-community,ibinti/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,fnouama/intellij-community,semonte/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,signed/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,da1z/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,da1z/intellij-community,apixandru/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,xfournet/intellij-community,ryano144/intellij-community,ryano144/intellij-community,consulo/consulo,michaelgallacher/intellij-community,ibinti/intellij-community,ibinti/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,ernestp/consulo,idea4bsd/idea4bsd,nicolargo/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,FHannes/intellij-community,fitermay/intellij-community,holmes/intellij-community,vvv1559/intellij-community,allotria/intellij-community,supersven/intellij-community,vladmm/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,caot/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,ryano144/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,ahb0327/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,signed/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,robovm/robovm-studio,xfournet/intellij-community,tmpgit/intellij-community,allotria/intellij-community,diorcety/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,adedayo/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,asedunov/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,izonder/intellij-community,asedunov/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,kdwink/intellij-community,diorcety/intellij-community,fnouama/intellij-community,jagguli/intellij-community,clumsy/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,amith01994/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,samthor/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,ibinti/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,clumsy/intellij-community,ernestp/consulo,hurricup/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,signed/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,xfournet/intellij-community,clumsy/intellij-community,ryano144/intellij-community,caot/intellij-community,fitermay/intellij-community,kool79/intellij-community,robovm/robovm-studio,amith01994/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,fitermay/intellij-community,samthor/intellij-community,diorcety/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,slisson/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,ernestp/consulo,apixandru/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,da1z/intellij-community,Lekanich/intellij-community,kool79/intellij-community,dslomov/intellij-community,jagguli/intellij-community,consulo/consulo,allotria/intellij-community,blademainer/intellij-community,consulo/consulo,lucafavatella/intellij-community,retomerz/intellij-community,jagguli/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,adedayo/intellij-community,izonder/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,caot/intellij-community,semonte/intellij-community,adedayo/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,hurricup/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,amith01994/intellij-community,izonder/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,diorcety/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,supersven/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,allotria/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,hurricup/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,consulo/consulo,slisson/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,izonder/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,signed/intellij-community,robovm/robovm-studio,xfournet/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,consulo/consulo,allotria/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,ernestp/consulo,wreckJ/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,jagguli/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,supersven/intellij-community,ibinti/intellij-community,petteyg/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,supersven/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,samthor/intellij-community,xfournet/intellij-community,petteyg/intellij-community,ibinti/intellij-community,kool79/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,caot/intellij-community,clumsy/intellij-community,kdwink/intellij-community,supersven/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,clumsy/intellij-community,caot/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,da1z/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,ryano144/intellij-community,caot/intellij-community,hurricup/intellij-community,allotria/intellij-community,diorcety/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,FHannes/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,semonte/intellij-community,FHannes/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,retomerz/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,ernestp/consulo,supersven/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,FHannes/intellij-community,petteyg/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,vladmm/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,vladmm/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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.intellij.codeInsight.daemon.impl; import com.intellij.codeHighlighting.Pass; import com.intellij.codeHighlighting.TextEditorHighlightingPass; import com.intellij.codeInsight.CodeInsightSettings; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInsight.daemon.ImplicitUsageProvider; import com.intellij.codeInsight.daemon.JavaErrorMessages; import com.intellij.codeInsight.daemon.impl.analysis.HighlightLevelUtil; import com.intellij.codeInsight.daemon.impl.analysis.HighlightMessageUtil; import com.intellij.codeInsight.daemon.impl.analysis.HighlightMethodUtil; import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil; import com.intellij.codeInsight.daemon.impl.quickfix.*; import com.intellij.codeInsight.intention.EmptyIntentionAction; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInsight.intention.IntentionManager; import com.intellij.codeInspection.InspectionProfile; import com.intellij.codeInspection.InspectionProfileEntry; import com.intellij.codeInspection.InspectionsBundle; import com.intellij.codeInspection.deadCode.UnusedDeclarationInspection; import com.intellij.codeInspection.ex.GlobalInspectionToolWrapper; import com.intellij.codeInspection.ex.InspectionManagerEx; import com.intellij.codeInspection.ex.LocalInspectionToolWrapper; import com.intellij.codeInspection.reference.UnusedDeclarationFixProvider; import com.intellij.codeInspection.unusedImport.UnusedImportLocalInspection; import com.intellij.codeInspection.unusedParameters.UnusedParametersInspection; import com.intellij.codeInspection.unusedSymbol.UnusedSymbolLocalInspection; import com.intellij.codeInspection.util.SpecialAnnotationsUtil; import com.intellij.diagnostic.LogMessageEx; import com.intellij.diagnostic.errordialog.Attachment; import com.intellij.find.FindManager; import com.intellij.find.findUsages.*; import com.intellij.find.impl.FindManagerImpl; import com.intellij.lang.Language; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.undo.UndoManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.profile.codeInspection.InspectionProjectProfileManager; import com.intellij.psi.*; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.impl.PsiClassImplUtil; import com.intellij.psi.impl.source.PsiClassImpl; import com.intellij.psi.impl.source.jsp.jspJava.JspxImportStatement; import com.intellij.psi.jsp.JspFile; import com.intellij.psi.jsp.JspSpiUtil; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiSearchHelper; import com.intellij.psi.search.SearchScope; import com.intellij.psi.search.searches.OverridingMethodsSearch; import com.intellij.psi.search.searches.SuperMethodsSearch; import com.intellij.psi.util.PropertyUtil; import com.intellij.psi.util.PsiUtilCore; import com.intellij.refactoring.changeSignature.ChangeSignatureGestureDetector; import com.intellij.util.Processor; import gnu.trove.THashSet; import gnu.trove.TObjectIntHashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.PropertyKey; import java.util.*; public class PostHighlightingPass extends TextEditorHighlightingPass { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.PostHighlightingPass"); private RefCountHolder myRefCountHolder; private final PsiFile myFile; @Nullable private final Editor myEditor; private final int myStartOffset; private final int myEndOffset; private Collection<HighlightInfo> myHighlights; private boolean myHasRedundantImports; private final JavaCodeStyleManager myStyleManager; private int myCurrentEntryIndex; private boolean myHasMissortedImports; private final ImplicitUsageProvider[] myImplicitUsageProviders; private UnusedDeclarationInspection myDeadCodeInspection; private UnusedSymbolLocalInspection myUnusedSymbolInspection; private HighlightDisplayKey myUnusedSymbolKey; private boolean myDeadCodeEnabled; private boolean myInLibrary; private HighlightDisplayKey myDeadCodeKey; private HighlightInfoType myDeadCodeInfoType; private UnusedParametersInspection myUnusedParametersInspection; PostHighlightingPass(@NotNull Project project, @NotNull PsiFile file, @Nullable Editor editor, @NotNull Document document) { super(project, document, true); myFile = file; myEditor = editor; myStartOffset = 0; myEndOffset = file.getTextLength(); myStyleManager = JavaCodeStyleManager.getInstance(myProject); myCurrentEntryIndex = -1; myImplicitUsageProviders = Extensions.getExtensions(ImplicitUsageProvider.EP_NAME); } @Override public void doCollectInformation(final ProgressIndicator progress) { DaemonCodeAnalyzer daemonCodeAnalyzer = DaemonCodeAnalyzer.getInstance(myProject); final FileStatusMap fileStatusMap = ((DaemonCodeAnalyzerImpl)daemonCodeAnalyzer).getFileStatusMap(); final List<HighlightInfo> highlights = new ArrayList<HighlightInfo>(); final FileViewProvider viewProvider = myFile.getViewProvider(); final Set<Language> relevantLanguages = viewProvider.getLanguages(); final Set<PsiElement> elementSet = new THashSet<PsiElement>(); for (Language language : relevantLanguages) { PsiElement psiRoot = viewProvider.getPsi(language); if (!HighlightLevelUtil.shouldHighlight(psiRoot)) continue; List<PsiElement> elements = CollectHighlightsUtil.getElementsInRange(psiRoot, myStartOffset, myEndOffset); elementSet.addAll(elements); } ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex(); VirtualFile virtualFile = viewProvider.getVirtualFile(); myInLibrary = fileIndex.isInLibraryClasses(virtualFile) || fileIndex.isInLibrarySource(virtualFile); myRefCountHolder = RefCountHolder.getInstance(myFile); if (!myRefCountHolder.retrieveUnusedReferencesInfo(new Runnable() { @Override public void run() { boolean errorFound = collectHighlights(elementSet, highlights, progress); myHighlights = highlights; if (errorFound) { fileStatusMap.setErrorFoundFlag(myDocument, true); } } })) { // we must be sure GHP will restart fileStatusMap.markFileScopeDirty(getDocument(), Pass.UPDATE_ALL); GeneralHighlightingPass.cancelAndRestartDaemonLater(progress, myProject, this); } } @Override public List<HighlightInfo> getInfos() { return myHighlights == null ? null : new ArrayList<HighlightInfo>(myHighlights); } @Override public void doApplyInformationToEditor() { if (myHighlights == null) return; UpdateHighlightersUtil.setHighlightersToEditor(myProject, myDocument, myStartOffset, myEndOffset, myHighlights, getColorsScheme(), Pass.POST_UPDATE_ALL); PostHighlightingPassFactory.markFileUpToDate(myFile); Editor editor = myEditor; if (editor != null && timeToOptimizeImports()) { optimizeImportsOnTheFly(editor); } } private void optimizeImportsOnTheFly(@NotNull final Editor editor) { if (myHasRedundantImports || myHasMissortedImports) { final OptimizeImportsFix optimizeImportsFix = new OptimizeImportsFix(); if (optimizeImportsFix.isAvailable(myProject, editor, myFile) && myFile.isWritable()) { invokeOnTheFlyImportOptimizer(new Runnable() { @Override public void run() { optimizeImportsFix.invoke(myProject, editor, myFile); } }, myFile, editor); } } } public static void invokeOnTheFlyImportOptimizer(@NotNull final Runnable runnable, @NotNull final PsiFile file, @NotNull final Editor editor) { final long stamp = editor.getDocument().getModificationStamp(); ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { if (file.getProject().isDisposed() || editor.isDisposed() || editor.getDocument().getModificationStamp() != stamp) return; //no need to optimize imports on the fly during undo/redo final UndoManager undoManager = UndoManager.getInstance(editor.getProject()); if (undoManager.isUndoInProgress() || undoManager.isRedoInProgress()) return; PsiDocumentManager.getInstance(file.getProject()).commitAllDocuments(); String beforeText = file.getText(); final long oldStamp = editor.getDocument().getModificationStamp(); CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() { @Override public void run() { ApplicationManager.getApplication().runWriteAction(runnable); } }); if (oldStamp != editor.getDocument().getModificationStamp()) { String afterText = file.getText(); if (Comparing.strEqual(beforeText, afterText)) { LOG.error(LogMessageEx.createEvent("Import optimizer hasn't optimized any imports", file.getViewProvider().getVirtualFile().getPath(), new Attachment(file.getViewProvider().getVirtualFile()))); } } } }); } // returns true if error highlight was created private boolean collectHighlights(@NotNull Collection<PsiElement> elements, @NotNull final List<HighlightInfo> result, @NotNull ProgressIndicator progress) throws ProcessCanceledException { ApplicationManager.getApplication().assertReadAccessAllowed(); InspectionProfile profile = InspectionProjectProfileManager.getInstance(myProject).getInspectionProfile(); myUnusedSymbolKey = HighlightDisplayKey.find(UnusedSymbolLocalInspection.SHORT_NAME); boolean unusedSymbolEnabled = profile.isToolEnabled(myUnusedSymbolKey, myFile); HighlightDisplayKey unusedImportKey = HighlightDisplayKey.find(UnusedImportLocalInspection.SHORT_NAME); boolean unusedImportEnabled = profile.isToolEnabled(unusedImportKey, myFile); LocalInspectionToolWrapper unusedSymbolTool = (LocalInspectionToolWrapper)profile.getInspectionTool(UnusedSymbolLocalInspection.SHORT_NAME, myFile); myUnusedSymbolInspection = unusedSymbolTool == null ? null : (UnusedSymbolLocalInspection)unusedSymbolTool.getTool(); LOG.assertTrue(ApplicationManager.getApplication().isUnitTestMode() || myUnusedSymbolInspection != null); myDeadCodeKey = HighlightDisplayKey.find(UnusedDeclarationInspection.SHORT_NAME); myDeadCodeInspection = (UnusedDeclarationInspection)profile.getInspectionTool(UnusedDeclarationInspection.SHORT_NAME, myFile); myDeadCodeEnabled = profile.isToolEnabled(myDeadCodeKey, myFile); final InspectionProfileEntry inspectionTool = profile.getInspectionTool(UnusedParametersInspection.SHORT_NAME, myFile); myUnusedParametersInspection = inspectionTool != null ? (UnusedParametersInspection)((GlobalInspectionToolWrapper)inspectionTool).getTool() : null; LOG.assertTrue(ApplicationManager.getApplication().isUnitTestMode() || myUnusedParametersInspection != null); if (unusedImportEnabled && JspPsiUtil.isInJspFile(myFile)) { final JspFile jspFile = JspPsiUtil.getJspFile(myFile); if (jspFile != null) { unusedImportEnabled = !JspSpiUtil.isIncludedOrIncludesSomething(jspFile); } } myDeadCodeInfoType = myDeadCodeKey == null ? null : new HighlightInfoType.HighlightInfoTypeImpl(profile.getErrorLevel(myDeadCodeKey, myFile).getSeverity(), HighlightInfoType.UNUSED_SYMBOL.getAttributesKey()); boolean errorFound = false; if (unusedSymbolEnabled) { for (PsiElement element : elements) { progress.checkCanceled(); if (element instanceof PsiIdentifier) { PsiIdentifier identifier = (PsiIdentifier)element; HighlightInfo info = processIdentifier(identifier, progress); if (info != null) { errorFound |= info.getSeverity() == HighlightSeverity.ERROR; result.add(info); } } } } if (unusedImportEnabled && myFile instanceof PsiJavaFile && HighlightLevelUtil.shouldHighlight(myFile)) { PsiImportList importList = ((PsiJavaFile)myFile).getImportList(); if (importList != null) { final PsiImportStatementBase[] imports = importList.getAllImportStatements(); for (PsiImportStatementBase statement : imports) { progress.checkCanceled(); final HighlightInfo info = processImport(statement, unusedImportKey); if (info != null) { errorFound |= info.getSeverity() == HighlightSeverity.ERROR; result.add(info); } } } } return errorFound; } @Nullable private HighlightInfo processIdentifier(PsiIdentifier identifier, ProgressIndicator progress) { if (InspectionManagerEx.inspectionResultSuppressed(identifier, myUnusedSymbolInspection)) return null; PsiElement parent = identifier.getParent(); if (PsiUtilCore.hasErrorElementChild(parent)) return null; if (parent instanceof PsiLocalVariable && myUnusedSymbolInspection.LOCAL_VARIABLE) { return processLocalVariable((PsiLocalVariable)parent, progress); } if (parent instanceof PsiField && myUnusedSymbolInspection.FIELD) { return processField((PsiField)parent, identifier, progress); } if (parent instanceof PsiParameter && myUnusedSymbolInspection.PARAMETER) { if (InspectionManagerEx.isSuppressed(identifier, UnusedParametersInspection.SHORT_NAME)) return null; return processParameter((PsiParameter)parent, progress); } if (parent instanceof PsiMethod && myUnusedSymbolInspection.METHOD) { return processMethod((PsiMethod)parent, progress); } if (parent instanceof PsiClass && myUnusedSymbolInspection.CLASS) { return processClass((PsiClass)parent, progress); } return null; } @Nullable private HighlightInfo processLocalVariable(PsiLocalVariable variable, ProgressIndicator progress) { PsiIdentifier identifier = variable.getNameIdentifier(); if (identifier == null) return null; if (isImplicitUsage(variable, progress)) return null; if (!myRefCountHolder.isReferenced(variable)) { String message = JavaErrorMessages.message("local.variable.is.never.used", identifier.getText()); HighlightInfo highlightInfo = createUnusedSymbolInfo(identifier, message, HighlightInfoType.UNUSED_SYMBOL); QuickFixAction.registerQuickFixAction(highlightInfo, new RemoveUnusedVariableFix(variable), myUnusedSymbolKey); return highlightInfo; } boolean referenced = myRefCountHolder.isReferencedForRead(variable); if (!referenced && !isImplicitRead(variable, progress)) { String message = JavaErrorMessages.message("local.variable.is.not.used.for.reading", identifier.getText()); HighlightInfo highlightInfo = createUnusedSymbolInfo(identifier, message, HighlightInfoType.UNUSED_SYMBOL); QuickFixAction.registerQuickFixAction(highlightInfo, new RemoveUnusedVariableFix(variable), myUnusedSymbolKey); return highlightInfo; } if (!variable.hasInitializer()) { referenced = myRefCountHolder.isReferencedForWrite(variable); if (!referenced && !isImplicitWrite(variable, progress)) { String message = JavaErrorMessages.message("local.variable.is.not.assigned", identifier.getText()); final HighlightInfo unusedSymbolInfo = createUnusedSymbolInfo(identifier, message, HighlightInfoType.UNUSED_SYMBOL); QuickFixAction.registerQuickFixAction(unusedSymbolInfo, new EmptyIntentionAction(UnusedSymbolLocalInspection.DISPLAY_NAME), myUnusedSymbolKey); return unusedSymbolInfo; } } return null; } private boolean isImplicitUsage(final PsiModifierListOwner element, ProgressIndicator progress) { if (UnusedSymbolLocalInspection.isInjected(element)) return true; for (ImplicitUsageProvider provider : myImplicitUsageProviders) { progress.checkCanceled(); if (provider.isImplicitUsage(element)) { return true; } } return false; } private boolean isImplicitRead(final PsiVariable element, ProgressIndicator progress) { for(ImplicitUsageProvider provider: myImplicitUsageProviders) { progress.checkCanceled(); if (provider.isImplicitRead(element)) { return true; } } return UnusedSymbolLocalInspection.isInjected(element); } private boolean isImplicitWrite(final PsiVariable element, ProgressIndicator progress) { for(ImplicitUsageProvider provider: myImplicitUsageProviders) { progress.checkCanceled(); if (provider.isImplicitWrite(element)) { return true; } } return UnusedSymbolLocalInspection.isInjected(element); } private static HighlightInfo createUnusedSymbolInfo(PsiElement element, String message, final HighlightInfoType highlightInfoType) { HighlightInfo info = HighlightInfo.createHighlightInfo(highlightInfoType, element, message); UnusedDeclarationFixProvider[] fixProviders = Extensions.getExtensions(UnusedDeclarationFixProvider.EP_NAME); for (UnusedDeclarationFixProvider provider : fixProviders) { IntentionAction[] fixes = provider.getQuickFixes(element); for (IntentionAction fix : fixes) { QuickFixAction.registerQuickFixAction(info, fix); } } return info; } @Nullable private HighlightInfo processField(final PsiField field, final PsiIdentifier identifier, ProgressIndicator progress) { if (field.hasModifierProperty(PsiModifier.PRIVATE)) { if (!myRefCountHolder.isReferenced(field) && !isImplicitUsage(field, progress)) { if (HighlightUtil.isSerializationImplicitlyUsedField(field)) { return null; } String message = JavaErrorMessages.message("private.field.is.not.used", identifier.getText()); HighlightInfo highlightInfo = suggestionsToMakeFieldUsed(field, identifier, message); if (!field.hasInitializer()) { QuickFixAction.registerQuickFixAction(highlightInfo, HighlightMethodUtil.getFixRange(field), new CreateConstructorParameterFromFieldFix(field), null); } return highlightInfo; } final boolean readReferenced = myRefCountHolder.isReferencedForRead(field); if (!readReferenced && !isImplicitRead(field, progress)) { String message = JavaErrorMessages.message("private.field.is.not.used.for.reading", identifier.getText()); return suggestionsToMakeFieldUsed(field, identifier, message); } if (field.hasInitializer()) { return null; } final boolean writeReferenced = myRefCountHolder.isReferencedForWrite(field); if (!writeReferenced && !isImplicitWrite(field, progress)) { String message = JavaErrorMessages.message("private.field.is.not.assigned", identifier.getText()); final HighlightInfo info = createUnusedSymbolInfo(identifier, message, HighlightInfoType.UNUSED_SYMBOL); QuickFixAction.registerQuickFixAction(info, new CreateGetterOrSetterFix(false, true, field), myUnusedSymbolKey); QuickFixAction.registerQuickFixAction(info, HighlightMethodUtil.getFixRange(field), new CreateConstructorParameterFromFieldFix(field), null); SpecialAnnotationsUtil.createAddToSpecialAnnotationFixes(field, new Processor<String>() { @Override public boolean process(final String annoName) { QuickFixAction.registerQuickFixAction(info, UnusedSymbolLocalInspection.createQuickFix(annoName, "fields", field.getProject())); return true; } }); return info; } } else if (isImplicitUsage(field, progress)) { return null; } else if (!myRefCountHolder.isReferenced(field) && weAreSureThereAreNoUsages(field, progress)) { return formatUnusedSymbolHighlightInfo("field.is.not.used", field, "fields", myDeadCodeKey, myDeadCodeInfoType); } return null; } private HighlightInfo suggestionsToMakeFieldUsed(final PsiField field, final PsiIdentifier identifier, final String message) { HighlightInfo highlightInfo = createUnusedSymbolInfo(identifier, message, HighlightInfoType.UNUSED_SYMBOL); QuickFixAction.registerQuickFixAction(highlightInfo, new RemoveUnusedVariableFix(field), myUnusedSymbolKey); QuickFixAction.registerQuickFixAction(highlightInfo, new CreateGetterOrSetterFix(true, false, field), myUnusedSymbolKey); QuickFixAction.registerQuickFixAction(highlightInfo, new CreateGetterOrSetterFix(false, true, field), myUnusedSymbolKey); QuickFixAction.registerQuickFixAction(highlightInfo, new CreateGetterOrSetterFix(true, true, field), myUnusedSymbolKey); return highlightInfo; } private static boolean isOverriddenOrOverrides(PsiMethod method) { boolean overrides = SuperMethodsSearch.search(method, null, true, false).findFirst() != null; return overrides || OverridingMethodsSearch.search(method).findFirst() != null; } @Nullable private HighlightInfo processParameter(PsiParameter parameter, ProgressIndicator progress) { PsiElement declarationScope = parameter.getDeclarationScope(); if (declarationScope instanceof PsiMethod) { PsiMethod method = (PsiMethod)declarationScope; if (PsiUtilCore.hasErrorElementChild(method)) return null; if ((method.isConstructor() || method.hasModifierProperty(PsiModifier.PRIVATE) || method.hasModifierProperty(PsiModifier.STATIC) || !method.hasModifierProperty(PsiModifier.ABSTRACT) && myUnusedSymbolInspection.REPORT_PARAMETER_FOR_PUBLIC_METHODS && !isOverriddenOrOverrides(method)) && !method.hasModifierProperty(PsiModifier.NATIVE) && !HighlightMethodUtil.isSerializationRelatedMethod(method, method.getContainingClass()) && !PsiClassImplUtil.isMainMethod(method)) { if (UnusedSymbolLocalInspection.isInjected(method)) return null; HighlightInfo highlightInfo = checkUnusedParameter(parameter, progress); if (highlightInfo != null) { final ArrayList<IntentionAction> options = new ArrayList<IntentionAction>(); options.addAll(IntentionManager.getInstance().getStandardIntentionOptions(myUnusedSymbolKey, myFile)); if (myUnusedParametersInspection != null) { Collections.addAll(options, myUnusedParametersInspection.getSuppressActions(parameter)); } //need suppress from Unused Parameters but settings from Unused Symbol QuickFixAction.registerQuickFixAction(highlightInfo, new RemoveUnusedParameterFix(parameter), options, HighlightDisplayKey.getDisplayNameByKey(myUnusedSymbolKey)); return highlightInfo; } } } else if (declarationScope instanceof PsiForeachStatement) { HighlightInfo highlightInfo = checkUnusedParameter(parameter, progress); if (highlightInfo != null) { QuickFixAction.registerQuickFixAction(highlightInfo, new EmptyIntentionAction(UnusedSymbolLocalInspection.DISPLAY_NAME), myUnusedSymbolKey); return highlightInfo; } } return null; } @Nullable private HighlightInfo checkUnusedParameter(final PsiParameter parameter, ProgressIndicator progress) { if (!myRefCountHolder.isReferenced(parameter) && !isImplicitUsage(parameter, progress)) { PsiIdentifier identifier = parameter.getNameIdentifier(); assert identifier != null; String message = JavaErrorMessages.message("parameter.is.not.used", identifier.getText()); return createUnusedSymbolInfo(identifier, message, HighlightInfoType.UNUSED_SYMBOL); } return null; } @Nullable private HighlightInfo processMethod(final PsiMethod method, ProgressIndicator progress) { boolean isPrivate = method.hasModifierProperty(PsiModifier.PRIVATE); PsiClass containingClass = method.getContainingClass(); if (isMethodReferenced(method, progress, isPrivate, containingClass)) return null; HighlightInfoType highlightInfoType; HighlightDisplayKey highlightDisplayKey; String key; if (isPrivate) { highlightInfoType = HighlightInfoType.UNUSED_SYMBOL; highlightDisplayKey = myUnusedSymbolKey; key = method.isConstructor() ? "private.constructor.is.not.used" : "private.method.is.not.used"; } else { highlightInfoType = myDeadCodeInfoType; highlightDisplayKey = myDeadCodeKey; key = method.isConstructor() ? "constructor.is.not.used" : "method.is.not.used"; } String symbolName = HighlightMessageUtil.getSymbolName(method, PsiSubstitutor.EMPTY); String message = JavaErrorMessages.message(key, symbolName); PsiIdentifier identifier = method.getNameIdentifier(); final HighlightInfo highlightInfo = createUnusedSymbolInfo(identifier, message, highlightInfoType); QuickFixAction.registerQuickFixAction(highlightInfo, new SafeDeleteFix(method), highlightDisplayKey); SpecialAnnotationsUtil.createAddToSpecialAnnotationFixes(method, new Processor<String>() { @Override public boolean process(final String annoName) { QuickFixAction.registerQuickFixAction(highlightInfo, UnusedSymbolLocalInspection.createQuickFix(annoName, "methods", method.getProject())); return true; } }); if (method.getReturnType() != null || containingClass != null && Comparing.strEqual(containingClass.getName(), method.getName())) { //ignore methods with deleted return types as they are always marked as unused without any reason ChangeSignatureGestureDetector.getInstance(myProject).dismissForElement(method); } return highlightInfo; } private boolean isMethodReferenced(PsiMethod method, ProgressIndicator progress, boolean aPrivate, PsiClass containingClass) { if (myRefCountHolder.isReferenced(method)) return true; if (HighlightMethodUtil.isSerializationRelatedMethod(method, containingClass)) return true; if (aPrivate) { if (isIntentionalPrivateConstructor(method, containingClass)) { return true; } if (isImplicitUsage(method, progress)) { return true; } } else { //class maybe used in some weird way, e.g. from XML, therefore the only constructor is used too if (containingClass != null && method.isConstructor() && containingClass.getConstructors().length == 1 && isClassUnused(containingClass, progress) == USED) { return true; } if (isImplicitUsage(method, progress)) return true; if (method.findSuperMethods().length != 0) { return true; } if (!weAreSureThereAreNoUsages(method, progress)) { return true; } } return false; } private boolean weAreSureThereAreNoUsages(PsiMember member, ProgressIndicator progress) { if (myInLibrary) return false; if (!myDeadCodeEnabled) return false; if (myDeadCodeInspection.isEntryPoint(member)) return false; String name = member.getName(); if (name == null) return false; SearchScope useScope = member.getUseScope(); if (!(useScope instanceof GlobalSearchScope)) return false; GlobalSearchScope scope = (GlobalSearchScope)useScope; // some classes may have references from within XML outside dependent modules, e.g. our actions if (member instanceof PsiClass) scope = GlobalSearchScope.projectScope(myProject).uniteWith(scope); PsiSearchHelper.SearchCostResult cheapEnough = PsiSearchHelper.SERVICE.getInstance(myFile.getProject()) .isCheapEnoughToSearch(name, scope, myFile, progress); if (cheapEnough == PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES) return false; //search usages if it cheap //if count is 0 there is no usages since we've called myRefCountHolder.isReferenced() before if (cheapEnough == PsiSearchHelper.SearchCostResult.ZERO_OCCURRENCES) { if (member instanceof PsiEnumConstant) { return !isEnumValuesMethodUsed(member, progress); } if (!canBeReferencedViaWeirdNames(member)) return true; } FindUsagesManager findUsagesManager = ((FindManagerImpl)FindManager.getInstance(myProject)).getFindUsagesManager(); FindUsagesOptions findUsagesOptions; if (member instanceof PsiClass) { findUsagesOptions = new JavaClassFindUsagesOptions(myProject); } else if (member instanceof PsiMethod) { findUsagesOptions = new JavaMethodFindUsagesOptions(myProject); } else if (member instanceof PsiField) { findUsagesOptions = new JavaVariableFindUsagesOptions(myProject); } else { LOG.error("unknown member: " + member); return false; } findUsagesOptions.searchScope = scope; boolean used = findUsagesManager.isUsed(member, findUsagesOptions); if (!used && member instanceof PsiEnumConstant) { return !isEnumValuesMethodUsed(member, progress); } return !used; } private boolean isEnumValuesMethodUsed(PsiMember member, ProgressIndicator progress) { final PsiClassImpl containingClass = (PsiClassImpl)member.getContainingClass(); if (containingClass == null) return true; final PsiMethod valuesMethod = containingClass.getValuesMethod(); if (valuesMethod == null) return true; boolean isPrivate = valuesMethod.hasModifierProperty(PsiModifier.PRIVATE); return isMethodReferenced(valuesMethod, progress, isPrivate, containingClass); } private static boolean canBeReferencedViaWeirdNames(PsiMember member) { if (member instanceof PsiClass) return false; PsiFile containingFile = member.getContainingFile(); if (!(containingFile instanceof PsiJavaFile)) return true; // Groovy field can be referenced from Java by getter if (member instanceof PsiField) return false; //Java field cannot be referenced by anything but its name if (member instanceof PsiMethod) { return PropertyUtil.isSimplePropertyAccessor((PsiMethod)member); //Java accessors can be referenced by field name from Groovy } return false; } @Nullable private HighlightInfo processClass(PsiClass aClass, ProgressIndicator progress) { int usage = isClassUnused(aClass, progress); if (usage == USED) return null; String pattern; HighlightDisplayKey highlightDisplayKey; HighlightInfoType highlightInfoType; if (aClass.getContainingClass() != null && aClass.hasModifierProperty(PsiModifier.PRIVATE)) { pattern = aClass.isInterface() ? "private.inner.interface.is.not.used" : "private.inner.class.is.not.used"; highlightDisplayKey = myUnusedSymbolKey; highlightInfoType = HighlightInfoType.UNUSED_SYMBOL; } else if (aClass.getParent() instanceof PsiDeclarationStatement) { // local class pattern = "local.class.is.not.used"; highlightDisplayKey = myUnusedSymbolKey; highlightInfoType = HighlightInfoType.UNUSED_SYMBOL; } else if (aClass instanceof PsiTypeParameter) { pattern = "type.parameter.is.not.used"; highlightDisplayKey = myUnusedSymbolKey; highlightInfoType = HighlightInfoType.UNUSED_SYMBOL; } else { pattern = "class.is.not.used"; highlightDisplayKey = myDeadCodeKey; highlightInfoType = myDeadCodeInfoType; } return formatUnusedSymbolHighlightInfo(pattern, aClass, "classes", highlightDisplayKey, highlightInfoType); } private static final int USED = 1; private static final int UNUSED_LOCALLY = 2; private static final int UNUSED_GLOBALLY = 3; private final TObjectIntHashMap<PsiClass> unusedClassCache = new TObjectIntHashMap<PsiClass>(); private int isClassUnused(PsiClass aClass, ProgressIndicator progress) { if (aClass == null) return USED; int result = unusedClassCache.get(aClass); if (result == 0) { result = isReallyUnused(aClass, progress); unusedClassCache.put(aClass, result); } return result; } private int isReallyUnused(PsiClass aClass, ProgressIndicator progress) { if (isImplicitUsage(aClass, progress) || myRefCountHolder.isReferenced(aClass)) return USED; if (aClass.getContainingClass() != null && aClass.hasModifierProperty(PsiModifier.PRIVATE) || aClass.getParent() instanceof PsiDeclarationStatement || aClass instanceof PsiTypeParameter) return UNUSED_LOCALLY; if (weAreSureThereAreNoUsages(aClass, progress)) return UNUSED_GLOBALLY; return USED; } private static HighlightInfo formatUnusedSymbolHighlightInfo(@PropertyKey(resourceBundle = JavaErrorMessages.BUNDLE) String pattern, final PsiNameIdentifierOwner aClass, final String element, final HighlightDisplayKey highlightDisplayKey, final HighlightInfoType highlightInfoType) { String symbolName = aClass.getName(); String message = JavaErrorMessages.message(pattern, symbolName); PsiElement identifier = aClass.getNameIdentifier(); final HighlightInfo highlightInfo = createUnusedSymbolInfo(identifier, message, highlightInfoType); QuickFixAction.registerQuickFixAction(highlightInfo, new SafeDeleteFix(aClass), highlightDisplayKey); SpecialAnnotationsUtil.createAddToSpecialAnnotationFixes((PsiModifierListOwner)aClass, new Processor<String>() { @Override public boolean process(final String annoName) { QuickFixAction.registerQuickFixAction(highlightInfo, UnusedSymbolLocalInspection.createQuickFix(annoName, element, aClass.getProject())); return true; } }); return highlightInfo; } @Nullable private HighlightInfo processImport(PsiImportStatementBase importStatement, HighlightDisplayKey unusedImportKey) { // jsp include directive hack if (importStatement instanceof JspxImportStatement && ((JspxImportStatement)importStatement).isForeignFileImport()) return null; if (PsiUtilCore.hasErrorElementChild(importStatement)) return null; boolean isRedundant = myRefCountHolder.isRedundant(importStatement); if (!isRedundant && !(importStatement instanceof PsiImportStaticStatement)) { //check import from same package String packageName = ((PsiClassOwner)importStatement.getContainingFile()).getPackageName(); PsiJavaCodeReferenceElement reference = importStatement.getImportReference(); PsiElement resolved = reference == null ? null : reference.resolve(); if (resolved instanceof PsiPackage) { isRedundant = packageName.equals(((PsiPackage)resolved).getQualifiedName()); } else if (resolved instanceof PsiClass && !importStatement.isOnDemand()) { String qName = ((PsiClass)resolved).getQualifiedName(); if (qName != null) { String name = ((PsiClass)resolved).getName(); isRedundant = qName.equals(packageName + '.' + name); } } } if (isRedundant) { return registerRedundantImport(importStatement, unusedImportKey); } int entryIndex = myStyleManager.findEntryIndex(importStatement); if (entryIndex < myCurrentEntryIndex) { myHasMissortedImports = true; } myCurrentEntryIndex = entryIndex; return null; } private HighlightInfo registerRedundantImport(PsiImportStatementBase importStatement, HighlightDisplayKey unusedImportKey) { HighlightInfo info = HighlightInfo.createHighlightInfo(JavaHighlightInfoTypes.UNUSED_IMPORT, importStatement, InspectionsBundle.message("unused.import.statement")); QuickFixAction.registerQuickFixAction(info, new OptimizeImportsFix(), unusedImportKey); QuickFixAction.registerQuickFixAction(info, new EnableOptimizeImportsOnTheFlyFix(), unusedImportKey); myHasRedundantImports = true; return info; } private boolean timeToOptimizeImports() { if (!CodeInsightSettings.getInstance().OPTIMIZE_IMPORTS_ON_THE_FLY) return false; DaemonCodeAnalyzerImpl codeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(myProject); PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myDocument); // dont optimize out imports in JSP since it can be included in other JSP if (file == null || !codeAnalyzer.isHighlightingAvailable(file) || !(file instanceof PsiJavaFile) || file instanceof JspFile) return false; if (!codeAnalyzer.isErrorAnalyzingFinished(file)) return false; boolean errors = containsErrorsPreventingOptimize(file); return !errors && codeAnalyzer.canChangeFileSilently(myFile); } private boolean containsErrorsPreventingOptimize(PsiFile file) { // ignore unresolved imports errors PsiImportList importList = ((PsiJavaFile)file).getImportList(); final TextRange importsRange = importList == null ? TextRange.EMPTY_RANGE : importList.getTextRange(); boolean hasErrorsExceptUnresolvedImports = !DaemonCodeAnalyzerImpl.processHighlights(myDocument, myProject, HighlightSeverity.ERROR, 0, myDocument.getTextLength(), new Processor<HighlightInfo>() { @Override public boolean process(HighlightInfo error) { int infoStart = error.getActualStartOffset(); int infoEnd = error.getActualEndOffset(); return importsRange.containsRange(infoStart,infoEnd) && error.type.equals(HighlightInfoType.WRONG_REF); } }); return hasErrorsExceptUnresolvedImports; } private static boolean isIntentionalPrivateConstructor(PsiMethod method, PsiClass containingClass) { return method.isConstructor() && method.getParameterList().getParametersCount() == 0 && containingClass != null && containingClass.getConstructors().length == 1; } }
java/java-impl/src/com/intellij/codeInsight/daemon/impl/PostHighlightingPass.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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.intellij.codeInsight.daemon.impl; import com.intellij.codeHighlighting.Pass; import com.intellij.codeHighlighting.TextEditorHighlightingPass; import com.intellij.codeInsight.CodeInsightSettings; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInsight.daemon.ImplicitUsageProvider; import com.intellij.codeInsight.daemon.JavaErrorMessages; import com.intellij.codeInsight.daemon.impl.analysis.HighlightLevelUtil; import com.intellij.codeInsight.daemon.impl.analysis.HighlightMessageUtil; import com.intellij.codeInsight.daemon.impl.analysis.HighlightMethodUtil; import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil; import com.intellij.codeInsight.daemon.impl.quickfix.*; import com.intellij.codeInsight.intention.EmptyIntentionAction; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInsight.intention.IntentionManager; import com.intellij.codeInspection.InspectionProfile; import com.intellij.codeInspection.InspectionProfileEntry; import com.intellij.codeInspection.InspectionsBundle; import com.intellij.codeInspection.deadCode.UnusedDeclarationInspection; import com.intellij.codeInspection.ex.GlobalInspectionToolWrapper; import com.intellij.codeInspection.ex.InspectionManagerEx; import com.intellij.codeInspection.ex.LocalInspectionToolWrapper; import com.intellij.codeInspection.reference.UnusedDeclarationFixProvider; import com.intellij.codeInspection.unusedImport.UnusedImportLocalInspection; import com.intellij.codeInspection.unusedParameters.UnusedParametersInspection; import com.intellij.codeInspection.unusedSymbol.UnusedSymbolLocalInspection; import com.intellij.codeInspection.util.SpecialAnnotationsUtil; import com.intellij.diagnostic.LogMessageEx; import com.intellij.diagnostic.errordialog.Attachment; import com.intellij.find.FindManager; import com.intellij.find.findUsages.*; import com.intellij.find.impl.FindManagerImpl; import com.intellij.lang.Language; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.profile.codeInspection.InspectionProjectProfileManager; import com.intellij.psi.*; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.impl.PsiClassImplUtil; import com.intellij.psi.impl.source.PsiClassImpl; import com.intellij.psi.impl.source.jsp.jspJava.JspxImportStatement; import com.intellij.psi.jsp.JspFile; import com.intellij.psi.jsp.JspSpiUtil; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiSearchHelper; import com.intellij.psi.search.SearchScope; import com.intellij.psi.search.searches.OverridingMethodsSearch; import com.intellij.psi.search.searches.SuperMethodsSearch; import com.intellij.psi.util.PropertyUtil; import com.intellij.psi.util.PsiUtilCore; import com.intellij.refactoring.changeSignature.ChangeSignatureGestureDetector; import com.intellij.util.Processor; import gnu.trove.THashSet; import gnu.trove.TObjectIntHashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.PropertyKey; import java.util.*; public class PostHighlightingPass extends TextEditorHighlightingPass { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.PostHighlightingPass"); private RefCountHolder myRefCountHolder; private final PsiFile myFile; @Nullable private final Editor myEditor; private final int myStartOffset; private final int myEndOffset; private Collection<HighlightInfo> myHighlights; private boolean myHasRedundantImports; private final JavaCodeStyleManager myStyleManager; private int myCurrentEntryIndex; private boolean myHasMissortedImports; private final ImplicitUsageProvider[] myImplicitUsageProviders; private UnusedDeclarationInspection myDeadCodeInspection; private UnusedSymbolLocalInspection myUnusedSymbolInspection; private HighlightDisplayKey myUnusedSymbolKey; private boolean myDeadCodeEnabled; private boolean myInLibrary; private HighlightDisplayKey myDeadCodeKey; private HighlightInfoType myDeadCodeInfoType; private UnusedParametersInspection myUnusedParametersInspection; PostHighlightingPass(@NotNull Project project, @NotNull PsiFile file, @Nullable Editor editor, @NotNull Document document) { super(project, document, true); myFile = file; myEditor = editor; myStartOffset = 0; myEndOffset = file.getTextLength(); myStyleManager = JavaCodeStyleManager.getInstance(myProject); myCurrentEntryIndex = -1; myImplicitUsageProviders = Extensions.getExtensions(ImplicitUsageProvider.EP_NAME); } @Override public void doCollectInformation(final ProgressIndicator progress) { DaemonCodeAnalyzer daemonCodeAnalyzer = DaemonCodeAnalyzer.getInstance(myProject); final FileStatusMap fileStatusMap = ((DaemonCodeAnalyzerImpl)daemonCodeAnalyzer).getFileStatusMap(); final List<HighlightInfo> highlights = new ArrayList<HighlightInfo>(); final FileViewProvider viewProvider = myFile.getViewProvider(); final Set<Language> relevantLanguages = viewProvider.getLanguages(); final Set<PsiElement> elementSet = new THashSet<PsiElement>(); for (Language language : relevantLanguages) { PsiElement psiRoot = viewProvider.getPsi(language); if (!HighlightLevelUtil.shouldHighlight(psiRoot)) continue; List<PsiElement> elements = CollectHighlightsUtil.getElementsInRange(psiRoot, myStartOffset, myEndOffset); elementSet.addAll(elements); } ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex(); VirtualFile virtualFile = viewProvider.getVirtualFile(); myInLibrary = fileIndex.isInLibraryClasses(virtualFile) || fileIndex.isInLibrarySource(virtualFile); myRefCountHolder = RefCountHolder.getInstance(myFile); if (!myRefCountHolder.retrieveUnusedReferencesInfo(new Runnable() { @Override public void run() { boolean errorFound = collectHighlights(elementSet, highlights, progress); myHighlights = highlights; if (errorFound) { fileStatusMap.setErrorFoundFlag(myDocument, true); } } })) { // we must be sure GHP will restart fileStatusMap.markFileScopeDirty(getDocument(), Pass.UPDATE_ALL); GeneralHighlightingPass.cancelAndRestartDaemonLater(progress, myProject, this); } } @Override public List<HighlightInfo> getInfos() { return myHighlights == null ? null : new ArrayList<HighlightInfo>(myHighlights); } @Override public void doApplyInformationToEditor() { if (myHighlights == null) return; UpdateHighlightersUtil.setHighlightersToEditor(myProject, myDocument, myStartOffset, myEndOffset, myHighlights, getColorsScheme(), Pass.POST_UPDATE_ALL); PostHighlightingPassFactory.markFileUpToDate(myFile); Editor editor = myEditor; if (editor != null && timeToOptimizeImports()) { optimizeImportsOnTheFly(editor); } } private void optimizeImportsOnTheFly(@NotNull final Editor editor) { if (myHasRedundantImports || myHasMissortedImports) { final OptimizeImportsFix optimizeImportsFix = new OptimizeImportsFix(); if (optimizeImportsFix.isAvailable(myProject, editor, myFile) && myFile.isWritable()) { invokeOnTheFlyImportOptimizer(new Runnable() { @Override public void run() { optimizeImportsFix.invoke(myProject, editor, myFile); } }, myFile, editor); } } } public static void invokeOnTheFlyImportOptimizer(@NotNull final Runnable runnable, @NotNull final PsiFile file, @NotNull final Editor editor) { final long stamp = editor.getDocument().getModificationStamp(); ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { if (file.getProject().isDisposed() || editor.isDisposed() || editor.getDocument().getModificationStamp() != stamp) return; PsiDocumentManager.getInstance(file.getProject()).commitAllDocuments(); String beforeText = file.getText(); final long oldStamp = editor.getDocument().getModificationStamp(); CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() { @Override public void run() { ApplicationManager.getApplication().runWriteAction(runnable); } }); if (oldStamp != editor.getDocument().getModificationStamp()) { String afterText = file.getText(); if (Comparing.strEqual(beforeText, afterText)) { LOG.error(LogMessageEx.createEvent("Import optimizer hasn't optimized any imports", file.getViewProvider().getVirtualFile().getPath(), new Attachment(file.getViewProvider().getVirtualFile()))); } } } }); } // returns true if error highlight was created private boolean collectHighlights(@NotNull Collection<PsiElement> elements, @NotNull final List<HighlightInfo> result, @NotNull ProgressIndicator progress) throws ProcessCanceledException { ApplicationManager.getApplication().assertReadAccessAllowed(); InspectionProfile profile = InspectionProjectProfileManager.getInstance(myProject).getInspectionProfile(); myUnusedSymbolKey = HighlightDisplayKey.find(UnusedSymbolLocalInspection.SHORT_NAME); boolean unusedSymbolEnabled = profile.isToolEnabled(myUnusedSymbolKey, myFile); HighlightDisplayKey unusedImportKey = HighlightDisplayKey.find(UnusedImportLocalInspection.SHORT_NAME); boolean unusedImportEnabled = profile.isToolEnabled(unusedImportKey, myFile); LocalInspectionToolWrapper unusedSymbolTool = (LocalInspectionToolWrapper)profile.getInspectionTool(UnusedSymbolLocalInspection.SHORT_NAME, myFile); myUnusedSymbolInspection = unusedSymbolTool == null ? null : (UnusedSymbolLocalInspection)unusedSymbolTool.getTool(); LOG.assertTrue(ApplicationManager.getApplication().isUnitTestMode() || myUnusedSymbolInspection != null); myDeadCodeKey = HighlightDisplayKey.find(UnusedDeclarationInspection.SHORT_NAME); myDeadCodeInspection = (UnusedDeclarationInspection)profile.getInspectionTool(UnusedDeclarationInspection.SHORT_NAME, myFile); myDeadCodeEnabled = profile.isToolEnabled(myDeadCodeKey, myFile); final InspectionProfileEntry inspectionTool = profile.getInspectionTool(UnusedParametersInspection.SHORT_NAME, myFile); myUnusedParametersInspection = inspectionTool != null ? (UnusedParametersInspection)((GlobalInspectionToolWrapper)inspectionTool).getTool() : null; LOG.assertTrue(ApplicationManager.getApplication().isUnitTestMode() || myUnusedParametersInspection != null); if (unusedImportEnabled && JspPsiUtil.isInJspFile(myFile)) { final JspFile jspFile = JspPsiUtil.getJspFile(myFile); if (jspFile != null) { unusedImportEnabled = !JspSpiUtil.isIncludedOrIncludesSomething(jspFile); } } myDeadCodeInfoType = myDeadCodeKey == null ? null : new HighlightInfoType.HighlightInfoTypeImpl(profile.getErrorLevel(myDeadCodeKey, myFile).getSeverity(), HighlightInfoType.UNUSED_SYMBOL.getAttributesKey()); boolean errorFound = false; if (unusedSymbolEnabled) { for (PsiElement element : elements) { progress.checkCanceled(); if (element instanceof PsiIdentifier) { PsiIdentifier identifier = (PsiIdentifier)element; HighlightInfo info = processIdentifier(identifier, progress); if (info != null) { errorFound |= info.getSeverity() == HighlightSeverity.ERROR; result.add(info); } } } } if (unusedImportEnabled && myFile instanceof PsiJavaFile && HighlightLevelUtil.shouldHighlight(myFile)) { PsiImportList importList = ((PsiJavaFile)myFile).getImportList(); if (importList != null) { final PsiImportStatementBase[] imports = importList.getAllImportStatements(); for (PsiImportStatementBase statement : imports) { progress.checkCanceled(); final HighlightInfo info = processImport(statement, unusedImportKey); if (info != null) { errorFound |= info.getSeverity() == HighlightSeverity.ERROR; result.add(info); } } } } return errorFound; } @Nullable private HighlightInfo processIdentifier(PsiIdentifier identifier, ProgressIndicator progress) { if (InspectionManagerEx.inspectionResultSuppressed(identifier, myUnusedSymbolInspection)) return null; PsiElement parent = identifier.getParent(); if (PsiUtilCore.hasErrorElementChild(parent)) return null; if (parent instanceof PsiLocalVariable && myUnusedSymbolInspection.LOCAL_VARIABLE) { return processLocalVariable((PsiLocalVariable)parent, progress); } if (parent instanceof PsiField && myUnusedSymbolInspection.FIELD) { return processField((PsiField)parent, identifier, progress); } if (parent instanceof PsiParameter && myUnusedSymbolInspection.PARAMETER) { if (InspectionManagerEx.isSuppressed(identifier, UnusedParametersInspection.SHORT_NAME)) return null; return processParameter((PsiParameter)parent, progress); } if (parent instanceof PsiMethod && myUnusedSymbolInspection.METHOD) { return processMethod((PsiMethod)parent, progress); } if (parent instanceof PsiClass && myUnusedSymbolInspection.CLASS) { return processClass((PsiClass)parent, progress); } return null; } @Nullable private HighlightInfo processLocalVariable(PsiLocalVariable variable, ProgressIndicator progress) { PsiIdentifier identifier = variable.getNameIdentifier(); if (identifier == null) return null; if (isImplicitUsage(variable, progress)) return null; if (!myRefCountHolder.isReferenced(variable)) { String message = JavaErrorMessages.message("local.variable.is.never.used", identifier.getText()); HighlightInfo highlightInfo = createUnusedSymbolInfo(identifier, message, HighlightInfoType.UNUSED_SYMBOL); QuickFixAction.registerQuickFixAction(highlightInfo, new RemoveUnusedVariableFix(variable), myUnusedSymbolKey); return highlightInfo; } boolean referenced = myRefCountHolder.isReferencedForRead(variable); if (!referenced && !isImplicitRead(variable, progress)) { String message = JavaErrorMessages.message("local.variable.is.not.used.for.reading", identifier.getText()); HighlightInfo highlightInfo = createUnusedSymbolInfo(identifier, message, HighlightInfoType.UNUSED_SYMBOL); QuickFixAction.registerQuickFixAction(highlightInfo, new RemoveUnusedVariableFix(variable), myUnusedSymbolKey); return highlightInfo; } if (!variable.hasInitializer()) { referenced = myRefCountHolder.isReferencedForWrite(variable); if (!referenced && !isImplicitWrite(variable, progress)) { String message = JavaErrorMessages.message("local.variable.is.not.assigned", identifier.getText()); final HighlightInfo unusedSymbolInfo = createUnusedSymbolInfo(identifier, message, HighlightInfoType.UNUSED_SYMBOL); QuickFixAction.registerQuickFixAction(unusedSymbolInfo, new EmptyIntentionAction(UnusedSymbolLocalInspection.DISPLAY_NAME), myUnusedSymbolKey); return unusedSymbolInfo; } } return null; } private boolean isImplicitUsage(final PsiModifierListOwner element, ProgressIndicator progress) { if (UnusedSymbolLocalInspection.isInjected(element)) return true; for (ImplicitUsageProvider provider : myImplicitUsageProviders) { progress.checkCanceled(); if (provider.isImplicitUsage(element)) { return true; } } return false; } private boolean isImplicitRead(final PsiVariable element, ProgressIndicator progress) { for(ImplicitUsageProvider provider: myImplicitUsageProviders) { progress.checkCanceled(); if (provider.isImplicitRead(element)) { return true; } } return UnusedSymbolLocalInspection.isInjected(element); } private boolean isImplicitWrite(final PsiVariable element, ProgressIndicator progress) { for(ImplicitUsageProvider provider: myImplicitUsageProviders) { progress.checkCanceled(); if (provider.isImplicitWrite(element)) { return true; } } return UnusedSymbolLocalInspection.isInjected(element); } private static HighlightInfo createUnusedSymbolInfo(PsiElement element, String message, final HighlightInfoType highlightInfoType) { HighlightInfo info = HighlightInfo.createHighlightInfo(highlightInfoType, element, message); UnusedDeclarationFixProvider[] fixProviders = Extensions.getExtensions(UnusedDeclarationFixProvider.EP_NAME); for (UnusedDeclarationFixProvider provider : fixProviders) { IntentionAction[] fixes = provider.getQuickFixes(element); for (IntentionAction fix : fixes) { QuickFixAction.registerQuickFixAction(info, fix); } } return info; } @Nullable private HighlightInfo processField(final PsiField field, final PsiIdentifier identifier, ProgressIndicator progress) { if (field.hasModifierProperty(PsiModifier.PRIVATE)) { if (!myRefCountHolder.isReferenced(field) && !isImplicitUsage(field, progress)) { if (HighlightUtil.isSerializationImplicitlyUsedField(field)) { return null; } String message = JavaErrorMessages.message("private.field.is.not.used", identifier.getText()); HighlightInfo highlightInfo = suggestionsToMakeFieldUsed(field, identifier, message); if (!field.hasInitializer()) { QuickFixAction.registerQuickFixAction(highlightInfo, HighlightMethodUtil.getFixRange(field), new CreateConstructorParameterFromFieldFix(field), null); } return highlightInfo; } final boolean readReferenced = myRefCountHolder.isReferencedForRead(field); if (!readReferenced && !isImplicitRead(field, progress)) { String message = JavaErrorMessages.message("private.field.is.not.used.for.reading", identifier.getText()); return suggestionsToMakeFieldUsed(field, identifier, message); } if (field.hasInitializer()) { return null; } final boolean writeReferenced = myRefCountHolder.isReferencedForWrite(field); if (!writeReferenced && !isImplicitWrite(field, progress)) { String message = JavaErrorMessages.message("private.field.is.not.assigned", identifier.getText()); final HighlightInfo info = createUnusedSymbolInfo(identifier, message, HighlightInfoType.UNUSED_SYMBOL); QuickFixAction.registerQuickFixAction(info, new CreateGetterOrSetterFix(false, true, field), myUnusedSymbolKey); QuickFixAction.registerQuickFixAction(info, HighlightMethodUtil.getFixRange(field), new CreateConstructorParameterFromFieldFix(field), null); SpecialAnnotationsUtil.createAddToSpecialAnnotationFixes(field, new Processor<String>() { @Override public boolean process(final String annoName) { QuickFixAction.registerQuickFixAction(info, UnusedSymbolLocalInspection.createQuickFix(annoName, "fields", field.getProject())); return true; } }); return info; } } else if (isImplicitUsage(field, progress)) { return null; } else if (!myRefCountHolder.isReferenced(field) && weAreSureThereAreNoUsages(field, progress)) { return formatUnusedSymbolHighlightInfo("field.is.not.used", field, "fields", myDeadCodeKey, myDeadCodeInfoType); } return null; } private HighlightInfo suggestionsToMakeFieldUsed(final PsiField field, final PsiIdentifier identifier, final String message) { HighlightInfo highlightInfo = createUnusedSymbolInfo(identifier, message, HighlightInfoType.UNUSED_SYMBOL); QuickFixAction.registerQuickFixAction(highlightInfo, new RemoveUnusedVariableFix(field), myUnusedSymbolKey); QuickFixAction.registerQuickFixAction(highlightInfo, new CreateGetterOrSetterFix(true, false, field), myUnusedSymbolKey); QuickFixAction.registerQuickFixAction(highlightInfo, new CreateGetterOrSetterFix(false, true, field), myUnusedSymbolKey); QuickFixAction.registerQuickFixAction(highlightInfo, new CreateGetterOrSetterFix(true, true, field), myUnusedSymbolKey); return highlightInfo; } private static boolean isOverriddenOrOverrides(PsiMethod method) { boolean overrides = SuperMethodsSearch.search(method, null, true, false).findFirst() != null; return overrides || OverridingMethodsSearch.search(method).findFirst() != null; } @Nullable private HighlightInfo processParameter(PsiParameter parameter, ProgressIndicator progress) { PsiElement declarationScope = parameter.getDeclarationScope(); if (declarationScope instanceof PsiMethod) { PsiMethod method = (PsiMethod)declarationScope; if (PsiUtilCore.hasErrorElementChild(method)) return null; if ((method.isConstructor() || method.hasModifierProperty(PsiModifier.PRIVATE) || method.hasModifierProperty(PsiModifier.STATIC) || !method.hasModifierProperty(PsiModifier.ABSTRACT) && myUnusedSymbolInspection.REPORT_PARAMETER_FOR_PUBLIC_METHODS && !isOverriddenOrOverrides(method)) && !method.hasModifierProperty(PsiModifier.NATIVE) && !HighlightMethodUtil.isSerializationRelatedMethod(method, method.getContainingClass()) && !PsiClassImplUtil.isMainMethod(method)) { if (UnusedSymbolLocalInspection.isInjected(method)) return null; HighlightInfo highlightInfo = checkUnusedParameter(parameter, progress); if (highlightInfo != null) { final ArrayList<IntentionAction> options = new ArrayList<IntentionAction>(); options.addAll(IntentionManager.getInstance().getStandardIntentionOptions(myUnusedSymbolKey, myFile)); if (myUnusedParametersInspection != null) { Collections.addAll(options, myUnusedParametersInspection.getSuppressActions(parameter)); } //need suppress from Unused Parameters but settings from Unused Symbol QuickFixAction.registerQuickFixAction(highlightInfo, new RemoveUnusedParameterFix(parameter), options, HighlightDisplayKey.getDisplayNameByKey(myUnusedSymbolKey)); return highlightInfo; } } } else if (declarationScope instanceof PsiForeachStatement) { HighlightInfo highlightInfo = checkUnusedParameter(parameter, progress); if (highlightInfo != null) { QuickFixAction.registerQuickFixAction(highlightInfo, new EmptyIntentionAction(UnusedSymbolLocalInspection.DISPLAY_NAME), myUnusedSymbolKey); return highlightInfo; } } return null; } @Nullable private HighlightInfo checkUnusedParameter(final PsiParameter parameter, ProgressIndicator progress) { if (!myRefCountHolder.isReferenced(parameter) && !isImplicitUsage(parameter, progress)) { PsiIdentifier identifier = parameter.getNameIdentifier(); assert identifier != null; String message = JavaErrorMessages.message("parameter.is.not.used", identifier.getText()); return createUnusedSymbolInfo(identifier, message, HighlightInfoType.UNUSED_SYMBOL); } return null; } @Nullable private HighlightInfo processMethod(final PsiMethod method, ProgressIndicator progress) { boolean isPrivate = method.hasModifierProperty(PsiModifier.PRIVATE); PsiClass containingClass = method.getContainingClass(); if (isMethodReferenced(method, progress, isPrivate, containingClass)) return null; HighlightInfoType highlightInfoType; HighlightDisplayKey highlightDisplayKey; String key; if (isPrivate) { highlightInfoType = HighlightInfoType.UNUSED_SYMBOL; highlightDisplayKey = myUnusedSymbolKey; key = method.isConstructor() ? "private.constructor.is.not.used" : "private.method.is.not.used"; } else { highlightInfoType = myDeadCodeInfoType; highlightDisplayKey = myDeadCodeKey; key = method.isConstructor() ? "constructor.is.not.used" : "method.is.not.used"; } String symbolName = HighlightMessageUtil.getSymbolName(method, PsiSubstitutor.EMPTY); String message = JavaErrorMessages.message(key, symbolName); PsiIdentifier identifier = method.getNameIdentifier(); final HighlightInfo highlightInfo = createUnusedSymbolInfo(identifier, message, highlightInfoType); QuickFixAction.registerQuickFixAction(highlightInfo, new SafeDeleteFix(method), highlightDisplayKey); SpecialAnnotationsUtil.createAddToSpecialAnnotationFixes(method, new Processor<String>() { @Override public boolean process(final String annoName) { QuickFixAction.registerQuickFixAction(highlightInfo, UnusedSymbolLocalInspection.createQuickFix(annoName, "methods", method.getProject())); return true; } }); if (method.getReturnType() != null || containingClass != null && Comparing.strEqual(containingClass.getName(), method.getName())) { //ignore methods with deleted return types as they are always marked as unused without any reason ChangeSignatureGestureDetector.getInstance(myProject).dismissForElement(method); } return highlightInfo; } private boolean isMethodReferenced(PsiMethod method, ProgressIndicator progress, boolean aPrivate, PsiClass containingClass) { if (myRefCountHolder.isReferenced(method)) return true; if (HighlightMethodUtil.isSerializationRelatedMethod(method, containingClass)) return true; if (aPrivate) { if (isIntentionalPrivateConstructor(method, containingClass)) { return true; } if (isImplicitUsage(method, progress)) { return true; } } else { //class maybe used in some weird way, e.g. from XML, therefore the only constructor is used too if (containingClass != null && method.isConstructor() && containingClass.getConstructors().length == 1 && isClassUnused(containingClass, progress) == USED) { return true; } if (isImplicitUsage(method, progress)) return true; if (method.findSuperMethods().length != 0) { return true; } if (!weAreSureThereAreNoUsages(method, progress)) { return true; } } return false; } private boolean weAreSureThereAreNoUsages(PsiMember member, ProgressIndicator progress) { if (myInLibrary) return false; if (!myDeadCodeEnabled) return false; if (myDeadCodeInspection.isEntryPoint(member)) return false; String name = member.getName(); if (name == null) return false; SearchScope useScope = member.getUseScope(); if (!(useScope instanceof GlobalSearchScope)) return false; GlobalSearchScope scope = (GlobalSearchScope)useScope; // some classes may have references from within XML outside dependent modules, e.g. our actions if (member instanceof PsiClass) scope = GlobalSearchScope.projectScope(myProject).uniteWith(scope); PsiSearchHelper.SearchCostResult cheapEnough = PsiSearchHelper.SERVICE.getInstance(myFile.getProject()) .isCheapEnoughToSearch(name, scope, myFile, progress); if (cheapEnough == PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES) return false; //search usages if it cheap //if count is 0 there is no usages since we've called myRefCountHolder.isReferenced() before if (cheapEnough == PsiSearchHelper.SearchCostResult.ZERO_OCCURRENCES) { if (member instanceof PsiEnumConstant) { return !isEnumValuesMethodUsed(member, progress); } if (!canBeReferencedViaWeirdNames(member)) return true; } FindUsagesManager findUsagesManager = ((FindManagerImpl)FindManager.getInstance(myProject)).getFindUsagesManager(); FindUsagesOptions findUsagesOptions; if (member instanceof PsiClass) { findUsagesOptions = new JavaClassFindUsagesOptions(myProject); } else if (member instanceof PsiMethod) { findUsagesOptions = new JavaMethodFindUsagesOptions(myProject); } else if (member instanceof PsiField) { findUsagesOptions = new JavaVariableFindUsagesOptions(myProject); } else { LOG.error("unknown member: " + member); return false; } findUsagesOptions.searchScope = scope; boolean used = findUsagesManager.isUsed(member, findUsagesOptions); if (!used && member instanceof PsiEnumConstant) { return !isEnumValuesMethodUsed(member, progress); } return !used; } private boolean isEnumValuesMethodUsed(PsiMember member, ProgressIndicator progress) { final PsiClassImpl containingClass = (PsiClassImpl)member.getContainingClass(); if (containingClass == null) return true; final PsiMethod valuesMethod = containingClass.getValuesMethod(); if (valuesMethod == null) return true; boolean isPrivate = valuesMethod.hasModifierProperty(PsiModifier.PRIVATE); return isMethodReferenced(valuesMethod, progress, isPrivate, containingClass); } private static boolean canBeReferencedViaWeirdNames(PsiMember member) { if (member instanceof PsiClass) return false; PsiFile containingFile = member.getContainingFile(); if (!(containingFile instanceof PsiJavaFile)) return true; // Groovy field can be referenced from Java by getter if (member instanceof PsiField) return false; //Java field cannot be referenced by anything but its name if (member instanceof PsiMethod) { return PropertyUtil.isSimplePropertyAccessor((PsiMethod)member); //Java accessors can be referenced by field name from Groovy } return false; } @Nullable private HighlightInfo processClass(PsiClass aClass, ProgressIndicator progress) { int usage = isClassUnused(aClass, progress); if (usage == USED) return null; String pattern; HighlightDisplayKey highlightDisplayKey; HighlightInfoType highlightInfoType; if (aClass.getContainingClass() != null && aClass.hasModifierProperty(PsiModifier.PRIVATE)) { pattern = aClass.isInterface() ? "private.inner.interface.is.not.used" : "private.inner.class.is.not.used"; highlightDisplayKey = myUnusedSymbolKey; highlightInfoType = HighlightInfoType.UNUSED_SYMBOL; } else if (aClass.getParent() instanceof PsiDeclarationStatement) { // local class pattern = "local.class.is.not.used"; highlightDisplayKey = myUnusedSymbolKey; highlightInfoType = HighlightInfoType.UNUSED_SYMBOL; } else if (aClass instanceof PsiTypeParameter) { pattern = "type.parameter.is.not.used"; highlightDisplayKey = myUnusedSymbolKey; highlightInfoType = HighlightInfoType.UNUSED_SYMBOL; } else { pattern = "class.is.not.used"; highlightDisplayKey = myDeadCodeKey; highlightInfoType = myDeadCodeInfoType; } return formatUnusedSymbolHighlightInfo(pattern, aClass, "classes", highlightDisplayKey, highlightInfoType); } private static final int USED = 1; private static final int UNUSED_LOCALLY = 2; private static final int UNUSED_GLOBALLY = 3; private final TObjectIntHashMap<PsiClass> unusedClassCache = new TObjectIntHashMap<PsiClass>(); private int isClassUnused(PsiClass aClass, ProgressIndicator progress) { if (aClass == null) return USED; int result = unusedClassCache.get(aClass); if (result == 0) { result = isReallyUnused(aClass, progress); unusedClassCache.put(aClass, result); } return result; } private int isReallyUnused(PsiClass aClass, ProgressIndicator progress) { if (isImplicitUsage(aClass, progress) || myRefCountHolder.isReferenced(aClass)) return USED; if (aClass.getContainingClass() != null && aClass.hasModifierProperty(PsiModifier.PRIVATE) || aClass.getParent() instanceof PsiDeclarationStatement || aClass instanceof PsiTypeParameter) return UNUSED_LOCALLY; if (weAreSureThereAreNoUsages(aClass, progress)) return UNUSED_GLOBALLY; return USED; } private static HighlightInfo formatUnusedSymbolHighlightInfo(@PropertyKey(resourceBundle = JavaErrorMessages.BUNDLE) String pattern, final PsiNameIdentifierOwner aClass, final String element, final HighlightDisplayKey highlightDisplayKey, final HighlightInfoType highlightInfoType) { String symbolName = aClass.getName(); String message = JavaErrorMessages.message(pattern, symbolName); PsiElement identifier = aClass.getNameIdentifier(); final HighlightInfo highlightInfo = createUnusedSymbolInfo(identifier, message, highlightInfoType); QuickFixAction.registerQuickFixAction(highlightInfo, new SafeDeleteFix(aClass), highlightDisplayKey); SpecialAnnotationsUtil.createAddToSpecialAnnotationFixes((PsiModifierListOwner)aClass, new Processor<String>() { @Override public boolean process(final String annoName) { QuickFixAction.registerQuickFixAction(highlightInfo, UnusedSymbolLocalInspection.createQuickFix(annoName, element, aClass.getProject())); return true; } }); return highlightInfo; } @Nullable private HighlightInfo processImport(PsiImportStatementBase importStatement, HighlightDisplayKey unusedImportKey) { // jsp include directive hack if (importStatement instanceof JspxImportStatement && ((JspxImportStatement)importStatement).isForeignFileImport()) return null; if (PsiUtilCore.hasErrorElementChild(importStatement)) return null; boolean isRedundant = myRefCountHolder.isRedundant(importStatement); if (!isRedundant && !(importStatement instanceof PsiImportStaticStatement)) { //check import from same package String packageName = ((PsiClassOwner)importStatement.getContainingFile()).getPackageName(); PsiJavaCodeReferenceElement reference = importStatement.getImportReference(); PsiElement resolved = reference == null ? null : reference.resolve(); if (resolved instanceof PsiPackage) { isRedundant = packageName.equals(((PsiPackage)resolved).getQualifiedName()); } else if (resolved instanceof PsiClass && !importStatement.isOnDemand()) { String qName = ((PsiClass)resolved).getQualifiedName(); if (qName != null) { String name = ((PsiClass)resolved).getName(); isRedundant = qName.equals(packageName + '.' + name); } } } if (isRedundant) { return registerRedundantImport(importStatement, unusedImportKey); } int entryIndex = myStyleManager.findEntryIndex(importStatement); if (entryIndex < myCurrentEntryIndex) { myHasMissortedImports = true; } myCurrentEntryIndex = entryIndex; return null; } private HighlightInfo registerRedundantImport(PsiImportStatementBase importStatement, HighlightDisplayKey unusedImportKey) { HighlightInfo info = HighlightInfo.createHighlightInfo(JavaHighlightInfoTypes.UNUSED_IMPORT, importStatement, InspectionsBundle.message("unused.import.statement")); QuickFixAction.registerQuickFixAction(info, new OptimizeImportsFix(), unusedImportKey); QuickFixAction.registerQuickFixAction(info, new EnableOptimizeImportsOnTheFlyFix(), unusedImportKey); myHasRedundantImports = true; return info; } private boolean timeToOptimizeImports() { if (!CodeInsightSettings.getInstance().OPTIMIZE_IMPORTS_ON_THE_FLY) return false; DaemonCodeAnalyzerImpl codeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(myProject); PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myDocument); // dont optimize out imports in JSP since it can be included in other JSP if (file == null || !codeAnalyzer.isHighlightingAvailable(file) || !(file instanceof PsiJavaFile) || file instanceof JspFile) return false; if (!codeAnalyzer.isErrorAnalyzingFinished(file)) return false; boolean errors = containsErrorsPreventingOptimize(file); return !errors && codeAnalyzer.canChangeFileSilently(myFile); } private boolean containsErrorsPreventingOptimize(PsiFile file) { // ignore unresolved imports errors PsiImportList importList = ((PsiJavaFile)file).getImportList(); final TextRange importsRange = importList == null ? TextRange.EMPTY_RANGE : importList.getTextRange(); boolean hasErrorsExceptUnresolvedImports = !DaemonCodeAnalyzerImpl.processHighlights(myDocument, myProject, HighlightSeverity.ERROR, 0, myDocument.getTextLength(), new Processor<HighlightInfo>() { @Override public boolean process(HighlightInfo error) { int infoStart = error.getActualStartOffset(); int infoEnd = error.getActualEndOffset(); return importsRange.containsRange(infoStart,infoEnd) && error.type.equals(HighlightInfoType.WRONG_REF); } }); return hasErrorsExceptUnresolvedImports; } private static boolean isIntentionalPrivateConstructor(PsiMethod method, PsiClass containingClass) { return method.isConstructor() && method.getParameterList().getParametersCount() == 0 && containingClass != null && containingClass.getConstructors().length == 1; } }
EA-33195 - assert: DocumentUndoProvider$MyEditorDocumentListener.documentChanged: skip optimize imports during undo/redo
java/java-impl/src/com/intellij/codeInsight/daemon/impl/PostHighlightingPass.java
EA-33195 - assert: DocumentUndoProvider$MyEditorDocumentListener.documentChanged: skip optimize imports during undo/redo
<ide><path>ava/java-impl/src/com/intellij/codeInsight/daemon/impl/PostHighlightingPass.java <ide> import com.intellij.lang.annotation.HighlightSeverity; <ide> import com.intellij.openapi.application.ApplicationManager; <ide> import com.intellij.openapi.command.CommandProcessor; <add>import com.intellij.openapi.command.undo.UndoManager; <ide> import com.intellij.openapi.diagnostic.Logger; <ide> import com.intellij.openapi.editor.Document; <ide> import com.intellij.openapi.editor.Editor; <ide> @Override <ide> public void run() { <ide> if (file.getProject().isDisposed() || editor.isDisposed() || editor.getDocument().getModificationStamp() != stamp) return; <add> //no need to optimize imports on the fly during undo/redo <add> final UndoManager undoManager = UndoManager.getInstance(editor.getProject()); <add> if (undoManager.isUndoInProgress() || undoManager.isRedoInProgress()) return; <ide> PsiDocumentManager.getInstance(file.getProject()).commitAllDocuments(); <ide> String beforeText = file.getText(); <ide> final long oldStamp = editor.getDocument().getModificationStamp();
Java
apache-2.0
594cb89cbe30efa41b49b3ec98d5f0ad39d86043
0
wschaeferB/autopsy,narfindustries/autopsy,dgrove727/autopsy,wschaeferB/autopsy,esaunders/autopsy,millmanorama/autopsy,APriestman/autopsy,wschaeferB/autopsy,APriestman/autopsy,rcordovano/autopsy,rcordovano/autopsy,millmanorama/autopsy,esaunders/autopsy,rcordovano/autopsy,millmanorama/autopsy,rcordovano/autopsy,APriestman/autopsy,esaunders/autopsy,wschaeferB/autopsy,wschaeferB/autopsy,narfindustries/autopsy,narfindustries/autopsy,rcordovano/autopsy,APriestman/autopsy,esaunders/autopsy,rcordovano/autopsy,APriestman/autopsy,esaunders/autopsy,APriestman/autopsy,millmanorama/autopsy,APriestman/autopsy,dgrove727/autopsy,dgrove727/autopsy
/* * Autopsy Forensic Browser * * Copyright 2012-2017 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * 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.sleuthkit.autopsy.ingest; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.datamodel.AbstractFile; import org.sleuthkit.datamodel.Content; import org.sleuthkit.datamodel.FileSystem; import org.sleuthkit.datamodel.TskCoreException; import org.sleuthkit.datamodel.TskData; /** * Creates ingest tasks for ingest jobs, queuing the tasks in priority order for * execution by the ingest manager's ingest threads. */ final class IngestTasksScheduler { private static final Logger logger = Logger.getLogger(IngestTasksScheduler.class.getName()); private static final int FAT_NTFS_FLAGS = TskData.TSK_FS_TYPE_ENUM.TSK_FS_TYPE_FAT12.getValue() | TskData.TSK_FS_TYPE_ENUM.TSK_FS_TYPE_FAT16.getValue() | TskData.TSK_FS_TYPE_ENUM.TSK_FS_TYPE_FAT32.getValue() | TskData.TSK_FS_TYPE_ENUM.TSK_FS_TYPE_NTFS.getValue(); private static IngestTasksScheduler instance; /** * Scheduling of data source ingest tasks is accomplished by putting them in * a FIFO queue to be consumed by the ingest threads, so the queue is * wrapped in a "dispenser" that implements the IngestTaskQueue interface * and is exposed via a getter method. */ private final LinkedBlockingQueue<DataSourceIngestTask> pendingDataSourceTasks; private final DataSourceIngestTaskQueue dataSourceTasksDispenser; /** * Scheduling of file ingest tasks is accomplished by "shuffling" them * through a sequence of internal queues that allows for the interleaving of * tasks from different ingest jobs based on priority. These scheduling * queues are: * * 1. Root directory tasks (priority queue) * * 2. Directory tasks (FIFO queue) * * 3. Pending file tasks (LIFO queue). * * The pending file tasks queue is LIFO to handle large numbers of files * extracted from archive files. At least one image has been processed that * had a folder full of archive files. The queue grew to have thousands of * entries, as each successive archive file was expanded, so now extracted * files get added to the front of the queue so that in such a scenario they * would be processed before the expansion of the next archive file. * * Tasks in the pending file tasks queue are ready to be consumed by the * ingest threads, so the queue is wrapped in a "dispenser" that implements * the IngestTaskQueue interface and is exposed via a getter method. */ private final TreeSet<FileIngestTask> rootDirectoryTasks; private final List<FileIngestTask> directoryTasks; private final BlockingDeque<FileIngestTask> pendingFileTasks; private final FileIngestTaskQueue fileTasksDispenser; /** * The ingest tasks scheduler allows ingest jobs to query it to see if there * are any tasks in progress for the job. To make this possible, the ingest * tasks scheduler needs to keep track not only of the tasks in its queues, * but also of the tasks that have been handed out for processing by the * ingest threads. Therefore all ingest tasks are added to this list when * they are created and are not removed when an ingest thread takes an * ingest task. Instead, the ingest thread calls back into the scheduler * when the task is completed, at which time the task will be removed from * this list. */ private final Set<IngestTask> tasksInProgress; /** * Gets the ingest tasks scheduler singleton. */ synchronized static IngestTasksScheduler getInstance() { if (IngestTasksScheduler.instance == null) { IngestTasksScheduler.instance = new IngestTasksScheduler(); } return IngestTasksScheduler.instance; } /** * Constructs an ingest tasks scheduler. */ private IngestTasksScheduler() { this.pendingDataSourceTasks = new LinkedBlockingQueue<>(); this.dataSourceTasksDispenser = new DataSourceIngestTaskQueue(); this.rootDirectoryTasks = new TreeSet<>(new RootDirectoryTaskComparator()); this.directoryTasks = new ArrayList<>(); this.pendingFileTasks = new LinkedBlockingDeque<>(); this.fileTasksDispenser = new FileIngestTaskQueue(); this.tasksInProgress = new HashSet<>(); } /** * Gets this ingest task scheduler's implementation of the IngestTaskQueue * interface for data source ingest tasks. * * @return The data source ingest tasks queue. */ IngestTaskQueue getDataSourceIngestTaskQueue() { return this.dataSourceTasksDispenser; } /** * Gets this ingest task scheduler's implementation of the IngestTaskQueue * interface for file ingest tasks. * * @return The file ingest tasks queue. */ IngestTaskQueue getFileIngestTaskQueue() { return this.fileTasksDispenser; } /** * Schedules a data source ingest task and file ingest tasks for an ingest * job. * * @param job The job for which the tasks are to be scheduled. * * @throws InterruptedException if the calling thread is blocked due to a * full tasks queue and is interrupted. */ synchronized void scheduleIngestTasks(DataSourceIngestJob job) { if (!job.isCancelled()) { // Scheduling of both a data source ingest task and file ingest tasks // for a job must be an atomic operation. Otherwise, the data source // task might be completed before the file tasks are scheduled, // resulting in a potential false positive when another thread checks // whether or not all the tasks for the job are completed. this.scheduleDataSourceIngestTask(job); this.scheduleFileIngestTasks(job); } } /** * Schedules a data source ingest task for an ingest job. * * @param job The job for which the tasks are to be scheduled. */ synchronized void scheduleDataSourceIngestTask(DataSourceIngestJob job) { if (!job.isCancelled()) { DataSourceIngestTask task = new DataSourceIngestTask(job); this.tasksInProgress.add(task); try { this.pendingDataSourceTasks.put(task); } catch (InterruptedException ex) { /** * The current thread was interrupted while blocked on a full * queue. Discard the task and reset the interrupted flag. */ this.tasksInProgress.remove(task); Thread.currentThread().interrupt(); } } } /** * Schedules file ingest tasks for an ingest job. * * @param job The job for which the tasks are to be scheduled. */ synchronized void scheduleFileIngestTasks(DataSourceIngestJob job) { if (!job.isCancelled()) { // Get the top level files for the data source associated with this job // and add them to the root directories priority queue. List<AbstractFile> topLevelFiles = getTopLevelFiles(job.getDataSource()); for (AbstractFile firstLevelFile : topLevelFiles) { FileIngestTask task = new FileIngestTask(job, firstLevelFile); if (IngestTasksScheduler.shouldEnqueueFileTask(task)) { this.tasksInProgress.add(task); this.rootDirectoryTasks.add(task); } } shuffleFileTaskQueues(); } } /** * Schedules a file ingest task for an ingest job. * * @param job The job for which the tasks are to be scheduled. * @param file The file to be associated with the task. */ synchronized void scheduleFileIngestTask(DataSourceIngestJob job, AbstractFile file) { if (!job.isCancelled()) { FileIngestTask task = new FileIngestTask(job, file); if (IngestTasksScheduler.shouldEnqueueFileTask(task)) { this.tasksInProgress.add(task); addToPendingFileTasksQueue(task); } } } /** * Allows an ingest thread to notify this ingest task scheduler that a task * has been completed. * * @param task The completed task. */ synchronized void notifyTaskCompleted(IngestTask task) { tasksInProgress.remove(task); } /** * Queries the task scheduler to determine whether or not all current ingest * tasks for an ingest job are completed. * * @param job The job for which the query is to be performed. * * @return True or false. */ synchronized boolean tasksForJobAreCompleted(DataSourceIngestJob job) { for (IngestTask task : tasksInProgress) { if (task.getIngestJob().getId() == job.getId()) { logger.log(Level.INFO, "Checking {0} total tasks for incomplete tasks for job, no tasks found (jobId={1})", new Object[]{tasksInProgress.size(), job.getId()}); //NON-NLS return false; } } logger.log(Level.INFO, "Checking {0} total tasks for incomplete tasks for job, tasks found (jobId={1})", new Object[]{tasksInProgress.size(), job.getId()}); //NON-NLS return true; } /** * Clears the "upstream" task scheduling queues for an ingest job, but does * nothing about tasks that have already been shuffled into the concurrently * accessed blocking queues shared with the ingest threads. Note that tasks * in the "downstream" queues or already taken by the ingest threads will be * flushed out when the ingest threads call back with their task completed * notifications. * * @param job The job for which the tasks are to to canceled. */ synchronized void cancelPendingTasksForIngestJob(DataSourceIngestJob job) { /** * This code should not flush the blocking queues that are concurrently * accessed by the ingest threads. This is because the "lock striping" * and "weakly consistent" iterators of these collections make it so * that this code could have a different view of the queues than the * ingest threads. It does clean out the directory level tasks before * they are exploded into file tasks. */ long jobId = job.getId(); this.removeTasksForJob(this.rootDirectoryTasks, jobId); this.removeTasksForJob(this.directoryTasks, jobId); this.shuffleFileTaskQueues(); } /** * Gets the top level files such as file system root directories, layout * files and virtual directories for a data source. Used to create file * tasks to put into the root directories queue. * * @param dataSource The data source. * * @return A list of top level files. */ private static List<AbstractFile> getTopLevelFiles(Content dataSource) { List<AbstractFile> topLevelFiles = new ArrayList<>(); Collection<AbstractFile> rootObjects = dataSource.accept(new GetRootDirectoryVisitor()); if (rootObjects.isEmpty() && dataSource instanceof AbstractFile) { // The data source is itself a file to be processed. topLevelFiles.add((AbstractFile) dataSource); } else { for (AbstractFile root : rootObjects) { List<Content> children; try { children = root.getChildren(); if (children.isEmpty()) { // Add the root object itself, it could be an unallocated // space file, or a child of a volume or an image. topLevelFiles.add(root); } else { // The root object is a file system root directory, get // the files within it. for (Content child : children) { if (child instanceof AbstractFile) { topLevelFiles.add((AbstractFile) child); } } } } catch (TskCoreException ex) { logger.log(Level.WARNING, "Could not get children of root to enqueue: " + root.getId() + ": " + root.getName(), ex); //NON-NLS } } } return topLevelFiles; } /** * "Shuffles" the file task queues to ensure that there is at least one task * in the pending file ingest tasks queue, as long as there are still file * ingest tasks to be performed. */ synchronized private void shuffleFileTaskQueues() { // This is synchronized because it is called both by synchronized // methods of this ingest scheduler and an unsynchronized method of its // file tasks "dispenser". while (true) { // Loop until either the pending file tasks queue is NOT empty // or the upstream queues that feed into it ARE empty. if (!this.pendingFileTasks.isEmpty()) { // There are file tasks ready to be consumed, exit. return; } if (this.directoryTasks.isEmpty()) { if (this.rootDirectoryTasks.isEmpty()) { // There are no root directory tasks to move into the // directory queue, exit. return; } else { // Move the next root directory task into the // directories queue. Note that the task was already // added to the tasks in progress list when the task was // created in scheduleFileIngestTasks(). this.directoryTasks.add(this.rootDirectoryTasks.pollFirst()); } } // Try to add the most recently added directory from the // directory tasks queue to the pending file tasks queue. FileIngestTask directoryTask = this.directoryTasks.remove(this.directoryTasks.size() - 1); if (shouldEnqueueFileTask(directoryTask)) { addToPendingFileTasksQueue(directoryTask); } else { this.tasksInProgress.remove(directoryTask); } // If the directory contains subdirectories or files, try to // enqueue tasks for them as well. final AbstractFile directory = directoryTask.getFile(); try { for (Content child : directory.getChildren()) { if (child instanceof AbstractFile) { AbstractFile file = (AbstractFile) child; FileIngestTask childTask = new FileIngestTask(directoryTask.getIngestJob(), file); if (file.hasChildren()) { // Found a subdirectory, put the task in the // pending directory tasks queue. Note the // addition of the task to the tasks in progress // list. This is necessary because this is the // first appearance of this task in the queues. this.tasksInProgress.add(childTask); this.directoryTasks.add(childTask); } else if (shouldEnqueueFileTask(childTask)) { // Found a file, put the task directly into the // pending file tasks queue. this.tasksInProgress.add(childTask); addToPendingFileTasksQueue(childTask); } } } } catch (TskCoreException ex) { String errorMessage = String.format("An error occurred getting the children of %s", directory.getName()); //NON-NLS logger.log(Level.SEVERE, errorMessage, ex); } } } /** * Examines the file associated with a file ingest task to determine whether * or not the file should be processed and therefore whether or not the task * should be enqueued. * * @param task The task to be scrutinized. * * @return True or false. */ private static boolean shouldEnqueueFileTask(final FileIngestTask task) { final AbstractFile file = task.getFile(); // Skip the task if the file is actually the pseudo-file for the parent // or current directory. String fileName = file.getName(); if (fileName.equals(".") || fileName.equals("..")) { return false; } /** * Check if the file is a member of the file ingest filter that is being * applied to the current run of ingest, checks if unallocated space * should be processed inside call to fileIsMemberOf */ if (file.isFile() && task.getIngestJob().getFileIngestFilter().fileIsMemberOf(file) == null) { return false; } // Skip the task if the file is one of a select group of special, large // NTFS or FAT file system files. if (file instanceof org.sleuthkit.datamodel.File) { final org.sleuthkit.datamodel.File f = (org.sleuthkit.datamodel.File) file; // Get the type of the file system, if any, that owns the file. TskData.TSK_FS_TYPE_ENUM fsType = TskData.TSK_FS_TYPE_ENUM.TSK_FS_TYPE_UNSUPP; try { FileSystem fs = f.getFileSystem(); if (fs != null) { fsType = fs.getFsType(); } } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error querying file system for " + f, ex); //NON-NLS } // If the file system is not NTFS or FAT, don't skip the file. if ((fsType.getValue() & FAT_NTFS_FLAGS) == 0) { return true; } // Find out whether the file is in a root directory. boolean isInRootDir = false; try { AbstractFile parent = f.getParentDirectory(); isInRootDir = parent.isRoot(); } catch (TskCoreException ex) { logger.log(Level.WARNING, "Error querying parent directory for" + f.getName(), ex); //NON-NLS } // If the file is in the root directory of an NTFS or FAT file // system, check its meta-address and check its name for the '$' // character and a ':' character (not a default attribute). if (isInRootDir && f.getMetaAddr() < 32) { String name = f.getName(); if (name.length() > 0 && name.charAt(0) == '$' && name.contains(":")) { return false; } } } return true; } /** * Adds a file ingest task to the blocking pending tasks queue. * * @param task The task to add. */ synchronized private void addToPendingFileTasksQueue(FileIngestTask task) { try { this.pendingFileTasks.putFirst(task); } catch (InterruptedException ex) { /** * The current thread was interrupted while blocked on a full queue. * Discard the task and reset the interrupted flag. */ this.tasksInProgress.remove(task); Thread.currentThread().interrupt(); } } /** * Removes all of the ingest tasks associated with an ingest job from a * tasks queue. The task is removed from the the tasks in progress list as * well. * * @param taskQueue The queue from which to remove the tasks. * @param jobId The id of the job for which the tasks are to be removed. */ synchronized private void removeTasksForJob(Collection<? extends IngestTask> taskQueue, long jobId) { Iterator<? extends IngestTask> iterator = taskQueue.iterator(); while (iterator.hasNext()) { IngestTask task = iterator.next(); if (task.getIngestJob().getId() == jobId) { this.tasksInProgress.remove(task); iterator.remove(); } } } /** * Counts the number of ingest tasks in a task queue for a given job. * * @param queue The queue for which to count tasks. * @param jobId The id of the job for which the tasks are to be counted. * * @return The count. */ private static int countTasksForJob(Collection<? extends IngestTask> queue, long jobId) { Iterator<? extends IngestTask> iterator = queue.iterator(); int count = 0; while (iterator.hasNext()) { IngestTask task = (IngestTask) iterator.next(); if (task.getIngestJob().getId() == jobId) { count++; } } return count; } /** * Returns a snapshot of the states of the tasks in progress for an ingest * job. * * @param jobId The identifier assigned to the job. * * @return */ synchronized IngestJobTasksSnapshot getTasksSnapshotForJob(long jobId) { return new IngestJobTasksSnapshot(jobId); } /** * Prioritizes tasks for the root directories file ingest tasks queue (file * system root directories, layout files and virtual directories). */ private static class RootDirectoryTaskComparator implements Comparator<FileIngestTask> { @Override public int compare(FileIngestTask q1, FileIngestTask q2) { AbstractFilePriority.Priority p1 = AbstractFilePriority.getPriority(q1.getFile()); AbstractFilePriority.Priority p2 = AbstractFilePriority.getPriority(q2.getFile()); if (p1 == p2) { return (int) (q2.getFile().getId() - q1.getFile().getId()); } else { return p2.ordinal() - p1.ordinal(); } } private static class AbstractFilePriority { enum Priority { LAST, LOW, MEDIUM, HIGH } static final List<Pattern> LAST_PRI_PATHS = new ArrayList<>(); static final List<Pattern> LOW_PRI_PATHS = new ArrayList<>(); static final List<Pattern> MEDIUM_PRI_PATHS = new ArrayList<>(); static final List<Pattern> HIGH_PRI_PATHS = new ArrayList<>(); /* * prioritize root directory folders based on the assumption that we * are looking for user content. Other types of investigations may * want different priorities. */ static /* * prioritize root directory folders based on the assumption that we * are looking for user content. Other types of investigations may * want different priorities. */ { // these files have no structure, so they go last //unalloc files are handled as virtual files in getPriority() //LAST_PRI_PATHS.schedule(Pattern.compile("^\\$Unalloc", Pattern.CASE_INSENSITIVE)); //LAST_PRI_PATHS.schedule(Pattern.compile("^\\Unalloc", Pattern.CASE_INSENSITIVE)); LAST_PRI_PATHS.add(Pattern.compile("^pagefile", Pattern.CASE_INSENSITIVE)); LAST_PRI_PATHS.add(Pattern.compile("^hiberfil", Pattern.CASE_INSENSITIVE)); // orphan files are often corrupt and windows does not typically have // user content, so put them towards the bottom LOW_PRI_PATHS.add(Pattern.compile("^\\$OrphanFiles", Pattern.CASE_INSENSITIVE)); LOW_PRI_PATHS.add(Pattern.compile("^Windows", Pattern.CASE_INSENSITIVE)); // all other files go into the medium category too MEDIUM_PRI_PATHS.add(Pattern.compile("^Program Files", Pattern.CASE_INSENSITIVE)); // user content is top priority HIGH_PRI_PATHS.add(Pattern.compile("^Users", Pattern.CASE_INSENSITIVE)); HIGH_PRI_PATHS.add(Pattern.compile("^Documents and Settings", Pattern.CASE_INSENSITIVE)); HIGH_PRI_PATHS.add(Pattern.compile("^home", Pattern.CASE_INSENSITIVE)); HIGH_PRI_PATHS.add(Pattern.compile("^ProgramData", Pattern.CASE_INSENSITIVE)); } /** * Get the enabled priority for a given file. * * @param abstractFile * * @return */ static AbstractFilePriority.Priority getPriority(final AbstractFile abstractFile) { if (!abstractFile.getType().equals(TskData.TSK_DB_FILES_TYPE_ENUM.FS)) { //quickly filter out unstructured content //non-fs virtual files and dirs, such as representing unalloc space return AbstractFilePriority.Priority.LAST; } //determine the fs files priority by name final String path = abstractFile.getName(); if (path == null) { return AbstractFilePriority.Priority.MEDIUM; } for (Pattern p : HIGH_PRI_PATHS) { Matcher m = p.matcher(path); if (m.find()) { return AbstractFilePriority.Priority.HIGH; } } for (Pattern p : MEDIUM_PRI_PATHS) { Matcher m = p.matcher(path); if (m.find()) { return AbstractFilePriority.Priority.MEDIUM; } } for (Pattern p : LOW_PRI_PATHS) { Matcher m = p.matcher(path); if (m.find()) { return AbstractFilePriority.Priority.LOW; } } for (Pattern p : LAST_PRI_PATHS) { Matcher m = p.matcher(path); if (m.find()) { return AbstractFilePriority.Priority.LAST; } } //default is medium return AbstractFilePriority.Priority.MEDIUM; } } } /** * Wraps access to pending data source ingest tasks in the interface * required by the ingest threads. */ private final class DataSourceIngestTaskQueue implements IngestTaskQueue { @Override public IngestTask getNextTask() throws InterruptedException { return IngestTasksScheduler.this.pendingDataSourceTasks.take(); } } /** * Wraps access to pending file ingest tasks in the interface required by * the ingest threads. */ private final class FileIngestTaskQueue implements IngestTaskQueue { @Override public IngestTask getNextTask() throws InterruptedException { FileIngestTask task = IngestTasksScheduler.this.pendingFileTasks.takeFirst(); shuffleFileTaskQueues(); return task; } } /** * A snapshot of ingest tasks data for an ingest job. */ class IngestJobTasksSnapshot { private final long jobId; private final long rootQueueSize; private final long dirQueueSize; private final long fileQueueSize; private final long dsQueueSize; private final long runningListSize; /** * Constructs a snapshot of ingest tasks data for an ingest job. * * @param jobId The identifier associated with the job. */ IngestJobTasksSnapshot(long jobId) { this.jobId = jobId; this.rootQueueSize = countTasksForJob(IngestTasksScheduler.this.rootDirectoryTasks, jobId); this.dirQueueSize = countTasksForJob(IngestTasksScheduler.this.directoryTasks, jobId); this.fileQueueSize = countTasksForJob(IngestTasksScheduler.this.pendingFileTasks, jobId); this.dsQueueSize = countTasksForJob(IngestTasksScheduler.this.pendingDataSourceTasks, jobId); this.runningListSize = countTasksForJob(IngestTasksScheduler.this.tasksInProgress, jobId); } /** * Gets the identifier associated with the ingest job for which this * snapshot was created. * * @return The ingest job identifier. */ long getJobId() { return jobId; } /** * Gets the number of file ingest tasks associated with the job that are * in the root directories queue. * * @return The tasks count. */ long getRootQueueSize() { return rootQueueSize; } /** * Gets the number of file ingest tasks associated with the job that are * in the root directories queue. * * @return The tasks count. */ long getDirectoryTasksQueueSize() { return dirQueueSize; } long getFileQueueSize() { return fileQueueSize; } long getDsQueueSize() { return dsQueueSize; } long getRunningListSize() { return runningListSize; } } }
Core/src/org/sleuthkit/autopsy/ingest/IngestTasksScheduler.java
/* * Autopsy Forensic Browser * * Copyright 2012-2017 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * 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.sleuthkit.autopsy.ingest; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.datamodel.AbstractFile; import org.sleuthkit.datamodel.Content; import org.sleuthkit.datamodel.FileSystem; import org.sleuthkit.datamodel.TskCoreException; import org.sleuthkit.datamodel.TskData; /** * Creates ingest tasks for ingest jobs, queuing the tasks in priority order for * execution by the ingest manager's ingest threads. */ final class IngestTasksScheduler { private static final Logger logger = Logger.getLogger(IngestTasksScheduler.class.getName()); private static final int FAT_NTFS_FLAGS = TskData.TSK_FS_TYPE_ENUM.TSK_FS_TYPE_FAT12.getValue() | TskData.TSK_FS_TYPE_ENUM.TSK_FS_TYPE_FAT16.getValue() | TskData.TSK_FS_TYPE_ENUM.TSK_FS_TYPE_FAT32.getValue() | TskData.TSK_FS_TYPE_ENUM.TSK_FS_TYPE_NTFS.getValue(); private static IngestTasksScheduler instance; /** * Scheduling of data source ingest tasks is accomplished by putting them in * a FIFO queue to be consumed by the ingest threads, so the queue is * wrapped in a "dispenser" that implements the IngestTaskQueue interface * and is exposed via a getter method. */ private final LinkedBlockingQueue<DataSourceIngestTask> pendingDataSourceTasks; private final DataSourceIngestTaskQueue dataSourceTasksDispenser; /** * Scheduling of file ingest tasks is accomplished by "shuffling" them * through a sequence of internal queues that allows for the interleaving of * tasks from different ingest jobs based on priority. These scheduling * queues are: * * 1. Root directory tasks (priority queue) * * 2. Directory tasks (FIFO queue) * * 3. Pending file tasks (LIFO queue). * * The pending file tasks queue is LIFO to handle large numbers of files * extracted from archive files. At least one image has been processed that * had a folder full of archive files. The queue grew to have thousands of * entries, as each successive archive file was expanded, so now extracted * files get added to the front of the queue so that in such a scenario they * would be processed before the expansion of the next archive file. * * Tasks in the pending file tasks queue are ready to be consumed by the * ingest threads, so the queue is wrapped in a "dispenser" that implements * the IngestTaskQueue interface and is exposed via a getter method. */ private final TreeSet<FileIngestTask> rootDirectoryTasks; private final List<FileIngestTask> directoryTasks; private final BlockingDeque<FileIngestTask> pendingFileTasks; private final FileIngestTaskQueue fileTasksDispenser; /** * The ingest tasks scheduler allows ingest jobs to query it to see if there * are any tasks in progress for the job. To make this possible, the ingest * tasks scheduler needs to keep track not only of the tasks in its queues, * but also of the tasks that have been handed out for processing by the * ingest threads. Therefore all ingest tasks are added to this list when * they are created and are not removed when an ingest thread takes an * ingest task. Instead, the ingest thread calls back into the scheduler * when the task is completed, at which time the task will be removed from * this list. */ private final Set<IngestTask> tasksInProgress; /** * Gets the ingest tasks scheduler singleton. */ synchronized static IngestTasksScheduler getInstance() { if (IngestTasksScheduler.instance == null) { IngestTasksScheduler.instance = new IngestTasksScheduler(); } return IngestTasksScheduler.instance; } /** * Constructs an ingest tasks scheduler. */ private IngestTasksScheduler() { this.pendingDataSourceTasks = new LinkedBlockingQueue<>(); this.dataSourceTasksDispenser = new DataSourceIngestTaskQueue(); this.rootDirectoryTasks = new TreeSet<>(new RootDirectoryTaskComparator()); this.directoryTasks = new ArrayList<>(); this.pendingFileTasks = new LinkedBlockingDeque<>(); this.fileTasksDispenser = new FileIngestTaskQueue(); this.tasksInProgress = new HashSet<>(); } /** * Gets this ingest task scheduler's implementation of the IngestTaskQueue * interface for data source ingest tasks. * * @return The data source ingest tasks queue. */ IngestTaskQueue getDataSourceIngestTaskQueue() { return this.dataSourceTasksDispenser; } /** * Gets this ingest task scheduler's implementation of the IngestTaskQueue * interface for file ingest tasks. * * @return The file ingest tasks queue. */ IngestTaskQueue getFileIngestTaskQueue() { return this.fileTasksDispenser; } /** * Schedules a data source ingest task and file ingest tasks for an ingest * job. * * @param job The job for which the tasks are to be scheduled. * * @throws InterruptedException if the calling thread is blocked due to a * full tasks queue and is interrupted. */ synchronized void scheduleIngestTasks(DataSourceIngestJob job) { if (!job.isCancelled()) { // Scheduling of both a data source ingest task and file ingest tasks // for a job must be an atomic operation. Otherwise, the data source // task might be completed before the file tasks are scheduled, // resulting in a potential false positive when another thread checks // whether or not all the tasks for the job are completed. this.scheduleDataSourceIngestTask(job); this.scheduleFileIngestTasks(job); } } /** * Schedules a data source ingest task for an ingest job. * * @param job The job for which the tasks are to be scheduled. */ synchronized void scheduleDataSourceIngestTask(DataSourceIngestJob job) { if (!job.isCancelled()) { DataSourceIngestTask task = new DataSourceIngestTask(job); this.tasksInProgress.add(task); try { this.pendingDataSourceTasks.put(task); } catch (InterruptedException ex) { /** * The current thread was interrupted while blocked on a full * queue. Discard the task and reset the interrupted flag. */ this.tasksInProgress.remove(task); Thread.currentThread().interrupt(); } } } /** * Schedules file ingest tasks for an ingest job. * * @param job The job for which the tasks are to be scheduled. */ synchronized void scheduleFileIngestTasks(DataSourceIngestJob job) { if (!job.isCancelled()) { // Get the top level files for the data source associated with this job // and add them to the root directories priority queue. List<AbstractFile> topLevelFiles = getTopLevelFiles(job.getDataSource()); for (AbstractFile firstLevelFile : topLevelFiles) { FileIngestTask task = new FileIngestTask(job, firstLevelFile); if (IngestTasksScheduler.shouldEnqueueFileTask(task)) { this.tasksInProgress.add(task); this.rootDirectoryTasks.add(task); } } shuffleFileTaskQueues(); } } /** * Schedules a file ingest task for an ingest job. * * @param job The job for which the tasks are to be scheduled. * @param file The file to be associated with the task. */ synchronized void scheduleFileIngestTask(DataSourceIngestJob job, AbstractFile file) { if (!job.isCancelled()) { FileIngestTask task = new FileIngestTask(job, file); if (IngestTasksScheduler.shouldEnqueueFileTask(task)) { this.tasksInProgress.add(task); addToPendingFileTasksQueue(task); } } } /** * Allows an ingest thread to notify this ingest task scheduler that a task * has been completed. * * @param task The completed task. */ synchronized void notifyTaskCompleted(IngestTask task) { tasksInProgress.remove(task); } /** * Queries the task scheduler to determine whether or not all current ingest * tasks for an ingest job are completed. * * @param job The job for which the query is to be performed. * * @return True or false. */ synchronized boolean tasksForJobAreCompleted(DataSourceIngestJob job) { for (IngestTask task : tasksInProgress) { if (task.getIngestJob().getId() == job.getId()) { return false; } } return true; } /** * Clears the "upstream" task scheduling queues for an ingest job, but does * nothing about tasks that have already been shuffled into the concurrently * accessed blocking queues shared with the ingest threads. Note that tasks * in the "downstream" queues or already taken by the ingest threads will be * flushed out when the ingest threads call back with their task completed * notifications. * * @param job The job for which the tasks are to to canceled. */ synchronized void cancelPendingTasksForIngestJob(DataSourceIngestJob job) { /** * This code should not flush the blocking queues that are concurrently * accessed by the ingest threads. This is because the "lock striping" * and "weakly consistent" iterators of these collections make it so * that this code could have a different view of the queues than the * ingest threads. It does clean out the directory level tasks before * they are exploded into file tasks. */ long jobId = job.getId(); this.removeTasksForJob(this.rootDirectoryTasks, jobId); this.removeTasksForJob(this.directoryTasks, jobId); this.shuffleFileTaskQueues(); } /** * Gets the top level files such as file system root directories, layout * files and virtual directories for a data source. Used to create file * tasks to put into the root directories queue. * * @param dataSource The data source. * * @return A list of top level files. */ private static List<AbstractFile> getTopLevelFiles(Content dataSource) { List<AbstractFile> topLevelFiles = new ArrayList<>(); Collection<AbstractFile> rootObjects = dataSource.accept(new GetRootDirectoryVisitor()); if (rootObjects.isEmpty() && dataSource instanceof AbstractFile) { // The data source is itself a file to be processed. topLevelFiles.add((AbstractFile) dataSource); } else { for (AbstractFile root : rootObjects) { List<Content> children; try { children = root.getChildren(); if (children.isEmpty()) { // Add the root object itself, it could be an unallocated // space file, or a child of a volume or an image. topLevelFiles.add(root); } else { // The root object is a file system root directory, get // the files within it. for (Content child : children) { if (child instanceof AbstractFile) { topLevelFiles.add((AbstractFile) child); } } } } catch (TskCoreException ex) { logger.log(Level.WARNING, "Could not get children of root to enqueue: " + root.getId() + ": " + root.getName(), ex); //NON-NLS } } } return topLevelFiles; } /** * "Shuffles" the file task queues to ensure that there is at least one task * in the pending file ingest tasks queue, as long as there are still file * ingest tasks to be performed. */ synchronized private void shuffleFileTaskQueues() { // This is synchronized because it is called both by synchronized // methods of this ingest scheduler and an unsynchronized method of its // file tasks "dispenser". while (true) { // Loop until either the pending file tasks queue is NOT empty // or the upstream queues that feed into it ARE empty. if (!this.pendingFileTasks.isEmpty()) { // There are file tasks ready to be consumed, exit. return; } if (this.directoryTasks.isEmpty()) { if (this.rootDirectoryTasks.isEmpty()) { // There are no root directory tasks to move into the // directory queue, exit. return; } else { // Move the next root directory task into the // directories queue. Note that the task was already // added to the tasks in progress list when the task was // created in scheduleFileIngestTasks(). this.directoryTasks.add(this.rootDirectoryTasks.pollFirst()); } } // Try to add the most recently added directory from the // directory tasks queue to the pending file tasks queue. FileIngestTask directoryTask = this.directoryTasks.remove(this.directoryTasks.size() - 1); if (shouldEnqueueFileTask(directoryTask)) { addToPendingFileTasksQueue(directoryTask); } else { this.tasksInProgress.remove(directoryTask); } // If the directory contains subdirectories or files, try to // enqueue tasks for them as well. final AbstractFile directory = directoryTask.getFile(); try { for (Content child : directory.getChildren()) { if (child instanceof AbstractFile) { AbstractFile file = (AbstractFile) child; FileIngestTask childTask = new FileIngestTask(directoryTask.getIngestJob(), file); if (file.hasChildren()) { // Found a subdirectory, put the task in the // pending directory tasks queue. Note the // addition of the task to the tasks in progress // list. This is necessary because this is the // first appearance of this task in the queues. this.tasksInProgress.add(childTask); this.directoryTasks.add(childTask); } else if (shouldEnqueueFileTask(childTask)) { // Found a file, put the task directly into the // pending file tasks queue. this.tasksInProgress.add(childTask); addToPendingFileTasksQueue(childTask); } } } } catch (TskCoreException ex) { String errorMessage = String.format("An error occurred getting the children of %s", directory.getName()); //NON-NLS logger.log(Level.SEVERE, errorMessage, ex); } } } /** * Examines the file associated with a file ingest task to determine whether * or not the file should be processed and therefore whether or not the task * should be enqueued. * * @param task The task to be scrutinized. * * @return True or false. */ private static boolean shouldEnqueueFileTask(final FileIngestTask task) { final AbstractFile file = task.getFile(); // Skip the task if the file is actually the pseudo-file for the parent // or current directory. String fileName = file.getName(); if (fileName.equals(".") || fileName.equals("..")) { return false; } /** * Check if the file is a member of the file ingest filter that is being * applied to the current run of ingest, checks if unallocated space * should be processed inside call to fileIsMemberOf */ if (file.isFile() && task.getIngestJob().getFileIngestFilter().fileIsMemberOf(file) == null) { return false; } // Skip the task if the file is one of a select group of special, large // NTFS or FAT file system files. if (file instanceof org.sleuthkit.datamodel.File) { final org.sleuthkit.datamodel.File f = (org.sleuthkit.datamodel.File) file; // Get the type of the file system, if any, that owns the file. TskData.TSK_FS_TYPE_ENUM fsType = TskData.TSK_FS_TYPE_ENUM.TSK_FS_TYPE_UNSUPP; try { FileSystem fs = f.getFileSystem(); if (fs != null) { fsType = fs.getFsType(); } } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error querying file system for " + f, ex); //NON-NLS } // If the file system is not NTFS or FAT, don't skip the file. if ((fsType.getValue() & FAT_NTFS_FLAGS) == 0) { return true; } // Find out whether the file is in a root directory. boolean isInRootDir = false; try { AbstractFile parent = f.getParentDirectory(); isInRootDir = parent.isRoot(); } catch (TskCoreException ex) { logger.log(Level.WARNING, "Error querying parent directory for" + f.getName(), ex); //NON-NLS } // If the file is in the root directory of an NTFS or FAT file // system, check its meta-address and check its name for the '$' // character and a ':' character (not a default attribute). if (isInRootDir && f.getMetaAddr() < 32) { String name = f.getName(); if (name.length() > 0 && name.charAt(0) == '$' && name.contains(":")) { return false; } } } return true; } /** * Adds a file ingest task to the blocking pending tasks queue. * * @param task The task to add. */ synchronized private void addToPendingFileTasksQueue(FileIngestTask task) { try { this.pendingFileTasks.putFirst(task); } catch (InterruptedException ex) { /** * The current thread was interrupted while blocked on a full queue. * Discard the task and reset the interrupted flag. */ this.tasksInProgress.remove(task); Thread.currentThread().interrupt(); } } /** * Removes all of the ingest tasks associated with an ingest job from a * tasks queue. The task is removed from the the tasks in progress list as * well. * * @param taskQueue The queue from which to remove the tasks. * @param jobId The id of the job for which the tasks are to be removed. */ synchronized private void removeTasksForJob(Collection<? extends IngestTask> taskQueue, long jobId) { Iterator<? extends IngestTask> iterator = taskQueue.iterator(); while (iterator.hasNext()) { IngestTask task = iterator.next(); if (task.getIngestJob().getId() == jobId) { this.tasksInProgress.remove(task); iterator.remove(); } } } /** * Counts the number of ingest tasks in a task queue for a given job. * * @param queue The queue for which to count tasks. * @param jobId The id of the job for which the tasks are to be counted. * * @return The count. */ private static int countTasksForJob(Collection<? extends IngestTask> queue, long jobId) { Iterator<? extends IngestTask> iterator = queue.iterator(); int count = 0; while (iterator.hasNext()) { IngestTask task = (IngestTask) iterator.next(); if (task.getIngestJob().getId() == jobId) { count++; } } return count; } /** * Returns a snapshot of the states of the tasks in progress for an ingest * job. * * @param jobId The identifier assigned to the job. * * @return */ synchronized IngestJobTasksSnapshot getTasksSnapshotForJob(long jobId) { return new IngestJobTasksSnapshot(jobId); } /** * Prioritizes tasks for the root directories file ingest tasks queue (file * system root directories, layout files and virtual directories). */ private static class RootDirectoryTaskComparator implements Comparator<FileIngestTask> { @Override public int compare(FileIngestTask q1, FileIngestTask q2) { AbstractFilePriority.Priority p1 = AbstractFilePriority.getPriority(q1.getFile()); AbstractFilePriority.Priority p2 = AbstractFilePriority.getPriority(q2.getFile()); if (p1 == p2) { return (int) (q2.getFile().getId() - q1.getFile().getId()); } else { return p2.ordinal() - p1.ordinal(); } } private static class AbstractFilePriority { enum Priority { LAST, LOW, MEDIUM, HIGH } static final List<Pattern> LAST_PRI_PATHS = new ArrayList<>(); static final List<Pattern> LOW_PRI_PATHS = new ArrayList<>(); static final List<Pattern> MEDIUM_PRI_PATHS = new ArrayList<>(); static final List<Pattern> HIGH_PRI_PATHS = new ArrayList<>(); /* * prioritize root directory folders based on the assumption that we * are looking for user content. Other types of investigations may * want different priorities. */ static /* * prioritize root directory folders based on the assumption that we * are looking for user content. Other types of investigations may * want different priorities. */ { // these files have no structure, so they go last //unalloc files are handled as virtual files in getPriority() //LAST_PRI_PATHS.schedule(Pattern.compile("^\\$Unalloc", Pattern.CASE_INSENSITIVE)); //LAST_PRI_PATHS.schedule(Pattern.compile("^\\Unalloc", Pattern.CASE_INSENSITIVE)); LAST_PRI_PATHS.add(Pattern.compile("^pagefile", Pattern.CASE_INSENSITIVE)); LAST_PRI_PATHS.add(Pattern.compile("^hiberfil", Pattern.CASE_INSENSITIVE)); // orphan files are often corrupt and windows does not typically have // user content, so put them towards the bottom LOW_PRI_PATHS.add(Pattern.compile("^\\$OrphanFiles", Pattern.CASE_INSENSITIVE)); LOW_PRI_PATHS.add(Pattern.compile("^Windows", Pattern.CASE_INSENSITIVE)); // all other files go into the medium category too MEDIUM_PRI_PATHS.add(Pattern.compile("^Program Files", Pattern.CASE_INSENSITIVE)); // user content is top priority HIGH_PRI_PATHS.add(Pattern.compile("^Users", Pattern.CASE_INSENSITIVE)); HIGH_PRI_PATHS.add(Pattern.compile("^Documents and Settings", Pattern.CASE_INSENSITIVE)); HIGH_PRI_PATHS.add(Pattern.compile("^home", Pattern.CASE_INSENSITIVE)); HIGH_PRI_PATHS.add(Pattern.compile("^ProgramData", Pattern.CASE_INSENSITIVE)); } /** * Get the enabled priority for a given file. * * @param abstractFile * * @return */ static AbstractFilePriority.Priority getPriority(final AbstractFile abstractFile) { if (!abstractFile.getType().equals(TskData.TSK_DB_FILES_TYPE_ENUM.FS)) { //quickly filter out unstructured content //non-fs virtual files and dirs, such as representing unalloc space return AbstractFilePriority.Priority.LAST; } //determine the fs files priority by name final String path = abstractFile.getName(); if (path == null) { return AbstractFilePriority.Priority.MEDIUM; } for (Pattern p : HIGH_PRI_PATHS) { Matcher m = p.matcher(path); if (m.find()) { return AbstractFilePriority.Priority.HIGH; } } for (Pattern p : MEDIUM_PRI_PATHS) { Matcher m = p.matcher(path); if (m.find()) { return AbstractFilePriority.Priority.MEDIUM; } } for (Pattern p : LOW_PRI_PATHS) { Matcher m = p.matcher(path); if (m.find()) { return AbstractFilePriority.Priority.LOW; } } for (Pattern p : LAST_PRI_PATHS) { Matcher m = p.matcher(path); if (m.find()) { return AbstractFilePriority.Priority.LAST; } } //default is medium return AbstractFilePriority.Priority.MEDIUM; } } } /** * Wraps access to pending data source ingest tasks in the interface * required by the ingest threads. */ private final class DataSourceIngestTaskQueue implements IngestTaskQueue { @Override public IngestTask getNextTask() throws InterruptedException { return IngestTasksScheduler.this.pendingDataSourceTasks.take(); } } /** * Wraps access to pending file ingest tasks in the interface required by * the ingest threads. */ private final class FileIngestTaskQueue implements IngestTaskQueue { @Override public IngestTask getNextTask() throws InterruptedException { FileIngestTask task = IngestTasksScheduler.this.pendingFileTasks.takeFirst(); shuffleFileTaskQueues(); return task; } } /** * A snapshot of ingest tasks data for an ingest job. */ class IngestJobTasksSnapshot { private final long jobId; private final long rootQueueSize; private final long dirQueueSize; private final long fileQueueSize; private final long dsQueueSize; private final long runningListSize; /** * Constructs a snapshot of ingest tasks data for an ingest job. * * @param jobId The identifier associated with the job. */ IngestJobTasksSnapshot(long jobId) { this.jobId = jobId; this.rootQueueSize = countTasksForJob(IngestTasksScheduler.this.rootDirectoryTasks, jobId); this.dirQueueSize = countTasksForJob(IngestTasksScheduler.this.directoryTasks, jobId); this.fileQueueSize = countTasksForJob(IngestTasksScheduler.this.pendingFileTasks, jobId); this.dsQueueSize = countTasksForJob(IngestTasksScheduler.this.pendingDataSourceTasks, jobId); this.runningListSize = countTasksForJob(IngestTasksScheduler.this.tasksInProgress, jobId); } /** * Gets the identifier associated with the ingest job for which this * snapshot was created. * * @return The ingest job identifier. */ long getJobId() { return jobId; } /** * Gets the number of file ingest tasks associated with the job that are * in the root directories queue. * * @return The tasks count. */ long getRootQueueSize() { return rootQueueSize; } /** * Gets the number of file ingest tasks associated with the job that are * in the root directories queue. * * @return The tasks count. */ long getDirectoryTasksQueueSize() { return dirQueueSize; } long getFileQueueSize() { return fileQueueSize; } long getDsQueueSize() { return dsQueueSize; } long getRunningListSize() { return runningListSize; } } }
Added temporary logging to IngestTasksScheduler.tasksForJobAreCompleted
Core/src/org/sleuthkit/autopsy/ingest/IngestTasksScheduler.java
Added temporary logging to IngestTasksScheduler.tasksForJobAreCompleted
<ide><path>ore/src/org/sleuthkit/autopsy/ingest/IngestTasksScheduler.java <ide> synchronized boolean tasksForJobAreCompleted(DataSourceIngestJob job) { <ide> for (IngestTask task : tasksInProgress) { <ide> if (task.getIngestJob().getId() == job.getId()) { <add> logger.log(Level.INFO, "Checking {0} total tasks for incomplete tasks for job, no tasks found (jobId={1})", new Object[]{tasksInProgress.size(), job.getId()}); //NON-NLS <ide> return false; <ide> } <ide> } <add> logger.log(Level.INFO, "Checking {0} total tasks for incomplete tasks for job, tasks found (jobId={1})", new Object[]{tasksInProgress.size(), job.getId()}); //NON-NLS <ide> return true; <ide> } <ide>
Java
apache-2.0
fed94e9b199a90a404adb6c81f838e534dce7284
0
dslomov/intellij-community,kool79/intellij-community,orekyuu/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,kdwink/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,joewalnes/idea-community,consulo/consulo,dslomov/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,robovm/robovm-studio,blademainer/intellij-community,amith01994/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,caot/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,semonte/intellij-community,holmes/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,signed/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,caot/intellij-community,fnouama/intellij-community,slisson/intellij-community,ernestp/consulo,da1z/intellij-community,hurricup/intellij-community,blademainer/intellij-community,signed/intellij-community,asedunov/intellij-community,vladmm/intellij-community,allotria/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,Lekanich/intellij-community,kool79/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,ernestp/consulo,holmes/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,da1z/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,joewalnes/idea-community,wreckJ/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,joewalnes/idea-community,blademainer/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,da1z/intellij-community,fnouama/intellij-community,ibinti/intellij-community,retomerz/intellij-community,allotria/intellij-community,hurricup/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,hurricup/intellij-community,kdwink/intellij-community,apixandru/intellij-community,caot/intellij-community,izonder/intellij-community,da1z/intellij-community,caot/intellij-community,supersven/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,da1z/intellij-community,kool79/intellij-community,clumsy/intellij-community,ryano144/intellij-community,signed/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,samthor/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,dslomov/intellij-community,robovm/robovm-studio,amith01994/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,consulo/consulo,xfournet/intellij-community,adedayo/intellij-community,supersven/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,holmes/intellij-community,amith01994/intellij-community,fitermay/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,Distrotech/intellij-community,allotria/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,retomerz/intellij-community,robovm/robovm-studio,semonte/intellij-community,kdwink/intellij-community,signed/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,slisson/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,consulo/consulo,ol-loginov/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,holmes/intellij-community,joewalnes/idea-community,youdonghai/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,da1z/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,allotria/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,izonder/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,signed/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,slisson/intellij-community,da1z/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,caot/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,kool79/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,signed/intellij-community,nicolargo/intellij-community,caot/intellij-community,kool79/intellij-community,diorcety/intellij-community,allotria/intellij-community,diorcety/intellij-community,ernestp/consulo,asedunov/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,samthor/intellij-community,asedunov/intellij-community,xfournet/intellij-community,consulo/consulo,mglukhikh/intellij-community,asedunov/intellij-community,FHannes/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,kool79/intellij-community,xfournet/intellij-community,joewalnes/idea-community,Lekanich/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,kool79/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,ernestp/consulo,adedayo/intellij-community,semonte/intellij-community,joewalnes/idea-community,jagguli/intellij-community,samthor/intellij-community,wreckJ/intellij-community,izonder/intellij-community,Lekanich/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,izonder/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,asedunov/intellij-community,fnouama/intellij-community,petteyg/intellij-community,ryano144/intellij-community,samthor/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,robovm/robovm-studio,blademainer/intellij-community,ahb0327/intellij-community,joewalnes/idea-community,samthor/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,kool79/intellij-community,signed/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,caot/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,allotria/intellij-community,ryano144/intellij-community,da1z/intellij-community,ernestp/consulo,nicolargo/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,samthor/intellij-community,slisson/intellij-community,fnouama/intellij-community,diorcety/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,nicolargo/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,apixandru/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,holmes/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,kdwink/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,signed/intellij-community,jagguli/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,apixandru/intellij-community,kdwink/intellij-community,joewalnes/idea-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,signed/intellij-community,hurricup/intellij-community,da1z/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,clumsy/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,amith01994/intellij-community,semonte/intellij-community,allotria/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,semonte/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,semonte/intellij-community,diorcety/intellij-community,consulo/consulo,allotria/intellij-community,petteyg/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,amith01994/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,signed/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,alphafoobar/intellij-community,joewalnes/idea-community,vvv1559/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,ahb0327/intellij-community,supersven/intellij-community,amith01994/intellij-community,supersven/intellij-community,xfournet/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,samthor/intellij-community,semonte/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,FHannes/intellij-community,consulo/consulo,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,jagguli/intellij-community,kool79/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,petteyg/intellij-community,apixandru/intellij-community,blademainer/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,robovm/robovm-studio,fnouama/intellij-community,blademainer/intellij-community,dslomov/intellij-community,da1z/intellij-community,jagguli/intellij-community,FHannes/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,FHannes/intellij-community,clumsy/intellij-community,diorcety/intellij-community,retomerz/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,vladmm/intellij-community,fitermay/intellij-community,xfournet/intellij-community,supersven/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,asedunov/intellij-community,ibinti/intellij-community,blademainer/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,robovm/robovm-studio,jagguli/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,caot/intellij-community,nicolargo/intellij-community,holmes/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community
/* * Copyright 2000-2010 JetBrains s.r.o. * * 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.intellij.openapi.editor.impl; import com.intellij.openapi.editor.FoldRegion; import com.intellij.openapi.editor.RangeMarker; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.CollectionFactory; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; /** * User: cdr */ abstract class FoldRegionsTree { public static final boolean DEBUG = Boolean.getBoolean("idea.editor.debug.folding"); private FoldRegion[] myCachedVisible; private FoldRegion[] myCachedTopLevelRegions; private int[] myCachedEndOffsets; private int[] myCachedStartOffsets; private int[] myCachedFoldedLines; int myCachedLastIndex = -1; private ArrayList<FoldRegion> myRegions = CollectionFactory.arrayList(); //sorted in tree left-to-right topdown traversal order private static final Comparator<FoldRegion> BY_END_OFFSET = new Comparator<FoldRegion>() { public int compare(FoldRegion r1, FoldRegion r2) { int end1 = r1.getEndOffset(); int end2 = r2.getEndOffset(); if (end1 < end2) return -1; if (end1 > end2) return 1; return 0; } }; private static final Comparator<? super FoldRegion> BY_END_OFFSET_REVERSE = Collections.reverseOrder(BY_END_OFFSET); void clear() { myCachedVisible = null; myCachedTopLevelRegions = null; myCachedEndOffsets = null; myCachedStartOffsets = null; myCachedFoldedLines = null; if (myRegions != null) { for (FoldRegion region : myRegions) { region.dispose(); } } myRegions = new ArrayList<FoldRegion>(); } private boolean isFoldingEnabledAndUpToDate() { return isFoldingEnabled() && myCachedVisible != null; } protected abstract boolean isFoldingEnabled(); protected abstract boolean isBatchFoldingProcessing(); void rebuild() { ArrayList<FoldRegion> topLevels = new ArrayList<FoldRegion>(myRegions.size() / 2); ArrayList<FoldRegion> visible = new ArrayList<FoldRegion>(myRegions.size()); FoldRegion[] regions = myRegions.toArray(new FoldRegion[myRegions.size()]); FoldRegion currentToplevel = null; for (FoldRegion region : regions) { if (region.isValid()) { visible.add(region); if (!region.isExpanded()) { if (currentToplevel == null || currentToplevel.getEndOffset() < region.getStartOffset()) { currentToplevel = region; topLevels.add(region); } } } } myCachedTopLevelRegions = topLevels.isEmpty() ? FoldRegion.EMPTY_ARRAY : topLevels.toArray(new FoldRegion[topLevels.size()]); Arrays.sort(myCachedTopLevelRegions, BY_END_OFFSET); FoldRegion[] visibleArrayed = visible.toArray(new FoldRegion[visible.size()]); for (FoldRegion visibleRegion : visibleArrayed) { for (FoldRegion topLevelRegion : myCachedTopLevelRegions) { if (contains(topLevelRegion, visibleRegion)) { visible.remove(visibleRegion); break; } } } myCachedVisible = visible.toArray(new FoldRegion[visible.size()]); Arrays.sort(myCachedVisible, BY_END_OFFSET_REVERSE); updateCachedOffsets(); } void updateCachedOffsets() { if (!isFoldingEnabled()) { return; } if (myCachedVisible == null) { rebuild(); return; } for (FoldRegion foldRegion : myCachedVisible) { if (!foldRegion.isValid()) { rebuild(); return; } } int length = myCachedTopLevelRegions.length; if (myCachedEndOffsets == null || myCachedEndOffsets.length != length) { if (length != 0) { myCachedEndOffsets = new int[length]; myCachedStartOffsets = new int[length]; myCachedFoldedLines = new int[length]; } else { myCachedEndOffsets = ArrayUtil.EMPTY_INT_ARRAY; myCachedStartOffsets = ArrayUtil.EMPTY_INT_ARRAY; myCachedFoldedLines = ArrayUtil.EMPTY_INT_ARRAY; } } int sum = 0; for (int i = 0; i < length; i++) { FoldRegion region = myCachedTopLevelRegions[i]; myCachedStartOffsets[i] = region.getStartOffset(); myCachedEndOffsets[i] = region.getEndOffset() - 1; sum += region.getDocument().getLineNumber(region.getEndOffset()) - region.getDocument().getLineNumber(region.getStartOffset()); myCachedFoldedLines[i] = sum; } } boolean addRegion(FoldRegion range) { // During batchProcessing elements are inserted in ascending order, // binary search find acceptable insertion place first time int fastIndex = myCachedLastIndex != -1 && isBatchFoldingProcessing() ? myCachedLastIndex + 1 : Collections.binarySearch(myRegions, range, RangeMarker.BY_START_OFFSET); if (fastIndex < 0) fastIndex = -fastIndex - 1; for (int i = fastIndex - 1; i >=0; --i) { final FoldRegion region = myRegions.get(i); if (region.getEndOffset() < range.getStartOffset()) break; if (region.isValid() && intersects(region, range)) { return false; } } for (int i = fastIndex; i < myRegions.size(); i++) { final FoldRegion region = myRegions.get(i); if (range.getStartOffset() < region.getStartOffset() || range.getStartOffset() == region.getStartOffset() && range.getEndOffset() > region.getEndOffset()) { for (int j = i + 1; j < myRegions.size(); j++) { final FoldRegion next = myRegions.get(j); if (next.getEndOffset() >= range.getEndOffset() && next.isValid()) { if (next.getStartOffset() < range.getStartOffset()) { return false; } else { break; } } } myRegions.add(myCachedLastIndex = i, range); return true; } } myRegions.add(myCachedLastIndex = myRegions.size(),range); return true; } @Nullable FoldRegion fetchOutermost(int offset) { if (!isFoldingEnabledAndUpToDate()) return null; final int[] starts = myCachedStartOffsets; final int[] ends = myCachedEndOffsets; int start = 0; int end = ends.length - 1; while (start <= end) { int i = (start + end) / 2; if (offset < starts[i]) { end = i - 1; } else if (offset > ends[i]) { start = i + 1; } else { // We encountered situation when cached data is inconsistent. It's not clear what produced that, so, the following was done: // 1. Corresponding check was added and cached data is rebuilt in case of inconsistency; // 2. Debug asserts are activated if dedicated flag is on (it's off by default); if (myCachedStartOffsets[i] != myCachedTopLevelRegions[i].getStartOffset()) { if (DEBUG) { assert false : "inconsistent cached fold data detected. Start offsets: " + Arrays.toString(myCachedStartOffsets) + ", end offsets: " + Arrays.toString(myCachedEndOffsets) + ", top regions: " + Arrays.toString(myCachedTopLevelRegions) + ", visible regions: " + Arrays.toString(myCachedVisible); } rebuild(); return fetchOutermost(offset); } return myCachedTopLevelRegions[i]; } } return null; } FoldRegion[] fetchVisible() { if (!isFoldingEnabledAndUpToDate()) return FoldRegion.EMPTY_ARRAY; return myCachedVisible; } @Nullable FoldRegion[] fetchTopLevel() { if (!isFoldingEnabledAndUpToDate()) return null; return myCachedTopLevelRegions; } private static boolean contains(FoldRegion outer, FoldRegion inner) { return outer.getStartOffset() < inner.getStartOffset() && outer.getEndOffset() > inner.getStartOffset(); } private static boolean intersects(FoldRegion r1, FoldRegion r2) { final int s1 = r1.getStartOffset(); final int s2 = r2.getStartOffset(); final int e1 = r1.getEndOffset(); final int e2 = r2.getEndOffset(); return s1 == s2 && e1 == e2 || s1 < s2 && s2 < e1 && e1 < e2 || s2 < s1 && s1 < e2 && e2 < e1; } static boolean contains(FoldRegion region, int offset) { return region.getStartOffset() < offset && region.getEndOffset() > offset; } public FoldRegion[] fetchCollapsedAt(int offset) { if (!isFoldingEnabledAndUpToDate()) return FoldRegion.EMPTY_ARRAY; ArrayList<FoldRegion> allCollapsed = new ArrayList<FoldRegion>(); for (FoldRegion region : myRegions) { if (!region.isExpanded() && contains(region, offset)) { allCollapsed.add(region); } } return allCollapsed.toArray(new FoldRegion[allCollapsed.size()]); } boolean intersectsRegion(int startOffset, int endOffset) { if (!isFoldingEnabled()) return true; for (FoldRegion region : myRegions) { boolean contains1 = contains(region, startOffset); boolean contains2 = contains(region, endOffset); if (contains1 != contains2) { return true; } } return false; } FoldRegion[] fetchAllRegions() { if (!isFoldingEnabledAndUpToDate()) return FoldRegion.EMPTY_ARRAY; return myRegions.toArray(new FoldRegion[myRegions.size()]); } void removeRegion(FoldRegion range) { myRegions.remove(range); } int getFoldedLinesCountBefore(int offset) { int idx = getLastTopLevelIndexBefore(offset); if (idx == -1) return 0; return myCachedFoldedLines[idx]; } public int getLastTopLevelIndexBefore(int offset) { if (!isFoldingEnabledAndUpToDate()) return -1; int start = 0; int end = myCachedEndOffsets.length - 1; while (start <= end) { int i = (start + end) / 2; if (offset < myCachedEndOffsets[i]) { end = i - 1; } else if (offset > myCachedEndOffsets[i]) { start = i + 1; } else { return i; } } return end; } }
platform/platform-impl/src/com/intellij/openapi/editor/impl/FoldRegionsTree.java
/* * Copyright 2000-2010 JetBrains s.r.o. * * 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.intellij.openapi.editor.impl; import com.intellij.openapi.editor.FoldRegion; import com.intellij.openapi.editor.RangeMarker; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.CollectionFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; /** * User: cdr */ abstract class FoldRegionsTree { private FoldRegion[] myCachedVisible; private FoldRegion[] myCachedTopLevelRegions; private int[] myCachedEndOffsets; private int[] myCachedStartOffsets; private int[] myCachedFoldedLines; int myCachedLastIndex = -1; private ArrayList<FoldRegion> myRegions = CollectionFactory.arrayList(); //sorted in tree left-to-right topdown traversal order private static final Comparator<FoldRegion> BY_END_OFFSET = new Comparator<FoldRegion>() { public int compare(FoldRegion r1, FoldRegion r2) { int end1 = r1.getEndOffset(); int end2 = r2.getEndOffset(); if (end1 < end2) return -1; if (end1 > end2) return 1; return 0; } }; private static final Comparator<? super FoldRegion> BY_END_OFFSET_REVERSE = Collections.reverseOrder(BY_END_OFFSET); void clear() { myCachedVisible = null; myCachedTopLevelRegions = null; myCachedEndOffsets = null; myCachedStartOffsets = null; myCachedFoldedLines = null; if (myRegions != null) { for (FoldRegion region : myRegions) { region.dispose(); } } myRegions = new ArrayList<FoldRegion>(); } private boolean isFoldingEnabledAndUpToDate() { return isFoldingEnabled() && myCachedVisible != null; } protected abstract boolean isFoldingEnabled(); protected abstract boolean isBatchFoldingProcessing(); void rebuild() { ArrayList<FoldRegion> topLevels = new ArrayList<FoldRegion>(myRegions.size() / 2); ArrayList<FoldRegion> visible = new ArrayList<FoldRegion>(myRegions.size()); FoldRegion[] regions = myRegions.toArray(new FoldRegion[myRegions.size()]); FoldRegion currentToplevel = null; for (FoldRegion region : regions) { if (region.isValid()) { visible.add(region); if (!region.isExpanded()) { if (currentToplevel == null || currentToplevel.getEndOffset() < region.getStartOffset()) { currentToplevel = region; topLevels.add(region); } } } } myCachedTopLevelRegions = topLevels.isEmpty() ? FoldRegion.EMPTY_ARRAY : topLevels.toArray(new FoldRegion[topLevels.size()]); Arrays.sort(myCachedTopLevelRegions, BY_END_OFFSET); FoldRegion[] visibleArrayed = visible.toArray(new FoldRegion[visible.size()]); for (FoldRegion visibleRegion : visibleArrayed) { for (FoldRegion topLevelRegion : myCachedTopLevelRegions) { if (contains(topLevelRegion, visibleRegion)) { visible.remove(visibleRegion); break; } } } myCachedVisible = visible.toArray(new FoldRegion[visible.size()]); Arrays.sort(myCachedVisible, BY_END_OFFSET_REVERSE); updateCachedOffsets(); } void updateCachedOffsets() { if (!isFoldingEnabled()) { return; } if (myCachedVisible == null) { rebuild(); return; } for (FoldRegion foldRegion : myCachedVisible) { if (!foldRegion.isValid()) { rebuild(); return; } } int length = myCachedTopLevelRegions.length; if (myCachedEndOffsets == null || myCachedEndOffsets.length != length) { if (length != 0) { myCachedEndOffsets = new int[length]; myCachedStartOffsets = new int[length]; myCachedFoldedLines = new int[length]; } else { myCachedEndOffsets = ArrayUtil.EMPTY_INT_ARRAY; myCachedStartOffsets = ArrayUtil.EMPTY_INT_ARRAY; myCachedFoldedLines = ArrayUtil.EMPTY_INT_ARRAY; } } int sum = 0; for (int i = 0; i < length; i++) { FoldRegion region = myCachedTopLevelRegions[i]; myCachedStartOffsets[i] = region.getStartOffset(); myCachedEndOffsets[i] = region.getEndOffset() - 1; sum += region.getDocument().getLineNumber(region.getEndOffset()) - region.getDocument().getLineNumber(region.getStartOffset()); myCachedFoldedLines[i] = sum; } } boolean addRegion(FoldRegion range) { // During batchProcessing elements are inserted in ascending order, // binary search find acceptable insertion place first time int fastIndex = myCachedLastIndex != -1 && isBatchFoldingProcessing() ? myCachedLastIndex + 1 : Collections.binarySearch(myRegions, range, RangeMarker.BY_START_OFFSET); if (fastIndex < 0) fastIndex = -fastIndex - 1; for (int i = fastIndex - 1; i >=0; --i) { final FoldRegion region = myRegions.get(i); if (region.getEndOffset() < range.getStartOffset()) break; if (region.isValid() && intersects(region, range)) { return false; } } for (int i = fastIndex; i < myRegions.size(); i++) { final FoldRegion region = myRegions.get(i); if (range.getStartOffset() < region.getStartOffset() || range.getStartOffset() == region.getStartOffset() && range.getEndOffset() > region.getEndOffset()) { for (int j = i + 1; j < myRegions.size(); j++) { final FoldRegion next = myRegions.get(j); if (next.getEndOffset() >= range.getEndOffset() && next.isValid()) { if (next.getStartOffset() < range.getStartOffset()) { return false; } else { break; } } } myRegions.add(myCachedLastIndex = i, range); return true; } } myRegions.add(myCachedLastIndex = myRegions.size(),range); return true; } FoldRegion fetchOutermost(int offset) { if (!isFoldingEnabledAndUpToDate()) return null; final int[] starts = myCachedStartOffsets; final int[] ends = myCachedEndOffsets; int start = 0; int end = ends.length - 1; while (start <= end) { int i = (start + end) / 2; if (offset < starts[i]) { end = i - 1; } else if (offset > ends[i]) { start = i + 1; } else { return myCachedTopLevelRegions[i]; } } return null; } FoldRegion[] fetchVisible() { if (!isFoldingEnabledAndUpToDate()) return FoldRegion.EMPTY_ARRAY; return myCachedVisible; } FoldRegion[] fetchTopLevel() { if (!isFoldingEnabledAndUpToDate()) return null; return myCachedTopLevelRegions; } private static boolean contains(FoldRegion outer, FoldRegion inner) { return outer.getStartOffset() < inner.getStartOffset() && outer.getEndOffset() > inner.getStartOffset(); } private static boolean intersects(FoldRegion r1, FoldRegion r2) { final int s1 = r1.getStartOffset(); final int s2 = r2.getStartOffset(); final int e1 = r1.getEndOffset(); final int e2 = r2.getEndOffset(); return s1 == s2 && e1 == e2 || s1 < s2 && s2 < e1 && e1 < e2 || s2 < s1 && s1 < e2 && e2 < e1; } static boolean contains(FoldRegion region, int offset) { return region.getStartOffset() < offset && region.getEndOffset() > offset; } public FoldRegion[] fetchCollapsedAt(int offset) { if (!isFoldingEnabledAndUpToDate()) return FoldRegion.EMPTY_ARRAY; ArrayList<FoldRegion> allCollapsed = new ArrayList<FoldRegion>(); for (FoldRegion region : myRegions) { if (!region.isExpanded() && contains(region, offset)) { allCollapsed.add(region); } } return allCollapsed.toArray(new FoldRegion[allCollapsed.size()]); } boolean intersectsRegion(int startOffset, int endOffset) { if (!isFoldingEnabled()) return true; for (FoldRegion region : myRegions) { boolean contains1 = contains(region, startOffset); boolean contains2 = contains(region, endOffset); if (contains1 != contains2) { return true; } } return false; } FoldRegion[] fetchAllRegions() { if (!isFoldingEnabledAndUpToDate()) return FoldRegion.EMPTY_ARRAY; return myRegions.toArray(new FoldRegion[myRegions.size()]); } void removeRegion(FoldRegion range) { myRegions.remove(range); } int getFoldedLinesCountBefore(int offset) { int idx = getLastTopLevelIndexBefore(offset); if (idx == -1) return 0; return myCachedFoldedLines[idx]; } public int getLastTopLevelIndexBefore(int offset) { if (!isFoldingEnabledAndUpToDate()) return -1; int start = 0; int end = myCachedEndOffsets.length - 1; while (start <= end) { int i = (start + end) / 2; if (offset < myCachedEndOffsets[i]) { end = i - 1; } else if (offset > myCachedEndOffsets[i]) { start = i + 1; } else { return i; } } return end; } }
We encountered situation when cached folding data is inconsistent. It's not clear what produced that, so, the following was done: 1. Corresponding check was added and cached data is rebuilt in case of inconsistency; 2. Debug asserts are activated if dedicated flag is on (it's off by default);
platform/platform-impl/src/com/intellij/openapi/editor/impl/FoldRegionsTree.java
We encountered situation when cached folding data is inconsistent. It's not clear what produced that, so, the following was done: 1. Corresponding check was added and cached data is rebuilt in case of inconsistency; 2. Debug asserts are activated if dedicated flag is on (it's off by default);
<ide><path>latform/platform-impl/src/com/intellij/openapi/editor/impl/FoldRegionsTree.java <ide> import com.intellij.openapi.editor.RangeMarker; <ide> import com.intellij.util.ArrayUtil; <ide> import com.intellij.util.containers.CollectionFactory; <add>import org.jetbrains.annotations.Nullable; <ide> <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <ide> * User: cdr <ide> */ <ide> abstract class FoldRegionsTree { <add> <add> public static final boolean DEBUG = Boolean.getBoolean("idea.editor.debug.folding"); <add> <ide> private FoldRegion[] myCachedVisible; <ide> private FoldRegion[] myCachedTopLevelRegions; <ide> private int[] myCachedEndOffsets; <ide> return true; <ide> } <ide> <add> @Nullable <ide> FoldRegion fetchOutermost(int offset) { <ide> if (!isFoldingEnabledAndUpToDate()) return null; <ide> <ide> start = i + 1; <ide> } <ide> else { <add> // We encountered situation when cached data is inconsistent. It's not clear what produced that, so, the following was done: <add> // 1. Corresponding check was added and cached data is rebuilt in case of inconsistency; <add> // 2. Debug asserts are activated if dedicated flag is on (it's off by default); <add> if (myCachedStartOffsets[i] != myCachedTopLevelRegions[i].getStartOffset()) { <add> if (DEBUG) { <add> assert false : <add> "inconsistent cached fold data detected. Start offsets: " + Arrays.toString(myCachedStartOffsets) <add> + ", end offsets: " + Arrays.toString(myCachedEndOffsets) + ", top regions: " + Arrays.toString(myCachedTopLevelRegions) <add> + ", visible regions: " + Arrays.toString(myCachedVisible); <add> } <add> rebuild(); <add> return fetchOutermost(offset); <add> } <ide> return myCachedTopLevelRegions[i]; <ide> } <ide> } <ide> return myCachedVisible; <ide> } <ide> <add> @Nullable <ide> FoldRegion[] fetchTopLevel() { <ide> if (!isFoldingEnabledAndUpToDate()) return null; <ide> return myCachedTopLevelRegions;
Java
mit
b29e0f84303377d092e59630f16efae6c2bbfc7c
0
gilleain/signatures
package signature.simple; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import junit.framework.Assert; import org.junit.Test; import signature.SymmetryClass; public class CanonicalLabellingTest { public int[] getLabels(SimpleGraph graph) { SimpleGraphSignature signature = new SimpleGraphSignature(graph); return signature.getCanonicalLabels(); } public void permuteTest(SimpleGraph graph) { System.out.println(Arrays.toString(getLabels(graph)) + " " + graph); SimpleGraphPermutor permutor = new SimpleGraphPermutor(graph); Set<String> relabelledStrings = new HashSet<String>(); // permute, and relabel while (permutor.hasNext()) { SimpleGraph permutation = permutor.next(); int[] labels = getLabels(permutation); SimpleGraph relabelled = new SimpleGraph(permutation, labels); boolean isIdentity = isIdentity(labels); System.out.println( Arrays.toString(labels) + " " + permutation + " " + relabelled + " " + isIdentity); relabelledStrings.add(relabelled.toString()); } Assert.assertEquals(1, relabelledStrings.size()); // list the number of unique strings Iterator<String> values = relabelledStrings.iterator(); for (int i = 0; i < relabelledStrings.size(); i++) { System.out.println(i + " " + values.next()); } } public boolean isIdentity(int[] permutation) { if (permutation.length < 1) return true; int prev = permutation[0]; for (int i = 1; i < permutation.length; i++) { if (permutation[i] < prev) return false; prev = permutation[i]; } return true; } @Test public void testSimpleGraphLabelling() { String graphString = "0:1,1:2"; SimpleGraph graph = new SimpleGraph(graphString); SimpleGraphSignature signature = new SimpleGraphSignature(graph); int[] labels = signature.getCanonicalLabels(); Assert.assertTrue(isIdentity(labels)); } @Test public void fourCycleTest() { permuteTest(new SimpleGraph("0:1,0:3,1:2,2:3")); } @Test public void fiveCycleTest() { permuteTest(new SimpleGraph("0:1,0:4,1:2,2:3,3:4")); } @Test public void threeFourFusedCycle() { permuteTest(new SimpleGraph("0:1,0:2,1:2,1:3,2:4,3:4")); } @Test public void threeThreeFusedCycle() { permuteTest(new SimpleGraph("0:1,0:2,0:3,1:4,2:4,3:4")); } @Test public void largePermuteTestA() { permuteTest(new SimpleGraph("5:7,6:7,0:6,1:6,2:5,3:5,0:4,1:4,2:4,3:4,0:3,2:3,0:1,1:2")); } @Test public void largePermuteTestB() { permuteTest(new SimpleGraph("5:7,6:7,0:6,2:6,1:5,3:5,0:4,1:4,2:4,3:4,0:3,1:3,0:2,1:2")); } @Test public void tmpOrbitsTest() { SimpleGraph a = new SimpleGraph("5:7,6:7,0:6,1:6,2:5,3:5,0:4,1:4,2:4,3:4,0:3,2:3,0:1,1:2"); // SimpleGraph b = new SimpleGraph("5:7,6:7,0:6,2:6,1:5,3:5,0:4,1:4,2:4,3:4,0:3,1:3,0:2,1:2"); SimpleGraphSignature sigA = new SimpleGraphSignature(a); for (SymmetryClass cls : sigA.getSymmetryClasses()) { System.out.println(cls); } } @Test public void isomorphicPair() { SimpleGraph a = new SimpleGraph("5:7,6:7,0:6,1:6,2:5,3:5,0:4,1:4,2:4,3:4,0:3,2:3,0:1,1:2"); SimpleGraph b = new SimpleGraph("5:7,6:7,0:6,2:6,1:5,3:5,0:4,1:4,2:4,3:4,0:3,1:3,0:2,1:2"); SimpleGraphSignature sigA = new SimpleGraphSignature(a); SimpleGraphSignature sigB = new SimpleGraphSignature(b); Assert.assertEquals(sigA.toCanonicalString(), sigB.toCanonicalString()); } }
src/test/java/signature/simple/CanonicalLabellingTest.java
package signature.simple; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import junit.framework.Assert; import org.junit.Test; import signature.simple.SimpleGraph; import signature.simple.SimpleGraphPermutor; import signature.simple.SimpleGraphSignature; public class CanonicalLabellingTest { public int[] getLabels(SimpleGraph graph) { SimpleGraphSignature signature = new SimpleGraphSignature(graph); return signature.getCanonicalLabels(); } public void permuteTest(SimpleGraph graph) { System.out.println(Arrays.toString(getLabels(graph)) + " " + graph); SimpleGraphPermutor permutor = new SimpleGraphPermutor(graph); Set<String> relabelledStrings = new HashSet<String>(); // permute, and relabel while (permutor.hasNext()) { SimpleGraph permutation = permutor.next(); int[] labels = getLabels(permutation); SimpleGraph relabelled = new SimpleGraph(permutation, labels); boolean isIdentity = isIdentity(labels); System.out.println( Arrays.toString(labels) + " " + permutation + " " + relabelled + " " + isIdentity); relabelledStrings.add(relabelled.toString()); } Assert.assertEquals(1, relabelledStrings.size()); // list the number of unique strings Iterator<String> values = relabelledStrings.iterator(); for (int i = 0; i < relabelledStrings.size(); i++) { System.out.println(i + " " + values.next()); } } public boolean isIdentity(int[] permutation) { if (permutation.length < 1) return true; int prev = permutation[0]; for (int i = 1; i < permutation.length; i++) { if (permutation[i] < prev) return false; prev = permutation[i]; } return true; } @Test public void testSimpleGraphLabelling() { String graphString = "0:1,1:2"; SimpleGraph graph = new SimpleGraph(graphString); SimpleGraphSignature signature = new SimpleGraphSignature(graph); int[] labels = signature.getCanonicalLabels(); Assert.assertTrue(isIdentity(labels)); } @Test public void fourCycleTest() { permuteTest(new SimpleGraph("0:1,0:3,1:2,2:3")); } @Test public void fiveCycleTest() { permuteTest(new SimpleGraph("0:1,0:4,1:2,2:3,3:4")); } @Test public void threeFourFusedCycle() { permuteTest(new SimpleGraph("0:1,0:2,1:2,1:3,2:4,3:4")); } @Test public void threeThreeFusedCycle() { permuteTest(new SimpleGraph("0:1,0:2,0:3,1:4,2:4,3:4")); } @Test public void isomorphicPair() { // SimpleGraph a = new SimpleGraph("5:7,6:7,0:6,1:6,2:5,3:5,0:4,1:4,2:4,3:4,0:3,1:3,0:2,1:2"); SimpleGraph a = new SimpleGraph("0:2,0:3,0:4,0:6,1:2,1:3,1:4,1:6,2:4,2:5,3:4,3:5,5:7,6:7"); // SimpleGraph b = new SimpleGraph("5:7,6:7,0:6,2:6,1:5,3:5,0:4,1:4,2:4,3:4,0:3,1:3,0:2,1:2"); SimpleGraph b = new SimpleGraph("0:2,0:3,0:4,0:6,1:2,1:3,1:4,1:5,2:4,2:6,3:4,3:5,5:7,6:7"); SimpleGraphSignature sigA = new SimpleGraphSignature(a); SimpleGraphSignature sigB = new SimpleGraphSignature(b); Assert.assertEquals(sigA.toCanonicalString(), sigB.toCanonicalString()); } }
Change test to the actual failing (isomorphic) graphs
src/test/java/signature/simple/CanonicalLabellingTest.java
Change test to the actual failing (isomorphic) graphs
<ide><path>rc/test/java/signature/simple/CanonicalLabellingTest.java <ide> <ide> import org.junit.Test; <ide> <del>import signature.simple.SimpleGraph; <del>import signature.simple.SimpleGraphPermutor; <del>import signature.simple.SimpleGraphSignature; <add>import signature.SymmetryClass; <ide> <ide> public class CanonicalLabellingTest { <ide> <ide> } <ide> <ide> @Test <add> public void largePermuteTestA() { <add> permuteTest(new SimpleGraph("5:7,6:7,0:6,1:6,2:5,3:5,0:4,1:4,2:4,3:4,0:3,2:3,0:1,1:2")); <add> } <add> <add> @Test <add> public void largePermuteTestB() { <add> permuteTest(new SimpleGraph("5:7,6:7,0:6,2:6,1:5,3:5,0:4,1:4,2:4,3:4,0:3,1:3,0:2,1:2")); <add> } <add> <add> @Test <add> public void tmpOrbitsTest() { <add> SimpleGraph a = new SimpleGraph("5:7,6:7,0:6,1:6,2:5,3:5,0:4,1:4,2:4,3:4,0:3,2:3,0:1,1:2"); <add>// SimpleGraph b = new SimpleGraph("5:7,6:7,0:6,2:6,1:5,3:5,0:4,1:4,2:4,3:4,0:3,1:3,0:2,1:2"); <add> SimpleGraphSignature sigA = new SimpleGraphSignature(a); <add> for (SymmetryClass cls : sigA.getSymmetryClasses()) { <add> System.out.println(cls); <add> } <add> } <add> <add> @Test <ide> public void isomorphicPair() { <del>// SimpleGraph a = new SimpleGraph("5:7,6:7,0:6,1:6,2:5,3:5,0:4,1:4,2:4,3:4,0:3,1:3,0:2,1:2"); <del> SimpleGraph a = new SimpleGraph("0:2,0:3,0:4,0:6,1:2,1:3,1:4,1:6,2:4,2:5,3:4,3:5,5:7,6:7"); <del> <del>// SimpleGraph b = new SimpleGraph("5:7,6:7,0:6,2:6,1:5,3:5,0:4,1:4,2:4,3:4,0:3,1:3,0:2,1:2"); <del> SimpleGraph b = new SimpleGraph("0:2,0:3,0:4,0:6,1:2,1:3,1:4,1:5,2:4,2:6,3:4,3:5,5:7,6:7"); <add> SimpleGraph a = new SimpleGraph("5:7,6:7,0:6,1:6,2:5,3:5,0:4,1:4,2:4,3:4,0:3,2:3,0:1,1:2"); <add> SimpleGraph b = new SimpleGraph("5:7,6:7,0:6,2:6,1:5,3:5,0:4,1:4,2:4,3:4,0:3,1:3,0:2,1:2"); <ide> <ide> SimpleGraphSignature sigA = new SimpleGraphSignature(a); <ide> SimpleGraphSignature sigB = new SimpleGraphSignature(b);
Java
apache-2.0
4b571b3f0b9e0cfb1b8281a4f6ba42cd32a64631
0
lgrill-pentaho/pentaho-kettle,lgrill-pentaho/pentaho-kettle,HiromuHota/pentaho-kettle,ddiroma/pentaho-kettle,e-cuellar/pentaho-kettle,HiromuHota/pentaho-kettle,emartin-pentaho/pentaho-kettle,rmansoor/pentaho-kettle,dkincade/pentaho-kettle,HiromuHota/pentaho-kettle,marcoslarsen/pentaho-kettle,mkambol/pentaho-kettle,pminutillo/pentaho-kettle,DFieldFL/pentaho-kettle,roboguy/pentaho-kettle,tmcsantos/pentaho-kettle,mkambol/pentaho-kettle,e-cuellar/pentaho-kettle,tkafalas/pentaho-kettle,bmorrise/pentaho-kettle,mkambol/pentaho-kettle,tkafalas/pentaho-kettle,graimundo/pentaho-kettle,rmansoor/pentaho-kettle,DFieldFL/pentaho-kettle,mdamour1976/pentaho-kettle,mbatchelor/pentaho-kettle,pminutillo/pentaho-kettle,dkincade/pentaho-kettle,wseyler/pentaho-kettle,pentaho/pentaho-kettle,roboguy/pentaho-kettle,skofra0/pentaho-kettle,flbrino/pentaho-kettle,marcoslarsen/pentaho-kettle,graimundo/pentaho-kettle,kurtwalker/pentaho-kettle,e-cuellar/pentaho-kettle,tmcsantos/pentaho-kettle,kurtwalker/pentaho-kettle,mdamour1976/pentaho-kettle,ccaspanello/pentaho-kettle,lgrill-pentaho/pentaho-kettle,tkafalas/pentaho-kettle,bmorrise/pentaho-kettle,dkincade/pentaho-kettle,ddiroma/pentaho-kettle,skofra0/pentaho-kettle,pedrofvteixeira/pentaho-kettle,pentaho/pentaho-kettle,pentaho/pentaho-kettle,kurtwalker/pentaho-kettle,mdamour1976/pentaho-kettle,flbrino/pentaho-kettle,matthewtckr/pentaho-kettle,ddiroma/pentaho-kettle,wseyler/pentaho-kettle,ccaspanello/pentaho-kettle,skofra0/pentaho-kettle,ccaspanello/pentaho-kettle,roboguy/pentaho-kettle,rmansoor/pentaho-kettle,matthewtckr/pentaho-kettle,HiromuHota/pentaho-kettle,tmcsantos/pentaho-kettle,matthewtckr/pentaho-kettle,pedrofvteixeira/pentaho-kettle,skofra0/pentaho-kettle,mkambol/pentaho-kettle,kurtwalker/pentaho-kettle,flbrino/pentaho-kettle,DFieldFL/pentaho-kettle,pentaho/pentaho-kettle,flbrino/pentaho-kettle,mbatchelor/pentaho-kettle,lgrill-pentaho/pentaho-kettle,matthewtckr/pentaho-kettle,e-cuellar/pentaho-kettle,emartin-pentaho/pentaho-kettle,roboguy/pentaho-kettle,pminutillo/pentaho-kettle,pminutillo/pentaho-kettle,wseyler/pentaho-kettle,pedrofvteixeira/pentaho-kettle,emartin-pentaho/pentaho-kettle,marcoslarsen/pentaho-kettle,wseyler/pentaho-kettle,mbatchelor/pentaho-kettle,graimundo/pentaho-kettle,pedrofvteixeira/pentaho-kettle,rmansoor/pentaho-kettle,bmorrise/pentaho-kettle,graimundo/pentaho-kettle,marcoslarsen/pentaho-kettle,emartin-pentaho/pentaho-kettle,DFieldFL/pentaho-kettle,ccaspanello/pentaho-kettle,mbatchelor/pentaho-kettle,bmorrise/pentaho-kettle,ddiroma/pentaho-kettle,tmcsantos/pentaho-kettle,mdamour1976/pentaho-kettle,tkafalas/pentaho-kettle,dkincade/pentaho-kettle
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2018 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * 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.pentaho.di.ui.trans.steps.xmloutput; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.core.util.Utils; import org.pentaho.di.core.Props; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDialogInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.steps.xmloutput.XMLField; import org.pentaho.di.trans.steps.xmloutput.XMLField.ContentType; import org.pentaho.di.trans.steps.xmloutput.XMLOutputMeta; import org.pentaho.di.ui.core.dialog.EnterSelectionDialog; import org.pentaho.di.ui.core.dialog.ErrorDialog; import org.pentaho.di.ui.core.widget.ColumnInfo; import org.pentaho.di.ui.core.widget.TableView; import org.pentaho.di.ui.core.widget.TextVar; import org.pentaho.di.ui.trans.step.BaseStepDialog; import org.pentaho.di.ui.trans.step.TableItemInsertListener; public class XMLOutputDialog extends BaseStepDialog implements StepDialogInterface { private static Class<?> PKG = XMLOutputMeta.class; // for i18n purposes, needed by Translator2!! private CTabFolder wTabFolder; private FormData fdTabFolder; private CTabItem wFileTab, wContentTab, wFieldsTab; private FormData fdFileComp, fdContentComp, fdFieldsComp; private Label wlFilename; private Button wbFilename; private TextVar wFilename; private FormData fdlFilename, fdbFilename, fdFilename; private Label wlExtension; private TextVar wExtension; private FormData fdlExtension, fdExtension; private Label wlServletOutput; private Button wServletOutput; private FormData fdlServletOutput, fdServletOutput; private Label wlAddStepnr; private Button wAddStepnr; private FormData fdlAddStepnr, fdAddStepnr; private Label wlAddDate; private Button wAddDate; private FormData fdlAddDate, fdAddDate; private Label wlAddTime; private Button wAddTime; private FormData fdlAddTime, fdAddTime; private Button wbShowFiles; private FormData fdbShowFiles; private Label wlZipped; private Button wZipped; private FormData fdlZipped, fdZipped; private Label wlOmitNullValues; private Button wOmitNullValues; private FormData fdlOmitNullValues, fdOmitNullValues; private Label wlEncoding; private CCombo wEncoding; private FormData fdlEncoding, fdEncoding; private Label wlNameSpace; private Text wNameSpace; private FormData fdlNameSpace, fdNameSpace; private Label wlMainElement; private CCombo wMainElement; private FormData fdlMainElement, fdMainElement; private Label wlRepeatElement; private CCombo wRepeatElement; private FormData fdlRepeatElement, fdRepeatElement; private Label wlSplitEvery; private Text wSplitEvery; private FormData fdlSplitEvery, fdSplitEvery; private TableView wFields; private FormData fdFields; private XMLOutputMeta input; private Button wMinWidth; private Listener lsMinWidth; private boolean gotEncodings = false; private Label wlAddToResult; private Button wAddToResult; private FormData fdlAddToResult, fdAddToResult; private Label wlDoNotOpenNewFileInit; private Button wDoNotOpenNewFileInit; private FormData fdlDoNotOpenNewFileInit, fdDoNotOpenNewFileInit; private Label wlSpecifyFormat; private Button wSpecifyFormat; private FormData fdlSpecifyFormat, fdSpecifyFormat; private Label wlDateTimeFormat; private CCombo wDateTimeFormat; private FormData fdlDateTimeFormat, fdDateTimeFormat; private ColumnInfo[] colinf; private Map<String, Integer> inputFields; public XMLOutputDialog( Shell parent, Object in, TransMeta transMeta, String sname ) { super( parent, (BaseStepMeta) in, transMeta, sname ); input = (XMLOutputMeta) in; inputFields = new HashMap<String, Integer>(); } public String open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell( parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN ); props.setLook( shell ); setShellImage( shell, input ); ModifyListener lsMod = new ModifyListener() { public void modifyText( ModifyEvent e ) { input.setChanged(); } }; changed = input.hasChanged(); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout( formLayout ); shell.setText( BaseMessages.getString( PKG, "XMLOutputDialog.DialogTitle" ) ); int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Stepname line wlStepname = new Label( shell, SWT.RIGHT ); wlStepname.setText( BaseMessages.getString( PKG, "System.Label.StepName" ) ); props.setLook( wlStepname ); fdlStepname = new FormData(); fdlStepname.left = new FormAttachment( 0, 0 ); fdlStepname.top = new FormAttachment( 0, margin ); fdlStepname.right = new FormAttachment( middle, -margin ); wlStepname.setLayoutData( fdlStepname ); wStepname = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); wStepname.setText( stepname ); props.setLook( wStepname ); wStepname.addModifyListener( lsMod ); fdStepname = new FormData(); fdStepname.left = new FormAttachment( middle, 0 ); fdStepname.top = new FormAttachment( 0, margin ); fdStepname.right = new FormAttachment( 100, 0 ); wStepname.setLayoutData( fdStepname ); wTabFolder = new CTabFolder( shell, SWT.BORDER ); props.setLook( wTabFolder, Props.WIDGET_STYLE_TAB ); // //////////////////////// // START OF FILE TAB/// // / wFileTab = new CTabItem( wTabFolder, SWT.NONE ); wFileTab.setText( BaseMessages.getString( PKG, "XMLOutputDialog.FileTab.Tab" ) ); Composite wFileComp = new Composite( wTabFolder, SWT.NONE ); props.setLook( wFileComp ); FormLayout fileLayout = new FormLayout(); fileLayout.marginWidth = 3; fileLayout.marginHeight = 3; wFileComp.setLayout( fileLayout ); // Filename line wlFilename = new Label( wFileComp, SWT.RIGHT ); wlFilename.setText( BaseMessages.getString( PKG, "XMLOutputDialog.Filename.Label" ) ); props.setLook( wlFilename ); fdlFilename = new FormData(); fdlFilename.left = new FormAttachment( 0, 0 ); fdlFilename.top = new FormAttachment( 0, margin ); fdlFilename.right = new FormAttachment( middle, -margin ); wlFilename.setLayoutData( fdlFilename ); wbFilename = new Button( wFileComp, SWT.PUSH | SWT.CENTER ); props.setLook( wbFilename ); wbFilename.setText( BaseMessages.getString( PKG, "XMLOutputDialog.Browse.Button" ) ); fdbFilename = new FormData(); fdbFilename.right = new FormAttachment( 100, 0 ); fdbFilename.top = new FormAttachment( 0, 0 ); wbFilename.setLayoutData( fdbFilename ); wFilename = new TextVar( transMeta, wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wFilename ); wFilename.addModifyListener( lsMod ); fdFilename = new FormData(); fdFilename.left = new FormAttachment( middle, 0 ); fdFilename.top = new FormAttachment( 0, margin ); fdFilename.right = new FormAttachment( wbFilename, -margin ); wFilename.setLayoutData( fdFilename ); // Open new File at Init wlDoNotOpenNewFileInit = new Label( wFileComp, SWT.RIGHT ); wlDoNotOpenNewFileInit.setText( BaseMessages.getString( PKG, "XMLOutputDialog.DoNotOpenNewFileInit.Label" ) ); props.setLook( wlDoNotOpenNewFileInit ); fdlDoNotOpenNewFileInit = new FormData(); fdlDoNotOpenNewFileInit.left = new FormAttachment( 0, 0 ); fdlDoNotOpenNewFileInit.top = new FormAttachment( wFilename, margin ); fdlDoNotOpenNewFileInit.right = new FormAttachment( middle, -margin ); wlDoNotOpenNewFileInit.setLayoutData( fdlDoNotOpenNewFileInit ); wDoNotOpenNewFileInit = new Button( wFileComp, SWT.CHECK ); wDoNotOpenNewFileInit .setToolTipText( BaseMessages.getString( PKG, "XMLOutputDialog.DoNotOpenNewFileInit.Tooltip" ) ); props.setLook( wDoNotOpenNewFileInit ); fdDoNotOpenNewFileInit = new FormData(); fdDoNotOpenNewFileInit.left = new FormAttachment( middle, 0 ); fdDoNotOpenNewFileInit.top = new FormAttachment( wFilename, margin ); fdDoNotOpenNewFileInit.right = new FormAttachment( 100, 0 ); wDoNotOpenNewFileInit.setLayoutData( fdDoNotOpenNewFileInit ); wDoNotOpenNewFileInit.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { input.setChanged(); } } ); // Run this as a command instead? wlServletOutput = new Label( wFileComp, SWT.RIGHT ); wlServletOutput.setText( BaseMessages.getString( PKG, "XMLOutputDialog.ServletOutput.Label" ) ); props.setLook( wlServletOutput ); fdlServletOutput = new FormData(); fdlServletOutput.left = new FormAttachment( 0, 0 ); fdlServletOutput.top = new FormAttachment( wDoNotOpenNewFileInit, margin ); fdlServletOutput.right = new FormAttachment( middle, -margin ); wlServletOutput.setLayoutData( fdlServletOutput ); wServletOutput = new Button( wFileComp, SWT.CHECK ); wServletOutput.setToolTipText( BaseMessages.getString( PKG, "XMLOutputDialog.ServletOutput.Tooltip" ) ); props.setLook( wServletOutput ); fdServletOutput = new FormData(); fdServletOutput.left = new FormAttachment( middle, 0 ); fdServletOutput.top = new FormAttachment( wDoNotOpenNewFileInit, margin ); fdServletOutput.right = new FormAttachment( 100, 0 ); wServletOutput.setLayoutData( fdServletOutput ); wServletOutput.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { input.setChanged(); setFlagsServletOption(); } } ); // Extension line wlExtension = new Label( wFileComp, SWT.RIGHT ); wlExtension.setText( BaseMessages.getString( PKG, "XMLOutputDialog.Extension.Label" ) ); props.setLook( wlExtension ); fdlExtension = new FormData(); fdlExtension.left = new FormAttachment( 0, 0 ); fdlExtension.top = new FormAttachment( wServletOutput, margin ); fdlExtension.right = new FormAttachment( middle, -margin ); wlExtension.setLayoutData( fdlExtension ); wExtension = new TextVar( transMeta, wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); wExtension.setText( "" ); props.setLook( wExtension ); wExtension.addModifyListener( lsMod ); fdExtension = new FormData(); fdExtension.left = new FormAttachment( middle, 0 ); fdExtension.top = new FormAttachment( wServletOutput, margin ); fdExtension.right = new FormAttachment( 100, 0 ); wExtension.setLayoutData( fdExtension ); // Create multi-part file? wlAddStepnr = new Label( wFileComp, SWT.RIGHT ); wlAddStepnr.setText( BaseMessages.getString( PKG, "XMLOutputDialog.AddStepNr.Label" ) ); props.setLook( wlAddStepnr ); fdlAddStepnr = new FormData(); fdlAddStepnr.left = new FormAttachment( 0, 0 ); fdlAddStepnr.top = new FormAttachment( wExtension, margin ); fdlAddStepnr.right = new FormAttachment( middle, -margin ); wlAddStepnr.setLayoutData( fdlAddStepnr ); wAddStepnr = new Button( wFileComp, SWT.CHECK ); props.setLook( wAddStepnr ); fdAddStepnr = new FormData(); fdAddStepnr.left = new FormAttachment( middle, 0 ); fdAddStepnr.top = new FormAttachment( wExtension, margin ); fdAddStepnr.right = new FormAttachment( 100, 0 ); wAddStepnr.setLayoutData( fdAddStepnr ); wAddStepnr.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { input.setChanged(); } } ); // Create multi-part file? wlAddDate = new Label( wFileComp, SWT.RIGHT ); wlAddDate.setText( BaseMessages.getString( PKG, "XMLOutputDialog.AddDate.Label" ) ); props.setLook( wlAddDate ); fdlAddDate = new FormData(); fdlAddDate.left = new FormAttachment( 0, 0 ); fdlAddDate.top = new FormAttachment( wAddStepnr, margin ); fdlAddDate.right = new FormAttachment( middle, -margin ); wlAddDate.setLayoutData( fdlAddDate ); wAddDate = new Button( wFileComp, SWT.CHECK ); props.setLook( wAddDate ); fdAddDate = new FormData(); fdAddDate.left = new FormAttachment( middle, 0 ); fdAddDate.top = new FormAttachment( wAddStepnr, margin ); fdAddDate.right = new FormAttachment( 100, 0 ); wAddDate.setLayoutData( fdAddDate ); wAddDate.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { input.setChanged(); } } ); // Create multi-part file? wlAddTime = new Label( wFileComp, SWT.RIGHT ); wlAddTime.setText( BaseMessages.getString( PKG, "XMLOutputDialog.AddTime.Label" ) ); props.setLook( wlAddTime ); fdlAddTime = new FormData(); fdlAddTime.left = new FormAttachment( 0, 0 ); fdlAddTime.top = new FormAttachment( wAddDate, margin ); fdlAddTime.right = new FormAttachment( middle, -margin ); wlAddTime.setLayoutData( fdlAddTime ); wAddTime = new Button( wFileComp, SWT.CHECK ); props.setLook( wAddTime ); fdAddTime = new FormData(); fdAddTime.left = new FormAttachment( middle, 0 ); fdAddTime.top = new FormAttachment( wAddDate, margin ); fdAddTime.right = new FormAttachment( 100, 0 ); wAddTime.setLayoutData( fdAddTime ); wAddTime.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { input.setChanged(); } } ); // Specify date time format? wlSpecifyFormat = new Label( wFileComp, SWT.RIGHT ); wlSpecifyFormat.setText( BaseMessages.getString( PKG, "XMLOutputDialog.SpecifyFormat.Label" ) ); props.setLook( wlSpecifyFormat ); fdlSpecifyFormat = new FormData(); fdlSpecifyFormat.left = new FormAttachment( 0, 0 ); fdlSpecifyFormat.top = new FormAttachment( wAddTime, margin ); fdlSpecifyFormat.right = new FormAttachment( middle, -margin ); wlSpecifyFormat.setLayoutData( fdlSpecifyFormat ); wSpecifyFormat = new Button( wFileComp, SWT.CHECK ); props.setLook( wSpecifyFormat ); wSpecifyFormat.setToolTipText( BaseMessages.getString( PKG, "XMLOutputDialog.SpecifyFormat.Tooltip" ) ); fdSpecifyFormat = new FormData(); fdSpecifyFormat.left = new FormAttachment( middle, 0 ); fdSpecifyFormat.top = new FormAttachment( wAddTime, margin ); fdSpecifyFormat.right = new FormAttachment( 100, 0 ); wSpecifyFormat.setLayoutData( fdSpecifyFormat ); wSpecifyFormat.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { input.setChanged(); setDateTimeFormat(); } } ); // Prepare a list of possible DateTimeFormats... String[] dats = Const.getDateFormats(); // DateTimeFormat wlDateTimeFormat = new Label( wFileComp, SWT.RIGHT ); wlDateTimeFormat.setText( BaseMessages.getString( PKG, "XMLOutputDialog.DateTimeFormat.Label" ) ); props.setLook( wlDateTimeFormat ); fdlDateTimeFormat = new FormData(); fdlDateTimeFormat.left = new FormAttachment( 0, 0 ); fdlDateTimeFormat.top = new FormAttachment( wSpecifyFormat, margin ); fdlDateTimeFormat.right = new FormAttachment( middle, -margin ); wlDateTimeFormat.setLayoutData( fdlDateTimeFormat ); wDateTimeFormat = new CCombo( wFileComp, SWT.BORDER | SWT.READ_ONLY ); wDateTimeFormat.setEditable( true ); props.setLook( wDateTimeFormat ); wDateTimeFormat.addModifyListener( lsMod ); fdDateTimeFormat = new FormData(); fdDateTimeFormat.left = new FormAttachment( middle, 0 ); fdDateTimeFormat.top = new FormAttachment( wSpecifyFormat, margin ); fdDateTimeFormat.right = new FormAttachment( 100, 0 ); wDateTimeFormat.setLayoutData( fdDateTimeFormat ); for ( int x = 0; x < dats.length; x++ ) { wDateTimeFormat.add( dats[x] ); } wbShowFiles = new Button( wFileComp, SWT.PUSH | SWT.CENTER ); props.setLook( wbShowFiles ); wbShowFiles.setText( BaseMessages.getString( PKG, "XMLOutputDialog.ShowFiles.Button" ) ); fdbShowFiles = new FormData(); fdbShowFiles.left = new FormAttachment( middle, 0 ); fdbShowFiles.top = new FormAttachment( wDateTimeFormat, margin * 2 ); wbShowFiles.setLayoutData( fdbShowFiles ); wbShowFiles.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { XMLOutputMeta tfoi = new XMLOutputMeta(); getInfo( tfoi ); String[] files = tfoi.getFiles( transMeta ); if ( files != null && files.length > 0 ) { EnterSelectionDialog esd = new EnterSelectionDialog( shell, files, BaseMessages.getString( PKG, "XMLOutputDialog.OutputFiles.DialogTitle" ), BaseMessages.getString( PKG, "XMLOutputDialog.OutputFiles.DialogMessage" ) ); esd.setViewOnly(); esd.open(); } else { MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR ); mb.setMessage( BaseMessages.getString( PKG, "XMLOutputDialog.NoFilesFound.DialogMessage" ) ); mb.setText( BaseMessages.getString( PKG, "System.Dialog.Error.Title" ) ); mb.open(); } } } ); // Add File to the result files name wlAddToResult = new Label( wFileComp, SWT.RIGHT ); wlAddToResult.setText( BaseMessages.getString( PKG, "XMLOutputDialog.AddFileToResult.Label" ) ); props.setLook( wlAddToResult ); fdlAddToResult = new FormData(); fdlAddToResult.left = new FormAttachment( 0, 0 ); fdlAddToResult.top = new FormAttachment( wbShowFiles, 2 * margin ); fdlAddToResult.right = new FormAttachment( middle, -margin ); wlAddToResult.setLayoutData( fdlAddToResult ); wAddToResult = new Button( wFileComp, SWT.CHECK ); wAddToResult.setToolTipText( BaseMessages.getString( PKG, "XMLOutputDialog.AddFileToResult.Tooltip" ) ); props.setLook( wAddToResult ); fdAddToResult = new FormData(); fdAddToResult.left = new FormAttachment( middle, 0 ); fdAddToResult.top = new FormAttachment( wbShowFiles, 2 * margin ); fdAddToResult.right = new FormAttachment( 100, 0 ); wAddToResult.setLayoutData( fdAddToResult ); SelectionAdapter lsSelR = new SelectionAdapter() { public void widgetSelected( SelectionEvent arg0 ) { input.setChanged(); } }; wAddToResult.addSelectionListener( lsSelR ); fdFileComp = new FormData(); fdFileComp.left = new FormAttachment( 0, 0 ); fdFileComp.top = new FormAttachment( 0, 0 ); fdFileComp.right = new FormAttachment( 100, 0 ); fdFileComp.bottom = new FormAttachment( 100, 0 ); wFileComp.setLayoutData( fdFileComp ); wFileComp.layout(); wFileTab.setControl( wFileComp ); // /////////////////////////////////////////////////////////// // / END OF FILE TAB // /////////////////////////////////////////////////////////// // //////////////////////// // START OF CONTENT TAB/// // / wContentTab = new CTabItem( wTabFolder, SWT.NONE ); wContentTab.setText( BaseMessages.getString( PKG, "XMLOutputDialog.ContentTab.TabTitle" ) ); FormLayout contentLayout = new FormLayout(); contentLayout.marginWidth = 3; contentLayout.marginHeight = 3; Composite wContentComp = new Composite( wTabFolder, SWT.NONE ); props.setLook( wContentComp ); wContentComp.setLayout( contentLayout ); wlZipped = new Label( wContentComp, SWT.RIGHT ); wlZipped.setText( BaseMessages.getString( PKG, "XMLOutputDialog.Zipped.Label" ) ); props.setLook( wlZipped ); fdlZipped = new FormData(); fdlZipped.left = new FormAttachment( 0, 0 ); fdlZipped.top = new FormAttachment( 0, 0 ); fdlZipped.right = new FormAttachment( middle, -margin ); wlZipped.setLayoutData( fdlZipped ); wZipped = new Button( wContentComp, SWT.CHECK ); props.setLook( wZipped ); fdZipped = new FormData(); fdZipped.left = new FormAttachment( middle, 0 ); fdZipped.top = new FormAttachment( 0, 0 ); fdZipped.right = new FormAttachment( 100, 0 ); wZipped.setLayoutData( fdZipped ); wZipped.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { input.setChanged(); } } ); wlEncoding = new Label( wContentComp, SWT.RIGHT ); wlEncoding.setText( BaseMessages.getString( PKG, "XMLOutputDialog.Encoding.Label" ) ); props.setLook( wlEncoding ); fdlEncoding = new FormData(); fdlEncoding.left = new FormAttachment( 0, 0 ); fdlEncoding.top = new FormAttachment( wZipped, margin ); fdlEncoding.right = new FormAttachment( middle, -margin ); wlEncoding.setLayoutData( fdlEncoding ); wEncoding = new CCombo( wContentComp, SWT.BORDER | SWT.READ_ONLY ); wEncoding.setEditable( true ); props.setLook( wEncoding ); wEncoding.addModifyListener( lsMod ); fdEncoding = new FormData(); fdEncoding.left = new FormAttachment( middle, 0 ); fdEncoding.top = new FormAttachment( wZipped, margin ); fdEncoding.right = new FormAttachment( 100, 0 ); wEncoding.setLayoutData( fdEncoding ); wEncoding.addFocusListener( new FocusListener() { public void focusLost( org.eclipse.swt.events.FocusEvent e ) { } public void focusGained( org.eclipse.swt.events.FocusEvent e ) { Cursor busy = new Cursor( shell.getDisplay(), SWT.CURSOR_WAIT ); shell.setCursor( busy ); setEncodings(); shell.setCursor( null ); busy.dispose(); } } ); wlNameSpace = new Label( wContentComp, SWT.RIGHT ); wlNameSpace.setText( BaseMessages.getString( PKG, "XMLOutputDialog.NameSpace.Label" ) ); props.setLook( wlNameSpace ); fdlNameSpace = new FormData(); fdlNameSpace.left = new FormAttachment( 0, 0 ); fdlNameSpace.top = new FormAttachment( wEncoding, margin ); fdlNameSpace.right = new FormAttachment( middle, -margin ); wlNameSpace.setLayoutData( fdlNameSpace ); wNameSpace = new Text( wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wNameSpace ); wNameSpace.addModifyListener( lsMod ); fdNameSpace = new FormData(); fdNameSpace.left = new FormAttachment( middle, 0 ); fdNameSpace.top = new FormAttachment( wEncoding, margin ); fdNameSpace.right = new FormAttachment( 100, 0 ); wNameSpace.setLayoutData( fdNameSpace ); wlMainElement = new Label( wContentComp, SWT.RIGHT ); wlMainElement.setText( BaseMessages.getString( PKG, "XMLOutputDialog.MainElement.Label" ) ); props.setLook( wlMainElement ); fdlMainElement = new FormData(); fdlMainElement.left = new FormAttachment( 0, 0 ); fdlMainElement.top = new FormAttachment( wNameSpace, margin ); fdlMainElement.right = new FormAttachment( middle, -margin ); wlMainElement.setLayoutData( fdlMainElement ); wMainElement = new CCombo( wContentComp, SWT.BORDER | SWT.READ_ONLY ); wMainElement.setEditable( true ); props.setLook( wMainElement ); wMainElement.addModifyListener( lsMod ); fdMainElement = new FormData(); fdMainElement.left = new FormAttachment( middle, 0 ); fdMainElement.top = new FormAttachment( wNameSpace, margin ); fdMainElement.right = new FormAttachment( 100, 0 ); wMainElement.setLayoutData( fdMainElement ); wlRepeatElement = new Label( wContentComp, SWT.RIGHT ); wlRepeatElement.setText( BaseMessages.getString( PKG, "XMLOutputDialog.RepeatElement.Label" ) ); props.setLook( wlRepeatElement ); fdlRepeatElement = new FormData(); fdlRepeatElement.left = new FormAttachment( 0, 0 ); fdlRepeatElement.top = new FormAttachment( wMainElement, margin ); fdlRepeatElement.right = new FormAttachment( middle, -margin ); wlRepeatElement.setLayoutData( fdlRepeatElement ); wRepeatElement = new CCombo( wContentComp, SWT.BORDER | SWT.READ_ONLY ); wRepeatElement.setEditable( true ); props.setLook( wRepeatElement ); wRepeatElement.addModifyListener( lsMod ); fdRepeatElement = new FormData(); fdRepeatElement.left = new FormAttachment( middle, 0 ); fdRepeatElement.top = new FormAttachment( wMainElement, margin ); fdRepeatElement.right = new FormAttachment( 100, 0 ); wRepeatElement.setLayoutData( fdRepeatElement ); wlSplitEvery = new Label( wContentComp, SWT.RIGHT ); wlSplitEvery.setText( BaseMessages.getString( PKG, "XMLOutputDialog.SplitEvery.Label" ) ); props.setLook( wlSplitEvery ); fdlSplitEvery = new FormData(); fdlSplitEvery.left = new FormAttachment( 0, 0 ); fdlSplitEvery.top = new FormAttachment( wRepeatElement, margin ); fdlSplitEvery.right = new FormAttachment( middle, -margin ); wlSplitEvery.setLayoutData( fdlSplitEvery ); wSplitEvery = new Text( wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wSplitEvery ); wSplitEvery.addModifyListener( lsMod ); fdSplitEvery = new FormData(); fdSplitEvery.left = new FormAttachment( middle, 0 ); fdSplitEvery.top = new FormAttachment( wRepeatElement, margin ); fdSplitEvery.right = new FormAttachment( 100, 0 ); wSplitEvery.setLayoutData( fdSplitEvery ); wlOmitNullValues = new Label( wContentComp, SWT.RIGHT ); wlOmitNullValues.setText( BaseMessages.getString( PKG, "XMLOutputDialog.OmitNullValues.Label" ) ); props.setLook( wlOmitNullValues ); fdlOmitNullValues = new FormData(); fdlOmitNullValues.left = new FormAttachment( 0, 0 ); fdlOmitNullValues.top = new FormAttachment( wSplitEvery, margin ); fdlOmitNullValues.right = new FormAttachment( middle, -margin ); wlOmitNullValues.setLayoutData( fdlOmitNullValues ); wOmitNullValues = new Button( wContentComp, SWT.CHECK ); props.setLook( wOmitNullValues ); fdOmitNullValues = new FormData(); fdOmitNullValues.left = new FormAttachment( middle, 0 ); fdOmitNullValues.top = new FormAttachment( wSplitEvery, margin ); fdOmitNullValues.right = new FormAttachment( 100, 0 ); wOmitNullValues.setLayoutData( fdOmitNullValues ); wOmitNullValues.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { input.setChanged(); } } ); fdContentComp = new FormData(); fdContentComp.left = new FormAttachment( 0, 0 ); fdContentComp.top = new FormAttachment( 0, 0 ); fdContentComp.right = new FormAttachment( 100, 0 ); fdContentComp.bottom = new FormAttachment( 100, 0 ); wContentComp.setLayoutData( fdContentComp ); wContentComp.layout(); wContentTab.setControl( wContentComp ); // /////////////////////////////////////////////////////////// // / END OF CONTENT TAB // /////////////////////////////////////////////////////////// // Fields tab... // wFieldsTab = new CTabItem( wTabFolder, SWT.NONE ); wFieldsTab.setText( BaseMessages.getString( PKG, "XMLOutputDialog.FieldsTab.TabTitle" ) ); FormLayout fieldsLayout = new FormLayout(); fieldsLayout.marginWidth = Const.FORM_MARGIN; fieldsLayout.marginHeight = Const.FORM_MARGIN; Composite wFieldsComp = new Composite( wTabFolder, SWT.NONE ); wFieldsComp.setLayout( fieldsLayout ); props.setLook( wFieldsComp ); wGet = new Button( wFieldsComp, SWT.PUSH ); wGet.setText( BaseMessages.getString( PKG, "XMLOutputDialog.Get.Button" ) ); wGet.setToolTipText( BaseMessages.getString( PKG, "XMLOutputDialog.Get.Tooltip" ) ); wMinWidth = new Button( wFieldsComp, SWT.PUSH ); wMinWidth.setText( BaseMessages.getString( PKG, "XMLOutputDialog.MinWidth.Label" ) ); wMinWidth.setToolTipText( BaseMessages.getString( PKG, "XMLOutputDialog.MinWidth.Tooltip" ) ); setButtonPositions( new Button[] { wGet, wMinWidth }, margin, null ); final int FieldsRows = input.getOutputFields().length; // Prepare a list of possible formats... String[] nums = Const.getNumberFormats(); int totsize = dats.length + nums.length; String[] formats = new String[totsize]; for ( int x = 0; x < dats.length; x++ ) { formats[x] = dats[x]; } for ( int x = 0; x < nums.length; x++ ) { formats[dats.length + x] = nums[x]; } colinf = new ColumnInfo[] { new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.Fieldname.Column" ), ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] { "" }, false ), new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.ElementName.Column" ), ColumnInfo.COLUMN_TYPE_TEXT, false ), new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.ContentType.Column" ), ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] { "Element", "Attribute", }, false ), new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.Type.Column" ), ColumnInfo.COLUMN_TYPE_CCOMBO, ValueMeta.getTypes() ), new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.Format.Column" ), ColumnInfo.COLUMN_TYPE_CCOMBO, formats ), new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.Length.Column" ), ColumnInfo.COLUMN_TYPE_TEXT, false ), new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.Precision.Column" ), ColumnInfo.COLUMN_TYPE_TEXT, false ), new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.Currency.Column" ), ColumnInfo.COLUMN_TYPE_TEXT, false ), new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.Decimal.Column" ), ColumnInfo.COLUMN_TYPE_TEXT, false ), new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.Group.Column" ), ColumnInfo.COLUMN_TYPE_TEXT, false ), new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.Null.Column" ), ColumnInfo.COLUMN_TYPE_TEXT, false ) }; wFields = new TableView( transMeta, wFieldsComp, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, colinf, FieldsRows, lsMod, props ); fdFields = new FormData(); fdFields.left = new FormAttachment( 0, 0 ); fdFields.top = new FormAttachment( 0, 0 ); fdFields.right = new FormAttachment( 100, 0 ); fdFields.bottom = new FormAttachment( wGet, -margin ); wFields.setLayoutData( fdFields ); // // Search the fields in the background final Runnable runnable = new Runnable() { public void run() { StepMeta stepMeta = transMeta.findStep( stepname ); if ( stepMeta != null ) { try { RowMetaInterface row = transMeta.getPrevStepFields( stepMeta ); // Remember these fields... for ( int i = 0; i < row.size(); i++ ) { inputFields.put( row.getValueMeta( i ).getName(), Integer.valueOf( i ) ); } setComboBoxes(); } catch ( KettleException e ) { logError( BaseMessages.getString( PKG, "System.Dialog.GetFieldsFailed.Message" ) ); } } } }; new Thread( runnable ).start(); fdFieldsComp = new FormData(); fdFieldsComp.left = new FormAttachment( 0, 0 ); fdFieldsComp.top = new FormAttachment( 0, 0 ); fdFieldsComp.right = new FormAttachment( 100, 0 ); fdFieldsComp.bottom = new FormAttachment( 100, 0 ); wFieldsComp.setLayoutData( fdFieldsComp ); wFieldsComp.layout(); wFieldsTab.setControl( wFieldsComp ); fdTabFolder = new FormData(); fdTabFolder.left = new FormAttachment( 0, 0 ); fdTabFolder.top = new FormAttachment( wStepname, margin ); fdTabFolder.right = new FormAttachment( 100, 0 ); fdTabFolder.bottom = new FormAttachment( 100, -50 ); wTabFolder.setLayoutData( fdTabFolder ); wOK = new Button( shell, SWT.PUSH ); wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) ); wCancel = new Button( shell, SWT.PUSH ); wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) ); setButtonPositions( new Button[] { wOK, wCancel }, margin, wTabFolder ); // Add listeners lsOK = new Listener() { public void handleEvent( Event e ) { ok(); } }; lsGet = new Listener() { public void handleEvent( Event e ) { get(); } }; lsMinWidth = new Listener() { public void handleEvent( Event e ) { setMinimalWidth(); } }; lsCancel = new Listener() { public void handleEvent( Event e ) { cancel(); } }; wOK.addListener( SWT.Selection, lsOK ); wGet.addListener( SWT.Selection, lsGet ); wMinWidth.addListener( SWT.Selection, lsMinWidth ); wCancel.addListener( SWT.Selection, lsCancel ); lsDef = new SelectionAdapter() { public void widgetDefaultSelected( SelectionEvent e ) { ok(); } }; wStepname.addSelectionListener( lsDef ); wFilename.addSelectionListener( lsDef ); // Whenever something changes, set the tooltip to the expanded version: wFilename.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { wFilename.setToolTipText( transMeta.environmentSubstitute( wFilename.getText() ) ); } } ); wbFilename.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { FileDialog dialog = new FileDialog( shell, SWT.SAVE ); dialog.setFilterExtensions( new String[] { "*.xml", "*.txt", "*.csv", "*" } ); if ( wFilename.getText() != null ) { dialog.setFileName( transMeta.environmentSubstitute( wFilename.getText() ) ); } dialog.setFilterNames( new String[] { BaseMessages.getString( PKG, "System.FileType.XMLFiles" ), BaseMessages.getString( PKG, "System.FileType.TextFiles" ), BaseMessages.getString( PKG, "System.FileType.CSVFiles" ), BaseMessages.getString( PKG, "System.FileType.AllFiles" ) } ); if ( dialog.open() != null ) { wFilename.setText( dialog.getFilterPath() + System.getProperty( "file.separator" ) + dialog.getFileName() ); } } } ); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed( ShellEvent e ) { cancel(); } } ); lsResize = new Listener() { public void handleEvent( Event event ) { Point size = shell.getSize(); wFields.setSize( size.x - 10, size.y - 50 ); wFields.table.setSize( size.x - 10, size.y - 50 ); wFields.redraw(); } }; shell.addListener( SWT.Resize, lsResize ); wTabFolder.setSelection( 0 ); // Set the shell size, based upon previous time... setSize(); getData(); setDateTimeFormat(); input.setChanged( changed ); shell.open(); while ( !shell.isDisposed() ) { if ( !display.readAndDispatch() ) { display.sleep(); } } return stepname; } protected void setFlagsServletOption() { boolean enableFilename = !wServletOutput.getSelection(); wlFilename.setEnabled( enableFilename ); wFilename.setEnabled( enableFilename ); wlDoNotOpenNewFileInit.setEnabled( enableFilename ); wDoNotOpenNewFileInit.setEnabled( enableFilename ); wlExtension.setEnabled( enableFilename ); wExtension.setEnabled( enableFilename ); wlSplitEvery.setEnabled( enableFilename ); wSplitEvery.setEnabled( enableFilename ); wlAddDate.setEnabled( enableFilename ); wAddDate.setEnabled( enableFilename ); wlAddTime.setEnabled( enableFilename ); wAddTime.setEnabled( enableFilename ); wlDateTimeFormat.setEnabled( enableFilename ); wDateTimeFormat.setEnabled( enableFilename ); wlSpecifyFormat.setEnabled( enableFilename ); wSpecifyFormat.setEnabled( enableFilename ); wlAddStepnr.setEnabled( enableFilename ); wAddStepnr.setEnabled( enableFilename ); wbShowFiles.setEnabled( enableFilename ); wlAddToResult.setEnabled( enableFilename ); wAddToResult.setEnabled( enableFilename ); } private void setDateTimeFormat() { if ( wSpecifyFormat.getSelection() ) { wAddDate.setSelection( false ); wAddTime.setSelection( false ); } wDateTimeFormat.setEnabled( wSpecifyFormat.getSelection() ); wlDateTimeFormat.setEnabled( wSpecifyFormat.getSelection() ); wAddDate.setEnabled( !wSpecifyFormat.getSelection() && !wServletOutput.getSelection() ); wlAddDate.setEnabled( !wSpecifyFormat.getSelection() && !wServletOutput.getSelection() ); wAddTime.setEnabled( !wSpecifyFormat.getSelection() && !wServletOutput.getSelection() ); wlAddTime.setEnabled( !wSpecifyFormat.getSelection() && !wServletOutput.getSelection() ); } private void setEncodings() { // Encoding of the text file: if ( !gotEncodings ) { gotEncodings = true; wEncoding.removeAll(); List<Charset> values = new ArrayList<Charset>( Charset.availableCharsets().values() ); for ( int i = 0; i < values.size(); i++ ) { Charset charSet = values.get( i ); wEncoding.add( charSet.displayName() ); } // Now select the default! String defEncoding = Const.getEnvironmentVariable( "file.encoding", "UTF-8" ); int idx = Const.indexOfString( defEncoding, wEncoding.getItems() ); if ( idx >= 0 ) { wEncoding.select( idx ); } } } /** * Copy information from the meta-data input to the dialog fields. */ public void getData() { if ( input.getFileName() != null ) { wFilename.setText( input.getFileName() ); } if ( input.getExtension() != null ) { wExtension.setText( input.getExtension() ); } wDoNotOpenNewFileInit.setSelection( input.isDoNotOpenNewFileInit() ); wServletOutput.setSelection( input.isServletOutput() ); setFlagsServletOption(); if ( input.getEncoding() != null ) { wEncoding.setText( input.getEncoding() ); } if ( input.getNameSpace() != null ) { wNameSpace.setText( input.getNameSpace() ); } if ( input.getMainElement() != null ) { wMainElement.setText( input.getMainElement() ); } if ( input.getRepeatElement() != null ) { wRepeatElement.setText( input.getRepeatElement() ); } wSplitEvery.setText( "" + input.getSplitEvery() ); wZipped.setSelection( input.isZipped() ); wOmitNullValues.setSelection( input.isOmitNullValues() ); wAddDate.setSelection( input.isDateInFilename() ); wAddTime.setSelection( input.isTimeInFilename() ); wAddStepnr.setSelection( input.isStepNrInFilename() ); wAddToResult.setSelection( input.isAddToResultFiles() ); if ( input.getDateTimeFormat() != null ) { wDateTimeFormat.setText( input.getDateTimeFormat() ); } wSpecifyFormat.setSelection( input.isSpecifyFormat() ); if ( isDebug() ) { logDebug( BaseMessages.getString( PKG, "XMLOutputDialog.Log.GettingFieldsInfo" ) ); } for ( int i = 0; i < input.getOutputFields().length; i++ ) { XMLField field = input.getOutputFields()[i]; TableItem item = wFields.table.getItem( i ); int index = 1; if ( field.getFieldName() != null ) { item.setText( index++, field.getFieldName() ); } if ( field.getElementName() != null ) { item.setText( index++, field.getElementName() ); } else { // Fixup for defect JIRA PDI-607. Make it the same functionality // as the loading of the original XML file. if ( field.getFieldName() != null ) { item.setText( index++, field.getFieldName() ); } else { index++; } } item.setText( index++, field.getContentType().name() ); item.setText( index++, field.getTypeDesc() ); if ( field.getFormat() != null ) { item.setText( index++, field.getFormat() ); } else { index++; } if ( field.getLength() >= 0 ) { item.setText( index++, "" + field.getLength() ); } else { index++; } if ( field.getPrecision() >= 0 ) { item.setText( index++, "" + field.getPrecision() ); } else { index++; } if ( field.getCurrencySymbol() != null ) { item.setText( index++, field.getCurrencySymbol() ); } else { index++; } if ( field.getDecimalSymbol() != null ) { item.setText( index++, field.getDecimalSymbol() ); } else { index++; } if ( field.getGroupingSymbol() != null ) { item.setText( index++, field.getGroupingSymbol() ); } else { index++; } if ( field.getNullString() != null ) { item.setText( index++, field.getNullString() ); } else { index++; } } wFields.optWidth( true ); wStepname.selectAll(); wStepname.setFocus(); } private void cancel() { stepname = null; input.setChanged( backupChanged ); dispose(); } private void getInfo( XMLOutputMeta xmlOutputMeta ) { xmlOutputMeta.setFileName( wFilename.getText() ); xmlOutputMeta.setEncoding( wEncoding.getText() ); xmlOutputMeta.setNameSpace( wNameSpace.getText() ); xmlOutputMeta.setMainElement( wMainElement.getText() ); xmlOutputMeta.setRepeatElement( wRepeatElement.getText() ); xmlOutputMeta.setExtension( wExtension.getText() ); xmlOutputMeta.setDoNotOpenNewFileInit( wDoNotOpenNewFileInit.getSelection() ); xmlOutputMeta.setServletOutput( wServletOutput.getSelection() ); xmlOutputMeta.setSplitEvery( Const.toInt( wSplitEvery.getText(), 0 ) ); xmlOutputMeta.setDateTimeFormat( wDateTimeFormat.getText() ); xmlOutputMeta.setSpecifyFormat( wSpecifyFormat.getSelection() ); xmlOutputMeta.setStepNrInFilename( wAddStepnr.getSelection() ); xmlOutputMeta.setDateInFilename( wAddDate.getSelection() ); xmlOutputMeta.setTimeInFilename( wAddTime.getSelection() ); xmlOutputMeta.setAddToResultFiles( wAddToResult.getSelection() ); xmlOutputMeta.setZipped( wZipped.getSelection() ); xmlOutputMeta.setOmitNullValues( wOmitNullValues.getSelection() ); // Table table = wFields.table; int nrfields = wFields.nrNonEmpty(); xmlOutputMeta.allocate( nrfields ); for ( int i = 0; i < nrfields; i++ ) { XMLField field = new XMLField(); TableItem item = wFields.getNonEmpty( i ); int index = 1; field.setFieldName( item.getText( index++ ) ); field.setElementName( item.getText( index++ ) ); if ( field.getFieldName().equals( field.getElementName() ) ) { field.setElementName( "" ); } field.setContentType( ContentType.valueOf( item.getText( index++ ) ) ); field.setType( item.getText( index++ ) ); field.setFormat( item.getText( index++ ) ); field.setLength( Const.toInt( item.getText( index++ ), -1 ) ); field.setPrecision( Const.toInt( item.getText( index++ ), -1 ) ); field.setCurrencySymbol( item.getText( index++ ) ); field.setDecimalSymbol( item.getText( index++ ) ); field.setGroupingSymbol( item.getText( index++ ) ); field.setNullString( item.getText( index++ ) ); // CHECKSTYLE:Indentation:OFF xmlOutputMeta.getOutputFields()[i] = field; } } private void ok() { if ( Utils.isEmpty( wStepname.getText() ) ) { return; } stepname = wStepname.getText(); // return value getInfo( input ); dispose(); } private void get() { try { RowMetaInterface r = transMeta.getPrevStepFields( stepname ); if ( r != null && !r.isEmpty() ) { TableItemInsertListener listener = new TableItemInsertListener() { public boolean tableItemInserted( TableItem tableItem, ValueMetaInterface v ) { tableItem.setText( 3, ContentType.Element.name() ); if ( v.isNumber() ) { if ( v.getLength() > 0 ) { int le = v.getLength(); int pr = v.getPrecision(); if ( v.getPrecision() <= 0 ) { pr = 0; } String mask = " "; for ( int m = 0; m < le - pr; m++ ) { mask += "0"; } if ( pr > 0 ) { mask += "."; } for ( int m = 0; m < pr; m++ ) { mask += "0"; } tableItem.setText( 4, mask ); } } return true; } }; BaseStepDialog.getFieldsFromPrevious( r, wFields, 1, new int[] { 1 }, new int[] { 4 }, 6, 7, listener ); } } catch ( KettleException ke ) { new ErrorDialog( shell, BaseMessages.getString( PKG, "System.Dialog.GetFieldsFailed.Title" ), BaseMessages .getString( PKG, "System.Dialog.GetFieldsFailed.Message" ), ke ); } } /** * Sets the output width to minimal width... * */ public void setMinimalWidth() { int nrNonEmptyFields = wFields.nrNonEmpty(); for ( int i = 0; i < nrNonEmptyFields; i++ ) { TableItem item = wFields.getNonEmpty( i ); item.setText( 5, "" ); item.setText( 6, "" ); int type = ValueMeta.getType( item.getText( 2 ) ); switch ( type ) { case ValueMeta.TYPE_STRING: item.setText( 4, "" ); break; case ValueMeta.TYPE_INTEGER: item.setText( 4, "0" ); break; case ValueMeta.TYPE_NUMBER: item.setText( 4, "0.#####" ); break; case ValueMeta.TYPE_DATE: break; default: break; } } wFields.optWidth( true ); } protected void setComboBoxes() { // Something was changed in the row. // final Map<String, Integer> fields = new HashMap<String, Integer>(); // Add the currentMeta fields... fields.putAll( inputFields ); Set<String> keySet = fields.keySet(); List<String> entries = new ArrayList<String>( keySet ); String[] fieldNames = entries.toArray( new String[entries.size()] ); Const.sortStrings( fieldNames ); colinf[0].setComboValues( fieldNames ); } }
plugins/xml/core/src/main/java/org/pentaho/di/ui/trans/steps/xmloutput/XMLOutputDialog.java
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2018 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * 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.pentaho.di.ui.trans.steps.xmloutput; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.core.util.StringUtil; import org.pentaho.di.core.util.Utils; import org.pentaho.di.core.Props; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDialogInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.steps.xmloutput.XMLField; import org.pentaho.di.trans.steps.xmloutput.XMLField.ContentType; import org.pentaho.di.trans.steps.xmloutput.XMLOutputMeta; import org.pentaho.di.ui.core.dialog.EnterSelectionDialog; import org.pentaho.di.ui.core.dialog.ErrorDialog; import org.pentaho.di.ui.core.widget.ColumnInfo; import org.pentaho.di.ui.core.widget.TableView; import org.pentaho.di.ui.core.widget.TextVar; import org.pentaho.di.ui.trans.step.BaseStepDialog; import org.pentaho.di.ui.trans.step.TableItemInsertListener; public class XMLOutputDialog extends BaseStepDialog implements StepDialogInterface { private static Class<?> PKG = XMLOutputMeta.class; // for i18n purposes, needed by Translator2!! private CTabFolder wTabFolder; private FormData fdTabFolder; private CTabItem wFileTab, wContentTab, wFieldsTab; private FormData fdFileComp, fdContentComp, fdFieldsComp; private Label wlFilename; private Button wbFilename; private TextVar wFilename; private FormData fdlFilename, fdbFilename, fdFilename; private Label wlExtension; private TextVar wExtension; private FormData fdlExtension, fdExtension; private Label wlServletOutput; private Button wServletOutput; private FormData fdlServletOutput, fdServletOutput; private Label wlAddStepnr; private Button wAddStepnr; private FormData fdlAddStepnr, fdAddStepnr; private Label wlAddDate; private Button wAddDate; private FormData fdlAddDate, fdAddDate; private Label wlAddTime; private Button wAddTime; private FormData fdlAddTime, fdAddTime; private Button wbShowFiles; private FormData fdbShowFiles; private Label wlZipped; private Button wZipped; private FormData fdlZipped, fdZipped; private Label wlOmitNullValues; private Button wOmitNullValues; private FormData fdlOmitNullValues, fdOmitNullValues; private Label wlEncoding; private CCombo wEncoding; private FormData fdlEncoding, fdEncoding; private Label wlNameSpace; private Text wNameSpace; private FormData fdlNameSpace, fdNameSpace; private Label wlMainElement; private CCombo wMainElement; private FormData fdlMainElement, fdMainElement; private Label wlRepeatElement; private CCombo wRepeatElement; private FormData fdlRepeatElement, fdRepeatElement; private Label wlSplitEvery; private Text wSplitEvery; private FormData fdlSplitEvery, fdSplitEvery; private TableView wFields; private FormData fdFields; private XMLOutputMeta input; private Button wMinWidth; private Listener lsMinWidth; private boolean gotEncodings = false; private Label wlAddToResult; private Button wAddToResult; private FormData fdlAddToResult, fdAddToResult; private Label wlDoNotOpenNewFileInit; private Button wDoNotOpenNewFileInit; private FormData fdlDoNotOpenNewFileInit, fdDoNotOpenNewFileInit; private Label wlSpecifyFormat; private Button wSpecifyFormat; private FormData fdlSpecifyFormat, fdSpecifyFormat; private Label wlDateTimeFormat; private CCombo wDateTimeFormat; private FormData fdlDateTimeFormat, fdDateTimeFormat; private ColumnInfo[] colinf; private Map<String, Integer> inputFields; public XMLOutputDialog( Shell parent, Object in, TransMeta transMeta, String sname ) { super( parent, (BaseStepMeta) in, transMeta, sname ); input = (XMLOutputMeta) in; inputFields = new HashMap<String, Integer>(); } public String open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell( parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN ); props.setLook( shell ); setShellImage( shell, input ); ModifyListener lsMod = new ModifyListener() { public void modifyText( ModifyEvent e ) { input.setChanged(); } }; changed = input.hasChanged(); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout( formLayout ); shell.setText( BaseMessages.getString( PKG, "XMLOutputDialog.DialogTitle" ) ); int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Stepname line wlStepname = new Label( shell, SWT.RIGHT ); wlStepname.setText( BaseMessages.getString( PKG, "System.Label.StepName" ) ); props.setLook( wlStepname ); fdlStepname = new FormData(); fdlStepname.left = new FormAttachment( 0, 0 ); fdlStepname.top = new FormAttachment( 0, margin ); fdlStepname.right = new FormAttachment( middle, -margin ); wlStepname.setLayoutData( fdlStepname ); wStepname = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); wStepname.setText( stepname ); props.setLook( wStepname ); wStepname.addModifyListener( lsMod ); fdStepname = new FormData(); fdStepname.left = new FormAttachment( middle, 0 ); fdStepname.top = new FormAttachment( 0, margin ); fdStepname.right = new FormAttachment( 100, 0 ); wStepname.setLayoutData( fdStepname ); wTabFolder = new CTabFolder( shell, SWT.BORDER ); props.setLook( wTabFolder, Props.WIDGET_STYLE_TAB ); // //////////////////////// // START OF FILE TAB/// // / wFileTab = new CTabItem( wTabFolder, SWT.NONE ); wFileTab.setText( BaseMessages.getString( PKG, "XMLOutputDialog.FileTab.Tab" ) ); Composite wFileComp = new Composite( wTabFolder, SWT.NONE ); props.setLook( wFileComp ); FormLayout fileLayout = new FormLayout(); fileLayout.marginWidth = 3; fileLayout.marginHeight = 3; wFileComp.setLayout( fileLayout ); // Filename line wlFilename = new Label( wFileComp, SWT.RIGHT ); wlFilename.setText( BaseMessages.getString( PKG, "XMLOutputDialog.Filename.Label" ) ); props.setLook( wlFilename ); fdlFilename = new FormData(); fdlFilename.left = new FormAttachment( 0, 0 ); fdlFilename.top = new FormAttachment( 0, margin ); fdlFilename.right = new FormAttachment( middle, -margin ); wlFilename.setLayoutData( fdlFilename ); wbFilename = new Button( wFileComp, SWT.PUSH | SWT.CENTER ); props.setLook( wbFilename ); wbFilename.setText( BaseMessages.getString( PKG, "XMLOutputDialog.Browse.Button" ) ); fdbFilename = new FormData(); fdbFilename.right = new FormAttachment( 100, 0 ); fdbFilename.top = new FormAttachment( 0, 0 ); wbFilename.setLayoutData( fdbFilename ); wFilename = new TextVar( transMeta, wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wFilename ); wFilename.addModifyListener( lsMod ); fdFilename = new FormData(); fdFilename.left = new FormAttachment( middle, 0 ); fdFilename.top = new FormAttachment( 0, margin ); fdFilename.right = new FormAttachment( wbFilename, -margin ); wFilename.setLayoutData( fdFilename ); // Open new File at Init wlDoNotOpenNewFileInit = new Label( wFileComp, SWT.RIGHT ); wlDoNotOpenNewFileInit.setText( BaseMessages.getString( PKG, "XMLOutputDialog.DoNotOpenNewFileInit.Label" ) ); props.setLook( wlDoNotOpenNewFileInit ); fdlDoNotOpenNewFileInit = new FormData(); fdlDoNotOpenNewFileInit.left = new FormAttachment( 0, 0 ); fdlDoNotOpenNewFileInit.top = new FormAttachment( wFilename, margin ); fdlDoNotOpenNewFileInit.right = new FormAttachment( middle, -margin ); wlDoNotOpenNewFileInit.setLayoutData( fdlDoNotOpenNewFileInit ); wDoNotOpenNewFileInit = new Button( wFileComp, SWT.CHECK ); wDoNotOpenNewFileInit .setToolTipText( BaseMessages.getString( PKG, "XMLOutputDialog.DoNotOpenNewFileInit.Tooltip" ) ); props.setLook( wDoNotOpenNewFileInit ); fdDoNotOpenNewFileInit = new FormData(); fdDoNotOpenNewFileInit.left = new FormAttachment( middle, 0 ); fdDoNotOpenNewFileInit.top = new FormAttachment( wFilename, margin ); fdDoNotOpenNewFileInit.right = new FormAttachment( 100, 0 ); wDoNotOpenNewFileInit.setLayoutData( fdDoNotOpenNewFileInit ); wDoNotOpenNewFileInit.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { input.setChanged(); } } ); // Run this as a command instead? wlServletOutput = new Label( wFileComp, SWT.RIGHT ); wlServletOutput.setText( BaseMessages.getString( PKG, "XMLOutputDialog.ServletOutput.Label" ) ); props.setLook( wlServletOutput ); fdlServletOutput = new FormData(); fdlServletOutput.left = new FormAttachment( 0, 0 ); fdlServletOutput.top = new FormAttachment( wDoNotOpenNewFileInit, margin ); fdlServletOutput.right = new FormAttachment( middle, -margin ); wlServletOutput.setLayoutData( fdlServletOutput ); wServletOutput = new Button( wFileComp, SWT.CHECK ); wServletOutput.setToolTipText( BaseMessages.getString( PKG, "XMLOutputDialog.ServletOutput.Tooltip" ) ); props.setLook( wServletOutput ); fdServletOutput = new FormData(); fdServletOutput.left = new FormAttachment( middle, 0 ); fdServletOutput.top = new FormAttachment( wDoNotOpenNewFileInit, margin ); fdServletOutput.right = new FormAttachment( 100, 0 ); wServletOutput.setLayoutData( fdServletOutput ); wServletOutput.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { input.setChanged(); setFlagsServletOption(); } } ); // Extension line wlExtension = new Label( wFileComp, SWT.RIGHT ); wlExtension.setText( BaseMessages.getString( PKG, "XMLOutputDialog.Extension.Label" ) ); props.setLook( wlExtension ); fdlExtension = new FormData(); fdlExtension.left = new FormAttachment( 0, 0 ); fdlExtension.top = new FormAttachment( wServletOutput, margin ); fdlExtension.right = new FormAttachment( middle, -margin ); wlExtension.setLayoutData( fdlExtension ); wExtension = new TextVar( transMeta, wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); wExtension.setText( "" ); props.setLook( wExtension ); wExtension.addModifyListener( lsMod ); fdExtension = new FormData(); fdExtension.left = new FormAttachment( middle, 0 ); fdExtension.top = new FormAttachment( wServletOutput, margin ); fdExtension.right = new FormAttachment( 100, 0 ); wExtension.setLayoutData( fdExtension ); // Create multi-part file? wlAddStepnr = new Label( wFileComp, SWT.RIGHT ); wlAddStepnr.setText( BaseMessages.getString( PKG, "XMLOutputDialog.AddStepNr.Label" ) ); props.setLook( wlAddStepnr ); fdlAddStepnr = new FormData(); fdlAddStepnr.left = new FormAttachment( 0, 0 ); fdlAddStepnr.top = new FormAttachment( wExtension, margin ); fdlAddStepnr.right = new FormAttachment( middle, -margin ); wlAddStepnr.setLayoutData( fdlAddStepnr ); wAddStepnr = new Button( wFileComp, SWT.CHECK ); props.setLook( wAddStepnr ); fdAddStepnr = new FormData(); fdAddStepnr.left = new FormAttachment( middle, 0 ); fdAddStepnr.top = new FormAttachment( wExtension, margin ); fdAddStepnr.right = new FormAttachment( 100, 0 ); wAddStepnr.setLayoutData( fdAddStepnr ); wAddStepnr.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { input.setChanged(); } } ); // Create multi-part file? wlAddDate = new Label( wFileComp, SWT.RIGHT ); wlAddDate.setText( BaseMessages.getString( PKG, "XMLOutputDialog.AddDate.Label" ) ); props.setLook( wlAddDate ); fdlAddDate = new FormData(); fdlAddDate.left = new FormAttachment( 0, 0 ); fdlAddDate.top = new FormAttachment( wAddStepnr, margin ); fdlAddDate.right = new FormAttachment( middle, -margin ); wlAddDate.setLayoutData( fdlAddDate ); wAddDate = new Button( wFileComp, SWT.CHECK ); props.setLook( wAddDate ); fdAddDate = new FormData(); fdAddDate.left = new FormAttachment( middle, 0 ); fdAddDate.top = new FormAttachment( wAddStepnr, margin ); fdAddDate.right = new FormAttachment( 100, 0 ); wAddDate.setLayoutData( fdAddDate ); wAddDate.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { input.setChanged(); } } ); // Create multi-part file? wlAddTime = new Label( wFileComp, SWT.RIGHT ); wlAddTime.setText( BaseMessages.getString( PKG, "XMLOutputDialog.AddTime.Label" ) ); props.setLook( wlAddTime ); fdlAddTime = new FormData(); fdlAddTime.left = new FormAttachment( 0, 0 ); fdlAddTime.top = new FormAttachment( wAddDate, margin ); fdlAddTime.right = new FormAttachment( middle, -margin ); wlAddTime.setLayoutData( fdlAddTime ); wAddTime = new Button( wFileComp, SWT.CHECK ); props.setLook( wAddTime ); fdAddTime = new FormData(); fdAddTime.left = new FormAttachment( middle, 0 ); fdAddTime.top = new FormAttachment( wAddDate, margin ); fdAddTime.right = new FormAttachment( 100, 0 ); wAddTime.setLayoutData( fdAddTime ); wAddTime.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { input.setChanged(); } } ); // Specify date time format? wlSpecifyFormat = new Label( wFileComp, SWT.RIGHT ); wlSpecifyFormat.setText( BaseMessages.getString( PKG, "XMLOutputDialog.SpecifyFormat.Label" ) ); props.setLook( wlSpecifyFormat ); fdlSpecifyFormat = new FormData(); fdlSpecifyFormat.left = new FormAttachment( 0, 0 ); fdlSpecifyFormat.top = new FormAttachment( wAddTime, margin ); fdlSpecifyFormat.right = new FormAttachment( middle, -margin ); wlSpecifyFormat.setLayoutData( fdlSpecifyFormat ); wSpecifyFormat = new Button( wFileComp, SWT.CHECK ); props.setLook( wSpecifyFormat ); wSpecifyFormat.setToolTipText( BaseMessages.getString( PKG, "XMLOutputDialog.SpecifyFormat.Tooltip" ) ); fdSpecifyFormat = new FormData(); fdSpecifyFormat.left = new FormAttachment( middle, 0 ); fdSpecifyFormat.top = new FormAttachment( wAddTime, margin ); fdSpecifyFormat.right = new FormAttachment( 100, 0 ); wSpecifyFormat.setLayoutData( fdSpecifyFormat ); wSpecifyFormat.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { input.setChanged(); setDateTimeFormat(); } } ); // Prepare a list of possible DateTimeFormats... String[] dats = Const.getDateFormats(); // DateTimeFormat wlDateTimeFormat = new Label( wFileComp, SWT.RIGHT ); wlDateTimeFormat.setText( BaseMessages.getString( PKG, "XMLOutputDialog.DateTimeFormat.Label" ) ); props.setLook( wlDateTimeFormat ); fdlDateTimeFormat = new FormData(); fdlDateTimeFormat.left = new FormAttachment( 0, 0 ); fdlDateTimeFormat.top = new FormAttachment( wSpecifyFormat, margin ); fdlDateTimeFormat.right = new FormAttachment( middle, -margin ); wlDateTimeFormat.setLayoutData( fdlDateTimeFormat ); wDateTimeFormat = new CCombo( wFileComp, SWT.BORDER | SWT.READ_ONLY ); wDateTimeFormat.setEditable( true ); props.setLook( wDateTimeFormat ); wDateTimeFormat.addModifyListener( lsMod ); fdDateTimeFormat = new FormData(); fdDateTimeFormat.left = new FormAttachment( middle, 0 ); fdDateTimeFormat.top = new FormAttachment( wSpecifyFormat, margin ); fdDateTimeFormat.right = new FormAttachment( 100, 0 ); wDateTimeFormat.setLayoutData( fdDateTimeFormat ); for ( int x = 0; x < dats.length; x++ ) { wDateTimeFormat.add( dats[x] ); } wbShowFiles = new Button( wFileComp, SWT.PUSH | SWT.CENTER ); props.setLook( wbShowFiles ); wbShowFiles.setText( BaseMessages.getString( PKG, "XMLOutputDialog.ShowFiles.Button" ) ); fdbShowFiles = new FormData(); fdbShowFiles.left = new FormAttachment( middle, 0 ); fdbShowFiles.top = new FormAttachment( wDateTimeFormat, margin * 2 ); wbShowFiles.setLayoutData( fdbShowFiles ); wbShowFiles.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { XMLOutputMeta tfoi = new XMLOutputMeta(); getInfo( tfoi ); String[] files = tfoi.getFiles( transMeta ); if ( files != null && files.length > 0 ) { EnterSelectionDialog esd = new EnterSelectionDialog( shell, files, BaseMessages.getString( PKG, "XMLOutputDialog.OutputFiles.DialogTitle" ), BaseMessages.getString( PKG, "XMLOutputDialog.OutputFiles.DialogMessage" ) ); esd.setViewOnly(); esd.open(); } else { MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR ); mb.setMessage( BaseMessages.getString( PKG, "XMLOutputDialog.NoFilesFound.DialogMessage" ) ); mb.setText( BaseMessages.getString( PKG, "System.Dialog.Error.Title" ) ); mb.open(); } } } ); // Add File to the result files name wlAddToResult = new Label( wFileComp, SWT.RIGHT ); wlAddToResult.setText( BaseMessages.getString( PKG, "XMLOutputDialog.AddFileToResult.Label" ) ); props.setLook( wlAddToResult ); fdlAddToResult = new FormData(); fdlAddToResult.left = new FormAttachment( 0, 0 ); fdlAddToResult.top = new FormAttachment( wbShowFiles, 2 * margin ); fdlAddToResult.right = new FormAttachment( middle, -margin ); wlAddToResult.setLayoutData( fdlAddToResult ); wAddToResult = new Button( wFileComp, SWT.CHECK ); wAddToResult.setToolTipText( BaseMessages.getString( PKG, "XMLOutputDialog.AddFileToResult.Tooltip" ) ); props.setLook( wAddToResult ); fdAddToResult = new FormData(); fdAddToResult.left = new FormAttachment( middle, 0 ); fdAddToResult.top = new FormAttachment( wbShowFiles, 2 * margin ); fdAddToResult.right = new FormAttachment( 100, 0 ); wAddToResult.setLayoutData( fdAddToResult ); SelectionAdapter lsSelR = new SelectionAdapter() { public void widgetSelected( SelectionEvent arg0 ) { input.setChanged(); } }; wAddToResult.addSelectionListener( lsSelR ); fdFileComp = new FormData(); fdFileComp.left = new FormAttachment( 0, 0 ); fdFileComp.top = new FormAttachment( 0, 0 ); fdFileComp.right = new FormAttachment( 100, 0 ); fdFileComp.bottom = new FormAttachment( 100, 0 ); wFileComp.setLayoutData( fdFileComp ); wFileComp.layout(); wFileTab.setControl( wFileComp ); // /////////////////////////////////////////////////////////// // / END OF FILE TAB // /////////////////////////////////////////////////////////// // //////////////////////// // START OF CONTENT TAB/// // / wContentTab = new CTabItem( wTabFolder, SWT.NONE ); wContentTab.setText( BaseMessages.getString( PKG, "XMLOutputDialog.ContentTab.TabTitle" ) ); FormLayout contentLayout = new FormLayout(); contentLayout.marginWidth = 3; contentLayout.marginHeight = 3; Composite wContentComp = new Composite( wTabFolder, SWT.NONE ); props.setLook( wContentComp ); wContentComp.setLayout( contentLayout ); wlZipped = new Label( wContentComp, SWT.RIGHT ); wlZipped.setText( BaseMessages.getString( PKG, "XMLOutputDialog.Zipped.Label" ) ); props.setLook( wlZipped ); fdlZipped = new FormData(); fdlZipped.left = new FormAttachment( 0, 0 ); fdlZipped.top = new FormAttachment( 0, 0 ); fdlZipped.right = new FormAttachment( middle, -margin ); wlZipped.setLayoutData( fdlZipped ); wZipped = new Button( wContentComp, SWT.CHECK ); props.setLook( wZipped ); fdZipped = new FormData(); fdZipped.left = new FormAttachment( middle, 0 ); fdZipped.top = new FormAttachment( 0, 0 ); fdZipped.right = new FormAttachment( 100, 0 ); wZipped.setLayoutData( fdZipped ); wZipped.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { input.setChanged(); } } ); wlEncoding = new Label( wContentComp, SWT.RIGHT ); wlEncoding.setText( BaseMessages.getString( PKG, "XMLOutputDialog.Encoding.Label" ) ); props.setLook( wlEncoding ); fdlEncoding = new FormData(); fdlEncoding.left = new FormAttachment( 0, 0 ); fdlEncoding.top = new FormAttachment( wZipped, margin ); fdlEncoding.right = new FormAttachment( middle, -margin ); wlEncoding.setLayoutData( fdlEncoding ); wEncoding = new CCombo( wContentComp, SWT.BORDER | SWT.READ_ONLY ); wEncoding.setEditable( true ); props.setLook( wEncoding ); wEncoding.addModifyListener( lsMod ); fdEncoding = new FormData(); fdEncoding.left = new FormAttachment( middle, 0 ); fdEncoding.top = new FormAttachment( wZipped, margin ); fdEncoding.right = new FormAttachment( 100, 0 ); wEncoding.setLayoutData( fdEncoding ); wEncoding.addFocusListener( new FocusListener() { public void focusLost( org.eclipse.swt.events.FocusEvent e ) { } public void focusGained( org.eclipse.swt.events.FocusEvent e ) { Cursor busy = new Cursor( shell.getDisplay(), SWT.CURSOR_WAIT ); shell.setCursor( busy ); setEncodings(); shell.setCursor( null ); busy.dispose(); } } ); wlNameSpace = new Label( wContentComp, SWT.RIGHT ); wlNameSpace.setText( BaseMessages.getString( PKG, "XMLOutputDialog.NameSpace.Label" ) ); props.setLook( wlNameSpace ); fdlNameSpace = new FormData(); fdlNameSpace.left = new FormAttachment( 0, 0 ); fdlNameSpace.top = new FormAttachment( wEncoding, margin ); fdlNameSpace.right = new FormAttachment( middle, -margin ); wlNameSpace.setLayoutData( fdlNameSpace ); wNameSpace = new Text( wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wNameSpace ); wNameSpace.addModifyListener( lsMod ); fdNameSpace = new FormData(); fdNameSpace.left = new FormAttachment( middle, 0 ); fdNameSpace.top = new FormAttachment( wEncoding, margin ); fdNameSpace.right = new FormAttachment( 100, 0 ); wNameSpace.setLayoutData( fdNameSpace ); wlMainElement = new Label( wContentComp, SWT.RIGHT ); wlMainElement.setText( BaseMessages.getString( PKG, "XMLOutputDialog.MainElement.Label" ) ); props.setLook( wlMainElement ); fdlMainElement = new FormData(); fdlMainElement.left = new FormAttachment( 0, 0 ); fdlMainElement.top = new FormAttachment( wNameSpace, margin ); fdlMainElement.right = new FormAttachment( middle, -margin ); wlMainElement.setLayoutData( fdlMainElement ); wMainElement = new CCombo( wContentComp, SWT.BORDER | SWT.READ_ONLY ); wMainElement.setEditable( true ); props.setLook( wMainElement ); wMainElement.addModifyListener( lsMod ); fdMainElement = new FormData(); fdMainElement.left = new FormAttachment( middle, 0 ); fdMainElement.top = new FormAttachment( wNameSpace, margin ); fdMainElement.right = new FormAttachment( 100, 0 ); wMainElement.setLayoutData( fdMainElement ); wlRepeatElement = new Label( wContentComp, SWT.RIGHT ); wlRepeatElement.setText( BaseMessages.getString( PKG, "XMLOutputDialog.RepeatElement.Label" ) ); props.setLook( wlRepeatElement ); fdlRepeatElement = new FormData(); fdlRepeatElement.left = new FormAttachment( 0, 0 ); fdlRepeatElement.top = new FormAttachment( wMainElement, margin ); fdlRepeatElement.right = new FormAttachment( middle, -margin ); wlRepeatElement.setLayoutData( fdlRepeatElement ); wRepeatElement = new CCombo( wContentComp, SWT.BORDER | SWT.READ_ONLY ); wRepeatElement.setEditable( true ); props.setLook( wRepeatElement ); wRepeatElement.addModifyListener( lsMod ); fdRepeatElement = new FormData(); fdRepeatElement.left = new FormAttachment( middle, 0 ); fdRepeatElement.top = new FormAttachment( wMainElement, margin ); fdRepeatElement.right = new FormAttachment( 100, 0 ); wRepeatElement.setLayoutData( fdRepeatElement ); wlSplitEvery = new Label( wContentComp, SWT.RIGHT ); wlSplitEvery.setText( BaseMessages.getString( PKG, "XMLOutputDialog.SplitEvery.Label" ) ); props.setLook( wlSplitEvery ); fdlSplitEvery = new FormData(); fdlSplitEvery.left = new FormAttachment( 0, 0 ); fdlSplitEvery.top = new FormAttachment( wRepeatElement, margin ); fdlSplitEvery.right = new FormAttachment( middle, -margin ); wlSplitEvery.setLayoutData( fdlSplitEvery ); wSplitEvery = new Text( wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wSplitEvery ); wSplitEvery.addModifyListener( lsMod ); fdSplitEvery = new FormData(); fdSplitEvery.left = new FormAttachment( middle, 0 ); fdSplitEvery.top = new FormAttachment( wRepeatElement, margin ); fdSplitEvery.right = new FormAttachment( 100, 0 ); wSplitEvery.setLayoutData( fdSplitEvery ); wlOmitNullValues = new Label( wContentComp, SWT.RIGHT ); wlOmitNullValues.setText( BaseMessages.getString( PKG, "XMLOutputDialog.OmitNullValues.Label" ) ); props.setLook( wlOmitNullValues ); fdlOmitNullValues = new FormData(); fdlOmitNullValues.left = new FormAttachment( 0, 0 ); fdlOmitNullValues.top = new FormAttachment( wSplitEvery, margin ); fdlOmitNullValues.right = new FormAttachment( middle, -margin ); wlOmitNullValues.setLayoutData( fdlOmitNullValues ); wOmitNullValues = new Button( wContentComp, SWT.CHECK ); props.setLook( wOmitNullValues ); fdOmitNullValues = new FormData(); fdOmitNullValues.left = new FormAttachment( middle, 0 ); fdOmitNullValues.top = new FormAttachment( wSplitEvery, margin ); fdOmitNullValues.right = new FormAttachment( 100, 0 ); wOmitNullValues.setLayoutData( fdOmitNullValues ); wOmitNullValues.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { input.setChanged(); } } ); fdContentComp = new FormData(); fdContentComp.left = new FormAttachment( 0, 0 ); fdContentComp.top = new FormAttachment( 0, 0 ); fdContentComp.right = new FormAttachment( 100, 0 ); fdContentComp.bottom = new FormAttachment( 100, 0 ); wContentComp.setLayoutData( fdContentComp ); wContentComp.layout(); wContentTab.setControl( wContentComp ); // /////////////////////////////////////////////////////////// // / END OF CONTENT TAB // /////////////////////////////////////////////////////////// // Fields tab... // wFieldsTab = new CTabItem( wTabFolder, SWT.NONE ); wFieldsTab.setText( BaseMessages.getString( PKG, "XMLOutputDialog.FieldsTab.TabTitle" ) ); FormLayout fieldsLayout = new FormLayout(); fieldsLayout.marginWidth = Const.FORM_MARGIN; fieldsLayout.marginHeight = Const.FORM_MARGIN; Composite wFieldsComp = new Composite( wTabFolder, SWT.NONE ); wFieldsComp.setLayout( fieldsLayout ); props.setLook( wFieldsComp ); wGet = new Button( wFieldsComp, SWT.PUSH ); wGet.setText( BaseMessages.getString( PKG, "XMLOutputDialog.Get.Button" ) ); wGet.setToolTipText( BaseMessages.getString( PKG, "XMLOutputDialog.Get.Tooltip" ) ); wMinWidth = new Button( wFieldsComp, SWT.PUSH ); wMinWidth.setText( BaseMessages.getString( PKG, "XMLOutputDialog.MinWidth.Label" ) ); wMinWidth.setToolTipText( BaseMessages.getString( PKG, "XMLOutputDialog.MinWidth.Tooltip" ) ); setButtonPositions( new Button[] { wGet, wMinWidth }, margin, null ); final int FieldsRows = input.getOutputFields().length; // Prepare a list of possible formats... String[] nums = Const.getNumberFormats(); int totsize = dats.length + nums.length; String[] formats = new String[totsize]; for ( int x = 0; x < dats.length; x++ ) { formats[x] = dats[x]; } for ( int x = 0; x < nums.length; x++ ) { formats[dats.length + x] = nums[x]; } colinf = new ColumnInfo[] { new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.Fieldname.Column" ), ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] { "" }, false ), new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.ElementName.Column" ), ColumnInfo.COLUMN_TYPE_TEXT, false ), new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.ContentType.Column" ), ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] { "Element", "Attribute", }, false ), new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.Type.Column" ), ColumnInfo.COLUMN_TYPE_CCOMBO, ValueMeta.getTypes() ), new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.Format.Column" ), ColumnInfo.COLUMN_TYPE_CCOMBO, formats ), new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.Length.Column" ), ColumnInfo.COLUMN_TYPE_TEXT, false ), new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.Precision.Column" ), ColumnInfo.COLUMN_TYPE_TEXT, false ), new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.Currency.Column" ), ColumnInfo.COLUMN_TYPE_TEXT, false ), new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.Decimal.Column" ), ColumnInfo.COLUMN_TYPE_TEXT, false ), new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.Group.Column" ), ColumnInfo.COLUMN_TYPE_TEXT, false ), new ColumnInfo( BaseMessages.getString( PKG, "XMLOutputDialog.Null.Column" ), ColumnInfo.COLUMN_TYPE_TEXT, false ) }; wFields = new TableView( transMeta, wFieldsComp, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, colinf, FieldsRows, lsMod, props ); fdFields = new FormData(); fdFields.left = new FormAttachment( 0, 0 ); fdFields.top = new FormAttachment( 0, 0 ); fdFields.right = new FormAttachment( 100, 0 ); fdFields.bottom = new FormAttachment( wGet, -margin ); wFields.setLayoutData( fdFields ); // // Search the fields in the background final Runnable runnable = new Runnable() { public void run() { StepMeta stepMeta = transMeta.findStep( stepname ); if ( stepMeta != null ) { try { RowMetaInterface row = transMeta.getPrevStepFields( stepMeta ); // Remember these fields... for ( int i = 0; i < row.size(); i++ ) { inputFields.put( row.getValueMeta( i ).getName(), Integer.valueOf( i ) ); } setComboBoxes(); } catch ( KettleException e ) { logError( BaseMessages.getString( PKG, "System.Dialog.GetFieldsFailed.Message" ) ); } } } }; new Thread( runnable ).start(); fdFieldsComp = new FormData(); fdFieldsComp.left = new FormAttachment( 0, 0 ); fdFieldsComp.top = new FormAttachment( 0, 0 ); fdFieldsComp.right = new FormAttachment( 100, 0 ); fdFieldsComp.bottom = new FormAttachment( 100, 0 ); wFieldsComp.setLayoutData( fdFieldsComp ); wFieldsComp.layout(); wFieldsTab.setControl( wFieldsComp ); fdTabFolder = new FormData(); fdTabFolder.left = new FormAttachment( 0, 0 ); fdTabFolder.top = new FormAttachment( wStepname, margin ); fdTabFolder.right = new FormAttachment( 100, 0 ); fdTabFolder.bottom = new FormAttachment( 100, -50 ); wTabFolder.setLayoutData( fdTabFolder ); wOK = new Button( shell, SWT.PUSH ); wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) ); wCancel = new Button( shell, SWT.PUSH ); wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) ); setButtonPositions( new Button[] { wOK, wCancel }, margin, wTabFolder ); // Add listeners lsOK = new Listener() { public void handleEvent( Event e ) { ok(); } }; lsGet = new Listener() { public void handleEvent( Event e ) { get(); } }; lsMinWidth = new Listener() { public void handleEvent( Event e ) { setMinimalWidth(); } }; lsCancel = new Listener() { public void handleEvent( Event e ) { cancel(); } }; wOK.addListener( SWT.Selection, lsOK ); wGet.addListener( SWT.Selection, lsGet ); wMinWidth.addListener( SWT.Selection, lsMinWidth ); wCancel.addListener( SWT.Selection, lsCancel ); lsDef = new SelectionAdapter() { public void widgetDefaultSelected( SelectionEvent e ) { ok(); } }; wStepname.addSelectionListener( lsDef ); wFilename.addSelectionListener( lsDef ); // Whenever something changes, set the tooltip to the expanded version: wFilename.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { wFilename.setToolTipText( transMeta.environmentSubstitute( wFilename.getText() ) ); } } ); wbFilename.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { FileDialog dialog = new FileDialog( shell, SWT.SAVE ); dialog.setFilterExtensions( new String[] { "*.xml", "*.txt", "*.csv", "*" } ); if ( wFilename.getText() != null ) { dialog.setFileName( transMeta.environmentSubstitute( wFilename.getText() ) ); } dialog.setFilterNames( new String[] { BaseMessages.getString( PKG, "System.FileType.XMLFiles" ), BaseMessages.getString( PKG, "System.FileType.TextFiles" ), BaseMessages.getString( PKG, "System.FileType.CSVFiles" ), BaseMessages.getString( PKG, "System.FileType.AllFiles" ) } ); if ( dialog.open() != null ) { wFilename.setText( dialog.getFilterPath() + System.getProperty( "file.separator" ) + dialog.getFileName() ); } } } ); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed( ShellEvent e ) { cancel(); } } ); lsResize = new Listener() { public void handleEvent( Event event ) { Point size = shell.getSize(); wFields.setSize( size.x - 10, size.y - 50 ); wFields.table.setSize( size.x - 10, size.y - 50 ); wFields.redraw(); } }; shell.addListener( SWT.Resize, lsResize ); wTabFolder.setSelection( 0 ); // Set the shell size, based upon previous time... setSize(); getData(); setDateTimeFormat(); input.setChanged( changed ); shell.open(); while ( !shell.isDisposed() ) { if ( !display.readAndDispatch() ) { display.sleep(); } } return stepname; } protected void setFlagsServletOption() { boolean enableFilename = !wServletOutput.getSelection(); wlFilename.setEnabled( enableFilename ); wFilename.setEnabled( enableFilename ); wlDoNotOpenNewFileInit.setEnabled( enableFilename ); wDoNotOpenNewFileInit.setEnabled( enableFilename ); wlExtension.setEnabled( enableFilename ); wExtension.setEnabled( enableFilename ); wlSplitEvery.setEnabled( enableFilename ); wSplitEvery.setEnabled( enableFilename ); wlAddDate.setEnabled( enableFilename ); wAddDate.setEnabled( enableFilename ); wlAddTime.setEnabled( enableFilename ); wAddTime.setEnabled( enableFilename ); wlDateTimeFormat.setEnabled( enableFilename ); wDateTimeFormat.setEnabled( enableFilename ); wlSpecifyFormat.setEnabled( enableFilename ); wSpecifyFormat.setEnabled( enableFilename ); wlAddStepnr.setEnabled( enableFilename ); wAddStepnr.setEnabled( enableFilename ); wbShowFiles.setEnabled( enableFilename ); wlAddToResult.setEnabled( enableFilename ); wAddToResult.setEnabled( enableFilename ); } private void setDateTimeFormat() { if ( wSpecifyFormat.getSelection() ) { wAddDate.setSelection( false ); wAddTime.setSelection( false ); } wDateTimeFormat.setEnabled( wSpecifyFormat.getSelection() ); wlDateTimeFormat.setEnabled( wSpecifyFormat.getSelection() ); wAddDate.setEnabled( !wSpecifyFormat.getSelection() && !wServletOutput.getSelection() ); wlAddDate.setEnabled( !wSpecifyFormat.getSelection() && !wServletOutput.getSelection() ); wAddTime.setEnabled( !wSpecifyFormat.getSelection() && !wServletOutput.getSelection() ); wlAddTime.setEnabled( !wSpecifyFormat.getSelection() && !wServletOutput.getSelection() ); } private void setEncodings() { // Encoding of the text file: if ( !gotEncodings ) { gotEncodings = true; wEncoding.removeAll(); List<Charset> values = new ArrayList<Charset>( Charset.availableCharsets().values() ); for ( int i = 0; i < values.size(); i++ ) { Charset charSet = values.get( i ); wEncoding.add( charSet.displayName() ); } // Now select the default! String defEncoding = Const.getEnvironmentVariable( "file.encoding", "UTF-8" ); int idx = Const.indexOfString( defEncoding, wEncoding.getItems() ); if ( idx >= 0 ) { wEncoding.select( idx ); } } } /** * Copy information from the meta-data input to the dialog fields. */ public void getData() { if ( input.getFileName() != null ) { wFilename.setText( input.getFileName() ); } if ( input.getExtension() != null ) { wExtension.setText( input.getExtension() ); } wDoNotOpenNewFileInit.setSelection( input.isDoNotOpenNewFileInit() ); wServletOutput.setSelection( input.isServletOutput() ); setFlagsServletOption(); if ( input.getEncoding() != null ) { wEncoding.setText( input.getEncoding() ); } if ( input.getNameSpace() != null ) { wNameSpace.setText( input.getNameSpace() ); } if ( input.getMainElement() != null ) { wMainElement.setText( input.getMainElement() ); } if ( input.getRepeatElement() != null ) { wRepeatElement.setText( input.getRepeatElement() ); } wSplitEvery.setText( "" + input.getSplitEvery() ); wZipped.setSelection( input.isZipped() ); wOmitNullValues.setSelection( input.isOmitNullValues() ); wAddDate.setSelection( input.isDateInFilename() ); wAddTime.setSelection( input.isTimeInFilename() ); wAddStepnr.setSelection( input.isStepNrInFilename() ); wAddToResult.setSelection( input.isAddToResultFiles() ); if ( input.getDateTimeFormat() != null ) { wDateTimeFormat.setText( input.getDateTimeFormat() ); } wSpecifyFormat.setSelection( input.isSpecifyFormat() ); if ( isDebug() ) { logDebug( BaseMessages.getString( PKG, "XMLOutputDialog.Log.GettingFieldsInfo" ) ); } for ( int i = 0; i < input.getOutputFields().length; i++ ) { XMLField field = input.getOutputFields()[i]; TableItem item = wFields.table.getItem( i ); int index = 1; if ( field.getFieldName() != null ) { item.setText( index++, field.getFieldName() ); } if ( field.getElementName() != null ) { item.setText( index++, field.getElementName() ); } else { // Fixup for defect JIRA PDI-607. Make it the same functionality // as the loading of the original XML file. if ( field.getFieldName() != null ) { item.setText( index++, field.getFieldName() ); } else { index++; } } item.setText( index++, field.getContentType().name() ); item.setText( index++, field.getTypeDesc() ); if ( field.getFormat() != null ) { item.setText( index++, field.getFormat() ); } else { index++; } if ( field.getLength() >= 0 ) { item.setText( index++, "" + field.getLength() ); } else { index++; } if ( field.getPrecision() >= 0 ) { item.setText( index++, "" + field.getPrecision() ); } else { index++; } if ( field.getCurrencySymbol() != null ) { item.setText( index++, field.getCurrencySymbol() ); } else { index++; } if ( field.getDecimalSymbol() != null ) { item.setText( index++, field.getDecimalSymbol() ); } else { index++; } if ( field.getGroupingSymbol() != null ) { item.setText( index++, field.getGroupingSymbol() ); } else { index++; } if ( field.getNullString() != null ) { item.setText( index++, field.getNullString() ); } else { index++; } } wFields.optWidth( true ); wStepname.selectAll(); wStepname.setFocus(); } private void cancel() { stepname = null; input.setChanged( backupChanged ); dispose(); } private void getInfo( XMLOutputMeta xmlOutputMeta ) { xmlOutputMeta.setFileName( wFilename.getText() ); xmlOutputMeta.setEncoding( wEncoding.getText() ); xmlOutputMeta.setNameSpace( wNameSpace.getText() ); xmlOutputMeta.setMainElement( wMainElement.getText() ); xmlOutputMeta.setRepeatElement( wRepeatElement.getText() ); xmlOutputMeta.setExtension( wExtension.getText() ); xmlOutputMeta.setDoNotOpenNewFileInit( wDoNotOpenNewFileInit.getSelection() ); xmlOutputMeta.setServletOutput( wServletOutput.getSelection() ); xmlOutputMeta.setSplitEvery( Const.toInt( wSplitEvery.getText(), 0 ) ); xmlOutputMeta.setDateTimeFormat( wDateTimeFormat.getText() ); xmlOutputMeta.setSpecifyFormat( wSpecifyFormat.getSelection() ); xmlOutputMeta.setStepNrInFilename( wAddStepnr.getSelection() ); xmlOutputMeta.setDateInFilename( wAddDate.getSelection() ); xmlOutputMeta.setTimeInFilename( wAddTime.getSelection() ); xmlOutputMeta.setAddToResultFiles( wAddToResult.getSelection() ); xmlOutputMeta.setZipped( wZipped.getSelection() ); xmlOutputMeta.setOmitNullValues( wOmitNullValues.getSelection() ); // Table table = wFields.table; int nrfields = wFields.nrNonEmpty(); xmlOutputMeta.allocate( nrfields ); for ( int i = 0; i < nrfields; i++ ) { XMLField field = new XMLField(); TableItem item = wFields.getNonEmpty( i ); int index = 1; field.setFieldName( item.getText( index++ ) ); field.setElementName( item.getText( index++ ) ); if ( field.getFieldName().equals( field.getElementName() ) ) { field.setElementName( "" ); } String contentType = item.getText( index++ ); if ( !StringUtil.isEmpty( contentType ) ) { field.setContentType( ContentType.valueOf( contentType ) ); } field.setType( item.getText( index++ ) ); field.setFormat( item.getText( index++ ) ); field.setLength( Const.toInt( item.getText( index++ ), -1 ) ); field.setPrecision( Const.toInt( item.getText( index++ ), -1 ) ); field.setCurrencySymbol( item.getText( index++ ) ); field.setDecimalSymbol( item.getText( index++ ) ); field.setGroupingSymbol( item.getText( index++ ) ); field.setNullString( item.getText( index++ ) ); // CHECKSTYLE:Indentation:OFF xmlOutputMeta.getOutputFields()[i] = field; } } private void ok() { if ( Utils.isEmpty( wStepname.getText() ) ) { return; } stepname = wStepname.getText(); // return value getInfo( input ); dispose(); } private void get() { try { RowMetaInterface r = transMeta.getPrevStepFields( stepname ); if ( r != null && !r.isEmpty() ) { TableItemInsertListener listener = new TableItemInsertListener() { public boolean tableItemInserted( TableItem tableItem, ValueMetaInterface v ) { if ( v.isNumber() ) { if ( v.getLength() > 0 ) { int le = v.getLength(); int pr = v.getPrecision(); if ( v.getPrecision() <= 0 ) { pr = 0; } String mask = " "; for ( int m = 0; m < le - pr; m++ ) { mask += "0"; } if ( pr > 0 ) { mask += "."; } for ( int m = 0; m < pr; m++ ) { mask += "0"; } tableItem.setText( 4, mask ); } } return true; } }; BaseStepDialog.getFieldsFromPrevious( r, wFields, 1, new int[] { 1 }, new int[] { 4 }, 6, 7, listener ); } } catch ( KettleException ke ) { new ErrorDialog( shell, BaseMessages.getString( PKG, "System.Dialog.GetFieldsFailed.Title" ), BaseMessages .getString( PKG, "System.Dialog.GetFieldsFailed.Message" ), ke ); } } /** * Sets the output width to minimal width... * */ public void setMinimalWidth() { int nrNonEmptyFields = wFields.nrNonEmpty(); for ( int i = 0; i < nrNonEmptyFields; i++ ) { TableItem item = wFields.getNonEmpty( i ); item.setText( 5, "" ); item.setText( 6, "" ); int type = ValueMeta.getType( item.getText( 2 ) ); switch ( type ) { case ValueMeta.TYPE_STRING: item.setText( 4, "" ); break; case ValueMeta.TYPE_INTEGER: item.setText( 4, "0" ); break; case ValueMeta.TYPE_NUMBER: item.setText( 4, "0.#####" ); break; case ValueMeta.TYPE_DATE: break; default: break; } } wFields.optWidth( true ); } protected void setComboBoxes() { // Something was changed in the row. // final Map<String, Integer> fields = new HashMap<String, Integer>(); // Add the currentMeta fields... fields.putAll( inputFields ); Set<String> keySet = fields.keySet(); List<String> entries = new ArrayList<String>( keySet ); String[] fieldNames = entries.toArray( new String[entries.size()] ); Const.sortStrings( fieldNames ); colinf[0].setComboValues( fieldNames ); } }
[BACKLOG-22745] Get Fields in the XML Output step causes an exception
plugins/xml/core/src/main/java/org/pentaho/di/ui/trans/steps/xmloutput/XMLOutputDialog.java
[BACKLOG-22745] Get Fields in the XML Output step causes an exception
<ide><path>lugins/xml/core/src/main/java/org/pentaho/di/ui/trans/steps/xmloutput/XMLOutputDialog.java <ide> import org.eclipse.swt.widgets.TableItem; <ide> import org.eclipse.swt.widgets.Text; <ide> import org.pentaho.di.core.Const; <del>import org.pentaho.di.core.util.StringUtil; <ide> import org.pentaho.di.core.util.Utils; <ide> import org.pentaho.di.core.Props; <ide> import org.pentaho.di.core.exception.KettleException; <ide> if ( field.getFieldName().equals( field.getElementName() ) ) { <ide> field.setElementName( "" ); <ide> } <del> <del> String contentType = item.getText( index++ ); <del> if ( !StringUtil.isEmpty( contentType ) ) { <del> field.setContentType( ContentType.valueOf( contentType ) ); <del> } <del> <add> field.setContentType( ContentType.valueOf( item.getText( index++ ) ) ); <ide> field.setType( item.getText( index++ ) ); <ide> field.setFormat( item.getText( index++ ) ); <ide> field.setLength( Const.toInt( item.getText( index++ ), -1 ) ); <ide> if ( r != null && !r.isEmpty() ) { <ide> TableItemInsertListener listener = new TableItemInsertListener() { <ide> public boolean tableItemInserted( TableItem tableItem, ValueMetaInterface v ) { <add> tableItem.setText( 3, ContentType.Element.name() ); <ide> if ( v.isNumber() ) { <ide> if ( v.getLength() > 0 ) { <ide> int le = v.getLength();
JavaScript
mit
460f63147bdcea62ea5fd06d623f166555e76500
0
CanalTP/navitia-playground,CanalTP/navitia-playground
// Copyright (c) 2016 Hove // // 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. 'use strict'; // fake includes var response; var storage; var summary; var utils; var d3; var map = {}; var jawg = '9bHKgmlnYBVN0RILGGVn9t5mV1htebujO8fvecasKWZPb1apHmEFD9nOpWLjrYM7'; map.DrawSectionOption = { DRAWSTART: 2, // 10 DRAWEND: 1, // 01 DRAWBOTH: 3, // 11 DRAWNEITHER: 0 // 00 }; map._should_draw_section_start = function(option) { return option & 2;// jshint ignore:line }; map._should_draw_section_end = function(option) { return option & 1;// jshint ignore:line }; map.STARTTEXT = 'Start'; map.ENDTEXT = 'End'; map.makeFeatures = { region: function(context, json) { if (json.shape) { var geoJsonShape = wkt2geojson(json.shape); return map._makePolygon(context, 'region', geoJsonShape, json, '#008ACA'); } return []; }, section: function(context, json, draw_section_option) { var style = {}; if (json.display_informations && json.display_informations.color) { style.color = '#' + json.display_informations.color; } switch (json.type) { case 'street_network': switch (json.mode) { case 'bike': return map._makeBikeStreetInfo(context, 'section', json) .concat(map._makeStopTimesMarker(context, json, style, draw_section_option)); case 'taxi': style = map.taxiStyle; break; case 'car': style = map.carStyle; break; case 'carnopark': style = map.carStyle; break; case 'walking': style = map.walkingStyle; break; case 'ridesharing': style = map.ridesharingStyle; break; } break; case 'transfer': switch (json.transfer_type) { case 'guaranteed': style = map.carStyle; break; case 'extension': style = map.bikeStyle; break; case 'walking': style = map.walkingStyle; break; } break; case 'ridesharing': style = map.ridesharingStyle; break; case 'crow_fly': style = map.crowFlyStyle; break; } if (draw_section_option === undefined) { draw_section_option = map.DrawSectionOption.DRAWBOTH; } return map._makeString(context, 'section', json, style) .concat(map.makeFeatures.vias(context, json)) .concat(map._makeStringViaToPt(context,'section', json, map.crowFlyStyle)) .concat(map._makeStopTimesMarker(context, json, style, draw_section_option)); }, line: function(context, json) { return map._makeString(context, 'line', json, json); }, journey: function(context, json) { if (! ('sections' in json)) { return []; } var bind = function(s, i, array) { var draw_section_option = map.DrawSectionOption.DRAWNEITHER; if ( i === 0) { draw_section_option |= map.DrawSectionOption.DRAWSTART;// jshint ignore:line } if ( i === (array.length -1) ) { draw_section_option |= map.DrawSectionOption.DRAWEND;// jshint ignore:line } return map.makeFeatures.section(context, s, draw_section_option); }; return utils.flatMap(json.sections, bind); }, isochrone: function(context, json) { if (! ('geojson' in json)) { return []; } var color = context.getColorFromMinDuration(json.min_duration); return map._makePolygon(context, 'isochrone', json.geojson, json, color) .concat(map._makeStopTimesMarker(context, json, {}, map.DrawSectionOption.DRAWBOTH)); }, heat_map: function(context, json) { if (! ('heat_matrix' in json)) { return []; } var scale = 0; json.heat_matrix.lines.forEach(function(lines) { lines.duration.forEach(function(duration) { if (duration !== null) { scale = Math.max(duration, scale); } }); }); var local_map = []; json.heat_matrix.lines.forEach(function(lines/*, i*/) { lines.duration.forEach(function(duration, j) { var color; if (duration !== null) { var ratio = duration / scale; color = utils.getColorFromRatio(ratio); } else { color = '#000000'; // for the moment, we don't want to print the null duration squares because // it impacts the performances of the navigator. return; } var rectangle = [ [json.heat_matrix.line_headers[j].cell_lat.max_lat, lines.cell_lon.max_lon], [json.heat_matrix.line_headers[j].cell_lat.min_lat, lines.cell_lon.min_lon] ]; local_map.push(map._makePixel(context, 'heat_map', rectangle, json, color, duration)); }); }); var draw_section_option = map.DrawSectionOption.DRAWBOTH; return local_map.concat(map._makeStopTimesMarker(context, json, {}, draw_section_option)); }, address: function(context, json) { return map._makeMarker(context, 'address', json); }, administrative_region: function(context, json) { return map._makeMarker(context, 'administrative_region', json); }, stop_area: function(context, json) { return map._makeMarker(context, 'stop_area', json); }, stop_point: function(context, json) { return map._makeMarker(context, 'stop_point', json).concat(map._makeMarkerForAccessPoint(context, json)); }, place: function(context, json) { return map._makeMarker(context, 'place', json); }, pt_object: function(context, json) { return map.getFeatures(context, json.embedded_type, json[json.embedded_type]); }, poi: function(context, json) { return map._makeMarker(context, 'poi', json); }, free_floating: function(context, json) { return map._makeMarker(context, 'free_floating', json); }, access_point: function(context, json) { var icon = map._makeAccessPointIcon(json); return map._makeMarker(context, 'access_point', json, null, null, icon); }, connection: function(context, json) { return utils.flatMap([json.origin, json.destination], function(json) { return map._makeMarker(context, 'stop_point', json); }); }, via: function(context, json) { var icon = map._makeAccessPointIcon(json); return map._makeMarker(context, 'via', json, null, null, icon); }, vias: function(context, json) { if (! json.vias) { return []; } var draw_entrance = false; var draw_exit = false; if (json.path[json.path.length - 1].via_uri){ draw_entrance = true; } if (json.path[0].via_uri){ draw_exit = true; } var bind = function(ap) { var new_ap = utils.deepClone(ap || {}); new_ap.draw_entrance = draw_entrance; new_ap.draw_exit = draw_exit; return map.makeFeatures.via(context, new_ap); }; return utils.flatMap(json.vias, bind); }, vehicle_position: function(context, json) { if (! json.vehicle_journey_positions) { return []; } var bind = function(s) { return map.makeFeatures.vehicle_journey_position(context, s); }; return utils.flatMap(json.vehicle_journey_positions, bind); }, vehicle_journey_position: function(context, json) { return map._makeMarker(context, 'vehicle_position', json); }, response: function(context, json) { var key = response.responseCollectionName(json); if (key === null) { return []; } var type = utils.getType(key); if (!(type in map.makeFeatures)) { return []; } var bind = function(s) { return map.makeFeatures[type](context, s); }; return utils.flatMap(json[key].slice().reverse(), bind); }, // TODO: implement when geojson_index is available elevations: function() { return []; } }; map.hasMap = function(context, type, json) { return map.getFeatures(context, type, json).length !== 0 || map.makeElevationGraph[type] instanceof Function; }; map.getFeatures = function(context, type, json) { if (! (map.makeFeatures[type] instanceof Function)) { return []; } if (! (json instanceof Object)) { return []; } try { return map.makeFeatures[type](context, json); } catch (e) { console.log(sprintf('map.makeFeatures[%s] thows an exception:', type));// jshint ignore:line console.log(e);// jshint ignore:line return []; } }; map._makeTileLayers = function() { var copyOSM = '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'; var courtesy = function(name) { return sprintf('%s & %s', copyOSM, name); }; var makeStamenTileLayer = function(name) { return L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/' + name + '/{z}/{x}/{y}.png', { subdomains: 'abcd', attribution: courtesy('<a href="http://maps.stamen.com">Stamen Design</a>'), detectRetina: true }); }; return { 'Bright': L.tileLayer('https://tile.jawg.io/8030075a-bdf3-4b3a-814e-e28ab5880b40/{z}/{x}/{y}.png?access-token=' + jawg, { attribution: courtesy('<a href="https://www.jawg.io" target="_blank">&copy; Jawg</a> - ' + '<a href="https://www.openstreetmap.org" target="_blank">&copy; OpenStreetMap</a>&nbsp;contributors'), detectRetina: true }), 'Dark': L.tileLayer('https://tile.jawg.io/d3fdb780-a086-4c52-ba10-40106332bd0c/{z}/{x}/{y}.png?access-token=' + jawg, { attribution: courtesy('<a href="https://www.jawg.io" target="_blank">&copy; Jawg</a> - ' + '<a href="https://www.openstreetmap.org" target="_blank">&copy; OpenStreetMap</a>&nbsp;contributors'), detectRetina: true }), 'HOT': L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', { maxZoom: 19, attribution: courtesy('<a href="http://hot.openstreetmap.org/">Humanitarian OpenStreetMap Team</a>'), detectRetina: true }), 'Hydda': L.tileLayer('https://{s}.tile.openstreetmap.se/hydda/full/{z}/{x}/{y}.png', { attribution: courtesy('<a href="http://openstreetmap.se/">OpenStreetMap Sweden</a>'), detectRetina: true }), 'Mapnik': L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: copyOSM, detectRetina: true }), 'Terrain': L.tileLayer('https://tile.jawg.io/d3fdb780-a086-4c52-ba10-40106332bd0c/{z}/{x}/{y}.png?access-token=' + jawg , { attribution: courtesy('<a href="https://www.jawg.io" target="_blank">&copy; Jawg</a> - ' + '<a href="https://www.openstreetmap.org" target="_blank">&copy; OpenStreetMap</a>&nbsp;contributors'), detectRetina: true }), 'Toner': makeStamenTileLayer('toner-lite'), 'Watercolor': makeStamenTileLayer('watercolor'), }; }; map._getDefaultLayerName = function() { var saved = storage.getLayer(); if (saved) { return saved; } return 'Bright'; }; map.createMap = function(handle) { var div = $('<div/>'); // setting for default path of images used by leaflet L.Icon.Default.imagePath = 'lib/img/leaflet/dist/images/'; div.addClass('leaflet'); var m = L.map(div.get(0), {renderer: L.canvas()}); var tileLayers = map._makeTileLayers(); tileLayers[map._getDefaultLayerName()].addTo(m); L.control.layers(tileLayers).addTo(m); m.on('baselayerchange', storage.saveLayer); L.control.scale().addTo(m); var bounds = handle(m); // Cleanly destroying the map div.on('npg:remove', function() { m.remove(); }); // GPS location var circle = L.circle([0,0], { radius: 100, }); m.on('locationfound', function(e) { circle.setRadius(e.accuracy / 2) .setStyle({color: '#3388ff'}) .setLatLng(e.latlng) .bindPopup(sprintf('%.5f;%.5f ±%dm', e.latlng.lng, e.latlng.lat, e.accuracy)); }); m.on('locationerror', function(e) { circle.setStyle({color: 'red'}).bindPopup(e.message); }); m.on('unload', function() { m.stopLocate(); }); m.locate({enableHighAccuracy: true, watch: true}); m.on('moveend', function() { storage.saveBounds(m.getBounds()); }); setTimeout(function() { if (bounds) { m.fitBounds(bounds); } else { m.fitWorld(); } circle.addTo(m); // workaround for https://github.com/Leaflet/Leaflet/issues/4978 }, 100); return div; }; map.makeElevationGraph = {}; map.makeElevationGraph.elevations = function(context, json) { var data = json; if (!data) { return; } var div_elevation = $('<div/>'); div_elevation.addClass('elevation'); var height = 100; var margin = 10; var svg = d3.select(div_elevation.get(0)).append('svg') .attr('class', 'elevation-svg') .append('g') .attr('transform', 'translate(20, 20)'); svg.append('text') .attr('class', 'elevation-title') .style('font-weight', 'bold') .style('text-anchor', 'center') .attr('x', '50%') .attr('y', 0) .text('Elevation Graph'); svg.append('text') .attr('class', 'elevation-label') .attr('x', 10) .attr('y', 140) .text('Distance from start (m)'); svg.append('text') .attr('class', 'elevation-label') .attr('x', 10) .attr('y', 0) .text('Height (m)'); // define the line // set the ranges var xScale = d3.scaleLinear().range([0, 1000]); var yScale = d3.scaleLinear().range([height, 0]); // Scale the range of the data xScale.domain(d3.extent(data, function(d) { return d.distance_from_start;})); yScale.domain([d3.min(data, function(d) { return d.elevation; }) / 1.2, d3.max(data, function(d) { return d.elevation; }) * 1.2]); var xAxis = d3.axisBottom(xScale); var yAxis = d3.axisLeft(yScale); var xGrid = xAxis.ticks(5).tickFormat(''); var yGrid = yAxis.ticks(5).tickFormat(''); // add the X gridlines svg.append('g') .attr('class', 'grid x') .attr('transform', sprintf('translate(%s, %s)', margin, height)); // add the Y gridlines svg.append('g') .attr('class', 'grid y') .attr('transform', sprintf('translate(%s, 0)', margin)); // add the valueline path. svg.append('path') .data([data]) .attr('class', 'elevation-line') .attr('transform', sprintf('translate(%s, 0)', margin)); // add the X Axis svg.append('g') .attr('class', 'axis x'); // add the Y Axis svg.append('g') .attr('class', 'axis y'); // to make it responsive var draw_elevation = function (){ // It's impossible(?) to get the div's width, since it's not yet added to DOM... // the default width is set to 1600 as a good guess... var width = div_elevation.width() || 1600; // Scale the range of the data xScale.domain(d3.extent(data, function(d) { return d.distance_from_start;})); xScale.range([0, width - 50]); xGrid.tickSize(-height); svg.select('.grid.x') .call(xGrid); yGrid.tickSize(-(width - 50)); svg.select('.grid.y') .call(yGrid); svg.select('.axis.x') .attr('transform', sprintf('translate(%s, %s)', margin, height)) .call(d3.axisBottom(xScale)); svg.select('.axis.y') .attr('transform', sprintf('translate(%s, 0)', margin)) .call(d3.axisLeft(yScale)); var valueline = d3.line() .x(function(d) { return xScale(d.distance_from_start); }) .y(function(d) { return yScale(d.elevation); }); svg.selectAll('.elevation-line').attr('d', valueline); }; d3.select(window).on('resize', draw_elevation); draw_elevation(); return div_elevation; }; map.getElevationGraph = function(context, type, json) { if (! (map.makeElevationGraph[type] instanceof Function)) { return; } if (! (json instanceof Object)) { return; } try { return map.makeElevationGraph[type](context, json); } catch (e) { console.log(sprintf('map.makeFeatures[%s] thows an exception:', type));// jshint ignore:line console.log(e);// jshint ignore:line } }; map.run = function(context, type, json) { var features = []; var div_elevation; var div = $('<div/>'); // Draw elevations if ((div_elevation = map.getElevationGraph(context, type, json))) { div.append(div_elevation); // TODO: remove return once geojson_index is available return div; } if ((features = map.getFeatures(context, type, json)).length) { var div_map = map.createMap(function(m) { return L.featureGroup(features).addTo(m).getBounds(); }); div.append(div_map); return div; } else { var div_nomap = $('<div/>'); div_nomap.addClass('noMap'); div_nomap.append('No map'); return div_nomap; } }; map._makeMarkerForAccessPoint = function(context, sp) { if (! sp.access_points){ return []; } var bind = function(ap) { ap = utils.deepClone(ap || {}); ap.draw_entrance = ap.is_entrance; ap.draw_exit = ap.is_exit; var icon = map._makeAccessPointIcon(ap); var marker = map._makeMarker(context, 'via', ap, null, null, icon); var style1 = utils.deepClone(map.crowFlyStyle); style1.color = 'white'; style1.weight = 7; style1.opacity = 10; style1.dashArray = '0, 12'; var style2 = utils.deepClone(map.crowFlyStyle); style2.weight = 5; style2.opacity = 10; style2.dashArray = '0, 12'; var from = ap.coord; var to = sp.coord; return marker.concat([ L.polyline([from, to], style1), L.polyline([from, to], style2) ]); }; return utils.flatMap(sp.access_points, bind); }; map._makeAccessPointIcon = function(json) { var iconUrl; if (json.draw_entrance && json.draw_exit) { iconUrl = 'img/pictos/EntranceExitMarker.png'; } else if (json.draw_entrance) { iconUrl = 'img/pictos/EntranceMarker.png'; } else if (json.draw_exit) { iconUrl = 'img/pictos/ExitMarker.png'; } else if (json.is_entrance && json.is_exit) { iconUrl = 'img/pictos/EntranceExitMarker.png'; } else if (json.is_entrance) { iconUrl = 'img/pictos/EntranceMarker.png'; } else if (json.is_exit) { iconUrl = 'img/pictos/ExitMarker.png'; } else { return; } return L.icon({ iconUrl: iconUrl, iconSize: [32, 42.1], iconAnchor: [16, 42.1], // point of the icon which will correspond to marker's location }); }; map._makeMarker = function(context, type, json, style, label, icon) { var lat, lon; var obj = json; switch (type){ case 'stop_date_time': obj = json.stop_point; lat = obj.coord.lat; lon = obj.coord.lon; break; case 'place': lat = json[json.embedded_type].coord.lat; lon = json[json.embedded_type].coord.lon; break; case 'via': lat = json.access_point.coord.lat; lon = json.access_point.coord.lon; break; default: if (!json.coord){ return []; } lat = json.coord.lat; lon = json.coord.lon; } var sum = summary.run(context, type, json); var t = type === 'place' ? json.embedded_type : type; var marker; if (! style) { if (icon) { marker = L.marker([lat, lon], {icon: icon}); } else { marker = L.marker([lat, lon]); } } else { style = utils.deepClone(style || {}); delete style.dashArray; if (! style.color) { style.color = '#000000'; } style.opacity = 1; style.fillColor = 'white'; style.fillOpacity = 1; marker = L.circleMarker([lat, lon], style); marker.setRadius(5); } if (label) { marker.bindTooltip(label, {permanent: true, opacity: 1}); } return [marker.bindPopup(map._makeLink(context, t, obj, sum)[0])]; }; map.bikeStyle = { color: '#a3ab3a', dashArray: '0, 8' }; map.bikeStyleNoCycleLane = { color: '#ed2939', dashArray: '0, 8' }; map.bikeStyleSharedCycleWay = { color: '#ff7b00', dashArray: '0, 8' }; map.bikeStyleDedicatedCycleWay = { color: '#fee832', dashArray: '0, 8' }; map.bikeStyleSeparatedCycleWay = { color: '#006b3e', dashArray: '0, 8' }; map.carStyle = { color: '#c9731d', dashArray: '0, 8' }; map.taxiStyle = { color: '#297e52', dashArray: '0, 8' }; map.walkingStyle = { color: '#298bbc', dashArray: '0, 8' }; map.ridesharingStyle = { color: '#6e3ea8', dashArray: '0, 8' }; map.crowFlyStyle = { color: '#6e3ea8', dashArray: '0, 8' }; map._getCoordFromPlace = function(place) { if (place && place[place.embedded_type] && place[place.embedded_type].coord) { return place[place.embedded_type].coord; } return null; }; map._makeStringViaToPt = function(context, type, json, style) { if (! json.vias || json.vias.length === 0) { return []; } var from; var to; // At the moment, we have only one via in PathItem if (json.path[json.path.length - 1].via_uri){ from = json.vias[0].access_point.coord; to = map._getCoordFromPlace(json.to); } if (json.path[0].via_uri){ from = map._getCoordFromPlace(json.from); to = json.vias[0].access_point.coord; } var style1 = utils.deepClone(style); style1.color = 'white'; style1.weight = 7; style1.opacity = 1; style1.dashArray = '0, 10'; var style2 = utils.deepClone(style); style2.weight = 5; style2.opacity = 1; style2.dashArray = '0, 10'; var sum = summary.run(context, type, json); return [ L.polyline([from, to], style1), L.polyline([from, to], style2).bindPopup(sum) ]; }; map._makeSubGeojson = function(geojson, start, end) { var res = utils.deepClone(geojson); res.coordinates = geojson.coordinates.slice(start, end+1); return res; }; map._pushCycleLaneStyle = function(context, type, json, sub_geojson, street_info, cycle_lane_type_styles, style, line) { var sum = summary.run(context, type, json); if (street_info.cycle_path_type in cycle_lane_type_styles) { sum.append(' (', street_info.cycle_path_type, ')'); cycle_lane_type_styles[street_info.cycle_path_type].weight = 5; cycle_lane_type_styles[street_info.cycle_path_type].opacity = 1; line.push( L.geoJson(sub_geojson, { style: style }), L.geoJson(sub_geojson, { style: cycle_lane_type_styles[street_info.cycle_path_type] }).bindPopup(sum) ); } }; map._makeBikeStreetInfo = function(context, type, json) { var cycleLaneTypeStyles = { 'no_cycle_lane': map.bikeStyleNoCycleLane, 'shared_cycle_way': map.bikeStyleSharedCycleWay, 'separated_cycle_way': map.bikeStyleSeparatedCycleWay, 'dedicated_cycle_way': map.bikeStyleDedicatedCycleWay }; var styleWhite = { color: 'white', dashArray: '0, 8', weight: 7, opacity: 1 }; var line = []; var subGeojson; var newJson; if (json.street_informations && json.street_informations.length && json.geojson && json.geojson.coordinates !== undefined && json.geojson.coordinates.length) { var fromOffset = json.street_informations[0].geojson_offset; for (var idx = 1; idx < json.street_informations.length; idx++) { var streetInfo = json.street_informations[idx - 1]; var offset = json.street_informations[idx].geojson_offset; subGeojson = map._makeSubGeojson(json.geojson, fromOffset, offset); newJson = utils.deepClone(json); newJson.streetInfo = streetInfo; map._pushCycleLaneStyle(context, type, newJson, subGeojson, streetInfo, cycleLaneTypeStyles, styleWhite, line); fromOffset = offset; } subGeojson = map._makeSubGeojson(json.geojson, fromOffset, json.geojson.coordinates.length); newJson = utils.deepClone(json); newJson.streetInfo = json.street_informations[json.street_informations.length-1]; map._pushCycleLaneStyle(context, type, newJson, subGeojson, newJson.streetInfo, cycleLaneTypeStyles, styleWhite, line); } return line; }; map._makeString = function(context, type, json, style) { style = utils.deepClone(style || {}); if (! style.color) { style.color = '#000000'; } if (style.color.match(/^[0-9A-Fa-f]{6}$/)) { style.color = '#' + style.color; } var sum = summary.run(context, type, json); var from = map._getCoordFromPlace(json.from); var to = map._getCoordFromPlace(json.to); var style1 = utils.deepClone(style); style1.color = 'white'; style1.weight = 7; style1.opacity = 1; var style2 = utils.deepClone(style); style2.weight = 5; style2.opacity = 1; if (json.geojson && json.geojson.coordinates.length) { return [ L.geoJson(json.geojson, { style: style1 }), L.geoJson(json.geojson, { style: style2 }).bindPopup(sum) ]; } else if (from && to) { return [ L.polyline([from, to], style1), L.polyline([from, to], style2).bindPopup(sum) ]; } else { return []; } }; map._makeStopTimesMarker = function(context, json, style, draw_section_option) { var stopTimes = json.stop_date_times; var markers = []; if (stopTimes) { // when section is PT stopTimes.forEach(function(st, i) { var label = null; if (i === 0 && map._should_draw_section_start(draw_section_option)) { label = map.STARTTEXT; }else if (i === (stopTimes.length -1 ) && map._should_draw_section_end(draw_section_option)) { label = map.ENDTEXT; } markers = markers.concat(map._makeMarker(context, 'stop_date_time', st, style, label)); }); } else { // when section is Walking var from = json.from; var to = json.to; var label_from = null; var label_to = null; if (from && map._should_draw_section_start(draw_section_option)) { label_from = map.STARTTEXT; markers.push(map._makeMarker(context, 'place', from, style, label_from)[0]); } if (to && map._should_draw_section_end(draw_section_option)) { label_to = map.ENDTEXT; markers.push(map._makeMarker(context, 'place', to, style, label_to)[0]); } } return markers; }; map._makePolygon = function(context, type, geoJsonCoords, json, color) { var sum = summary.run(context, type, json); // TODO use link when navitia has debugged the ticket NAVITIAII-2133 var link = map._makeLink(context, type, json, sum)[0]; return [ L.geoJson(geoJsonCoords, { color: '#555555', opacity: 1, weight: 0.5, fillColor: color, fillOpacity: 0.25 }).bindPopup(link) ]; }; map._makeLink = function(context, type, obj, name) { return context.makeLink(type, obj, name); }; map._makePixel = function(context, type, PolygonCoords, json, color, duration) { var sum = 'not accessible'; if (duration !== null) { sum = sprintf('duration: %s', utils.durationToString(duration)); } return L.rectangle(PolygonCoords, { smoothFactor: 0, color: '#555555', opacity: 0, weight: 0, fillColor: color, fillOpacity: 0.25 }).bindPopup(sum); };
js/map.js
// Copyright (c) 2016 Hove // // 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. 'use strict'; // fake includes var response; var storage; var summary; var utils; var d3; var map = {}; var jawg = '9bHKgmlnYBVN0RILGGVn9t5mV1htebujO8fvecasKWZPb1apHmEFD9nOpWLjrYM7'; map.DrawSectionOption = { DRAWSTART: 2, // 10 DRAWEND: 1, // 01 DRAWBOTH: 3, // 11 DRAWNEITHER: 0 // 00 }; map._should_draw_section_start = function(option) { return option & 2;// jshint ignore:line }; map._should_draw_section_end = function(option) { return option & 1;// jshint ignore:line }; map.STARTTEXT = 'Start'; map.ENDTEXT = 'End'; map.makeFeatures = { region: function(context, json) { if (json.shape) { var geoJsonShape = wkt2geojson(json.shape); return map._makePolygon(context, 'region', geoJsonShape, json, '#008ACA'); } return []; }, section: function(context, json, draw_section_option) { var style = {}; if (json.display_informations && json.display_informations.color) { style.color = '#' + json.display_informations.color; } switch (json.type) { case 'street_network': switch (json.mode) { case 'bike': style = map.bikeStyle; break; case 'taxi': style = map.taxiStyle; break; case 'car': style = map.carStyle; break; case 'carnopark': style = map.carStyle; break; case 'walking': style = map.walkingStyle; break; case 'ridesharing': style = map.ridesharingStyle; break; } break; case 'transfer': switch (json.transfer_type) { case 'guaranteed': style = map.carStyle; break; case 'extension': style = map.bikeStyle; break; case 'walking': style = map.walkingStyle; break; } break; case 'ridesharing': style = map.ridesharingStyle; break; case 'crow_fly': style = map.crowFlyStyle; break; } if (draw_section_option === undefined) { draw_section_option = map.DrawSectionOption.DRAWBOTH; } return map._makeString(context, 'section', json, style) .concat(map.makeFeatures.vias(context, json)) .concat(map._makeStringViaToPt(context,'section', json, map.crowFlyStyle)) .concat(map._makeStopTimesMarker(context, json, style, draw_section_option)); }, line: function(context, json) { return map._makeString(context, 'line', json, json); }, journey: function(context, json) { if (! ('sections' in json)) { return []; } var bind = function(s, i, array) { var draw_section_option = map.DrawSectionOption.DRAWNEITHER; if ( i === 0) { draw_section_option |= map.DrawSectionOption.DRAWSTART;// jshint ignore:line } if ( i === (array.length -1) ) { draw_section_option |= map.DrawSectionOption.DRAWEND;// jshint ignore:line } return map.makeFeatures.section(context, s, draw_section_option); }; return utils.flatMap(json.sections, bind); }, isochrone: function(context, json) { if (! ('geojson' in json)) { return []; } var color = context.getColorFromMinDuration(json.min_duration); return map._makePolygon(context, 'isochrone', json.geojson, json, color) .concat(map._makeStopTimesMarker(context, json, {}, map.DrawSectionOption.DRAWBOTH)); }, heat_map: function(context, json) { if (! ('heat_matrix' in json)) { return []; } var scale = 0; json.heat_matrix.lines.forEach(function(lines) { lines.duration.forEach(function(duration) { if (duration !== null) { scale = Math.max(duration, scale); } }); }); var local_map = []; json.heat_matrix.lines.forEach(function(lines/*, i*/) { lines.duration.forEach(function(duration, j) { var color; if (duration !== null) { var ratio = duration / scale; color = utils.getColorFromRatio(ratio); } else { color = '#000000'; // for the moment, we don't want to print the null duration squares because // it impacts the performances of the navigator. return; } var rectangle = [ [json.heat_matrix.line_headers[j].cell_lat.max_lat, lines.cell_lon.max_lon], [json.heat_matrix.line_headers[j].cell_lat.min_lat, lines.cell_lon.min_lon] ]; local_map.push(map._makePixel(context, 'heat_map', rectangle, json, color, duration)); }); }); var draw_section_option = map.DrawSectionOption.DRAWBOTH; return local_map.concat(map._makeStopTimesMarker(context, json, {}, draw_section_option)); }, address: function(context, json) { return map._makeMarker(context, 'address', json); }, administrative_region: function(context, json) { return map._makeMarker(context, 'administrative_region', json); }, stop_area: function(context, json) { return map._makeMarker(context, 'stop_area', json); }, stop_point: function(context, json) { return map._makeMarker(context, 'stop_point', json).concat(map._makeMarkerForAccessPoint(context, json)); }, place: function(context, json) { return map._makeMarker(context, 'place', json); }, pt_object: function(context, json) { return map.getFeatures(context, json.embedded_type, json[json.embedded_type]); }, poi: function(context, json) { return map._makeMarker(context, 'poi', json); }, free_floating: function(context, json) { return map._makeMarker(context, 'free_floating', json); }, access_point: function(context, json) { var icon = map._makeAccessPointIcon(json); return map._makeMarker(context, 'access_point', json, null, null, icon); }, connection: function(context, json) { return utils.flatMap([json.origin, json.destination], function(json) { return map._makeMarker(context, 'stop_point', json); }); }, via: function(context, json) { var icon = map._makeAccessPointIcon(json); return map._makeMarker(context, 'via', json, null, null, icon); }, vias: function(context, json) { if (! json.vias) { return []; } var draw_entrance = false; var draw_exit = false; if (json.path[json.path.length - 1].via_uri){ draw_entrance = true; } if (json.path[0].via_uri){ draw_exit = true; } var bind = function(ap) { var new_ap = utils.deepClone(ap || {}); new_ap.draw_entrance = draw_entrance; new_ap.draw_exit = draw_exit; return map.makeFeatures.via(context, new_ap); }; return utils.flatMap(json.vias, bind); }, vehicle_position: function(context, json) { if (! json.vehicle_journey_positions) { return []; } var bind = function(s) { return map.makeFeatures.vehicle_journey_position(context, s); }; return utils.flatMap(json.vehicle_journey_positions, bind); }, vehicle_journey_position: function(context, json) { return map._makeMarker(context, 'vehicle_position', json); }, response: function(context, json) { var key = response.responseCollectionName(json); if (key === null) { return []; } var type = utils.getType(key); if (!(type in map.makeFeatures)) { return []; } var bind = function(s) { return map.makeFeatures[type](context, s); }; return utils.flatMap(json[key].slice().reverse(), bind); }, // TODO: implement when geojson_index is available elevations: function() { return []; } }; map.hasMap = function(context, type, json) { return map.getFeatures(context, type, json).length !== 0 || map.makeElevationGraph[type] instanceof Function; }; map.getFeatures = function(context, type, json) { if (! (map.makeFeatures[type] instanceof Function)) { return []; } if (! (json instanceof Object)) { return []; } try { return map.makeFeatures[type](context, json); } catch (e) { console.log(sprintf('map.makeFeatures[%s] thows an exception:', type));// jshint ignore:line console.log(e);// jshint ignore:line return []; } }; map._makeTileLayers = function() { var copyOSM = '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'; var courtesy = function(name) { return sprintf('%s & %s', copyOSM, name); }; var makeStamenTileLayer = function(name) { return L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/' + name + '/{z}/{x}/{y}.png', { subdomains: 'abcd', attribution: courtesy('<a href="http://maps.stamen.com">Stamen Design</a>'), detectRetina: true }); }; return { 'Bright': L.tileLayer('https://tile.jawg.io/8030075a-bdf3-4b3a-814e-e28ab5880b40/{z}/{x}/{y}.png?access-token=' + jawg, { attribution: courtesy('<a href="https://www.jawg.io" target="_blank">&copy; Jawg</a> - ' + '<a href="https://www.openstreetmap.org" target="_blank">&copy; OpenStreetMap</a>&nbsp;contributors'), detectRetina: true }), 'Dark': L.tileLayer('https://tile.jawg.io/d3fdb780-a086-4c52-ba10-40106332bd0c/{z}/{x}/{y}.png?access-token=' + jawg, { attribution: courtesy('<a href="https://www.jawg.io" target="_blank">&copy; Jawg</a> - ' + '<a href="https://www.openstreetmap.org" target="_blank">&copy; OpenStreetMap</a>&nbsp;contributors'), detectRetina: true }), 'HOT': L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', { maxZoom: 19, attribution: courtesy('<a href="http://hot.openstreetmap.org/">Humanitarian OpenStreetMap Team</a>'), detectRetina: true }), 'Hydda': L.tileLayer('https://{s}.tile.openstreetmap.se/hydda/full/{z}/{x}/{y}.png', { attribution: courtesy('<a href="http://openstreetmap.se/">OpenStreetMap Sweden</a>'), detectRetina: true }), 'Mapnik': L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: copyOSM, detectRetina: true }), 'Terrain': L.tileLayer('https://tile.jawg.io/d3fdb780-a086-4c52-ba10-40106332bd0c/{z}/{x}/{y}.png?access-token=' + jawg , { attribution: courtesy('<a href="https://www.jawg.io" target="_blank">&copy; Jawg</a> - ' + '<a href="https://www.openstreetmap.org" target="_blank">&copy; OpenStreetMap</a>&nbsp;contributors'), detectRetina: true }), 'Toner': makeStamenTileLayer('toner-lite'), 'Watercolor': makeStamenTileLayer('watercolor'), }; }; map._getDefaultLayerName = function() { var saved = storage.getLayer(); if (saved) { return saved; } return 'Bright'; }; map.createMap = function(handle) { var div = $('<div/>'); // setting for default path of images used by leaflet L.Icon.Default.imagePath = 'lib/img/leaflet/dist/images/'; div.addClass('leaflet'); var m = L.map(div.get(0), {renderer: L.canvas()}); var tileLayers = map._makeTileLayers(); tileLayers[map._getDefaultLayerName()].addTo(m); L.control.layers(tileLayers).addTo(m); m.on('baselayerchange', storage.saveLayer); L.control.scale().addTo(m); var bounds = handle(m); // Cleanly destroying the map div.on('npg:remove', function() { m.remove(); }); // GPS location var circle = L.circle([0,0], { radius: 100, }); m.on('locationfound', function(e) { circle.setRadius(e.accuracy / 2) .setStyle({color: '#3388ff'}) .setLatLng(e.latlng) .bindPopup(sprintf('%.5f;%.5f ±%dm', e.latlng.lng, e.latlng.lat, e.accuracy)); }); m.on('locationerror', function(e) { circle.setStyle({color: 'red'}).bindPopup(e.message); }); m.on('unload', function() { m.stopLocate(); }); m.locate({enableHighAccuracy: true, watch: true}); m.on('moveend', function() { storage.saveBounds(m.getBounds()); }); setTimeout(function() { if (bounds) { m.fitBounds(bounds); } else { m.fitWorld(); } circle.addTo(m); // workaround for https://github.com/Leaflet/Leaflet/issues/4978 }, 100); return div; }; map.makeElevationGraph = {}; map.makeElevationGraph.elevations = function(context, json) { var data = json; if (!data) { return; } var div_elevation = $('<div/>'); div_elevation.addClass('elevation'); var height = 100; var margin = 10; var svg = d3.select(div_elevation.get(0)).append('svg') .attr('class', 'elevation-svg') .append('g') .attr('transform', 'translate(20, 20)'); svg.append('text') .attr('class', 'elevation-title') .style('font-weight', 'bold') .style('text-anchor', 'center') .attr('x', '50%') .attr('y', 0) .text('Elevation Graph'); svg.append('text') .attr('class', 'elevation-label') .attr('x', 10) .attr('y', 140) .text('Distance from start (m)'); svg.append('text') .attr('class', 'elevation-label') .attr('x', 10) .attr('y', 0) .text('Height (m)'); // define the line // set the ranges var xScale = d3.scaleLinear().range([0, 1000]); var yScale = d3.scaleLinear().range([height, 0]); // Scale the range of the data xScale.domain(d3.extent(data, function(d) { return d.distance_from_start;})); yScale.domain([d3.min(data, function(d) { return d.elevation; }) / 1.2, d3.max(data, function(d) { return d.elevation; }) * 1.2]); var xAxis = d3.axisBottom(xScale); var yAxis = d3.axisLeft(yScale); var xGrid = xAxis.ticks(5).tickFormat(''); var yGrid = yAxis.ticks(5).tickFormat(''); // add the X gridlines svg.append('g') .attr('class', 'grid x') .attr('transform', sprintf('translate(%s, %s)', margin, height)); // add the Y gridlines svg.append('g') .attr('class', 'grid y') .attr('transform', sprintf('translate(%s, 0)', margin)); // add the valueline path. svg.append('path') .data([data]) .attr('class', 'elevation-line') .attr('transform', sprintf('translate(%s, 0)', margin)); // add the X Axis svg.append('g') .attr('class', 'axis x'); // add the Y Axis svg.append('g') .attr('class', 'axis y'); // to make it responsive var draw_elevation = function (){ // It's impossible(?) to get the div's width, since it's not yet added to DOM... // the default width is set to 1600 as a good guess... var width = div_elevation.width() || 1600; // Scale the range of the data xScale.domain(d3.extent(data, function(d) { return d.distance_from_start;})); xScale.range([0, width - 50]); xGrid.tickSize(-height); svg.select('.grid.x') .call(xGrid); yGrid.tickSize(-(width - 50)); svg.select('.grid.y') .call(yGrid); svg.select('.axis.x') .attr('transform', sprintf('translate(%s, %s)', margin, height)) .call(d3.axisBottom(xScale)); svg.select('.axis.y') .attr('transform', sprintf('translate(%s, 0)', margin)) .call(d3.axisLeft(yScale)); var valueline = d3.line() .x(function(d) { return xScale(d.distance_from_start); }) .y(function(d) { return yScale(d.elevation); }); svg.selectAll('.elevation-line').attr('d', valueline); }; d3.select(window).on('resize', draw_elevation); draw_elevation(); return div_elevation; }; map.getElevationGraph = function(context, type, json) { if (! (map.makeElevationGraph[type] instanceof Function)) { return; } if (! (json instanceof Object)) { return; } try { return map.makeElevationGraph[type](context, json); } catch (e) { console.log(sprintf('map.makeFeatures[%s] thows an exception:', type));// jshint ignore:line console.log(e);// jshint ignore:line } }; map.run = function(context, type, json) { var features = []; var div_elevation; var div = $('<div/>'); // Draw elevations if ((div_elevation = map.getElevationGraph(context, type, json))) { div.append(div_elevation); // TODO: remove return once geojson_index is available return div; } if ((features = map.getFeatures(context, type, json)).length) { var div_map = map.createMap(function(m) { return L.featureGroup(features).addTo(m).getBounds(); }); div.append(div_map); return div; } else { var div_nomap = $('<div/>'); div_nomap.addClass('noMap'); div_nomap.append('No map'); return div_nomap; } }; map._makeMarkerForAccessPoint = function(context, sp) { if (! sp.access_points){ return []; } var bind = function(ap) { ap = utils.deepClone(ap || {}); ap.draw_entrance = ap.is_entrance; ap.draw_exit = ap.is_exit; var icon = map._makeAccessPointIcon(ap); var marker = map._makeMarker(context, 'via', ap, null, null, icon); var style1 = utils.deepClone(map.crowFlyStyle); style1.color = 'white'; style1.weight = 7; style1.opacity = 10; style1.dashArray = '0, 12'; var style2 = utils.deepClone(map.crowFlyStyle); style2.weight = 5; style2.opacity = 10; style2.dashArray = '0, 12'; var from = ap.coord; var to = sp.coord; return marker.concat([ L.polyline([from, to], style1), L.polyline([from, to], style2) ]); }; return utils.flatMap(sp.access_points, bind); }; map._makeAccessPointIcon = function(json) { var iconUrl; if (json.draw_entrance && json.draw_exit) { iconUrl = 'img/pictos/EntranceExitMarker.png'; } else if (json.draw_entrance) { iconUrl = 'img/pictos/EntranceMarker.png'; } else if (json.draw_exit) { iconUrl = 'img/pictos/ExitMarker.png'; } else if (json.is_entrance && json.is_exit) { iconUrl = 'img/pictos/EntranceExitMarker.png'; } else if (json.is_entrance) { iconUrl = 'img/pictos/EntranceMarker.png'; } else if (json.is_exit) { iconUrl = 'img/pictos/ExitMarker.png'; } else { return; } return L.icon({ iconUrl: iconUrl, iconSize: [32, 42.1], iconAnchor: [16, 42.1], // point of the icon which will correspond to marker's location }); }; map._makeMarker = function(context, type, json, style, label, icon) { var lat, lon; var obj = json; switch (type){ case 'stop_date_time': obj = json.stop_point; lat = obj.coord.lat; lon = obj.coord.lon; break; case 'place': lat = json[json.embedded_type].coord.lat; lon = json[json.embedded_type].coord.lon; break; case 'via': lat = json.access_point.coord.lat; lon = json.access_point.coord.lon; break; default: if (!json.coord){ return []; } lat = json.coord.lat; lon = json.coord.lon; } var sum = summary.run(context, type, json); var t = type === 'place' ? json.embedded_type : type; var marker; if (! style) { if (icon) { marker = L.marker([lat, lon], {icon: icon}); } else { marker = L.marker([lat, lon]); } } else { style = utils.deepClone(style || {}); delete style.dashArray; if (! style.color) { style.color = '#000000'; } style.opacity = 1; style.fillColor = 'white'; style.fillOpacity = 1; marker = L.circleMarker([lat, lon], style); marker.setRadius(5); } if (label) { marker.bindTooltip(label, {permanent: true, opacity: 1}); } return [marker.bindPopup(map._makeLink(context, t, obj, sum)[0])]; }; map.bikeStyle = { color: '#a3ab3a', dashArray: '0, 8' }; map.carStyle = { color: '#c9731d', dashArray: '0, 8' }; map.taxiStyle = { color: '#297e52', dashArray: '0, 8' }; map.walkingStyle = { color: '#298bbc', dashArray: '0, 8' }; map.ridesharingStyle = { color: '#6e3ea8', dashArray: '0, 8' }; map.crowFlyStyle = { color: '#6e3ea8', dashArray: '0, 8' }; map._getCoordFromPlace = function(place) { if (place && place[place.embedded_type] && place[place.embedded_type].coord) { return place[place.embedded_type].coord; } return null; }; map._makeStringViaToPt = function(context, type, json, style) { if (! json.vias || json.vias.length === 0) { return []; } var from; var to; // At the moment, we have only one via in PathItem if (json.path[json.path.length - 1].via_uri){ from = json.vias[0].access_point.coord; to = map._getCoordFromPlace(json.to); } if (json.path[0].via_uri){ from = map._getCoordFromPlace(json.from); to = json.vias[0].access_point.coord; } var style1 = utils.deepClone(style); style1.color = 'white'; style1.weight = 7; style1.opacity = 1; style1.dashArray = '0, 10'; var style2 = utils.deepClone(style); style2.weight = 5; style2.opacity = 1; style2.dashArray = '0, 10'; var sum = summary.run(context, type, json); return [ L.polyline([from, to], style1), L.polyline([from, to], style2).bindPopup(sum) ]; }; map._makeString = function(context, type, json, style) { style = utils.deepClone(style || {}); if (! style.color) { style.color = '#000000'; } if (style.color.match(/^[0-9A-Fa-f]{6}$/)) { style.color = '#' + style.color; } var sum = summary.run(context, type, json); var from = map._getCoordFromPlace(json.from); var to = map._getCoordFromPlace(json.to); var style1 = utils.deepClone(style); style1.color = 'white'; style1.weight = 7; style1.opacity = 1; var style2 = utils.deepClone(style); style2.weight = 5; style2.opacity = 1; if (json.geojson && json.geojson.coordinates.length) { return [ L.geoJson(json.geojson, { style: style1 }), L.geoJson(json.geojson, { style: style2 }).bindPopup(sum) ]; } else if (from && to) { return [ L.polyline([from, to], style1), L.polyline([from, to], style2).bindPopup(sum) ]; } else { return []; } }; map._makeStopTimesMarker = function(context, json, style, draw_section_option) { var stopTimes = json.stop_date_times; var markers = []; if (stopTimes) { // when section is PT stopTimes.forEach(function(st, i) { var label = null; if (i === 0 && map._should_draw_section_start(draw_section_option)) { label = map.STARTTEXT; }else if (i === (stopTimes.length -1 ) && map._should_draw_section_end(draw_section_option)) { label = map.ENDTEXT; } markers = markers.concat(map._makeMarker(context, 'stop_date_time', st, style, label)); }); } else { // when section is Walking var from = json.from; var to = json.to; var label_from = null; var label_to = null; if (from && map._should_draw_section_start(draw_section_option)) { label_from = map.STARTTEXT; markers.push(map._makeMarker(context, 'place', from, style, label_from)[0]); } if (to && map._should_draw_section_end(draw_section_option)) { label_to = map.ENDTEXT; markers.push(map._makeMarker(context, 'place', to, style, label_to)[0]); } } return markers; }; map._makePolygon = function(context, type, geoJsonCoords, json, color) { var sum = summary.run(context, type, json); // TODO use link when navitia has debugged the ticket NAVITIAII-2133 var link = map._makeLink(context, type, json, sum)[0]; return [ L.geoJson(geoJsonCoords, { color: '#555555', opacity: 1, weight: 0.5, fillColor: color, fillOpacity: 0.25 }).bindPopup(link) ]; }; map._makeLink = function(context, type, obj, name) { return context.makeLink(type, obj, name); }; map._makePixel = function(context, type, PolygonCoords, json, color, duration) { var sum = 'not accessible'; if (duration !== null) { sum = sprintf('duration: %s', utils.durationToString(duration)); } return L.rectangle(PolygonCoords, { smoothFactor: 0, color: '#555555', opacity: 0, weight: 0, fillColor: color, fillOpacity: 0.25 }).bindPopup(sum); };
Revert "Revert "Add bike street information(s)""
js/map.js
Revert "Revert "Add bike street information(s)""
<ide><path>s/map.js <ide> switch (json.type) { <ide> case 'street_network': <ide> switch (json.mode) { <del> case 'bike': style = map.bikeStyle; break; <add> case 'bike': <add> return map._makeBikeStreetInfo(context, 'section', json) <add> .concat(map._makeStopTimesMarker(context, json, style, draw_section_option)); <ide> case 'taxi': style = map.taxiStyle; break; <ide> case 'car': style = map.carStyle; break; <ide> case 'carnopark': style = map.carStyle; break; <ide> }; <ide> <ide> map.bikeStyle = { color: '#a3ab3a', dashArray: '0, 8' }; <add>map.bikeStyleNoCycleLane = { color: '#ed2939', dashArray: '0, 8' }; <add>map.bikeStyleSharedCycleWay = { color: '#ff7b00', dashArray: '0, 8' }; <add>map.bikeStyleDedicatedCycleWay = { color: '#fee832', dashArray: '0, 8' }; <add>map.bikeStyleSeparatedCycleWay = { color: '#006b3e', dashArray: '0, 8' }; <ide> map.carStyle = { color: '#c9731d', dashArray: '0, 8' }; <ide> map.taxiStyle = { color: '#297e52', dashArray: '0, 8' }; <ide> map.walkingStyle = { color: '#298bbc', dashArray: '0, 8' }; <ide> L.polyline([from, to], style1), <ide> L.polyline([from, to], style2).bindPopup(sum) <ide> ]; <add>}; <add> <add>map._makeSubGeojson = function(geojson, start, end) { <add> var res = utils.deepClone(geojson); <add> res.coordinates = geojson.coordinates.slice(start, end+1); <add> return res; <add>}; <add> <add>map._pushCycleLaneStyle = function(context, type, json, sub_geojson, street_info, cycle_lane_type_styles, style, line) { <add> var sum = summary.run(context, type, json); <add> if (street_info.cycle_path_type in cycle_lane_type_styles) { <add> sum.append(' (', street_info.cycle_path_type, ')'); <add> cycle_lane_type_styles[street_info.cycle_path_type].weight = 5; <add> cycle_lane_type_styles[street_info.cycle_path_type].opacity = 1; <add> line.push( <add> L.geoJson(sub_geojson, { style: style }), <add> L.geoJson(sub_geojson, { style: cycle_lane_type_styles[street_info.cycle_path_type] }).bindPopup(sum) <add> ); <add> } <add>}; <add> <add>map._makeBikeStreetInfo = function(context, type, json) { <add> var cycleLaneTypeStyles = { <add> 'no_cycle_lane': map.bikeStyleNoCycleLane, <add> 'shared_cycle_way': map.bikeStyleSharedCycleWay, <add> 'separated_cycle_way': map.bikeStyleSeparatedCycleWay, <add> 'dedicated_cycle_way': map.bikeStyleDedicatedCycleWay <add> }; <add> <add> var styleWhite = { color: 'white', dashArray: '0, 8', weight: 7, opacity: 1 }; <add> <add> var line = []; <add> var subGeojson; <add> var newJson; <add> <add> if (json.street_informations && <add> json.street_informations.length && <add> json.geojson && <add> json.geojson.coordinates !== undefined && <add> json.geojson.coordinates.length) { <add> var fromOffset = json.street_informations[0].geojson_offset; <add> <add> for (var idx = 1; idx < json.street_informations.length; idx++) { <add> var streetInfo = json.street_informations[idx - 1]; <add> var offset = json.street_informations[idx].geojson_offset; <add> <add> subGeojson = map._makeSubGeojson(json.geojson, fromOffset, offset); <add> newJson = utils.deepClone(json); <add> newJson.streetInfo = streetInfo; <add> map._pushCycleLaneStyle(context, type, newJson, subGeojson, streetInfo, cycleLaneTypeStyles, styleWhite, line); <add> fromOffset = offset; <add> } <add> <add> subGeojson = map._makeSubGeojson(json.geojson, fromOffset, json.geojson.coordinates.length); <add> newJson = utils.deepClone(json); <add> newJson.streetInfo = json.street_informations[json.street_informations.length-1]; <add> map._pushCycleLaneStyle(context, type, newJson, subGeojson, newJson.streetInfo, cycleLaneTypeStyles, styleWhite, line); <add> } <add> return line; <ide> }; <ide> <ide> map._makeString = function(context, type, json, style) {
JavaScript
mit
db76a382f7eedc3eb4876bde639b1d4c6f65f389
0
vibertthio/beact,vibertthio/beact,vibertthio/beact
import React, { Component } from 'react'; import { WindowResizeListener } from 'react-window-resize-listener'; import uuid4 from 'uuid/v4'; import axios from 'axios'; import key from 'keymaster'; import styles from '../styles/DrumMachine.css'; import Matrix from './Matrix'; import { Sequencer, Keyboard, changeBPM, presets } from '../utils/Audio'; import Animation, { animationKey2IndexMapping } from '../utils/Animation'; import menu1 from '../assets/images/menu/menu1.svg'; import menu2 from '../assets/images/menu/menu2.svg'; import menu3 from '../assets/images/menu/menu3.svg'; import menu4 from '../assets/images/menu/menu4.svg'; import menu5 from '../assets/images/menu/menu5.svg'; import menu6 from '../assets/images/menu/menu6.svg'; import menu7 from '../assets/images/menu/menu7.svg'; import menu8 from '../assets/images/menu/menu8.svg'; import menu9 from '../assets/images/menu/menu9.svg'; import menu10 from '../assets/images/menu/menu10.svg'; import menu11 from '../assets/images/menu/menu11.svg'; import menuLogo from '../assets/images/logo.png'; import mi1 from '../assets/images/material-icon/ic_menu_white_24dp_2x.png'; import mi2 from '../assets/images/material-icon/ic_close_white_24dp_2x.png'; import mi3 from '../assets/images/material-icon/ic_pause_white_24dp_2x.png'; import mi4 from '../assets/images/material-icon/ic_play_arrow_white_24dp_2x.png'; import mi5 from '../assets/images/material-icon/ic_refresh_white_24dp_2x.png'; import mi6 from '../assets/images/material-icon/ic_shuffle_white_24dp_2x.png'; import narutoW from '../assets/images/material-icon/narutoW.png'; import narutoG from '../assets/images/material-icon/narutoG2.png'; let fadeoutID; let logoID; let keys = ''; keys = new Array(26); for (let i = 0; i < 26; i += 1) { keys[i] = String.fromCharCode(97 + i); } keys = keys.join(', '); /** * DrumMachine */ class DrumMachine extends Component { /** * [constructor description] */ constructor() { super(); const data = []; for (let i = 0; i < 16; i += 1) { data[i] = []; for (let j = 0; j < 8; j += 1) { // data[i][j] = (Math.random() > 0.15) ? 0 : 1; data[i][j] = 0; } } this.state = { data, currentBeat: 0, playing: false, patternLists: [], patternTitle: '', currentPatternId: '', drumNoteChain: [], currentChainElement: '', currentChainElementIndex: 0, currentPlayingChainElement: 0, drumRecords: [], keyRecords: [], recordTitle: '', currentPlayingRecord: [], currentPlayingRecordElement: 0, keyStartTimeCorrection: 0, hidden: true, wait: true, idle: false, currentSample: 'A', narutoBool: false, }; this.setCurrentBeat = this.setCurrentBeat.bind(this); this.recordSequencer = this.recordSequencer.bind(this); this.saveRecord = this.saveRecord.bind(this); this.handleRecordTitleChange = this.handleRecordTitleChange.bind(this); this.storeDrumRecord = this.storeDrumRecord.bind(this); this.storeKeyRecord = this.storeKeyRecord.bind(this); this.playRecord = this.playRecord.bind(this); this.playNextRecordElement = this.playNextRecordElement.bind(this); this.exitPlayRecord = this.exitPlayRecord.bind(this); this.deleteRecord = this.deleteRecord.bind(this); this.handleTitleChange = this.handleTitleChange.bind(this); this.savePattern = this.savePattern.bind(this); this.playPattern = this.playPattern.bind(this); this.editPattern = this.editPattern.bind(this); this.deleteCurrentPattern = this.deleteCurrentPattern.bind(this); this.exitPattern = this.exitPattern.bind(this); this.renderPatterns = this.renderPatterns.bind(this); this.updateChain = this.updateChain.bind(this); this.renderChain = this.renderChain.bind(this); this.setCurrentChainElementAtLast = this.setCurrentChainElementAtLast.bind(this); this.setCurrentChainElementAtHere = this.setCurrentChainElementAtHere.bind(this); this.setCurrentChainElementIndex = this.setCurrentChainElementIndex.bind(this); this.deleteCurrentChainElement = this.deleteCurrentChainElement.bind(this); this.playNextChainElement = this.playNextChainElement.bind(this); this.playChain = this.playChain.bind(this); this.exitChain = this.exitChain.bind(this); this.playDrumAni = this.playDrumAni.bind(this); this.detectKeyboard = this.detectKeyboard.bind(this); this.setSample = this.setSample.bind(this); this.sequencer = new Sequencer( this.state.data, this.setCurrentBeat, this.playNextChainElement, this.storeDrumRecord, this.playNextRecordElement, this.playDrumAni, ); this.keyboard = new Keyboard(this.storeKeyRecord); this.toggleHidden = this.toggleHidden.bind(this); this.hideSpinner = this.hideSpinner.bind(this); this.showDOM = this.showDOM.bind(this); // this.showLogo = this.showLogo.bind(this); this.toggleNarutoBool = this.toggleNarutoBool.bind(this); } /** * [componentDidMount description] */ componentDidMount() { this.detectKeyboard(); this.ani = Animation(); axios.get('/api/patterns') .then((res) => { this.setState({ patternLists: res.data }); }) .catch((err) => { console.log(err); }); axios.get('/api/notes') .then((res) => { this.setState({ drumRecords: res.data }); }) .catch((err) => { console.log(err); }); axios.get('/api/keys') .then((res) => { this.setState({ keyRecords: res.data }); }) .catch((err) => { console.log(err); }); /** * hide loading spinner and wait 3.5s after DOM is loaded. */ const outShowDOM = this.hideSpinner; // const outShowLogo = this.showLogo; /** * [startTimer description] */ function startTimer() { fadeoutID = window.setTimeout(outShowDOM, 3500); } startTimer(); } /** * [setCurrentBeat description] * @param {number} currentBeat */ setCurrentBeat(currentBeat) { this.setState({ currentBeat, }); } /** * [setCurrentChainAtLast description] */ setCurrentChainElementAtLast() { this.sequencer.isPlayingChain = false; this.sequencer.isPlayingRecord = false; this.setState({ currentChainElement: '' }); } /** * [setCurrentChainElementIndex description] * @param {number} id for currentChainElementIndex */ setCurrentChainElementIndex(id) { for (let i = 0; i < this.state.drumNoteChain.length; i += 1) { if (id === this.state.drumNoteChain[i].id) { this.setState({ currentChainElementIndex: i }); return; } } } /** * @param {String} id width of window * [setCurrentChainAtHere description] */ setCurrentChainElementAtHere(id) { this.sequencer.isPlayingChain = false; this.sequencer.isPlayingRecord = false; const drumNoteChain = this.state.drumNoteChain; const data = this.state.data; for (let k = 0; k < drumNoteChain.length; k += 1) { if (drumNoteChain[k].id === id) { for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = drumNoteChain[k].data[i][j]; } } } } this.setState({ currentChainElement: id, data }); this.setCurrentChainElementIndex(id); } /** * @param {String} sample width of window * [deleteRecord description] */ setSample(sample) { this.sequencer.currentSample = sample; this.setState({ currentSample: sample }); } /** * [clearClicked description] * @param {number} i first index * @param {number} j second index */ clearClicked() { const data = this.state.data; let i; let j; for (i = 0; i < 16; i += 1) { for (j = 0; j < 8; j += 1) { data[i][j] = 0; } } this.setState({ data, }); } /** * [clearClicked description] * @param {number} i first index * @param {number} j second index */ randomClicked() { const data = this.state.data; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = (Math.random() > 0.8) ? 1 : 0; } } this.setState({ data, }); } /** * [toggleNarutoBool description] * @param {bool} narutoBool */ toggleNarutoBool() { if (this.state.narutoBool) { this.keyboard.startNormal(); this.ani.startNormal(); } else { this.keyboard.startNaruto(); this.ani.startNaruto(); } this.setState({ narutoBool: !this.state.narutoBool, }); } /** * [handleClick description] * @param {number} i first index * @param {number} j second index */ handleClick(i, j) { const data = this.state.data; data[i][j] = (data[i][j] === 0) ? 1 : 0; this.setState({ data, }); } /** * [handleResize description] * @param {number} w width of window * @param {number} h height of window */ handleResize(w, h) { this.ani.resize(w, h); } /** * [startSequence description] */ startSequencer() { this.sequencer.start(); this.setState({ playing: true, }); if (this.sequencer.recording === true) { this.keyboard.startRecording(); } } /** * [stopSequencer description] */ stopSequencer() { if (this.sequencer.recording !== true) { this.sequencer.stop(); this.setState({ playing: false, currentBeat: 0, }); } } /** * [recordSequencer description] */ recordSequencer() { if (this.state.recordTitle === '') { console.log('Please give your record a title'); } else if (this.sequencer.recording === true) { this.sequencer.stopRecording(); this.keyboard.stopRecording(); this.setState({ playing: false, currentBeat: 0, recordTitle: '', }); this.saveRecord(); console.log('stopRecording'); } else { // countDown 3 seconds console.log('startRecording'); this.sequencer.startRecording(); if (this.state.playing === true) { this.keyboard.startRecording(); } } } /** * @param {object} event width of window * [playPattern description] */ handleRecordTitleChange(event) { this.setState({ recordTitle: event.target.value }); } /** * [saveRecord description] */ saveRecord() { // add title as a paramater (feature) this.sequencer.saveRecord(this.keyboard.saveRecord, this.keyboard.storeRecord, this.state.recordTitle); } /** * @param {Array} records width of window * [storeDrumRecord description] */ storeDrumRecord(records) { this.setState({ drumRecords: records }); } /** * @param {Array} records width of window * [storeKeyRecord description] */ storeKeyRecord(records) { this.setState({ keyRecords: records }); } /** * @param {Array} record width of window * [playRecord description] */ playRecord(record) { this.setState({ hidden: true }); this.sequencer.isPlayingChain = false; this.sequencer.isPlayingRecord = true; this.keyboard.isPlayingRecord = true; this.stopSequencer(); this.exitPattern(); const data = this.state.data; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = record.content[0][i][j]; } } this.setState({ data, currentPlayingRecord: record.content, currentPlayingRecordElement: 0, keyStartTimeCorrection: record.startTime }); for (let i = 0; i < this.state.keyRecords.length; i += 1) { if (this.state.keyRecords[i].id === record.id) { this.startSequencer(); this.keyboard.playRecord(this.state.keyRecords[i], this.ani.triggerKeyAnimation); } } } /** * [exitPlayRecord description] */ exitPlayRecord() { if (this.sequencer.isPlayingRecord === true) { this.sequencer.isPlayingRecord = false; this.keyboard.isPlayingRecord = false; const data = this.state.data; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = 0; } } this.setState({ data, currentPlayingRecord: [], currentPlayingRecordElement: 0 }); this.keyboard.clearSchedule(); this.stopSequencer(); } this.setState({ hidden: false }); } /** * @param {Number} recordId width of window * [deleteRecord description] */ deleteRecord(recordId) { axios.delete(`/api/notes/${recordId}`) .then( axios.get('/api/notes') .then((res) => { this.setState({ drumRecords: res.data }); }) .catch((err) => { console.log(err); }), ) .catch((err) => { console.log(err); }); axios.delete(`/api/keys/${recordId}`) .then( axios.get('/api/keys') .then((res) => { this.setState({ keyRecords: res.data }); }) .catch((err) => { console.log(err); }), ) .catch((err) => { console.log(err); }); console.log(recordId); } /** * [playNextRecordElement description] */ playNextRecordElement() { const data = this.state.data; let stopDrum = false; let num = this.state.currentPlayingRecordElement; num += 1; // we can configure it to no replay mode if (num === this.state.currentPlayingRecord.length) { num = 0; stopDrum = true; this.exitPlayRecord(); } if (stopDrum === false) { for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = this.state.currentPlayingRecord[num][i][j]; } } } this.setState({ currentPlayingRecordElement: num, data }); } /** * @param {object} event width of window * [playPattern description] */ handleTitleChange(event) { this.setState({ patternTitle: event.target.value }); } /** * [savePattern description] */ savePattern() { if (this.state.patternTitle !== '') { axios.post('/api/patterns', { title: this.state.patternTitle, content: this.state.data, id: uuid4(), }) .then( axios.get('/api/patterns') .then((res) => { this.setState({ patternLists: res.data }); }) .catch((err) => { console.log(err); }), ) .catch(err => console.log(err)); this.setState({ patternTitle: '' }); } else { console.log('Please give your pattern a name!'); } } /** * @param {object} pattern width of window * [playPattern description] */ playPattern(pattern) { this.sequencer.isPlayingRecord = false; this.sequencer.isPlayingChain = false; this.stopSequencer(); const data = this.state.data; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = pattern.content[i][j]; } } this.setState({ data, currentPatternId: pattern.id, // eslint-disable-line no-underscore-dangle }); this.startSequencer(); } /** * [editPattern description] */ editPattern() { if (this.state.patternTitle !== '') { axios.put(`/api/patterns/${this.state.currentPatternId}`, { title: this.state.patternTitle, content: this.state.data, }) .then( axios.get('/api/patterns') .then((res) => { this.setState({ patternLists: res.data }); }) .catch((err) => { console.log(err); }), ) .catch(err => console.log(err)); } else { axios.put(`/api/patterns/${this.state.currentPatternId}`, { content: this.state.data, }) .then( axios.get('/api/patterns') .then((res) => { this.setState({ patternLists: res.data }); }) .catch((err) => { console.log(err); }), ) .catch(err => console.log(err)); } } /** * [exitPattern description] */ exitPattern() { if (this.state.currentPatternId !== '') { const data = this.state.data; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = 0; } } this.setState({ currentPatternId: '', data }); this.stopSequencer(); } } /** * [deleteCurrentPattern description] */ deleteCurrentPattern() { if (this.state.currentPatternId !== '') { axios.delete(`/api/patterns/${this.state.currentPatternId}`) .then( axios.get('/api/patterns') .then((res) => { this.setState({ patternLists: res.data }); }) .catch((err) => { console.log(err); }), ) .catch((err) => { console.log(err); }); this.exitPattern(); this.stopSequencer(); } } /** * @param {Number} id width of window * [deletePattern description] */ deletePattern(id) { if (id === this.state.currentPatternId) { this.deleteCurrentPattern(); } else { axios.delete(`/api/patterns/${id}`) .then( axios.get('/api/patterns') .then((res) => { this.setState({ patternLists: res.data }); }) .catch((err) => { console.log(err); }), ) .catch((err) => { console.log(err); }); } } /** * [appendChain description] */ updateChain() { const drumNoteChain = this.state.drumNoteChain; const data = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = this.state.data[i][j]; } } const newChainElement = { id: uuid4(), data }; if (this.state.currentChainElement === '') { drumNoteChain.push(newChainElement); } else { for (let i = 0; i < drumNoteChain.length; i += 1) { if (drumNoteChain[i].id === this.state.currentChainElement) { newChainElement.id = drumNoteChain[i].id; drumNoteChain[i] = newChainElement; } } } this.setState({ drumNoteChain }); } /** * [deleteCurrentChainElement description] */ deleteCurrentChainElement() { if (this.state.currentChainElement !== '') { const drumNoteChain = this.state.drumNoteChain; const newDrumNoteChain = drumNoteChain.filter( element => element.id !== this.state.currentChainElement); drumNoteChain.pop(); for (let k = 0; k < drumNoteChain.length; k += 1) { drumNoteChain[k].id = newDrumNoteChain[k].id; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { drumNoteChain[k].data[i][j] = newDrumNoteChain[k].data[i][j]; } } } this.setState({ drumNoteChain, currentChainElement: '', currentChainElementIndex: 0 }); this.stopSequencer(); this.exitPattern(); } } /** * [playChain description] */ playChain() { if (this.state.drumNoteChain.length > 0) { this.sequencer.isPlayingRecord = false; this.sequencer.isPlayingChain = true; this.stopSequencer(); this.exitPattern(); const data = this.state.data; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = this.state.drumNoteChain[0].data[i][j]; } } this.setState({ data, currentPlayingChainElement: 0 }); this.startSequencer(); } } /** * [exitChain description] */ exitChain() { if (this.sequencer.isPlayingChain === true) { this.sequencer.isPlayingChain = false; const data = this.state.data; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = 0; } } this.stopSequencer(); this.setState({ currentPlayingChainElement: 0, data, currentChainElement: '' }); } } /** * [playNextChainElement description] */ playNextChainElement() { let num = this.state.currentPlayingChainElement; num += 1; // we can configure it to no replay mode if (num === this.state.drumNoteChain.length) { num = 0; } const data = this.state.data; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = this.state.drumNoteChain[num].data[i][j]; } } this.setState({ currentPlayingChainElement: num, data }); } /** * @param {Array} column width of window * [playDrumAni description] */ playDrumAni(column) { for (let i = 0; i < column.length; i += 1) { // this.ani.triggerSequencerAnimation( // animationDrum2IndexMapping[0][column[i]], // ); this.ani.triggerSequencerAnimation(column[i]); } } /** * [detectKeyboard description] */ detectKeyboard() { key(keys, (e, h) => { const index = animationKey2IndexMapping[h.shortcut]; this.ani.triggerKeyAnimation(index); const char = (h.shortcut.charCodeAt(0) - 97).toString(); this.keyboard.currentKey = char; this.keyboard.playKey(); }); // start / stop key('space', () => { if (!this.state.playing) { this.startSequencer(); } else { this.stopSequencer(); } }); // speed key('up', () => { changeBPM(10); }); key('down', () => { changeBPM(-10); }); // change sound bank key('right', () => { this.sequencer.changeSampleSet(true); }); key('left', () => { this.sequencer.changeSampleSet(false); }); // change sequencer animation bank key('shift+right', () => { this.ani.changeSequencerAnimations(true); }); key('shift+left', () => { this.ani.changeSequencerAnimations(false); }); // change key animation/sound bank key('shift+up', () => { this.ani.changeKeyAnimations(true); this.keyboard.changeSampleSet(true); if (this.keyboard.currentSampleIndex === 1) { this.setState({ narutoBool: true }); } else { this.setState({ narutoBool: false }); } }); key('shift+down', () => { this.ani.changeKeyAnimations(false); this.keyboard.changeSampleSet(false); if (this.keyboard.currentSampleIndex === 1) { this.setState({ narutoBool: true }); } else { this.setState({ narutoBool: false }); } }); // loading presets key('1, 2, 3, 4, 5, 6, 7, 8', (e, h) => { const index = h.shortcut.charCodeAt(0) - 49; const data = this.state.data; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = presets[index][i][j]; } } this.setState({ data, }); }); } /** * [hideSpinner description] */ hideSpinner() { const spinner = document.getElementById('spinner'); spinner.classList.add('loaded'); const loadingTitle = document.getElementById('loadingTitle'); loadingTitle.classList.add('loaded'); const logo = document.getElementById('beactLogo'); logo.classList.add('showLogo'); const showLogo = () => { const beactLogo = document.getElementById('beactLogo'); beactLogo.classList.remove('showLogo'); window.clearTimeout(logoID); }; logoID = window.setTimeout(showLogo, 2000); window.clearTimeout(fadeoutID); fadeoutID = window.setTimeout(this.showDOM, 3000); } /** * [showDOM description] */ showDOM() { const rootDiv = document.getElementById('root'); rootDiv.classList.add('fullHeight'); this.setState({ wait: false }); } /** * [toggleHidden description] */ toggleHidden() { this.setState({ hidden: !this.state.hidden, }); } /** * [renderPatterns description] * @return {Element} */ renderPatterns() { const { patternLists } = this.state; return patternLists.map(pattern => ( <div className={styles.renderedLi} key={pattern.id}> <button className={styles.renderedLiTitle} onTouchTap={() => this.playPattern(pattern)}> <span className={styles.listText}>{pattern.title}</span> </button> <button className={styles.renderedListX} onTouchTap={() => this.deletePattern(pattern.id)}> <span className={styles.listXBtn}>X</span> </button> </div>)); } /** * [renderRecords description] * @return {Element} */ renderRecords() { const { drumRecords } = this.state; return drumRecords.map(drumRecord => ( <div className={styles.renderedLi} key={drumRecord.id}> <button className={styles.renderedLiTitle} onTouchTap={() => this.playRecord(drumRecord)}> <span className={styles.listText}>{drumRecord.title}</span> </button> <button className={styles.renderedListX} onTouchTap={() => this.deleteRecord(drumRecord.id)} > <span className={styles.listXBtn}>X</span> </button> </div>)); } /** * [renderChain description] * @return {Element} */ renderChain() { const { drumNoteChain, currentPlayingChainElement, currentChainElement, currentChainElementIndex } = this.state; return drumNoteChain.map((chainElement, i) => ( <div key={chainElement.id} className={styles.chainLi} style={{ color: '#d8b98a' }} onTouchTap={() => this.setCurrentChainElementAtHere(chainElement.id)} > <div className={ `${styles.chainItem} ${(i === currentPlayingChainElement) ? styles.currentPlayingItem : ''}` } > <span className={styles.chainIndex}>{i + 1}{(currentChainElement !== '' && currentChainElementIndex === i) ? 'V' : ''}</span> </div> </div> )); } /** * [render description] * @return {Element} */ render() { const { hidden, wait, playing, narutoBool } = this.state; return ( <div className={(wait === true) ? styles.hideDOM : styles.showDOM}> {(this.sequencer.isPlayingRecord === false) ? <button className={`${styles.icon} ${styles.menuIcon} ${(hidden === true) ? '' : styles.displayHide}`} onTouchTap={() => this.toggleHidden()} > <img src={mi1} alt="menu" /> </button> : <button className={`${styles.icon} ${styles.menuIcon}`} onClick={() => console.log('Exit Playing Record Button clicked')} onTouchTap={() => this.exitPlayRecord()} > <img src={mi2} alt="close" /> </button>} {(playing) ? <button className={`${styles.icon} ${styles.toggleIcon} ${(hidden === true) ? '' : styles.displayHide}`} onTouchTap={() => this.stopSequencer()} > <img src={mi3} alt="pause" /> </button> : <button className={`${styles.icon} ${styles.toggleIcon} ${(hidden === true) ? '' : styles.displayHide}`} onTouchTap={() => this.startSequencer()} > <img src={mi4} alt="play" /> </button>} <button className={ `${styles.icon} ${styles.clearIcon} ${(hidden === true) ? '' : styles.displayHide}` } onTouchTap={() => this.clearClicked()} > <img src={mi5} alt="refresh" /> </button> <button className={ `${styles.icon} ${styles.randomIcon} ${(hidden === true) ? '' : styles.displayHide}` } onTouchTap={() => this.randomClicked()} style={{ color: '#eecdcc' }} > <img src={mi6} alt="shuffle" /> </button> <button className={ `${styles.icon} ${styles.narutoIcon} ${(hidden === true) ? '' : styles.displayHide}` } onTouchTap={() => this.toggleNarutoBool()} > <img src={narutoG} style={{ display: `${narutoBool ? 'block' : 'none'}` }} className={styles.glow} alt="narutoG" /> <img src={narutoW} style={{ display: `${narutoBool ? 'none' : 'block'}` }} alt="narutoW" /> </button> <div className={ `${styles.menu} ${(hidden === true) ? styles.toggleRevMenu : styles.toggleMenu}` } > <div className={styles.colorMenu}> {/* 1 */} <div className={`${styles.row1} ${styles.row}`}> {(this.sequencer.recording === true) ? <div> recording... </div> : <div className={styles.row1BtnWrap}> <button className={styles.row1l} onClick={() => console.log('Start Button clicked')} onTouchTap={() => this.startSequencer()} > <img src={menu1} alt="Start Button" /> </button> <button className={styles.row1r} onClick={() => console.log('Stop Button clicked')} onTouchTap={() => this.stopSequencer()} > <img src={menu2} alt="Stop Button" /> </button> </div>} </div> {/* 2 */} <div className={`${styles.evenrow} ${styles.row}`}> <img src={menu3} alt="Patten Icon" /> </div> {/* 3 */} <div className={`${styles.row3} ${styles.row}`}> <div className={styles.row3l}> <button className={styles.row3lu} onClick={() => console.log('Save New Pattern clicked')} onTouchTap={() => this.savePattern()} > <img src={menu4} alt="Save New Pattern" /> </button> <button className={styles.row3ld} onClick={() => console.log('Exit Pattern clicked')} onTouchTap={() => this.exitPattern()} > <img src={menu9} alt="Exit Pattern" /> </button> </div> <div className={styles.row3m}> <button className={styles.row3mBtn} onClick={() => console.log('update pattern')} onTouchTap={() => this.editPattern()} > <img src={menu8} alt="Update Pattern" /> </button> </div> <div className={styles.row3r}> <div className={styles.row3ru}> <input type="text" className={styles.row3input} value={this.state.patternTitle} onChange={this.handleTitleChange} placeholder="input pattern name..." /> </div> <div className={styles.row3rd}> {this.renderPatterns()} </div> </div> </div> {/* 4 */} <div className={`${styles.evenrow} ${styles.row}`}> <img className={styles.chain} src={menu6} alt="Chain Icon" /> </div> {/* 5 */} <div className={`${styles.row5} ${styles.row}`}> <div className={styles.row5l}> <div className={styles.row5lu}> <button className={styles.row5lul} onClick={() => console.log('Play Chain Button clicked')} onTouchTap={() => this.playChain()} > <img src={menu1} alt="Play Chain Button" /> </button> <button className={styles.row5lur} onClick={() => console.log('Update Chain Button clicked')} onTouchTap={() => this.updateChain()} > <img src={menu7} alt="Update Chain Button" /> </button> </div> <div className={styles.row5ld}> <button className={styles.row5ldl} onClick={() => console.log('Exit Chain Button Chain clicked')} onTouchTap={() => this.exitChain()} > <img src={menu9} alt="Exit Chain Button Chain Index" /> </button> <button className={styles.row5ldr} onClick={() => console.log('Delete Current Chain Element Button clicked')} onTouchTap={() => this.deleteCurrentChainElement()} > <img src={menu5} alt="Delete Current Chain Element Button" /> </button> </div> </div> <div className={styles.row5r}> {(this.state.drumNoteChain.length === 0) ? <div>HEAD</div> : this.renderChain()} <div className={styles.chainLi} style={{ color: '#d8b98a' }} onTouchTap={() => this.setCurrentChainElementAtLast()} > + </div> </div> </div> {/* 6 */} <div className={`${styles.evenrow} ${styles.row}`}> <img src={menu10} alt="Record Icon" /> </div> {/* 7 */} <div className={`${styles.row7} ${styles.row}`}> <div className={styles.row7l}> <button className={ `${styles.row7lbtn} ${(this.sequencer.recording === true) ? styles.recordingBtn : ''}`} onClick={() => console.log('Record Button clicked')} onTouchTap={() => this.recordSequencer()} > <img src={menu11} alt="Record Button" /> </button> </div> <div className={ `${styles.row3r} ${(this.sequencer.recording === true) ? styles.displayHide : ''}`} > <div className={styles.row3ru}> <input type="text" className={styles.row3input} value={this.state.recordTitle} onChange={this.handleRecordTitleChange} placeholder="input record name..." /> </div> <div className={styles.row3rd}> {this.renderRecords()} </div> </div> </div> {/* 8 */} <div className={`${styles.evenrow} ${styles.row}`}> <span>Beact</span> </div> {/* 9 */} <div className={`${styles.row9} ${styles.row}`}> <span>by Vibert, Joey, Scya, 2017</span> </div> </div> </div> <button className={ `${styles.mask} ${(hidden === false ? styles.showMask : styles.hideMask)}`} onClick={() => this.toggleHidden()} > <img src={menuLogo} alt="BEACT" className={styles.menuLogo} /> </button> <Matrix data={this.state.data} playing={this.state.playing} currentBeat={this.state.currentBeat} onClick={(i, j) => this.handleClick(i, j)} /> <div className={styles.animation} id="animation" /> <WindowResizeListener onResize={w => this.handleResize(w.windowWidth, w.windowHeight)} /> <div> <input type="text" id="one" onKeyPress={this.detectKeyboard} /> </div> </div> ); } } export default DrumMachine;
src/components/DrumMachine.js
import React, { Component } from 'react'; import { WindowResizeListener } from 'react-window-resize-listener'; import uuid4 from 'uuid/v4'; import axios from 'axios'; import key from 'keymaster'; import styles from '../styles/DrumMachine.css'; import Matrix from './Matrix'; import { Sequencer, Keyboard, changeBPM, presets } from '../utils/Audio'; import Animation, { animationKey2IndexMapping } from '../utils/Animation'; import menu1 from '../assets/images/menu/menu1.svg'; import menu2 from '../assets/images/menu/menu2.svg'; import menu3 from '../assets/images/menu/menu3.svg'; import menu4 from '../assets/images/menu/menu4.svg'; import menu5 from '../assets/images/menu/menu5.svg'; import menu6 from '../assets/images/menu/menu6.svg'; import menu7 from '../assets/images/menu/menu7.svg'; import menu8 from '../assets/images/menu/menu8.svg'; import menu9 from '../assets/images/menu/menu9.svg'; import menu10 from '../assets/images/menu/menu10.svg'; import menu11 from '../assets/images/menu/menu11.svg'; import menuLogo from '../assets/images/logo.png'; import mi1 from '../assets/images/material-icon/ic_menu_white_24dp_2x.png'; import mi2 from '../assets/images/material-icon/ic_close_white_24dp_2x.png'; import mi3 from '../assets/images/material-icon/ic_pause_white_24dp_2x.png'; import mi4 from '../assets/images/material-icon/ic_play_arrow_white_24dp_2x.png'; import mi5 from '../assets/images/material-icon/ic_refresh_white_24dp_2x.png'; import mi6 from '../assets/images/material-icon/ic_shuffle_white_24dp_2x.png'; import narutoW from '../assets/images/material-icon/narutoW.png'; import narutoG from '../assets/images/material-icon/narutoG2.png'; let fadeoutID; let logoID; let keys = ''; keys = new Array(26); for (let i = 0; i < 26; i += 1) { keys[i] = String.fromCharCode(97 + i); } keys = keys.join(', '); /** * DrumMachine */ class DrumMachine extends Component { /** * [constructor description] */ constructor() { super(); const data = []; for (let i = 0; i < 16; i += 1) { data[i] = []; for (let j = 0; j < 8; j += 1) { // data[i][j] = (Math.random() > 0.15) ? 0 : 1; data[i][j] = 0; } } this.state = { data, currentBeat: 0, playing: false, patternLists: [], patternTitle: '', currentPatternId: '', drumNoteChain: [], currentChainElement: '', currentChainElementIndex: 0, currentPlayingChainElement: 0, drumRecords: [], keyRecords: [], recordTitle: '', currentPlayingRecord: [], currentPlayingRecordElement: 0, keyStartTimeCorrection: 0, hidden: true, wait: true, idle: false, currentSample: 'A', narutoBool: false, }; this.setCurrentBeat = this.setCurrentBeat.bind(this); this.recordSequencer = this.recordSequencer.bind(this); this.saveRecord = this.saveRecord.bind(this); this.handleRecordTitleChange = this.handleRecordTitleChange.bind(this); this.storeDrumRecord = this.storeDrumRecord.bind(this); this.storeKeyRecord = this.storeKeyRecord.bind(this); this.playRecord = this.playRecord.bind(this); this.playNextRecordElement = this.playNextRecordElement.bind(this); this.exitPlayRecord = this.exitPlayRecord.bind(this); this.deleteRecord = this.deleteRecord.bind(this); this.handleTitleChange = this.handleTitleChange.bind(this); this.savePattern = this.savePattern.bind(this); this.playPattern = this.playPattern.bind(this); this.editPattern = this.editPattern.bind(this); this.deleteCurrentPattern = this.deleteCurrentPattern.bind(this); this.exitPattern = this.exitPattern.bind(this); this.renderPatterns = this.renderPatterns.bind(this); this.updateChain = this.updateChain.bind(this); this.renderChain = this.renderChain.bind(this); this.setCurrentChainElementAtLast = this.setCurrentChainElementAtLast.bind(this); this.setCurrentChainElementAtHere = this.setCurrentChainElementAtHere.bind(this); this.setCurrentChainElementIndex = this.setCurrentChainElementIndex.bind(this); this.deleteCurrentChainElement = this.deleteCurrentChainElement.bind(this); this.playNextChainElement = this.playNextChainElement.bind(this); this.playChain = this.playChain.bind(this); this.exitChain = this.exitChain.bind(this); this.playDrumAni = this.playDrumAni.bind(this); this.detectKeyboard = this.detectKeyboard.bind(this); this.setSample = this.setSample.bind(this); this.sequencer = new Sequencer( this.state.data, this.setCurrentBeat, this.playNextChainElement, this.storeDrumRecord, this.playNextRecordElement, this.playDrumAni, ); this.keyboard = new Keyboard(this.storeKeyRecord); this.toggleHidden = this.toggleHidden.bind(this); this.hideSpinner = this.hideSpinner.bind(this); this.showDOM = this.showDOM.bind(this); // this.showLogo = this.showLogo.bind(this); this.toggleNarutoBool = this.toggleNarutoBool.bind(this); } /** * [componentDidMount description] */ componentDidMount() { this.detectKeyboard(); this.ani = Animation(); axios.get('/api/patterns') .then((res) => { this.setState({ patternLists: res.data }); }) .catch((err) => { console.log(err); }); axios.get('/api/notes') .then((res) => { this.setState({ drumRecords: res.data }); }) .catch((err) => { console.log(err); }); axios.get('/api/keys') .then((res) => { this.setState({ keyRecords: res.data }); }) .catch((err) => { console.log(err); }); /** * hide loading spinner and wait 3.5s after DOM is loaded. */ const outShowDOM = this.hideSpinner; // const outShowLogo = this.showLogo; /** * [startTimer description] */ function startTimer() { fadeoutID = window.setTimeout(outShowDOM, 3500); } startTimer(); } /** * [setCurrentBeat description] * @param {number} currentBeat */ setCurrentBeat(currentBeat) { this.setState({ currentBeat, }); } /** * [setCurrentChainAtLast description] */ setCurrentChainElementAtLast() { this.sequencer.isPlayingChain = false; this.sequencer.isPlayingRecord = false; this.setState({ currentChainElement: '' }); } /** * [setCurrentChainElementIndex description] * @param {number} id for currentChainElementIndex */ setCurrentChainElementIndex(id) { for (let i = 0; i < this.state.drumNoteChain.length; i += 1) { if (id === this.state.drumNoteChain[i].id) { this.setState({ currentChainElementIndex: i }); return; } } } /** * @param {String} id width of window * [setCurrentChainAtHere description] */ setCurrentChainElementAtHere(id) { this.sequencer.isPlayingChain = false; this.sequencer.isPlayingRecord = false; const drumNoteChain = this.state.drumNoteChain; const data = this.state.data; for (let k = 0; k < drumNoteChain.length; k += 1) { if (drumNoteChain[k].id === id) { for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = drumNoteChain[k].data[i][j]; } } } } this.setState({ currentChainElement: id, data }); this.setCurrentChainElementIndex(id); } /** * @param {String} sample width of window * [deleteRecord description] */ setSample(sample) { this.sequencer.currentSample = sample; this.setState({ currentSample: sample }); } /** * [clearClicked description] * @param {number} i first index * @param {number} j second index */ clearClicked() { const data = this.state.data; let i; let j; for (i = 0; i < 16; i += 1) { for (j = 0; j < 8; j += 1) { data[i][j] = 0; } } this.setState({ data, }); } /** * [clearClicked description] * @param {number} i first index * @param {number} j second index */ randomClicked() { const data = this.state.data; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = (Math.random() > 0.8) ? 1 : 0; } } this.setState({ data, }); } /** * [toggleNarutoBool description] * @param {bool} narutoBool */ toggleNarutoBool() { if (this.state.narutoBool) { this.keyboard.startNormal(); this.ani.startNormal(); } else { this.keyboard.startNaruto(); this.ani.startNaruto(); } this.setState({ narutoBool: !this.state.narutoBool, }); } /** * [handleClick description] * @param {number} i first index * @param {number} j second index */ handleClick(i, j) { const data = this.state.data; data[i][j] = (data[i][j] === 0) ? 1 : 0; this.setState({ data, }); } /** * [handleResize description] * @param {number} w width of window * @param {number} h height of window */ handleResize(w, h) { this.ani.resize(w, h); } /** * [startSequence description] */ startSequencer() { this.sequencer.start(); this.setState({ playing: true, }); if (this.sequencer.recording === true) { this.keyboard.startRecording(); } } /** * [stopSequencer description] */ stopSequencer() { if (this.sequencer.recording !== true) { this.sequencer.stop(); this.setState({ playing: false, currentBeat: 0, }); } } /** * [recordSequencer description] */ recordSequencer() { if (this.state.recordTitle === '') { console.log('Please give your record a title'); } else if (this.sequencer.recording === true) { this.sequencer.stopRecording(); this.keyboard.stopRecording(); this.setState({ playing: false, currentBeat: 0, recordTitle: '', }); this.saveRecord(); console.log('stopRecording'); } else { // countDown 3 seconds console.log('startRecording'); this.sequencer.startRecording(); if (this.state.playing === true) { this.keyboard.startRecording(); } } } /** * @param {object} event width of window * [playPattern description] */ handleRecordTitleChange(event) { this.setState({ recordTitle: event.target.value }); } /** * [saveRecord description] */ saveRecord() { // add title as a paramater (feature) this.sequencer.saveRecord(this.keyboard.saveRecord, this.keyboard.storeRecord, this.state.recordTitle); } /** * @param {Array} records width of window * [storeDrumRecord description] */ storeDrumRecord(records) { this.setState({ drumRecords: records }); } /** * @param {Array} records width of window * [storeKeyRecord description] */ storeKeyRecord(records) { this.setState({ keyRecords: records }); } /** * @param {Array} record width of window * [playRecord description] */ playRecord(record) { this.setState({ hidden: true }); this.sequencer.isPlayingChain = false; this.sequencer.isPlayingRecord = true; this.keyboard.isPlayingRecord = true; this.stopSequencer(); this.exitPattern(); const data = this.state.data; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = record.content[0][i][j]; } } this.setState({ data, currentPlayingRecord: record.content, currentPlayingRecordElement: 0, keyStartTimeCorrection: record.startTime }); for (let i = 0; i < this.state.keyRecords.length; i += 1) { if (this.state.keyRecords[i].id === record.id) { this.startSequencer(); this.keyboard.playRecord(this.state.keyRecords[i], this.ani.triggerKeyAnimation); } } } /** * [exitPlayRecord description] */ exitPlayRecord() { if (this.sequencer.isPlayingRecord === true) { this.sequencer.isPlayingRecord = false; this.keyboard.isPlayingRecord = false; const data = this.state.data; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = 0; } } this.setState({ data, currentPlayingRecord: [], currentPlayingRecordElement: 0 }); this.keyboard.clearSchedule(); this.stopSequencer(); } this.setState({ hidden: false }); } /** * @param {Number} recordId width of window * [deleteRecord description] */ deleteRecord(recordId) { axios.delete(`/api/notes/${recordId}`) .then( axios.get('/api/notes') .then((res) => { this.setState({ drumRecords: res.data }); }) .catch((err) => { console.log(err); }), ) .catch((err) => { console.log(err); }); axios.delete(`/api/keys/${recordId}`) .then( axios.get('/api/keys') .then((res) => { this.setState({ keyRecords: res.data }); }) .catch((err) => { console.log(err); }), ) .catch((err) => { console.log(err); }); console.log(recordId); } /** * [playNextRecordElement description] */ playNextRecordElement() { const data = this.state.data; let stopDrum = false; let num = this.state.currentPlayingRecordElement; num += 1; // we can configure it to no replay mode if (num === this.state.currentPlayingRecord.length) { num = 0; stopDrum = true; this.exitPlayRecord(); } if (stopDrum === false) { for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = this.state.currentPlayingRecord[num][i][j]; } } } this.setState({ currentPlayingRecordElement: num, data }); } /** * @param {object} event width of window * [playPattern description] */ handleTitleChange(event) { this.setState({ patternTitle: event.target.value }); } /** * [savePattern description] */ savePattern() { if (this.state.patternTitle !== '') { axios.post('/api/patterns', { title: this.state.patternTitle, content: this.state.data, id: uuid4(), }) .then( axios.get('/api/patterns') .then((res) => { this.setState({ patternLists: res.data }); }) .catch((err) => { console.log(err); }), ) .catch(err => console.log(err)); this.setState({ patternTitle: '' }); } else { console.log('Please give your pattern a name!'); } } /** * @param {object} pattern width of window * [playPattern description] */ playPattern(pattern) { this.sequencer.isPlayingRecord = false; this.sequencer.isPlayingChain = false; this.stopSequencer(); const data = this.state.data; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = pattern.content[i][j]; } } this.setState({ data, currentPatternId: pattern.id, // eslint-disable-line no-underscore-dangle }); this.startSequencer(); } /** * [editPattern description] */ editPattern() { if (this.state.patternTitle !== '') { axios.put(`/api/patterns/${this.state.currentPatternId}`, { title: this.state.patternTitle, content: this.state.data, }) .then( axios.get('/api/patterns') .then((res) => { this.setState({ patternLists: res.data }); }) .catch((err) => { console.log(err); }), ) .catch(err => console.log(err)); } else { axios.put(`/api/patterns/${this.state.currentPatternId}`, { content: this.state.data, }) .then( axios.get('/api/patterns') .then((res) => { this.setState({ patternLists: res.data }); }) .catch((err) => { console.log(err); }), ) .catch(err => console.log(err)); } } /** * [exitPattern description] */ exitPattern() { if (this.state.currentPatternId !== '') { const data = this.state.data; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = 0; } } this.setState({ currentPatternId: '', data }); this.stopSequencer(); } } /** * [deleteCurrentPattern description] */ deleteCurrentPattern() { if (this.state.currentPatternId !== '') { axios.delete(`/api/patterns/${this.state.currentPatternId}`) .then( axios.get('/api/patterns') .then((res) => { this.setState({ patternLists: res.data }); }) .catch((err) => { console.log(err); }), ) .catch((err) => { console.log(err); }); this.exitPattern(); this.stopSequencer(); } } /** * @param {Number} id width of window * [deletePattern description] */ deletePattern(id) { if (id === this.state.currentPatternId) { this.deleteCurrentPattern(); } else { axios.delete(`/api/patterns/${id}`) .then( axios.get('/api/patterns') .then((res) => { this.setState({ patternLists: res.data }); }) .catch((err) => { console.log(err); }), ) .catch((err) => { console.log(err); }); } } /** * [appendChain description] */ updateChain() { const drumNoteChain = this.state.drumNoteChain; const data = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = this.state.data[i][j]; } } const newChainElement = { id: uuid4(), data }; if (this.state.currentChainElement === '') { drumNoteChain.push(newChainElement); } else { for (let i = 0; i < drumNoteChain.length; i += 1) { if (drumNoteChain[i].id === this.state.currentChainElement) { newChainElement.id = drumNoteChain[i].id; drumNoteChain[i] = newChainElement; } } } this.setState({ drumNoteChain }); } /** * [deleteCurrentChainElement description] */ deleteCurrentChainElement() { if (this.state.currentChainElement !== '') { const drumNoteChain = this.state.drumNoteChain; const newDrumNoteChain = drumNoteChain.filter( element => element.id !== this.state.currentChainElement); drumNoteChain.pop(); for (let k = 0; k < drumNoteChain.length; k += 1) { drumNoteChain[k].id = newDrumNoteChain[k].id; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { drumNoteChain[k].data[i][j] = newDrumNoteChain[k].data[i][j]; } } } this.setState({ drumNoteChain, currentChainElement: '', currentChainElementIndex: 0 }); this.stopSequencer(); this.exitPattern(); } } /** * [playChain description] */ playChain() { if (this.state.drumNoteChain.length > 0) { this.sequencer.isPlayingRecord = false; this.sequencer.isPlayingChain = true; this.stopSequencer(); this.exitPattern(); const data = this.state.data; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = this.state.drumNoteChain[0].data[i][j]; } } this.setState({ data, currentPlayingChainElement: 0 }); this.startSequencer(); } } /** * [exitChain description] */ exitChain() { if (this.sequencer.isPlayingChain === true) { this.sequencer.isPlayingChain = false; const data = this.state.data; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = 0; } } this.stopSequencer(); this.setState({ currentPlayingChainElement: 0, data, currentChainElement: '' }); } } /** * [playNextChainElement description] */ playNextChainElement() { let num = this.state.currentPlayingChainElement; num += 1; // we can configure it to no replay mode if (num === this.state.drumNoteChain.length) { num = 0; } const data = this.state.data; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = this.state.drumNoteChain[num].data[i][j]; } } this.setState({ currentPlayingChainElement: num, data }); } /** * @param {Array} column width of window * [playDrumAni description] */ playDrumAni(column) { for (let i = 0; i < column.length; i += 1) { // this.ani.triggerSequencerAnimation( // animationDrum2IndexMapping[0][column[i]], // ); this.ani.triggerSequencerAnimation(column[i]); } } /** * [detectKeyboard description] */ detectKeyboard() { key(keys, (e, h) => { const index = animationKey2IndexMapping[h.shortcut]; this.ani.triggerKeyAnimation(index); const char = (h.shortcut.charCodeAt(0) - 97).toString(); this.keyboard.currentKey = char; this.keyboard.playKey(); }); // start / stop key('space', () => { if (!this.state.playing) { this.startSequencer(); } else { this.stopSequencer(); } }); // speed key('up', () => { changeBPM(10); }); key('down', () => { changeBPM(-10); }); // change sound bank key('right', () => { this.sequencer.changeSampleSet(true); }); key('left', () => { this.sequencer.changeSampleSet(false); }); // change sequencer animation bank key('shift+right', () => { this.ani.changeSequencerAnimations(true); }); key('shift+left', () => { this.ani.changeSequencerAnimations(false); }); // change key animation/sound bank key('shift+up', () => { this.ani.changeKeyAnimations(true); this.keyboard.changeSampleSet(true); if (this.keyboard.currentSampleIndex === 1) { this.setState({ narutoBool: true }); } else { this.setState({ narutoBool: false }); } }); key('shift+down', () => { this.ani.changeKeyAnimations(false); this.keyboard.changeSampleSet(false); if (this.keyboard.currentSampleIndex === 1) { this.setState({ narutoBool: true }); } else { this.setState({ narutoBool: false }); } }); // loading presets key('1, 2, 3, 4, 5, 6, 7, 8', (e, h) => { const index = h.shortcut.charCodeAt(0) - 49; const data = this.state.data; for (let i = 0; i < 16; i += 1) { for (let j = 0; j < 8; j += 1) { data[i][j] = presets[index][i][j]; } } this.setState({ data, }); }); } /** * [hideSpinner description] */ hideSpinner() { const spinner = document.getElementById('spinner'); spinner.classList.add('loaded'); const loadingTitle = document.getElementById('loadingTitle'); loadingTitle.classList.add('loaded'); const logo = document.getElementById('beactLogo'); logo.classList.add('showLogo'); const showLogo = () => { const beactLogo = document.getElementById('beactLogo'); beactLogo.classList.remove('showLogo'); window.clearTimeout(logoID); }; logoID = window.setTimeout(showLogo, 2000); window.clearTimeout(fadeoutID); fadeoutID = window.setTimeout(this.showDOM, 3000); } /** * [showDOM description] */ showDOM() { const rootDiv = document.getElementById('root'); rootDiv.classList.add('fullHeight'); this.setState({ wait: false }); } /** * [toggleHidden description] */ toggleHidden() { this.setState({ hidden: !this.state.hidden, }); } /** * [renderPatterns description] * @return {Element} */ renderPatterns() { const { patternLists } = this.state; return patternLists.map(pattern => ( <div className={styles.renderedLi} key={pattern.id}> <button className={styles.renderedLiTitle} onTouchTap={() => this.playPattern(pattern)}> <span className={styles.listText}>{pattern.title}</span> </button> <button className={styles.renderedListX} onTouchTap={() => this.deletePattern(pattern.id)}> <span className={styles.listXBtn}>X</span> </button> </div>)); } /** * [renderRecords description] * @return {Element} */ renderRecords() { const { drumRecords } = this.state; return drumRecords.map(drumRecord => ( <div className={styles.renderedLi} key={drumRecord.id}> <button className={styles.renderedLiTitle} onTouchTap={() => this.playRecord(drumRecord)}> <span className={styles.listText}>{drumRecord.title}</span> </button> <button className={styles.renderedListX} onTouchTap={() => this.deleteRecord(drumRecord.id)} > <span className={styles.listXBtn}>X</span> </button> </div>)); } /** * [renderChain description] * @return {Element} */ renderChain() { const { drumNoteChain, currentPlayingChainElement, currentChainElement, currentChainElementIndex } = this.state; return drumNoteChain.map((chainElement, i) => ( <div key={chainElement.id} className={styles.chainLi} style={{ color: '#d8b98a' }} onTouchTap={() => this.setCurrentChainElementAtHere(chainElement.id)} > <div className={ `${styles.chainItem} ${(i === currentPlayingChainElement) ? styles.currentPlayingItem : ''}` } > <span className={styles.chainIndex}>{i + 1}{(currentChainElement !== '' && currentChainElementIndex === i) ? 'V' : ''}</span> </div> </div> )); } /** * [render description] * @return {Element} */ render() { const { hidden, wait, playing, narutoBool } = this.state; return ( <div className={(wait === true) ? styles.hideDOM : styles.showDOM}> {(this.sequencer.isPlayingRecord === false) ? <button className={`${styles.icon} ${styles.menuIcon} ${(hidden === true) ? '' : styles.displayHide}`} onTouchTap={() => this.toggleHidden()} > <img src={mi1} alt="menu" /> </button> : <button className={`${styles.icon} ${styles.menuIcon}`} onClick={() => console.log('Exit Playing Record Button clicked')} onTouchTap={() => this.exitPlayRecord()} > <img src={mi2} alt="close" /> </button>} {(playing) ? <button className={`${styles.icon} ${styles.toggleIcon} ${(hidden === true) ? '' : styles.displayHide}`} onTouchTap={() => this.stopSequencer()} > <img src={mi3} alt="pause" /> </button> : <button className={`${styles.icon} ${styles.toggleIcon} ${(hidden === true) ? '' : styles.displayHide}`} onTouchTap={() => this.startSequencer()} > <img src={mi4} alt="play" /> </button>} <button className={ `${styles.icon} ${styles.clearIcon} ${(hidden === true) ? '' : styles.displayHide}` } onTouchTap={() => this.clearClicked()} > <img src={mi5} alt="refresh" /> </button> <button className={ `${styles.icon} ${styles.randomIcon} ${(hidden === true) ? '' : styles.displayHide}` } onTouchTap={() => this.randomClicked()} style={{ color: '#eecdcc' }} > <img src={mi6} alt="shuffle" /> </button> <button className={ `${styles.icon} ${styles.narutoIcon} ${(hidden === true) ? '' : styles.displayHide}` } onTouchTap={() => this.toggleNarutoBool()} > {narutoBool ? <img src={narutoG} className={styles.glow} alt="narutoG" /> : null} {narutoBool ? null : <img src={narutoW} alt="narutoW" />} </button> <div className={ `${styles.menu} ${(hidden === true) ? styles.toggleRevMenu : styles.toggleMenu}` } > <div className={styles.colorMenu}> {/* 1 */} <div className={`${styles.row1} ${styles.row}`}> {(this.sequencer.recording === true) ? <div> recording... </div> : <div className={styles.row1BtnWrap}> <button className={styles.row1l} onClick={() => console.log('Start Button clicked')} onTouchTap={() => this.startSequencer()} > <img src={menu1} alt="Start Button" /> </button> <button className={styles.row1r} onClick={() => console.log('Stop Button clicked')} onTouchTap={() => this.stopSequencer()} > <img src={menu2} alt="Stop Button" /> </button> </div>} </div> {/* 2 */} <div className={`${styles.evenrow} ${styles.row}`}> <img src={menu3} alt="Patten Icon" /> </div> {/* 3 */} <div className={`${styles.row3} ${styles.row}`}> <div className={styles.row3l}> <button className={styles.row3lu} onClick={() => console.log('Save New Pattern clicked')} onTouchTap={() => this.savePattern()} > <img src={menu4} alt="Save New Pattern" /> </button> <button className={styles.row3ld} onClick={() => console.log('Exit Pattern clicked')} onTouchTap={() => this.exitPattern()} > <img src={menu9} alt="Exit Pattern" /> </button> </div> <div className={styles.row3m}> <button className={styles.row3mBtn} onClick={() => console.log('update pattern')} onTouchTap={() => this.editPattern()} > <img src={menu8} alt="Update Pattern" /> </button> </div> <div className={styles.row3r}> <div className={styles.row3ru}> <input type="text" className={styles.row3input} value={this.state.patternTitle} onChange={this.handleTitleChange} placeholder="input pattern name..." /> </div> <div className={styles.row3rd}> {this.renderPatterns()} </div> </div> </div> {/* 4 */} <div className={`${styles.evenrow} ${styles.row}`}> <img className={styles.chain} src={menu6} alt="Chain Icon" /> </div> {/* 5 */} <div className={`${styles.row5} ${styles.row}`}> <div className={styles.row5l}> <div className={styles.row5lu}> <button className={styles.row5lul} onClick={() => console.log('Play Chain Button clicked')} onTouchTap={() => this.playChain()} > <img src={menu1} alt="Play Chain Button" /> </button> <button className={styles.row5lur} onClick={() => console.log('Update Chain Button clicked')} onTouchTap={() => this.updateChain()} > <img src={menu7} alt="Update Chain Button" /> </button> </div> <div className={styles.row5ld}> <button className={styles.row5ldl} onClick={() => console.log('Exit Chain Button Chain clicked')} onTouchTap={() => this.exitChain()} > <img src={menu9} alt="Exit Chain Button Chain Index" /> </button> <button className={styles.row5ldr} onClick={() => console.log('Delete Current Chain Element Button clicked')} onTouchTap={() => this.deleteCurrentChainElement()} > <img src={menu5} alt="Delete Current Chain Element Button" /> </button> </div> </div> <div className={styles.row5r}> {(this.state.drumNoteChain.length === 0) ? <div>HEAD</div> : this.renderChain()} <div className={styles.chainLi} style={{ color: '#d8b98a' }} onTouchTap={() => this.setCurrentChainElementAtLast()} > + </div> </div> </div> {/* 6 */} <div className={`${styles.evenrow} ${styles.row}`}> <img src={menu10} alt="Record Icon" /> </div> {/* 7 */} <div className={`${styles.row7} ${styles.row}`}> <div className={styles.row7l}> <button className={ `${styles.row7lbtn} ${(this.sequencer.recording === true) ? styles.recordingBtn : ''}`} onClick={() => console.log('Record Button clicked')} onTouchTap={() => this.recordSequencer()} > <img src={menu11} alt="Record Button" /> </button> </div> <div className={ `${styles.row3r} ${(this.sequencer.recording === true) ? styles.displayHide : ''}`} > <div className={styles.row3ru}> <input type="text" className={styles.row3input} value={this.state.recordTitle} onChange={this.handleRecordTitleChange} placeholder="input record name..." /> </div> <div className={styles.row3rd}> {this.renderRecords()} </div> </div> </div> {/* 8 */} <div className={`${styles.evenrow} ${styles.row}`}> <span>Beact</span> </div> {/* 9 */} <div className={`${styles.row9} ${styles.row}`}> <span>by Vibert, Joey, Scya, 2017</span> </div> </div> </div> <button className={ `${styles.mask} ${(hidden === false ? styles.showMask : styles.hideMask)}`} onClick={() => this.toggleHidden()} > <img src={menuLogo} alt="BEACT" className={styles.menuLogo} /> </button> <Matrix data={this.state.data} playing={this.state.playing} currentBeat={this.state.currentBeat} onClick={(i, j) => this.handleClick(i, j)} /> <div className={styles.animation} id="animation" /> <WindowResizeListener onResize={w => this.handleResize(w.windowWidth, w.windowHeight)} /> <div> <input type="text" id="one" onKeyPress={this.detectKeyboard} /> </div> </div> ); } } export default DrumMachine;
:flags: conditional render by controling display
src/components/DrumMachine.js
:flags: conditional render by controling display
<ide><path>rc/components/DrumMachine.js <ide> } <ide> onTouchTap={() => this.toggleNarutoBool()} <ide> > <del> {narutoBool ? <img src={narutoG} className={styles.glow} alt="narutoG" /> : null} <del> {narutoBool ? null : <img src={narutoW} alt="narutoW" />} <add> <img src={narutoG} style={{ display: `${narutoBool ? 'block' : 'none'}` }} className={styles.glow} alt="narutoG" /> <add> <img src={narutoW} style={{ display: `${narutoBool ? 'none' : 'block'}` }} alt="narutoW" /> <ide> </button> <ide> <div <ide> className={
Java
apache-2.0
fb00ab5963dd07a0faae6e0f6fd8e923c52a23cb
0
LuisePufahl/camunda-bpm-platform_batchProcessing,hupda-edpe/c,xasx/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,jangalinski/camunda-bpm-platform,1and1/camunda-bpm-platform,filiphr/camunda-bpm-platform,joansmith/camunda-bpm-platform,fouasnon/camunda-bpm-platform,clintmanning/new-empty,AlexMinsk/camunda-bpm-platform,joansmith/camunda-bpm-platform,bentrm/camunda-bpm-platform,rainerh/camunda-bpm-platform,skjolber/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,bentrm/camunda-bpm-platform,Sumitdahiya/camunda,plexiti/camunda-bpm-platform,clintmanning/new-empty,skjolber/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,bentrm/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,tcrossland/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,tcrossland/camunda-bpm-platform,holisticon/camunda-bpm-platform,jangalinski/camunda-bpm-platform,jangalinski/camunda-bpm-platform,xasx/camunda-bpm-platform,filiphr/camunda-bpm-platform,xasx/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,rainerh/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,holisticon/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,menski/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,nibin/camunda-bpm-platform,clintmanning/new-empty,falko/camunda-bpm-platform,plexiti/camunda-bpm-platform,filiphr/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,Sumitdahiya/camunda,plexiti/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,Sumitdahiya/camunda,LuisePufahl/camunda-bpm-platform_batchProcessing,menski/camunda-bpm-platform,xasx/camunda-bpm-platform,joansmith/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,filiphr/camunda-bpm-platform,nibin/camunda-bpm-platform,jangalinski/camunda-bpm-platform,plexiti/camunda-bpm-platform,fouasnon/camunda-bpm-platform,menski/camunda-bpm-platform,bentrm/camunda-bpm-platform,plexiti/camunda-bpm-platform,skjolber/camunda-bpm-platform,LuisePufahl/camunda-bpm-platform_batchProcessing,Sumitdahiya/camunda,ingorichtsmeier/camunda-bpm-platform,joansmith/camunda-bpm-platform,holisticon/camunda-bpm-platform,camunda/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,jangalinski/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,joansmith/camunda-bpm-platform,hupda-edpe/c,skjolber/camunda-bpm-platform,camunda/camunda-bpm-platform,menski/camunda-bpm-platform,tcrossland/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,falko/camunda-bpm-platform,jangalinski/camunda-bpm-platform,nibin/camunda-bpm-platform,xasx/camunda-bpm-platform,skjolber/camunda-bpm-platform,langfr/camunda-bpm-platform,holisticon/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,LuisePufahl/camunda-bpm-platform_batchProcessing,joansmith/camunda-bpm-platform,LuisePufahl/camunda-bpm-platform_batchProcessing,menski/camunda-bpm-platform,camunda/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,xasx/camunda-bpm-platform,1and1/camunda-bpm-platform,langfr/camunda-bpm-platform,tcrossland/camunda-bpm-platform,rainerh/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,fouasnon/camunda-bpm-platform,holisticon/camunda-bpm-platform,langfr/camunda-bpm-platform,fouasnon/camunda-bpm-platform,tcrossland/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,fouasnon/camunda-bpm-platform,1and1/camunda-bpm-platform,camunda/camunda-bpm-platform,falko/camunda-bpm-platform,hupda-edpe/c,falko/camunda-bpm-platform,hupda-edpe/c,hupda-edpe/c,nibin/camunda-bpm-platform,camunda/camunda-bpm-platform,nibin/camunda-bpm-platform,nibin/camunda-bpm-platform,hupda-edpe/c,bentrm/camunda-bpm-platform,fouasnon/camunda-bpm-platform,camunda/camunda-bpm-platform,falko/camunda-bpm-platform,skjolber/camunda-bpm-platform,1and1/camunda-bpm-platform,tcrossland/camunda-bpm-platform,rainerh/camunda-bpm-platform,LuisePufahl/camunda-bpm-platform_batchProcessing,falko/camunda-bpm-platform,rainerh/camunda-bpm-platform,Sumitdahiya/camunda,langfr/camunda-bpm-platform,filiphr/camunda-bpm-platform,Sumitdahiya/camunda,holisticon/camunda-bpm-platform,plexiti/camunda-bpm-platform,langfr/camunda-bpm-platform,bentrm/camunda-bpm-platform,filiphr/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,langfr/camunda-bpm-platform,rainerh/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform
package com.camunda.fox.platform.test.functional.ejb.remote; import org.activiti.engine.runtime.ProcessInstance; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import com.camunda.fox.platform.test.functional.ejb.remote.bean.BusinessInterface; import com.camunda.fox.platform.test.functional.ejb.remote.bean.RemoteSingletonBean; import com.camunda.fox.platform.test.functional.ejb.remote.bean.RemoteSingletonBeanClientDelegateBean; import com.camunda.fox.platform.test.util.AbstractFoxPlatformIntegrationTest; /** * This test verifies that a CDI Java Bean Delegate is able to inject and invoke the * remote business interface of a SingletonBean from a different application * * Note: * - works on Jboss * - works on Glassfish * * @author Daniel Meyer * */ @RunWith(Arquillian.class) public class RemoteSingletonBeanInvocationTest extends AbstractFoxPlatformIntegrationTest { @Deployment(name="pa", order=2) public static WebArchive processArchive() { return initWebArchiveDeployment() .addClass(RemoteSingletonBeanClientDelegateBean.class) .addClass(BusinessInterface.class) // the business interface .addAsResource("com/camunda/fox/platform/test/functional/ejb/remote/RemoteSingletonBeanInvocationTest.testInvokeBean.bpmn20.xml"); } @Deployment(order=1) public static WebArchive delegateDeployment() { return ShrinkWrap.create(WebArchive.class, "service.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClass(AbstractFoxPlatformIntegrationTest.class) .addClass(RemoteSingletonBean.class) // the EJB .addClass(BusinessInterface.class); // the business interface } @Test @OperateOnDeployment("pa") public void testInvokeBean() throws Exception{ // this testcase first resolves the Bean synchronously and then from the JobExecutor ProcessInstance pi = runtimeService.startProcessInstanceByKey("testInvokeBean"); Assert.assertEquals(runtimeService.getVariable(pi.getId(), "result"), true); runtimeService.setVariable(pi.getId(), "result", false); taskService.complete(taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult().getId()); waitForJobExecutorToProcessAllJobs(60000, 300); Assert.assertEquals(runtimeService.getVariable(pi.getId(), "result"), true); taskService.complete(taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult().getId()); } @Test public void testMultipleInvocations() { // this is greater than any Datasource / EJB / Thread Pool size -> make sure all resources are released properly. int instances = 100; String[] ids = new String[instances]; for(int i=0; i<instances; i++) { ids[i] = runtimeService.startProcessInstanceByKey("testInvokeBean").getId(); Assert.assertEquals(runtimeService.getVariable(ids[i], "result"), true); runtimeService.setVariable(ids[i], "result", false); taskService.complete(taskService.createTaskQuery().processInstanceId(ids[i]).singleResult().getId()); } waitForJobExecutorToProcessAllJobs(180*1000, 300); for(int i=0; i<instances; i++) { Assert.assertEquals(runtimeService.getVariable(ids[i], "result"), true); taskService.complete(taskService.createTaskQuery().processInstanceId(ids[i]).singleResult().getId()); } } }
qa/integration-tests/src/test/java/com/camunda/fox/platform/test/functional/ejb/remote/RemoteSingletonBeanInvocationTest.java
package com.camunda.fox.platform.test.functional.ejb.remote; import org.activiti.engine.runtime.ProcessInstance; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import com.camunda.fox.platform.test.functional.ejb.remote.bean.BusinessInterface; import com.camunda.fox.platform.test.functional.ejb.remote.bean.RemoteSingletonBean; import com.camunda.fox.platform.test.functional.ejb.remote.bean.RemoteSingletonBeanClientDelegateBean; import com.camunda.fox.platform.test.util.AbstractFoxPlatformIntegrationTest; /** * This test verifies that a CDI Java Bean Delegate is able to inject and invoke the * remote business interface of a SingletonBean from a different application * * Note: * - works on Jboss * - works on Glassfish * * @author Daniel Meyer * */ @RunWith(Arquillian.class) public class RemoteSingletonBeanInvocationTest extends AbstractFoxPlatformIntegrationTest { @Deployment(name="pa", order=2) public static WebArchive processArchive() { return initWebArchiveDeployment() .addClass(RemoteSingletonBeanClientDelegateBean.class) .addClass(BusinessInterface.class) // the business interface .addAsResource("com/camunda/fox/platform/test/functional/ejb/remote/RemoteSingletonBeanInvocationTest.testInvokeBean.bpmn20.xml"); } @Deployment(order=1) public static WebArchive delegateDeployment() { return ShrinkWrap.create(WebArchive.class, "service.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClass(AbstractFoxPlatformIntegrationTest.class) .addClass(RemoteSingletonBean.class) // the EJB .addClass(BusinessInterface.class); // the business interface } @Test @OperateOnDeployment("pa") public void testInvokeBean() throws Exception{ // this testcase first resolves the Bean synchronously and then from the JobExecutor ProcessInstance pi = runtimeService.startProcessInstanceByKey("testInvokeBean"); Assert.assertEquals(runtimeService.getVariable(pi.getId(), "result"), true); runtimeService.setVariable(pi.getId(), "result", false); taskService.complete(taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult().getId()); waitForJobExecutorToProcessAllJobs(6000, 300); Assert.assertEquals(runtimeService.getVariable(pi.getId(), "result"), true); taskService.complete(taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult().getId()); } @Test public void testMultipleInvocations() { // this is greater than any Datasource / EJB / Thread Pool size -> make sure all resources are released properly. int instances = 100; String[] ids = new String[instances]; for(int i=0; i<instances; i++) { ids[i] = runtimeService.startProcessInstanceByKey("testInvokeBean").getId(); Assert.assertEquals(runtimeService.getVariable(ids[i], "result"), true); runtimeService.setVariable(ids[i], "result", false); taskService.complete(taskService.createTaskQuery().processInstanceId(ids[i]).singleResult().getId()); } waitForJobExecutorToProcessAllJobs(60*1000, 300); for(int i=0; i<instances; i++) { Assert.assertEquals(runtimeService.getVariable(ids[i], "result"), true); taskService.complete(taskService.createTaskQuery().processInstanceId(ids[i]).singleResult().getId()); } } }
Increased time for JobExecutor
qa/integration-tests/src/test/java/com/camunda/fox/platform/test/functional/ejb/remote/RemoteSingletonBeanInvocationTest.java
Increased time for JobExecutor
<ide><path>a/integration-tests/src/test/java/com/camunda/fox/platform/test/functional/ejb/remote/RemoteSingletonBeanInvocationTest.java <ide> <ide> taskService.complete(taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult().getId()); <ide> <del> waitForJobExecutorToProcessAllJobs(6000, 300); <add> waitForJobExecutorToProcessAllJobs(60000, 300); <ide> <ide> Assert.assertEquals(runtimeService.getVariable(pi.getId(), "result"), true); <ide> <ide> taskService.complete(taskService.createTaskQuery().processInstanceId(ids[i]).singleResult().getId()); <ide> } <ide> <del> waitForJobExecutorToProcessAllJobs(60*1000, 300); <add> waitForJobExecutorToProcessAllJobs(180*1000, 300); <ide> <ide> for(int i=0; i<instances; i++) { <ide> Assert.assertEquals(runtimeService.getVariable(ids[i], "result"), true);
Java
mit
52074625f4d2e81b2589aa5149fb7c8166e3c122
0
sakuranodoka/MyApplication
package com.example.administrator.myapplication; import android.Manifest; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; //import android.location.Location; //import android.location.LocationListener; import android.location.Location; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationAvailability; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { private static final int CONTENT_REQUEST = 1337; public GoogleApiClient googleApiClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); Button captureBtn = (Button) findViewById(R.id.capture); captureBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int REQUEST_CAMERA = 0; Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "IMG_" + timeStamp + ".jpg"; File f = new File(Environment.getExternalStorageDirectory() , "DCIM/Camera/" + imageFileName); Uri uri = Uri.fromFile(f); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(Intent.createChooser(intent , "Take a picture with"), REQUEST_CAMERA); } }); Button scanBtn = (Button) findViewById(R.id.scan); scanBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { IntentIntegrator scanIntegrator = new IntentIntegrator(MainActivity.this); scanIntegrator.initiateScan(); } }); // ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1); // ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); // LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // MyCurrentLoctionListener locationListener = new MyCurrentLoctionListener(); // Here, thisActivity is the current activity googleApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); //Log.v("xxxxxx", LocationManager.GPS_PROVIDER.toString()); //locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); } @Override protected void onStart() { super.onStart(); googleApiClient.connect(); } @Override protected void onStop() { super.onStop(); if (googleApiClient != null && googleApiClient.isConnected()) { googleApiClient.disconnect(); } } /*@Override public void onLocationChanged(Location location) { TextView txtLat = (TextView) findViewById(R.id.textView); txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude()); }*/ public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case 1: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { } else { // permission denied, boo! Disable the // functionality that depends on this permission. } return; } // other 'case' lines to check for other // permissions this app might request } } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_camera) { // Handle the camera action } else if (id == R.id.nav_gallery) { } else if (id == R.id.nav_slideshow) { } else if (id == R.id.nav_manage) { } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { System.gc(); IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if (scanningResult != null) { //we have a result Log.v("xxxxxx", " |NNNN.msn"); String scanContent = scanningResult.getContents(); String scanFormat = scanningResult.getFormatName(); TextView textView = (TextView) findViewById(R.id.textView); //String contents = data.getStringExtra("SCAN_RESULT"); textView.setText(scanContent+" "+scanFormat); Toast toast = Toast.makeText(getApplicationContext(), scanContent+" "+scanFormat, Toast.LENGTH_SHORT); toast.show(); } if (resultCode == RESULT_OK) { if (requestCode == CONTENT_REQUEST) { /*Intent i=new Intent(Intent.ACTION_VIEW); i.setDataAndType(Uri.fromFile(output), "image/jpeg"); startActivity(i); finish();*/ // Save a file: path for use with ACTION_VIEW intents //mCurrentPhotoPath = "file:" + image.getAbsolutePath(); /*Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); File f = new File(mCurrentPhotoPath); Uri contentUri = Uri.fromFile(f); mediaScanIntent.setData(contentUri); this.sendBroadcast(mediaScanIntent);*/ Log.v("xxxxxx", " |NNNN.msn"); //data.putExtra(MediaStore.EXTRA_OUTPUT, "android.jpg"); //use imageUri here to access the image //Bundle extras = data.getExtras(); //Log.e("URI",imageUri.toString()); //Bitmap bmp = (Bitmap) extras.get("data"); // here you will get the image as bitmap /*File outFile = new File(Environment.getExternalStorageDirectory(), "myname.jpeg"); FileOutputStream fos = null; try { fos = new FileOutputStream(outFile); } catch (FileNotFoundException e) { e.printStackTrace(); } photo.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close();*/ } else if (resultCode == RESULT_CANCELED) { Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT); } else if (resultCode == 2) { Log.v("xxxxxx", "tttttttttt"); //TextView textView = (TextView) findViewById(R.id.textView); String contents = data.getStringExtra("SCAN_RESULT"); //textView.setText(contents); /*if (resultCode == RESULT_OK) { TextView textView = (TextView) findViewById(R.id.textView); String contents = data.getStringExtra("SCAN_RESULT"); String format = data.getStringExtra("SCAN_RESULT_FORMAT"); textView.setText("Result : " + contents); }*/ } } } @Override public void onConnected(Bundle bundle) { LocationAvailability locationAvailability = LocationServices.FusedLocationApi.getLocationAvailability(googleApiClient); if(locationAvailability.isLocationAvailable()) { LocationRequest locationRequest = new LocationRequest() .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) .setInterval(5000); LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this); } else { // Log.v("xxxxxx","qwrqwrwerwer"); // Do something when location provider not available } } @Override public void onLocationChanged(Location location) { TextView textView = (TextView) findViewById(R.id.textView); textView.setText("Latitude : " + location.getLatitude() + "\n" + "Longistudesmd : " + location.getLongitude()); } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } }
app/src/main/java/com/example/administrator/myapplication/MainActivity.java
package com.example.administrator.myapplication; import android.Manifest; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; //import android.location.Location; //import android.location.LocationListener; import android.location.Location; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationAvailability; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { private static final int CONTENT_REQUEST = 1337; public GoogleApiClient googleApiClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); Button captureBtn = (Button) findViewById(R.id.capture); captureBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int REQUEST_CAMERA = 0; Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "IMG_" + timeStamp + ".jpg"; File f = new File(Environment.getExternalStorageDirectory() , "DCIM/Camera/" + imageFileName); Uri uri = Uri.fromFile(f); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(Intent.createChooser(intent , "Take a picture with"), REQUEST_CAMERA); } }); Button scanBtn = (Button) findViewById(R.id.scan); scanBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { IntentIntegrator scanIntegrator = new IntentIntegrator(MainActivity.this); scanIntegrator.initiateScan(); } }); // ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1); // ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); // LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // MyCurrentLoctionListener locationListener = new MyCurrentLoctionListener(); // Here, thisActivity is the current activity googleApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); //Log.v("xxxxxx", LocationManager.GPS_PROVIDER.toString()); //locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); } @Override protected void onStart() { super.onStart(); googleApiClient.connect(); } @Override protected void onStop() { super.onStop(); if (googleApiClient != null && googleApiClient.isConnected()) { googleApiClient.disconnect(); } } /*@Override public void onLocationChanged(Location location) { TextView txtLat = (TextView) findViewById(R.id.textView); txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude()); }*/ public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case 1: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { } else { // permission denied, boo! Disable the // functionality that depends on this permission. } return; } // other 'case' lines to check for other // permissions this app might request } } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_camera) { // Handle the camera action } else if (id == R.id.nav_gallery) { } else if (id == R.id.nav_slideshow) { } else if (id == R.id.nav_manage) { } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { System.gc(); IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if (scanningResult != null) { //we have a result Log.v("xxxxxx", " |NNNN.msn"); String scanContent = scanningResult.getContents(); String scanFormat = scanningResult.getFormatName(); TextView textView = (TextView) findViewById(R.id.textView); //String contents = data.getStringExtra("SCAN_RESULT"); textView.setText(scanContent+" "+scanFormat); Toast toast = Toast.makeText(getApplicationContext(), scanContent+" "+scanFormat, Toast.LENGTH_SHORT); toast.show(); } if (resultCode == RESULT_OK) { if (requestCode == CONTENT_REQUEST) { /*Intent i=new Intent(Intent.ACTION_VIEW); i.setDataAndType(Uri.fromFile(output), "image/jpeg"); startActivity(i); finish();*/ // Save a file: path for use with ACTION_VIEW intents //mCurrentPhotoPath = "file:" + image.getAbsolutePath(); /*Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); File f = new File(mCurrentPhotoPath); Uri contentUri = Uri.fromFile(f); mediaScanIntent.setData(contentUri); this.sendBroadcast(mediaScanIntent);*/ Log.v("xxxxxx", " |NNNN.msn"); //data.putExtra(MediaStore.EXTRA_OUTPUT, "android.jpg"); //use imageUri here to access the image //Bundle extras = data.getExtras(); //Log.e("URI",imageUri.toString()); //Bitmap bmp = (Bitmap) extras.get("data"); // here you will get the image as bitmap /*File outFile = new File(Environment.getExternalStorageDirectory(), "myname.jpeg"); FileOutputStream fos = null; try { fos = new FileOutputStream(outFile); } catch (FileNotFoundException e) { e.printStackTrace(); } photo.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close();*/ } else if (resultCode == RESULT_CANCELED) { Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT); } else if (resultCode == 2) { Log.v("xxxxxx", "tttttttttt"); //TextView textView = (TextView) findViewById(R.id.textView); String contents = data.getStringExtra("SCAN_RESULT"); //textView.setText(contents); /*if (resultCode == RESULT_OK) { TextView textView = (TextView) findViewById(R.id.textView); String contents = data.getStringExtra("SCAN_RESULT"); String format = data.getStringExtra("SCAN_RESULT_FORMAT"); textView.setText("Result : " + contents); }*/ } } } @Override public void onConnected(Bundle bundle) { LocationAvailability locationAvailability = LocationServices.FusedLocationApi.getLocationAvailability(googleApiClient); if(locationAvailability.isLocationAvailable()) { LocationRequest locationRequest = new LocationRequest() .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) .setInterval(5000); LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this); } else { // Log.v("xxxxxx","qwrqwrwerwer"); // Do something when location provider not available } } @Override public void onLocationChanged(Location location) { TextView textView = (TextView) findViewById(R.id.textView); textView.setText("Latitude : " + location.getLatitude() + "\n" + "Longistudesm : " + location.getLongitude()); } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } }
First Commit Testing V.1.02 - Camera Capture (Fixed) - Barcode Reader (Fixed) - GPS Location (Latitude and Longtitude) (Fixed)
app/src/main/java/com/example/administrator/myapplication/MainActivity.java
First Commit Testing V.1.02 - Camera Capture (Fixed) - Barcode Reader (Fixed) - GPS Location (Latitude and Longtitude) (Fixed)
<ide><path>pp/src/main/java/com/example/administrator/myapplication/MainActivity.java <ide> public void onLocationChanged(Location location) { <ide> TextView textView = (TextView) findViewById(R.id.textView); <ide> textView.setText("Latitude : " + location.getLatitude() + "\n" + <del> "Longistudesm : " + location.getLongitude()); <add> "Longistudesmd : " + location.getLongitude()); <ide> } <ide> <ide> @Override
Java
apache-2.0
6d8be12a1538aea0932dddd448dcf7a0620d638d
0
Imran-C/cassandra,nvoron23/cassandra,snazy/cassandra,scaledata/cassandra,GabrielNicolasAvellaneda/cassandra,Stratio/stratio-cassandra,snazy/cassandra,michaelsembwever/cassandra,iburmistrov/Cassandra,joesiewert/cassandra,jrwest/cassandra,LatencyUtils/cassandra-stress2,exoscale/cassandra,yonglehou/cassandra,MasahikoSawada/cassandra,chbatey/cassandra-1,Stratio/stratio-cassandra,ifesdjeen/cassandra,chaordic/cassandra,ifesdjeen/cassandra,aweisberg/cassandra,Jollyplum/cassandra,bcoverston/cassandra,adejanovski/cassandra,swps/cassandra,pcmanus/cassandra,jkni/cassandra,apache/cassandra,bpupadhyaya/cassandra,blerer/cassandra,driftx/cassandra,ben-manes/cassandra,iamaleksey/cassandra,kgreav/cassandra,asias/cassandra,szhou1234/cassandra,sivikt/cassandra,aweisberg/cassandra,aboudreault/cassandra,Imran-C/cassandra,GabrielNicolasAvellaneda/cassandra,aweisberg/cassandra,iburmistrov/Cassandra,nvoron23/cassandra,yanbit/cassandra,vramaswamy456/cassandra,jasobrown/cassandra,yukim/cassandra,asias/cassandra,christian-esken/cassandra,mambocab/cassandra,macintoshio/cassandra,wreda/cassandra,matthewtt/cassandra_read,sharvanath/cassandra,lalithsuresh/cassandra-c3,mashuai/Cassandra-Research,lalithsuresh/cassandra-c3,ifesdjeen/cassandra,hhorii/cassandra,lalithsuresh/cassandra-c3,pthomaid/cassandra,kangkot/stratio-cassandra,taigetco/cassandra_read,xiongzheng/Cassandra-Research,aarushi12002/cassandra,sluk3r/cassandra,aboudreault/cassandra,pkdevbox/cassandra,juiceblender/cassandra,jasonwee/cassandra,adejanovski/cassandra,belliottsmith/cassandra,modempachev4/kassandra,thobbs/cassandra,bpupadhyaya/cassandra,josh-mckenzie/cassandra,adelapena/cassandra,vaibhi9/cassandra,dongjiaqiang/cassandra,hhorii/cassandra,mshuler/cassandra,caidongyun/cassandra,phact/cassandra,adelapena/cassandra,DikangGu/cassandra,michaelsembwever/cassandra,christian-esken/cassandra,qinjin/mdtc-cassandra,scylladb/scylla-tools-java,emolsson/cassandra,nlalevee/cassandra,chbatey/cassandra-1,juiceblender/cassandra,Jaumo/cassandra,strapdata/cassandra,yukim/cassandra,iamaleksey/cassandra,yonglehou/cassandra,emolsson/cassandra,mambocab/cassandra,wreda/cassandra,szhou1234/cassandra,adejanovski/cassandra,thelastpickle/cassandra,apache/cassandra,mashuai/Cassandra-Research,pallavi510/cassandra,modempachev4/kassandra,matthewtt/cassandra_read,scaledata/cassandra,ollie314/cassandra,regispl/cassandra,DikangGu/cassandra,nlalevee/cassandra,pcmanus/cassandra,cooldoger/cassandra,WorksApplications/cassandra,hengxin/cassandra,iburmistrov/Cassandra,josh-mckenzie/cassandra,chaordic/cassandra,rmarchei/cassandra,jasobrown/cassandra,jasonstack/cassandra,blerer/cassandra,bdeggleston/cassandra,JeremiahDJordan/cassandra,sayanh/ViewMaintenanceCassandra,matthewtt/cassandra_read,tommystendahl/cassandra,clohfink/cassandra,blambov/cassandra,newrelic-forks/cassandra,WorksApplications/cassandra,Jaumo/cassandra,guanxi55nba/db-improvement,regispl/cassandra,carlyeks/cassandra,weideng1/cassandra,rackerlabs/cloudmetrics-cassandra,Instagram/cassandra,a-buck/cassandra,scylladb/scylla-tools-java,mheffner/cassandra-1,blambov/cassandra,swps/cassandra,instaclustr/cassandra,blambov/cassandra,jkni/cassandra,DikangGu/cassandra,AtwooTM/cassandra,bcoverston/cassandra,strapdata/cassandra,sharvanath/cassandra,likaiwalkman/cassandra,pauloricardomg/cassandra,aureagle/cassandra,dongjiaqiang/cassandra,sedulam/CASSANDRA-12201,boneill42/cassandra,aureagle/cassandra,Stratio/stratio-cassandra,strapdata/cassandra,yanbit/cassandra,driftx/cassandra,jeromatron/cassandra,whitepages/cassandra,pauloricardomg/cassandra,guanxi55nba/key-value-store,krummas/cassandra,sayanh/ViewMaintenanceSupport,mt0803/cassandra,nutbunnies/cassandra,swps/cassandra,helena/cassandra,rackerlabs/cloudmetrics-cassandra,michaelmior/cassandra,mkjellman/cassandra,aureagle/cassandra,nutbunnies/cassandra,mkjellman/cassandra,belliottsmith/cassandra,Instagram/cassandra,hengxin/cassandra,Jaumo/cassandra,WorksApplications/cassandra,stef1927/cassandra,mkjellman/cassandra,bcoverston/cassandra,macintoshio/cassandra,spodkowinski/cassandra,krummas/cassandra,michaelmior/cassandra,mashuai/Cassandra-Research,blerer/cassandra,adelapena/cassandra,Jollyplum/cassandra,caidongyun/cassandra,darach/cassandra,sharvanath/cassandra,a-buck/cassandra,scaledata/cassandra,LatencyUtils/cassandra-stress2,tjake/cassandra,weipinghe/cassandra,ptuckey/cassandra,darach/cassandra,apache/cassandra,adelapena/cassandra,nitsanw/cassandra,sriki77/cassandra,bdeggleston/cassandra,AtwooTM/cassandra,DICL/cassandra,pcn/cassandra-1,jbellis/cassandra,ptuckey/cassandra,belliottsmith/cassandra,likaiwalkman/cassandra,tongjixianing/projects,gdusbabek/cassandra,weideng1/cassandra,phact/cassandra,aarushi12002/cassandra,newrelic-forks/cassandra,thobbs/cassandra,stef1927/cassandra,josh-mckenzie/cassandra,likaiwalkman/cassandra,jasonstack/cassandra,sedulam/CASSANDRA-12201,exoscale/cassandra,nvoron23/cassandra,sluk3r/cassandra,yukim/cassandra,carlyeks/cassandra,ollie314/cassandra,kgreav/cassandra,christian-esken/cassandra,michaelmior/cassandra,fengshao0907/Cassandra-Research,sedulam/CASSANDRA-12201,ben-manes/cassandra,jeffjirsa/cassandra,michaelsembwever/cassandra,yukim/cassandra,thelastpickle/cassandra,apache/cassandra,ptuckey/cassandra,shawnkumar/cstargraph,rogerchina/cassandra,spodkowinski/cassandra,sivikt/cassandra,iamaleksey/cassandra,weipinghe/cassandra,jasobrown/cassandra,sriki77/cassandra,clohfink/cassandra,Bj0rnen/cassandra,ibmsoe/cassandra,JeremiahDJordan/cassandra,tjake/cassandra,thelastpickle/cassandra,mike-tr-adamson/cassandra,guard163/cassandra,AtwooTM/cassandra,bdeggleston/cassandra,jeffjirsa/cassandra,jeffjirsa/cassandra,guanxi55nba/db-improvement,mambocab/cassandra,yonglehou/cassandra,xiongzheng/Cassandra-Research,fengshao0907/Cassandra-Research,Instagram/cassandra,juiceblender/cassandra,mt0803/cassandra,cooldoger/cassandra,macintoshio/cassandra,wreda/cassandra,blambov/cassandra,sayanh/ViewMaintenanceCassandra,pkdevbox/cassandra,fengshao0907/cassandra-1,guard163/cassandra,knifewine/cassandra,pcn/cassandra-1,dkua/cassandra,chbatey/cassandra-1,instaclustr/cassandra,mshuler/cassandra,JeremiahDJordan/cassandra,yhnishi/cassandra,snazy/cassandra,mkjellman/cassandra,guanxi55nba/key-value-store,EnigmaCurry/cassandra,jasonwee/cassandra,bdeggleston/cassandra,mshuler/cassandra,pkdevbox/cassandra,helena/cassandra,gdusbabek/cassandra,rdio/cassandra,scylladb/scylla-tools-java,ejankan/cassandra,asias/cassandra,ibmsoe/cassandra,knifewine/cassandra,aweisberg/cassandra,cooldoger/cassandra,Stratio/stratio-cassandra,emolsson/cassandra,jbellis/cassandra,RyanMagnusson/cassandra,mike-tr-adamson/cassandra,tjake/cassandra,beobal/cassandra,beobal/cassandra,phact/cassandra,rmarchei/cassandra,LatencyUtils/cassandra-stress2,boneill42/cassandra,nitsanw/cassandra,DICL/cassandra,jkni/cassandra,sluk3r/cassandra,ibmsoe/cassandra,chaordic/cassandra,MasahikoSawada/cassandra,iamaleksey/cassandra,codefollower/Cassandra-Research,dkua/cassandra,mheffner/cassandra-1,beobal/cassandra,rogerchina/cassandra,krummas/cassandra,dkua/cassandra,xiongzheng/Cassandra-Research,taigetco/cassandra_read,tommystendahl/cassandra,ifesdjeen/cassandra,jasonwee/cassandra,scylladb/scylla-tools-java,spodkowinski/cassandra,jrwest/cassandra,yangzhe1991/cassandra,a-buck/cassandra,vaibhi9/cassandra,hengxin/cassandra,jrwest/cassandra,clohfink/cassandra,bpupadhyaya/cassandra,rdio/cassandra,szhou1234/cassandra,weipinghe/cassandra,regispl/cassandra,cooldoger/cassandra,aboudreault/cassandra,jasobrown/cassandra,sayanh/ViewMaintenanceCassandra,jeromatron/cassandra,pofallon/cassandra,guanxi55nba/key-value-store,RyanMagnusson/cassandra,ben-manes/cassandra,rogerchina/cassandra,GabrielNicolasAvellaneda/cassandra,jrwest/cassandra,yangzhe1991/cassandra,pcmanus/cassandra,Bj0rnen/cassandra,tongjixianing/projects,ejankan/cassandra,szhou1234/cassandra,fengshao0907/Cassandra-Research,knifewine/cassandra,RyanMagnusson/cassandra,bcoverston/cassandra,josh-mckenzie/cassandra,modempachev4/kassandra,Imran-C/cassandra,ptnapoleon/cassandra,kgreav/cassandra,belliottsmith/cassandra,rdio/cassandra,jsanda/cassandra,shawnkumar/cstargraph,nitsanw/cassandra,jeromatron/cassandra,exoscale/cassandra,kgreav/cassandra,pthomaid/cassandra,WorksApplications/cassandra,instaclustr/cassandra,taigetco/cassandra_read,qinjin/mdtc-cassandra,weideng1/cassandra,nlalevee/cassandra,mt0803/cassandra,joesiewert/cassandra,Stratio/stratio-cassandra,jeffjirsa/cassandra,pauloricardomg/cassandra,jsanda/cassandra,whitepages/cassandra,ptnapoleon/cassandra,newrelic-forks/cassandra,pofallon/cassandra,jsanda/cassandra,yhnishi/cassandra,EnigmaCurry/cassandra,EnigmaCurry/cassandra,pauloricardomg/cassandra,strapdata/cassandra,Jollyplum/cassandra,rackerlabs/cloudmetrics-cassandra,tongjixianing/projects,hhorii/cassandra,qinjin/mdtc-cassandra,kangkot/stratio-cassandra,blerer/cassandra,tommystendahl/cassandra,nutbunnies/cassandra,vramaswamy456/cassandra,bmel/cassandra,codefollower/Cassandra-Research,dongjiaqiang/cassandra,helena/cassandra,sivikt/cassandra,driftx/cassandra,whitepages/cassandra,bmel/cassandra,thobbs/cassandra,clohfink/cassandra,juiceblender/cassandra,guanxi55nba/db-improvement,beobal/cassandra,gdusbabek/cassandra,mike-tr-adamson/cassandra,carlyeks/cassandra,ollie314/cassandra,kangkot/stratio-cassandra,driftx/cassandra,sayanh/ViewMaintenanceSupport,rmarchei/cassandra,yanbit/cassandra,Bj0rnen/cassandra,vramaswamy456/cassandra,darach/cassandra,tjake/cassandra,yangzhe1991/cassandra,pallavi510/cassandra,thelastpickle/cassandra,kangkot/stratio-cassandra,MasahikoSawada/cassandra,mheffner/cassandra-1,ejankan/cassandra,bmel/cassandra,joesiewert/cassandra,fengshao0907/cassandra-1,vaibhi9/cassandra,guard163/cassandra,sriki77/cassandra,stef1927/cassandra,DICL/cassandra,jasonstack/cassandra,ptnapoleon/cassandra,pallavi510/cassandra,kangkot/stratio-cassandra,mshuler/cassandra,krummas/cassandra,jbellis/cassandra,instaclustr/cassandra,michaelsembwever/cassandra,caidongyun/cassandra,codefollower/Cassandra-Research,shawnkumar/cstargraph,stef1927/cassandra,fengshao0907/cassandra-1,pcn/cassandra-1,spodkowinski/cassandra,yhnishi/cassandra,pofallon/cassandra,Instagram/cassandra,tommystendahl/cassandra,aarushi12002/cassandra,mike-tr-adamson/cassandra,pthomaid/cassandra,snazy/cassandra,boneill42/cassandra
/** * 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.cassandra.metrics; import java.util.concurrent.TimeUnit; import com.yammer.metrics.Metrics; import com.yammer.metrics.core.Gauge; import com.yammer.metrics.core.Meter; import com.yammer.metrics.core.MetricName; import com.yammer.metrics.util.RatioGauge; import org.apache.cassandra.service.FileCacheService; public class FileCacheMetrics { private static final MetricNameFactory factory = new DefaultNameFactory("FileCache"); /** Total number of hits */ public final Meter hits; /** Total number of requests */ public final Meter requests; /** hit rate */ public final Gauge<Double> hitRate; /** Total size of file cache, in bytes */ public final Gauge<Long> size; public FileCacheMetrics() { hits = Metrics.newMeter(factory.createMetricName("Hits"), "hits", TimeUnit.SECONDS); requests = Metrics.newMeter(factory.createMetricName("Requests"), "requests", TimeUnit.SECONDS); hitRate = Metrics.newGauge(factory.createMetricName("HitRate"), new RatioGauge() { protected double getNumerator() { return hits.count(); } protected double getDenominator() { return requests.count(); } }); size = Metrics.newGauge(factory.createMetricName("Size"), new Gauge<Long>() { public Long value() { return FileCacheService.instance.sizeInBytes(); } }); } }
src/java/org/apache/cassandra/metrics/FileCacheMetrics.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.cassandra.metrics; import java.util.concurrent.TimeUnit; import com.yammer.metrics.Metrics; import com.yammer.metrics.core.Gauge; import com.yammer.metrics.core.Meter; import com.yammer.metrics.core.MetricName; import com.yammer.metrics.util.RatioGauge; import org.apache.cassandra.service.FileCacheService; public class FileCacheMetrics { /** Total number of hits */ public final Meter hits; /** Total number of requests */ public final Meter requests; /** hit rate */ public final Gauge<Double> hitRate; /** Total size of file cache, in bytes */ public final Gauge<Long> size; public FileCacheMetrics() { hits = Metrics.newMeter(new MetricName(FileCacheService.class, "Hits"), "hits", TimeUnit.SECONDS); requests = Metrics.newMeter(new MetricName(FileCacheService.class, "Requests"), "requests", TimeUnit.SECONDS); hitRate = Metrics.newGauge(new MetricName(FileCacheService.class, "HitRate"), new RatioGauge() { protected double getNumerator() { return hits.count(); } protected double getDenominator() { return requests.count(); } }); size = Metrics.newGauge(new MetricName(FileCacheService.class, "Size"), new Gauge<Long>() { public Long value() { return FileCacheService.instance.sizeInBytes(); } }); } }
Correctly name FileCache metrics. Patch by Nick Bailey, reviewed by brandonwilliams for CASSANDRA-7294
src/java/org/apache/cassandra/metrics/FileCacheMetrics.java
Correctly name FileCache metrics.
<ide><path>rc/java/org/apache/cassandra/metrics/FileCacheMetrics.java <ide> <ide> public class FileCacheMetrics <ide> { <add> private static final MetricNameFactory factory = new DefaultNameFactory("FileCache"); <add> <ide> /** Total number of hits */ <ide> public final Meter hits; <ide> /** Total number of requests */ <ide> <ide> public FileCacheMetrics() <ide> { <del> hits = Metrics.newMeter(new MetricName(FileCacheService.class, "Hits"), "hits", TimeUnit.SECONDS); <del> requests = Metrics.newMeter(new MetricName(FileCacheService.class, "Requests"), "requests", TimeUnit.SECONDS); <del> hitRate = Metrics.newGauge(new MetricName(FileCacheService.class, "HitRate"), new RatioGauge() <add> hits = Metrics.newMeter(factory.createMetricName("Hits"), "hits", TimeUnit.SECONDS); <add> requests = Metrics.newMeter(factory.createMetricName("Requests"), "requests", TimeUnit.SECONDS); <add> hitRate = Metrics.newGauge(factory.createMetricName("HitRate"), new RatioGauge() <ide> { <ide> protected double getNumerator() <ide> { <ide> return requests.count(); <ide> } <ide> }); <del> size = Metrics.newGauge(new MetricName(FileCacheService.class, "Size"), new Gauge<Long>() <add> size = Metrics.newGauge(factory.createMetricName("Size"), new Gauge<Long>() <ide> { <ide> public Long value() <ide> {
JavaScript
mit
75ad43baeb80b9552cab6f8399f32f33263736dc
0
notmessenger/sl-ember-components,notmessenger/sl-ember-components,softlayer/sl-ember-components,softlayer/sl-ember-components
import Ember from 'ember'; import hbs from 'htmlbars-inline-precompile'; import { moduleForComponent, test } from 'ember-qunit'; import sinon from 'sinon'; const mockStream = { actions: {}, on( actionName, handler ) { this.actions[ actionName ] = handler; }, subject: { dispose() { mockStream.actions = {}; }, onCompleted() {} } }; const template = hbs` {{#sl-modal as |modal|}} {{sl-modal-header title="Simple Example" ariaLabelledBy=modal.ariaLabelledBy }} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} `; moduleForComponent( 'sl-modal', 'Integration | Component | sl modal', { afterEach() { this.$( '.modal' ).remove(); Ember.$( '.modal-backdrop' ).remove(); }, integration: true }); test( 'Check setting of template properties', function( assert ) { // we currently only pass thru the backdrop parameter assert.expect( 6 ); const spy = sinon.spy( Ember.$.fn, 'modal' ); // props passed to bootstrap modal that are not bound to template const nonTemplateProps = { 'keyboard': true, 'show': false }; // all props set one way const template1 = hbs` {{#sl-modal backdrop=false animated=false }} {{sl-modal-header}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} `; // all props set another way const template2 = hbs` {{#sl-modal backdrop=true animated=true }} {{sl-modal-header}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} `; // all props allowed to default const template3 = hbs` {{#sl-modal}} {{sl-modal-header}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} `; this.render( template1 ); const $first = this.$( '>:first-child' ); assert.deepEqual( spy.args[0][0], Ember.$.extend( { 'backdrop': false }, nonTemplateProps ), 'All parameters passed thru to jQuery.fn.modal (checking setting) 1/3' ); this.render( template2 ); const $second = this.$( '>:first-child' ); assert.deepEqual( spy.args[1][0], Ember.$.extend( { 'backdrop': true }, nonTemplateProps ), 'All parameters passed thru to jQuery.fn.modal (checking setting) 2/3' ); this.render( template3 ); const $third = this.$( '>:first-child' ); assert.deepEqual( spy.args[2][0], Ember.$.extend( { 'backdrop': true }, nonTemplateProps ), 'All parameters passed thru to jQuery.fn.modal (checking defaults) 3/3' ); assert.strictEqual( $first.filter( ':not(.fade)' ).length, 1, 'fade class not present when animated set to false' ); assert.strictEqual( $second.filter( '.fade' ).length, 1, 'fade class present when animated set to true' ); assert.strictEqual( $third.filter( '.fade' ).length, 1, 'fade class present when animated not set' ); Ember.$.fn.modal.restore(); }); test( 'Classes are present', function( assert ) { this.render( template ); assert.ok( this.$( '>:first-child' ).hasClass( 'modal' ), 'Has class modal' ); }); test( 'Listeners are setup and firing appropriately', function( assert ) { assert.expect( 4 ); const beforeShowDone = assert.async(); const afterShowDone = assert.async(); const beforeHideDone = assert.async(); const afterHideDone = assert.async(); const beforeShow = () => { assert.ok( true, 'beforeShow was triggered' ); beforeShowDone(); }; const afterShow = () => { assert.ok( true, 'afterShow was triggered' ); afterShowDone(); }; const beforeHide = () => { assert.ok( true, 'beforeHide was triggered' ); beforeHideDone(); }; const afterHide = () => { assert.ok( true, 'afterHide was triggered' ); afterHideDone(); }; this.on( 'beforeShow', beforeShow ); this.on( 'afterShow', afterShow ); this.on( 'beforeHide', beforeHide ); this.on( 'afterHide', afterHide ); this.render( hbs` {{#sl-modal name="testing" beforeShow="beforeShow" afterShow="afterShow" beforeHide="beforeHide" afterHide="afterHide" }} {{sl-modal-header}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} ` ); Ember.run( () => { this.$( '>:first-child' ).modal( 'show' ); this.$( '>:first-child' ).modal( 'hide' ); }); this.hideModal = false; }); test( 'Property isOpen is set appropriately', function( assert ) { this.set( 'isOpen' ); this.render( hbs` {{#sl-modal isOpen=isOpen}} {{sl-modal-header title="Simple Example"}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} ` ); Ember.run( () => { this.$( '>:first-child' ).trigger( 'shown.bs.modal' ); }); assert.strictEqual( this.get( 'isOpen' ), true, 'isOpen was set to true when modal show event was triggered' ); Ember.run( () => { this.$( '>:first-child' ).trigger( 'hidden.bs.modal' ); }); assert.strictEqual( this.get( 'isOpen' ), false, 'isOpen was set to false when modal close event was triggered' ); }); test( 'Closing of modal using close button works', function( assert ) { assert.expect( 1 ); const closeDone = assert.async(); const modalClosed = () => { assert.ok( true, 'Modal was closed' ); closeDone(); }; this.on( 'modalClosed', modalClosed ); this.render( hbs` {{#sl-modal afterHide="modalClosed"}} {{sl-modal-header title="Simple Example"}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} ` ); Ember.run( () => { this.$( '>:first-child' ).modal( 'show' ); this.$( '>:first-child' ).find( '.close' ).click(); }); }); test( 'ariaDescribedBy attribute binding', function( assert ) { const describedBy = 'targetId'; this.set( 'ariaDescribedBy', describedBy ); this.render( hbs` {{#sl-modal ariaDescribedBy=ariaDescribedBy}} {{sl-modal-header title="Simple Example"}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} ` ); assert.strictEqual( this.$( '>:first-child' ).attr( 'aria-describedby' ), describedBy ); }); test( 'aria-hidden is true', function( assert ) { this.render( template ); assert.strictEqual( this.$( '>:first-child' ).attr( 'aria-hidden' ), 'true' ); }); test( 'aria-labelledby is set', function( assert ) { this.render( template ); assert.strictEqual( this.$( '>:first-child' ).attr( 'aria-labelledby' ), this.$( '>:first-child' ).find( '.modal-title' ).prop( 'id' ), '"aria-labelledby" points to correct element' ); }); test( 'Component responds to "hide" stream action', function( assert ) { this.set( 'stream', mockStream ); this.set( 'hide', sinon.spy() ); this.render( hbs` {{#sl-modal stream=stream hide=hide}} {{sl-modal-header title="Simple Example"}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} ` ); mockStream.actions[ 'hide' ](); assert.ok( this.get( 'hide' ).calledOnce, 'hide() was triggered successfully' ); }); test( 'Component responds to "show" stream action', function( assert ) { this.set( 'stream', mockStream ); this.set( 'show', sinon.spy() ); this.render( hbs` {{#sl-modal stream=stream show=show}} {{sl-modal-header title="Simple Example"}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} ` ); mockStream.actions[ 'show' ](); assert.ok( this.get( 'show' ).calledOnce, 'hide() was triggered successfully' ); }); test( 'Components do not cross-contaminate', function( assert ) { assert.expect( 6 ); const spyModal = sinon.spy( Ember.$.fn, 'modal' ); const spyOn = sinon.spy( Ember.$.fn, 'on' ); this.render( hbs` {{#sl-modal}} {{sl-modal-header title="Simple Example 1"}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} ` ); const $first = this.$( '>:first-child' ); assert.deepEqual( spyModal.thisValues.map( ( i ) => i.get( 0 ) ), spyModal.thisValues.map( ( ) => $first.get( 0 ) ), 'First modal attaches to the proper element ($.fn.modal)' ); assert.deepEqual( spyOn.thisValues.map( ( i ) => i.get( 0 ) ), spyOn.thisValues.map( ( ) => $first.get( 0 ) ), 'First modal attaches to the proper element ($.fn.on)' ); spyModal.reset(); spyOn.reset(); this.render( hbs` {{#sl-modal}} {{sl-modal-header title="Simple Example 2"}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} ` ); const $second = this.$( '>:first-child' ); assert.deepEqual( spyModal.thisValues.map( ( i ) => i.get( 0 ) ), spyModal.thisValues.map( ( ) => $second.get( 0 ) ), 'Second modal attaches to the proper element ($.fn.modal)' ); assert.deepEqual( spyOn.thisValues.map( ( i ) => i.get( 0 ) ), spyOn.thisValues.map( ( ) => $second.get( 0 ) ), 'Second modal attaches to the proper element ($.fn.on)' ); spyModal.reset(); spyOn.reset(); $second.modal( 'show' ); assert.deepEqual( spyModal.thisValues.map( ( i ) => i.get( 0 ) ), spyModal.thisValues.map( ( ) => $second.get( 0 ) ), 'Second modal acts on the proper dom element (1/2)' ); spyModal.reset(); $second.modal( 'hide' ); assert.deepEqual( spyModal.thisValues.map( ( i ) => i.get( 0 ) ), spyModal.thisValues.map( ( ) => $second.get( 0 ) ), 'Second modal acts on the proper dom element (2/2)' ); Ember.$.fn.modal.restore(); Ember.$.fn.on.restore(); });
tests/integration/components/sl-modal-test.js
import Ember from 'ember'; import hbs from 'htmlbars-inline-precompile'; import { moduleForComponent, test } from 'ember-qunit'; import sinon from 'sinon'; const mockStream = { actions: {}, on( actionName, handler ) { this.actions[ actionName ] = handler; }, subject: { dispose() { mockStream.actions = {}; }, onCompleted() {} } }; const template = hbs` {{#sl-modal as |modal|}} {{sl-modal-header title="Simple Example" ariaLabelledBy=modal.ariaLabelledBy }} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} `; moduleForComponent( 'sl-modal', 'Integration | Component | sl modal', { afterEach() { this.$( '.modal' ).remove(); Ember.$( '.modal-backdrop' ).remove(); }, integration: true }); test( 'Check setting of template properties', function( assert ) { // we currently only pass thru the backdrop parameter assert.expect( 6 ); const spy = sinon.spy( Ember.$.fn, 'modal' ); // props passed to bootstrap modal that are not bound to template const nonTemplateProps = { 'keyboard': true, 'show': false }; // all props set one way const template1 = hbs` {{#sl-modal backdrop=false animated=false }} {{sl-modal-header}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} `; // all props set another way const template2 = hbs` {{#sl-modal backdrop=true animated=true }} {{sl-modal-header}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} `; // all props allowed to default const template3 = hbs` {{#sl-modal}} {{sl-modal-header}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} `; this.render( template1 ); const $first = this.$( '>:first-child' ); assert.deepEqual( spy.args[0][0], Ember.$.extend( { 'backdrop': false }, nonTemplateProps ), 'All parameters passed thru to jQuery.fn.modal (checking setting) 1/3' ); this.render( template2 ); const $second = this.$( '>:first-child' ); assert.deepEqual( spy.args[1][0], Ember.$.extend( { 'backdrop': true }, nonTemplateProps ), 'All parameters passed thru to jQuery.fn.modal (checking setting) 2/3' ); this.render( template3 ); const $third = this.$( '>:first-child' ); assert.deepEqual( spy.args[2][0], Ember.$.extend( { 'backdrop': true }, nonTemplateProps ), 'All parameters passed thru to jQuery.fn.modal (checking defaults) 3/3' ); assert.strictEqual( $first.filter( ':not(.fade)' ).length, 1, 'fade class not present when animated set to false' ); assert.strictEqual( $second.filter( '.fade' ).length, 1, 'fade class present when animated set to true' ); assert.strictEqual( $third.filter( '.fade' ).length, 1, 'fade class present when animated not set' ); Ember.$.fn.modal.restore(); }); test( 'Classes are present', function( assert ) { this.render( template ); assert.ok( this.$( '>:first-child' ).hasClass( 'modal' ), 'Has class modal' ); }); test( 'Listeners are setup and firing appropriately', function( assert ) { assert.expect( 4 ); const beforeShowDone = assert.async(); const afterShowDone = assert.async(); const beforeHideDone = assert.async(); const afterHideDone = assert.async(); const beforeShow = () => { assert.ok( true, 'beforeShow was triggered' ); beforeShowDone(); }; const afterShow = () => { assert.ok( true, 'afterShow was triggered' ); afterShowDone(); }; const beforeHide = () => { assert.ok( true, 'beforeHide was triggered' ); beforeHideDone(); }; const afterHide = () => { assert.ok( true, 'afterHide was triggered' ); afterHideDone(); }; this.on( 'beforeShow', beforeShow ); this.on( 'afterShow', afterShow ); this.on( 'beforeHide', beforeHide ); this.on( 'afterHide', afterHide ); this.render( hbs` {{#sl-modal name="testing" beforeShow="beforeShow" afterShow="afterShow" beforeHide="beforeHide" afterHide="afterHide" }} {{sl-modal-header}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} ` ); Ember.run( () => { this.$( '>:first-child' ).modal( 'show' ); this.$( '>:first-child' ).modal( 'hide' ); }); this.hideModal = false; }); test( 'Property isOpen is set appropriately', function( assert ) { this.set( 'isOpen' ); this.render( hbs` {{#sl-modal isOpen=isOpen}} {{sl-modal-header title="Simple Example"}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} ` ); Ember.run( () => { this.$( '>:first-child' ).trigger( 'shown.bs.modal' ); }); assert.strictEqual( this.get( 'isOpen' ), true, 'isOpen was set to true when modal show event was triggered' ); Ember.run( () => { this.$( '>:first-child' ).trigger( 'hidden.bs.modal' ); }); assert.strictEqual( this.get( 'isOpen' ), false, 'isOpen was set to false when modal close event was triggered' ); }); test( 'Closing of modal using close button works', function( assert ) { assert.expect( 1 ); const closeDone = assert.async(); const modalClosed = () => { assert.ok( true, 'Modal was closed' ); closeDone(); }; this.on( 'modalClosed', modalClosed ); this.render( hbs` {{#sl-modal afterHide="modalClosed"}} {{sl-modal-header title="Simple Example"}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} ` ); Ember.run( () => { this.$( '>:first-child' ).modal( 'show' ); this.$( '>:first-child' ).find( '.close' ).click(); }); }); test( 'ariaDescribedBy attribute binding', function( assert ) { const describedBy = 'targetId'; this.set( 'ariaDescribedBy', describedBy ); this.render( hbs` {{#sl-modal ariaDescribedBy=ariaDescribedBy}} {{sl-modal-header title="Simple Example"}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} ` ); assert.strictEqual( this.$( '>:first-child' ).attr( 'aria-describedby' ), describedBy ); }); test( 'aria-hidden is true', function( assert ) { this.render( template ); assert.strictEqual( this.$( '>:first-child' ).attr( 'aria-hidden' ), 'true' ); }); test( 'aria-labelledby is set', function( assert ) { this.render( template ); assert.strictEqual( this.$( '>:first-child' ).attr( 'aria-labelledby' ), this.$( '>:first-child' ).find( '.modal-title' ).prop( 'id' ), '"aria-labelledby" points to correct element' ); }); test( 'Component responds to "hide" stream action', function( assert ) { this.set( 'stream', mockStream ); this.set( 'hide', sinon.spy() ); this.render( hbs` {{#sl-modal stream=stream hide=hide}} {{sl-modal-header title="Simple Example"}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} ` ); mockStream.actions[ 'hide' ](); assert.ok( this.get( 'hide' ).calledOnce, 'hide() was triggered successfully' ); }); test( 'Component responds to "show" stream action', function( assert ) { this.set( 'stream', mockStream ); this.set( 'show', sinon.spy() ); this.render( hbs` {{#sl-modal stream=stream show=show}} {{sl-modal-header title="Simple Example"}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} ` ); mockStream.actions[ 'show' ](); assert.ok( this.get( 'show' ).calledOnce, 'hide() was triggered successfully' ); }); test( 'Components do not cross-contaminate', function( assert ) { assert.expect( 6 ); const spyModal = sinon.spy( Ember.$.fn, 'modal' ); const spyOn = sinon.spy( Ember.$.fn, 'on' ); const arrayOfJQtoArrayOfDom = function( arr ) { const newArr = []; $.each( arr, function( key, val ) { newArr.push( val.get( 0 ) ); } ); return newArr; }; this.render( hbs` {{#sl-modal}} {{sl-modal-header title="Simple Example 1"}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} ` ); const $first = this.$( '>:first-child' ); assert.deepEqual( arrayOfJQtoArrayOfDom( spyModal.thisValues ), new Array( spyModal.thisValues.length ).fill( $first.get( 0 ) ), 'First modal attaches to the proper element ($.fn.modal)' ); assert.deepEqual( arrayOfJQtoArrayOfDom( spyOn.thisValues ), new Array( spyOn.thisValues.length ).fill( $first.get( 0 ) ), 'First modal attaches to the proper element ($.fn.on)' ); spyModal.reset(); spyOn.reset(); this.render( hbs` {{#sl-modal}} {{sl-modal-header title="Simple Example 2"}} {{#sl-modal-body}} <p>A simple modal example</p> {{/sl-modal-body}} {{sl-modal-footer}} {{/sl-modal}} ` ); const $second = this.$( '>:first-child' ); assert.deepEqual( arrayOfJQtoArrayOfDom( spyModal.thisValues ), new Array( spyModal.thisValues.length ).fill( $second.get( 0 ) ), 'Second modal attaches to the proper element ($.fn.modal)' ); assert.deepEqual( arrayOfJQtoArrayOfDom( spyOn.thisValues ), new Array( spyOn.thisValues.length ).fill( $second.get( 0 ) ), 'Second modal attaches to the proper element ($.fn.on)' ); spyModal.reset(); spyOn.reset(); $second.modal( 'show' ); assert.deepEqual( arrayOfJQtoArrayOfDom( spyModal.thisValues ), new Array( spyModal.thisValues.length ).fill( $second.get( 0 ) ), 'Second modal acts on the proper dom element (1/2)' ); spyModal.reset(); $second.modal( 'hide' ); assert.deepEqual( arrayOfJQtoArrayOfDom( spyModal.thisValues ), new Array( spyModal.thisValues.length ).fill( $second.get( 0 ) ), 'Second modal acts on the proper dom element (2/2)' ); Ember.$.fn.modal.restore(); Ember.$.fn.on.restore(); });
cleaned up the last test to be more straight-forward
tests/integration/components/sl-modal-test.js
cleaned up the last test to be more straight-forward
<ide><path>ests/integration/components/sl-modal-test.js <ide> const spyModal = sinon.spy( Ember.$.fn, 'modal' ); <ide> const spyOn = sinon.spy( Ember.$.fn, 'on' ); <ide> <del> const arrayOfJQtoArrayOfDom = function( arr ) { <del> const newArr = []; <del> $.each( <del> arr, <del> function( key, val ) { <del> newArr.push( val.get( 0 ) ); <del> } <del> ); <del> return newArr; <del> }; <del> <ide> this.render( hbs` <ide> {{#sl-modal}} <ide> {{sl-modal-header title="Simple Example 1"}} <ide> {{sl-modal-footer}} <ide> {{/sl-modal}} <ide> ` ); <del> <add> <ide> const $first = this.$( '>:first-child' ); <ide> <ide> assert.deepEqual( <del> arrayOfJQtoArrayOfDom( spyModal.thisValues ), <del> new Array( spyModal.thisValues.length ).fill( $first.get( 0 ) ), <add> spyModal.thisValues.map( ( i ) => i.get( 0 ) ), <add> spyModal.thisValues.map( ( ) => $first.get( 0 ) ), <ide> 'First modal attaches to the proper element ($.fn.modal)' <ide> ); <ide> <ide> assert.deepEqual( <del> arrayOfJQtoArrayOfDom( spyOn.thisValues ), <del> new Array( spyOn.thisValues.length ).fill( $first.get( 0 ) ), <add> spyOn.thisValues.map( ( i ) => i.get( 0 ) ), <add> spyOn.thisValues.map( ( ) => $first.get( 0 ) ), <ide> 'First modal attaches to the proper element ($.fn.on)' <ide> ); <ide> <ide> const $second = this.$( '>:first-child' ); <ide> <ide> assert.deepEqual( <del> arrayOfJQtoArrayOfDom( spyModal.thisValues ), <del> new Array( spyModal.thisValues.length ).fill( $second.get( 0 ) ), <add> spyModal.thisValues.map( ( i ) => i.get( 0 ) ), <add> spyModal.thisValues.map( ( ) => $second.get( 0 ) ), <ide> 'Second modal attaches to the proper element ($.fn.modal)' <ide> ); <ide> <ide> assert.deepEqual( <del> arrayOfJQtoArrayOfDom( spyOn.thisValues ), <del> new Array( spyOn.thisValues.length ).fill( $second.get( 0 ) ), <add> spyOn.thisValues.map( ( i ) => i.get( 0 ) ), <add> spyOn.thisValues.map( ( ) => $second.get( 0 ) ), <ide> 'Second modal attaches to the proper element ($.fn.on)' <ide> ); <ide> <ide> $second.modal( 'show' ); <ide> <ide> assert.deepEqual( <del> arrayOfJQtoArrayOfDom( spyModal.thisValues ), <del> new Array( spyModal.thisValues.length ).fill( $second.get( 0 ) ), <add> spyModal.thisValues.map( ( i ) => i.get( 0 ) ), <add> spyModal.thisValues.map( ( ) => $second.get( 0 ) ), <ide> 'Second modal acts on the proper dom element (1/2)' <ide> ); <ide> <ide> $second.modal( 'hide' ); <ide> <ide> assert.deepEqual( <del> arrayOfJQtoArrayOfDom( spyModal.thisValues ), <del> new Array( spyModal.thisValues.length ).fill( $second.get( 0 ) ), <add> spyModal.thisValues.map( ( i ) => i.get( 0 ) ), <add> spyModal.thisValues.map( ( ) => $second.get( 0 ) ), <ide> 'Second modal acts on the proper dom element (2/2)' <ide> ); <ide>
Java
apache-2.0
88030526bae0ffd4a6704c90d20eb0904c6fcd86
0
vvv1559/intellij-community,xfournet/intellij-community,allotria/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,FHannes/intellij-community,da1z/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,da1z/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,hurricup/intellij-community,hurricup/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,semonte/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,asedunov/intellij-community,allotria/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,asedunov/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,allotria/intellij-community,fitermay/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,allotria/intellij-community,fitermay/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,FHannes/intellij-community,signed/intellij-community,signed/intellij-community,fitermay/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,allotria/intellij-community,signed/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,semonte/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,apixandru/intellij-community,asedunov/intellij-community,asedunov/intellij-community,asedunov/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,da1z/intellij-community,allotria/intellij-community,asedunov/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,allotria/intellij-community,hurricup/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,ibinti/intellij-community,FHannes/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,apixandru/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,vvv1559/intellij-community,signed/intellij-community,apixandru/intellij-community,signed/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,fitermay/intellij-community,fitermay/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,asedunov/intellij-community,da1z/intellij-community,asedunov/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,da1z/intellij-community,semonte/intellij-community,apixandru/intellij-community,hurricup/intellij-community,hurricup/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,signed/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,asedunov/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,FHannes/intellij-community,allotria/intellij-community,semonte/intellij-community,asedunov/intellij-community,ibinti/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,apixandru/intellij-community,signed/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,ibinti/intellij-community,xfournet/intellij-community,semonte/intellij-community,signed/intellij-community,youdonghai/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,semonte/intellij-community,semonte/intellij-community,allotria/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,da1z/intellij-community,asedunov/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,signed/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,xfournet/intellij-community,allotria/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,da1z/intellij-community,vvv1559/intellij-community
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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.intellij.util; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.WString; import com.sun.jna.ptr.IntByReference; import com.sun.jna.win32.StdCallLibrary; import org.jetbrains.annotations.NotNull; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; @SuppressWarnings({"UseOfSystemOutOrSystemErr", "CallToPrintStackTrace"}) public class Restarter { private Restarter() { } private static int getRestartCode() { return SystemProperties.getIntProperty("jb.restart.code", 0); } public static boolean isSupported() { if (getRestartCode() != 0) return true; if (SystemInfo.isWindows) return new File(PathManager.getBinPath(), "restarter.exe").exists(); if (SystemInfo.isMac) return PathManager.getHomePath().contains(".app"); return false; } public static int scheduleRestart(@NotNull String... beforeRestart) throws IOException { try { int restartCode = getRestartCode(); if (restartCode != 0) { runCommand(beforeRestart); return restartCode; } else if (SystemInfo.isWindows) { restartOnWindows(beforeRestart); return 0; } else if (SystemInfo.isMac) { restartOnMac(beforeRestart); return 0; } } catch (Throwable t) { throw new IOException("Cannot restart application: " + t.getMessage(), t); } runCommand(beforeRestart); throw new IOException("Cannot restart application: not supported."); } private static void runCommand(String... beforeRestart) throws IOException { if (beforeRestart.length == 0) return; File restartDir = new File(getRestarterDir()); String systemPath = new File(System.getProperty("user.home") + "/." + System.getProperty("idea.paths.selector") + "/system/restart").getPath(); if (! systemPath.equals(restartDir.getPath())){ throw new IOException("idea.system.path was changed. Restart is not supported."); } if (!FileUtilRt.createDirectory(restartDir)) { throw new IOException("Cannot create dir: " + restartDir); } File restarter = new File(restartDir, "restarter.sh"); BufferedWriter output = new BufferedWriter(new FileWriter(restarter)); try { output.write("#!/bin/sh\n"); for (int i = 0; i < beforeRestart.length; i++) { output.write(beforeRestart[i]); if (i <= beforeRestart.length - 2) output.write(' '); if (i >= beforeRestart.length - 2) output.write('"'); } output.write('\n'); } finally { output.close(); } if (!restarter.setExecutable(true, true)) { throw new IOException("Cannot make file executable: " + restarter); } } private static void restartOnWindows(@NotNull final String... beforeRestart) throws IOException { Kernel32 kernel32 = (Kernel32)Native.loadLibrary("kernel32", Kernel32.class); Shell32 shell32 = (Shell32)Native.loadLibrary("shell32", Shell32.class); final int pid = kernel32.GetCurrentProcessId(); final IntByReference argc = new IntByReference(); Pointer argv_ptr = shell32.CommandLineToArgvW(kernel32.GetCommandLineW(), argc); final String[] argv = argv_ptr.getWideStringArray(0, argc.getValue()); kernel32.LocalFree(argv_ptr); doScheduleRestart(new File(PathManager.getBinPath(), "restarter.exe"), new Consumer<List<String>>() { @Override public void consume(List<String> commands) { Collections.addAll(commands, String.valueOf(pid), String.valueOf(beforeRestart.length)); Collections.addAll(commands, beforeRestart); Collections.addAll(commands, String.valueOf(argv.length)); Collections.addAll(commands, argv); } }); // Since the process ID is passed through the command line, we want to make sure that we don't exit before the "restarter" // process has a chance to open the handle to our process, and that it doesn't wait for the termination of an unrelated // process which happened to have the same process ID. TimeoutUtil.sleep(500); } private static void restartOnMac(@NotNull final String... beforeRestart) throws IOException { String homePath = PathManager.getHomePath(); int p = homePath.indexOf(".app"); if (p < 0) throw new IOException("Application bundle not found: " + homePath); final String bundlePath = homePath.substring(0, p + 4); doScheduleRestart(new File(PathManager.getBinPath(), "restarter"), new Consumer<List<String>>() { @Override public void consume(List<String> commands) { Collections.addAll(commands, bundlePath); Collections.addAll(commands, beforeRestart); } }); } private static String[] getRestartArgv(String[] argv) { int countArgs = argv.length; for (int i = argv.length-1; i >=0; i--) { if (argv[i].endsWith("com.intellij.idea.Main") || argv[i].endsWith(".exe")) { countArgs = i + 1; if ("0".equals(argv[2])) { // update number of args in according with removed cmd line args argv[3] = String.valueOf(Integer.valueOf(argv[3]) - (argv.length - (i+1))); } if (argv[i].endsWith(".exe") && argv[i].indexOf(File.separator) < 0) { //absolute path argv[i] = new File(PathManager.getBinPath(), argv[i]).getPath(); } break; } } String[] restartArg = new String[countArgs]; System.arraycopy(argv, 0, restartArg, 0, countArgs); return restartArg; } private static void doScheduleRestart(File restarterFile, Consumer<List<String>> argumentsBuilder) throws IOException { List<String> commands = new ArrayList<String>(); commands.add(createTempExecutable(restarterFile).getPath()); argumentsBuilder.consume(commands); String[] argv = getRestartArgv(ArrayUtil.toStringArray(commands)); Runtime.getRuntime().exec(argv); } public static String getRestarterDir() { return PathManager.getSystemPath() + "/restart"; } public static File createTempExecutable(File executable) throws IOException { File executableDir = new File(getRestarterDir()); if (!FileUtilRt.createDirectory(executableDir)) throw new IOException("Cannot create dir: " + executableDir); File copy = new File(executableDir.getPath() + "/" + executable.getName()); if (!FileUtilRt.ensureCanCreateFile(copy) || (copy.exists() && !copy.delete())) { String ext = FileUtilRt.getExtension(executable.getName()); copy = FileUtilRt.createTempFile(executableDir, FileUtilRt.getNameWithoutExtension(copy.getName()), StringUtil.isEmptyOrSpaces(ext) ? ".tmp" : ("." + ext), true, false); } FileUtilRt.copy(executable, copy); if (!copy.setExecutable(executable.canExecute())) throw new IOException("Cannot make file executable: " + copy); return copy; } private interface Kernel32 extends StdCallLibrary { int GetCurrentProcessId(); WString GetCommandLineW(); Pointer LocalFree(Pointer pointer); } private interface Shell32 extends StdCallLibrary { Pointer CommandLineToArgvW(WString command_line, IntByReference argc); } }
platform/util/src/com/intellij/util/Restarter.java
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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.intellij.util; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.WString; import com.sun.jna.ptr.IntByReference; import com.sun.jna.win32.StdCallLibrary; import org.jetbrains.annotations.NotNull; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; @SuppressWarnings({"UseOfSystemOutOrSystemErr", "CallToPrintStackTrace"}) public class Restarter { private Restarter() { } private static int getRestartCode() { return SystemProperties.getIntProperty("jb.restart.code", 0); } public static boolean isSupported() { if (getRestartCode() != 0) return true; if (SystemInfo.isWindows) return new File(PathManager.getBinPath(), "restarter.exe").exists(); if (SystemInfo.isMac) return PathManager.getHomePath().contains(".app"); return false; } public static int scheduleRestart(@NotNull String... beforeRestart) throws IOException { try { int restartCode = getRestartCode(); if (restartCode != 0) { runCommand(beforeRestart); return restartCode; } else if (SystemInfo.isWindows) { restartOnWindows(beforeRestart); return 0; } else if (SystemInfo.isMac) { restartOnMac(beforeRestart); return 0; } } catch (Throwable t) { throw new IOException("Cannot restart application: " + t.getMessage(), t); } runCommand(beforeRestart); throw new IOException("Cannot restart application: not supported."); } private static void runCommand(String... beforeRestart) throws IOException { if (beforeRestart.length == 0) return; File restartDir = new File(getRestarterDir()); String systemPath = new File(System.getProperty("user.home") + "/." + System.getProperty("idea.paths.selector") + "/system/restart").getPath(); if (! systemPath.equals(restartDir.getPath())){ throw new IOException("idea.system.path was changed. Restart is not supported."); } if (!FileUtilRt.createDirectory(restartDir)) { throw new IOException("Cannot create dir: " + restartDir); } File restarter = new File(restartDir, "restarter.sh"); BufferedWriter output = new BufferedWriter(new FileWriter(restarter)); try { output.write("#!/bin/sh\n"); for (int i = 0; i < beforeRestart.length; i++) { output.write(beforeRestart[i]); if (i <= beforeRestart.length - 2) output.write(' '); if (i >= beforeRestart.length - 2) output.write('"'); } output.write('\n'); } finally { output.close(); } if (!restarter.setExecutable(true, true)) { throw new IOException("Cannot make file executable: " + restarter); } } private static void restartOnWindows(@NotNull final String... beforeRestart) throws IOException { Kernel32 kernel32 = (Kernel32)Native.loadLibrary("kernel32", Kernel32.class); Shell32 shell32 = (Shell32)Native.loadLibrary("shell32", Shell32.class); final int pid = kernel32.GetCurrentProcessId(); final IntByReference argc = new IntByReference(); Pointer argv_ptr = shell32.CommandLineToArgvW(kernel32.GetCommandLineW(), argc); final String[] argv = argv_ptr.getStringArray(0, argc.getValue(), true); kernel32.LocalFree(argv_ptr); doScheduleRestart(new File(PathManager.getBinPath(), "restarter.exe"), new Consumer<List<String>>() { @Override public void consume(List<String> commands) { Collections.addAll(commands, String.valueOf(pid), String.valueOf(beforeRestart.length)); Collections.addAll(commands, beforeRestart); Collections.addAll(commands, String.valueOf(argv.length)); Collections.addAll(commands, argv); } }); // Since the process ID is passed through the command line, we want to make sure that we don't exit before the "restarter" // process has a chance to open the handle to our process, and that it doesn't wait for the termination of an unrelated // process which happened to have the same process ID. TimeoutUtil.sleep(500); } private static void restartOnMac(@NotNull final String... beforeRestart) throws IOException { String homePath = PathManager.getHomePath(); int p = homePath.indexOf(".app"); if (p < 0) throw new IOException("Application bundle not found: " + homePath); final String bundlePath = homePath.substring(0, p + 4); doScheduleRestart(new File(PathManager.getBinPath(), "restarter"), new Consumer<List<String>>() { @Override public void consume(List<String> commands) { Collections.addAll(commands, bundlePath); Collections.addAll(commands, beforeRestart); } }); } private static String[] getRestartArgv(String[] argv) { int countArgs = argv.length; for (int i = argv.length-1; i >=0; i--) { if (argv[i].endsWith("com.intellij.idea.Main") || argv[i].endsWith(".exe")) { countArgs = i + 1; if ("0".equals(argv[2])) { // update number of args in according with removed cmd line args argv[3] = String.valueOf(Integer.valueOf(argv[3]) - (argv.length - (i+1))); } if (argv[i].endsWith(".exe") && argv[i].indexOf(File.separator) < 0) { //absolute path argv[i] = new File(PathManager.getBinPath(), argv[i]).getPath(); } break; } } String[] restartArg = new String[countArgs]; System.arraycopy(argv, 0, restartArg, 0, countArgs); return restartArg; } private static void doScheduleRestart(File restarterFile, Consumer<List<String>> argumentsBuilder) throws IOException { List<String> commands = new ArrayList<String>(); commands.add(createTempExecutable(restarterFile).getPath()); argumentsBuilder.consume(commands); String[] argv = getRestartArgv(ArrayUtil.toStringArray(commands)); Runtime.getRuntime().exec(argv); } public static String getRestarterDir() { return PathManager.getSystemPath() + "/restart"; } public static File createTempExecutable(File executable) throws IOException { File executableDir = new File(getRestarterDir()); if (!FileUtilRt.createDirectory(executableDir)) throw new IOException("Cannot create dir: " + executableDir); File copy = new File(executableDir.getPath() + "/" + executable.getName()); if (!FileUtilRt.ensureCanCreateFile(copy) || (copy.exists() && !copy.delete())) { String ext = FileUtilRt.getExtension(executable.getName()); copy = FileUtilRt.createTempFile(executableDir, FileUtilRt.getNameWithoutExtension(copy.getName()), StringUtil.isEmptyOrSpaces(ext) ? ".tmp" : ("." + ext), true, false); } FileUtilRt.copy(executable, copy); if (!copy.setExecutable(executable.canExecute())) throw new IOException("Cannot make file executable: " + copy); return copy; } private interface Kernel32 extends StdCallLibrary { int GetCurrentProcessId(); WString GetCommandLineW(); Pointer LocalFree(Pointer pointer); } private interface Shell32 extends StdCallLibrary { Pointer CommandLineToArgvW(WString command_line, IntByReference argc); } }
Cleanup (deprecated API usage)
platform/util/src/com/intellij/util/Restarter.java
Cleanup (deprecated API usage)
<ide><path>latform/util/src/com/intellij/util/Restarter.java <ide> final int pid = kernel32.GetCurrentProcessId(); <ide> final IntByReference argc = new IntByReference(); <ide> Pointer argv_ptr = shell32.CommandLineToArgvW(kernel32.GetCommandLineW(), argc); <del> final String[] argv = argv_ptr.getStringArray(0, argc.getValue(), true); <add> final String[] argv = argv_ptr.getWideStringArray(0, argc.getValue()); <ide> kernel32.LocalFree(argv_ptr); <ide> <ide> doScheduleRestart(new File(PathManager.getBinPath(), "restarter.exe"), new Consumer<List<String>>() {
Java
apache-2.0
09d10b5cf388b2212f0bd8bf94ad63d13e75fa49
0
philburk/jsyn,philburk/jsyn,philburk/jsyn
/* * Copyright 2011 Phil Burk, Mobileer 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 com.jsyn.unitgen; import com.jsyn.ports.UnitInputPort; import com.jsyn.ports.UnitOutputPort; /** * Pass the input through to the output unchanged. This is often used for distributing a signal to * multiple ports inside a circuit. It can also be used as a summing node, in other words, a mixer. * * This is just like PassThrough except the input and output ports have multiple parts. * The default is two parts, ie. stereo. * * @author Phil Burk (C) 2016 Mobileer Inc * @see Circuit * @see PassThrough */ public class MultiPassThrough extends UnitGenerator implements UnitSink, UnitSource { public UnitInputPort input; public UnitOutputPort output; private final int mNumParts; /* Define Unit Ports used by connect() and set(). */ public MultiPassThrough(int numParts) { mNumParts = numParts; addPort(input = new UnitInputPort(numParts, "Input")); addPort(output = new UnitOutputPort(numParts, "Output")); } public MultiPassThrough() { this(2); // stereo } @Override public UnitInputPort getInput() { return input; } @Override public UnitOutputPort getOutput() { return output; } @Override public void generate(int start, int limit) { for (int partIndex = 0; partIndex < mNumParts; partIndex++) { double[] inputs = input.getValues(partIndex); double[] outputs = output.getValues(partIndex); for (int i = start; i < limit; i++) { outputs[i] = inputs[i]; } } } }
src/com/jsyn/unitgen/MultiPassThrough.java
/* * Copyright 2011 Phil Burk, Mobileer 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 com.jsyn.unitgen; import com.jsyn.ports.UnitInputPort; import com.jsyn.ports.UnitOutputPort; /** * Pass the input through to the output unchanged. This is often used for distributing a signal to * multiple ports inside a circuit. It can also be used as a summing node, in other words, a mixer. * * This is just like PassThrough except the input and output ports have multiple parts. * The default is two parts, ie. stereo. * * @author Phil Burk (C) 2016 Mobileer Inc * @see Circuit * @see PassThrough */ public class MultiPassThrough extends UnitGenerator implements UnitSink, UnitSource { public UnitInputPort input; public UnitOutputPort output; private int mNumParts; /* Define Unit Ports used by connect() and set(). */ public MultiPassThrough(int numParts) { mNumParts = numParts; addPort(input = new UnitInputPort(numParts, "Input")); addPort(output = new UnitOutputPort(numParts, "Output")); } public MultiPassThrough() { this(2); // stereo } @Override public UnitInputPort getInput() { return input; } @Override public UnitOutputPort getOutput() { return output; } @Override public void generate(int start, int limit) { for (int partIndex = 0; partIndex < mNumParts; partIndex++) { double[] inputs = input.getValues(partIndex); double[] outputs = output.getValues(partIndex); for (int i = start; i < limit; i++) { outputs[i] = inputs[i]; } } } }
jsyn: some minor improvements Use final in MultiPassThrough
src/com/jsyn/unitgen/MultiPassThrough.java
jsyn: some minor improvements
<ide><path>rc/com/jsyn/unitgen/MultiPassThrough.java <ide> public class MultiPassThrough extends UnitGenerator implements UnitSink, UnitSource { <ide> public UnitInputPort input; <ide> public UnitOutputPort output; <del> private int mNumParts; <add> private final int mNumParts; <ide> <ide> /* Define Unit Ports used by connect() and set(). */ <ide> public MultiPassThrough(int numParts) {
Java
apache-2.0
05f1488dc63322c513fe743ac127a0cf3f163395
0
DoudTechData/ignite,f7753/ignite,daradurvs/ignite,dmagda/incubator-ignite,leveyj/ignite,rfqu/ignite,endian675/ignite,arijitt/incubator-ignite,dlnufox/ignite,WilliamDo/ignite,dmagda/incubator-ignite,agura/incubator-ignite,tkpanther/ignite,shroman/ignite,svladykin/ignite,svladykin/ignite,StalkXT/ignite,psadusumilli/ignite,apache/ignite,vsisko/incubator-ignite,ascherbakoff/ignite,daradurvs/ignite,vsuslov/incubator-ignite,shurun19851206/ignite,thuTom/ignite,SharplEr/ignite,mcherkasov/ignite,kromulan/ignite,sk0x50/ignite,vladisav/ignite,endian675/ignite,rfqu/ignite,BiryukovVA/ignite,WilliamDo/ignite,shroman/ignite,afinka77/ignite,sylentprayer/ignite,sylentprayer/ignite,shurun19851206/ignite,apacheignite/ignite,a1vanov/ignite,murador/ignite,agura/incubator-ignite,alexzaitzev/ignite,andrey-kuznetsov/ignite,ptupitsyn/ignite,mcherkasov/ignite,ntikhonov/ignite,samaitra/ignite,daradurvs/ignite,nivanov/ignite,gargvish/ignite,leveyj/ignite,vldpyatkov/ignite,StalkXT/ignite,amirakhmedov/ignite,adeelmahmood/ignite,endian675/ignite,leveyj/ignite,sk0x50/ignite,vadopolski/ignite,SharplEr/ignite,leveyj/ignite,murador/ignite,dream-x/ignite,ntikhonov/ignite,andrey-kuznetsov/ignite,andrey-kuznetsov/ignite,BiryukovVA/ignite,nizhikov/ignite,agura/incubator-ignite,ptupitsyn/ignite,ascherbakoff/ignite,ashutakGG/incubator-ignite,DoudTechData/ignite,BiryukovVA/ignite,kromulan/ignite,psadusumilli/ignite,andrey-kuznetsov/ignite,agura/incubator-ignite,ryanzz/ignite,gargvish/ignite,kromulan/ignite,voipp/ignite,wmz7year/ignite,xtern/ignite,alexzaitzev/ignite,dlnufox/ignite,nizhikov/ignite,chandresh-pancholi/ignite,SomeFire/ignite,ilantukh/ignite,endian675/ignite,dlnufox/ignite,svladykin/ignite,ptupitsyn/ignite,agoncharuk/ignite,svladykin/ignite,shroman/ignite,f7753/ignite,rfqu/ignite,a1vanov/ignite,sylentprayer/ignite,vadopolski/ignite,psadusumilli/ignite,voipp/ignite,wmz7year/ignite,NSAmelchev/ignite,apacheignite/ignite,vldpyatkov/ignite,irudyak/ignite,ilantukh/ignite,xtern/ignite,tkpanther/ignite,DoudTechData/ignite,a1vanov/ignite,ntikhonov/ignite,samaitra/ignite,SomeFire/ignite,ntikhonov/ignite,tkpanther/ignite,tkpanther/ignite,vsuslov/incubator-ignite,adeelmahmood/ignite,adeelmahmood/ignite,apache/ignite,shurun19851206/ignite,ptupitsyn/ignite,ptupitsyn/ignite,voipp/ignite,nivanov/ignite,f7753/ignite,irudyak/ignite,apacheignite/ignite,vladisav/ignite,sk0x50/ignite,louishust/incubator-ignite,ashutakGG/incubator-ignite,ascherbakoff/ignite,shurun19851206/ignite,zzcclp/ignite,vadopolski/ignite,ptupitsyn/ignite,arijitt/incubator-ignite,adeelmahmood/ignite,BiryukovVA/ignite,WilliamDo/ignite,avinogradovgg/ignite,tkpanther/ignite,BiryukovVA/ignite,afinka77/ignite,thuTom/ignite,ptupitsyn/ignite,ilantukh/ignite,shroman/ignite,pperalta/ignite,SharplEr/ignite,apacheignite/ignite,psadusumilli/ignite,shroman/ignite,SharplEr/ignite,nivanov/ignite,dmagda/incubator-ignite,SharplEr/ignite,chandresh-pancholi/ignite,amirakhmedov/ignite,psadusumilli/ignite,sylentprayer/ignite,dlnufox/ignite,kromulan/ignite,murador/ignite,avinogradovgg/ignite,akuznetsov-gridgain/ignite,alexzaitzev/ignite,voipp/ignite,samaitra/ignite,shroman/ignite,dlnufox/ignite,dream-x/ignite,vsisko/incubator-ignite,daradurvs/ignite,apache/ignite,endian675/ignite,murador/ignite,agura/incubator-ignite,zzcclp/ignite,gargvish/ignite,amirakhmedov/ignite,pperalta/ignite,apache/ignite,WilliamDo/ignite,vladisav/ignite,agoncharuk/ignite,gargvish/ignite,xtern/ignite,irudyak/ignite,wmz7year/ignite,dream-x/ignite,NSAmelchev/ignite,shroman/ignite,vsisko/incubator-ignite,louishust/incubator-ignite,chandresh-pancholi/ignite,ntikhonov/ignite,sk0x50/ignite,ilantukh/ignite,daradurvs/ignite,nizhikov/ignite,mcherkasov/ignite,alexzaitzev/ignite,kromulan/ignite,xtern/ignite,endian675/ignite,BiryukovVA/ignite,vadopolski/ignite,dmagda/incubator-ignite,mcherkasov/ignite,amirakhmedov/ignite,SomeFire/ignite,nizhikov/ignite,sk0x50/ignite,xtern/ignite,vladisav/ignite,leveyj/ignite,afinka77/ignite,leveyj/ignite,voipp/ignite,f7753/ignite,SomeFire/ignite,samaitra/ignite,xtern/ignite,vldpyatkov/ignite,avinogradovgg/ignite,DoudTechData/ignite,irudyak/ignite,gargvish/ignite,wmz7year/ignite,chandresh-pancholi/ignite,vsuslov/incubator-ignite,adeelmahmood/ignite,akuznetsov-gridgain/ignite,adeelmahmood/ignite,vsisko/incubator-ignite,shroman/ignite,andrey-kuznetsov/ignite,akuznetsov-gridgain/ignite,nizhikov/ignite,zzcclp/ignite,zzcclp/ignite,daradurvs/ignite,thuTom/ignite,irudyak/ignite,StalkXT/ignite,vadopolski/ignite,apache/ignite,avinogradovgg/ignite,andrey-kuznetsov/ignite,f7753/ignite,amirakhmedov/ignite,agoncharuk/ignite,kidaa/incubator-ignite,WilliamDo/ignite,svladykin/ignite,samaitra/ignite,agura/incubator-ignite,VladimirErshov/ignite,ryanzz/ignite,xtern/ignite,pperalta/ignite,afinka77/ignite,murador/ignite,rfqu/ignite,thuTom/ignite,nizhikov/ignite,ilantukh/ignite,DoudTechData/ignite,voipp/ignite,arijitt/incubator-ignite,dmagda/incubator-ignite,shurun19851206/ignite,sk0x50/ignite,andrey-kuznetsov/ignite,vldpyatkov/ignite,kidaa/incubator-ignite,mcherkasov/ignite,VladimirErshov/ignite,WilliamDo/ignite,svladykin/ignite,amirakhmedov/ignite,thuTom/ignite,afinka77/ignite,chandresh-pancholi/ignite,avinogradovgg/ignite,arijitt/incubator-ignite,amirakhmedov/ignite,andrey-kuznetsov/ignite,mcherkasov/ignite,dream-x/ignite,tkpanther/ignite,f7753/ignite,DoudTechData/ignite,chandresh-pancholi/ignite,nivanov/ignite,NSAmelchev/ignite,murador/ignite,dream-x/ignite,NSAmelchev/ignite,samaitra/ignite,alexzaitzev/ignite,kromulan/ignite,SharplEr/ignite,pperalta/ignite,ilantukh/ignite,SomeFire/ignite,BiryukovVA/ignite,kromulan/ignite,ptupitsyn/ignite,SharplEr/ignite,BiryukovVA/ignite,pperalta/ignite,a1vanov/ignite,nivanov/ignite,ptupitsyn/ignite,StalkXT/ignite,sylentprayer/ignite,ashutakGG/incubator-ignite,zzcclp/ignite,sylentprayer/ignite,kidaa/incubator-ignite,ryanzz/ignite,samaitra/ignite,SomeFire/ignite,DoudTechData/ignite,endian675/ignite,murador/ignite,daradurvs/ignite,xtern/ignite,mcherkasov/ignite,andrey-kuznetsov/ignite,ntikhonov/ignite,BiryukovVA/ignite,alexzaitzev/ignite,vladisav/ignite,NSAmelchev/ignite,agoncharuk/ignite,arijitt/incubator-ignite,vldpyatkov/ignite,kidaa/incubator-ignite,daradurvs/ignite,SomeFire/ignite,wmz7year/ignite,rfqu/ignite,vsuslov/incubator-ignite,dlnufox/ignite,amirakhmedov/ignite,ntikhonov/ignite,VladimirErshov/ignite,dmagda/incubator-ignite,murador/ignite,a1vanov/ignite,vldpyatkov/ignite,nivanov/ignite,agura/incubator-ignite,alexzaitzev/ignite,vsuslov/incubator-ignite,StalkXT/ignite,daradurvs/ignite,wmz7year/ignite,ryanzz/ignite,leveyj/ignite,ashutakGG/incubator-ignite,StalkXT/ignite,agura/incubator-ignite,pperalta/ignite,vladisav/ignite,VladimirErshov/ignite,ashutakGG/incubator-ignite,shurun19851206/ignite,avinogradovgg/ignite,kromulan/ignite,pperalta/ignite,zzcclp/ignite,adeelmahmood/ignite,dream-x/ignite,vsisko/incubator-ignite,f7753/ignite,chandresh-pancholi/ignite,NSAmelchev/ignite,alexzaitzev/ignite,vldpyatkov/ignite,alexzaitzev/ignite,vsuslov/incubator-ignite,zzcclp/ignite,vsisko/incubator-ignite,ilantukh/ignite,chandresh-pancholi/ignite,louishust/incubator-ignite,ilantukh/ignite,SharplEr/ignite,ascherbakoff/ignite,ascherbakoff/ignite,afinka77/ignite,SomeFire/ignite,apacheignite/ignite,apacheignite/ignite,daradurvs/ignite,SomeFire/ignite,apacheignite/ignite,ashutakGG/incubator-ignite,nizhikov/ignite,dream-x/ignite,sylentprayer/ignite,ascherbakoff/ignite,dmagda/incubator-ignite,thuTom/ignite,ryanzz/ignite,apache/ignite,NSAmelchev/ignite,irudyak/ignite,apache/ignite,louishust/incubator-ignite,agoncharuk/ignite,dream-x/ignite,VladimirErshov/ignite,voipp/ignite,ryanzz/ignite,psadusumilli/ignite,VladimirErshov/ignite,VladimirErshov/ignite,BiryukovVA/ignite,voipp/ignite,ryanzz/ignite,ryanzz/ignite,ascherbakoff/ignite,nizhikov/ignite,thuTom/ignite,gargvish/ignite,tkpanther/ignite,avinogradovgg/ignite,kidaa/incubator-ignite,samaitra/ignite,vadopolski/ignite,ascherbakoff/ignite,arijitt/incubator-ignite,apache/ignite,vsisko/incubator-ignite,zzcclp/ignite,afinka77/ignite,dlnufox/ignite,ascherbakoff/ignite,vadopolski/ignite,ntikhonov/ignite,endian675/ignite,irudyak/ignite,louishust/incubator-ignite,rfqu/ignite,gargvish/ignite,pperalta/ignite,sk0x50/ignite,wmz7year/ignite,gargvish/ignite,andrey-kuznetsov/ignite,chandresh-pancholi/ignite,nizhikov/ignite,a1vanov/ignite,akuznetsov-gridgain/ignite,dmagda/incubator-ignite,tkpanther/ignite,StalkXT/ignite,f7753/ignite,samaitra/ignite,agoncharuk/ignite,SomeFire/ignite,akuznetsov-gridgain/ignite,dlnufox/ignite,sylentprayer/ignite,vladisav/ignite,psadusumilli/ignite,irudyak/ignite,rfqu/ignite,nivanov/ignite,samaitra/ignite,NSAmelchev/ignite,a1vanov/ignite,mcherkasov/ignite,psadusumilli/ignite,shroman/ignite,apacheignite/ignite,wmz7year/ignite,apache/ignite,SharplEr/ignite,NSAmelchev/ignite,sk0x50/ignite,agoncharuk/ignite,VladimirErshov/ignite,amirakhmedov/ignite,WilliamDo/ignite,irudyak/ignite,a1vanov/ignite,shurun19851206/ignite,DoudTechData/ignite,vsisko/incubator-ignite,louishust/incubator-ignite,vladisav/ignite,xtern/ignite,voipp/ignite,nivanov/ignite,sk0x50/ignite,akuznetsov-gridgain/ignite,WilliamDo/ignite,ptupitsyn/ignite,svladykin/ignite,StalkXT/ignite,shroman/ignite,thuTom/ignite,rfqu/ignite,ilantukh/ignite,leveyj/ignite,afinka77/ignite,agoncharuk/ignite,ilantukh/ignite,vadopolski/ignite,vldpyatkov/ignite,kidaa/incubator-ignite,StalkXT/ignite,shurun19851206/ignite,adeelmahmood/ignite
/* * 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.ignite.spi.discovery.tcp; import org.apache.ignite.*; import org.apache.ignite.cluster.*; import org.apache.ignite.configuration.*; import org.apache.ignite.events.*; import org.apache.ignite.internal.*; import org.apache.ignite.internal.util.*; import org.apache.ignite.internal.util.io.*; import org.apache.ignite.internal.util.typedef.*; import org.apache.ignite.internal.util.typedef.internal.*; import org.apache.ignite.lang.*; import org.apache.ignite.resources.*; import org.apache.ignite.spi.*; import org.apache.ignite.spi.discovery.tcp.ipfinder.*; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.*; import org.apache.ignite.spi.discovery.tcp.messages.*; import org.apache.ignite.testframework.*; import org.apache.ignite.testframework.junits.common.*; import org.jetbrains.annotations.*; import java.io.*; import java.net.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import static java.util.concurrent.TimeUnit.*; import static org.apache.ignite.events.EventType.*; /** * Client-based discovery tests. */ public class TcpClientDiscoverySpiSelfTest extends GridCommonAbstractTest { /** */ private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true); /** */ private static final AtomicInteger srvIdx = new AtomicInteger(); /** */ private static final AtomicInteger clientIdx = new AtomicInteger(); /** */ private static Collection<UUID> srvNodeIds; /** */ private static Collection<UUID> clientNodeIds; /** */ private static int clientsPerSrv; /** */ private static CountDownLatch srvJoinedLatch; /** */ private static CountDownLatch srvLeftLatch; /** */ private static CountDownLatch srvFailedLatch; /** */ private static CountDownLatch clientJoinedLatch; /** */ private static CountDownLatch clientLeftLatch; /** */ private static CountDownLatch clientFailedLatch; /** */ private static CountDownLatch msgLatch; /** */ private UUID nodeId; /** */ private TcpDiscoveryVmIpFinder clientIpFinder; /** */ private long joinTimeout = TcpClientDiscoverySpi.DFLT_JOIN_TIMEOUT; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); cfg.setLocalHost("127.0.0.1"); if (gridName.startsWith("server")) { TcpDiscoverySpi disco = new TcpDiscoverySpi(); disco.setIpFinder(IP_FINDER); cfg.setDiscoverySpi(disco); } else if (gridName.startsWith("client")) { TcpClientDiscoverySpi disco = new TestTcpClientDiscovery(); disco.setJoinTimeout(joinTimeout); TcpDiscoveryVmIpFinder ipFinder; if (clientIpFinder != null) ipFinder = clientIpFinder; else { ipFinder = new TcpDiscoveryVmIpFinder(); String addr = new ArrayList<>(IP_FINDER.getRegisteredAddresses()). get((clientIdx.get() - 1) / clientsPerSrv).toString(); if (addr.startsWith("/")) addr = addr.substring(1); ipFinder.setAddresses(Collections.singletonList(addr)); } disco.setIpFinder(ipFinder); cfg.setDiscoverySpi(disco); String nodeId = cfg.getNodeId().toString(); nodeId = "cc" + nodeId.substring(2); cfg.setNodeId(UUID.fromString(nodeId)); } if (nodeId != null) cfg.setNodeId(nodeId); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { Collection<InetSocketAddress> addrs = IP_FINDER.getRegisteredAddresses(); if (!F.isEmpty(addrs)) IP_FINDER.unregisterAddresses(addrs); srvIdx.set(0); clientIdx.set(0); srvNodeIds = new GridConcurrentHashSet<>(); clientNodeIds = new GridConcurrentHashSet<>(); clientsPerSrv = 2; } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { stopAllClients(true); stopAllServers(true); nodeId = null; clientIpFinder = null; joinTimeout = TcpClientDiscoverySpi.DFLT_JOIN_TIMEOUT; assert G.allGrids().isEmpty(); } /** * * @throws Exception */ public void testJoinTimeout() throws Exception { clientIpFinder = new TcpDiscoveryVmIpFinder(); joinTimeout = 1000; try { startClientNodes(1); fail("Client cannot be start because no server nodes run"); } catch (IgniteCheckedException e) { IgniteSpiException spiEx = e.getCause(IgniteSpiException.class); assert spiEx != null : e; assert spiEx.getMessage().contains("Join process timed out") : spiEx.getMessage(); } } /** * @throws Exception If failed. */ public void testClientNodeJoin() throws Exception { startServerNodes(3); startClientNodes(3); checkNodes(3, 3); srvJoinedLatch = new CountDownLatch(3); clientJoinedLatch = new CountDownLatch(3); attachListeners(3, 3); startClientNodes(1); await(srvJoinedLatch); await(clientJoinedLatch); checkNodes(3, 4); } /** * @throws Exception If failed. */ public void testClientNodeLeave() throws Exception { startServerNodes(3); startClientNodes(3); checkNodes(3, 3); srvLeftLatch = new CountDownLatch(3); clientLeftLatch = new CountDownLatch(2); attachListeners(3, 3); stopGrid("client-2"); await(srvLeftLatch); await(clientLeftLatch); checkNodes(3, 2); } /** * @throws Exception If failed. */ public void testClientNodeFail() throws Exception { startServerNodes(3); startClientNodes(3); checkNodes(3, 3); srvFailedLatch = new CountDownLatch(3); clientFailedLatch = new CountDownLatch(2); attachListeners(3, 3); failClient(2); await(srvFailedLatch); await(clientFailedLatch); checkNodes(3, 2); } /** * @throws Exception If failed. */ public void testServerNodeJoin() throws Exception { startServerNodes(3); startClientNodes(3); checkNodes(3, 3); srvJoinedLatch = new CountDownLatch(3); clientJoinedLatch = new CountDownLatch(3); attachListeners(3, 3); startServerNodes(1); await(srvJoinedLatch); await(clientJoinedLatch); checkNodes(4, 3); } /** * @throws Exception If failed. */ public void testServerNodeLeave() throws Exception { startServerNodes(3); startClientNodes(3); checkNodes(3, 3); srvLeftLatch = new CountDownLatch(2); clientLeftLatch = new CountDownLatch(3); attachListeners(3, 3); stopGrid("server-2"); await(srvLeftLatch); await(clientLeftLatch); checkNodes(2, 3); } /** * @throws Exception If failed. */ public void testServerNodeFail() throws Exception { startServerNodes(3); startClientNodes(3); checkNodes(3, 3); srvFailedLatch = new CountDownLatch(2); clientFailedLatch = new CountDownLatch(3); attachListeners(3, 3); assert U.<Map>field(G.ignite("server-2").configuration().getDiscoverySpi(), "clientMsgWorkers").isEmpty(); failServer(2); await(srvFailedLatch); await(clientFailedLatch); checkNodes(2, 3); } /** * @throws Exception If failed. */ public void testPing() throws Exception { startServerNodes(2); startClientNodes(1); Ignite srv0 = G.ignite("server-0"); Ignite srv1 = G.ignite("server-1"); Ignite client = G.ignite("client-0"); assert ((IgniteEx)srv0).context().discovery().pingNode(client.cluster().localNode().id()); assert ((IgniteEx)srv1).context().discovery().pingNode(client.cluster().localNode().id()); assert ((IgniteEx)client).context().discovery().pingNode(srv0.cluster().localNode().id()); assert ((IgniteEx)client).context().discovery().pingNode(srv1.cluster().localNode().id()); } /** * @throws Exception If failed. */ public void testPingFailedNodeFromClient() throws Exception { startServerNodes(2); startClientNodes(1); Ignite srv0 = G.ignite("server-0"); Ignite srv1 = G.ignite("server-1"); Ignite client = G.ignite("client-0"); final CountDownLatch latch = new CountDownLatch(1); ((TcpDiscoverySpi)srv1.configuration().getDiscoverySpi()).addIncomeConnectionListener(new IgniteInClosure<Socket>() { @Override public void apply(Socket sock) { try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } } }); assert ((IgniteEx)client).context().discovery().pingNode(srv0.cluster().localNode().id()); assert !((IgniteEx)client).context().discovery().pingNode(srv1.cluster().localNode().id()); latch.countDown(); } /** * @throws Exception If failed. */ public void testPingFailedClientNode() throws Exception { startServerNodes(2); startClientNodes(1); Ignite srv0 = G.ignite("server-0"); Ignite srv1 = G.ignite("server-1"); Ignite client = G.ignite("client-0"); ((TcpDiscoverySpiAdapter)srv0.configuration().getDiscoverySpi()).setAckTimeout(1000); ((TestTcpClientDiscovery)client.configuration().getDiscoverySpi()).pauseSocketWrite(); assert !((IgniteEx)srv1).context().discovery().pingNode(client.cluster().localNode().id()); assert !((IgniteEx)srv0).context().discovery().pingNode(client.cluster().localNode().id()); ((TestTcpClientDiscovery)client.configuration().getDiscoverySpi()).resumeAll(); assert ((IgniteEx)srv1).context().discovery().pingNode(client.cluster().localNode().id()); assert ((IgniteEx)srv0).context().discovery().pingNode(client.cluster().localNode().id()); } /** * @throws Exception If failed. */ public void testClientReconnectOnRouterFail() throws Exception { clientsPerSrv = 1; startServerNodes(3); startClientNodes(3); checkNodes(3, 3); setClientRouter(2, 0); srvFailedLatch = new CountDownLatch(2); clientFailedLatch = new CountDownLatch(3); attachListeners(2, 3); failServer(2); await(srvFailedLatch); await(clientFailedLatch); checkNodes(2, 3); } /** * @throws Exception If failed. */ public void testClientReconnectOnNetworkProblem() throws Exception { clientsPerSrv = 1; startServerNodes(3); startClientNodes(3); checkNodes(3, 3); setClientRouter(2, 0); srvFailedLatch = new CountDownLatch(2); clientFailedLatch = new CountDownLatch(3); attachListeners(2, 3); ((TcpClientDiscoverySpi)G.ignite("client-2").configuration().getDiscoverySpi()).brokeConnection(); G.ignite("client-2").message().remoteListen(null, new MessageListener()); // Send some discovery message. checkNodes(3, 3); } /** * @throws Exception If failed. */ public void testGetMissedMessagesOnReconnect() throws Exception { clientsPerSrv = 1; startServerNodes(3); startClientNodes(2); checkNodes(3, 2); clientLeftLatch = new CountDownLatch(1); srvLeftLatch = new CountDownLatch(2); attachListeners(2, 2); ((TestTcpClientDiscovery)G.ignite("client-1").configuration().getDiscoverySpi()).pauseAll(); stopGrid("server-2"); await(srvLeftLatch); await(srvLeftLatch); Thread.sleep(500); assert G.ignite("client-0").cluster().nodes().size() == 4; assert G.ignite("client-1").cluster().nodes().size() == 5; clientLeftLatch = new CountDownLatch(1); ((TestTcpClientDiscovery)G.ignite("client-1").configuration().getDiscoverySpi()).resumeAll(); await(clientLeftLatch); checkNodes(2, 2); } /** * @throws Exception If failed. */ public void testClientSegmentation() throws Exception { clientsPerSrv = 1; startServerNodes(3); startClientNodes(3); checkNodes(3, 3); srvFailedLatch = new CountDownLatch(2 + 2); clientFailedLatch = new CountDownLatch(2 + 2); attachListeners(2, 2); final CountDownLatch client2StoppedLatch = new CountDownLatch(1); IgnitionListener lsnr = new IgnitionListener() { @Override public void onStateChange(@Nullable String name, IgniteState state) { if (state == IgniteState.STOPPED_ON_SEGMENTATION) client2StoppedLatch.countDown(); } }; G.addListener(lsnr); try { failServer(2); await(srvFailedLatch); await(clientFailedLatch); await(client2StoppedLatch); checkNodes(2, 2); } finally { G.removeListener(lsnr); } } /** * @throws Exception If failed. */ public void testClientNodeJoinOneServer() throws Exception { startServerNodes(1); srvJoinedLatch = new CountDownLatch(1); attachListeners(1, 0); startClientNodes(1); await(srvJoinedLatch); checkNodes(1, 1); } /** * @throws Exception If failed. */ public void testClientNodeLeaveOneServer() throws Exception { startServerNodes(1); startClientNodes(1); checkNodes(1, 1); srvLeftLatch = new CountDownLatch(1); attachListeners(1, 0); stopGrid("client-0"); await(srvLeftLatch); checkNodes(1, 0); } /** * @throws Exception If failed. */ public void testClientNodeFailOneServer() throws Exception { startServerNodes(1); startClientNodes(1); checkNodes(1, 1); srvFailedLatch = new CountDownLatch(1); attachListeners(1, 0); failClient(0); await(srvFailedLatch); checkNodes(1, 0); } /** * @throws Exception If failed. */ public void testMetrics() throws Exception { startServerNodes(3); startClientNodes(3); checkNodes(3, 3); attachListeners(3, 3); assertTrue(checkMetrics(3, 3, 0)); G.ignite("client-0").compute().broadcast(F.noop()); assertTrue(GridTestUtils.waitForCondition(new PA() { @Override public boolean apply() { return checkMetrics(3, 3, 1); } }, 10000)); checkMetrics(3, 3, 1); G.ignite("server-0").compute().broadcast(F.noop()); assertTrue(GridTestUtils.waitForCondition(new PA() { @Override public boolean apply() { return checkMetrics(3, 3, 2); } }, 10000)); } /** * @param srvCnt Number of Number of server nodes. * @param clientCnt Number of client nodes. * @param execJobsCnt Expected number of executed jobs. * @return Whether metrics are correct. */ private boolean checkMetrics(int srvCnt, int clientCnt, int execJobsCnt) { for (int i = 0; i < srvCnt; i++) { Ignite g = G.ignite("server-" + i); for (ClusterNode n : g.cluster().nodes()) { if (n.metrics().getTotalExecutedJobs() != execJobsCnt) return false; } } for (int i = 0; i < clientCnt; i++) { Ignite g = G.ignite("client-" + i); for (ClusterNode n : g.cluster().nodes()) { if (n.metrics().getTotalExecutedJobs() != execJobsCnt) return false; } } return true; } /** * @throws Exception If failed. */ public void testDataExchangeFromServer() throws Exception { testDataExchange("server-0"); } /** * TODO: IGNITE-587. * * @throws Exception If failed. */ public void testDataExchangeFromClient() throws Exception { testDataExchange("client-0"); } /** * @throws Exception If failed. */ private void testDataExchange(String masterName) throws Exception { startServerNodes(2); startClientNodes(2); checkNodes(2, 2); IgniteMessaging msg = grid(masterName).message(); UUID id = null; try { id = msg.remoteListen(null, new MessageListener()); msgLatch = new CountDownLatch(4); msg.send(null, "Message 1"); await(msgLatch); startServerNodes(1); startClientNodes(1); checkNodes(3, 3); msgLatch = new CountDownLatch(6); msg.send(null, "Message 2"); await(msgLatch); } finally { if (id != null) msg.stopRemoteListen(id); } } /** * @throws Exception If any error occurs. */ public void testDuplicateId() throws Exception { startServerNodes(2); nodeId = G.ignite("server-1").cluster().localNode().id(); try { startGrid("client-0"); assert false; } catch (IgniteCheckedException e) { IgniteSpiException spiEx = e.getCause(IgniteSpiException.class); assert spiEx != null : e; assert spiEx.getMessage().contains("same ID") : spiEx.getMessage(); } } /** * @throws Exception If any error occurs. */ public void testTimeoutWaitingNodeAddedMessage() throws Exception { startServerNodes(2); final CountDownLatch cnt = new CountDownLatch(1); ((TcpDiscoverySpi)G.ignite("server-1").configuration().getDiscoverySpi()).addSendMessageListener( new IgniteInClosure<TcpDiscoveryAbstractMessage>() { @Override public void apply(TcpDiscoveryAbstractMessage msg) { try { cnt.await(10, MINUTES); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IgniteInterruptedException(e); } } }); try { startGrid("client-0"); assert false; } catch (IgniteCheckedException e) { cnt.countDown(); IgniteSpiException spiEx = e.getCause(IgniteSpiException.class); assert spiEx != null : e; assert spiEx.getMessage().contains("Join process timed out") : spiEx.getMessage(); } } /** * @throws Exception If any error occurs. */ public void testGridStartTime() throws Exception { startServerNodes(2); startClientNodes(2); long startTime = -1; for (Ignite g : G.allGrids()) { IgniteEx kernal = (IgniteEx)g; assertTrue(kernal.context().discovery().gridStartTime() > 0); if (startTime == -1) startTime = kernal.context().discovery().gridStartTime(); else assertEquals(startTime, kernal.context().discovery().gridStartTime()); } } /** * @param clientIdx Index. * @throws Exception In case of error. */ private void setClientRouter(int clientIdx, int srvIdx) throws Exception { TcpClientDiscoverySpi disco = (TcpClientDiscoverySpi)G.ignite("client-" + clientIdx).configuration().getDiscoverySpi(); TcpDiscoveryVmIpFinder ipFinder = (TcpDiscoveryVmIpFinder)disco.getIpFinder(); String addr = new ArrayList<>(IP_FINDER.getRegisteredAddresses()).get(srvIdx).toString(); if (addr.startsWith("/")) addr = addr.substring(1); ipFinder.setAddresses(Collections.singletonList(addr)); } /** * @param cnt Number of nodes. * @throws Exception In case of error. */ private void startServerNodes(int cnt) throws Exception { for (int i = 0; i < cnt; i++) { Ignite g = startGrid("server-" + srvIdx.getAndIncrement()); srvNodeIds.add(g.cluster().localNode().id()); } } /** * @param cnt Number of nodes. * @throws Exception In case of error. */ private void startClientNodes(int cnt) throws Exception { for (int i = 0; i < cnt; i++) { Ignite g = startGrid("client-" + clientIdx.getAndIncrement()); clientNodeIds.add(g.cluster().localNode().id()); } } /** * @param idx Index. */ private void failServer(int idx) { ((TcpDiscoverySpi)G.ignite("server-" + idx).configuration().getDiscoverySpi()).simulateNodeFailure(); } /** * @param idx Index. */ private void failClient(int idx) { ((TcpClientDiscoverySpi)G.ignite("client-" + idx).configuration().getDiscoverySpi()).simulateNodeFailure(); } /** * @param srvCnt Number of server nodes. * @param clientCnt Number of client nodes. */ private void attachListeners(int srvCnt, int clientCnt) throws Exception { if (srvJoinedLatch != null) { for (int i = 0; i < srvCnt; i++) { G.ignite("server-" + i).events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event evt) { info("Joined event fired on server: " + evt); srvJoinedLatch.countDown(); return true; } }, EVT_NODE_JOINED); } } if (srvLeftLatch != null) { for (int i = 0; i < srvCnt; i++) { G.ignite("server-" + i).events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event evt) { info("Left event fired on server: " + evt); srvLeftLatch.countDown(); return true; } }, EVT_NODE_LEFT); } } if (srvFailedLatch != null) { for (int i = 0; i < srvCnt; i++) { G.ignite("server-" + i).events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event evt) { info("Failed event fired on server: " + evt); srvFailedLatch.countDown(); return true; } }, EVT_NODE_FAILED); } } if (clientJoinedLatch != null) { for (int i = 0; i < clientCnt; i++) { G.ignite("client-" + i).events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event evt) { info("Joined event fired on client: " + evt); clientJoinedLatch.countDown(); return true; } }, EVT_NODE_JOINED); } } if (clientLeftLatch != null) { for (int i = 0; i < clientCnt; i++) { G.ignite("client-" + i).events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event evt) { info("Left event fired on client: " + evt); clientLeftLatch.countDown(); return true; } }, EVT_NODE_LEFT); } } if (clientFailedLatch != null) { for (int i = 0; i < clientCnt; i++) { G.ignite("client-" + i).events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event evt) { info("Failed event fired on client: " + evt); clientFailedLatch.countDown(); return true; } }, EVT_NODE_FAILED); } } } /** * @param srvCnt Number of server nodes. * @param clientCnt Number of client nodes. */ private void checkNodes(int srvCnt, int clientCnt) { for (int i = 0; i < srvCnt; i++) { Ignite g = G.ignite("server-" + i); assertTrue(srvNodeIds.contains(g.cluster().localNode().id())); assertFalse(g.cluster().localNode().isClient()); checkRemoteNodes(g, srvCnt + clientCnt - 1); } for (int i = 0; i < clientCnt; i++) { Ignite g = G.ignite("client-" + i); assertTrue(clientNodeIds.contains(g.cluster().localNode().id())); assertTrue(g.cluster().localNode().isClient()); checkRemoteNodes(g, srvCnt + clientCnt - 1); } } /** * @param ignite Grid. * @param expCnt Expected nodes count. */ @SuppressWarnings("TypeMayBeWeakened") private void checkRemoteNodes(Ignite ignite, int expCnt) { Collection<ClusterNode> nodes = ignite.cluster().forRemotes().nodes(); assertEquals(expCnt, nodes.size()); for (ClusterNode node : nodes) { UUID id = node.id(); if (clientNodeIds.contains(id)) assertTrue(node.isClient()); else if (srvNodeIds.contains(id)) assertFalse(node.isClient()); else assert false : "Unexpected node ID: " + id; } } /** * @param latch Latch. * @throws InterruptedException If interrupted. */ private void await(CountDownLatch latch) throws InterruptedException { assertTrue("Latch count: " + latch.getCount(), latch.await(10000, MILLISECONDS)); } /** */ private static class MessageListener implements IgniteBiPredicate<UUID, Object> { /** */ @IgniteInstanceResource private Ignite ignite; /** {@inheritDoc} */ @Override public boolean apply(UUID uuid, Object msg) { X.println(">>> Received [locNodeId=" + ignite.configuration().getNodeId() + ", msg=" + msg + ']'); msgLatch.countDown(); return true; } } /** * */ private static class TestTcpClientDiscovery extends TcpClientDiscoverySpi { /** */ private final Object mux = new Object(); /** */ private final AtomicBoolean writeLock = new AtomicBoolean(); /** */ private final AtomicBoolean openSockLock = new AtomicBoolean(); /** * @param lock Lock. */ private void waitFor(AtomicBoolean lock) { try { synchronized (mux) { while (lock.get()) mux.wait(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } /** * @param isPause Is lock. * @param locks Locks. */ private void pauseResumeOperation(boolean isPause, AtomicBoolean... locks) { synchronized (mux) { for (AtomicBoolean lock : locks) lock.set(isPause); mux.notifyAll(); } } /** {@inheritDoc} */ @Override protected void writeToSocket(Socket sock, TcpDiscoveryAbstractMessage msg, GridByteArrayOutputStream bout) throws IOException, IgniteCheckedException { waitFor(writeLock); super.writeToSocket(sock, msg, bout); } /** {@inheritDoc} */ @Override protected Socket openSocket(InetSocketAddress sockAddr) throws IOException { waitFor(openSockLock); return super.openSocket(sockAddr); } /** * */ public void pauseSocketWrite() { pauseResumeOperation(true, writeLock); } /** * */ public void pauseAll() { pauseResumeOperation(true, openSockLock, writeLock); brokeConnection(); } /** * */ public void resumeAll() { pauseResumeOperation(false, openSockLock, writeLock); } } }
modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpClientDiscoverySpiSelfTest.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.ignite.spi.discovery.tcp; import org.apache.ignite.*; import org.apache.ignite.cluster.*; import org.apache.ignite.configuration.*; import org.apache.ignite.events.*; import org.apache.ignite.internal.*; import org.apache.ignite.internal.util.*; import org.apache.ignite.internal.util.io.*; import org.apache.ignite.internal.util.typedef.*; import org.apache.ignite.internal.util.typedef.internal.*; import org.apache.ignite.lang.*; import org.apache.ignite.resources.*; import org.apache.ignite.spi.*; import org.apache.ignite.spi.discovery.tcp.ipfinder.*; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.*; import org.apache.ignite.spi.discovery.tcp.messages.*; import org.apache.ignite.testframework.*; import org.apache.ignite.testframework.junits.common.*; import org.jetbrains.annotations.*; import java.io.*; import java.net.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import static java.util.concurrent.TimeUnit.*; import static org.apache.ignite.events.EventType.*; /** * Client-based discovery tests. */ public class TcpClientDiscoverySpiSelfTest extends GridCommonAbstractTest { /** */ private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true); /** */ private static final AtomicInteger srvIdx = new AtomicInteger(); /** */ private static final AtomicInteger clientIdx = new AtomicInteger(); /** */ private static Collection<UUID> srvNodeIds; /** */ private static Collection<UUID> clientNodeIds; /** */ private static int clientsPerSrv; /** */ private static CountDownLatch srvJoinedLatch; /** */ private static CountDownLatch srvLeftLatch; /** */ private static CountDownLatch srvFailedLatch; /** */ private static CountDownLatch clientJoinedLatch; /** */ private static CountDownLatch clientLeftLatch; /** */ private static CountDownLatch clientFailedLatch; /** */ private static CountDownLatch msgLatch; /** */ private UUID nodeId; /** */ private TcpDiscoveryVmIpFinder clientIpFinder; /** */ private long joinTimeout = TcpClientDiscoverySpi.DFLT_JOIN_TIMEOUT; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); cfg.setLocalHost("127.0.0.1"); if (gridName.startsWith("server")) { TcpDiscoverySpi disco = new TcpDiscoverySpi(); disco.setIpFinder(IP_FINDER); cfg.setDiscoverySpi(disco); } else if (gridName.startsWith("client")) { TcpClientDiscoverySpi disco = new TestTcpClientDiscovery(); disco.setJoinTimeout(joinTimeout); TcpDiscoveryVmIpFinder ipFinder; if (clientIpFinder != null) ipFinder = clientIpFinder; else { ipFinder = new TcpDiscoveryVmIpFinder(); String addr = new ArrayList<>(IP_FINDER.getRegisteredAddresses()). get((clientIdx.get() - 1) / clientsPerSrv).toString(); if (addr.startsWith("/")) addr = addr.substring(1); ipFinder.setAddresses(Arrays.asList(addr)); } disco.setIpFinder(ipFinder); cfg.setDiscoverySpi(disco); String nodeId = cfg.getNodeId().toString(); nodeId = "cc" + nodeId.substring(2); cfg.setNodeId(UUID.fromString(nodeId)); } if (nodeId != null) cfg.setNodeId(nodeId); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { Collection<InetSocketAddress> addrs = IP_FINDER.getRegisteredAddresses(); if (!F.isEmpty(addrs)) IP_FINDER.unregisterAddresses(addrs); srvIdx.set(0); clientIdx.set(0); srvNodeIds = new GridConcurrentHashSet<>(); clientNodeIds = new GridConcurrentHashSet<>(); clientsPerSrv = 2; } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { stopAllClients(true); stopAllServers(true); nodeId = null; clientIpFinder = null; joinTimeout = TcpClientDiscoverySpi.DFLT_JOIN_TIMEOUT; assert G.allGrids().isEmpty(); } /** * * @throws Exception */ public void testJoinTimeout() throws Exception { clientIpFinder = new TcpDiscoveryVmIpFinder(); joinTimeout = 1000; try { startClientNodes(1); fail("Client cannot be start because no server nodes run"); } catch (IgniteCheckedException e) { IgniteSpiException spiEx = e.getCause(IgniteSpiException.class); assert spiEx != null : e; assert spiEx.getMessage().contains("Join process timed out") : spiEx.getMessage(); } } /** * @throws Exception If failed. */ public void testClientNodeJoin() throws Exception { startServerNodes(3); startClientNodes(3); checkNodes(3, 3); srvJoinedLatch = new CountDownLatch(3); clientJoinedLatch = new CountDownLatch(3); attachListeners(3, 3); startClientNodes(1); await(srvJoinedLatch); await(clientJoinedLatch); checkNodes(3, 4); } /** * @throws Exception If failed. */ public void testClientNodeLeave() throws Exception { startServerNodes(3); startClientNodes(3); checkNodes(3, 3); srvLeftLatch = new CountDownLatch(3); clientLeftLatch = new CountDownLatch(2); attachListeners(3, 3); stopGrid("client-2"); await(srvLeftLatch); await(clientLeftLatch); checkNodes(3, 2); } /** * @throws Exception If failed. */ public void testClientNodeFail() throws Exception { startServerNodes(3); startClientNodes(3); checkNodes(3, 3); srvFailedLatch = new CountDownLatch(3); clientFailedLatch = new CountDownLatch(2); attachListeners(3, 3); failClient(2); await(srvFailedLatch); await(clientFailedLatch); checkNodes(3, 2); } /** * @throws Exception If failed. */ public void testServerNodeJoin() throws Exception { startServerNodes(3); startClientNodes(3); checkNodes(3, 3); srvJoinedLatch = new CountDownLatch(3); clientJoinedLatch = new CountDownLatch(3); attachListeners(3, 3); startServerNodes(1); await(srvJoinedLatch); await(clientJoinedLatch); checkNodes(4, 3); } /** * @throws Exception If failed. */ public void testServerNodeLeave() throws Exception { startServerNodes(3); startClientNodes(3); checkNodes(3, 3); srvLeftLatch = new CountDownLatch(2); clientLeftLatch = new CountDownLatch(3); attachListeners(3, 3); stopGrid("server-2"); await(srvLeftLatch); await(clientLeftLatch); checkNodes(2, 3); } /** * @throws Exception If failed. */ public void testServerNodeFail() throws Exception { startServerNodes(3); startClientNodes(3); checkNodes(3, 3); srvFailedLatch = new CountDownLatch(2); clientFailedLatch = new CountDownLatch(3); attachListeners(3, 3); assert U.<Map>field(G.ignite("server-2").configuration().getDiscoverySpi(), "clientMsgWorkers").isEmpty(); failServer(2); await(srvFailedLatch); await(clientFailedLatch); checkNodes(2, 3); } /** * @throws Exception If failed. */ public void testPing() throws Exception { startServerNodes(2); startClientNodes(1); Ignite srv0 = G.ignite("server-0"); Ignite srv1 = G.ignite("server-1"); Ignite client = G.ignite("client-0"); assert ((IgniteEx)srv0).context().discovery().pingNode(client.cluster().localNode().id()); assert ((IgniteEx)srv1).context().discovery().pingNode(client.cluster().localNode().id()); assert ((IgniteEx)client).context().discovery().pingNode(srv0.cluster().localNode().id()); assert ((IgniteEx)client).context().discovery().pingNode(srv1.cluster().localNode().id()); } /** * @throws Exception If failed. */ public void testPingFailedNodeFromClient() throws Exception { startServerNodes(2); startClientNodes(1); Ignite srv0 = G.ignite("server-0"); Ignite srv1 = G.ignite("server-1"); Ignite client = G.ignite("client-0"); final CountDownLatch latch = new CountDownLatch(1); ((TcpDiscoverySpi)srv1.configuration().getDiscoverySpi()).addIncomeConnectionListener(new IgniteInClosure<Socket>() { @Override public void apply(Socket sock) { try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } } }); assert ((IgniteEx)client).context().discovery().pingNode(srv0.cluster().localNode().id()); assert !((IgniteEx)client).context().discovery().pingNode(srv1.cluster().localNode().id()); latch.countDown(); } /** * @throws Exception If failed. */ public void testPingFailedClientNode() throws Exception { startServerNodes(2); startClientNodes(1); Ignite srv0 = G.ignite("server-0"); Ignite srv1 = G.ignite("server-1"); Ignite client = G.ignite("client-0"); ((TcpDiscoverySpiAdapter)srv0.configuration().getDiscoverySpi()).setAckTimeout(1000); ((TestTcpClientDiscovery)client.configuration().getDiscoverySpi()).pauseSocketWrite(); assert !((IgniteEx)srv1).context().discovery().pingNode(client.cluster().localNode().id()); assert !((IgniteEx)srv0).context().discovery().pingNode(client.cluster().localNode().id()); ((TestTcpClientDiscovery)client.configuration().getDiscoverySpi()).resumeAll(); assert ((IgniteEx)srv1).context().discovery().pingNode(client.cluster().localNode().id()); assert ((IgniteEx)srv0).context().discovery().pingNode(client.cluster().localNode().id()); } /** * @throws Exception If failed. */ public void testClientReconnectOnRouterFail() throws Exception { clientsPerSrv = 1; startServerNodes(3); startClientNodes(3); checkNodes(3, 3); setClientRouter(2, 0); srvFailedLatch = new CountDownLatch(2); clientFailedLatch = new CountDownLatch(3); attachListeners(2, 3); failServer(2); await(srvFailedLatch); await(clientFailedLatch); checkNodes(2, 3); } /** * @throws Exception If failed. */ public void testClientReconnectOnNetworkProblem() throws Exception { clientsPerSrv = 1; startServerNodes(3); startClientNodes(3); checkNodes(3, 3); setClientRouter(2, 0); srvFailedLatch = new CountDownLatch(2); clientFailedLatch = new CountDownLatch(3); attachListeners(2, 3); ((TcpClientDiscoverySpi)G.ignite("client-2").configuration().getDiscoverySpi()).brokeConnection(); G.ignite("client-2").message().remoteListen(null, new MessageListener()); // Send some discovery message. checkNodes(3, 3); } /** * @throws Exception If failed. */ public void testGetMissedMessagesOnReconnect() throws Exception { clientsPerSrv = 1; startServerNodes(3); startClientNodes(2); checkNodes(3, 2); clientLeftLatch = new CountDownLatch(1); srvLeftLatch = new CountDownLatch(2); attachListeners(2, 2); ((TestTcpClientDiscovery)G.ignite("client-1").configuration().getDiscoverySpi()).pauseAll(); stopGrid("server-2"); await(srvLeftLatch); await(srvLeftLatch); Thread.sleep(500); assert G.ignite("client-0").cluster().nodes().size() == 4; assert G.ignite("client-1").cluster().nodes().size() == 5; clientLeftLatch = new CountDownLatch(1); ((TestTcpClientDiscovery)G.ignite("client-1").configuration().getDiscoverySpi()).resumeAll(); await(clientLeftLatch); checkNodes(2, 2); } /** * @throws Exception If failed. */ public void testClientSegmentation() throws Exception { clientsPerSrv = 1; startServerNodes(3); startClientNodes(3); checkNodes(3, 3); // setClientRouter(2, 2); srvFailedLatch = new CountDownLatch(2 + 2); clientFailedLatch = new CountDownLatch(2 + 2); attachListeners(2, 2); final CountDownLatch client2StoppedLatch = new CountDownLatch(1); IgnitionListener lsnr = new IgnitionListener() { @Override public void onStateChange(@Nullable String name, IgniteState state) { if (state == IgniteState.STOPPED_ON_SEGMENTATION) client2StoppedLatch.countDown(); } }; G.addListener(lsnr); try { failServer(2); await(srvFailedLatch); await(clientFailedLatch); await(client2StoppedLatch); checkNodes(2, 2); } finally { G.removeListener(lsnr); } } /** * @throws Exception If failed. */ public void testClientNodeJoinOneServer() throws Exception { startServerNodes(1); srvJoinedLatch = new CountDownLatch(1); attachListeners(1, 0); startClientNodes(1); await(srvJoinedLatch); checkNodes(1, 1); } /** * @throws Exception If failed. */ public void testClientNodeLeaveOneServer() throws Exception { startServerNodes(1); startClientNodes(1); checkNodes(1, 1); srvLeftLatch = new CountDownLatch(1); attachListeners(1, 0); stopGrid("client-0"); await(srvLeftLatch); checkNodes(1, 0); } /** * @throws Exception If failed. */ public void testClientNodeFailOneServer() throws Exception { startServerNodes(1); startClientNodes(1); checkNodes(1, 1); srvFailedLatch = new CountDownLatch(1); attachListeners(1, 0); failClient(0); await(srvFailedLatch); checkNodes(1, 0); } /** * @throws Exception If failed. */ public void testMetrics() throws Exception { startServerNodes(3); startClientNodes(3); checkNodes(3, 3); attachListeners(3, 3); assertTrue(checkMetrics(3, 3, 0)); G.ignite("client-0").compute().broadcast(F.noop()); assertTrue(GridTestUtils.waitForCondition(new PA() { @Override public boolean apply() { return checkMetrics(3, 3, 1); } }, 10000)); checkMetrics(3, 3, 1); G.ignite("server-0").compute().broadcast(F.noop()); assertTrue(GridTestUtils.waitForCondition(new PA() { @Override public boolean apply() { return checkMetrics(3, 3, 2); } }, 10000)); } /** * @param srvCnt Number of Number of server nodes. * @param clientCnt Number of client nodes. * @param execJobsCnt Expected number of executed jobs. * @return Whether metrics are correct. */ private boolean checkMetrics(int srvCnt, int clientCnt, int execJobsCnt) { for (int i = 0; i < srvCnt; i++) { Ignite g = G.ignite("server-" + i); for (ClusterNode n : g.cluster().nodes()) { if (n.metrics().getTotalExecutedJobs() != execJobsCnt) return false; } } for (int i = 0; i < clientCnt; i++) { Ignite g = G.ignite("client-" + i); for (ClusterNode n : g.cluster().nodes()) { if (n.metrics().getTotalExecutedJobs() != execJobsCnt) return false; } } return true; } /** * @throws Exception If failed. */ public void testDataExchangeFromServer() throws Exception { testDataExchange("server-0"); } /** * TODO: IGNITE-587. * * @throws Exception If failed. */ public void testDataExchangeFromClient() throws Exception { testDataExchange("client-0"); } /** * @throws Exception If failed. */ private void testDataExchange(String masterName) throws Exception { startServerNodes(2); startClientNodes(2); checkNodes(2, 2); IgniteMessaging msg = grid(masterName).message(); UUID id = null; try { id = msg.remoteListen(null, new MessageListener()); msgLatch = new CountDownLatch(4); msg.send(null, "Message 1"); await(msgLatch); startServerNodes(1); startClientNodes(1); checkNodes(3, 3); msgLatch = new CountDownLatch(6); msg.send(null, "Message 2"); await(msgLatch); } finally { if (id != null) msg.stopRemoteListen(id); } } /** * @throws Exception If any error occurs. */ public void testDuplicateId() throws Exception { startServerNodes(2); nodeId = G.ignite("server-1").cluster().localNode().id(); try { startGrid("client-0"); assert false; } catch (IgniteCheckedException e) { IgniteSpiException spiEx = e.getCause(IgniteSpiException.class); assert spiEx != null : e; assert spiEx.getMessage().contains("same ID") : spiEx.getMessage(); } } /** * @throws Exception If any error occurs. */ public void testTimeoutWaitingNodeAddedMessage() throws Exception { startServerNodes(2); final CountDownLatch cnt = new CountDownLatch(1); ((TcpDiscoverySpi)G.ignite("server-1").configuration().getDiscoverySpi()).addSendMessageListener( new IgniteInClosure<TcpDiscoveryAbstractMessage>() { @Override public void apply(TcpDiscoveryAbstractMessage msg) { try { cnt.await(10, MINUTES); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IgniteInterruptedException(e); } } }); try { startGrid("client-0"); assert false; } catch (IgniteCheckedException e) { cnt.countDown(); IgniteSpiException spiEx = e.getCause(IgniteSpiException.class); assert spiEx != null : e; assert spiEx.getMessage().contains("Join process timed out") : spiEx.getMessage(); } } /** * @throws Exception If any error occurs. */ public void testGridStartTime() throws Exception { startServerNodes(2); startClientNodes(2); long startTime = -1; for (Ignite g : G.allGrids()) { IgniteEx kernal = (IgniteKernal)g; assertTrue(kernal.context().discovery().gridStartTime() > 0); if (startTime == -1) startTime = kernal.context().discovery().gridStartTime(); else assertEquals(startTime, kernal.context().discovery().gridStartTime()); } } /** * @param clientIdx Index. * @throws Exception In case of error. */ private void setClientRouter(int clientIdx, int srvIdx) throws Exception { TcpClientDiscoverySpi disco = (TcpClientDiscoverySpi)G.ignite("client-" + clientIdx).configuration().getDiscoverySpi(); TcpDiscoveryVmIpFinder ipFinder = (TcpDiscoveryVmIpFinder)disco.getIpFinder(); String addr = new ArrayList<>(IP_FINDER.getRegisteredAddresses()).get(srvIdx).toString(); if (addr.startsWith("/")) addr = addr.substring(1); ipFinder.setAddresses(Arrays.asList(addr)); } /** * @param cnt Number of nodes. * @throws Exception In case of error. */ private void startServerNodes(int cnt) throws Exception { for (int i = 0; i < cnt; i++) { Ignite g = startGrid("server-" + srvIdx.getAndIncrement()); srvNodeIds.add(g.cluster().localNode().id()); } } /** * @param cnt Number of nodes. * @throws Exception In case of error. */ private void startClientNodes(int cnt) throws Exception { for (int i = 0; i < cnt; i++) { Ignite g = startGrid("client-" + clientIdx.getAndIncrement()); clientNodeIds.add(g.cluster().localNode().id()); } } /** * @param idx Index. */ private void failServer(int idx) { ((TcpDiscoverySpi)G.ignite("server-" + idx).configuration().getDiscoverySpi()).simulateNodeFailure(); } /** * @param idx Index. */ private void failClient(int idx) { ((TcpClientDiscoverySpi)G.ignite("client-" + idx).configuration().getDiscoverySpi()).simulateNodeFailure(); } /** * @param srvCnt Number of server nodes. * @param clientCnt Number of client nodes. */ private void attachListeners(int srvCnt, int clientCnt) throws Exception { if (srvJoinedLatch != null) { for (int i = 0; i < srvCnt; i++) { G.ignite("server-" + i).events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event evt) { info("Joined event fired on server: " + evt); srvJoinedLatch.countDown(); return true; } }, EVT_NODE_JOINED); } } if (srvLeftLatch != null) { for (int i = 0; i < srvCnt; i++) { G.ignite("server-" + i).events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event evt) { info("Left event fired on server: " + evt); srvLeftLatch.countDown(); return true; } }, EVT_NODE_LEFT); } } if (srvFailedLatch != null) { for (int i = 0; i < srvCnt; i++) { G.ignite("server-" + i).events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event evt) { info("Failed event fired on server: " + evt); srvFailedLatch.countDown(); return true; } }, EVT_NODE_FAILED); } } if (clientJoinedLatch != null) { for (int i = 0; i < clientCnt; i++) { G.ignite("client-" + i).events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event evt) { info("Joined event fired on client: " + evt); clientJoinedLatch.countDown(); return true; } }, EVT_NODE_JOINED); } } if (clientLeftLatch != null) { for (int i = 0; i < clientCnt; i++) { G.ignite("client-" + i).events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event evt) { info("Left event fired on client: " + evt); clientLeftLatch.countDown(); return true; } }, EVT_NODE_LEFT); } } if (clientFailedLatch != null) { for (int i = 0; i < clientCnt; i++) { G.ignite("client-" + i).events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event evt) { info("Failed event fired on client: " + evt); clientFailedLatch.countDown(); return true; } }, EVT_NODE_FAILED); } } } /** * @param srvCnt Number of server nodes. * @param clientCnt Number of client nodes. */ private void checkNodes(int srvCnt, int clientCnt) { for (int i = 0; i < srvCnt; i++) { Ignite g = G.ignite("server-" + i); assertTrue(srvNodeIds.contains(g.cluster().localNode().id())); assertFalse(g.cluster().localNode().isClient()); checkRemoteNodes(g, srvCnt + clientCnt - 1); } for (int i = 0; i < clientCnt; i++) { Ignite g = G.ignite("client-" + i); assertTrue(clientNodeIds.contains(g.cluster().localNode().id())); assertTrue(g.cluster().localNode().isClient()); checkRemoteNodes(g, srvCnt + clientCnt - 1); } } /** * @param ignite Grid. * @param expCnt Expected nodes count. */ @SuppressWarnings("TypeMayBeWeakened") private void checkRemoteNodes(Ignite ignite, int expCnt) { Collection<ClusterNode> nodes = ignite.cluster().forRemotes().nodes(); assertEquals(expCnt, nodes.size()); for (ClusterNode node : nodes) { UUID id = node.id(); if (clientNodeIds.contains(id)) assertTrue(node.isClient()); else if (srvNodeIds.contains(id)) assertFalse(node.isClient()); else assert false : "Unexpected node ID: " + id; } } /** * @param latch Latch. * @throws InterruptedException If interrupted. */ private void await(CountDownLatch latch) throws InterruptedException { assertTrue("Latch count: " + latch.getCount(), latch.await(10000, MILLISECONDS)); } /** */ private static class MessageListener implements IgniteBiPredicate<UUID, Object> { @IgniteInstanceResource private Ignite ignite; /** {@inheritDoc} */ @Override public boolean apply(UUID uuid, Object msg) { X.println(">>> Received [locNodeId=" + ignite.configuration().getNodeId() + ", msg=" + msg + ']'); msgLatch.countDown(); return true; } } /** * */ private static class TestTcpClientDiscovery extends TcpClientDiscoverySpi { /** */ private final Object mux = new Object(); /** */ private final AtomicBoolean writeLock = new AtomicBoolean(); /** */ private final AtomicBoolean openSockLock = new AtomicBoolean(); /** * @param lock Lock. */ private void waitFor(AtomicBoolean lock) { try { synchronized (mux) { while (lock.get()) mux.wait(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } /** * @param isPause Is lock. * @param locks Locks. */ private void pauseResumeOperation(boolean isPause, AtomicBoolean... locks) { synchronized (mux) { for (AtomicBoolean lock : locks) lock.set(isPause); mux.notifyAll(); } } /** {@inheritDoc} */ @Override protected void writeToSocket(Socket sock, TcpDiscoveryAbstractMessage msg, GridByteArrayOutputStream bout) throws IOException, IgniteCheckedException { waitFor(writeLock); super.writeToSocket(sock, msg, bout); } /** {@inheritDoc} */ @Override protected Socket openSocket(InetSocketAddress sockAddr) throws IOException { waitFor(openSockLock); return super.openSocket(sockAddr); } /** * */ public void pauseSocketWrite() { pauseResumeOperation(true, writeLock); } /** * */ public void pauseAll() { pauseResumeOperation(true, openSockLock, writeLock); brokeConnection(); } /** * */ public void resumeAll() { pauseResumeOperation(false, openSockLock, writeLock); } } }
IGNITE-709 Code cleanup.
modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpClientDiscoverySpiSelfTest.java
IGNITE-709 Code cleanup.
<ide><path>odules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpClientDiscoverySpiSelfTest.java <ide> if (addr.startsWith("/")) <ide> addr = addr.substring(1); <ide> <del> ipFinder.setAddresses(Arrays.asList(addr)); <add> ipFinder.setAddresses(Collections.singletonList(addr)); <ide> } <ide> <ide> disco.setIpFinder(ipFinder); <ide> <ide> checkNodes(3, 3); <ide> <del>// setClientRouter(2, 2); <del> <ide> srvFailedLatch = new CountDownLatch(2 + 2); <ide> clientFailedLatch = new CountDownLatch(2 + 2); <ide> <ide> long startTime = -1; <ide> <ide> for (Ignite g : G.allGrids()) { <del> IgniteEx kernal = (IgniteKernal)g; <add> IgniteEx kernal = (IgniteEx)g; <ide> <ide> assertTrue(kernal.context().discovery().gridStartTime() > 0); <ide> <ide> if (addr.startsWith("/")) <ide> addr = addr.substring(1); <ide> <del> ipFinder.setAddresses(Arrays.asList(addr)); <add> ipFinder.setAddresses(Collections.singletonList(addr)); <ide> } <ide> <ide> /** <ide> /** <ide> */ <ide> private static class MessageListener implements IgniteBiPredicate<UUID, Object> { <add> /** */ <ide> @IgniteInstanceResource <ide> private Ignite ignite; <ide>
Java
apache-2.0
10281db5302ccf13bee0fba142bf592168889f86
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testFramework; import com.intellij.application.options.CodeStyle; import com.intellij.codeInsight.AutoPopupController; import com.intellij.ide.highlighter.ModuleFileType; import com.intellij.ide.highlighter.ProjectFileType; import com.intellij.ide.startup.impl.StartupManagerImpl; import com.intellij.idea.IdeaLogger; import com.intellij.idea.IdeaTestApplication; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.application.impl.LaterInvocator; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.command.impl.DocumentReferenceManagerImpl; import com.intellij.openapi.command.impl.UndoManagerImpl; import com.intellij.openapi.command.undo.DocumentReferenceManager; import com.intellij.openapi.command.undo.UndoManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.impl.text.AsyncHighlighterUpdater; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl; import com.intellij.openapi.module.EmptyModuleType; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.project.impl.ProjectImpl; import com.intellij.openapi.project.impl.ProjectManagerImpl; import com.intellij.openapi.project.impl.TooManyProjectLeakedException; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.ModuleRootModificationUtil; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.EmptyRunnable; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.impl.VirtualFilePointerTracker; import com.intellij.openapi.vfs.impl.jar.JarFileSystemImpl; import com.intellij.openapi.vfs.impl.local.LocalFileSystemImpl; import com.intellij.openapi.vfs.newvfs.impl.VirtualDirectoryImpl; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFSImpl; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.codeStyle.CodeStyleSchemes; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.impl.PsiDocumentManagerBase; import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageManagerImpl; import com.intellij.util.*; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.indexing.FileBasedIndexImpl; import com.intellij.util.indexing.IndexableSetContributor; import com.intellij.util.ui.UIUtil; import gnu.trove.THashSet; import gnu.trove.TIntHashSet; import junit.framework.TestCase; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.Collection; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit; /** * @author yole */ @SuppressWarnings({"UseOfSystemOutOrSystemErr", "CallToPrintStackTrace"}) public abstract class PlatformTestCase extends UsefulTestCase implements DataProvider { private static IdeaTestApplication ourApplication; private static boolean ourReportedLeakedProjects; protected ProjectManagerEx myProjectManager; protected Project myProject; protected Module myModule; protected final Collection<File> myFilesToDelete = new THashSet<>(); private final TempFiles myTempFiles = new TempFiles(myFilesToDelete); protected boolean myAssertionsInTestDetected; public static Thread ourTestThread; private static TestCase ourTestCase; private static final long DEFAULT_TEST_TIME = 300L; public static long ourTestTime = DEFAULT_TEST_TIME; private EditorListenerTracker myEditorListenerTracker; private ThreadTracker myThreadTracker; private static boolean ourPlatformPrefixInitialized; private static Set<VirtualFile> ourEternallyLivingFilesCache; private SdkLeakTracker myOldSdks; private VirtualFilePointerTracker myVirtualFilePointerTracker; @NotNull public TempFiles getTempDir() { return myTempFiles; } protected final VirtualFile createTestProjectStructure() throws IOException { return PsiTestUtil.createTestProjectStructure(myProject, myModule, myFilesToDelete); } protected final VirtualFile createTestProjectStructure(String rootPath) throws Exception { return PsiTestUtil.createTestProjectStructure(myProject, myModule, rootPath, myFilesToDelete); } /** * If a temp directory is reused from some previous test run, there might be cached children in its VFS. * Ensure they're removed */ public static void synchronizeTempDirVfs(@NotNull VirtualFile tempDir) { tempDir.getChildren(); tempDir.refresh(false, true); } protected void initApplication() throws Exception { boolean firstTime = ourApplication == null; ourApplication = IdeaTestApplication.getInstance(null); ourApplication.setDataProvider(this); if (firstTime) { cleanPersistedVFSContent(); } // try to remember old sdks as soon as possible after the app instantiation myOldSdks = new SdkLeakTracker(); } private static final String[] PREFIX_CANDIDATES = { "Rider", "GoLand", null, "AppCode", "CLion", "CidrCommon", "DataGrip", "Python", "PyCharmCore", "Ruby", "PhpStorm", "UltimateLangXml", "Idea", "PlatformLangXml" }; public static void doAutodetectPlatformPrefix() { if (ourPlatformPrefixInitialized) { return; } for (String candidate : PREFIX_CANDIDATES) { String markerPath = candidate != null ? "META-INF/" + candidate + "Plugin.xml" : "idea/ApplicationInfo.xml"; URL resource = PlatformTestCase.class.getClassLoader().getResource(markerPath); if (resource != null) { if (candidate != null) { setPlatformPrefix(candidate); } break; } } } private static void cleanPersistedVFSContent() { ((PersistentFSImpl)PersistentFS.getInstance()).cleanPersistedContents(); } @NotNull @Override protected CodeStyleSettings getCurrentCodeStyleSettings() { if (CodeStyleSchemes.getInstance().getCurrentScheme() == null) return new CodeStyleSettings(); return CodeStyle.getSettings(getProject()); } @Override protected void setUp() throws Exception { super.setUp(); File tempDir = new File(FileUtilRt.getTempDirectory()); myFilesToDelete.add(tempDir); if (ourTestCase != null) { String message = "Previous test " + ourTestCase + " hasn't called tearDown(). Probably overridden without super call."; ourTestCase = null; fail(message); } IdeaLogger.ourErrorsOccurred = null; LOG.debug(getClass().getName() + ".setUp()"); initApplication(); if (myOldSdks == null) { // some bastard's overridden initApplication completely myOldSdks = new SdkLeakTracker(); } myEditorListenerTracker = new EditorListenerTracker(); myThreadTracker = new ThreadTracker(); setUpProject(); storeSettings(); ourTestCase = this; if (myProject != null) { ProjectManagerEx.getInstanceEx().openTestProject(myProject); CodeStyle.setTemporarySettings(myProject, new CodeStyleSettings()); InjectedLanguageManagerImpl.pushInjectors(myProject); ((PsiDocumentManagerBase)PsiDocumentManager.getInstance(myProject)).clearUncommittedDocuments(); } UIUtil.dispatchAllInvocationEvents(); myVirtualFilePointerTracker = new VirtualFilePointerTracker(); } public final Project getProject() { return myProject; } public final PsiManager getPsiManager() { return PsiManager.getInstance(myProject); } public Module getModule() { return myModule; } protected void setUpProject() throws Exception { myProjectManager = ProjectManagerEx.getInstanceEx(); assertNotNull("Cannot instantiate ProjectManager component", myProjectManager); myProject = doCreateProject(getProjectDirOrFile()); myProjectManager.openTestProject(myProject); LocalFileSystem.getInstance().refreshIoFiles(myFilesToDelete); setUpModule(); setUpJdk(); LightPlatformTestCase.clearUncommittedDocuments(getProject()); runStartupActivities(); ((FileTypeManagerImpl)FileTypeManager.getInstance()).drainReDetectQueue(); } protected Project doCreateProject(@NotNull Path projectFile) throws Exception { return createProject(projectFile.toFile(), getClass().getName() + "." + getName()); } @NotNull public static Project createProject(File projectFile, @NotNull String creationPlace) { return createProject(projectFile.getPath(), creationPlace); } @NotNull public static Project createProject(@NotNull String path, @NotNull String creationPlace) { String fileName = PathUtilRt.getFileName(path); try { String projectName = FileUtilRt.getNameWithoutExtension(fileName); Project project = ProjectManagerEx.getInstanceEx().newProject(projectName, path, false, false); assert project != null; project.putUserData(CREATION_PLACE, creationPlace); return project; } catch (TooManyProjectLeakedException e) { if (ourReportedLeakedProjects) { fail("Too many projects leaked, again."); return null; } ourReportedLeakedProjects = true; TIntHashSet hashCodes = new TIntHashSet(); for (Project project : e.getLeakedProjects()) { hashCodes.add(System.identityHashCode(project)); } String dumpPath = PathManager.getHomePath() + "/leakedProjects.hprof.zip"; System.out.println("##teamcity[publishArtifacts 'leakedProjects.hprof.zip']"); try { FileUtil.delete(new File(dumpPath)); MemoryDumpHelper.captureMemoryDumpZipped(dumpPath); } catch (Exception ex) { ex.printStackTrace(); } StringBuilder leakers = new StringBuilder(); leakers.append("Too many projects leaked: \n"); LeakHunter.processLeaks(LeakHunter.allRoots(), ProjectImpl.class, p -> hashCodes.contains(System.identityHashCode(p)), (leaked,backLink)->{ int hashCode = System.identityHashCode(leaked); leakers.append("Leaked project found:").append(leaked).append("; hash: ").append(hashCode).append("; place: ") .append(getCreationPlace(leaked)).append("\n"); leakers.append(backLink).append("\n"); leakers.append(";-----\n"); hashCodes.remove(hashCode); return !hashCodes.isEmpty(); }); fail(leakers+"\nPlease see '"+dumpPath+"' for a memory dump"); return null; } } @NotNull @TestOnly public static String getCreationPlace(@NotNull Project project) { Object base; try { base = project.isDisposed() ? "" : project.getBaseDir(); } catch (Exception e) { base = " (" + e + " while getting base dir)"; } String place = project.getUserData(CREATION_PLACE); return project + " " +(place == null ? "" : place) + base; } protected void runStartupActivities() { final StartupManagerImpl startupManager = (StartupManagerImpl)StartupManager.getInstance(myProject); startupManager.runStartupActivities(); startupManager.startCacheUpdate(); startupManager.runPostStartupActivities(); } @NotNull protected Path getProjectDirOrFile() { return getProjectDirOrFile(false); } protected boolean isCreateProjectFileExplicitly() { return true; } @NotNull protected final Path getProjectDirOrFile(boolean isDirectoryBasedProject) { if (!isDirectoryBasedProject && isCreateProjectFileExplicitly()) { try { File tempFile = FileUtil.createTempFile(getName(), ProjectFileType.DOT_DEFAULT_EXTENSION); myFilesToDelete.add(tempFile); return tempFile.toPath(); } catch (IOException e) { throw new RuntimeException(e); } } Path tempFile = TemporaryDirectoryKt .generateTemporaryPath(FileUtil.sanitizeFileName(getName(), false) + (isDirectoryBasedProject ? "" : ProjectFileType.DOT_DEFAULT_EXTENSION)); myFilesToDelete.add(tempFile.toFile()); return tempFile; } protected void setUpModule() { try { WriteCommandAction.writeCommandAction(getProject()).run(() -> myModule = createMainModule()); } catch (IOException e) { throw new RuntimeException(e); } } @NotNull protected Module createMainModule() throws IOException { return createModule(myProject.getName()); } @NotNull protected Module createModule(@NonNls final String moduleName) { return doCreateRealModule(moduleName); } @NotNull protected Module doCreateRealModule(final String moduleName) { return doCreateRealModuleIn(moduleName, myProject, getModuleType()); } @NotNull protected Module doCreateRealModuleIn(@NotNull String moduleName, @NotNull Project project, final ModuleType moduleType) { return createModuleAt(moduleName, project, moduleType, Objects.requireNonNull(project.getBasePath())); } @NotNull protected Module createModuleAt(@NotNull String moduleName, @NotNull Project project, ModuleType moduleType, @NotNull String path) { if (isCreateProjectFileExplicitly()) { File moduleFile = new File(FileUtil.toSystemDependentName(path), moduleName + ModuleFileType.DOT_DEFAULT_EXTENSION); FileUtil.createIfDoesntExist(moduleFile); myFilesToDelete.add(moduleFile); return WriteAction.computeAndWait(() -> { VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(moduleFile); assertNotNull(virtualFile); Module module = ModuleManager.getInstance(project).newModule(virtualFile.getPath(), moduleType.getId()); module.getModuleFile(); return module; }); } ModuleManager moduleManager = ModuleManager.getInstance(project); return WriteAction.computeAndWait( () -> moduleManager.newModule(path + File.separatorChar + moduleName + ModuleFileType.DOT_DEFAULT_EXTENSION, moduleType.getId())); } protected ModuleType getModuleType() { return EmptyModuleType.getInstance(); } public static void cleanupApplicationCaches(Project project) { UndoManagerImpl globalInstance = (UndoManagerImpl)UndoManager.getGlobalInstance(); if (globalInstance != null) { globalInstance.dropHistoryInTests(); } if (project != null && !project.isDisposed()) { ((UndoManagerImpl)UndoManager.getInstance(project)).dropHistoryInTests(); ((DocumentReferenceManagerImpl)DocumentReferenceManager.getInstance()).cleanupForNextTest(); ((PsiManagerImpl)PsiManager.getInstance(project)).cleanupForNextTest(); } final ProjectManager projectManager = ProjectManager.getInstance(); assert projectManager != null : "The ProjectManager is not initialized yet"; ProjectManagerImpl projectManagerImpl = (ProjectManagerImpl)projectManager; if (projectManagerImpl.isDefaultProjectInitialized()) { Project defaultProject = projectManager.getDefaultProject(); ((PsiManagerImpl)PsiManager.getInstance(defaultProject)).cleanupForNextTest(); } AsyncHighlighterUpdater.completeAsyncTasks(); ((FileBasedIndexImpl) FileBasedIndex.getInstance()).cleanupForNextTest(); LocalFileSystemImpl localFileSystem = (LocalFileSystemImpl)LocalFileSystem.getInstance(); if (localFileSystem != null) { localFileSystem.cleanupForNextTest(); } } private static Set<VirtualFile> eternallyLivingFiles() { if (ourEternallyLivingFilesCache != null) { return ourEternallyLivingFilesCache; } Set<VirtualFile> survivors = new HashSet<>(); for (IndexableSetContributor contributor : IndexableSetContributor.EP_NAME.getExtensions()) { for (VirtualFile file : IndexableSetContributor.getRootsToIndex(contributor)) { registerSurvivor(survivors, file); } } ourEternallyLivingFilesCache = survivors; return survivors; } public static void addSurvivingFiles(@NotNull Collection<VirtualFile> files) { for (VirtualFile each : files) { registerSurvivor(eternallyLivingFiles(), each); } } private static void registerSurvivor(Set<VirtualFile> survivors, VirtualFile file) { addSubTree(file, survivors); while (file != null && survivors.add(file)) { file = file.getParent(); } } private static void addSubTree(VirtualFile root, Set<VirtualFile> to) { if (root instanceof VirtualDirectoryImpl) { for (VirtualFile child : ((VirtualDirectoryImpl)root).getCachedChildren()) { if (child instanceof VirtualDirectoryImpl) { to.add(child); addSubTree(child, to); } } } } @Override protected void tearDown() throws Exception { Project project = myProject; if (project != null && !project.isDisposed()) { AutoPopupController.getInstance(project).cancelAllRequests(); // clear "show param info" delayed requests leaking project } // don't use method references here to make stack trace reading easier //noinspection Convert2MethodRef new RunAll() .append(() -> disposeRootDisposable()) .append(() -> { if (project != null) { LightPlatformTestCase.doTearDown(project, ourApplication); } }) .append(() -> disposeProject()) .append(() -> UIUtil.dispatchAllInvocationEvents()) .append(() -> checkForSettingsDamage()) .append(() -> { if (project != null) { InjectedLanguageManagerImpl.checkInjectorsAreDisposed(project); } }) .append(() -> { ((JarFileSystemImpl)JarFileSystem.getInstance()).cleanupForNextTest(); getTempDir().deleteAll(); LocalFileSystem.getInstance().refreshIoFiles(myFilesToDelete); LaterInvocator.dispatchPendingFlushes(); ((FileBasedIndexImpl)FileBasedIndex.getInstance()).waitForVfsEventsExecuted(1, TimeUnit.MINUTES); }) .append(() -> { if (!myAssertionsInTestDetected) { if (IdeaLogger.ourErrorsOccurred != null) { throw IdeaLogger.ourErrorsOccurred; } } }) .append(super::tearDown) .append(() -> { if (myEditorListenerTracker != null) { myEditorListenerTracker.checkListenersLeak(); } }) .append(() -> { if (myThreadTracker != null) { myThreadTracker.checkLeak(); } }) .append(() -> LightPlatformTestCase.checkEditorsReleased()) .append(() -> myOldSdks.checkForJdkTableLeaks()) .append(() -> myVirtualFilePointerTracker.assertPointersAreDisposed()) .append(() -> { myProjectManager = null; myProject = null; myModule = null; myFilesToDelete.clear(); myEditorListenerTracker = null; myThreadTracker = null; //noinspection AssignmentToStaticFieldFromInstanceMethod ourTestCase = null; }) .run(); } private void disposeProject() { if (myProject != null) { closeAndDisposeProjectAndCheckThatNoOpenProjects(myProject); myProject = null; } } public static void closeAndDisposeProjectAndCheckThatNoOpenProjects(@NotNull final Project projectToClose) { RunAll runAll = new RunAll(); ProjectManagerEx projectManager = ProjectManagerEx.getInstanceEx(); if (projectManager instanceof ProjectManagerImpl) { for (Project project : projectManager.closeTestProject(projectToClose)) { runAll = runAll .append(() -> { throw new IllegalStateException("Test project is not disposed: " + project + ";\n created in: " + getCreationPlace(project)); }) .append(() -> ((ProjectManagerImpl)projectManager).forceCloseProject(project, true)); } } runAll.append(() -> WriteAction.run(() -> Disposer.dispose(projectToClose))).run(); } protected void resetAllFields() { resetClassFields(getClass()); } @Override protected final <T extends Disposable> T disposeOnTearDown(T disposable) { Disposer.register(myProject, disposable); return disposable; } private void resetClassFields(final Class<?> aClass) { try { clearDeclaredFields(this, aClass); } catch (IllegalAccessException e) { LOG.error(e); } if (aClass == PlatformTestCase.class) return; resetClassFields(aClass.getSuperclass()); } protected void setUpJdk() { final Sdk jdk = getTestProjectJdk(); Module[] modules = ModuleManager.getInstance(myProject).getModules(); for (Module module : modules) { ModuleRootModificationUtil.setModuleSdk(module, jdk); } } @Nullable protected Sdk getTestProjectJdk() { return null; } @Override public void runBare() throws Throwable { if (!shouldRunTest()) return; TestRunnerUtil.replaceIdeEventQueueSafely(); try { runBareImpl(); } finally { try { EdtTestUtil.runInEdtAndWait(() -> { cleanupApplicationCaches(getProject()); resetAllFields(); }); } catch (Throwable ignored) { } } } private void runBareImpl() throws Throwable { ThrowableRunnable<Throwable> runnable = () -> { ourTestThread = Thread.currentThread(); ourTestTime = DEFAULT_TEST_TIME; try { try { myAssertionsInTestDetected = true; setUp(); myAssertionsInTestDetected = false; } catch (Throwable e) { try { tearDown(); } catch (Throwable ignored) { } throw e; } Throwable exception = null; try { myAssertionsInTestDetected = true; runTest(); myAssertionsInTestDetected = false; } catch (Throwable e) { exception = e; } finally { try { tearDown(); } catch (Throwable e) { if (exception == null) { exception = e; } } } if (exception != null) { throw exception; } } finally { ourTestThread = null; } }; runBareRunnable(runnable); if (IdeaLogger.ourErrorsOccurred != null) { throw IdeaLogger.ourErrorsOccurred; } // just to make sure all deferred Runnable's to finish waitForAllLaters(); if (IdeaLogger.ourErrorsOccurred != null) { throw IdeaLogger.ourErrorsOccurred; } } private static void waitForAllLaters() throws InterruptedException, InvocationTargetException { for (int i = 0; i < 3; i++) { SwingUtilities.invokeAndWait(EmptyRunnable.getInstance()); } } protected void runBareRunnable(ThrowableRunnable<Throwable> runnable) throws Throwable { if (runInDispatchThread()) { EdtTestUtil.runInEdtAndWait(runnable); } else { runnable.run(); } } protected boolean isRunInWriteAction() { return false; } @Override protected void invokeTestRunnable(@NotNull final Runnable runnable) throws Exception { final Exception[] e = new Exception[1]; Runnable runnable1 = () -> { try { if (ApplicationManager.getApplication().isDispatchThread() && isRunInWriteAction()) { ApplicationManager.getApplication().runWriteAction(runnable); } else { runnable.run(); } } catch (Exception e1) { e[0] = e1; } }; if (annotatedWith(WrapInCommand.class)) { CommandProcessor.getInstance().executeCommand(myProject, runnable1, "", null); } else { runnable1.run(); } if (e[0] != null) { throw e[0]; } } @Override public Object getData(String dataId) { return myProject == null ? null : new TestDataProvider(myProject).getData(dataId); } @NotNull public File createTempDir(@NonNls @NotNull String prefix) throws IOException { return createTempDir(prefix, true); } @NotNull public File createTempDir(@NonNls @NotNull String prefix, final boolean refresh) throws IOException { final File tempDirectory = FileUtilRt.createTempDirectory("idea_test_" + prefix, null, false); myFilesToDelete.add(tempDirectory); if (refresh) { getVirtualFile(tempDirectory); } return tempDirectory; } protected static VirtualFile getVirtualFile(@NotNull File file) { return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file); } @NotNull protected File createTempDirectory() throws IOException { return createTempDir(""); } @NotNull protected File createTempDirectory(final boolean refresh) throws IOException { return createTempDir("", refresh); } @NotNull protected File createTempFile(@NotNull String name, @Nullable String text) throws IOException { File directory = createTempDirectory(); File file = new File(directory, name); if (!file.createNewFile()) { throw new IOException("Can't create " + file); } if (text != null) { FileUtil.writeToFile(file, text); } return file; } public static void setContentOnDisk(@NotNull File file, @Nullable byte[] bom, @NotNull String content, @NotNull Charset charset) throws IOException { FileOutputStream stream = new FileOutputStream(file); if (bom != null) { stream.write(bom); } try (OutputStreamWriter writer = new OutputStreamWriter(stream, charset)) { writer.write(content); } } @NotNull public VirtualFile createTempFile(@NonNls @NotNull String ext, @Nullable byte[] bom, @NonNls @NotNull String content, @NotNull Charset charset) throws IOException { File temp = FileUtil.createTempFile("copy", "." + ext); setContentOnDisk(temp, bom, content, charset); myFilesToDelete.add(temp); final VirtualFile file = getVirtualFile(temp); assert file != null : temp; return file; } @Nullable protected PsiFile getPsiFile(final Document document) { return PsiDocumentManager.getInstance(getProject()).getPsiFile(document); } private static void setPlatformPrefix(String prefix) { System.setProperty(PlatformUtils.PLATFORM_PREFIX_KEY, prefix); ourPlatformPrefixInitialized = true; } @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) public @interface WrapInCommand { } @NotNull protected static VirtualFile createChildData(@NotNull final VirtualFile dir, @NotNull @NonNls final String name) { try { return WriteAction.computeAndWait(()-> dir.createChildData(null, name)); } catch (IOException e) { throw new RuntimeException(e); } } @NotNull protected static VirtualFile createChildDirectory(@NotNull final VirtualFile dir, @NotNull @NonNls final String name) { try { return WriteAction.computeAndWait(()-> dir.createChildDirectory(null, name)); } catch (IOException e) { throw new RuntimeException(e); } } protected static void rename(@NotNull final VirtualFile vFile1, @NotNull final String newName) { try { WriteCommandAction.writeCommandAction(null).run(() -> vFile1.rename(vFile1, newName)); } catch (IOException e) { throw new RuntimeException(e); } } protected static void delete(@NotNull final VirtualFile vFile1) { VfsTestUtil.deleteFile(vFile1); } public static void move(@NotNull final VirtualFile vFile1, @NotNull final VirtualFile newFile) { try { WriteCommandAction.writeCommandAction(null).run(() -> vFile1.move(vFile1, newFile)); } catch (IOException e) { throw new RuntimeException(e); } } @NotNull protected static VirtualFile copy(@NotNull final VirtualFile file, @NotNull final VirtualFile newParent, @NotNull final String copyName) { final VirtualFile[] copy = new VirtualFile[1]; try { WriteCommandAction.writeCommandAction(null).run(() -> copy[0] = file.copy(file, newParent, copyName)); } catch (IOException e) { throw new RuntimeException(e); } return copy[0]; } public static void copyDirContentsTo(@NotNull final VirtualFile vTestRoot, @NotNull final VirtualFile toDir) { try { WriteCommandAction.writeCommandAction(null).run(() -> { for (VirtualFile file : vTestRoot.getChildren()) { VfsUtil.copy(file, file, toDir); } }); } catch (IOException e) { throw new RuntimeException(e); } } public static void setFileText(@NotNull final VirtualFile file, @NotNull final String text) { try { WriteAction.runAndWait(() -> VfsUtil.saveText(file, text)); } catch (IOException e) { throw new RuntimeException(e); } } public static void setBinaryContent(@NotNull final VirtualFile file, @NotNull final byte[] content) { try { WriteAction.runAndWait(() -> file.setBinaryContent(content)); } catch (IOException e) { throw new RuntimeException(e); } } public static void setBinaryContent(@NotNull final VirtualFile file, @NotNull final byte[] content, final long newModificationStamp, final long newTimeStamp, final Object requestor) { try { WriteAction.runAndWait(() -> file.setBinaryContent(content, newModificationStamp, newTimeStamp, requestor)); } catch (IOException e) { throw new RuntimeException(e); } } @NotNull protected VirtualFile getOrCreateProjectBaseDir() { VirtualFile baseDir = myProject.getBaseDir(); if (baseDir == null) { String basePath = myProject.getBasePath(); try { FileUtil.ensureExists(new File(Objects.requireNonNull(basePath))); } catch (IOException e) { throw new RuntimeException(e); } return LocalFileSystem.getInstance().refreshAndFindFileByPath(basePath); } return baseDir; } @NotNull protected static VirtualFile getOrCreateModuleDir(@NotNull Module module) throws IOException { File moduleDir = new File(PathUtil.getParentPath(module.getModuleFilePath())); FileUtil.ensureExists(moduleDir); return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(moduleDir); } }
platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testFramework; import com.intellij.application.options.CodeStyle; import com.intellij.codeInsight.AutoPopupController; import com.intellij.ide.highlighter.ModuleFileType; import com.intellij.ide.highlighter.ProjectFileType; import com.intellij.ide.startup.impl.StartupManagerImpl; import com.intellij.idea.IdeaLogger; import com.intellij.idea.IdeaTestApplication; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.application.impl.LaterInvocator; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.command.impl.DocumentReferenceManagerImpl; import com.intellij.openapi.command.impl.UndoManagerImpl; import com.intellij.openapi.command.undo.DocumentReferenceManager; import com.intellij.openapi.command.undo.UndoManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.impl.text.AsyncHighlighterUpdater; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl; import com.intellij.openapi.module.EmptyModuleType; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.project.impl.ProjectImpl; import com.intellij.openapi.project.impl.ProjectManagerImpl; import com.intellij.openapi.project.impl.TooManyProjectLeakedException; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.ModuleRootModificationUtil; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.EmptyRunnable; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.impl.VirtualFilePointerTracker; import com.intellij.openapi.vfs.impl.jar.JarFileSystemImpl; import com.intellij.openapi.vfs.impl.local.LocalFileSystemImpl; import com.intellij.openapi.vfs.newvfs.impl.VirtualDirectoryImpl; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFSImpl; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.codeStyle.CodeStyleSchemes; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.impl.PsiDocumentManagerBase; import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageManagerImpl; import com.intellij.util.*; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.indexing.FileBasedIndexImpl; import com.intellij.util.indexing.IndexableSetContributor; import com.intellij.util.ui.UIUtil; import gnu.trove.THashSet; import gnu.trove.TIntHashSet; import junit.framework.TestCase; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.Collection; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit; import static com.intellij.testFramework.TemporaryDirectoryKt.generateTemporaryPath; /** * @author yole */ @SuppressWarnings({"UseOfSystemOutOrSystemErr", "CallToPrintStackTrace"}) public abstract class PlatformTestCase extends UsefulTestCase implements DataProvider { private static IdeaTestApplication ourApplication; private static boolean ourReportedLeakedProjects; protected ProjectManagerEx myProjectManager; protected Project myProject; protected Module myModule; protected final Collection<File> myFilesToDelete = new THashSet<>(); private final TempFiles myTempFiles = new TempFiles(myFilesToDelete); protected boolean myAssertionsInTestDetected; public static Thread ourTestThread; private static TestCase ourTestCase; private static final long DEFAULT_TEST_TIME = 300L; public static long ourTestTime = DEFAULT_TEST_TIME; private EditorListenerTracker myEditorListenerTracker; private ThreadTracker myThreadTracker; private static boolean ourPlatformPrefixInitialized; private static Set<VirtualFile> ourEternallyLivingFilesCache; private SdkLeakTracker myOldSdks; private VirtualFilePointerTracker myVirtualFilePointerTracker; @NotNull public TempFiles getTempDir() { return myTempFiles; } protected final VirtualFile createTestProjectStructure() throws IOException { return PsiTestUtil.createTestProjectStructure(myProject, myModule, myFilesToDelete); } protected final VirtualFile createTestProjectStructure(String rootPath) throws Exception { return PsiTestUtil.createTestProjectStructure(myProject, myModule, rootPath, myFilesToDelete); } /** * If a temp directory is reused from some previous test run, there might be cached children in its VFS. * Ensure they're removed */ public static void synchronizeTempDirVfs(@NotNull VirtualFile tempDir) { tempDir.getChildren(); tempDir.refresh(false, true); } protected void initApplication() throws Exception { boolean firstTime = ourApplication == null; ourApplication = IdeaTestApplication.getInstance(null); ourApplication.setDataProvider(this); if (firstTime) { cleanPersistedVFSContent(); } // try to remember old sdks as soon as possible after the app instantiation myOldSdks = new SdkLeakTracker(); } private static final String[] PREFIX_CANDIDATES = { "Rider", "GoLand", null, "AppCode", "CLion", "CidrCommon", "DataGrip", "Python", "PyCharmCore", "Ruby", "PhpStorm", "UltimateLangXml", "Idea", "PlatformLangXml" }; public static void doAutodetectPlatformPrefix() { if (ourPlatformPrefixInitialized) { return; } for (String candidate : PREFIX_CANDIDATES) { String markerPath = candidate != null ? "META-INF/" + candidate + "Plugin.xml" : "idea/ApplicationInfo.xml"; URL resource = PlatformTestCase.class.getClassLoader().getResource(markerPath); if (resource != null) { if (candidate != null) { setPlatformPrefix(candidate); } break; } } } private static void cleanPersistedVFSContent() { ((PersistentFSImpl)PersistentFS.getInstance()).cleanPersistedContents(); } @NotNull @Override protected CodeStyleSettings getCurrentCodeStyleSettings() { if (CodeStyleSchemes.getInstance().getCurrentScheme() == null) return new CodeStyleSettings(); return CodeStyle.getSettings(getProject()); } @Override protected void setUp() throws Exception { super.setUp(); File tempDir = new File(FileUtilRt.getTempDirectory()); myFilesToDelete.add(tempDir); if (ourTestCase != null) { String message = "Previous test " + ourTestCase + " hasn't called tearDown(). Probably overridden without super call."; ourTestCase = null; fail(message); } IdeaLogger.ourErrorsOccurred = null; LOG.debug(getClass().getName() + ".setUp()"); initApplication(); if (myOldSdks == null) { // some bastard's overridden initApplication completely myOldSdks = new SdkLeakTracker(); } myEditorListenerTracker = new EditorListenerTracker(); myThreadTracker = new ThreadTracker(); setUpProject(); storeSettings(); ourTestCase = this; if (myProject != null) { ProjectManagerEx.getInstanceEx().openTestProject(myProject); CodeStyle.setTemporarySettings(myProject, new CodeStyleSettings()); InjectedLanguageManagerImpl.pushInjectors(myProject); ((PsiDocumentManagerBase)PsiDocumentManager.getInstance(myProject)).clearUncommittedDocuments(); } UIUtil.dispatchAllInvocationEvents(); myVirtualFilePointerTracker = new VirtualFilePointerTracker(); } public final Project getProject() { return myProject; } public final PsiManager getPsiManager() { return PsiManager.getInstance(myProject); } public Module getModule() { return myModule; } protected void setUpProject() throws Exception { myProjectManager = ProjectManagerEx.getInstanceEx(); assertNotNull("Cannot instantiate ProjectManager component", myProjectManager); myProject = doCreateProject(getProjectDirOrFile()); myProjectManager.openTestProject(myProject); LocalFileSystem.getInstance().refreshIoFiles(myFilesToDelete); setUpModule(); setUpJdk(); LightPlatformTestCase.clearUncommittedDocuments(getProject()); runStartupActivities(); ((FileTypeManagerImpl)FileTypeManager.getInstance()).drainReDetectQueue(); } protected Project doCreateProject(@NotNull Path projectFile) throws Exception { return createProject(projectFile.toFile(), getClass().getName() + "." + getName()); } @NotNull public static Project createProject(File projectFile, @NotNull String creationPlace) { return createProject(projectFile.getPath(), creationPlace); } @NotNull public static Project createProject(@NotNull String path, @NotNull String creationPlace) { String fileName = PathUtilRt.getFileName(path); try { String projectName = FileUtilRt.getNameWithoutExtension(fileName); Project project = ProjectManagerEx.getInstanceEx().newProject(projectName, path, false, false); assert project != null; project.putUserData(CREATION_PLACE, creationPlace); return project; } catch (TooManyProjectLeakedException e) { if (ourReportedLeakedProjects) { fail("Too many projects leaked, again."); return null; } ourReportedLeakedProjects = true; TIntHashSet hashCodes = new TIntHashSet(); for (Project project : e.getLeakedProjects()) { hashCodes.add(System.identityHashCode(project)); } String dumpPath = PathManager.getHomePath() + "/leakedProjects.hprof.zip"; System.out.println("##teamcity[publishArtifacts 'leakedProjects.hprof.zip']"); try { FileUtil.delete(new File(dumpPath)); MemoryDumpHelper.captureMemoryDumpZipped(dumpPath); } catch (Exception ex) { ex.printStackTrace(); } StringBuilder leakers = new StringBuilder(); leakers.append("Too many projects leaked: \n"); LeakHunter.processLeaks(LeakHunter.allRoots(), ProjectImpl.class, p -> hashCodes.contains(System.identityHashCode(p)), (leaked,backLink)->{ int hashCode = System.identityHashCode(leaked); leakers.append("Leaked project found:").append(leaked).append("; hash: ").append(hashCode).append("; place: ") .append(getCreationPlace(leaked)).append("\n"); leakers.append(backLink+"\n"); leakers.append(";-----\n"); hashCodes.remove(hashCode); return !hashCodes.isEmpty(); }); fail(leakers+"\nPlease see '"+dumpPath+"' for a memory dump"); return null; } } @NotNull @TestOnly public static String getCreationPlace(@NotNull Project project) { String place = project.getUserData(CREATION_PLACE); Object base; try { base = project.isDisposed() ? "" : project.getBaseDir(); } catch (Exception e) { base = " (" + e + " while getting base dir)"; } return project + (place != null ? place : "") + base; } protected void runStartupActivities() { final StartupManagerImpl startupManager = (StartupManagerImpl)StartupManager.getInstance(myProject); startupManager.runStartupActivities(); startupManager.startCacheUpdate(); startupManager.runPostStartupActivities(); } @NotNull protected Path getProjectDirOrFile() { return getProjectDirOrFile(false); } protected boolean isCreateProjectFileExplicitly() { return true; } @NotNull protected final Path getProjectDirOrFile(boolean isDirectoryBasedProject) { if (!isDirectoryBasedProject && isCreateProjectFileExplicitly()) { try { File tempFile = FileUtil.createTempFile(getName(), ProjectFileType.DOT_DEFAULT_EXTENSION); myFilesToDelete.add(tempFile); return tempFile.toPath(); } catch (IOException e) { throw new RuntimeException(e); } } Path tempFile = generateTemporaryPath(FileUtil.sanitizeFileName(getName(), false) + (isDirectoryBasedProject ? "" : ProjectFileType.DOT_DEFAULT_EXTENSION)); myFilesToDelete.add(tempFile.toFile()); return tempFile; } protected void setUpModule() { try { WriteCommandAction.writeCommandAction(getProject()).run(() -> myModule = createMainModule()); } catch (IOException e) { throw new RuntimeException(e); } } @NotNull protected Module createMainModule() throws IOException { return createModule(myProject.getName()); } @NotNull protected Module createModule(@NonNls final String moduleName) { return doCreateRealModule(moduleName); } @NotNull protected Module doCreateRealModule(final String moduleName) { return doCreateRealModuleIn(moduleName, myProject, getModuleType()); } @NotNull protected Module doCreateRealModuleIn(@NotNull String moduleName, @NotNull Project project, final ModuleType moduleType) { return createModuleAt(moduleName, project, moduleType, Objects.requireNonNull(project.getBasePath())); } @NotNull protected Module createModuleAt(@NotNull String moduleName, @NotNull Project project, ModuleType moduleType, @NotNull String path) { if (isCreateProjectFileExplicitly()) { File moduleFile = new File(FileUtil.toSystemDependentName(path), moduleName + ModuleFileType.DOT_DEFAULT_EXTENSION); FileUtil.createIfDoesntExist(moduleFile); myFilesToDelete.add(moduleFile); return WriteAction.computeAndWait(() -> { VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(moduleFile); assertNotNull(virtualFile); Module module = ModuleManager.getInstance(project).newModule(virtualFile.getPath(), moduleType.getId()); module.getModuleFile(); return module; }); } ModuleManager moduleManager = ModuleManager.getInstance(project); return WriteAction.computeAndWait( () -> moduleManager.newModule(path + File.separatorChar + moduleName + ModuleFileType.DOT_DEFAULT_EXTENSION, moduleType.getId())); } protected ModuleType getModuleType() { return EmptyModuleType.getInstance(); } public static void cleanupApplicationCaches(Project project) { UndoManagerImpl globalInstance = (UndoManagerImpl)UndoManager.getGlobalInstance(); if (globalInstance != null) { globalInstance.dropHistoryInTests(); } if (project != null && !project.isDisposed()) { ((UndoManagerImpl)UndoManager.getInstance(project)).dropHistoryInTests(); ((DocumentReferenceManagerImpl)DocumentReferenceManager.getInstance()).cleanupForNextTest(); ((PsiManagerImpl)PsiManager.getInstance(project)).cleanupForNextTest(); } final ProjectManager projectManager = ProjectManager.getInstance(); assert projectManager != null : "The ProjectManager is not initialized yet"; ProjectManagerImpl projectManagerImpl = (ProjectManagerImpl)projectManager; if (projectManagerImpl.isDefaultProjectInitialized()) { Project defaultProject = projectManager.getDefaultProject(); ((PsiManagerImpl)PsiManager.getInstance(defaultProject)).cleanupForNextTest(); } AsyncHighlighterUpdater.completeAsyncTasks(); ((FileBasedIndexImpl) FileBasedIndex.getInstance()).cleanupForNextTest(); LocalFileSystemImpl localFileSystem = (LocalFileSystemImpl)LocalFileSystem.getInstance(); if (localFileSystem != null) { localFileSystem.cleanupForNextTest(); } } private static Set<VirtualFile> eternallyLivingFiles() { if (ourEternallyLivingFilesCache != null) { return ourEternallyLivingFilesCache; } Set<VirtualFile> survivors = new HashSet<>(); for (IndexableSetContributor contributor : IndexableSetContributor.EP_NAME.getExtensions()) { for (VirtualFile file : IndexableSetContributor.getRootsToIndex(contributor)) { registerSurvivor(survivors, file); } } ourEternallyLivingFilesCache = survivors; return survivors; } public static void addSurvivingFiles(@NotNull Collection<VirtualFile> files) { for (VirtualFile each : files) { registerSurvivor(eternallyLivingFiles(), each); } } private static void registerSurvivor(Set<VirtualFile> survivors, VirtualFile file) { addSubTree(file, survivors); while (file != null && survivors.add(file)) { file = file.getParent(); } } private static void addSubTree(VirtualFile root, Set<VirtualFile> to) { if (root instanceof VirtualDirectoryImpl) { for (VirtualFile child : ((VirtualDirectoryImpl)root).getCachedChildren()) { if (child instanceof VirtualDirectoryImpl) { to.add(child); addSubTree(child, to); } } } } @Override protected void tearDown() throws Exception { Project project = myProject; if (project != null && !project.isDisposed()) { AutoPopupController.getInstance(project).cancelAllRequests(); // clear "show param info" delayed requests leaking project } // don't use method references here to make stack trace reading easier //noinspection Convert2MethodRef new RunAll() .append(() -> disposeRootDisposable()) .append(() -> { if (project != null) { LightPlatformTestCase.doTearDown(project, ourApplication); } }) .append(() -> disposeProject()) .append(() -> UIUtil.dispatchAllInvocationEvents()) .append(() -> checkForSettingsDamage()) .append(() -> { if (project != null) { InjectedLanguageManagerImpl.checkInjectorsAreDisposed(project); } }) .append(() -> { ((JarFileSystemImpl)JarFileSystem.getInstance()).cleanupForNextTest(); getTempDir().deleteAll(); LocalFileSystem.getInstance().refreshIoFiles(myFilesToDelete); LaterInvocator.dispatchPendingFlushes(); ((FileBasedIndexImpl)FileBasedIndex.getInstance()).waitForVfsEventsExecuted(1, TimeUnit.MINUTES); }) .append(() -> { if (!myAssertionsInTestDetected) { if (IdeaLogger.ourErrorsOccurred != null) { throw IdeaLogger.ourErrorsOccurred; } } }) .append(super::tearDown) .append(() -> { if (myEditorListenerTracker != null) { myEditorListenerTracker.checkListenersLeak(); } }) .append(() -> { if (myThreadTracker != null) { myThreadTracker.checkLeak(); } }) .append(() -> LightPlatformTestCase.checkEditorsReleased()) .append(() -> myOldSdks.checkForJdkTableLeaks()) .append(() -> myVirtualFilePointerTracker.assertPointersAreDisposed()) .append(() -> { myProjectManager = null; myProject = null; myModule = null; myFilesToDelete.clear(); myEditorListenerTracker = null; myThreadTracker = null; //noinspection AssignmentToStaticFieldFromInstanceMethod ourTestCase = null; }) .run(); } private void disposeProject() { if (myProject != null) { closeAndDisposeProjectAndCheckThatNoOpenProjects(myProject); myProject = null; } } public static void closeAndDisposeProjectAndCheckThatNoOpenProjects(@NotNull final Project projectToClose) { RunAll runAll = new RunAll(); ProjectManagerEx projectManager = ProjectManagerEx.getInstanceEx(); if (projectManager instanceof ProjectManagerImpl) { for (Project project : projectManager.closeTestProject(projectToClose)) { runAll = runAll .append(() -> { throw new IllegalStateException("Test project is not disposed: " + project + ";\n created in: " + getCreationPlace(project)); }) .append(() -> ((ProjectManagerImpl)projectManager).forceCloseProject(project, true)); } } runAll.append(() -> WriteAction.run(() -> Disposer.dispose(projectToClose))).run(); } protected void resetAllFields() { resetClassFields(getClass()); } @Override protected final <T extends Disposable> T disposeOnTearDown(T disposable) { Disposer.register(myProject, disposable); return disposable; } private void resetClassFields(final Class<?> aClass) { try { clearDeclaredFields(this, aClass); } catch (IllegalAccessException e) { LOG.error(e); } if (aClass == PlatformTestCase.class) return; resetClassFields(aClass.getSuperclass()); } private String getFullName() { return getClass().getName() + "." + getName(); } protected void setUpJdk() { //final ProjectJdkEx jdk = ProjectJdkUtil.getDefaultJdk("java 1.4"); final Sdk jdk = getTestProjectJdk(); // ProjectJdkImpl jdk = ProjectJdkTable.getInstance().addJdk(defaultJdk); Module[] modules = ModuleManager.getInstance(myProject).getModules(); for (Module module : modules) { ModuleRootModificationUtil.setModuleSdk(module, jdk); } } @Nullable protected Sdk getTestProjectJdk() { return null; } @Override public void runBare() throws Throwable { if (!shouldRunTest()) return; TestRunnerUtil.replaceIdeEventQueueSafely(); try { runBareImpl(); } finally { try { EdtTestUtil.runInEdtAndWait(() -> { cleanupApplicationCaches(getProject()); resetAllFields(); }); } catch (Throwable e) { // Ignore } } } private void runBareImpl() throws Throwable { ThrowableRunnable<Throwable> runnable = () -> { ourTestThread = Thread.currentThread(); ourTestTime = DEFAULT_TEST_TIME; try { try { myAssertionsInTestDetected = true; setUp(); myAssertionsInTestDetected = false; } catch (Throwable e) { try { tearDown(); } catch (Throwable ignored) { } throw e; } Throwable exception = null; try { myAssertionsInTestDetected = true; runTest(); myAssertionsInTestDetected = false; } catch (Throwable e) { exception = e; } finally { try { tearDown(); } catch (Throwable e) { if (exception == null) { exception = e; } } } if (exception != null) { throw exception; } } finally { ourTestThread = null; } }; runBareRunnable(runnable); if (IdeaLogger.ourErrorsOccurred != null) { throw IdeaLogger.ourErrorsOccurred; } // just to make sure all deferred Runnable's to finish waitForAllLaters(); if (IdeaLogger.ourErrorsOccurred != null) { throw IdeaLogger.ourErrorsOccurred; } } private static void waitForAllLaters() throws InterruptedException, InvocationTargetException { for (int i = 0; i < 3; i++) { SwingUtilities.invokeAndWait(EmptyRunnable.getInstance()); } } protected void runBareRunnable(ThrowableRunnable<Throwable> runnable) throws Throwable { if (runInDispatchThread()) { EdtTestUtil.runInEdtAndWait(runnable); } else { runnable.run(); } } protected boolean isRunInWriteAction() { return false; } @Override protected void invokeTestRunnable(@NotNull final Runnable runnable) throws Exception { final Exception[] e = new Exception[1]; Runnable runnable1 = () -> { try { if (ApplicationManager.getApplication().isDispatchThread() && isRunInWriteAction()) { ApplicationManager.getApplication().runWriteAction(runnable); } else { runnable.run(); } } catch (Exception e1) { e[0] = e1; } }; if (annotatedWith(WrapInCommand.class)) { CommandProcessor.getInstance().executeCommand(myProject, runnable1, "", null); } else { runnable1.run(); } if (e[0] != null) { throw e[0]; } } @Override public Object getData(String dataId) { return myProject == null ? null : new TestDataProvider(myProject).getData(dataId); } @NotNull public File createTempDir(@NonNls @NotNull String prefix) throws IOException { return createTempDir(prefix, true); } @NotNull public File createTempDir(@NonNls @NotNull String prefix, final boolean refresh) throws IOException { final File tempDirectory = FileUtilRt.createTempDirectory("idea_test_" + prefix, null, false); myFilesToDelete.add(tempDirectory); if (refresh) { getVirtualFile(tempDirectory); } return tempDirectory; } protected static VirtualFile getVirtualFile(@NotNull File file) { return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file); } @NotNull protected File createTempDirectory() throws IOException { return createTempDir(""); } @NotNull protected File createTempDirectory(final boolean refresh) throws IOException { return createTempDir("", refresh); } @NotNull protected File createTempFile(@NotNull String name, @Nullable String text) throws IOException { File directory = createTempDirectory(); File file = new File(directory, name); if (!file.createNewFile()) { throw new IOException("Can't create " + file); } if (text != null) { FileUtil.writeToFile(file, text); } return file; } public static void setContentOnDisk(@NotNull File file, @Nullable byte[] bom, @NotNull String content, @NotNull Charset charset) throws IOException { FileOutputStream stream = new FileOutputStream(file); if (bom != null) { stream.write(bom); } try (OutputStreamWriter writer = new OutputStreamWriter(stream, charset)) { writer.write(content); } } @NotNull public VirtualFile createTempFile(@NonNls @NotNull String ext, @Nullable byte[] bom, @NonNls @NotNull String content, @NotNull Charset charset) throws IOException { File temp = FileUtil.createTempFile("copy", "." + ext); setContentOnDisk(temp, bom, content, charset); myFilesToDelete.add(temp); final VirtualFile file = getVirtualFile(temp); assert file != null : temp; return file; } @Nullable protected PsiFile getPsiFile(final Document document) { return PsiDocumentManager.getInstance(getProject()).getPsiFile(document); } private static void setPlatformPrefix(String prefix) { System.setProperty(PlatformUtils.PLATFORM_PREFIX_KEY, prefix); ourPlatformPrefixInitialized = true; } @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) public @interface WrapInCommand { } @NotNull protected static VirtualFile createChildData(@NotNull final VirtualFile dir, @NotNull @NonNls final String name) { try { return WriteAction.computeAndWait(()-> dir.createChildData(null, name)); } catch (IOException e) { throw new RuntimeException(e); } } @NotNull protected static VirtualFile createChildDirectory(@NotNull final VirtualFile dir, @NotNull @NonNls final String name) { try { return WriteAction.computeAndWait(()-> dir.createChildDirectory(null, name)); } catch (IOException e) { throw new RuntimeException(e); } } protected static void rename(@NotNull final VirtualFile vFile1, @NotNull final String newName) { try { WriteCommandAction.writeCommandAction(null).run(() -> vFile1.rename(vFile1, newName)); } catch (IOException e) { throw new RuntimeException(e); } } protected static void delete(@NotNull final VirtualFile vFile1) { VfsTestUtil.deleteFile(vFile1); } public static void move(@NotNull final VirtualFile vFile1, @NotNull final VirtualFile newFile) { try { WriteCommandAction.writeCommandAction(null).run(() -> vFile1.move(vFile1, newFile)); } catch (IOException e) { throw new RuntimeException(e); } } @NotNull protected static VirtualFile copy(@NotNull final VirtualFile file, @NotNull final VirtualFile newParent, @NotNull final String copyName) { final VirtualFile[] copy = new VirtualFile[1]; try { WriteCommandAction.writeCommandAction(null).run(() -> copy[0] = file.copy(file, newParent, copyName)); } catch (IOException e) { throw new RuntimeException(e); } return copy[0]; } public static void copyDirContentsTo(@NotNull final VirtualFile vTestRoot, @NotNull final VirtualFile toDir) { try { WriteCommandAction.writeCommandAction(null).run(() -> { for (VirtualFile file : vTestRoot.getChildren()) { VfsUtil.copy(file, file, toDir); } }); } catch (IOException e) { throw new RuntimeException(e); } } public static void setFileText(@NotNull final VirtualFile file, @NotNull final String text) { try { WriteAction.runAndWait(() -> VfsUtil.saveText(file, text)); } catch (IOException e) { throw new RuntimeException(e); } } public static void setBinaryContent(@NotNull final VirtualFile file, @NotNull final byte[] content) { try { WriteAction.runAndWait(() -> file.setBinaryContent(content)); } catch (IOException e) { throw new RuntimeException(e); } } public static void setBinaryContent(@NotNull final VirtualFile file, @NotNull final byte[] content, final long newModificationStamp, final long newTimeStamp, final Object requestor) { try { WriteAction.runAndWait(() -> file.setBinaryContent(content, newModificationStamp, newTimeStamp, requestor)); } catch (IOException e) { throw new RuntimeException(e); } } @NotNull protected VirtualFile getOrCreateProjectBaseDir() { VirtualFile baseDir = myProject.getBaseDir(); if (baseDir == null) { String basePath = myProject.getBasePath(); try { FileUtil.ensureExists(new File(Objects.requireNonNull(basePath))); } catch (IOException e) { throw new RuntimeException(e); } return LocalFileSystem.getInstance().refreshAndFindFileByPath(basePath); } return baseDir; } @NotNull protected static VirtualFile getOrCreateModuleDir(@NotNull Module module) throws IOException { File moduleDir = new File(PathUtil.getParentPath(module.getModuleFilePath())); FileUtil.ensureExists(moduleDir); return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(moduleDir); } }
format leaked project info properly
platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java
format leaked project info properly
<ide><path>latform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java <ide> import java.util.Set; <ide> import java.util.concurrent.TimeUnit; <ide> <del>import static com.intellij.testFramework.TemporaryDirectoryKt.generateTemporaryPath; <del> <ide> /** <ide> * @author yole <ide> */ <ide> int hashCode = System.identityHashCode(leaked); <ide> leakers.append("Leaked project found:").append(leaked).append("; hash: ").append(hashCode).append("; place: ") <ide> .append(getCreationPlace(leaked)).append("\n"); <del> leakers.append(backLink+"\n"); <add> leakers.append(backLink).append("\n"); <ide> leakers.append(";-----\n"); <ide> <ide> hashCodes.remove(hashCode); <ide> @NotNull <ide> @TestOnly <ide> public static String getCreationPlace(@NotNull Project project) { <del> String place = project.getUserData(CREATION_PLACE); <ide> Object base; <ide> try { <ide> base = project.isDisposed() ? "" : project.getBaseDir(); <ide> catch (Exception e) { <ide> base = " (" + e + " while getting base dir)"; <ide> } <del> return project + (place != null ? place : "") + base; <add> String place = project.getUserData(CREATION_PLACE); <add> return project + " " +(place == null ? "" : place) + base; <ide> } <ide> <ide> protected void runStartupActivities() { <ide> } <ide> } <ide> <del> Path tempFile = generateTemporaryPath(FileUtil.sanitizeFileName(getName(), false) + (isDirectoryBasedProject ? "" : ProjectFileType.DOT_DEFAULT_EXTENSION)); <add> Path tempFile = TemporaryDirectoryKt <add> .generateTemporaryPath(FileUtil.sanitizeFileName(getName(), false) + (isDirectoryBasedProject ? "" : ProjectFileType.DOT_DEFAULT_EXTENSION)); <ide> myFilesToDelete.add(tempFile.toFile()); <ide> return tempFile; <ide> } <ide> resetClassFields(aClass.getSuperclass()); <ide> } <ide> <del> private String getFullName() { <del> return getClass().getName() + "." + getName(); <del> } <del> <ide> protected void setUpJdk() { <del> //final ProjectJdkEx jdk = ProjectJdkUtil.getDefaultJdk("java 1.4"); <ide> final Sdk jdk = getTestProjectJdk(); <del>// ProjectJdkImpl jdk = ProjectJdkTable.getInstance().addJdk(defaultJdk); <ide> Module[] modules = ModuleManager.getInstance(myProject).getModules(); <ide> for (Module module : modules) { <ide> ModuleRootModificationUtil.setModuleSdk(module, jdk); <ide> resetAllFields(); <ide> }); <ide> } <del> catch (Throwable e) { <del> // Ignore <add> catch (Throwable ignored) { <ide> } <ide> } <ide> }
JavaScript
bsd-3-clause
a762c9df61580cf563a1aa268716f8799b483ed5
0
digi604/django-smart-selects,savoirfairelinux/django-smart-selects,digi604/django-smart-selects,savoirfairelinux/django-smart-selects
(function($) { chainedm2m = function() { return { fireEvent: function(element,event) { var evt; if (document.createEventObject){ // dispatch for IE evt = document.createEventObject(); return element.fireEvent('on'+event,evt); } else{ // dispatch for firefox + others evt = document.createEvent("HTMLEvents"); evt.initEvent(event, true, true ); // event type,bubbling,cancelable return !element.dispatchEvent(evt); } }, dismissRelatedLookupPopup: function(win, chosenId) { var name = windowname_to_id(win.name); var elem = document.getElementById(name); if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) { elem.value += ',' + chosenId; } else { elem.value = chosenId; } fireEvent(elem, 'change'); win.close(); }, fill_field: function(val, initial_value, elem_id, url, initial_parent, auto_choose){ var $selectField = $(elem_id), $selectedto = $(elem_id+'_to'), cache_to = elem_id.replace('#', '') + '_to', cache_from = elem_id.replace('#', '') + '_from'; if (!$selectField.length) { $selectField = $(elem_id+'_from'); } function trigger_chosen_updated() { if ($.fn.chosen !== undefined) { $selectField.trigger('chosen:updated'); } } if (!val || val === ''){ $selectField.html(''); trigger_chosen_updated(); return; } // Make sure that these are always an arrays val = [].concat(val); initial_parent = [].concat(initial_parent); var target_url = url + "/" + val + "/"; options = [], selectedoptions = []; $.getJSON(target_url, function(j){ auto_choose = j.length == 1 && auto_choose; var selected_values = {}; // if val and initial_parent have any common values, we need to set selected options. if($(val).filter(initial_parent).length >= 0 && initial_value) { for (var i = 0; i < initial_value.length; i++) { selected_values[initial_value[i]] = true; } } // select values which were previously selected (for many2many - many2many chain) $(elem_id + ' option:selected').each(function(){ selected_values[$(this).val()] = true; }); $.each(j, function (index, optionData) { var option = $('<option></option>') .attr('value', optionData.value) .text(optionData.display) .attr('title', optionData.display); if (auto_choose || selected_values[optionData.value] === true) { if ($selectedto.length) { selectedoptions.push(option); } else { option.prop('selected', true); options.push(option); } } else { options.push(option); } }); $selectField.html(options); if ($selectedto.length) { $selectedto.html(selectedoptions); // SelectBox is a global var from djangojs "admin/js/SelectBox.js" for (var i = 0, j = selectedoptions.length; i < j; i++) { node = selectedoptions[i]; SelectBox.cache[cache_to].push({value: node.prop("value"), text: node.prop("text"), displayed: 1}); } for (var i = 0, j = options.length; i < j; i++) { node = options[i]; SelectBox.cache[cache_from].push({value: node.prop("value"), text: node.prop("text"), displayed: 1}); } } var width = $selectField.outerWidth(); if (navigator.appVersion.indexOf("MSIE") != -1) $selectField.width(width + 'px'); $selectField.trigger('change'); trigger_chosen_updated(); }); }, init: function(chainfield, url, id, value, auto_choose) { var initial_parent = $(chainfield).val(); var initial_value = value; if(!$(chainfield).hasClass("chained")){ var val = $(chainfield).val(); this.fill_field(val, initial_value, id, url, initial_parent, auto_choose); } var fill_field = this.fill_field; $(chainfield).change(function(){ var localID = id; if (localID.indexOf("__prefix__") > -1) { var prefix = $(this).attr("id").match(/\d+/)[0]; localID = localID.replace("__prefix__", prefix); } var start_value = $(localID).val(); var val = $(this).val(); fill_field(val, initial_value, localID, url, initial_parent, auto_choose); }); // allait en bas, hors du documentready if (typeof(dismissAddAnotherPopup) !== 'undefined') { var oldDismissAddAnotherPopup = dismissAddAnotherPopup; dismissAddAnotherPopup = function(win, newId, newRepr) { oldDismissAddAnotherPopup(win, newId, newRepr); if ("#" + windowname_to_id(win.name) == chainfield) { $(chainfield).change(); } }; } } }; }(); })(jQuery || django.jQuery);
smart_selects/static/smart-selects/admin/js/chainedm2m.js
(function($) { chainedm2m = function() { return { fireEvent: function(element,event) { var evt; if (document.createEventObject){ // dispatch for IE evt = document.createEventObject(); return element.fireEvent('on'+event,evt); } else{ // dispatch for firefox + others evt = document.createEvent("HTMLEvents"); evt.initEvent(event, true, true ); // event type,bubbling,cancelable return !element.dispatchEvent(evt); } }, dismissRelatedLookupPopup: function(win, chosenId) { var name = windowname_to_id(win.name); var elem = document.getElementById(name); if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) { elem.value += ',' + chosenId; } else { elem.value = chosenId; } fireEvent(elem, 'change'); win.close(); }, fill_field: function(val, initial_value, elem_id, url, initial_parent, auto_choose){ var $selectField = $(elem_id), $selectedto = $(elem_id+'_to'), cache_to = elem_id.replace('#', '') + '_to', cache_from = elem_id.replace('#', '') + '_from'; if (!$selectField.length) { $selectField = $(elem_id+'_from'); } function trigger_chosen_updated() { if ($.fn.chosen !== undefined) { $selectField.trigger('chosen:updated'); } } if (!val || val === ''){ $selectField.html(''); trigger_chosen_updated(); return; } // Make sure that these are always an arrays val = [].concat(val); initial_parent = [].concat(initial_parent); var target_url = url + "/" + val + "/"; options = [], selectedoptions = []; $.getJSON(target_url, function(j){ auto_choose = j.length == 1 && auto_choose; var selected_values = {}; // if val and initial_parent have any common values, we need to set selected options. if($(val).filter(initial_parent).length >= 0) { for (var i = 0; i < initial_value.length; i++) { selected_values[initial_value[i]] = true; } } // select values which were previously selected (for many2many - many2many chain) $(elem_id + ' option:selected').each(function(){ selected_values[$(this).val()] = true; }); $.each(j, function (index, optionData) { var option = $('<option></option>') .attr('value', optionData.value) .text(optionData.display) .attr('title', optionData.display); if (auto_choose || selected_values[optionData.value] === true) { if ($selectedto.length) { selectedoptions.push(option); } else { option.prop('selected', true); options.push(option); } } else { options.push(option); } }); $selectField.html(options); if ($selectedto.length) { $selectedto.html(selectedoptions); // SelectBox is a global var from djangojs "admin/js/SelectBox.js" for (var i = 0, j = selectedoptions.length; i < j; i++) { node = selectedoptions[i]; SelectBox.cache[cache_to].push({value: node.prop("value"), text: node.prop("text"), displayed: 1}); } for (var i = 0, j = options.length; i < j; i++) { node = options[i]; SelectBox.cache[cache_from].push({value: node.prop("value"), text: node.prop("text"), displayed: 1}); } } var width = $selectField.outerWidth(); if (navigator.appVersion.indexOf("MSIE") != -1) $selectField.width(width + 'px'); $selectField.trigger('change'); trigger_chosen_updated(); }); }, init: function(chainfield, url, id, value, auto_choose) { var initial_parent = $(chainfield).val(); var initial_value = value; if(!$(chainfield).hasClass("chained")){ var val = $(chainfield).val(); this.fill_field(val, initial_value, id, url, initial_parent, auto_choose); } var fill_field = this.fill_field; $(chainfield).change(function(){ var localID = id; if (localID.indexOf("__prefix__") > -1) { var prefix = $(this).attr("id").match(/\d+/)[0]; localID = localID.replace("__prefix__", prefix); } var start_value = $(localID).val(); var val = $(this).val(); fill_field(val, initial_value, localID, url, initial_parent, auto_choose); }); // allait en bas, hors du documentready if (typeof(dismissAddAnotherPopup) !== 'undefined') { var oldDismissAddAnotherPopup = dismissAddAnotherPopup; dismissAddAnotherPopup = function(win, newId, newRepr) { oldDismissAddAnotherPopup(win, newId, newRepr); if ("#" + windowname_to_id(win.name) == chainfield) { $(chainfield).change(); } }; } } }; }(); })(jQuery || django.jQuery);
little change for empty list
smart_selects/static/smart-selects/admin/js/chainedm2m.js
little change for empty list
<ide><path>mart_selects/static/smart-selects/admin/js/chainedm2m.js <ide> <ide> var selected_values = {}; <ide> // if val and initial_parent have any common values, we need to set selected options. <del> if($(val).filter(initial_parent).length >= 0) { <add> if($(val).filter(initial_parent).length >= 0 && initial_value) { <ide> for (var i = 0; i < initial_value.length; i++) { <ide> selected_values[initial_value[i]] = true; <ide> }
Java
bsd-3-clause
d21fc14a90c60f1efd058bf30c2905744b164302
0
NCIP/cacore-sdk,NCIP/cacore-sdk,NCIP/cacore-sdk,NCIP/cacore-sdk,NCIP/cacore-sdk,NCIP/cacore-sdk,NCIP/cacore-sdk
package gov.nih.nci.sdk.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Set; import org.junit.Test; /** * ModelConverterUtilTest * * @author John Chen * */ public class SDKUtilTest { @Test public void loadTags() { Set<String> tagNames = SDKUtil.getAllSDKTagNames(); assertEquals("All tags loaded", 58, tagNames.size()); } @Test public void isSDKTag() { assertFalse(SDKUtil.isSDKTag("this.is.not.sdk.tag")); assertTrue(SDKUtil.isSDKTag("package.prop.sec.encrypt")); assertTrue(SDKUtil.isSDKTag("package.oper.sec.role")); assertTrue(SDKUtil.isSDKTag("oper.sec.role")); assertTrue(SDKUtil.isSDKTag("oper.mea.desc")); assertTrue(SDKUtil.isSDKTag("rel.mea.desc")); assertTrue(SDKUtil.isSDKTag("class.per.table.name")); assertTrue(SDKUtil.isSDKTag("prop.per.primary.key")); assertTrue(SDKUtil.isSDKTag("prop.val.required")); assertTrue(SDKUtil.isSDKTag("prop.val.max.length")); assertTrue(SDKUtil.isSDKTag("prop.val.min.length")); } }
hydra/src/test/gov/nih/nci/sdk/util/SDKUtilTest.java
package gov.nih.nci.sdk.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Set; import org.junit.Test; /** * ModelConverterUtilTest * * @author John Chen * */ public class SDKUtilTest { @Test public void loadTags() { Set<String> tagNames = SDKUtil.getAllSDKTagNames(); assertEquals("All tags loaded", 56, tagNames.size()); } @Test public void isSDKTag() { assertFalse(SDKUtil.isSDKTag("this.is.not.sdk.tag")); assertTrue(SDKUtil.isSDKTag("package.prop.sec.encrypt")); assertTrue(SDKUtil.isSDKTag("package.oper.sec.role")); assertTrue(SDKUtil.isSDKTag("oper.sec.role")); assertTrue(SDKUtil.isSDKTag("oper.mea.desc")); assertTrue(SDKUtil.isSDKTag("rel.mea.desc")); assertTrue(SDKUtil.isSDKTag("class.per.table.name")); assertTrue(SDKUtil.isSDKTag("prop.per.primary.key")); assertTrue(SDKUtil.isSDKTag("prop.val.required")); assertTrue(SDKUtil.isSDKTag("prop.val.max.length")); assertTrue(SDKUtil.isSDKTag("prop.val.min.length")); } }
Updated with the newly added annotation tags SVN-Revision: 1257
hydra/src/test/gov/nih/nci/sdk/util/SDKUtilTest.java
Updated with the newly added annotation tags
<ide><path>ydra/src/test/gov/nih/nci/sdk/util/SDKUtilTest.java <ide> @Test <ide> public void loadTags() { <ide> Set<String> tagNames = SDKUtil.getAllSDKTagNames(); <del> assertEquals("All tags loaded", 56, tagNames.size()); <add> assertEquals("All tags loaded", 58, tagNames.size()); <ide> } <ide> <ide> @Test
JavaScript
apache-2.0
616ef1f58cd2c469f2a984b3d11badad74740619
0
opencb/jsorolla,opencb/jsorolla,opencb/jsorolla,opencb/jsorolla,opencb/jsorolla
/* * Copyright (c) 2015 Francisco Salavert (DCG-CIPF) * * This file is part of JS Common Libs. * * JS Common Libs 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. * * JS Common Libs 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 JS Common Libs. If not, see <http://www.gnu.org/licenses/>. */ /** * ** Generic adapter to any uri new FeatureTemplateAdapter({ uriTemplate: 'http://host/webserver/{customVar}/{species}/{region}', templateVariables: { customVar: 'info', }, species: genomeViewer.species, parse: function (response) { var itemsArray = []; for (var i = 0; i < response.response.length; i++) { var r = response.response[i]; itemsArray.push(r.result); } return itemsArray; } }) * ** templateVariables is used for custom variables in the uri. region and species will be ignored * ** as will be configured automatically * ** The species config is the current species should not appear in templateVariables * ** The region in the uriTemplate is provided by the track so should not appear in templateVariables * ** The parse function is used to adapt de features from the response */ function FeatureTemplateAdapter(args) { _.extend(this, Backbone.Events); this.templateVariables = {}; this.multiRegions = true; this.histogramMultiRegions = true; _.extend(this, args); this.configureCache(); this.debug = false; } FeatureTemplateAdapter.prototype = { setSpecies: function(species) { this.species = species; this.configureCache(); }, setHost: function(host) { this.configureCache(); this.host = host; }, configureCache: function() { var speciesString = ''; if (this.species != null) { var speciesString = this.species.id + this.species.assembly.name.replace(/[/_().\ -]/g, ''); } var cacheId = this.uriTemplate + speciesString; if (!this.cacheConfig) { this.cacheConfig = { // //subCacheId: this.resource + this.params.keys(), chunkSize: 3000 } } this.cacheConfig.cacheId = cacheId; this.cache = new FeatureChunkCache(this.cacheConfig); }, getData: function(args) { var _this = this; var params = {}; //histogram: (dataType == 'histogram') _.extend(params, this.params); _.extend(params, args.params); /** 1 region check **/ var region = args.region; var regionLimit = 300000000; if (this.species != null && this.species.chromosomes[region.chromosome] != null) { regionLimit = this.species.chromosomes[args.region.chromosome].end; } if (region.start > regionLimit || region.end < 1) { return; } region.start = (region.start < 1) ? 1 : region.start; region.end = (region.end > regionLimit) ? regionLimit : region.end; /** 2 category check **/ var categories = ["cat_" + Utils.queryString(this.templateVariables) + Utils.queryString(params)]; /** 3 dataType check **/ var dataType = args.dataType; if (_.isUndefined(dataType)) { console.log("dataType must be provided!!!"); } /** 4 chunkSize check **/ var chunkSize = params.interval ? params.interval : this.cacheConfig.chunkSize; // this.cache.defaultChunkSize should be the same if (this.debug) { console.log(chunkSize); } /** * Get the uncached regions (uncachedRegions) and cached chunks (cachedChunks). * Uncached regions will be used to query cellbase. The response data will be converted in chunks * by the Cache TODO???? * Cached chunks will be returned by the args.dataReady Callback. */ this.cache.get(region, categories, dataType, chunkSize, function(cachedChunks, uncachedRegions) { var category = categories[0]; var categoriesName = ""; for (var j = 0; j < categories.length; j++) { categoriesName += "," + categories[j]; } categoriesName = categoriesName.slice(1); // to remove first ',' var chunks = cachedChunks[category]; // TODO check how to manage multiple regions var queriesList; if (dataType !== 'histogram') { if (_this.multiRegions === false) { queriesList = _this._singleQueries(uncachedRegions[category]); } else { queriesList = _this._groupQueries(uncachedRegions[category]); } } else { if (_this.histogramMultiRegions === false) { queriesList = _this._singleQueries(uncachedRegions[category]); } else { queriesList = _this._groupQueries(uncachedRegions[category]); } } /** Uncached regions found **/ if (queriesList.length > 0) { args.webServiceCallCount = 0; for (var i = 0; i < queriesList.length; i++) { args.webServiceCallCount++; var queryRegion = queriesList[i]; var request = new XMLHttpRequest(); /** Temporal fix save queried region **/ request._queryRegion = queryRegion; request._originalRegion = region; request.onload = function() { args.webServiceCallCount--; if (request.status !== 400) { var response; try { response = JSON.parse(this.response); } catch (e) { console.log('Warning: Response is not JSON'); response = this.response; } /** Process response **/ var responseChunks = _this._success(response, categories, dataType, this._queryRegion, this._originalRegion, chunkSize); chunks = chunks.concat(responseChunks); } else { console.log("request.status: " + request.status); } if (args.webServiceCallCount === 0) { chunks.sort(function(a, b) { return a.chunkKey.localeCompare(b.chunkKey) }); args.done({ items: chunks, dataType: dataType, chunkSize: chunkSize, sender: _this }); } }; request.onerror = function() { console.log('Server error'); args.done(); }; var uriTemplate = new URITemplate(_this.uriTemplate); _this.templateVariables['region'] = queryRegion.toString(); _this.templateVariables['species'] = _this._getSpeciesQueryString(_this.species); var url = uriTemplate.expand(_this.templateVariables); url = Utils.addQueryParamtersToUrl(params, url); request.open('GET', url, true); console.log(url); request.send(); } } else /** All regions are cached **/ { args.done({ items: chunks, dataType: dataType, chunkSize: chunkSize, sender: _this }); } }); }, _success: function(response, categories, dataType, queryRegion, originalRegion, chunkSize) { //var timeId = Utils.randomString(4) + this.resource + " save"; //console.time(timeId); /** time log **/ var regions = []; var chunks = []; if (dataType !== 'histogram') { if (typeof this.parse === 'function') { chunks = this.parse(response, dataType); } else { chunks = response; } regions = this._getRegionsFromQueryRegions(queryRegion); } else { if (typeof this.parseHistogram === 'function') { chunks = this.parseHistogram(response); } else { chunks = response; } regions = this._getRegionsFromHistogramChunks(chunks, originalRegion.chromosome); } var items = this.cache.putByRegions(regions, chunks, categories, dataType, chunkSize); /** time log **/ //console.timeEnd(timeId); return items; }, /** * Transform the list on a list of lists, to limit the queries * [ r1,r2,r3,r4,r5,r6,r7,r8 ] * [ [r1,r2,r3,r4], [r5,r6,r7,r8] ] */ _groupQueries: function(uncachedRegions) { var groupSize = 50; var queriesLists = []; while (uncachedRegions.length > 0) { queriesLists.push(uncachedRegions.splice(0, groupSize).toString()); } return queriesLists; }, _singleQueries: function(uncachedRegions) { var queriesLists = []; for (var i = 0; i < uncachedRegions.length; i++) { var region = uncachedRegions[i]; queriesLists.push(region.toString()); } return queriesLists; }, _getSpeciesQueryString: function(species) { if (species == null) { return ''; } if (this.speciesParse != null) { return this.speciesParse(species); } else { return Utils.getSpeciesCode(species.scientificName) } }, _getRegionsFromQueryRegions: function(queryRegion) { var regions = []; var regionSplit = queryRegion.split(','); for (var i = 0; i < regionSplit.length; i++) { var regionStr = regionSplit[i]; regions.push(new Region(regionStr)); } return regions; }, _getRegionsFromHistogramChunks: function(intervals, chromosome) { var regions = []; for (var i = 0; i < intervals.length; i++) { var interval = intervals[i]; var region = new Region(interval); region.chromosome = chromosome; regions.push(region); } return regions; }, };
src/lib/data-adapter/feature/feature-template-adapter.js
/* * Copyright (c) 2015 Francisco Salavert (DCG-CIPF) * * This file is part of JS Common Libs. * * JS Common Libs 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. * * JS Common Libs 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 JS Common Libs. If not, see <http://www.gnu.org/licenses/>. */ /** * ** Generic adapter to any uri new FeatureTemplateAdapter({ uriTemplate: 'http://host/webserver/{customVar}/{species}/{region}', templateVariables: { customVar: 'info', }, species: genomeViewer.species, parse: function (response) { var itemsArray = []; for (var i = 0; i < response.response.length; i++) { var r = response.response[i]; itemsArray.push(r.result); } return itemsArray; } }) * ** templateVariables is used for custom variables in the uri. region and species will be ignored * ** as will be configured automatically * ** The species config is the current species should not appear in templateVariables * ** The region in the uriTemplate is provided by the track so should not appear in templateVariables * ** The parse function is used to adapt de features from the response */ function FeatureTemplateAdapter(args) { _.extend(this, Backbone.Events); this.templateVariables = {}; this.multiRegions = true; this.histogramMultiRegions = true; _.extend(this, args); this.configureCache(); this.debug = false; } FeatureTemplateAdapter.prototype = { setSpecies: function(species) { this.species = species; this.configureCache(); }, setHost: function(host) { this.configureCache(); this.host = host; }, configureCache: function() { var speciesString = ''; if (this.species != null) { var speciesString = this.species.id + this.species.assembly.name.replace(/[/_().\ -]/g, ''); } var cacheId = this.uriTemplate + speciesString; if (!this.cacheConfig) { this.cacheConfig = { // //subCacheId: this.resource + this.params.keys(), chunkSize: 3000 } } this.cacheConfig.cacheId = cacheId; this.cache = new FeatureChunkCache(this.cacheConfig); }, getData: function(args) { var _this = this; var params = {}; //histogram: (dataType == 'histogram') _.extend(params, this.params); _.extend(params, args.params); /** 1 region check **/ var region = args.region; var regionLimit = 300000000; if (this.species != null && this.species.chromosomes[region.chromosome] != null) { regionLimit = this.species.chromosomes[args.region.chromosome].end; } if (region.start > regionLimit || region.end < 1) { return; } region.start = (region.start < 1) ? 1 : region.start; region.end = (region.end > regionLimit) ? regionLimit : region.end; /** 2 category check **/ var categories = ["cat_" + Utils.queryString(this.templateVariables) + Utils.queryString(params)]; /** 3 dataType check **/ var dataType = args.dataType; if (_.isUndefined(dataType)) { console.log("dataType must be provided!!!"); } /** 4 chunkSize check **/ var chunkSize = params.interval ? params.interval : this.cacheConfig.chunkSize; // this.cache.defaultChunkSize should be the same if (this.debug) { console.log(chunkSize); } /** * Get the uncached regions (uncachedRegions) and cached chunks (cachedChunks). * Uncached regions will be used to query cellbase. The response data will be converted in chunks * by the Cache TODO???? * Cached chunks will be returned by the args.dataReady Callback. */ this.cache.get(region, categories, dataType, chunkSize, function(cachedChunks, uncachedRegions) { var category = categories[0]; var categoriesName = ""; for (var j = 0; j < categories.length; j++) { categoriesName += "," + categories[j]; } categoriesName = categoriesName.slice(1); // to remove first ',' var chunks = cachedChunks[category]; // TODO check how to manage multiple regions var queriesList; if (dataType !== 'histogram') { if (_this.multiRegions === false) { queriesList = _this._singleQueries(uncachedRegions[category]); } else { queriesList = _this._groupQueries(uncachedRegions[category]); } } else { if (_this.histogramMultiRegions === false) { queriesList = _this._singleQueries(uncachedRegions[category]); } else { queriesList = _this._groupQueries(uncachedRegions[category]); } } /** Uncached regions found **/ if (queriesList.length > 0) { args.webServiceCallCount = 0; for (var i = 0; i < queriesList.length; i++) { args.webServiceCallCount++; var queryRegion = queriesList[i]; var request = new XMLHttpRequest(); /** Temporal fix save queried region **/ request._queryRegion = queryRegion; request._originalRegion = region; request.onload = function() { args.webServiceCallCount--; if (request.status === 200) { var response; try { response = JSON.parse(this.response); } catch (e) { console.log('Warning: Response is not JSON'); response = this.response; } /** Process response **/ var responseChunks = _this._success(response, categories, dataType, this._queryRegion, this._originalRegion, chunkSize); chunks = chunks.concat(responseChunks); } else { console.log("request.status: " + request.status); } if (args.webServiceCallCount === 0) { chunks.sort(function(a, b) { return a.chunkKey.localeCompare(b.chunkKey) }); args.done({ items: chunks, dataType: dataType, chunkSize: chunkSize, sender: _this }); } }; request.onerror = function() { console.log('Server error'); args.done(); }; var uriTemplate = new URITemplate(_this.uriTemplate); _this.templateVariables['region'] = queryRegion.toString(); _this.templateVariables['species'] = _this._getSpeciesQueryString(_this.species); var url = uriTemplate.expand(_this.templateVariables); url = Utils.addQueryParamtersToUrl(params, url); request.open('GET', url, true); console.log(url); request.send(); } } else /** All regions are cached **/ { args.done({ items: chunks, dataType: dataType, chunkSize: chunkSize, sender: _this }); } }); }, _success: function(response, categories, dataType, queryRegion, originalRegion, chunkSize) { //var timeId = Utils.randomString(4) + this.resource + " save"; //console.time(timeId); /** time log **/ var regions = []; var chunks = []; if (dataType !== 'histogram') { if (typeof this.parse === 'function') { chunks = this.parse(response, dataType); } else { chunks = response; } regions = this._getRegionsFromQueryRegions(queryRegion); } else { if (typeof this.parseHistogram === 'function') { chunks = this.parseHistogram(response); } else { chunks = response; } regions = this._getRegionsFromHistogramChunks(chunks, originalRegion.chromosome); } var items = this.cache.putByRegions(regions, chunks, categories, dataType, chunkSize); /** time log **/ //console.timeEnd(timeId); return items; }, /** * Transform the list on a list of lists, to limit the queries * [ r1,r2,r3,r4,r5,r6,r7,r8 ] * [ [r1,r2,r3,r4], [r5,r6,r7,r8] ] */ _groupQueries: function(uncachedRegions) { var groupSize = 50; var queriesLists = []; while (uncachedRegions.length > 0) { queriesLists.push(uncachedRegions.splice(0, groupSize).toString()); } return queriesLists; }, _singleQueries: function(uncachedRegions) { var queriesLists = []; for (var i = 0; i < uncachedRegions.length; i++) { var region = uncachedRegions[i]; queriesLists.push(region.toString()); } return queriesLists; }, _getSpeciesQueryString: function(species) { if (species == null) { return ''; } if (this.speciesParse != null) { return this.speciesParse(species); } else { return Utils.getSpeciesCode(species.scientificName) } }, _getRegionsFromQueryRegions: function(queryRegion) { var regions = []; var regionSplit = queryRegion.split(','); for (var i = 0; i < regionSplit.length; i++) { var regionStr = regionSplit[i]; regions.push(new Region(regionStr)); } return regions; }, _getRegionsFromHistogramChunks: function(intervals, chromosome) { var regions = []; for (var i = 0; i < intervals.length; i++) { var interval = intervals[i]; var region = new Region(interval); region.chromosome = chromosome; regions.push(region); } return regions; }, };
feature template adapter status fix
src/lib/data-adapter/feature/feature-template-adapter.js
feature template adapter status fix
<ide><path>rc/lib/data-adapter/feature/feature-template-adapter.js <ide> <ide> request.onload = function() { <ide> args.webServiceCallCount--; <del> if (request.status === 200) { <add> if (request.status !== 400) { <ide> var response; <ide> try { <ide> response = JSON.parse(this.response);
JavaScript
mit
939a732ff63b1004f52f992dd5d642566a633dc8
0
A-Tokyo/generator-at-angular,A-Tokyo/generator-at-angular,A-Tokyo/generator-at-angular
'use strict'; var _ = require("lodash"); var utils = require("../../../utils.js"); module.exports = function (AngularATGenerator) { AngularATGenerator.prototype.copyCopmFiles = function copyFiles() { var data = {'pageName': this.props.pageName, 'pageNameCamel': _.camelCase(this.props.pageName), 'controllerName': _.upperFirst(_.camelCase(this.props.pageName)), 'pageModule': _.camelCase(this.props.pageModule), 'pageState': this.props.pageState, 'pageRoute': this.props.pageRoute}; this.fs.copyTpl( this.templatePath('page.html'), this.destinationPath(this.destinationRoot()+'/src/app/pages/'+data.pageName+'/'+data.pageName+'.html'), data ); this.fs.copyTpl( this.templatePath('page.scss'), this.destinationPath(this.destinationRoot()+'/src/app/pages/'+data.pageName+'/'+data.pageName+'.scss'), data ); this.fs.copyTpl( this.templatePath('page.module.js'), this.destinationPath(this.destinationRoot()+'/src/app/pages/'+data.pageName+'/'+data.pageName+'.module'+'.js'), data ); this.fs.copyTpl( this.templatePath('page.route.js'), this.destinationPath(this.destinationRoot()+'/src/app/pages/'+data.pageName+'/'+data.pageName+'.route'+'.js'), data ); this.fs.copyTpl( this.templatePath('page.controller.js'), this.destinationPath(this.destinationRoot()+'/src/app/pages/'+data.pageName+'/'+data.pageName+'.controller'+'.js'), data ); var indexModulesWriteLine = "require('./pages/"+data.pageName+"/"+data.pageName+".module').name,"; utils.addToFile("index.module.js",indexModulesWriteLine,utils.PAGE_MARKER,this.destinationRoot()+"/src/app"); }; };
generators/page/src/files.js
'use strict'; var _ = require("lodash"); var utils = require("../../../utils.js"); module.exports = function (AngularATGenerator) { AngularATGenerator.prototype.copyCopmFiles = function copyFiles() { var data = {'pageName': this.props.pageName, 'pageNameCamel': _.camelCase(this.props.pageName), 'controllerName': _.upperFirst(_.camelCase(this.props.pageName)), 'pageModule': _.camelCase(this.props.pageModule), 'pageState': this.props.pageState, 'pageRoute': this.props.pageRoute}; this.fs.copyTpl( this.templatePath('page.html'), this.destinationPath(this.destinationRoot()+'/src/app/pages/'+data.pageName+'/'+data.pageName+'.html'), data ); this.fs.copyTpl( this.templatePath('page.scss'), this.destinationPath(this.destinationRoot()+'/src/app/pages/'+data.pageName+'/'+data.pageName+'.scss'), data ); this.fs.copyTpl( this.templatePath('page.module.js'), this.destinationPath(this.destinationRoot()+'/src/app/pages/'+data.pageName+'/'+data.pageName+'.module'+'.js'), data ); this.fs.copyTpl( this.templatePath('page.route.js'), this.destinationPath(this.destinationRoot()+'/src/app/pages/'+data.pageName+'/'+data.pageName+'.route'+'.js'), data ); this.fs.copyTpl( this.templatePath('page.controller.js'), this.destinationPath(this.destinationRoot()+'/src/app/pages/'+data.pageName+'/'+data.pageName+'.controller'+'.js'), data ); var indexModulesWriteLine = "require('./pages/"+data.pageName+"/"+data.pageName+".module').name,"; utils.addToFile("index.module.js",indexModulesWriteLine,utils.PAGE_MARKER,this.destinationRoot()+"/src/app"); // var indexScssWriteLine = "@import '../../../app/components/"+this.props.componentName+"/"+this.props.componentName + ".scss';"; // utils.addToFile("index.scss",indexScssWriteLine,utils.SCSS_MARKER,this.destinationRoot()+"/src/assets/styles/sass"); }; };
removed unnecessary comments
generators/page/src/files.js
removed unnecessary comments
<ide><path>enerators/page/src/files.js <ide> ); <ide> var indexModulesWriteLine = "require('./pages/"+data.pageName+"/"+data.pageName+".module').name,"; <ide> utils.addToFile("index.module.js",indexModulesWriteLine,utils.PAGE_MARKER,this.destinationRoot()+"/src/app"); <del> // var indexScssWriteLine = "@import '../../../app/components/"+this.props.componentName+"/"+this.props.componentName + ".scss';"; <del> // utils.addToFile("index.scss",indexScssWriteLine,utils.SCSS_MARKER,this.destinationRoot()+"/src/assets/styles/sass"); <ide> }; <ide> };
Java
apache-2.0
0d1aaf2fd3e933b506bd705c92a43630b44566db
0
xiexiang89/Android-Auto-BannerView,xiexiang89/Android-Auto-BannerView,xiexiang89/Android-Auto-BannerView
/* * Copyright (C) 2016 The Edgar * * 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 banner.edgar.com.banner.activitys; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.edgar.banner.BannerItem; import com.edgar.banner.BannerPagerView; import com.facebook.drawee.backends.pipeline.Fresco; import java.util.ArrayList; import java.util.List; import banner.edgar.com.banner.FrescoBannerPageView; import banner.edgar.com.banner.R; import banner.edgar.com.banner.ToastUtils; public class MainActivity extends AppCompatActivity { private static final String ACTIVITYS_NAME = "banner.edgar.com.banner.activitys.%sActivity"; private BannerPagerView mBannerPagerView; private ListView mSampleListView; private ArrayAdapter<String> mSampleListAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSampleListView = (ListView) findViewById(R.id.listview); String[] array = getResources().getStringArray(R.array.banner_demo); mSampleListAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,array); mSampleListView.setAdapter(mSampleListAdapter); mSampleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { try { Class<?> clazz = getClassLoader().loadClass(generateActivityClassName(mSampleListAdapter.getItem(position))); Intent intent = new Intent(MainActivity.this,clazz); startActivity(intent); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }); } private static String generateActivityClassName(String prefixName){ return String.format(ACTIVITYS_NAME,prefixName); } }
app/src/main/java/banner/edgar/com/banner/activitys/MainActivity.java
/* * Copyright (C) 2016 The Edgar * * 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 banner.edgar.com.banner.activitys; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.edgar.banner.BannerItem; import com.edgar.banner.BannerPagerView; import com.facebook.drawee.backends.pipeline.Fresco; import java.util.ArrayList; import java.util.List; import banner.edgar.com.banner.FrescoBannerPageView; import banner.edgar.com.banner.R; import banner.edgar.com.banner.ToastUtils; public class MainActivity extends AppCompatActivity { private static final String ACTIVITYS_NAME = "banner.edgar.com.banner.activitys.%sActivity"; private BannerPagerView mBannerPagerView; private ListView mSampleListView; private ArrayAdapter<String> mSampleListAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSampleListView = (ListView) findViewById(R.id.listview); String[] array = getResources().getStringArray(R.array.banner_demo); mSampleListAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,array); mSampleListView.setAdapter(mSampleListAdapter); mSampleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { try { Class<?> clazz = getClassLoader().loadClass(generateActivityClassName(mSampleListAdapter.getItem(position))); Intent intent = new Intent(MainActivity.this,clazz); startActivity(intent); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }); // mBannerPagerView = (BannerPagerView) findViewById(R.id.banner_pager); // mBannerPagerView.setBannerPagerView(new FrescoBannerPageView()); // mBannerPagerView.setOnBannerClickListener(new BannerPagerView.OnBannerClickListener() { // @Override // public void onBannerClick(BannerItem bannerItem) { // ToastUtils.showToast(MainActivity.this,bannerItem.getBannerTitle()); // } // }); // mBannerPagerView.setBanner(BANNER_ITEMS); } private static String generateActivityClassName(String prefixName){ return String.format(ACTIVITYS_NAME,prefixName); } }
Remove old code
app/src/main/java/banner/edgar/com/banner/activitys/MainActivity.java
Remove old code
<ide><path>pp/src/main/java/banner/edgar/com/banner/activitys/MainActivity.java <ide> } <ide> } <ide> }); <del>// mBannerPagerView = (BannerPagerView) findViewById(R.id.banner_pager); <del>// mBannerPagerView.setBannerPagerView(new FrescoBannerPageView()); <del>// mBannerPagerView.setOnBannerClickListener(new BannerPagerView.OnBannerClickListener() { <del>// @Override <del>// public void onBannerClick(BannerItem bannerItem) { <del>// ToastUtils.showToast(MainActivity.this,bannerItem.getBannerTitle()); <del>// } <del>// }); <del>// mBannerPagerView.setBanner(BANNER_ITEMS); <ide> } <ide> <ide> private static String generateActivityClassName(String prefixName){
Java
bsd-3-clause
5ccbe666287e290dbdbcddf99ec517a7bf2eac89
0
knopflerfish/knopflerfish.org,knopflerfish/knopflerfish.org,knopflerfish/knopflerfish.org
/* * Oscar Bundle Repository * Copyright (c) 2004, Richard S. Hall * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of the ungoverned.org nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Contact: Richard S. Hall ([email protected]) * Contributor(s): * **/ package org.ungoverned.osgi.bundle.bundlerepository; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.*; import kxml.sax.KXmlSAXParser; import org.osgi.framework.*; import org.osgi.service.packageadmin.ExportedPackage; import org.osgi.service.packageadmin.PackageAdmin; import org.ungoverned.osgi.service.bundlerepository.*; import fr.imag.adele.metadataparser.MultivalueMap; import fr.imag.adele.metadataparser.XmlCommonHandler; public class BundleRepositoryServiceImpl implements BundleRepositoryService { private BundleContext m_context = null; private boolean m_initialized = false; private String[] m_urls = null; private List m_bundleList = new ArrayList(); private Map m_exportPackageMap = new HashMap(); private static final int EXPORT_PACKAGE_IDX = 0; private static final int EXPORT_BUNDLE_IDX = 1; private int m_hopCount = 1; private static final String[] DEFAULT_REPOSITORY_URL = { "http://oscar-osgi.sf.net/repository.xml" }; public static final String REPOSITORY_URL_PROP = "oscar.repository.url"; public static final String EXTERN_REPOSITORY_TAG = "extern-repositories"; public BundleRepositoryServiceImpl(BundleContext context) { m_context = context; String urlStr = context.getProperty(REPOSITORY_URL_PROP); if (urlStr != null) { StringTokenizer st = new StringTokenizer(urlStr); if (st.countTokens() > 0) { m_urls = new String[st.countTokens()]; for (int i = 0; i < m_urls.length; i++) { m_urls[i] = st.nextToken(); } } } // Use the default URL if none were specified. if (m_urls == null) { m_urls = DEFAULT_REPOSITORY_URL; } } public String[] getRepositoryURLs() { if (m_urls != null) { // Return a copy because the array is mutable. return (String[]) m_urls.clone(); } return null; } public synchronized void setRepositoryURLs(String[] urls) { if (urls != null) { m_urls = urls; initialize(); } } /** * Get the number of bundles available in the repository. * @return the number of available bundles. **/ public synchronized int getBundleRecordCount() { if (!m_initialized) { initialize(); } return m_bundleList.size(); } /** * Get the specified bundle record from the repository. * @param i the bundle record index to retrieve. * @return the associated bundle record or <tt>null</tt>. **/ public synchronized BundleRecord getBundleRecord(int i) { if (!m_initialized) { initialize(); } if ((i < 0) || (i >= getBundleRecordCount())) { return null; } return (BundleRecord) m_bundleList.get(i); } /** * Get bundle record for the bundle with the specified name * and version from the repository. * @param name the bundle record name to retrieve. * @param version three-interger array of the version associated with * the name to retrieve. * @return the associated bundle record or <tt>null</tt>. **/ public synchronized BundleRecord getBundleRecord(String name, int[] version) { if (!m_initialized) { initialize(); } BundleRecord[] records = getBundleRecords(name); if (records.length > 0) { for (int i = 0; i < records.length; i++) { String targetName = (String) records[i].getAttribute(BundleRecord.BUNDLE_NAME); int[] targetVersion = Util.parseVersionString( (String) records[i].getAttribute(BundleRecord.BUNDLE_VERSION)); if ((targetName != null) && targetName.equalsIgnoreCase(name) && (Util.compareVersion(targetVersion, version) == 0)) { return records[i]; } } } return null; } /** * Get all versions of bundle records for the specified name * from the repository. * @param name the bundle record name to retrieve. * @return an array of all versions of bundle records having the * specified name or <tt>null</tt>. **/ public synchronized BundleRecord[] getBundleRecords(String name) { if (!m_initialized) { initialize(); } BundleRecord[] records = new BundleRecord[0]; for (int i = 0; i < m_bundleList.size(); i++) { String targetName = (String) getBundleRecord(i).getAttribute(BundleRecord.BUNDLE_NAME); if ((targetName != null) && targetName.equalsIgnoreCase(name)) { BundleRecord[] newRecords = new BundleRecord[records.length + 1]; System.arraycopy(records, 0, newRecords, 0, records.length); newRecords[records.length] = getBundleRecord(i); records = newRecords; } } return records; } public boolean deployBundle( PrintStream out, PrintStream err, String updateLocation, boolean isResolve, boolean isStart) { // List to hole bundles that need to be started. List startList = null; // The first thing to do is to see if the bundle to be // deployed is locally installed. If so, then we have to // check if an update is available for it. If no update // is available then we just return. NOTE: This is sort // of a hack that is necessary because the resolvePackages() // method doesn't do this sort of checking, so we have // to do it here first. Bundle localBundle = findLocalBundleByUpdate(updateLocation); if (localBundle != null) { if (!isUpdateAvailable(out, err, localBundle)) { out.println("No update available: " + Util.getBundleName(localBundle)); return false; } } // Find the appropriate bundle record in the repository, // then calculate the transitive closure of its dependencies. BundleRecord record = findBundleRecordByUpdate(updateLocation); if (record != null) { // This set will contain all bundles that must be // deployed as a result of deploying the target bundle; // use a list because this will keep everything in order. List deployList = new ArrayList(); // Add the target bundle to the set, since it will // ultimately be deployed as a result of this request. deployList.add(updateLocation); // If the resolve flag is set, then get its imports to // calculate the transitive closure of its dependencies. if (isResolve) { PackageDeclaration[] imports = (PackageDeclaration[]) record.getAttribute(BundleRecord.IMPORT_PACKAGE); try { resolvePackages(imports, deployList); } catch (ResolveException ex) { err.println("Resolve error: " + ex.getPackageDeclaration()); return false; } } // Now iterate through all bundles in the deploy list // in reverse order and deploy each; the order is not // so important, but by reversing them at least the // dependencies will be printed first and perhaps it // will avoid some ordering issues when we are starting // bundles. for (int i = deployList.size() - 1; i >= 0; i--) { String deployLocation = (String) deployList.get(i); // See if the bundle is locally installed, in which case // we will be performing an update. localBundle = findLocalBundleByUpdate(deployLocation); if (localBundle != null) { // Verify that the locally installed bundle has an // update available for it; if not, then ignore it. if (!isUpdateAvailable(out, err, localBundle)) { continue; } // Print out an "updating" message. if (!deployLocation.equals(updateLocation)) { out.print("Updating dependency: "); } else { out.print("Updating: "); } out.println(Util.getBundleName(localBundle)); // Actually perform the update. try { localBundle.update(); } catch (BundleException ex) { err.println("Update error: " + Util.getBundleName(localBundle)); ex.printStackTrace(err); return false; } } else { // Print out an "installing" message. if (!deployLocation.equals(updateLocation)) { out.print("Installing dependency: "); } else { out.print("Installing: "); } record = findBundleRecordByUpdate(deployLocation); out.println(record.getAttribute(BundleRecord.BUNDLE_NAME)); // Actually perform the install. try { Bundle bundle = m_context.installBundle(deployLocation); // If necessary, save the installed bundle to be // started later. if (isStart) { if (startList == null) { startList = new ArrayList(); } startList.add(bundle); } } catch (BundleException ex) { err.println("Install error: " + record.getAttribute(BundleRecord.BUNDLE_NAME)); ex.printStackTrace(err); return false; } } } // If necessary, start bundles after installing them all. if (isStart) { for (int i = 0; (startList != null) && (i < startList.size()); i++) { localBundle = (Bundle) startList.get(i); try { localBundle.start(); } catch (BundleException ex) { err.println("Update error: " + Util.getBundleName(localBundle)); ex.printStackTrace(); } } } return true; } return false; } public BundleRecord[] resolvePackages(PackageDeclaration[] pkgs) throws ResolveException { // Create a list that will contain the transitive closure of // all import dependencies; use a list because this will keep // everything in order. List deployList = new ArrayList(); resolvePackages(pkgs, deployList); // Convert list of update locations to an array of bundle // records and return it. BundleRecord[] records = new BundleRecord[deployList.size()]; for (int i = 0; i < deployList.size(); i++) { String updateLocation = (String) deployList.get(i); records[i] = findBundleRecordByUpdate(updateLocation); } return records; } public void resolvePackages( PackageDeclaration[] pkgs, List deployList) throws ResolveException { for (int pkgIdx = 0; (pkgs != null) && (pkgIdx < pkgs.length); pkgIdx++) { // If the package can be locally resolved, then // it can be completely ignored; otherwise, try // to find a resolving bundle. if (!isLocallyResolvable(pkgs[pkgIdx])) { // Select resolving bundle for current package. BundleRecord source = selectResolvingBundle(pkgs[pkgIdx]); // If there is no resolving bundle, then throw a // resolve exception. if (source == null) { throw new ResolveException(pkgs[pkgIdx]); } // Get the update location of the resolving bundle. String updateLocation = (String) source.getAttribute(BundleRecord.BUNDLE_UPDATELOCATION); // If the resolving bundle's update location is already // in the deploy list, then just ignore it; otherwise, // add it to the deploy list and resolve its packages. if (!deployList.contains(updateLocation)) { deployList.add(updateLocation); PackageDeclaration[] imports = (PackageDeclaration[]) source.getAttribute(BundleRecord.IMPORT_PACKAGE); resolvePackages(imports, deployList); } } } } /** * Returns a locally installed bundle that has an update location * manifest attribute that matches the specified update location * value. * @param updateLocation the update location attribute for which to search. * @return a bundle with a matching update location attribute or * <tt>null</tt> if one could not be found. **/ private Bundle findLocalBundleByUpdate(String updateLocation) { Bundle[] locals = m_context.getBundles(); for (int i = 0; i < locals.length; i++) { String localUpdateLocation = (String) locals[i].getHeaders().get(BundleRecord.BUNDLE_UPDATELOCATION); if ((localUpdateLocation != null) && localUpdateLocation.equals(updateLocation)) { return locals[i]; } } return null; } private boolean isUpdateAvailable( PrintStream out, PrintStream err, Bundle bundle) { // Get the bundle's update location. String updateLocation = (String) bundle.getHeaders().get(Constants.BUNDLE_UPDATELOCATION); // Get associated repository bundle recorded for the // local bundle and see if an update is necessary. BundleRecord record = findBundleRecordByUpdate(updateLocation); if (record == null) { err.println(Util.getBundleName(bundle) + " not in repository."); return false; } // Check bundle version againts bundle record version. int[] bundleVersion = Util.parseVersionString( (String) bundle.getHeaders().get(Constants.BUNDLE_VERSION)); int[] recordVersion = Util.parseVersionString( (String) record.getAttribute(BundleRecord.BUNDLE_VERSION)); if (Util.compareVersion(recordVersion, bundleVersion) > 0) { return true; } return false; } /** * Returns the bundle record corresponding to the specified update * location string; update location strings are assumed to be * unique. * @param updateLocation the update location of the bundle record * to retrieve. * @return the corresponding bundle record or <tt>null</tt>. **/ private synchronized BundleRecord findBundleRecordByUpdate(String updateLocation) { if (!m_initialized) { initialize(); } for (int i = 0; i < m_bundleList.size(); i++) { String location = (String) getBundleRecord(i).getAttribute(BundleRecord.BUNDLE_UPDATELOCATION); if ((location != null) && location.equalsIgnoreCase(updateLocation)) { return getBundleRecord(i); } } return null; } /** * Determines whether a package is resolvable at the local framework. * @param target the package declaration to check for availability. * @return <tt>true</tt> if the package is available locally, * <tt>false</tt> otherwise. **/ private synchronized boolean isLocallyResolvable(PackageDeclaration target) { // Get package admin service. ServiceReference ref = m_context.getServiceReference( "org.osgi.service.packageadmin.PackageAdmin"); if (ref == null) { return false; } PackageAdmin pa = (PackageAdmin) m_context.getService(ref); if (pa == null) { return false; } ExportedPackage[] exports = pa.getExportedPackages((Bundle)null); if (exports != null) { for (int i = 0; (exports != null) && (i < exports.length); i++) { PackageDeclaration source = new PackageDeclaration( exports[i].getName(), exports[i].getSpecificationVersion()); if (source.doesSatisfy(target)) { return true; } } } return false; } /** * Selects a single source bundle record for the target package from * the repository. The algorithm tries to select a source bundle record * if it is already installed locally in the framework; this approach * favors updating already installed bundles rather than installing * new ones. If no matching bundles are installed locally, then the * first bundle record providing the target package is returned. * @param targetPkg the target package for which to select a source * bundle record. * @return the selected bundle record or <tt>null</tt> if no sources * could be found. **/ private BundleRecord selectResolvingBundle(PackageDeclaration targetPkg) { BundleRecord[] sources = findResolvingBundles(targetPkg); if (sources == null) { return null; } // Try to select a source bundle record that is already // installed locally. for (int i = 0; i < sources.length; i++) { String updateLocation = (String) sources[i].getAttribute(BundleRecord.BUNDLE_UPDATELOCATION); if (updateLocation != null) { Bundle bundle = findLocalBundleByUpdate(updateLocation); if (bundle != null) { return sources[i]; } } } // If none of the sources are installed locally, then // just pick the first one. return sources[0]; } /** * Returns an array of bundle records that resolve the supplied * package declaration. * @param target the package declaration to resolve. * @return an array of bundle records that resolve the package * declaration or <tt>null</tt> if none are found. **/ private synchronized BundleRecord[] findResolvingBundles(PackageDeclaration targetPkg) { // Create a list for storing bundles that can resolve package. ArrayList resolveList = new ArrayList(); // Get the exporter list from the export package map for this package. ArrayList exporterList = (ArrayList) m_exportPackageMap.get(targetPkg.getName()); // Loop through each exporter and see if it satisfies the target. for (int i = 0; (exporterList != null) && (i < exporterList.size()); i++) { // Get the export info from the exporter list. Object[] exportInfo = (Object[]) exporterList.get(i); // Get the export package from the export info. PackageDeclaration exportPkg = (PackageDeclaration) exportInfo[EXPORT_PACKAGE_IDX]; // Get the export bundle from the export info. BundleRecord exportBundle = (BundleRecord) exportInfo[EXPORT_BUNDLE_IDX]; // See if the export package satisfies the target package. if (exportPkg.doesSatisfy(targetPkg)) { // Add it to the list of resolving bundles. resolveList.add(exportBundle); } } // If no resolving bundles were found, return null. if (resolveList.size() == 0) { return null; } // Otherwise, return an array containing resolving bundles. return (BundleRecord[]) resolveList.toArray(new BundleRecord[resolveList.size()]); } private void initialize() { m_initialized = true; m_bundleList.clear(); m_exportPackageMap.clear(); for (int urlIdx = 0; (m_urls != null) && (urlIdx < m_urls.length); urlIdx++) { parseRepositoryFile(m_hopCount, m_urls[urlIdx]); } } private String getUserAgentForBundle(Bundle bundle) { String uaName = bundle.getSymbolicName(); String uaVers = (String) bundle.getHeaders().get("Bundle-Version"); String uaComm = ""; if (0==bundle.getBundleId()) { // The system bundle uaComm = uaVers; uaName = m_context.getProperty(Constants.FRAMEWORK_VENDOR); uaVers = m_context.getProperty(Constants.FRAMEWORK_VERSION); } return uaName + (uaVers!=null && uaVers.length()>0 ? ("/" + uaVers) : "") + (uaComm!=null && uaComm.length()>0 ? (" (" +uaComm +")") : ""); } private void parseRepositoryFile(int hopCount, String urlStr) { InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; try { // Do it the manual way to have a chance to // set request properties as proxy auth (EW). URL url = new URL(urlStr); URLConnection conn = url.openConnection(); // Support for http proxy authentication String auth = System.getProperty("http.proxyAuth"); if ((auth != null) && (auth.length() > 0)) { if ("http".equals(url.getProtocol()) || "https".equals(url.getProtocol())) { String base64 = Util.base64Encode(auth); conn.setRequestProperty( "Proxy-Authorization", "Basic " + base64); } } // Identify us (via User-Agent) with bundlename and the // framework vendor name and version. conn.setRequestProperty("User-Agent", getUserAgentForBundle(m_context.getBundle()) +" " +getUserAgentForBundle(m_context.getBundle(0)) ); is = conn.getInputStream(); // Create the parser Kxml XmlCommonHandler handler = new XmlCommonHandler(); handler.addType("bundles", ArrayList.class); handler.addType("repository", HashMap.class); handler.addType("extern-repositories", ArrayList.class); handler.addType("bundle", MultivalueMap.class); handler.addType("import-package", HashMap.class); handler.addType("export-package", HashMap.class); handler.setDefaultType(String.class); br = new BufferedReader(new InputStreamReader(is)); KXmlSAXParser parser; parser = new KXmlSAXParser(br); try { parser.parseXML(handler); } catch (Exception ex) { ex.printStackTrace(); return; } List root = (List) handler.getRoot(); for (int bundleIdx = 0; bundleIdx < root.size(); bundleIdx++) { Object obj = root.get(bundleIdx); // The elements of the root will either be a HashMap for // the repository tag or a MultivalueMap for the bundle // tag, as indicated above when we parsed the file. // If HashMap, then read repository information. if (obj instanceof HashMap) { // Create a case-insensitive map. Map repoMap = new TreeMap(new Comparator() { public int compare(Object o1, Object o2) { return o1.toString().compareToIgnoreCase(o2.toString()); } }); repoMap.putAll((Map) obj); // Process external repositories if hop count is // greater than zero. if (hopCount > 0) { // Get the external repository list. List externList = (List) repoMap.get(EXTERN_REPOSITORY_TAG); for (int i = 0; (externList != null) && (i < externList.size()); i++) { parseRepositoryFile(hopCount - 1, (String) externList.get(i)); } } } // Else if mulitvalue map, then create a bundle record // for the associated bundle meta-data. else if (obj instanceof MultivalueMap) { // Create a case-insensitive map. Map bundleMap = new TreeMap(new Comparator() { public int compare(Object o1, Object o2) { return o1.toString().compareToIgnoreCase(o2.toString()); } }); bundleMap.putAll((Map) obj); // Convert any import package declarations // to PackageDeclaration objects. Object target = bundleMap.get(BundleRecord.IMPORT_PACKAGE); if (target != null) { // Overwrite the original package declarations. bundleMap.put( BundleRecord.IMPORT_PACKAGE, convertPackageDeclarations(target)); } // Convert any export package declarations // to PackageDeclaration objects. target = bundleMap.get(BundleRecord.EXPORT_PACKAGE); if (target != null) { // Overwrite the original package declarations. bundleMap.put( BundleRecord.EXPORT_PACKAGE, convertPackageDeclarations(target)); } // Create a bundle record using the map. BundleRecord record = new BundleRecord(bundleMap); // Try to put all exported packages from this bundle // into the export package map to simplify access. try { PackageDeclaration[] exportPkgs = (PackageDeclaration[]) record.getAttribute(BundleRecord.EXPORT_PACKAGE); for (int exportIdx = 0; (exportPkgs != null) && (exportIdx < exportPkgs.length); exportIdx++) { // Check to see if this package is already in the // export package map. ArrayList exporterList = (ArrayList) m_exportPackageMap.get(exportPkgs[exportIdx].getName()); // If the package is not in the map, create an // array list for it. if (exporterList == null) { exporterList = new ArrayList(); } // Add the export info to the array list. Object[] exportInfo = new Object[2]; exportInfo[EXPORT_PACKAGE_IDX] = exportPkgs[exportIdx]; exportInfo[EXPORT_BUNDLE_IDX] = record; exporterList.add(exportInfo); // Put the array list containing the export info // into the export map, which will make it easy // to search for which bundles export what. Note, // if the exporterList already was in the map, this // will just overwrite it with the same value. m_exportPackageMap.put( exportPkgs[exportIdx].getName(), exporterList); } // TODO: Filter duplicates. m_bundleList.add(record); } catch (IllegalArgumentException ex) { // Ignore. } } } } catch (MalformedURLException ex) { System.err.println("Error: " + ex); } catch (IOException ex) { System.err.println("Error: " + ex); } finally { try { if (is != null) is.close(); } catch (IOException ex) { // Not much we can do. } } Collections.sort(m_bundleList, new Comparator() { public int compare(Object o1, Object o2) { BundleRecord r1 = (BundleRecord) o1; BundleRecord r2 = (BundleRecord) o2; String name1 = (String) r1.getAttribute(BundleRecord.BUNDLE_NAME); String name2 = (String) r2.getAttribute(BundleRecord.BUNDLE_NAME); return name1.compareToIgnoreCase(name2); } }); } private PackageDeclaration[] convertPackageDeclarations(Object target) { PackageDeclaration[] decls = null; // If there is only one package it will be a // Map as specified above when parsing. if (target instanceof Map) { // Put package declaration into an array. decls = new PackageDeclaration[1]; decls[0] = convertPackageMap((Map) target); } // If there is more than one package, then the // MultivalueMap will convert them to a list of maps. else if (target instanceof List) { List pkgList = (List) target; decls = new PackageDeclaration[pkgList.size()]; for (int pkgIdx = 0; pkgIdx < decls.length; pkgIdx++) { decls[pkgIdx] = convertPackageMap( (Map) pkgList.get(pkgIdx)); } } return decls; } private PackageDeclaration convertPackageMap(Map map) { // Create a case-insensitive map. Map pkgMap = new TreeMap(new Comparator() { public int compare(Object o1, Object o2) { return o1.toString().compareToIgnoreCase(o2.toString()); } }); pkgMap.putAll((Map) map); // Get package name and version. String name = (String) pkgMap.get(PackageDeclaration.PACKAGE_ATTR); String version = (String) pkgMap.get(PackageDeclaration.VERSION_ATTR); if (name != null) { return new PackageDeclaration(name, version); } return null; } }
osgi/bundles/bundlerepository/src/org/ungoverned/osgi/bundle/bundlerepository/BundleRepositoryServiceImpl.java
/* * Oscar Bundle Repository * Copyright (c) 2004, Richard S. Hall * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of the ungoverned.org nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Contact: Richard S. Hall ([email protected]) * Contributor(s): * **/ package org.ungoverned.osgi.bundle.bundlerepository; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.*; import kxml.sax.KXmlSAXParser; import org.osgi.framework.*; import org.osgi.service.packageadmin.ExportedPackage; import org.osgi.service.packageadmin.PackageAdmin; import org.ungoverned.osgi.service.bundlerepository.*; import fr.imag.adele.metadataparser.MultivalueMap; import fr.imag.adele.metadataparser.XmlCommonHandler; public class BundleRepositoryServiceImpl implements BundleRepositoryService { private BundleContext m_context = null; private boolean m_initialized = false; private String[] m_urls = null; private List m_bundleList = new ArrayList(); private Map m_exportPackageMap = new HashMap(); private static final int EXPORT_PACKAGE_IDX = 0; private static final int EXPORT_BUNDLE_IDX = 1; private int m_hopCount = 1; private static final String[] DEFAULT_REPOSITORY_URL = { "http://oscar-osgi.sf.net/repository.xml" }; public static final String REPOSITORY_URL_PROP = "oscar.repository.url"; public static final String EXTERN_REPOSITORY_TAG = "extern-repositories"; public BundleRepositoryServiceImpl(BundleContext context) { m_context = context; String urlStr = context.getProperty(REPOSITORY_URL_PROP); if (urlStr != null) { StringTokenizer st = new StringTokenizer(urlStr); if (st.countTokens() > 0) { m_urls = new String[st.countTokens()]; for (int i = 0; i < m_urls.length; i++) { m_urls[i] = st.nextToken(); } } } // Use the default URL if none were specified. if (m_urls == null) { m_urls = DEFAULT_REPOSITORY_URL; } } public String[] getRepositoryURLs() { if (m_urls != null) { // Return a copy because the array is mutable. return (String[]) m_urls.clone(); } return null; } public synchronized void setRepositoryURLs(String[] urls) { if (urls != null) { m_urls = urls; initialize(); } } /** * Get the number of bundles available in the repository. * @return the number of available bundles. **/ public synchronized int getBundleRecordCount() { if (!m_initialized) { initialize(); } return m_bundleList.size(); } /** * Get the specified bundle record from the repository. * @param i the bundle record index to retrieve. * @return the associated bundle record or <tt>null</tt>. **/ public synchronized BundleRecord getBundleRecord(int i) { if (!m_initialized) { initialize(); } if ((i < 0) || (i >= getBundleRecordCount())) { return null; } return (BundleRecord) m_bundleList.get(i); } /** * Get bundle record for the bundle with the specified name * and version from the repository. * @param name the bundle record name to retrieve. * @param version three-interger array of the version associated with * the name to retrieve. * @return the associated bundle record or <tt>null</tt>. **/ public synchronized BundleRecord getBundleRecord(String name, int[] version) { if (!m_initialized) { initialize(); } BundleRecord[] records = getBundleRecords(name); if (records.length > 0) { for (int i = 0; i < records.length; i++) { String targetName = (String) records[i].getAttribute(BundleRecord.BUNDLE_NAME); int[] targetVersion = Util.parseVersionString( (String) records[i].getAttribute(BundleRecord.BUNDLE_VERSION)); if ((targetName != null) && targetName.equalsIgnoreCase(name) && (Util.compareVersion(targetVersion, version) == 0)) { return records[i]; } } } return null; } /** * Get all versions of bundle records for the specified name * from the repository. * @param name the bundle record name to retrieve. * @return an array of all versions of bundle records having the * specified name or <tt>null</tt>. **/ public synchronized BundleRecord[] getBundleRecords(String name) { if (!m_initialized) { initialize(); } BundleRecord[] records = new BundleRecord[0]; for (int i = 0; i < m_bundleList.size(); i++) { String targetName = (String) getBundleRecord(i).getAttribute(BundleRecord.BUNDLE_NAME); if ((targetName != null) && targetName.equalsIgnoreCase(name)) { BundleRecord[] newRecords = new BundleRecord[records.length + 1]; System.arraycopy(records, 0, newRecords, 0, records.length); newRecords[records.length] = getBundleRecord(i); records = newRecords; } } return records; } public boolean deployBundle( PrintStream out, PrintStream err, String updateLocation, boolean isResolve, boolean isStart) { // List to hole bundles that need to be started. List startList = null; // The first thing to do is to see if the bundle to be // deployed is locally installed. If so, then we have to // check if an update is available for it. If no update // is available then we just return. NOTE: This is sort // of a hack that is necessary because the resolvePackages() // method doesn't do this sort of checking, so we have // to do it here first. Bundle localBundle = findLocalBundleByUpdate(updateLocation); if (localBundle != null) { if (!isUpdateAvailable(out, err, localBundle)) { out.println("No update available: " + Util.getBundleName(localBundle)); return false; } } // Find the appropriate bundle record in the repository, // then calculate the transitive closure of its dependencies. BundleRecord record = findBundleRecordByUpdate(updateLocation); if (record != null) { // This set will contain all bundles that must be // deployed as a result of deploying the target bundle; // use a list because this will keep everything in order. List deployList = new ArrayList(); // Add the target bundle to the set, since it will // ultimately be deployed as a result of this request. deployList.add(updateLocation); // If the resolve flag is set, then get its imports to // calculate the transitive closure of its dependencies. if (isResolve) { PackageDeclaration[] imports = (PackageDeclaration[]) record.getAttribute(BundleRecord.IMPORT_PACKAGE); try { resolvePackages(imports, deployList); } catch (ResolveException ex) { err.println("Resolve error: " + ex.getPackageDeclaration()); return false; } } // Now iterate through all bundles in the deploy list // in reverse order and deploy each; the order is not // so important, but by reversing them at least the // dependencies will be printed first and perhaps it // will avoid some ordering issues when we are starting // bundles. for (int i = deployList.size() - 1; i >= 0; i--) { String deployLocation = (String) deployList.get(i); // See if the bundle is locally installed, in which case // we will be performing an update. localBundle = findLocalBundleByUpdate(deployLocation); if (localBundle != null) { // Verify that the locally installed bundle has an // update available for it; if not, then ignore it. if (!isUpdateAvailable(out, err, localBundle)) { continue; } // Print out an "updating" message. if (!deployLocation.equals(updateLocation)) { out.print("Updating dependency: "); } else { out.print("Updating: "); } out.println(Util.getBundleName(localBundle)); // Actually perform the update. try { localBundle.update(); } catch (BundleException ex) { err.println("Update error: " + Util.getBundleName(localBundle)); ex.printStackTrace(err); return false; } } else { // Print out an "installing" message. if (!deployLocation.equals(updateLocation)) { out.print("Installing dependency: "); } else { out.print("Installing: "); } record = findBundleRecordByUpdate(deployLocation); out.println(record.getAttribute(BundleRecord.BUNDLE_NAME)); // Actually perform the install. try { Bundle bundle = m_context.installBundle(deployLocation); // If necessary, save the installed bundle to be // started later. if (isStart) { if (startList == null) { startList = new ArrayList(); } startList.add(bundle); } } catch (BundleException ex) { err.println("Install error: " + record.getAttribute(BundleRecord.BUNDLE_NAME)); ex.printStackTrace(err); return false; } } } // If necessary, start bundles after installing them all. if (isStart) { for (int i = 0; (startList != null) && (i < startList.size()); i++) { localBundle = (Bundle) startList.get(i); try { localBundle.start(); } catch (BundleException ex) { err.println("Update error: " + Util.getBundleName(localBundle)); ex.printStackTrace(); } } } return true; } return false; } public BundleRecord[] resolvePackages(PackageDeclaration[] pkgs) throws ResolveException { // Create a list that will contain the transitive closure of // all import dependencies; use a list because this will keep // everything in order. List deployList = new ArrayList(); resolvePackages(pkgs, deployList); // Convert list of update locations to an array of bundle // records and return it. BundleRecord[] records = new BundleRecord[deployList.size()]; for (int i = 0; i < deployList.size(); i++) { String updateLocation = (String) deployList.get(i); records[i] = findBundleRecordByUpdate(updateLocation); } return records; } public void resolvePackages( PackageDeclaration[] pkgs, List deployList) throws ResolveException { for (int pkgIdx = 0; (pkgs != null) && (pkgIdx < pkgs.length); pkgIdx++) { // If the package can be locally resolved, then // it can be completely ignored; otherwise, try // to find a resolving bundle. if (!isLocallyResolvable(pkgs[pkgIdx])) { // Select resolving bundle for current package. BundleRecord source = selectResolvingBundle(pkgs[pkgIdx]); // If there is no resolving bundle, then throw a // resolve exception. if (source == null) { throw new ResolveException(pkgs[pkgIdx]); } // Get the update location of the resolving bundle. String updateLocation = (String) source.getAttribute(BundleRecord.BUNDLE_UPDATELOCATION); // If the resolving bundle's update location is already // in the deploy list, then just ignore it; otherwise, // add it to the deploy list and resolve its packages. if (!deployList.contains(updateLocation)) { deployList.add(updateLocation); PackageDeclaration[] imports = (PackageDeclaration[]) source.getAttribute(BundleRecord.IMPORT_PACKAGE); resolvePackages(imports, deployList); } } } } /** * Returns a locally installed bundle that has an update location * manifest attribute that matches the specified update location * value. * @param updateLocation the update location attribute for which to search. * @return a bundle with a matching update location attribute or * <tt>null</tt> if one could not be found. **/ private Bundle findLocalBundleByUpdate(String updateLocation) { Bundle[] locals = m_context.getBundles(); for (int i = 0; i < locals.length; i++) { String localUpdateLocation = (String) locals[i].getHeaders().get(BundleRecord.BUNDLE_UPDATELOCATION); if ((localUpdateLocation != null) && localUpdateLocation.equals(updateLocation)) { return locals[i]; } } return null; } private boolean isUpdateAvailable( PrintStream out, PrintStream err, Bundle bundle) { // Get the bundle's update location. String updateLocation = (String) bundle.getHeaders().get(Constants.BUNDLE_UPDATELOCATION); // Get associated repository bundle recorded for the // local bundle and see if an update is necessary. BundleRecord record = findBundleRecordByUpdate(updateLocation); if (record == null) { err.println(Util.getBundleName(bundle) + " not in repository."); return false; } // Check bundle version againts bundle record version. int[] bundleVersion = Util.parseVersionString( (String) bundle.getHeaders().get(Constants.BUNDLE_VERSION)); int[] recordVersion = Util.parseVersionString( (String) record.getAttribute(BundleRecord.BUNDLE_VERSION)); if (Util.compareVersion(recordVersion, bundleVersion) > 0) { return true; } return false; } /** * Returns the bundle record corresponding to the specified update * location string; update location strings are assumed to be * unique. * @param updateLocation the update location of the bundle record * to retrieve. * @return the corresponding bundle record or <tt>null</tt>. **/ private synchronized BundleRecord findBundleRecordByUpdate(String updateLocation) { if (!m_initialized) { initialize(); } for (int i = 0; i < m_bundleList.size(); i++) { String location = (String) getBundleRecord(i).getAttribute(BundleRecord.BUNDLE_UPDATELOCATION); if ((location != null) && location.equalsIgnoreCase(updateLocation)) { return getBundleRecord(i); } } return null; } /** * Determines whether a package is resolvable at the local framework. * @param target the package declaration to check for availability. * @return <tt>true</tt> if the package is available locally, * <tt>false</tt> otherwise. **/ private synchronized boolean isLocallyResolvable(PackageDeclaration target) { // Get package admin service. ServiceReference ref = m_context.getServiceReference( "org.osgi.service.packageadmin.PackageAdmin"); if (ref == null) { return false; } PackageAdmin pa = (PackageAdmin) m_context.getService(ref); if (pa == null) { return false; } ExportedPackage[] exports = pa.getExportedPackages((Bundle)null); if (exports != null) { for (int i = 0; (exports != null) && (i < exports.length); i++) { PackageDeclaration source = new PackageDeclaration( exports[i].getName(), exports[i].getSpecificationVersion()); if (source.doesSatisfy(target)) { return true; } } } return false; } /** * Selects a single source bundle record for the target package from * the repository. The algorithm tries to select a source bundle record * if it is already installed locally in the framework; this approach * favors updating already installed bundles rather than installing * new ones. If no matching bundles are installed locally, then the * first bundle record providing the target package is returned. * @param targetPkg the target package for which to select a source * bundle record. * @return the selected bundle record or <tt>null</tt> if no sources * could be found. **/ private BundleRecord selectResolvingBundle(PackageDeclaration targetPkg) { BundleRecord[] sources = findResolvingBundles(targetPkg); if (sources == null) { return null; } // Try to select a source bundle record that is already // installed locally. for (int i = 0; i < sources.length; i++) { String updateLocation = (String) sources[i].getAttribute(BundleRecord.BUNDLE_UPDATELOCATION); if (updateLocation != null) { Bundle bundle = findLocalBundleByUpdate(updateLocation); if (bundle != null) { return sources[i]; } } } // If none of the sources are installed locally, then // just pick the first one. return sources[0]; } /** * Returns an array of bundle records that resolve the supplied * package declaration. * @param target the package declaration to resolve. * @return an array of bundle records that resolve the package * declaration or <tt>null</tt> if none are found. **/ private synchronized BundleRecord[] findResolvingBundles(PackageDeclaration targetPkg) { // Create a list for storing bundles that can resolve package. ArrayList resolveList = new ArrayList(); // Get the exporter list from the export package map for this package. ArrayList exporterList = (ArrayList) m_exportPackageMap.get(targetPkg.getName()); // Loop through each exporter and see if it satisfies the target. for (int i = 0; (exporterList != null) && (i < exporterList.size()); i++) { // Get the export info from the exporter list. Object[] exportInfo = (Object[]) exporterList.get(i); // Get the export package from the export info. PackageDeclaration exportPkg = (PackageDeclaration) exportInfo[EXPORT_PACKAGE_IDX]; // Get the export bundle from the export info. BundleRecord exportBundle = (BundleRecord) exportInfo[EXPORT_BUNDLE_IDX]; // See if the export package satisfies the target package. if (exportPkg.doesSatisfy(targetPkg)) { // Add it to the list of resolving bundles. resolveList.add(exportBundle); } } // If no resolving bundles were found, return null. if (resolveList.size() == 0) { return null; } // Otherwise, return an array containing resolving bundles. return (BundleRecord[]) resolveList.toArray(new BundleRecord[resolveList.size()]); } private void initialize() { m_initialized = true; m_bundleList.clear(); m_exportPackageMap.clear(); for (int urlIdx = 0; (m_urls != null) && (urlIdx < m_urls.length); urlIdx++) { parseRepositoryFile(m_hopCount, m_urls[urlIdx]); } } private String getUserAgentForBundle(Bundle bundle) { String uaName = bundle.getSymbolicName(); String uaVers = (String) bundle.getHeaders().get("Bundle-Version"); if (0==bundle.getBundleId()) { // The system bundle uaName = m_context.getProperty(Constants.FRAMEWORK_VENDOR); uaVers = m_context.getProperty(Constants.FRAMEWORK_VERSION) + "/" +uaVers; } return uaName + (uaVers!=null && uaVers.length()>0 ? ("/" + uaVers) : ""); } private void parseRepositoryFile(int hopCount, String urlStr) { InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; try { // Do it the manual way to have a chance to // set request properties as proxy auth (EW). URL url = new URL(urlStr); URLConnection conn = url.openConnection(); // Support for http proxy authentication String auth = System.getProperty("http.proxyAuth"); if ((auth != null) && (auth.length() > 0)) { if ("http".equals(url.getProtocol()) || "https".equals(url.getProtocol())) { String base64 = Util.base64Encode(auth); conn.setRequestProperty( "Proxy-Authorization", "Basic " + base64); } } // Identify us (via User-Agent) with bundlename and the // framework vendor name and version. conn.setRequestProperty("User-Agent", getUserAgentForBundle(m_context.getBundle()) +" " +getUserAgentForBundle(m_context.getBundle(0)) ); is = conn.getInputStream(); // Create the parser Kxml XmlCommonHandler handler = new XmlCommonHandler(); handler.addType("bundles", ArrayList.class); handler.addType("repository", HashMap.class); handler.addType("extern-repositories", ArrayList.class); handler.addType("bundle", MultivalueMap.class); handler.addType("import-package", HashMap.class); handler.addType("export-package", HashMap.class); handler.setDefaultType(String.class); br = new BufferedReader(new InputStreamReader(is)); KXmlSAXParser parser; parser = new KXmlSAXParser(br); try { parser.parseXML(handler); } catch (Exception ex) { ex.printStackTrace(); return; } List root = (List) handler.getRoot(); for (int bundleIdx = 0; bundleIdx < root.size(); bundleIdx++) { Object obj = root.get(bundleIdx); // The elements of the root will either be a HashMap for // the repository tag or a MultivalueMap for the bundle // tag, as indicated above when we parsed the file. // If HashMap, then read repository information. if (obj instanceof HashMap) { // Create a case-insensitive map. Map repoMap = new TreeMap(new Comparator() { public int compare(Object o1, Object o2) { return o1.toString().compareToIgnoreCase(o2.toString()); } }); repoMap.putAll((Map) obj); // Process external repositories if hop count is // greater than zero. if (hopCount > 0) { // Get the external repository list. List externList = (List) repoMap.get(EXTERN_REPOSITORY_TAG); for (int i = 0; (externList != null) && (i < externList.size()); i++) { parseRepositoryFile(hopCount - 1, (String) externList.get(i)); } } } // Else if mulitvalue map, then create a bundle record // for the associated bundle meta-data. else if (obj instanceof MultivalueMap) { // Create a case-insensitive map. Map bundleMap = new TreeMap(new Comparator() { public int compare(Object o1, Object o2) { return o1.toString().compareToIgnoreCase(o2.toString()); } }); bundleMap.putAll((Map) obj); // Convert any import package declarations // to PackageDeclaration objects. Object target = bundleMap.get(BundleRecord.IMPORT_PACKAGE); if (target != null) { // Overwrite the original package declarations. bundleMap.put( BundleRecord.IMPORT_PACKAGE, convertPackageDeclarations(target)); } // Convert any export package declarations // to PackageDeclaration objects. target = bundleMap.get(BundleRecord.EXPORT_PACKAGE); if (target != null) { // Overwrite the original package declarations. bundleMap.put( BundleRecord.EXPORT_PACKAGE, convertPackageDeclarations(target)); } // Create a bundle record using the map. BundleRecord record = new BundleRecord(bundleMap); // Try to put all exported packages from this bundle // into the export package map to simplify access. try { PackageDeclaration[] exportPkgs = (PackageDeclaration[]) record.getAttribute(BundleRecord.EXPORT_PACKAGE); for (int exportIdx = 0; (exportPkgs != null) && (exportIdx < exportPkgs.length); exportIdx++) { // Check to see if this package is already in the // export package map. ArrayList exporterList = (ArrayList) m_exportPackageMap.get(exportPkgs[exportIdx].getName()); // If the package is not in the map, create an // array list for it. if (exporterList == null) { exporterList = new ArrayList(); } // Add the export info to the array list. Object[] exportInfo = new Object[2]; exportInfo[EXPORT_PACKAGE_IDX] = exportPkgs[exportIdx]; exportInfo[EXPORT_BUNDLE_IDX] = record; exporterList.add(exportInfo); // Put the array list containing the export info // into the export map, which will make it easy // to search for which bundles export what. Note, // if the exporterList already was in the map, this // will just overwrite it with the same value. m_exportPackageMap.put( exportPkgs[exportIdx].getName(), exporterList); } // TODO: Filter duplicates. m_bundleList.add(record); } catch (IllegalArgumentException ex) { // Ignore. } } } } catch (MalformedURLException ex) { System.err.println("Error: " + ex); } catch (IOException ex) { System.err.println("Error: " + ex); } finally { try { if (is != null) is.close(); } catch (IOException ex) { // Not much we can do. } } Collections.sort(m_bundleList, new Comparator() { public int compare(Object o1, Object o2) { BundleRecord r1 = (BundleRecord) o1; BundleRecord r2 = (BundleRecord) o2; String name1 = (String) r1.getAttribute(BundleRecord.BUNDLE_NAME); String name2 = (String) r2.getAttribute(BundleRecord.BUNDLE_NAME); return name1.compareToIgnoreCase(name2); } }); } private PackageDeclaration[] convertPackageDeclarations(Object target) { PackageDeclaration[] decls = null; // If there is only one package it will be a // Map as specified above when parsing. if (target instanceof Map) { // Put package declaration into an array. decls = new PackageDeclaration[1]; decls[0] = convertPackageMap((Map) target); } // If there is more than one package, then the // MultivalueMap will convert them to a list of maps. else if (target instanceof List) { List pkgList = (List) target; decls = new PackageDeclaration[pkgList.size()]; for (int pkgIdx = 0; pkgIdx < decls.length; pkgIdx++) { decls[pkgIdx] = convertPackageMap( (Map) pkgList.get(pkgIdx)); } } return decls; } private PackageDeclaration convertPackageMap(Map map) { // Create a case-insensitive map. Map pkgMap = new TreeMap(new Comparator() { public int compare(Object o1, Object o2) { return o1.toString().compareToIgnoreCase(o2.toString()); } }); pkgMap.putAll((Map) map); // Get package name and version. String name = (String) pkgMap.get(PackageDeclaration.PACKAGE_ATTR); String version = (String) pkgMap.get(PackageDeclaration.VERSION_ATTR); if (name != null) { return new PackageDeclaration(name, version); } return null; } }
More User-Agent name improvements.
osgi/bundles/bundlerepository/src/org/ungoverned/osgi/bundle/bundlerepository/BundleRepositoryServiceImpl.java
More User-Agent name improvements.
<ide><path>sgi/bundles/bundlerepository/src/org/ungoverned/osgi/bundle/bundlerepository/BundleRepositoryServiceImpl.java <ide> { <ide> String uaName = bundle.getSymbolicName(); <ide> String uaVers = (String) bundle.getHeaders().get("Bundle-Version"); <add> String uaComm = ""; <ide> <ide> if (0==bundle.getBundleId()) { // The system bundle <add> uaComm = uaVers; <ide> uaName = m_context.getProperty(Constants.FRAMEWORK_VENDOR); <del> uaVers = m_context.getProperty(Constants.FRAMEWORK_VERSION) <del> + "/" +uaVers; <add> uaVers = m_context.getProperty(Constants.FRAMEWORK_VERSION); <ide> } <ide> return uaName <del> + (uaVers!=null && uaVers.length()>0 ? ("/" + uaVers) : ""); <add> + (uaVers!=null && uaVers.length()>0 ? ("/" + uaVers) : "") <add> + (uaComm!=null && uaComm.length()>0 ? (" (" +uaComm +")") : ""); <ide> } <ide> <ide> private void parseRepositoryFile(int hopCount, String urlStr)
Java
agpl-3.0
2b927973a22bdfe4c70c30a46563f7795fcaec92
0
o2oa/o2oa,o2oa/o2oa,o2oa/o2oa,o2oa/o2oa,o2oa/o2oa
package com.x.base.core.project.script; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.regex.Matcher; import javax.script.Compilable; import javax.script.CompiledScript; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import javax.script.SimpleScriptContext; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.x.base.core.entity.JpaObject; import com.x.base.core.project.config.Config; import com.x.base.core.project.tools.StringTools; import jdk.nashorn.api.scripting.ScriptObjectMirror; public class ScriptFactory { private ScriptFactory() { } public static final ScriptEngine scriptEngine = (new ScriptEngineManager()) .getEngineByName(Config.SCRIPTING_ENGINE_NAME); private static CompiledScript COMPILEDSCRIPT_INITIALSERVICESCRIPTTEXT; private static CompiledScript COMPILEDSCRIPT_INITIALSCRIPTTEXT; public static final String BINDING_NAME_RESOURCES = "resources"; public static final String BINDING_NAME_EFFECTIVEPERSON = "effectivePerson"; public static final String BINDING_NAME_WORKCONTEXT = "workContext"; public static final String BINDING_NAME_GSON = "gson"; public static final String BINDING_NAME_DATA = "data"; public static final String BINDING_NAME_ORGANIZATION = "organization"; public static final String BINDING_NAME_WEBSERVICESCLIENT = "webservicesClient"; public static final String BINDING_NAME_DICTIONARY = "dictionary"; public static final String BINDING_NAME_ROUTES = "routes"; public static final String BINDING_NAME_ROUTE = "routes"; public static final String BINDING_NAME_APPLICATIONS = "applications"; public static final String BINDING_NAME_ASSIGNDATA = "assignData"; public static final String BINDING_NAME_IDENTITY = "identity"; public static final String BINDING_NAME_PARAMETERS = "parameters"; public static final String BINDING_NAME_JAXRSRESPONSE = "jaxrsResponse"; public static final String BINDING_NAME_JAXWSRESPONSE = "jaxwsResponse"; public static final String BINDING_NAME_JAXRSBODY = "jaxrsBody"; public static final String BINDING_NAME_JAXRSHEAD = "jaxrsHead"; public static final String BINDING_NAME_SERVICEVALUE = "serviceValue"; public static final String BINDING_NAME_TASK = "task"; public static final String BINDING_NAME_EXPIRE = "expire"; public static final String BINDING_NAME_SERIAL = "serial"; public static final String BINDING_NAME_PROCESS = "process"; public static ScriptEngine newScriptEngine() { return (new ScriptEngineManager()).getEngineByName(Config.SCRIPTING_ENGINE_NAME); } public static CompiledScript initialServiceScriptText() throws Exception { if (COMPILEDSCRIPT_INITIALSERVICESCRIPTTEXT == null) { synchronized (ScriptFactory.class) { if (COMPILEDSCRIPT_INITIALSERVICESCRIPTTEXT == null) { String text = Config.initialServiceScriptText(); COMPILEDSCRIPT_INITIALSERVICESCRIPTTEXT = ((Compilable) scriptEngine).compile(text); } } } return COMPILEDSCRIPT_INITIALSERVICESCRIPTTEXT; } public static CompiledScript compile(String text) throws Exception { return ((Compilable) scriptEngine).compile(text); } public static CompiledScript initialScriptText() throws Exception { if (COMPILEDSCRIPT_INITIALSCRIPTTEXT == null) { synchronized (ScriptFactory.class) { if (COMPILEDSCRIPT_INITIALSCRIPTTEXT == null) { String text = Config.initialScriptText(); COMPILEDSCRIPT_INITIALSCRIPTTEXT = ((Compilable) scriptEngine).compile(text); } } } return COMPILEDSCRIPT_INITIALSCRIPTTEXT; } public static String functionalization(String text) { StringBuffer sb = new StringBuffer(); sb.append("(function(){").append(System.lineSeparator()); sb.append(Objects.toString(text, "")).append(System.lineSeparator()); sb.append("})();"); return sb.toString(); } public static List<String> asStringList(Object o) throws Exception { return readAsStringList(o); } public static String asString(Object o) throws Exception { return Objects.toString(o); } public static Boolean asBoolean(Object o) throws Exception { if (null == o) { return false; } if (o instanceof Number) { return ((Number) o).intValue() != 0; } return BooleanUtils.toBooleanObject(Objects.toString(o, "false")); } public static List<String> asDistinguishedName(Object o) throws Exception { List<String> list = new ArrayList<>(); if (null != o) { if (o instanceof CharSequence) { list.add(Objects.toString(o)); } else if (o instanceof Iterable) { for (Object obj : (Iterable<?>) o) { if (null != obj) { if (obj instanceof CharSequence) { list.add(Objects.toString(obj)); } else { Object d = PropertyUtils.getProperty(obj, JpaObject.DISTINGUISHEDNAME); if (null != d) { list.add(Objects.toString(d)); } } } } } else if (o instanceof ScriptObjectMirror) { ScriptObjectMirror som = (ScriptObjectMirror) o; if (som.isArray()) { Object[] objs = (som.to(Object[].class)); for (Object obj : objs) { if (null != obj) { if (obj instanceof CharSequence) { list.add(Objects.toString(obj)); } else { Object d = PropertyUtils.getProperty(obj, JpaObject.DISTINGUISHEDNAME); if (null != d) { list.add(Objects.toString(d)); } } } } } else { Object d = PropertyUtils.getProperty(o, JpaObject.DISTINGUISHEDNAME); if (null != d) { list.add(Objects.toString(d)); } } } } return list; } private static List<String> readAsStringList(Object obj) throws Exception { List<String> list = new ArrayList<>(); for (Object o : iterator(obj)) { list.add(Objects.toString(o)); } return list; } private static List<Object> iterator(Object obj) throws Exception { List<Object> results = new ArrayList<>(); iterator(obj, results); return results; } private static void iterator(Object obj, List<Object> results) throws Exception { if (null == obj) { return; } List<Object> list = new ArrayList<>(); if (obj.getClass().isArray()) { for (Object o : (Object[]) obj) { list.add(o); } } else if (obj instanceof Collection) { for (Object o : (Collection<?>) obj) { list.add(o); } } else if (obj instanceof ScriptObjectMirror) { ScriptObjectMirror som = (ScriptObjectMirror) obj; if (som.isArray()) { Object[] os = (som.to(Object[].class)); for (Object o : os) { list.add(o); } } else { results.add(som); } } else { results.add(obj); } for (Object o : list) { iterator(o, results); } } public static List<String> asDistinguishedNameList(Object o) throws Exception { List<String> list = new ArrayList<>(); if (null != o) { if (o instanceof CharSequence) { list.add(Objects.toString(o, "")); } else if (o instanceof JsonObject) { JsonObject jsonObject = (JsonObject) o; if (jsonObject.has(JpaObject.DISTINGUISHEDNAME)) { list.add(jsonObject.get(JpaObject.DISTINGUISHEDNAME).getAsString()); } } else if (o instanceof JsonArray) { for (JsonElement jsonElement : (JsonArray) o) { if (jsonElement.isJsonObject()) { JsonObject jsonObject = jsonElement.getAsJsonObject(); if (jsonObject.has(JpaObject.DISTINGUISHEDNAME)) { list.add(jsonObject.get(JpaObject.DISTINGUISHEDNAME).getAsString()); } } } } else if (o instanceof Iterable) { for (Object obj : (Iterable<?>) o) { if (null != obj) { if (obj instanceof CharSequence) { list.add(Objects.toString(obj, "")); } else { Object d = PropertyUtils.getProperty(obj, JpaObject.DISTINGUISHEDNAME); if (null != d) { list.add(Objects.toString(d, "")); } } } } } else if (o instanceof ScriptObjectMirror) { ScriptObjectMirror som = (ScriptObjectMirror) o; if (som.isArray()) { Object[] objs = (som.to(Object[].class)); for (Object obj : objs) { if (null != obj) { if (obj instanceof CharSequence) { list.add(Objects.toString(obj, "")); } else { Object d = PropertyUtils.getProperty(obj, JpaObject.DISTINGUISHEDNAME); if (null != d) { list.add(Objects.toString(d, "")); } } } } } else { Object d = PropertyUtils.getProperty(o, JpaObject.DISTINGUISHEDNAME); if (null != d) { list.add(Objects.toString(d, "")); } } } } return list; } }
o2server/x_base_core_project/src/main/java/com/x/base/core/project/script/ScriptFactory.java
package com.x.base.core.project.script; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.regex.Matcher; import javax.script.Compilable; import javax.script.CompiledScript; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import javax.script.SimpleScriptContext; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.x.base.core.entity.JpaObject; import com.x.base.core.project.config.Config; import com.x.base.core.project.tools.StringTools; import jdk.nashorn.api.scripting.ScriptObjectMirror; public class ScriptFactory { private ScriptFactory() { } public static final ScriptEngine scriptEngine = (new ScriptEngineManager()) .getEngineByName(Config.SCRIPTING_ENGINE_NAME); private static CompiledScript COMPILEDSCRIPT_INITIALSERVICESCRIPTTEXT; private static CompiledScript COMPILEDSCRIPT_INITIALSCRIPTTEXT; public static final String BINDING_NAME_RESOURCES = "resources"; public static final String BINDING_NAME_EFFECTIVEPERSON = "effectivePerson"; public static final String BINDING_NAME_WORKCONTEXT = "workContext"; public static final String BINDING_NAME_GSON = "gson"; public static final String BINDING_NAME_DATA = "data"; public static final String BINDING_NAME_ORGANIZATION = "organization"; public static final String BINDING_NAME_WEBSERVICESCLIENT = "webservicesClient"; public static final String BINDING_NAME_DICTIONARY = "dictionary"; public static final String BINDING_NAME_ROUTES = "routes"; public static final String BINDING_NAME_ROUTE = "routes"; public static final String BINDING_NAME_APPLICATIONS = "applications"; public static final String BINDING_NAME_ASSIGNDATA = "assignData"; public static final String BINDING_NAME_IDENTITY = "identity"; public static final String BINDING_NAME_PARAMETERS = "parameters"; public static final String BINDING_NAME_JAXRSRESPONSE = "jaxrsResponse"; public static final String BINDING_NAME_JAXWSRESPONSE = "jaxwsResponse"; public static final String BINDING_NAME_JAXRSBODY = "jaxrsBody"; public static final String BINDING_NAME_JAXRSHEAD = "jaxrsHead"; public static final String BINDING_NAME_SERVICEVALUE = "serviceValue"; public static final String BINDING_NAME_TASK = "task"; public static final String BINDING_NAME_EXPIRE = "expire"; public static final String BINDING_NAME_SERIAL = "serial"; public static final String BINDING_NAME_PROCESS = "process"; public static ScriptEngine newScriptEngine() { return (new ScriptEngineManager()).getEngineByName(Config.SCRIPTING_ENGINE_NAME); } public static CompiledScript initialServiceScriptText() throws Exception { if (COMPILEDSCRIPT_INITIALSERVICESCRIPTTEXT == null) { synchronized (ScriptFactory.class) { if (COMPILEDSCRIPT_INITIALSERVICESCRIPTTEXT == null) { String text = Config.initialServiceScriptText(); COMPILEDSCRIPT_INITIALSERVICESCRIPTTEXT = ((Compilable) scriptEngine).compile(text); } } } return COMPILEDSCRIPT_INITIALSERVICESCRIPTTEXT; } public static CompiledScript compile(String text) throws Exception { return ((Compilable) scriptEngine).compile(text); } public static CompiledScript initialScriptText() throws Exception { if (COMPILEDSCRIPT_INITIALSCRIPTTEXT == null) { synchronized (ScriptFactory.class) { if (COMPILEDSCRIPT_INITIALSCRIPTTEXT == null) { String text = Config.initialScriptText(); COMPILEDSCRIPT_INITIALSCRIPTTEXT = ((Compilable) scriptEngine).compile(text); } } } return COMPILEDSCRIPT_INITIALSCRIPTTEXT; } // public static String functionalization(String text) { // StringBuffer sb = new StringBuffer(); // sb.append("(function(){").append(System.lineSeparator()); // sb.append(Objects.toString(text, "")).append(System.lineSeparator()); // sb.append("})();"); // return sb.toString(); // } public static List<String> asStringList(Object o) throws Exception { return readAsStringList(o); } public static String asString(Object o) throws Exception { return Objects.toString(o); } public static Boolean asBoolean(Object o) throws Exception { if (null == o) { return false; } if (o instanceof Number) { return ((Number) o).intValue() != 0; } return BooleanUtils.toBooleanObject(Objects.toString(o, "false")); } public static List<String> asDistinguishedName(Object o) throws Exception { List<String> list = new ArrayList<>(); if (null != o) { if (o instanceof CharSequence) { list.add(Objects.toString(o)); } else if (o instanceof Iterable) { for (Object obj : (Iterable<?>) o) { if (null != obj) { if (obj instanceof CharSequence) { list.add(Objects.toString(obj)); } else { Object d = PropertyUtils.getProperty(obj, JpaObject.DISTINGUISHEDNAME); if (null != d) { list.add(Objects.toString(d)); } } } } } else if (o instanceof ScriptObjectMirror) { ScriptObjectMirror som = (ScriptObjectMirror) o; if (som.isArray()) { Object[] objs = (som.to(Object[].class)); for (Object obj : objs) { if (null != obj) { if (obj instanceof CharSequence) { list.add(Objects.toString(obj)); } else { Object d = PropertyUtils.getProperty(obj, JpaObject.DISTINGUISHEDNAME); if (null != d) { list.add(Objects.toString(d)); } } } } } else { Object d = PropertyUtils.getProperty(o, JpaObject.DISTINGUISHEDNAME); if (null != d) { list.add(Objects.toString(d)); } } } } return list; } private static List<String> readAsStringList(Object obj) throws Exception { List<String> list = new ArrayList<>(); for (Object o : iterator(obj)) { list.add(Objects.toString(o)); } return list; } private static List<Object> iterator(Object obj) throws Exception { List<Object> results = new ArrayList<>(); iterator(obj, results); return results; } private static void iterator(Object obj, List<Object> results) throws Exception { if (null == obj) { return; } List<Object> list = new ArrayList<>(); if (obj.getClass().isArray()) { for (Object o : (Object[]) obj) { list.add(o); } } else if (obj instanceof Collection) { for (Object o : (Collection<?>) obj) { list.add(o); } } else if (obj instanceof ScriptObjectMirror) { ScriptObjectMirror som = (ScriptObjectMirror) obj; if (som.isArray()) { Object[] os = (som.to(Object[].class)); for (Object o : os) { list.add(o); } } else { results.add(som); } } else { results.add(obj); } for (Object o : list) { iterator(o, results); } } public static List<String> asDistinguishedNameList(Object o) throws Exception { List<String> list = new ArrayList<>(); if (null != o) { if (o instanceof CharSequence) { list.add(Objects.toString(o, "")); } else if (o instanceof JsonObject) { JsonObject jsonObject = (JsonObject) o; if (jsonObject.has(JpaObject.DISTINGUISHEDNAME)) { list.add(jsonObject.get(JpaObject.DISTINGUISHEDNAME).getAsString()); } } else if (o instanceof JsonArray) { for (JsonElement jsonElement : (JsonArray) o) { if (jsonElement.isJsonObject()) { JsonObject jsonObject = jsonElement.getAsJsonObject(); if (jsonObject.has(JpaObject.DISTINGUISHEDNAME)) { list.add(jsonObject.get(JpaObject.DISTINGUISHEDNAME).getAsString()); } } } } else if (o instanceof Iterable) { for (Object obj : (Iterable<?>) o) { if (null != obj) { if (obj instanceof CharSequence) { list.add(Objects.toString(obj, "")); } else { Object d = PropertyUtils.getProperty(obj, JpaObject.DISTINGUISHEDNAME); if (null != d) { list.add(Objects.toString(d, "")); } } } } } else if (o instanceof ScriptObjectMirror) { ScriptObjectMirror som = (ScriptObjectMirror) o; if (som.isArray()) { Object[] objs = (som.to(Object[].class)); for (Object obj : objs) { if (null != obj) { if (obj instanceof CharSequence) { list.add(Objects.toString(obj, "")); } else { Object d = PropertyUtils.getProperty(obj, JpaObject.DISTINGUISHEDNAME); if (null != d) { list.add(Objects.toString(d, "")); } } } } } else { Object d = PropertyUtils.getProperty(o, JpaObject.DISTINGUISHEDNAME); if (null != d) { list.add(Objects.toString(d, "")); } } } } return list; } }
恢复ScriFactory
o2server/x_base_core_project/src/main/java/com/x/base/core/project/script/ScriptFactory.java
恢复ScriFactory
<ide><path>2server/x_base_core_project/src/main/java/com/x/base/core/project/script/ScriptFactory.java <ide> return COMPILEDSCRIPT_INITIALSCRIPTTEXT; <ide> } <ide> <del>// public static String functionalization(String text) { <del>// StringBuffer sb = new StringBuffer(); <del>// sb.append("(function(){").append(System.lineSeparator()); <del>// sb.append(Objects.toString(text, "")).append(System.lineSeparator()); <del>// sb.append("})();"); <del>// return sb.toString(); <del>// } <add> public static String functionalization(String text) { <add> StringBuffer sb = new StringBuffer(); <add> sb.append("(function(){").append(System.lineSeparator()); <add> sb.append(Objects.toString(text, "")).append(System.lineSeparator()); <add> sb.append("})();"); <add> return sb.toString(); <add> } <ide> <ide> public static List<String> asStringList(Object o) throws Exception { <ide> return readAsStringList(o);
Java
agpl-3.0
f1ea28d27774bc8877e2f803bf0585de385a2f26
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
9e9d774e-2e61-11e5-9284-b827eb9e62be
hello.java
9e97c056-2e61-11e5-9284-b827eb9e62be
9e9d774e-2e61-11e5-9284-b827eb9e62be
hello.java
9e9d774e-2e61-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>9e97c056-2e61-11e5-9284-b827eb9e62be <add>9e9d774e-2e61-11e5-9284-b827eb9e62be
Java
apache-2.0
be08830ab5552fe3736e7158ffcd64c6c438a1da
0
psoreide/bnd,psoreide/bnd,psoreide/bnd
package bndtools.m2e; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.project.MavenProject; import org.bndtools.api.ILogger; import org.bndtools.api.Logger; import org.bndtools.build.api.IProjectDecorator; import org.bndtools.build.api.IProjectDecorator.BndProjectInfo; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.WorkspaceJob; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jdt.core.IJavaModelMarker; import org.eclipse.m2e.core.MavenPlugin; import org.eclipse.m2e.core.embedder.IMaven; import org.eclipse.m2e.core.embedder.IMavenExecutionContext; import org.eclipse.m2e.core.internal.MavenPluginActivator; import org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager; import org.eclipse.m2e.core.lifecyclemapping.model.IPluginExecutionMetadata; import org.eclipse.m2e.core.project.IMavenProjectFacade; import org.eclipse.m2e.core.project.ResolverConfiguration; import org.eclipse.m2e.core.project.configurator.AbstractBuildParticipant; import org.eclipse.m2e.core.project.configurator.AbstractBuildParticipant2; import org.eclipse.m2e.core.project.configurator.AbstractProjectConfigurator; import org.eclipse.m2e.core.project.configurator.MojoExecutionBuildParticipant; import org.eclipse.m2e.core.project.configurator.ProjectConfigurationRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import aQute.bnd.osgi.Analyzer; import aQute.bnd.osgi.Jar; import aQute.bnd.osgi.Packages; import bndtools.launch.JUnitShortcut; public class BndConfigurator extends AbstractProjectConfigurator { protected final static Class<JUnitShortcut> shortcutClazz; static { /* * The class JUnitShortcut is loaded here because: a) this class is * loaded immediately to active the bndtools.m2e integration b) other * bndtools.m2e extensions instruct Eclipse to add shortcuts using this * type provided by bndtools.core and only referred to in the * plugin.xml. This reference causes the import to be added to * bndtools.m2e so that this process works. */ shortcutClazz = JUnitShortcut.class; } ILogger logger = Logger.getLogger(BndConfigurator.class); public static class MavenProjectInfo implements BndProjectInfo { private final MavenProject project; private final Packages exports; private final Packages imports; private final Packages contained; public MavenProjectInfo(MavenProject project) throws Exception { this.project = project; File file = new File(project.getBuild() .getOutputDirectory()); if (!file.exists()) { throw new IllegalStateException( "The output directory for project " + project.getName() + " does not exist"); } try (Jar jar = new Jar(file); Analyzer analyzer = new Analyzer(jar)) { analyzer.analyze(); exports = analyzer.getExports(); imports = analyzer.getImports(); contained = analyzer.getContained(); } } @Override public Collection<File> getSourcePath() throws Exception { List<File> sourcePath = new ArrayList<>(); for (String path : project.getCompileSourceRoots()) { sourcePath.add(new File(path)); } return sourcePath; } @Override public Packages getExports() { return exports; } @Override public Packages getImports() { return imports; } @Override public Packages getContained() { return contained; } } @Override public void configure(ProjectConfigurationRequest request, IProgressMonitor monitor) throws CoreException {} @Override public AbstractBuildParticipant getBuildParticipant(final IMavenProjectFacade projectFacade, final MojoExecution execution, IPluginExecutionMetadata executionMetadata) { return new MojoExecutionBuildParticipant(execution, true, true) { @Override public Set<IProject> build(int kind, IProgressMonitor monitor) throws Exception { // build mojo like normal final Set<IProject> build = super.build(kind, monitor); // nothing to do if configuration build if (kind == AbstractBuildParticipant2.PRECONFIGURE_BUILD) { return build; } final IProject project = projectFacade.getProject(); IMarker[] imarkers = project.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_INFINITE); if (imarkers != null && Arrays.stream(imarkers) .map(m -> m.getAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO)) .anyMatch(s -> s == IMarker.SEVERITY_ERROR)) { // there are compile errors, don't build jar return build; } // There might be more than one bnd-maven-plugin execution on // any single project. An example of this would be bundling test // classes. However, each such execution would be pointing at a // particular output directory, for example: // // ${project.build.outputDirectory} // vs. // ${project.build.testOutputDirectory} // // With that in mind the scope of detectable changes needs to be // limited to the actual output directory associated with the // plugin by reading the classesDir property. final File classesDir = maven.getMojoParameterValue(projectFacade.getMavenProject(), execution, "classesDir", File.class, monitor); // now we make sure jar is built in separate job, doing this // during maven builder will throw lifecycle // errors Job job = new WorkspaceJob("Executing " + project.getName() + " jar:jar goal") { @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, 3); execJarMojo(projectFacade, progress.newChild(1, SubMonitor.SUPPRESS_NONE)); // Find the maven output directory (usually "target") IPath buildDirPath = Path.fromOSString(classesDir.getAbsolutePath()); IPath projectPath = project.getLocation(); IPath relativeBuildDirPath = buildDirPath.makeRelativeTo(projectPath); IFolder buildDir = project.getFolder(relativeBuildDirPath); if (buildDir != null) { // TODO: there *may* be a remaining issue here if a // source-generation plugin gets triggered // by the above invocation of the jar:jar goal. // This could cause Eclipse to think that the Java // sources are dirty and queue the project // for rebuilding, thus entering an infinite loop. // One solution would be to find the output artifact // jar and refresh ONLY that. However we // have not been able to create the condition we // are worried about so we are deferring any extra // work on this until it's shown to be a // real problem. buildDir.refreshLocal(IResource.DEPTH_INFINITE, progress.newChild(1)); } else { Logger.getLogger(BndConfigurator.class) .logError(String.format( "Project build folder '%s' does not exist, or is not a child of the project path '%s'", buildDirPath, projectPath), null); progress.worked(1); } return Status.OK_STATUS; } }; job.setRule(project); job.schedule(); return build; } }; } private MavenProject getMavenProject(final IMavenProjectFacade projectFacade, IProgressMonitor monitor) throws CoreException { MavenProject mavenProject = projectFacade.getMavenProject(); if (mavenProject == null) { mavenProject = projectFacade.getMavenProject(monitor); } monitor.done(); return mavenProject; } private void execJarMojo(final IMavenProjectFacade projectFacade, IProgressMonitor monitor) throws CoreException { final IMaven maven = MavenPlugin.getMaven(); ProjectRegistryManager projectRegistryManager = MavenPluginActivator.getDefault() .getMavenProjectManagerImpl(); ResolverConfiguration resolverConfiguration = new ResolverConfiguration(); resolverConfiguration.setResolveWorkspaceProjects(true); IMavenExecutionContext context = projectRegistryManager.createExecutionContext(projectFacade.getPom(), resolverConfiguration); context.execute((context1, monitor1) -> { SubMonitor progress = SubMonitor.convert(monitor1); MavenProject mavenProject = getMavenProject(projectFacade, progress.newChild(1)); List<MojoExecution> mojoExecutions = projectFacade.getMojoExecutions("org.apache.maven.plugins", "maven-jar-plugin", monitor1, "jar"); for (MojoExecution mojoExecution : mojoExecutions) { maven.execute(mavenProject, mojoExecution, progress.newChild(1)); } // We can now decorate based on the build we just did. try { IProjectDecorator decorator = Injector.ref.get(); if (decorator != null) { BndProjectInfo info = new MavenProjectInfo(mavenProject); decorator.updateDecoration(projectFacade.getProject(), info); } } catch (Exception e) { logger.logError("Failed to decorate project " + projectFacade.getProject() .getName(), e); } return null; }, monitor); } @Component public static class Injector { private static AtomicReference<IProjectDecorator> ref = new AtomicReference<>(); @Reference void setDecorator(IProjectDecorator decorator) { ref.set(decorator); } void unsetDecorator(IProjectDecorator decorator) { ref.compareAndSet(decorator, null); } } }
bndtools.m2e/src/bndtools/m2e/BndConfigurator.java
package bndtools.m2e; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.project.MavenProject; import org.bndtools.api.ILogger; import org.bndtools.api.Logger; import org.bndtools.build.api.IProjectDecorator; import org.bndtools.build.api.IProjectDecorator.BndProjectInfo; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.WorkspaceJob; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jdt.core.IJavaModelMarker; import org.eclipse.m2e.core.MavenPlugin; import org.eclipse.m2e.core.embedder.IMaven; import org.eclipse.m2e.core.embedder.IMavenExecutionContext; import org.eclipse.m2e.core.internal.MavenPluginActivator; import org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager; import org.eclipse.m2e.core.lifecyclemapping.model.IPluginExecutionMetadata; import org.eclipse.m2e.core.project.IMavenProjectFacade; import org.eclipse.m2e.core.project.ResolverConfiguration; import org.eclipse.m2e.core.project.configurator.AbstractBuildParticipant; import org.eclipse.m2e.core.project.configurator.AbstractBuildParticipant2; import org.eclipse.m2e.core.project.configurator.AbstractProjectConfigurator; import org.eclipse.m2e.core.project.configurator.MojoExecutionBuildParticipant; import org.eclipse.m2e.core.project.configurator.ProjectConfigurationRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import aQute.bnd.osgi.Analyzer; import aQute.bnd.osgi.Jar; import aQute.bnd.osgi.Packages; import bndtools.launch.JUnitShortcut; public class BndConfigurator extends AbstractProjectConfigurator { protected final static Class<JUnitShortcut> shortcutClazz; static { /* * The class JUnitShortcut is loaded here because: a) this class is * loaded immediately to active the bndtools.m2e integration b) other * bndtools.m2e extensions instruct Eclipse to add shortcuts using this * type provided by bndtools.core and only referred to in the * plugin.xml. This reference causes the import to be added to * bndtools.m2e so that this process works. */ shortcutClazz = JUnitShortcut.class; } ILogger logger = Logger.getLogger(BndConfigurator.class); public static class MavenProjectInfo implements BndProjectInfo { private final MavenProject project; private final Packages exports; private final Packages imports; private final Packages contained; public MavenProjectInfo(MavenProject project) throws Exception { this.project = project; File file = new File(project.getBuild() .getOutputDirectory()); if (!file.exists()) { throw new IllegalStateException( "The output directory for project " + project.getName() + " does not exist"); } try (Jar jar = new Jar(file); Analyzer analyzer = new Analyzer(jar)) { analyzer.analyze(); exports = analyzer.getExports(); imports = analyzer.getImports(); contained = analyzer.getContained(); } } @Override public Collection<File> getSourcePath() throws Exception { List<File> sourcePath = new ArrayList<>(); for (String path : project.getCompileSourceRoots()) { sourcePath.add(new File(path)); } return sourcePath; } @Override public Packages getExports() { return exports; } @Override public Packages getImports() { return imports; } @Override public Packages getContained() { return contained; } } @Override public void configure(ProjectConfigurationRequest request, IProgressMonitor monitor) throws CoreException {} @Override public AbstractBuildParticipant getBuildParticipant(final IMavenProjectFacade projectFacade, MojoExecution execution, IPluginExecutionMetadata executionMetadata) { return new MojoExecutionBuildParticipant(execution, true, true) { @Override public Set<IProject> build(int kind, IProgressMonitor monitor) throws Exception { // build mojo like normal final Set<IProject> build = super.build(kind, monitor); // nothing to do if configuration build if (kind == AbstractBuildParticipant2.PRECONFIGURE_BUILD) { return build; } final IProject project = projectFacade.getProject(); IMarker[] imarkers = project.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_INFINITE); if (imarkers != null && Arrays.stream(imarkers) .map(m -> m.getAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO)) .anyMatch(s -> s == IMarker.SEVERITY_ERROR)) { // there are compile errors, don't build jar return build; } // now we make sure jar is built in separate job, doing this // during maven builder will throw lifecycle // errors Job job = new WorkspaceJob("Executing " + project.getName() + " jar:jar goal") { @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, 3); execJarMojo(projectFacade, progress.newChild(1, SubMonitor.SUPPRESS_NONE)); // Find the maven output directory (usually "target") MavenProject mvnProject = getMavenProject(projectFacade, progress.newChild(1)); IPath buildDirPath = Path.fromOSString(mvnProject.getBuild() .getDirectory()); IPath projectPath = project.getLocation(); IPath relativeBuildDirPath = buildDirPath.makeRelativeTo(projectPath); IFolder buildDir = project.getFolder(relativeBuildDirPath); if (buildDir != null) { // TODO: there *may* be a remaining issue here if a // source-generation plugin gets triggered // by the above invocation of the jar:jar goal. // This could cause Eclipse to think that the Java // sources are dirty and queue the project // for rebuilding, thus entering an infinite loop. // One solution would be to find the output artifact // jar and refresh ONLY that. However we // have not been able to create the condition we // are worried about so we are deferring any extra // work on this until it's shown to be a // real problem. buildDir.refreshLocal(IResource.DEPTH_INFINITE, progress.newChild(1)); } else { Logger.getLogger(BndConfigurator.class) .logError(String.format( "Project build folder '%s' does not exist, or is not a child of the project path '%s'", buildDirPath, projectPath), null); progress.worked(1); } return Status.OK_STATUS; } }; job.setRule(project); job.schedule(); return build; } }; } private MavenProject getMavenProject(final IMavenProjectFacade projectFacade, IProgressMonitor monitor) throws CoreException { MavenProject mavenProject = projectFacade.getMavenProject(); if (mavenProject == null) { mavenProject = projectFacade.getMavenProject(monitor); } monitor.done(); return mavenProject; } private void execJarMojo(final IMavenProjectFacade projectFacade, IProgressMonitor monitor) throws CoreException { final IMaven maven = MavenPlugin.getMaven(); ProjectRegistryManager projectRegistryManager = MavenPluginActivator.getDefault() .getMavenProjectManagerImpl(); ResolverConfiguration resolverConfiguration = new ResolverConfiguration(); resolverConfiguration.setResolveWorkspaceProjects(true); IMavenExecutionContext context = projectRegistryManager.createExecutionContext(projectFacade.getPom(), resolverConfiguration); context.execute((context1, monitor1) -> { SubMonitor progress = SubMonitor.convert(monitor1); MavenProject mavenProject = getMavenProject(projectFacade, progress.newChild(1)); List<MojoExecution> mojoExecutions = projectFacade.getMojoExecutions("org.apache.maven.plugins", "maven-jar-plugin", monitor1, "jar"); for (MojoExecution mojoExecution : mojoExecutions) { maven.execute(mavenProject, mojoExecution, progress.newChild(1)); } // We can now decorate based on the build we just did. try { IProjectDecorator decorator = Injector.ref.get(); if (decorator != null) { BndProjectInfo info = new MavenProjectInfo(mavenProject); decorator.updateDecoration(projectFacade.getProject(), info); } } catch (Exception e) { logger.logError("Failed to decorate project " + projectFacade.getProject() .getName(), e); } return null; }, monitor); } @Component public static class Injector { private static AtomicReference<IProjectDecorator> ref = new AtomicReference<>(); @Reference void setDecorator(IProjectDecorator decorator) { ref.set(decorator); } void unsetDecorator(IProjectDecorator decorator) { ref.compareAndSet(decorator, null); } } }
[m2e] Build in eclipse loops forever with bndtools.m2e project in Windows fixes #3536 Signed-off-by: Raymond Auge <[email protected]>
bndtools.m2e/src/bndtools/m2e/BndConfigurator.java
[m2e] Build in eclipse loops forever with bndtools.m2e project in Windows
<ide><path>ndtools.m2e/src/bndtools/m2e/BndConfigurator.java <ide> <ide> @Override <ide> public AbstractBuildParticipant getBuildParticipant(final IMavenProjectFacade projectFacade, <del> MojoExecution execution, IPluginExecutionMetadata executionMetadata) { <add> final MojoExecution execution, IPluginExecutionMetadata executionMetadata) { <ide> return new MojoExecutionBuildParticipant(execution, true, true) { <ide> @Override <ide> public Set<IProject> build(int kind, IProgressMonitor monitor) throws Exception { <ide> return build; <ide> } <ide> <add> // There might be more than one bnd-maven-plugin execution on <add> // any single project. An example of this would be bundling test <add> // classes. However, each such execution would be pointing at a <add> // particular output directory, for example: <add> // <add> // ${project.build.outputDirectory} <add> // vs. <add> // ${project.build.testOutputDirectory} <add> // <add> // With that in mind the scope of detectable changes needs to be <add> // limited to the actual output directory associated with the <add> // plugin by reading the classesDir property. <add> final File classesDir = maven.getMojoParameterValue(projectFacade.getMavenProject(), execution, <add> "classesDir", File.class, monitor); <add> <ide> // now we make sure jar is built in separate job, doing this <ide> // during maven builder will throw lifecycle <ide> // errors <ide> execJarMojo(projectFacade, progress.newChild(1, SubMonitor.SUPPRESS_NONE)); <ide> <ide> // Find the maven output directory (usually "target") <del> MavenProject mvnProject = getMavenProject(projectFacade, progress.newChild(1)); <del> IPath buildDirPath = Path.fromOSString(mvnProject.getBuild() <del> .getDirectory()); <add> IPath buildDirPath = Path.fromOSString(classesDir.getAbsolutePath()); <ide> IPath projectPath = project.getLocation(); <ide> IPath relativeBuildDirPath = buildDirPath.makeRelativeTo(projectPath); <ide> IFolder buildDir = project.getFolder(relativeBuildDirPath);
Java
apache-2.0
e1a0ec64b8eda04c89912f3c03ce6ad5358ff706
0
toby1984/jASM_16,toby1984/jASM_16
/** * Copyright 2012 Tobias Gierke <[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 de.codesourcery.jasm16.emulator; import java.util.*; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import org.apache.log4j.Logger; import de.codesourcery.jasm16.*; import de.codesourcery.jasm16.ast.OperandNode.OperandPosition; import de.codesourcery.jasm16.disassembler.DisassembledLine; import de.codesourcery.jasm16.disassembler.Disassembler; import de.codesourcery.jasm16.emulator.devices.*; import de.codesourcery.jasm16.emulator.exceptions.*; import de.codesourcery.jasm16.emulator.memory.*; import de.codesourcery.jasm16.utils.Misc; /** * DCPU-16 emulator. * * @author [email protected] */ public final class Emulator implements IEmulator { private static final Logger LOG = Logger.getLogger(Emulator.class); private static final boolean DEBUG = false; /** * Maximum number of interrupts the emulator's interrupt queue may hold. */ public static final int INTERRUPT_QUEUE_SIZE = 256; private static final boolean DEBUG_LISTENER_PERFORMANCE = false; private final IdentityHashMap<IEmulationListener,Long> listenerPerformance = new IdentityHashMap<IEmulationListener,Long>(); private final ClockThread clockThread; private final ListenerHelper listenerHelper = new ListenerHelper(); private static final AtomicLong cmdId = new AtomicLong(0); /** * Worker thread command types. * * @author [email protected] */ protected enum CommandType { START, STOP, TERMINATE, SPEED_CHANGE; } /** * Command to control the emulation's worker thread responsible * for the actual DCPU-16 instruction execution. * * <p>Command senders may request an acknowledge message * from the worker thread and block until it is received.Each * command carries a unique ID so that an * acknowledge message can be matched with the corresponding command.</p> * * @author [email protected] */ protected static final class Command { private final long id = cmdId.incrementAndGet(); private final Object payload; private final CommandType type; private final boolean requiresACK; public static Command terminateClockThread() { return new Command(CommandType.TERMINATE , true ); } public static Command stopCommandWithoutACK() { return new Command(CommandType.STOP,false); } public static Command stopCommand() { return new Command(CommandType.STOP,true); } public static Command startCommand() { return new Command(CommandType.START, true); } public static Command changeSpeedCommand(EmulationSpeed newSpeed) { return new Command(CommandType.SPEED_CHANGE,true,newSpeed); } protected Command(CommandType type, boolean requiresACK) { this(type,requiresACK,null); } protected Command(CommandType type, boolean requiresACK,Object payload) { this.type = type; this.payload = payload; this.requiresACK = requiresACK; } public Object getPayload() { return payload; } public boolean hasType(CommandType t) { return t.equals( this.type ); } public boolean requiresACK() { return requiresACK; } public boolean isTerminateCommand() { return type == CommandType.TERMINATE; } public boolean isStopCommand() { return type == CommandType.STOP|| type == CommandType.TERMINATE; } /** * Check whether this is a command that should make the * worker thread enter it's main <code>while()</code> loop. * * <p>When this method returns <code>true</code> , it does <b>not</b> mean * that the worker thread will actually start executing instructions , it will * only wake it up. * </p> * @return */ public boolean isStartWorkerMainLoopCommand() { return ! isStopCommand() || isTerminateCommand(); } public long getId() { return id; } @Override public String toString() { return type+" ( "+id+" , requires_ack="+requiresACK+" )"; } } /** * Helper to manage IEmulationListeners. * This class manages multiple internal lists , each for a specific listener type. * That way we avoid having to look-up listeners with a specific type each * time a notification needs to be send. * * @author [email protected] */ protected final class ListenerHelper { // @GuardedBy( emuListeners ) private final List<IEmulationListener> emuListeners = new ArrayList<IEmulationListener>(); // @GuardedBy( emuListeners ) private final List<IEmulationListener> beforeCommandExecListeners = new ArrayList<IEmulationListener>(); // @GuardedBy( emuListeners ) private final List<IEmulationListener> continuousModeBeforeCommandExecListeners = new ArrayList<IEmulationListener>(); // @GuardedBy( emuListeners ) private final List<IEmulationListener> afterCommandExecListeners = new ArrayList<IEmulationListener>(); // @GuardedBy( emuListeners ) private final List<IEmulationListener> continuousModeAfterCommandExecListeners = new ArrayList<IEmulationListener>(); private final IEmulationListenerInvoker BEFORE_COMMAND_INVOKER = new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.beforeCommandExecution( emulator ); } }; public void addEmulationListener(IEmulationListener listener) { if (listener == null) { throw new IllegalArgumentException("listener must not be NULL."); } synchronized (emuListeners) { emuListeners.add( listener ); if ( listener.isInvokeBeforeCommandExecution() ) { beforeCommandExecListeners.add( listener ); if ( listener.isInvokeAfterAndBeforeCommandExecutionInContinuousMode() ) { continuousModeBeforeCommandExecListeners.add( listener ); } } if ( listener.isInvokeAfterCommandExecution() ) { afterCommandExecListeners.add( listener ); if ( listener.isInvokeAfterAndBeforeCommandExecutionInContinuousMode() ) { continuousModeAfterCommandExecListeners.add( listener ); } } } } public void removeAllEmulationListeners() { synchronized (emuListeners) { removeAllNonHardwareListeners( emuListeners ); removeAllNonHardwareListeners( beforeCommandExecListeners ); removeAllNonHardwareListeners( continuousModeBeforeCommandExecListeners ); removeAllNonHardwareListeners( continuousModeAfterCommandExecListeners ); removeAllNonHardwareListeners( afterCommandExecListeners ); } } private void removeAllNonHardwareListeners(List<IEmulationListener> list) { for ( Iterator<IEmulationListener> it = list.iterator() ; it.hasNext() ; ) { if ( ! it.next().belongsToHardwareDevice() ) { it.remove(); } } } public void removeEmulationListener(IEmulationListener listener) { if (listener == null) { throw new IllegalArgumentException("listener must not be NULL."); } synchronized (emuListeners) { emuListeners.remove( listener ); beforeCommandExecListeners.remove( listener ); continuousModeBeforeCommandExecListeners.remove( listener ); continuousModeAfterCommandExecListeners.remove( listener ); afterCommandExecListeners.remove( listener ); } } public void notifyListeners(IEmulationListenerInvoker invoker) { notifyListeners( invoker , emuListeners ); } public void invokeAfterCommandExecutionListeners(boolean continousMode,final int executedCommandDuration) { final IEmulationListenerInvoker invoker = new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.afterCommandExecution( emulator , executedCommandDuration ); } }; if ( continousMode ) { notifyListeners( invoker , continuousModeAfterCommandExecListeners ); } else { notifyListeners( invoker , afterCommandExecListeners ); } } public void invokeBeforeCommandExecutionListeners(boolean continousMode) { if ( continousMode ) { notifyListeners( BEFORE_COMMAND_INVOKER , continuousModeBeforeCommandExecListeners ); } else { notifyListeners( BEFORE_COMMAND_INVOKER , beforeCommandExecListeners ); } } public void notifyListeners(IEmulationListenerInvoker invoker,List<IEmulationListener> listeners) { final List<IEmulationListener> copy; synchronized( emuListeners ) { if ( listeners.isEmpty() ) { return; } copy = new ArrayList<IEmulationListener>( listeners ); } if ( DEBUG_LISTENER_PERFORMANCE ) { for ( IEmulationListener l : copy) { long execTime = -System.currentTimeMillis(); try { invoker.invoke( Emulator.this , l ); } catch(Exception e) { LOG.error("notifyListeners(): Listener "+l+" failed",e); } finally { execTime += System.currentTimeMillis(); } final Long existing = listenerPerformance.get( l ); if ( existing == null ) { listenerPerformance.put( l , execTime ); } else { listenerPerformance.put( l , existing.longValue() + execTime ); } } } else { final int len = copy.size(); for ( int i = 0 ; i < len ; i++) { final IEmulationListener l = copy.get(i); try { invoker.invoke( Emulator.this , l ); } catch(Exception e) { LOG.error("notifyListeners(): Listener "+l+" failed",e); } } } } public void emulatorDisposed() { notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.beforeEmulatorIsDisposed( emulator ); } }); final List<IEmulationListener> copy; synchronized( emuListeners ) { copy = new ArrayList<IEmulationListener>( emuListeners ); } for ( IEmulationListener l : copy ) { removeEmulationListener( l ); } } } private volatile boolean ignoreAccessToUnknownDevices=false; private volatile boolean checkMemoryWrites = false; private volatile Throwable lastEmulationError = null; private volatile EmulationSpeed emulationSpeed = EmulationSpeed.MAX_SPEED; // ============ BreakPoints ======= // @GuardedBy( breakpoints ) private final Map<Address,List<Breakpoint>> breakpoints = new HashMap<Address,List<Breakpoint>>(); // ============ Memory ============ // memory needs to be thread-safe since the emulation runs in a separate thread // and UI threads may access the registers concurrently private final MainMemory memory = new MainMemory( 65536 , checkMemoryWrites ); // ========= devices =========== // @GuardedBy( devices ) private final List<IDevice> devices = new ArrayList<IDevice>(); // ============ CPU =============== private final Object CPU_LOCK = new Object(); private Address lastValidInstruction = null; // @GuardedBy( CPU_LOCK ) private final CPU cpu = new CPU(memory); // @GuardedBy( CPU_LOCK ) private final CPU visibleCPU = new CPU(memory); // a,b,c,x,y,z,i,j // all CPU registers needs to be thread-safe since the emulation runs in a separate thread // and UI threads may access the registers concurrently private volatile ILogger loggerDelegate = new PrintStreamLogger( System.out ); private final ILogger out = new ILogger() { @Override public void setLogLevel(de.codesourcery.jasm16.emulator.ILogger.LogLevel logLevel) { loggerDelegate.setLogLevel( logLevel ); } @Override public boolean isDebugEnabled() { return loggerDelegate.isDebugEnabled(); } @Override public void info(String message) { loggerDelegate.info(message); } @Override public void info(String message, Throwable cause) { loggerDelegate.info(message, cause); } @Override public void warn(String message) { loggerDelegate.warn(message); } @Override public void warn(String message, Throwable cause) { loggerDelegate.warn(message, cause); } @Override public void error(String message) { loggerDelegate.error(message); } @Override public void error(String message, Throwable cause) { loggerDelegate.error(message, cause); } @Override public void debug(String message) { loggerDelegate.debug(message); } @Override public void debug(String message, Throwable cause) { loggerDelegate.debug(message, cause); } }; /* (non-Javadoc) * @see de.codesourcery.jasm16.emulator.IEmulator#reset() */ @Override public void reset(boolean clearMemory) { stop(null); // reset memory BEFORE resetting devices // because if a device uses MMIO, doing the // resetMemory() call after resetDevices() may // trigger the device again and thus pollute // the reset state resetMemory(clearMemory); resetDevices(); synchronized( CPU_LOCK ) { cpu.reset(); visibleCPU.reset(); } // notify listeners listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.afterReset( emulator ); } }); } private void resetMemory(boolean clearMemory) { memory.resetWriteProtection(); if ( clearMemory ) { memory.clear(); } } private void resetDevices() { for ( IDevice device : getDevices() ) { try { device.reset(); } catch(Exception e) { LOG.error("reset(): Device "+device+" failed during reset",e); } } } @Override public boolean stop() { return stop( null ); } protected boolean stop(final Throwable cause) { this.lastEmulationError = cause; final boolean emulationWasRunning = clockThread.stopSimulation(); if ( emulationWasRunning ) { listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { final Address pc; synchronized( CPU_LOCK ) { pc = visibleCPU.pc; } listener.onStop( emulator , pc , cause ); } }); } // remove all internal breakpoints final List<Breakpoint> internalBPs = new ArrayList<Breakpoint>(); synchronized( breakpoints ) { for ( List<Breakpoint> bps : breakpoints.values() ) { for ( Breakpoint bp : bps ) { if ( bp.isOneShotBreakpoint() ) { internalBPs.add( bp ); } } } } for ( Breakpoint bp : internalBPs ) { deleteBreakpoint( bp ); } return emulationWasRunning; } @Override public void start() { listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.beforeContinuousExecution( emulator ); } }); clockThread.startSimulation(); } public Emulator() { clockThread = new ClockThread(); clockThread.start(); } /** * Thread responsible for execution of the * actual instruction emulation. * * <p>This thread's main loop supports two * execution modes, either {@link EmulationSpeed#MAX_SPEED} * or {@link EmulationSpeed#REAL_SPEED}.</p> * * @author [email protected] */ public final class ClockThread extends Thread { // values used for emulation speed calculations private long lastStart = 0; private int cycleCountAtLastStart=0; private long lastStop = 0; private int cycleCountAtLastStop=0; private final AtomicBoolean isRunnable = new AtomicBoolean(false); private final BlockingQueue<Command> cmdQueue = new ArrayBlockingQueue<Command>(1); private final BlockingQueue<Long> ackQueue = new ArrayBlockingQueue<Long>(300); // execution delay loop parameters determined by calibrate() method private volatile double adjustmentFactor = 1.0d; private volatile int oneCycleDelay = -1; // just a dummy value used in our delay loop private int dummy; // the current emulation speed private EmulationSpeed currentSpeed = emulationSpeed; public ClockThread() { setName("emulation-clock-thread"); setDaemon(true); } @Override public void run() { lastEmulationError = null; Command cmd = waitForStartCommand(); if ( cmd.isTerminateCommand() ) { out.info("Emulator thread terminated."); acknowledgeCommand( cmd ); return; } lastStart = System.currentTimeMillis(); cycleCountAtLastStart=cpu.currentCycle; acknowledgeCommand( cmd ); while ( true ) { if ( isRunnable.get() == false ) { // halt execution lastStop = System.currentTimeMillis(); cycleCountAtLastStop = cpu.currentCycle; if ( DEBUG_LISTENER_PERFORMANCE ) { for ( Map.Entry<IEmulationListener,Long> entry : listenerPerformance.entrySet() ) { out.debug( entry.getKey()+" = "+entry.getValue()+" millis" ); } } out.info("Emulator stopped."); out.info("Executed cycles: "+(cycleCountAtLastStop-cycleCountAtLastStart) +" ( in "+getRuntimeInSeconds()+" seconds )"); out.info("Estimated clock rate: "+getEstimatedClockSpeed() ); cmd = waitForStopCommand(); if ( cmd.isTerminateCommand() ) { acknowledgeCommand( cmd ); break; } acknowledgeCommand( cmd ); cmd = waitForStartCommand(); if ( cmd.isTerminateCommand() ) { acknowledgeCommand( cmd ); break; } lastEmulationError = null; cycleCountAtLastStart = cpu.currentCycle; lastStart = System.currentTimeMillis(); acknowledgeCommand(cmd); } /* ================ * Execute ONE instruction * ================ */ final int durationInCycles = internalExecuteOneInstruction(); if ( currentSpeed == EmulationSpeed.REAL_SPEED ) { // adjust execution speed every 10000 cycles // to account for CPU load changes / JIT / different instruction profiles if ( ( cpu.currentCycle % 10000 ) == 0 ) { final double deltaSeconds = ( System.currentTimeMillis() - lastStart) / 1000d; final double cyclesPerSecond = (cpu.currentCycle-cycleCountAtLastStart) / deltaSeconds; if ( ! Double.isInfinite( cyclesPerSecond ) ) { adjustmentFactor = ( cyclesPerSecond / 100000.0d ); } } // delay execution, this code is exactly the same code as the one timed in // measureDelayLoop() int j = (int) (oneCycleDelay*durationInCycles*adjustmentFactor); for ( ; j > 0 ; j-- ) { dummy = ((dummy*2+j*2)/3)/(dummy*7+j); } } } out.info("Emulator thread terminated."); } public void startSimulation() { if ( isRunnable.compareAndSet( false , true ) ) { sendToClockThread( Command.startCommand() ); } } /** * Stop simulation. * * @return true if the simulation was currently running and has been stopped, false if the simulation was already stopped. */ public boolean stopSimulation() { if ( isRunnable.compareAndSet(true,false) ) { if ( Thread.currentThread() == clockThread ) { sendToClockThread( Command.stopCommandWithoutACK() ); // no point in sending an ACK since the clock thread itself triggered the stop() } else { sendToClockThread( Command.stopCommand() ); } return true; } return false; } public void changeSpeed(EmulationSpeed newSpeed) { sendToClockThread( Command.changeSpeedCommand( newSpeed ) ); } private final AtomicBoolean terminateCommandReceived = new AtomicBoolean(false); private void sendToClockThread(Command cmd) { if ( cmd.hasType(CommandType.TERMINATE ) ) { if ( ! terminateCommandReceived.compareAndSet( false , true ) ) { throw new IllegalStateException("Can't process any more commands , worker thread already terminated"); } } safePut( cmdQueue , cmd ); if ( ! cmd.requiresACK() ) { // don't wait , we'll never receive this one anyway return; } do { final Long cmdId = ackQueue.peek(); if ( cmdId != null && cmdId.longValue() == cmd.getId() ) { safeTake( ackQueue ); return; } try { java.lang.Thread.sleep(100); } catch(InterruptedException e) { Thread.currentThread().interrupt(); } } while ( true ); } private <T> T safeTake(BlockingQueue<T> queue) { while(true) { try { return queue.take(); } catch (InterruptedException e) { Thread.currentThread(); } } } public double getRuntimeInSeconds() { if ( lastStart != 0 && lastStop != 0 ) { final long delta = lastStop - lastStart; if ( delta >= 0) { return delta / 1000.0d; } LOG.error("getRuntimeInSeconds(): Negative runtime ? "+delta+" ( lastStart: "+lastStart+" / lastStop: "+lastStop,new Exception()); throw new RuntimeException("Unreachable code reached"); } else if ( lastStart != 0 ) { return ( (double) System.currentTimeMillis() - (double) lastStart) / 1000.0d; } else if ( lastStart == 0 && lastStop == 0 ) { return 0; } LOG.error("getRuntimeInSeconds(): Unreachable code reached"); throw new RuntimeException("Unreachable code reached"); } protected final double measureDelayLoopInNanos() { double averages = 0.0d; int count = 0; for ( int i = 0 ; i < 10 ; i++ ) { averages += measureDelayLoop(); count++; } return (averages / count); } protected final double measureDelayLoop() { final int oldValue = clockThread.oneCycleDelay; final int LOOP_COUNT = 1000000; oneCycleDelay = LOOP_COUNT; final long nanoStart = System.nanoTime(); for ( int j = oneCycleDelay ; j > 0 ; j-- ) { dummy = ((dummy*2+j*2)/3)/(dummy*7+j); } long durationNanos = ( System.nanoTime() - nanoStart ); if ( durationNanos < 0) { durationNanos = -durationNanos; } oneCycleDelay = oldValue; return ( (double) durationNanos / (double) LOOP_COUNT); } public String getEstimatedClockSpeed() { final double clockRate = getCyclesPerSecond(); final double delta = clockRate-100000.0; final double deviationPercentage = 100.0d*( delta / 100000.0 ); final String sign = deviationPercentage > 0 ? "+" : ""; final String deviation = " ( "+sign+deviationPercentage+" % )"; if ( clockRate == -1.0d ) { return "<cannot calculate clock rate>"; } if ( clockRate < 1000 ) { return clockRate+" Hz"+deviation; } else if ( clockRate < 100000) { return (clockRate/1000)+" kHz"+deviation; } else if ( clockRate < 1000000000 ) { return (clockRate/1000000)+" MHz"+deviation; } return (clockRate/1000000000)+" GHz"+deviation; } public double getCyclesPerSecond() { if ( lastStart != 0 ) { final double runtime = getRuntimeInSeconds(); if ( runtime != 0.0d ) { return ((double)cycleCountAtLastStop - (double) cycleCountAtLastStart ) / getRuntimeInSeconds(); } } return 0.0d; } private Command waitForStopCommand() { return waitForCommand(false); } private Command waitForStartCommand() { return waitForCommand(true); } private Command waitForCommand(boolean expectingStartCommand) { while ( true ) { final Command result = safeTake( cmdQueue ); // note that everything that is NOT a stop/terminate command // is considered to be a START command so we need to adjust // the speed here before checking Command#isStartCommand() if ( result.hasType( CommandType.SPEED_CHANGE ) ) { currentSpeed = (EmulationSpeed) result.getPayload(); out.info("Emulation speed changed changed to "+currentSpeed); acknowledgeCommand( result ); continue; } if ( ( expectingStartCommand && result.isStartWorkerMainLoopCommand() ) || ( ! expectingStartCommand && result.isStopCommand() ) ) { return result; } acknowledgeCommand( result ); } } private void acknowledgeCommand(Command cmd) { if ( cmd.requiresACK() ) { safePut( ackQueue , cmd.getId() ); } } } public <T> T doWithEmulator(IEmulatorInvoker<T> invoker) { synchronized( CPU_LOCK ) { return invoker.doWithEmulator( this , cpu , memory ); } } /** * * @return number of DCPU-16 cycles the command execution took */ protected int internalExecuteOneInstruction() { beforeCommandExecution(); int execDurationInCycles=-1; try { boolean success = false; synchronized( CPU_LOCK ) { try { execDurationInCycles = cpu.executeInstruction(); lastValidInstruction = visibleCPU.pc; if ( checkMemoryWrites ) { // note-to-self: I cannot simply do ( currentPC - previousPC ) here because // the instruction might've been a JSR or ADD PC, X / SUB PC,Y or // a jump into an interrupt handler that skipped over non-instruction memory final int sizeInWords = calculateInstructionSizeInWords( visibleCPU.pc.getWordAddressValue() , memory ); memory.writeProtect( new AddressRange( visibleCPU.pc , Size.words( sizeInWords )) ); } cpu.currentCycle+=execDurationInCycles; cpu.pc = Address.wordAddress( cpu.currentInstructionPtr ); cpu.maybeProcessOneInterrupt(); // might push A on stack and set PC to IA success = true; } finally { if ( success ) { visibleCPU.populateFrom( cpu ); } else { // restore CPU register state on error cpu.populateFrom(visibleCPU); } } } } catch(EmulationErrorException e) { stop( e ); LOG.error( "internalExecuteOneInstruction(): Emulation error - "+e.getMessage()); out.warn("Simulation stopped due to a program error ( at address ."+visibleCPU.pc+")",e); return 0; } catch(Exception e) { stop( e ); LOG.error( "internalExecuteOneInstruction(): Internal error - "+e.getMessage(),e); out.error("Simulation stopped due to an internal error ( at address ."+visibleCPU.pc+")"); return 0; } finally { afterCommandExecution( execDurationInCycles , cpu ); } return execDurationInCycles; } @Override public void executeOneInstruction() { stop(null); internalExecuteOneInstruction(); } protected void beforeCommandExecution() { listenerHelper.invokeBeforeCommandExecutionListeners( this.clockThread.isRunnable.get() ); } /** * * @param executedCommandDuration duration (in cycles) of last command or -1 if execution failed with an internal emulator error */ protected void afterCommandExecution(final int executedCommandDuration,CPU hiddenCPU) { // invoke listeners listenerHelper.invokeAfterCommandExecutionListeners( clockThread.isRunnable.get() , executedCommandDuration ); // check whether we reached a breakpoint maybeHandleBreakpoint(hiddenCPU); } private void maybeHandleBreakpoint(CPU hiddenCPU) { /* * We can have at most 2 breakpoints at any address, * one regular (user-defined) breakpoint and * one internal breakpoint used by stepReturn() */ Breakpoint regularBP = null; Breakpoint oneShotBP = null; synchronized( breakpoints ) { final List<Breakpoint> candidates = breakpoints.get( hiddenCPU.pc ); if ( candidates == null || candidates.isEmpty() ) { return; } for ( Breakpoint bp : candidates ) { if ( bp.matches( this ) ) { if ( bp.isOneShotBreakpoint() ) { if ( oneShotBP == null ) { oneShotBP = bp; } else { throw new RuntimeException("Internal error, more than one internal breakpoint at "+bp.getAddress()); } } else { if ( regularBP == null ) { regularBP = bp; } else { throw new RuntimeException("Internal error, more than one regular breakpoint at "+bp.getAddress()); } } } } } if ( regularBP != null || oneShotBP != null ) { // stop() will also remove ANY one-shot breakpoints from the list stop(null); if ( regularBP != null ) // only notify client code about the regular BP, internal BP is invisible to the user { final Breakpoint finalRegularBP = regularBP; // Closures can only access stuff declared final... listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.onBreakpoint( emulator , finalRegularBP ); } }); } } } private boolean isConditionalInstruction(int instructionWord) { final int opCode = (instructionWord & 0x1f); return ( opCode >= 0x10 && opCode <= 0x17); } @Override public void skipCurrentInstruction() { synchronized(CPU_LOCK) { int adr = cpu.pc.getWordAddressValue(); adr += calculateInstructionSizeInWords( adr , memory ); cpu.pc = Address.wordAddress( adr ); visibleCPU.populateFrom( cpu ); } afterCommandExecution( 0 , visibleCPU ); } public static int calculateInstructionSizeInWords(Address address,IReadOnlyMemory memory) { return calculateInstructionSizeInWords(address.getWordAddressValue() , memory ); } public static int calculateInstructionSizeInWords(int address,IReadOnlyMemory memory) { @SuppressWarnings("deprecation") final int instructionWord = memory.read( address ); final int opCode = (instructionWord & 0x1f); int instructionSizeInWords=1; // +1 word for instruction itself switch( opCode ) { case 0x00: // skip special opcode instructionSizeInWords += getOperandsSizeInWordsForSpecialInstruction( instructionWord ); break; case 0x01: // SET case 0x02: // ADD case 0x03: // SUB case 0x04: // MUL case 0x05: // MLI case 0x06: // DIV case 0x07: // DVI case 0x08: // MOD case 0x09: // MDI case 0x0a: // AND case 0x0b: // BOR case 0x0c: // XOR case 0x0d: // SHR case 0x0e: // ASR case 0x0f: // SHL case 0x10: // IFB case 0x11: // IFC case 0x12: // IFE case 0x13: // IFN case 0x14: // IFG case 0x15: // IFA case 0x16: // IFL case 0x17: // IFU instructionSizeInWords += getOperandsSizeInWordsForBasicInstruction(instructionWord); break; case 0x18: // UNKNOWN case 0x19: // UNKNOWN; instructionSizeInWords += getOperandsSizeInWordsForUnknownInstruction( instructionWord ); break; case 0x1a: // ADX case 0x1b: // SBX instructionSizeInWords += getOperandsSizeInWordsForBasicInstruction(instructionWord); break; case 0x1c: // UNKNOWN case 0x1d: // UNKNOWN instructionSizeInWords += getOperandsSizeInWordsForUnknownInstruction( instructionWord ); break; case 0x1e: // STI case 0x1f: // STD instructionSizeInWords += getOperandsSizeInWordsForBasicInstruction( instructionWord ); break; default: instructionSizeInWords += getOperandsSizeInWordsForUnknownInstruction( instructionWord ); break; } return instructionSizeInWords; } private static int getOperandsSizeInWordsForBasicInstruction(int instructionWord) { // PC is already pointing at word AFTER current instruction here ! return getOperandSizeInWords(OperandPosition.SOURCE_OPERAND,instructionWord,false)+getOperandSizeInWords(OperandPosition.TARGET_OPERAND,instructionWord,false) ; } private static int getOperandsSizeInWordsForUnknownInstruction(int instructionWord) { // PC is already pointing at word AFTER current instruction here ! return 0; } private static int getOperandsSizeInWordsForSpecialInstruction(int instructionWord) { // PC is already pointing at word AFTER current instruction here ! return getOperandSizeInWords(OperandPosition.SOURCE_OPERAND,instructionWord,true); } private static int getOperandSizeInWords(OperandPosition position, int instructionWord,boolean isSpecialOpCode) { /* SET b,a * * b is always handled by the processor after a, and is the lower five bits. * In bits (in LSB-0 format), a basic instruction has the format: * * aaaaaabbbbbooooo * * b = TARGET operand * a = SOURCE operand * * Special opcodes always have their lower five bits unset, have one value and a * five bit opcode. In binary, they have the format: * * aaaaaaooooo00000 * * The value (a) is in the same six bit format as defined earlier. */ final int operandBits; if ( position == OperandPosition.SOURCE_OPERAND || isSpecialOpCode ) { // SET b , a ==> a operandBits = (instructionWord >>> 10) & ( 1+2+4+8+16+32); // SET b,a ==> b } else { operandBits = (instructionWord >>> 5) & ( 1+2+4+8+16); // SET b,a ==> b } if ( operandBits <= 0x07 ) { return 0; // operandDesc( registers[ operandBits ] ); } if ( operandBits <= 0x0f ) { return 0; // operandDesc( memory[ registers[ operandBits - 0x08 ] ] , 1 ); } if ( operandBits <= 0x17 ) { return 1; // operandDesc( memory[ registers[ operandBits - 0x10 ]+nextWord ] ,1 ); } switch( operandBits ) { case 0x18: // POP / [SP++] return 0 ; // operandDesc( memory[ sp ] , 1 ); case 0x19: return 0; // operandDesc( memory[ sp] , 1 ); case 0x1a: return 1; // operandDesc( memory[ sp + nextWord ] , 1 ); case 0x1b: return 0; // operandDesc( sp ); case 0x1c: return 0; // operandDesc( pc ); case 0x1d: return 0; // operandDesc( ex ); case 0x1e: return 1; // operandDesc( memory[ nextWord ] ,1 ); case 0x1f: return 1; // operandDesc( memory[ pc++ ] , 1 ); } // literal value: -1...30 ( 0x20 - 0x3f ) return 0; // operandDesc( operandBits - 0x21 , 0 ); } @Override public boolean canStepReturn() { return isJSR( memory.read( cpu.pc ) ); } @Override public void stepReturn() { if ( ! canStepReturn() ) { throw new IllegalStateException("PC is not at a JSR instruction, cannot skip return"); } final int currentInstructionSizeInWords = calculateInstructionSizeInWords( cpu.pc.getWordAddressValue() , memory ); final Address nextInstruction = cpu.pc.plus( Size.words( currentInstructionSizeInWords ) , true ); addBreakpoint( new OneShotBreakpoint( nextInstruction ) ); start(); } protected static boolean isJSR(int instructionWord) { final int basicOpCode = (instructionWord & 0x1f); if ( basicOpCode != 0 ) { return false; } final int specialOpCode = ( instructionWord >>> 5 ) &0x1f; return specialOpCode == 0x01; // JSR } private IDevice getDeviceForSlot(int hardwareSlot) { synchronized( devices ) { if ( hardwareSlot>=0 && hardwareSlot<devices.size()) { return devices.get(hardwareSlot); } } return null; } protected static final class OperandDesc { public final int value; public final int cycleCount; // how long it takes to perform the operation public OperandDesc(int value) { this.value = value & 0xffff; this.cycleCount = 0; } public OperandDesc(int value,int cycleCount) { this.value = value & 0xffff; this.cycleCount = cycleCount; } } protected static OperandDesc operandDesc(int value) { return new OperandDesc( value ); } protected static OperandDesc operandDesc(int value,int cycleCount) { return new OperandDesc( value , cycleCount ); } /* (non-Javadoc) * @see de.codesourcery.jasm16.emulator.IEmulator#loadMemory(de.codesourcery.jasm16.Address, byte[]) */ @Override public void loadMemory(final Address startingOffset, final byte[] data) { stop(null); if ( clockThread.isRunnable.get() ) { throw new IllegalStateException("Emulation not stopped?"); } memory.clear(); MemUtils.bulkLoad( memory , startingOffset , data ); // notify listeners listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.afterMemoryLoad( emulator , startingOffset , data.length ); } }); } protected interface IEmulationListenerInvoker { public void invoke(IEmulator emulator, IEmulationListener listener); } /* (non-Javadoc) * @see de.codesourcery.jasm16.emulator.IEmulator#calibrate() */ @Override public synchronized void calibrate() { listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.beforeCalibration( emulator ); } }); final double EXPECTED_CYCLES_PER_SECOND = 100000; // 100 kHz final double expectedNanosPerCycle = (1000.0d * 1000000.0d) / EXPECTED_CYCLES_PER_SECOND; out.info("Measuring delay loop..."); /* * Warm-up JVM / JIT. */ double sum =0.0d; for ( int i = 0 ; i < 5 ; i++ ) { final double tmp = clockThread.measureDelayLoopInNanos(); sum+= tmp; } /* * Repeatedly measure the execution time * for a single delay-loop iteration. */ final int LOOP_COUNT=5; sum =0.0d; for ( int i = 0 ; i < LOOP_COUNT ; i++ ) { final double tmp = clockThread.measureDelayLoopInNanos(); sum+= tmp; } final double nanosPerDelayLoopExecution = sum / LOOP_COUNT; out.info("one delay-loop iteration = "+nanosPerDelayLoopExecution+" nanoseconds."); final double loopIterationsPerCycle = expectedNanosPerCycle / nanosPerDelayLoopExecution; clockThread.adjustmentFactor = 1.0d; clockThread.oneCycleDelay = (int) Math.round( loopIterationsPerCycle ); out.info("one CPU cycle = "+clockThread.oneCycleDelay+" delay-loop iterations."); listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.afterCalibration( emulator ); } }); } @Override public IReadOnlyCPU getCPU() { synchronized( CPU_LOCK ) { final CPU result = new CPU(this.memory); result.populateFrom( this.visibleCPU ); return result; } } @Override public IReadOnlyMemory getMemory() { return memory; } @Override public void addEmulationListener(IEmulationListener listener) { listenerHelper.addEmulationListener( listener ); } public void removeAllEmulationListeners() { listenerHelper.removeAllEmulationListeners(); } @Override public void removeEmulationListener(IEmulationListener listener) { listenerHelper.removeEmulationListener( listener ); } private Breakpoint extractRegularBreakpoint(List<Breakpoint> bps) { Breakpoint result = null; for ( Breakpoint bp : bps ) { if ( ! bp.isOneShotBreakpoint() ) { if ( result != null ) { throw new IllegalStateException("More than one " + " regular breakpoint at address "+bp.getAddress()); } result = bp; } } return result; } @Override public void addBreakpoint(final Breakpoint bp) { if (bp == null) { throw new IllegalArgumentException("breakpoint must not be NULL."); } Breakpoint replacedBreakpoint; synchronized( breakpoints ) { List<Breakpoint> list = breakpoints.get( bp.getAddress() ); if ( list == null ) { list = new ArrayList<Breakpoint>(); breakpoints.put( bp.getAddress() , list ); } replacedBreakpoint = extractRegularBreakpoint( list ); if ( replacedBreakpoint != null ) { list.remove( replacedBreakpoint ); } list.add( bp ); } // notify listeners if ( replacedBreakpoint != null && ! replacedBreakpoint.isOneShotBreakpoint() ) { listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.breakpointDeleted( emulator , bp ); } }); } if ( ! bp.isOneShotBreakpoint() ) { listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.breakpointAdded( emulator , bp ); } }); } } @Override public void breakpointChanged(final Breakpoint bp) { Breakpoint existing; synchronized( breakpoints ) { final List<Breakpoint> list = breakpoints.get( bp.getAddress() ); if ( list != null ) { existing = extractRegularBreakpoint( list ); } else { existing = null; } } if ( existing == null ) { LOG.warn("breakpointChanged(): Unknown breakpoint "+bp); return; } listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.breakpointChanged( emulator , bp ); } }); } @Override public void deleteAllBreakpoints() { final List<Breakpoint> copy=new ArrayList<>(); synchronized( breakpoints ) { for ( List<Breakpoint> bp : breakpoints.values() ) { copy.addAll( bp ); } } for ( Breakpoint bp : copy ) { deleteBreakpoint( bp , false ); } listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.allBreakpointsDeleted( emulator ); } }); } @Override public void deleteBreakpoint(final Breakpoint bp) { deleteBreakpoint(bp,true); } private void deleteBreakpoint(final Breakpoint bp,boolean notifyListeners) { if (bp == null) { throw new IllegalArgumentException("breakpoint must not be NULL."); } Breakpoint existing; synchronized( breakpoints ) { final List<Breakpoint> list = breakpoints.get( bp.getAddress() ); if ( list != null ) { final int idx = list.indexOf( bp ); if ( idx != -1 ) { existing = list.remove( idx ); } else { existing = null; } if ( list.isEmpty() ) { breakpoints.remove( bp.getAddress() ); } } else { existing = null; } } // notify listeners if ( notifyListeners && existing != null && ! existing.isOneShotBreakpoint() ) { listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.breakpointDeleted( emulator , bp ); } }); } } @Override public List<Breakpoint> getBreakPoints() { final List<Breakpoint> result = new ArrayList<Breakpoint>(); synchronized( breakpoints ) { for ( List<Breakpoint> subList : breakpoints.values() ) { for ( Breakpoint bp : subList ) { if ( ! bp.isOneShotBreakpoint() ) { result.add( bp ); } } } } return result; } @Override public Breakpoint getBreakPoint(Address address) { if (address == null) { throw new IllegalArgumentException("address must not be NULL."); } synchronized( breakpoints ) { final List<Breakpoint> list = breakpoints.get( address ); if ( list == null ) { return null; } return extractRegularBreakpoint( list ); } } @Override public void unmapRegion(IMemoryRegion region) { synchronized( CPU_LOCK ) { this.memory.unmapRegion( region ); if ( out.isDebugEnabled() ) { out.debug("Unmapped memory region "+region); this.memory.dumpMemoryLayout(out); } } } @Override public void mapRegion(IMemoryRegion region) { synchronized( CPU_LOCK ) { this.memory.mapRegion( region ); if ( out.isDebugEnabled() ) { out.debug("Mapped memory region "+region); this.memory.dumpMemoryLayout( out ); } } } @Override public boolean triggerInterrupt(IInterrupt interrupt) { synchronized( CPU_LOCK ) { return cpu.triggerInterrupt( interrupt ); } } public int addOrReplaceDevice(IDevice device) throws DeviceErrorException { if (device == null) { throw new IllegalArgumentException("device must not be null"); } int existingSlot = -1; IDevice existingDevice = null; synchronized( devices ) { existingSlot = findDeviceSlotByDescriptor( device.getDeviceDescriptor() ); if ( existingSlot != -1 ) { existingDevice = devices.get( existingSlot ); } } final boolean requiresAdd; if ( existingDevice != null ) { // call beforeRemoveDevice() outside of synchronized block existingDevice.beforeRemoveDevice( this ); synchronized( devices ) { existingSlot = devices.indexOf( existingDevice ); if ( existingSlot == -1 ) { requiresAdd = true; } else { devices.remove( existingSlot ); devices.add( existingSlot , device ); requiresAdd = false; } } } else { requiresAdd = true; } if ( requiresAdd ) { return addDevice( device ); } // replaced device.afterAddDevice( this ); return existingSlot; } public List<IDevice> getDevicesByDescriptor(DeviceDescriptor desc) { if (desc == null) { throw new IllegalArgumentException("descriptor must not be null"); } final List<IDevice> result = new ArrayList<>(); synchronized( devices ) { for ( IDevice device : devices ) { if ( device.getDeviceDescriptor().matches( desc ) ) { result.add( device ); } } } return result; } private int findDeviceSlotByDescriptor(DeviceDescriptor descriptor) { int existingSlot = -1; synchronized( devices ) { int i = 0; for ( IDevice existing : devices ) { if ( existing.getDeviceDescriptor().matches( descriptor) ) { if ( existingSlot != -1 ) { throw new IllegalStateException("Found more than one existing device with descriptor "+descriptor ); } existingSlot = i; } i++; } } return existingSlot; } @Override public int addDevice(IDevice device) throws DeviceErrorException { if (device == null) { throw new IllegalArgumentException("device must not be null"); } final int slotNo; synchronized( devices ) { if ( ! device.supportsMultipleInstances() && findDeviceSlotByDescriptor( device.getDeviceDescriptor() ) != -1 ) { throw new IllegalStateException("Already one instance of device "+device.getDeviceDescriptor()+" registered."); } if ( devices.size() >= 65535 ) { throw new IllegalStateException("Already 65535 devices registered"); } slotNo = devices.size(); devices.add( device ); out.debug("Added device "+device); printDevices(); } boolean success = false; try { device.afterAddDevice( this ); success = true; } catch(RuntimeException e) { if ( e instanceof DeviceErrorException ) { throw e; } LOG.error("Device "+device+" failed in afterAddDevice() call",e); throw new DeviceErrorException( "afterAddDevice() failed: "+e.getMessage() , device , e ); } finally { if ( ! success ) { synchronized( devices ) { devices.remove( device ); } } } return slotNo; } private void printDevices() { synchronized( devices ) { int slot = 0; for ( IDevice d : devices ) { out.debug("Slot #"+slot+":"); out.debug( d.getDeviceDescriptor().toString(" ",true)); slot++; } } } @Override public List<IDevice> getDevices() { synchronized( devices ) { return new ArrayList<IDevice>( devices ); } } @Override public void removeDevice(IDevice device) { if (device == null) { throw new IllegalArgumentException("device must not be null"); } final boolean isRegistered; synchronized( devices ) { isRegistered = devices.contains( device ); } if ( isRegistered ) { try { device.beforeRemoveDevice( this ); } catch(RuntimeException e) { if ( e instanceof DeviceErrorException) { throw (DeviceErrorException) e; } LOG.error("Device "+device+" failed in beforeRemoveDevice() call",e); throw new DeviceErrorException( "breforeRemoveDevice() failed: "+e.getMessage() , device , e ); } } else { return; } synchronized( devices ) { devices.remove( device ); } if ( isRegistered ) { out.debug("Removed device "+device); printDevices(); } } @Override public EmulationSpeed getEmulationSpeed() { return emulationSpeed; } @Override public void setEmulationSpeed(final EmulationSpeed newSpeed) { if (newSpeed == null) { throw new IllegalArgumentException("speed must not be NULL."); } if ( this.emulationSpeed == newSpeed ) { return; } if ( newSpeed == EmulationSpeed.REAL_SPEED && ! isCalibrated() ) { calibrate(); } final EmulationSpeed oldSpeed = this.emulationSpeed; final boolean wasRunning = stop(); clockThread.changeSpeed( newSpeed ); this.emulationSpeed = newSpeed; listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.onEmulationSpeedChange( oldSpeed , newSpeed ); } }); if ( wasRunning ) { start(); } } @Override public boolean isCalibrated() { return clockThread.oneCycleDelay != -1; } @Override public Throwable getLastEmulationError() { return lastEmulationError; } private static <T> void safePut(BlockingQueue<T> queue, T value) { while(true) { try { queue.put(value); return; } catch (InterruptedException e) {} } } @Override public synchronized void dispose() { out.info("Disposing Emulator ..."); stop(); // terminate clock thread clockThread.sendToClockThread( Command.terminateClockThread() ); // notify listeners and remove them afterwards listenerHelper.emulatorDisposed(); // remove all devices for ( IDevice d : getDevices() ) { try { removeDevice( d ); } catch(Exception e) { LOG.error("dispose(): Failed to remove "+d); } } out.info("Emulator disposed."); } @Override public void setOutput(ILogger out) { if (out == null) { throw new IllegalArgumentException("out must not be null"); } this.loggerDelegate = out; } @Override public ILogger getOutput() { return out; } @Override public void setMemoryProtectionEnabled(boolean enabled) { checkMemoryWrites = enabled; memory.setCheckWriteAccess( enabled ); } @Override public boolean isMemoryProtectionEnabled() { return checkMemoryWrites; } @Override public void setIgnoreAccessToUnknownDevices(boolean yesNo) { this.ignoreAccessToUnknownDevices = yesNo; } protected final class CPU implements ICPU { // transient, only used inside of executeOneInstruction() code path public int currentInstructionPtr; public final MainMemory memory; /* Register A = Index 0 * Register B = Index 1 * Register C = Index 2 * Register X = Index 3 * Register Y = Index 4 * Register Z = Index 5 * Register I = Index 6 * Register J = Index 7 */ public final int[] commonRegisters = new int[ 8 ]; public int ex; public Address pc; public Address sp; public Address interruptAddress; public boolean queueInterrupts; public IInterrupt currentInterrupt; public final List<IInterrupt> interruptQueue= new ArrayList<IInterrupt>(); public int currentCycle; public CPU(MainMemory memory) { pc = sp = interruptAddress = WordAddress.ZERO; this.memory = memory; } public void populateFrom(CPU other) { System.arraycopy( other.commonRegisters , 0 , this.commonRegisters , 0 , 8 ); this.ex = other.ex; this.pc = other.pc; this.sp = other.sp; this.interruptAddress = other.interruptAddress; this.queueInterrupts = other.queueInterrupts; this.currentInterrupt = other.currentInterrupt; this.interruptQueue.clear(); this.interruptQueue.addAll(other.interruptQueue); this.currentCycle = other.currentCycle; } public boolean triggerInterrupt(IInterrupt interrupt) { if ( ! interruptsEnabled() ) { return false; } synchronized ( interruptQueue ) { if ( currentInterrupt == null && ! isQueueInterrupts() ) { currentInterrupt = interrupt; } else { // there's either already an IRQ waiting to be processed or the CPU is currently told to queue interrupts if ( interruptQueue.size() >= INTERRUPT_QUEUE_SIZE ) { throw new InterruptQueueFullException("Interrupt queue full ("+interruptQueue.size()+" entries already) , can't store "+interrupt); } setQueueInterrupts( true ); interruptQueue.add( interrupt ); } } return true; } public IInterrupt getNextProcessableInterrupt(boolean removeFromQueue) { synchronized( interruptQueue ) { if ( currentInterrupt != null ) { if ( ! removeFromQueue ) { return currentInterrupt; } final IInterrupt irq = currentInterrupt; currentInterrupt = null; return irq; } if ( ! interruptQueue.isEmpty() && ! isQueueInterrupts() ) { if ( removeFromQueue ) { return interruptQueue.remove(0); } return interruptQueue.get(0); } } return null; } public void reset() { currentCycle = 0; queueInterrupts = false; interruptQueue.clear(); sp = pc = interruptAddress = WordAddress.ZERO; ex = 0; for ( int i = 0 ; i < commonRegisters.length ; i++ ) { commonRegisters[i]=0; } } @Override public Address getPC() { return pc; } @Override public Address getSP() { return sp; } @Override public int getEX() { return ex; } @Override public Address getInterruptAddress() { return interruptAddress; } @Override public int getCurrentCycleCount() { return currentCycle; } @Override public void setRegisterValue(Register reg, int value) { switch( reg ) { case A: commonRegisters[0] = value & 0xffff; break; case B: commonRegisters[1] = value & 0xffff; break; case C: commonRegisters[2] = value & 0xffff; break; case EX: ex = value & 0xffff; break; case I: commonRegisters[6] = value & 0xffff; break; case J: commonRegisters[7] = value & 0xffff; break; case PC: pc = Address.wordAddress( value & 0xffff ); break; case SP: sp = Address.wordAddress( value & 0xffff ); break; case X: commonRegisters[3] = value & 0xffff; break; case Y: commonRegisters[4] = value & 0xffff; break; case Z: commonRegisters[5] = value & 0xffff; break; default: throw new RuntimeException("Unreachable code reached: "+reg); } } @Override public int getRegisterValue(Register reg) { switch( reg ) { case A: return commonRegisters[0]; case B: return commonRegisters[1]; case C: return commonRegisters[2]; case EX: return ex; case I: return commonRegisters[6]; case J: return commonRegisters[7]; case PC: return pc.getWordAddressValue(); case SP: return sp.getWordAddressValue(); case X: return commonRegisters[3]; case Y: return commonRegisters[4]; case Z: return commonRegisters[5]; default: throw new RuntimeException("Unreachable code reached: "+reg); } } @Override public void setQueueInterrupts(boolean yesNo) { this.queueInterrupts = yesNo; } @Override public boolean isQueueInterrupts() { return queueInterrupts; } @Override public boolean interruptsEnabled() { return interruptAddress != null && interruptAddress.getValue() != 0; } @Override public List<IInterrupt> getInterruptQueue() { return interruptQueue; } // ============== public int executeInstruction() { currentInstructionPtr = pc.getValue(); final int instructionWord = readNextWordAndAdvance(); final int opCode = (instructionWord & 0x1f); /* * |--- Basic opcodes (5 bits) ---------------------------------------------------- * |C | VAL | NAME | DESCRIPTION * +---+------+----------+--------------------------------------------------------- * |- | 0x00 | n/a | special instruction - see below * |1 | 0x01 | SET b, a | sets b to a * |2 | 0x02 | ADD b, a | sets b to b+a, sets EX to 0x0001 if there's an overflow, 0x0 otherwise * |2 | 0x03 | SUB b, a | sets b to b-a, sets EX to 0xffff if there's an underflow, 0x0 otherwise * |2 | 0x04 | MUL b, a | sets b to b*a, sets EX to ((b*a)>>16)&0xffff (treats b, a as unsigned) * |2 | 0x05 | MLI b, a | like MUL, but treat b, a as signed * |3 | 0x06 | DIV b, a | sets b to b/a, sets EX to ((b<<16)/a)&0xffff. if a==0, sets b and EX to 0 instead. (treats b, a as unsigned) * |3 | 0x07 | DVI b, a | like DIV, but treat b, a as signed. Rounds towards 0 * |3 | 0x08 | MOD b, a | sets b to b%a. if a==0, sets b to 0 instead. * |3 | 0x09 | MDI b, a | like MOD, but treat b, a as signed. Rounds towards 0 * |1 | 0x0a | AND b, a | sets b to b&a * |1 | 0x0b | BOR b, a | sets b to b|a * |1 | 0x0c | XOR b, a | sets b to b^a * |2 | 0x0d | SHR b, a | sets b to b>>>a, sets EX to ((b<<16)>>a)&0xffff (logical shift) * |2 | 0x0e | ASR b, a | sets b to b>>a, sets EX to ((b<<16)>>>a)&0xffff (arithmetic shift) (treats b as signed) * |2 | 0x0f | SHL b, a | sets b to b<<a, sets EX to ((b<<a)>>16)&0xffff * | * |2+| 0x10 | IFB b, a | performs next instruction only if (b&a)!=0 * |2+| 0x11 | IFC b, a | performs next instruction only if (b&a)==0 * |2+| 0x12 | IFE b, a | performs next instruction only if b==a * |2+| 0x13 | IFN b, a | performs next instruction only if b!=a * |2+| 0x14 | IFG b, a | performs next instruction only if b>a * |2+| 0x15 | IFA b, a | performs next instruction only if b>a (signed) * |2+| 0x16 | IFL b, a | performs next instruction only if b<a * |2+| 0x17 | IFU b, a | performs next instruction only if b<a (signed) * |- | 0x18 | - | * |- | 0x19 | - | * |3 | 0x1a | ADX b, a | sets b to b+a+EX, sets EX to 0x0001 if there is an over-flow, 0x0 otherwise * |3 | 0x1b | SBX b, a | sets b to b-a+EX, sets EX to 0xFFFF if there is an under-flow, 0x0 otherwise * |- | 0x1c | - | * |- | 0x1d | - | * |2 | 0x1e | STI b, a | sets b to a, then increases I and J by 1 * |2 | 0x1f | STD b, a | sets b to a, then decreases I and J by 1 * +---+------+----------+---------------------------------------------------------- */ switch( opCode ) { case 0x00: return handleSpecialOpCode( instructionWord ); case 0x01: return handleSET( instructionWord ); case 0x02: return handleADD( instructionWord ); case 0x03: return handleSUB( instructionWord ); case 0x04: return handleMUL( instructionWord ); case 0x05: return handleMLI( instructionWord ); case 0x06: return handleDIV( instructionWord ); case 0x07: return handleDVI( instructionWord ); case 0x08: return handleMOD( instructionWord ); case 0x09: return handleMDI( instructionWord ); case 0x0a: return handleAND( instructionWord ); case 0x0b: return handleBOR( instructionWord ); case 0x0c: return handleXOR( instructionWord ); case 0x0d: return handleSHR( instructionWord ); case 0x0e: return handleASR( instructionWord ); case 0x0f: return handleSHL( instructionWord ); case 0x10: return handleIFB( instructionWord ); case 0x11: return handleIFC( instructionWord ); case 0x12: return handleIFE( instructionWord ); case 0x13: return handleIFN( instructionWord ); case 0x14: return handleIFG( instructionWord ); case 0x15: return handleIFA( instructionWord ); case 0x16: return handleIFL( instructionWord ); case 0x17: return handleIFU( instructionWord ); case 0x18: case 0x19: return handleUnknownOpCode( instructionWord ); case 0x1a: return handleADX( instructionWord ); case 0x1b: return handleSBX( instructionWord ); case 0x1c: case 0x1d: return handleUnknownOpCode( instructionWord ); case 0x1e: return handleSTI( instructionWord ); case 0x1f: return handleSTD( instructionWord ); default: return handleUnknownOpCode( instructionWord ); } } private int handleSTD(int instructionWord) { // sets b to a, then decreases I and J by 1 // a,b,c,x,y,z,i,j final OperandDesc source = loadSourceOperand( instructionWord ); final int cycles = 2+storeTargetOperand( instructionWord , source.value )+source.cycleCount; int address = --commonRegisters[6]; // registers[6]-=1; <<< I if ( address < 0 ) { commonRegisters[6] = (int) WordAddress.MAX_ADDRESS; } address = --commonRegisters[7]; // registers[7]-=1; <<< J if ( address < 0 ) { commonRegisters[7]= (int) WordAddress.MAX_ADDRESS; } return cycles; } private int handleSTI(int instructionWord) { // sets b to a, then increases I and J by 1 // a,b,c,x,y,z,i,j final OperandDesc source = loadSourceOperand( instructionWord ); final int cycles = 2+storeTargetOperand( instructionWord , source.value )+source.cycleCount; int newWordAddress = ++commonRegisters[6]; // registers[6]+=1; <<< I if ( newWordAddress > WordAddress.MAX_ADDRESS ) { commonRegisters[6] = 0; } newWordAddress = ++commonRegisters[7]; // registers[7]+=1; <<< J if ( newWordAddress > WordAddress.MAX_ADDRESS ) { commonRegisters[7] = 0; } return cycles; } private int handleSBX(int instructionWord) { // sets b to b-a+EX, sets EX to 0xFFFF if there is an under-flow, 0x0001 if there's an overflow, 0x0 otherwise OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int b = target.value; final int a = source.value; int result = b-a+ex; if ( result < 0 ) { ex = 0xffff; } else if ( result > 0xffff ) { ex = 0x0001; } else { ex = 0; } if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result return 3+source.cycleCount; } return 3+storeTargetOperand( instructionWord , result & 0xffff )+source.cycleCount; } private int handleADX(int instructionWord) { // sets b to b+a+EX, sets EX to 0x0001 if there is an over-flow, 0x0 otherwise OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc = target.value + source.value + ex; if ( acc > 0xffff) { ex = 0x0001; } else { ex = 0; } if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result return 3+source.cycleCount; } return 3+storeTargetOperand( instructionWord , acc & 0xffff )+source.cycleCount; } private int handleUnknownOpCode(int instructionWord) { final Disassembler dis = new Disassembler(); // assume worst-case , each instruction only is one word final int instructionCount = Address.calcDistanceInBytes( Address.wordAddress( 0 ) , pc ).toSizeInWords().getValue(); List<DisassembledLine> lines = dis.disassemble( memory , Address.wordAddress( 0 ) , instructionCount , true ); for (DisassembledLine line : lines) { out.info( Misc.toHexString( line.getAddress() )+": "+line.getContents()); } Address lastValid = lastValidInstruction; if ( lastValid == null ) { lastValid = pc; } final String msg = "Unknown opcode 0x"+Misc.toHexString( instructionWord )+ " at address "+"0x"+Misc.toHexString( pc )+ " (last valid PC: "+Misc.toHexString( lastValid )+")"; out.warn(msg ); throw new UnknownOpcodeException( msg , instructionWord & 0xffff ); } private int handleIFU(int instructionWord) { // performs next instruction only if b<a (signed) OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , true ); int penalty = 0; if ( signed( target.value ) >= signed( source.value ) ) { penalty = handleConditionFailure(); } return 2+target.cycleCount+source.cycleCount+penalty; } private int handleConditionFailure() { boolean skippedInstructionIsConditional = isConditionalInstruction( memory.read( currentInstructionPtr ) ); currentInstructionPtr += calculateInstructionSizeInWords( currentInstructionPtr , memory ); if ( skippedInstructionIsConditional ) { do { skippedInstructionIsConditional = isConditionalInstruction( memory.read( currentInstructionPtr ) ); currentInstructionPtr += calculateInstructionSizeInWords( currentInstructionPtr , memory ); } while ( skippedInstructionIsConditional ); return 2; } return 1; } private int handleIFL(int instructionWord) { // performs next instruction only if b<a OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , true ); int penalty = 0; if ( target.value >= source.value ) { penalty = handleConditionFailure(); } return 2+target.cycleCount+source.cycleCount+penalty; } private int handleIFA(int instructionWord) { // performs next instruction only if b>a (signed) OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , true ); int penalty = 0; if ( signed( target.value ) <= signed( source.value ) ) { penalty = handleConditionFailure(); } return 2+target.cycleCount+source.cycleCount+penalty; } private int handleIFG(int instructionWord) { // performs next instruction only if b>a OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , true ); int penalty=0; if ( target.value <= source.value ) { penalty = handleConditionFailure(); } return 2+target.cycleCount+source.cycleCount+penalty; } private int handleIFN(int instructionWord) { // performs next instruction only if b!=a OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , true ); int penalty = 0; if ( target.value == source.value ) { penalty = handleConditionFailure(); } return 2+target.cycleCount+source.cycleCount+penalty; } private int handleIFE(int instructionWord) { // performs next instruction only if b==a OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , true ); int penalty=0; if ( target.value != source.value ) { penalty = handleConditionFailure(); } return 2+target.cycleCount+source.cycleCount+penalty; } private int handleIFC(int instructionWord) { // performs next instruction only if (b&a)==0 OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , true ); int penalty = 0; if ( (target.value & source.value) != 0 ) { penalty = handleConditionFailure(); } return 2+target.cycleCount+source.cycleCount+penalty; } private int handleIFB(int instructionWord) { // performs next instruction only if (b&a)!=0 OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , true ); int penalty=0; if ( (target.value & source.value) == 0 ) { penalty = handleConditionFailure(); } return 2+target.cycleCount+source.cycleCount+penalty; } private int handleSHL(int instructionWord) { // sets b to b<<a, sets EX to ((b<<a)>>16)&0xffff OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc = target.value << source.value; ex = (( target.value << source.value)>>16 ) & 0xffff; if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result return 1+source.cycleCount; } return 1+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleASR(int instructionWord) { // ASR b,a // arithmetic shift, sign extension !!! // sets b to b>>a, sets EX to ((b<<16)>>>a)&0xffff (arithmetic shift) (treats b as signed) OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc = signed( target.value ) >> source.value; ex = (( signed( target.value ) << 16) >>> source.value ) & 0xffff; if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result return 1+source.cycleCount; } return 1+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleSHR(int instructionWord) { // sets b to b>>>a, sets EX to ((b<<16)>>a)&0xffff (logical shift) OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc = target.value >>> source.value; ex = (( target.value << 16) >> source.value ) & 0xffff; if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result return 1+source.cycleCount; } return 1+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleXOR(int instructionWord) { // sets b to b^a OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc = target.value ^ source.value; return 1+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleBOR(int instructionWord) { // sets b to b|a OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc = target.value | source.value; return 1+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleAND(int instructionWord) { // sets b to b&a OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc = target.value & source.value; return 1+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleMDI(int instructionWord) { // like MOD, but treat b, a as signed. Rounds towards 0 OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc; if ( source.value == 0 ) { acc=0; } else { acc = signed( target.value ) % signed( source.value ); } return 3+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleMOD(int instructionWord) { // sets b to b%a. if a==0, sets b to 0 instead. OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc; if ( source.value == 0 ) { acc=0; } else { acc = target.value % source.value; } return 3+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleDVI(int instructionWord) { // e DIV, but treat b, a as signed. Rounds towards 0 OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc; if ( source.value == 0 ) { ex = 0; acc=0; } else { acc = signed( target.value ) / signed( source.value ); // ((b<<16)/a)&0xffff ex = (( signed( target.value ) << 16) / signed( source.value) )& 0xffff; } if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result return 3+source.cycleCount; } return 3+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleDIV(int instructionWord) { /* set b (TARGET) ,a (SOURCE) * sets b to b/a, sets EX to ((b<<16)/a)&0xffff. if a==0, sets b and EX to 0 instead. (treats b, a as unsigned) */ OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc; if ( source.value == 0 ) { ex = 0; acc=0; } else { acc = target.value / source.value; long tv = target.value; long sv = source.value; ex = (int) ( (( tv << 16) / sv ) & 0xffff); } if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result return 3+source.cycleCount; } return 3+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleMLI(int instructionWord) { // like MUL, but treat b, a as signed OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int a = signed( target.value ); final int b = signed( source.value ); final int acc = a * b; ex = ((a * b) >> 16 ) & 0xffff; if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result return 2+source.cycleCount; } return 2+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int signed( int value) { if ( ( value & ( 1 << 15 ) ) != 0 ) { // MSB set => negative value return 0xffff0000 | value; } return value; } private int handleMUL(int instructionWord) { // sets b to b*a, sets EX to ((b*a)>>16)&0xffff (treats b, a as unsigned) OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc = target.value * source.value; ex = ((target.value * source.value) >> 16 ) & 0xffff; if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result return 2+source.cycleCount; } return 2+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleSUB(int instructionWord) { // sets b to b-a, sets EX to 0xffff if there's an underflow, 0x0 otherwise OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc = target.value - source.value; if ( acc < 0 ) { ex = 0xffff; } else { ex = 0; } if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result return 2+source.cycleCount; } return 2+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleADD(int instructionWord) { // sets b to b+a, sets EX to 0x0001 if there's an overflow, 0x0 otherwise OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc = target.value + source.value; if ( acc > 0xffff) { ex = 0x0001; } else { ex = 0; } if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result return 2+source.cycleCount; } return 2+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleSET(int instructionWord) { final OperandDesc desc = loadSourceOperand( instructionWord ); return 1+storeTargetOperand( instructionWord , desc.value ) + desc.cycleCount; } private int handleSpecialOpCode(int instructionWord) { final int opCode = ( instructionWord >>> 5 ) &0x1f; /* * |--- Special opcodes: (5 bits) -------------------------------------------------- * | C | VAL | NAME | DESCRIPTION * |---+------+-------+------------------------------------------------------------- * | - | 0x00 | n/a | reserved for future expansion * | 3 | 0x01 | JSR a | pushes the address of the next instruction to the stack, then sets PC to a * | - | 0x02 | - | * | - | 0x03 | - | * | - | 0x04 | - | * | - | 0x05 | - | * | - | 0x06 | - | * | 9 | 0x07 | HCF a | use sparingly * | 4 | 0x08 | INT a | triggers a software interrupt with message a * | 1 | 0x09 | IAG a | sets a to IA * | 1 | 0x0a | IAS a | sets IA to a * | 3 | 0x0b | IAP a | if IA is 0, does nothing, otherwise pushes IA to the stack, * | | | | then sets IA to a * | 2 | 0x0c | IAQ a | if a is nonzero, interrupts will be added to the queue * | | | | instead of triggered. if a is zero, interrupts will be * | | | | triggered as normal again * | - | 0x0d | - | * | - | 0x0e | - | * | - | 0x0f | - | * | 2 | 0x10 | HWN a | sets a to number of connected hardware devices * | 4 | 0x11 | HWQ a | sets A, B, C, X, Y registers to information about hardware a * | | | | A+(B<<16) is a 32 bit word identifying the hardware id * | | | | C is the hardware version * | | | | X+(Y<<16) is a 32 bit word identifying the manufacturer * | 4+| 0x12 | HWI a | sends an interrupt to hardware a * | - | 0x13 | - | * | - | 0x14 | - | * | - | 0x15 | - | * | - | 0x16 | - | * | - | 0x17 | - | * | - | 0x18 | - | * | - | 0x19 | - | * | - | 0x1a | - | * | - | 0x1b | - | * | - | 0x1c | - | * | - | 0x1d | - | * | - | 0x1e | - | * | - | 0x1f | - | * |---+------+-------+------------------------------------------------------------- */ switch( opCode ) { case 0x00: return handleUnknownOpCode( instructionWord ); case 0x01: return handleJSR( instructionWord ); case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: return handleUnknownOpCode( instructionWord ); case 0x07: // HCF was removed in spec 1.7 // return handleHCF( instructionWord ); return handleUnknownOpCode( instructionWord ); case 0x08: return handleINT( instructionWord ); case 0x09: return handleIAG( instructionWord ); case 0x0a: return handleIAS( instructionWord ); case 0x0b: return handleRFI( instructionWord ); case 0x0c: return handleIAQ( instructionWord ); case 0x0d: case 0x0e: case 0x0f: return handleUnknownOpCode( instructionWord ); case 0x10: return handleHWN( instructionWord ); case 0x11: return handleHWQ( instructionWord ); case 0x12: return handleHWI( instructionWord ); case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: case 0x1f: default: return handleUnknownOpCode( instructionWord ); } } private int handleHWI(int instructionWord) { final OperandDesc operand = loadSourceOperand(instructionWord); final int hardwareSlot = operand.value; final IDevice device = getDeviceForSlot( hardwareSlot ); final int cyclesConsumed; if ( device == null ) { if ( ! ignoreAccessToUnknownDevices ) { LOG.error("handleHWI(): No device at slot #"+hardwareSlot); out.warn("No device at slot #"+hardwareSlot); throw new InvalidDeviceSlotNumberException("No device at slot #"+hardwareSlot); } cyclesConsumed = 0; } else { try { cyclesConsumed = device.handleInterrupt( Emulator.this, this , this.memory ); } catch(RuntimeException e) { if ( e instanceof DeviceErrorException) { throw e; } LOG.error("handleHWI(): Device "+device+" failed in handleInterrupt(): "+e.getMessage() , e ); throw new DeviceErrorException("Device "+device+" failed in handleInterrupt(): "+e.getMessage() , device , e ); } } return 4+operand.cycleCount+cyclesConsumed; } /* * * b is always handled by the processor after a, and is the lower five bits. * In bits (in LSB-0 format), a basic instruction has the format: * * aaaaaabbbbbooooo * * SET b,a * * b = TARGET operand * a = SOURCE operand * * --- Values: (5/6 bits) --------------------------------------------------------- * * | C | VALUE | DESCRIPTION * +---+-----------+---------------------------------------------------------------- * | 0 | 0x00-0x07 | register (A, B, C, X, Y, Z, I or J, in that order) * | 0 | 0x08-0x0f | [register] * | 1 | 0x10-0x17 | [register + next word] * | 0 | 0x18 | (PUSH / [--SP]) if in TARGET, or (POP / [SP++]) if in SOURCE * | 0 | 0x19 | [SP] / PEEK * | 1 | 0x1a | [SP + next word] / PICK n * | 0 | 0x1b | SP * | 0 | 0x1c | PC * | 0 | 0x1d | EX * | 1 | 0x1e | [next word] * | 1 | 0x1f | next word (literal) * | 0 | 0x20-0x3f | literal value 0xffff-0x1e (-1..30) (literal) (only for SOURCE) * +---+-----------+---------------------------------------------------------------- */ private int storeTargetOperand(int instructionWord,int value) { return storeTargetOperand( instructionWord , value , false ); } private int storeTargetOperand(int instructionWord,int value,boolean isSpecialOpcode) { final int operandBits; /* * Special opcodes always have their lower five bits unset, have one value and a * five bit opcode. * * In binary, they have the format: aaaaaaooooo00000 */ if ( isSpecialOpcode ) { operandBits = (instructionWord >>> 10) & ( 1+2+4+8+16+32); } else { operandBits = (instructionWord >>> 5) & ( 1+2+4+8+16); } if ( operandBits <= 07 ) { commonRegisters[ operandBits ] = value & 0xffff; return 0; } if ( operandBits <= 0x0f ) { memory.write( commonRegisters[ operandBits - 0x08 ] , value); return 1; } if ( operandBits <= 0x17 ) { final int nextWord = readNextWordAndAdvance(); writeMemoryWithOffsetAndWrapAround( commonRegisters[ operandBits - 0x10 ] , nextWord , value); return 1; } switch( operandBits ) { case 0x18: // (PUSH / [--SP]) if in b, or (POP / [SP++]) if in a push( value ); return 0; case 0x19: // PEEK/[SP] memory.write( sp , value ); return 0; case 0x1a: int nextWord = readNextWordAndAdvance(); Address dst = sp.plus( Address.wordAddress( nextWord ) , true); memory.write( dst , value ); return 1; case 0x1b: sp = Address.wordAddress( value & 0xffff ); return 0; case 0x1c: // PC currentInstructionPtr = value & 0xffff; return 0; case 0x1d: ex = value & 0xffff; return 0; case 0x1e: nextWord = readNextWordAndAdvance(); memory.write( nextWord , value); return 1; default: return handleIllegalTargetOperand(instructionWord); // assignment to literal value } } private int readNextWordAndAdvance() { final int word = memory.read( currentInstructionPtr ); currentInstructionPtr = (currentInstructionPtr+1) & 0xffff; return word; } private OperandDesc loadSourceOperand(int instructionWord) { /* SET b,a * * b = TARGET operand * a = SOURCE operand * * Special opcodes always have their lower five bits unset, have one value and a * five bit opcode. In binary, they have the format: aaaaaaooooo00000 * The value (a) is in the same six bit format as defined earlier. */ final int operandBits= (instructionWord >>> 10) & ( 1+2+4+8+16+32); if ( operandBits <= 0x07 ) { return operandDesc( commonRegisters[ operandBits ] ); } if ( operandBits <= 0x0f ) { return operandDesc( memory.read( commonRegisters[ operandBits - 0x08 ] ) , 1 ); } if ( operandBits <= 0x17 ) { final int nextWord = readNextWordAndAdvance(); return operandDesc( readMemoryWithOffsetAndWrapAround( commonRegisters[ operandBits - 0x10 ] , nextWord ) ,1 ); } switch( operandBits ) { case 0x18: // (PUSH / [--SP]) if in b, or (POP / [SP++]) if in a final OperandDesc tmp = operandDesc( memory.read( sp ) ); sp = sp.incrementByOne(true); return tmp; case 0x19: return operandDesc( memory.read( sp ) , 1 ); case 0x1a: int nextWord = readNextWordAndAdvance(); final Address dst = sp.plus( Address.wordAddress( nextWord ) , true ); return operandDesc( memory.read( dst ) , 1 ); case 0x1b: return operandDesc( sp.getValue() ); case 0x1c: return operandDesc( currentInstructionPtr ); case 0x1d: return operandDesc( ex ); case 0x1e: nextWord = readNextWordAndAdvance(); return operandDesc( memory.read( nextWord ) ,1 ); case 0x1f: return operandDesc( readNextWordAndAdvance() , 1 ); } // literal value: -1...30 ( 0x20 - 0x3f ) return operandDesc( ( operandBits - 0x21 ) , 0 ); } private int readMemoryWithOffsetAndWrapAround(int address,int offset) { int realAddress =(int) ( ( address + offset ) % (WordAddress.MAX_ADDRESS +1 ) ); return memory.read( realAddress ); } private void writeMemoryWithOffsetAndWrapAround(int address,int offset,int value) { int realAddress =(int) ( ( address + offset ) % (WordAddress.MAX_ADDRESS +1 ) ); memory.write( realAddress , value ); } protected final boolean isEXTargetOperand(int instructionWord) { final int operandBits; if ( (instructionWord & 0b11111) == 0 ) { // special instruction operandBits= (instructionWord >>> 10) & ( 1+2+4+8+16+32); } else { operandBits= (instructionWord >>> 5) & ( 1+2+4+8+16); } return operandBits == 0x1d; } /** * * @param instructionWord * @param specialInstruction * @param performIncrementDecrement Whether this invocation should also increment/decrement registers as necessary or * whether this is handled by the caller (because a subsequent STORE will be performed ) * @return */ protected OperandDesc loadTargetOperand(int instructionWord,boolean specialInstruction,boolean performIncrementDecrement) { /* * SET b,a * * b = TARGET operand * a = SOURCE operand * * SOURCE is always handled by the processor BEFORE TARGET, and is the lower five bits. * In bits (in LSB-0 format), a basic instruction has the format: * * aaaaaabbbbbooooo * * SPECIAL opcodes always have their lower five bits unset, have one value and a * five bit opcode. In binary, they have the format: * * aaaaaaooooo00000 * * The value (a) is in the same six bit format as defined earlier. */ final int operandBits; if ( specialInstruction ) { operandBits= (instructionWord >>> 10) & ( 1+2+4+8+16+32); } else { operandBits= (instructionWord >>> 5) & ( 1+2+4+8+16); } if ( operandBits <= 0x07 ) { return operandDesc( commonRegisters[ operandBits ] ); } if ( operandBits <= 0x0f ) { return operandDesc( memory.read( commonRegisters[ operandBits - 0x08 ] ) , 1 ); } if ( operandBits <= 0x17 ) { final int nextWord; if ( performIncrementDecrement ) { nextWord = readNextWordAndAdvance(); } else { nextWord = memory.read( currentInstructionPtr ); } return operandDesc( readMemoryWithOffsetAndWrapAround( commonRegisters[ operandBits - 0x10 ] , nextWord ) ,1 ); } switch( operandBits ) { case 0x18: // (PUSH / [--SP++]) if in b return operandDesc( memory.read( sp.decrementByOne() ) , 1 ); case 0x19: return operandDesc( memory.read( sp ) , 1 ); case 0x1a: int nextWord = 0; if ( performIncrementDecrement ) { nextWord = readNextWordAndAdvance(); } else { nextWord = memory.read( currentInstructionPtr ); } final Address dst = sp.plus( Address.wordAddress( nextWord ) , true ); return operandDesc( memory.read( dst ) , 1 ); case 0x1b: return operandDesc( sp.getValue() ); case 0x1c: return operandDesc( currentInstructionPtr ); case 0x1d: return operandDesc( ex ); case 0x1e: if ( performIncrementDecrement ) { nextWord = readNextWordAndAdvance(); } else { nextWord = memory.read( currentInstructionPtr ); } return operandDesc( memory.read( nextWord ) ,1 ); case 0x1f: if ( performIncrementDecrement ) { nextWord = readNextWordAndAdvance(); } else { nextWord = memory.read( currentInstructionPtr ); } return operandDesc( nextWord , 1 ); } // literal value: -1...30 ( 0x20 - 0x3f ) return operandDesc( operandBits - 0x21 , 0 ); } private int handleHWQ(int instructionWord) { // Sets A, B, C, X, Y registers to information about hardware a. final OperandDesc operand = loadSourceOperand(instructionWord); final int hardwareSlot = operand.value; final IDevice device = getDeviceForSlot( hardwareSlot ); if ( device == null ) { if ( ! ignoreAccessToUnknownDevices ) { LOG.error("handleHWQ(): No device at slot #"+hardwareSlot); out.warn("No device at slot #"+hardwareSlot); throw new InvalidDeviceSlotNumberException("No device at slot #"+hardwareSlot); } commonRegisters[0] = 0xffff; commonRegisters[1] = 0xffff; commonRegisters[2] = 0xffff; commonRegisters[3] = 0xffff; commonRegisters[4] = 0xffff; } else { /* sets A, B, C, X, Y registers to information about hardware a * * A+(B<<16) is a 32 bit word identifying the hardware id * C is the hardware version * X+(Y<<16) is a 32 bit word identifying the manufacturer */ /* A+(B<<16) is a 32 bit word identifying the hardware id * * A = LSB hardware ID (16 bit) * B = MSB hardware ID (16 bit) * C = hardware version * X = LSB manufacturer ID (16 bit) * Y = MSB manufacturer ID (16 bit) */ final DeviceDescriptor descriptor = device.getDeviceDescriptor(); commonRegisters[0] = (int) descriptor.getID() & 0xffff; commonRegisters[1] = (int) ( ( descriptor.getID() >>> 16 ) & 0xffff ); commonRegisters[2] = descriptor.getVersion() & 0xffff; commonRegisters[3] = (int) descriptor.getManufacturer() & 0xffff; commonRegisters[4] = (int) ( ( descriptor.getManufacturer() >>> 16 ) & 0xffff ); } return 4+operand.cycleCount; } private int handleHWN(int instructionWord) { // sets a to number of connected hardware devices final int deviceCount; synchronized( devices ) { deviceCount=devices.size(); } return 2 + storeTargetOperand( instructionWord , deviceCount , true ); } private int handleIAQ(int instructionWord) { /* if a is nonzero, interrupts will be added to the queue * instead of triggered. if a is zero, interrupts will be * triggered as normal again */ final OperandDesc operand = loadSourceOperand( instructionWord ); setQueueInterrupts( operand.value != 0 ); return 2+operand.cycleCount; } private int handleRFI(int instructionWord) { /* * 3 | 0x0b | RFI a | disables interrupt queueing, pops A from the stack, then | | | pops PC from the stack */ setQueueInterrupts( false ); commonRegisters[0] = pop(); // pop A from stack currentInstructionPtr = pop(); // pop PC from stack return 3; } private int handleIllegalTargetOperand(int instructionWord) { final String msg = "Illegal target operand in instruction word 0x"+ Misc.toHexString( instructionWord )+" at address 0x"+Misc.toHexString( pc ); LOG.error("handleIllegalTargetOperand(): "+msg); out.warn( msg); throw new InvalidTargetOperandException( msg ); } private int handleIAS(int instructionWord) { // IAS a => sets IA to a final OperandDesc operand = loadSourceOperand( instructionWord ); interruptAddress = Address.wordAddress( operand.value ); return 1+operand.cycleCount; } private int handleIAG(int instructionWord) { // IAG a => sets A to IA return 1+storeTargetOperand( instructionWord , interruptAddress.getValue() , true ); } private int handleINT(int instructionWord) { final OperandDesc operand = loadSourceOperand( instructionWord ); triggerInterrupt(new SoftwareInterrupt( operand.value )); return 4+operand.cycleCount; } private int handleJSR(int instructionWord) { // pushes the address of the next instruction to the stack, then sets PC to a OperandDesc source= loadSourceOperand( instructionWord ); push( currentInstructionPtr ); currentInstructionPtr = source.value; return 3+source.cycleCount; } private int pop() { // SET a, [SP++] final int result = memory.read( sp ); sp= sp.incrementByOne(true); return result; } private void push(int value) { // SET [--SP] , blubb sp = sp.decrementByOne(); memory.write( sp , value ); } public boolean maybeProcessOneInterrupt() { if ( interruptsEnabled() ) { final IInterrupt irq = getNextProcessableInterrupt( true ); if ( irq != null ) { // push PC to stack // SET [ --SP ] , PC push( pc.getValue() ); // push A to stack push( commonRegisters[0] ); pc = interruptAddress; commonRegisters[0] = irq.getMessage() & 0xffff; return true; } } return false; } } // end of class: CPU }
src/main/java/de/codesourcery/jasm16/emulator/Emulator.java
/** * Copyright 2012 Tobias Gierke <[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 de.codesourcery.jasm16.emulator; import java.util.*; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import org.apache.log4j.Logger; import de.codesourcery.jasm16.*; import de.codesourcery.jasm16.ast.OperandNode.OperandPosition; import de.codesourcery.jasm16.disassembler.DisassembledLine; import de.codesourcery.jasm16.disassembler.Disassembler; import de.codesourcery.jasm16.emulator.devices.*; import de.codesourcery.jasm16.emulator.exceptions.*; import de.codesourcery.jasm16.emulator.memory.*; import de.codesourcery.jasm16.utils.Misc; /** * DCPU-16 emulator. * * @author [email protected] */ public final class Emulator implements IEmulator { private static final Logger LOG = Logger.getLogger(Emulator.class); private static final boolean DEBUG = false; /** * Maximum number of interrupts the emulator's interrupt queue may hold. */ public static final int INTERRUPT_QUEUE_SIZE = 256; private static final boolean DEBUG_LISTENER_PERFORMANCE = false; private final IdentityHashMap<IEmulationListener,Long> listenerPerformance = new IdentityHashMap<IEmulationListener,Long>(); private final ClockThread clockThread; private final ListenerHelper listenerHelper = new ListenerHelper(); private static final AtomicLong cmdId = new AtomicLong(0); /** * Worker thread command types. * * @author [email protected] */ protected enum CommandType { START, STOP, TERMINATE, SPEED_CHANGE; } /** * Command to control the emulation's worker thread responsible * for the actual DCPU-16 instruction execution. * * <p>Command senders may request an acknowledge message * from the worker thread and block until it is received.Each * command carries a unique ID so that an * acknowledge message can be matched with the corresponding command.</p> * * @author [email protected] */ protected static final class Command { private final long id = cmdId.incrementAndGet(); private final Object payload; private final CommandType type; private final boolean requiresACK; public static Command terminateClockThread() { return new Command(CommandType.TERMINATE , true ); } public static Command stopCommandWithoutACK() { return new Command(CommandType.STOP,false); } public static Command stopCommand() { return new Command(CommandType.STOP,true); } public static Command startCommand() { return new Command(CommandType.START, true); } public static Command changeSpeedCommand(EmulationSpeed newSpeed) { return new Command(CommandType.SPEED_CHANGE,true,newSpeed); } protected Command(CommandType type, boolean requiresACK) { this(type,requiresACK,null); } protected Command(CommandType type, boolean requiresACK,Object payload) { this.type = type; this.payload = payload; this.requiresACK = requiresACK; } public Object getPayload() { return payload; } public boolean hasType(CommandType t) { return t.equals( this.type ); } public boolean requiresACK() { return requiresACK; } public boolean isTerminateCommand() { return type == CommandType.TERMINATE; } public boolean isStopCommand() { return type == CommandType.STOP|| type == CommandType.TERMINATE; } /** * Check whether this is a command that should make the * worker thread enter it's main <code>while()</code> loop. * * <p>When this method returns <code>true</code> , it does <b>not</b> mean * that the worker thread will actually start executing instructions , it will * only wake it up. * </p> * @return */ public boolean isStartWorkerMainLoopCommand() { return ! isStopCommand() || isTerminateCommand(); } public long getId() { return id; } @Override public String toString() { return type+" ( "+id+" , requires_ack="+requiresACK+" )"; } } /** * Helper to manage IEmulationListeners. * This class manages multiple internal lists , each for a specific listener type. * That way we avoid having to look-up listeners with a specific type each * time a notification needs to be send. * * @author [email protected] */ protected final class ListenerHelper { // @GuardedBy( emuListeners ) private final List<IEmulationListener> emuListeners = new ArrayList<IEmulationListener>(); // @GuardedBy( emuListeners ) private final List<IEmulationListener> beforeCommandExecListeners = new ArrayList<IEmulationListener>(); // @GuardedBy( emuListeners ) private final List<IEmulationListener> continuousModeBeforeCommandExecListeners = new ArrayList<IEmulationListener>(); // @GuardedBy( emuListeners ) private final List<IEmulationListener> afterCommandExecListeners = new ArrayList<IEmulationListener>(); // @GuardedBy( emuListeners ) private final List<IEmulationListener> continuousModeAfterCommandExecListeners = new ArrayList<IEmulationListener>(); private final IEmulationListenerInvoker BEFORE_COMMAND_INVOKER = new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.beforeCommandExecution( emulator ); } }; public void addEmulationListener(IEmulationListener listener) { if (listener == null) { throw new IllegalArgumentException("listener must not be NULL."); } synchronized (emuListeners) { emuListeners.add( listener ); if ( listener.isInvokeBeforeCommandExecution() ) { beforeCommandExecListeners.add( listener ); if ( listener.isInvokeAfterAndBeforeCommandExecutionInContinuousMode() ) { continuousModeBeforeCommandExecListeners.add( listener ); } } if ( listener.isInvokeAfterCommandExecution() ) { afterCommandExecListeners.add( listener ); if ( listener.isInvokeAfterAndBeforeCommandExecutionInContinuousMode() ) { continuousModeAfterCommandExecListeners.add( listener ); } } } } public void removeAllEmulationListeners() { synchronized (emuListeners) { removeAllNonHardwareListeners( emuListeners ); removeAllNonHardwareListeners( beforeCommandExecListeners ); removeAllNonHardwareListeners( continuousModeBeforeCommandExecListeners ); removeAllNonHardwareListeners( continuousModeAfterCommandExecListeners ); removeAllNonHardwareListeners( afterCommandExecListeners ); } } private void removeAllNonHardwareListeners(List<IEmulationListener> list) { for ( Iterator<IEmulationListener> it = list.iterator() ; it.hasNext() ; ) { if ( ! it.next().belongsToHardwareDevice() ) { it.remove(); } } } public void removeEmulationListener(IEmulationListener listener) { if (listener == null) { throw new IllegalArgumentException("listener must not be NULL."); } synchronized (emuListeners) { emuListeners.remove( listener ); beforeCommandExecListeners.remove( listener ); continuousModeBeforeCommandExecListeners.remove( listener ); continuousModeAfterCommandExecListeners.remove( listener ); afterCommandExecListeners.remove( listener ); } } public void notifyListeners(IEmulationListenerInvoker invoker) { notifyListeners( invoker , emuListeners ); } public void invokeAfterCommandExecutionListeners(boolean continousMode,final int executedCommandDuration) { final IEmulationListenerInvoker invoker = new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.afterCommandExecution( emulator , executedCommandDuration ); } }; if ( continousMode ) { notifyListeners( invoker , continuousModeAfterCommandExecListeners ); } else { notifyListeners( invoker , afterCommandExecListeners ); } } public void invokeBeforeCommandExecutionListeners(boolean continousMode) { if ( continousMode ) { notifyListeners( BEFORE_COMMAND_INVOKER , continuousModeBeforeCommandExecListeners ); } else { notifyListeners( BEFORE_COMMAND_INVOKER , beforeCommandExecListeners ); } } public void notifyListeners(IEmulationListenerInvoker invoker,List<IEmulationListener> listeners) { final List<IEmulationListener> copy; synchronized( emuListeners ) { if ( listeners.isEmpty() ) { return; } copy = new ArrayList<IEmulationListener>( listeners ); } if ( DEBUG_LISTENER_PERFORMANCE ) { for ( IEmulationListener l : copy) { long execTime = -System.currentTimeMillis(); try { invoker.invoke( Emulator.this , l ); } catch(Exception e) { LOG.error("notifyListeners(): Listener "+l+" failed",e); } finally { execTime += System.currentTimeMillis(); } final Long existing = listenerPerformance.get( l ); if ( existing == null ) { listenerPerformance.put( l , execTime ); } else { listenerPerformance.put( l , existing.longValue() + execTime ); } } } else { final int len = copy.size(); for ( int i = 0 ; i < len ; i++) { final IEmulationListener l = copy.get(i); try { invoker.invoke( Emulator.this , l ); } catch(Exception e) { LOG.error("notifyListeners(): Listener "+l+" failed",e); } } } } public void emulatorDisposed() { notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.beforeEmulatorIsDisposed( emulator ); } }); final List<IEmulationListener> copy; synchronized( emuListeners ) { copy = new ArrayList<IEmulationListener>( emuListeners ); } for ( IEmulationListener l : copy ) { removeEmulationListener( l ); } } } private volatile boolean ignoreAccessToUnknownDevices=false; private volatile boolean checkMemoryWrites = false; private volatile Throwable lastEmulationError = null; private volatile EmulationSpeed emulationSpeed = EmulationSpeed.MAX_SPEED; // ============ BreakPoints ======= // @GuardedBy( breakpoints ) private final Map<Address,List<Breakpoint>> breakpoints = new HashMap<Address,List<Breakpoint>>(); // ============ Memory ============ // memory needs to be thread-safe since the emulation runs in a separate thread // and UI threads may access the registers concurrently private final MainMemory memory = new MainMemory( 65536 , checkMemoryWrites ); // ========= devices =========== // @GuardedBy( devices ) private final List<IDevice> devices = new ArrayList<IDevice>(); // ============ CPU =============== private final Object CPU_LOCK = new Object(); private Address lastValidInstruction = null; // @GuardedBy( CPU_LOCK ) private final CPU cpu = new CPU(memory); // @GuardedBy( CPU_LOCK ) private final CPU visibleCPU = new CPU(memory); // a,b,c,x,y,z,i,j // all CPU registers needs to be thread-safe since the emulation runs in a separate thread // and UI threads may access the registers concurrently private volatile ILogger loggerDelegate = new PrintStreamLogger( System.out ); private final ILogger out = new ILogger() { @Override public void setLogLevel(de.codesourcery.jasm16.emulator.ILogger.LogLevel logLevel) { loggerDelegate.setLogLevel( logLevel ); } @Override public boolean isDebugEnabled() { return loggerDelegate.isDebugEnabled(); } @Override public void info(String message) { loggerDelegate.info(message); } @Override public void info(String message, Throwable cause) { loggerDelegate.info(message, cause); } @Override public void warn(String message) { loggerDelegate.warn(message); } @Override public void warn(String message, Throwable cause) { loggerDelegate.warn(message, cause); } @Override public void error(String message) { loggerDelegate.error(message); } @Override public void error(String message, Throwable cause) { loggerDelegate.error(message, cause); } @Override public void debug(String message) { loggerDelegate.debug(message); } @Override public void debug(String message, Throwable cause) { loggerDelegate.debug(message, cause); } }; /* (non-Javadoc) * @see de.codesourcery.jasm16.emulator.IEmulator#reset() */ @Override public void reset(boolean clearMemory) { stop(null); // reset memory BEFORE resetting devices // because if a device uses MMIO, doing the // resetMemory() call after resetDevices() may // trigger the device again and thus pollute // the reset state resetMemory(clearMemory); resetDevices(); synchronized( CPU_LOCK ) { cpu.reset(); visibleCPU.reset(); } // notify listeners listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.afterReset( emulator ); } }); } private void resetMemory(boolean clearMemory) { memory.resetWriteProtection(); if ( clearMemory ) { memory.clear(); } } private void resetDevices() { for ( IDevice device : getDevices() ) { try { device.reset(); } catch(Exception e) { LOG.error("reset(): Device "+device+" failed during reset",e); } } } @Override public boolean stop() { return stop( null ); } protected boolean stop(final Throwable cause) { this.lastEmulationError = cause; final boolean emulationWasRunning = clockThread.stopSimulation(); if ( emulationWasRunning ) { listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { final Address pc; synchronized( CPU_LOCK ) { pc = visibleCPU.pc; } listener.onStop( emulator , pc , cause ); } }); } // remove all internal breakpoints final List<Breakpoint> internalBPs = new ArrayList<Breakpoint>(); synchronized( breakpoints ) { for ( List<Breakpoint> bps : breakpoints.values() ) { for ( Breakpoint bp : bps ) { if ( bp.isOneShotBreakpoint() ) { internalBPs.add( bp ); } } } } for ( Breakpoint bp : internalBPs ) { deleteBreakpoint( bp ); } return emulationWasRunning; } @Override public void start() { listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.beforeContinuousExecution( emulator ); } }); clockThread.startSimulation(); } public Emulator() { clockThread = new ClockThread(); clockThread.start(); } /** * Thread responsible for execution of the * actual instruction emulation. * * <p>This thread's main loop supports two * execution modes, either {@link EmulationSpeed#MAX_SPEED} * or {@link EmulationSpeed#REAL_SPEED}.</p> * * @author [email protected] */ public final class ClockThread extends Thread { // values used for emulation speed calculations private long lastStart = 0; private int cycleCountAtLastStart=0; private long lastStop = 0; private int cycleCountAtLastStop=0; private final AtomicBoolean isRunnable = new AtomicBoolean(false); private final BlockingQueue<Command> cmdQueue = new ArrayBlockingQueue<Command>(1); private final BlockingQueue<Long> ackQueue = new ArrayBlockingQueue<Long>(300); // execution delay loop parameters determined by calibrate() method private volatile double adjustmentFactor = 1.0d; private volatile int oneCycleDelay = -1; // just a dummy value used in our delay loop private int dummy; // the current emulation speed private EmulationSpeed currentSpeed = emulationSpeed; public ClockThread() { setName("emulation-clock-thread"); setDaemon(true); } @Override public void run() { lastEmulationError = null; Command cmd = waitForStartCommand(); if ( cmd.isTerminateCommand() ) { out.info("Emulator thread terminated."); acknowledgeCommand( cmd ); return; } lastStart = System.currentTimeMillis(); cycleCountAtLastStart=cpu.currentCycle; acknowledgeCommand( cmd ); while ( true ) { if ( isRunnable.get() == false ) { // halt execution lastStop = System.currentTimeMillis(); cycleCountAtLastStop = cpu.currentCycle; if ( DEBUG_LISTENER_PERFORMANCE ) { for ( Map.Entry<IEmulationListener,Long> entry : listenerPerformance.entrySet() ) { out.debug( entry.getKey()+" = "+entry.getValue()+" millis" ); } } out.info("Emulator stopped."); out.info("Executed cycles: "+(cycleCountAtLastStop-cycleCountAtLastStart) +" ( in "+getRuntimeInSeconds()+" seconds )"); out.info("Estimated clock rate: "+getEstimatedClockSpeed() ); cmd = waitForStopCommand(); if ( cmd.isTerminateCommand() ) { acknowledgeCommand( cmd ); break; } acknowledgeCommand( cmd ); cmd = waitForStartCommand(); if ( cmd.isTerminateCommand() ) { acknowledgeCommand( cmd ); break; } lastEmulationError = null; cycleCountAtLastStart = cpu.currentCycle; lastStart = System.currentTimeMillis(); acknowledgeCommand(cmd); } /* ================ * Execute ONE instruction * ================ */ final int durationInCycles = internalExecuteOneInstruction(); if ( currentSpeed == EmulationSpeed.REAL_SPEED ) { // adjust execution speed every 10000 cycles // to account for CPU load changes / JIT / different instruction profiles if ( ( cpu.currentCycle % 10000 ) == 0 ) { final double deltaSeconds = ( System.currentTimeMillis() - lastStart) / 1000d; final double cyclesPerSecond = (cpu.currentCycle-cycleCountAtLastStart) / deltaSeconds; if ( ! Double.isInfinite( cyclesPerSecond ) ) { adjustmentFactor = ( cyclesPerSecond / 100000.0d ); } } // delay execution, this code is exactly the same code as the one timed in // measureDelayLoop() int j = (int) (oneCycleDelay*durationInCycles*adjustmentFactor); for ( ; j > 0 ; j-- ) { dummy = ((dummy*2+j*2)/3)/(dummy*7+j); } } } out.info("Emulator thread terminated."); } public void startSimulation() { if ( isRunnable.compareAndSet( false , true ) ) { sendToClockThread( Command.startCommand() ); } } /** * Stop simulation. * * @return true if the simulation was currently running and has been stopped, false if the simulation was already stopped. */ public boolean stopSimulation() { if ( isRunnable.compareAndSet(true,false) ) { if ( Thread.currentThread() == clockThread ) { sendToClockThread( Command.stopCommandWithoutACK() ); // no point in sending an ACK since the clock thread itself triggered the stop() } else { sendToClockThread( Command.stopCommand() ); } return true; } return false; } public void changeSpeed(EmulationSpeed newSpeed) { sendToClockThread( Command.changeSpeedCommand( newSpeed ) ); } private final AtomicBoolean terminateCommandReceived = new AtomicBoolean(false); private void sendToClockThread(Command cmd) { if ( cmd.hasType(CommandType.TERMINATE ) ) { if ( ! terminateCommandReceived.compareAndSet( false , true ) ) { throw new IllegalStateException("Can't process any more commands , worker thread already terminated"); } } safePut( cmdQueue , cmd ); if ( ! cmd.requiresACK() ) { // don't wait , we'll never receive this one anyway return; } do { final Long cmdId = ackQueue.peek(); if ( cmdId != null && cmdId.longValue() == cmd.getId() ) { safeTake( ackQueue ); return; } try { java.lang.Thread.sleep(100); } catch(InterruptedException e) { Thread.currentThread().interrupt(); } } while ( true ); } private <T> T safeTake(BlockingQueue<T> queue) { while(true) { try { return queue.take(); } catch (InterruptedException e) { Thread.currentThread(); } } } public double getRuntimeInSeconds() { if ( lastStart != 0 && lastStop != 0 ) { final long delta = lastStop - lastStart; if ( delta >= 0) { return delta / 1000.0d; } LOG.error("getRuntimeInSeconds(): Negative runtime ? "+delta+" ( lastStart: "+lastStart+" / lastStop: "+lastStop,new Exception()); throw new RuntimeException("Unreachable code reached"); } else if ( lastStart != 0 ) { return ( (double) System.currentTimeMillis() - (double) lastStart) / 1000.0d; } else if ( lastStart == 0 && lastStop == 0 ) { return 0; } LOG.error("getRuntimeInSeconds(): Unreachable code reached"); throw new RuntimeException("Unreachable code reached"); } protected final double measureDelayLoopInNanos() { double averages = 0.0d; int count = 0; for ( int i = 0 ; i < 10 ; i++ ) { averages += measureDelayLoop(); count++; } return (averages / count); } protected final double measureDelayLoop() { final int oldValue = clockThread.oneCycleDelay; final int LOOP_COUNT = 1000000; oneCycleDelay = LOOP_COUNT; final long nanoStart = System.nanoTime(); for ( int j = oneCycleDelay ; j > 0 ; j-- ) { dummy = ((dummy*2+j*2)/3)/(dummy*7+j); } long durationNanos = ( System.nanoTime() - nanoStart ); if ( durationNanos < 0) { durationNanos = -durationNanos; } oneCycleDelay = oldValue; return ( (double) durationNanos / (double) LOOP_COUNT); } public String getEstimatedClockSpeed() { final double clockRate = getCyclesPerSecond(); final double delta = clockRate-100000.0; final double deviationPercentage = 100.0d*( delta / 100000.0 ); final String sign = deviationPercentage > 0 ? "+" : ""; final String deviation = " ( "+sign+deviationPercentage+" % )"; if ( clockRate == -1.0d ) { return "<cannot calculate clock rate>"; } if ( clockRate < 1000 ) { return clockRate+" Hz"+deviation; } else if ( clockRate < 100000) { return (clockRate/1000)+" kHz"+deviation; } else if ( clockRate < 1000000000 ) { return (clockRate/1000000)+" MHz"+deviation; } return (clockRate/1000000000)+" GHz"+deviation; } public double getCyclesPerSecond() { if ( lastStart != 0 ) { final double runtime = getRuntimeInSeconds(); if ( runtime != 0.0d ) { return ((double)cycleCountAtLastStop - (double) cycleCountAtLastStart ) / getRuntimeInSeconds(); } } return 0.0d; } private Command waitForStopCommand() { return waitForCommand(false); } private Command waitForStartCommand() { return waitForCommand(true); } private Command waitForCommand(boolean expectingStartCommand) { while ( true ) { final Command result = safeTake( cmdQueue ); // note that everything that is NOT a stop/terminate command // is considered to be a START command so we need to adjust // the speed here before checking Command#isStartCommand() if ( result.hasType( CommandType.SPEED_CHANGE ) ) { currentSpeed = (EmulationSpeed) result.getPayload(); out.info("Emulation speed changed changed to "+currentSpeed); acknowledgeCommand( result ); continue; } if ( ( expectingStartCommand && result.isStartWorkerMainLoopCommand() ) || ( ! expectingStartCommand && result.isStopCommand() ) ) { return result; } acknowledgeCommand( result ); } } private void acknowledgeCommand(Command cmd) { if ( cmd.requiresACK() ) { safePut( ackQueue , cmd.getId() ); } } } public <T> T doWithEmulator(IEmulatorInvoker<T> invoker) { synchronized( CPU_LOCK ) { return invoker.doWithEmulator( this , cpu , memory ); } } /** * * @return number of DCPU-16 cycles the command execution took */ protected int internalExecuteOneInstruction() { beforeCommandExecution(); int execDurationInCycles=-1; try { boolean success = false; synchronized( CPU_LOCK ) { try { execDurationInCycles = cpu.executeInstruction(); lastValidInstruction = visibleCPU.pc; if ( checkMemoryWrites ) { // note-to-self: I cannot simply do ( currentPC - previousPC ) here because // the instruction might've been a JSR or ADD PC, X / SUB PC,Y or // a jump into an interrupt handler that skipped over non-instruction memory final int sizeInWords = calculateInstructionSizeInWords( visibleCPU.pc.getWordAddressValue() , memory ); memory.writeProtect( new AddressRange( visibleCPU.pc , Size.words( sizeInWords )) ); } cpu.currentCycle+=execDurationInCycles; cpu.pc = Address.wordAddress( cpu.currentInstructionPtr ); cpu.maybeProcessOneInterrupt(); // might push A on stack and set PC to IA success = true; } finally { if ( success ) { visibleCPU.populateFrom( cpu ); } else { // restore CPU register state on error cpu.populateFrom(visibleCPU); } } } } catch(EmulationErrorException e) { stop( e ); LOG.error( "internalExecuteOneInstruction(): Emulation error - "+e.getMessage()); out.warn("Simulation stopped due to a program error ( at address ."+visibleCPU.pc+")",e); return 0; } catch(Exception e) { stop( e ); LOG.error( "internalExecuteOneInstruction(): Internal error - "+e.getMessage(),e); out.error("Simulation stopped due to an internal error ( at address ."+visibleCPU.pc+")"); return 0; } finally { afterCommandExecution( execDurationInCycles , cpu ); } return execDurationInCycles; } @Override public void executeOneInstruction() { stop(null); internalExecuteOneInstruction(); } protected void beforeCommandExecution() { listenerHelper.invokeBeforeCommandExecutionListeners( this.clockThread.isRunnable.get() ); } /** * * @param executedCommandDuration duration (in cycles) of last command or -1 if execution failed with an internal emulator error */ protected void afterCommandExecution(final int executedCommandDuration,CPU hiddenCPU) { // invoke listeners listenerHelper.invokeAfterCommandExecutionListeners( clockThread.isRunnable.get() , executedCommandDuration ); // check whether we reached a breakpoint maybeHandleBreakpoint(hiddenCPU); } private void maybeHandleBreakpoint(CPU hiddenCPU) { /* * We can have at most 2 breakpoints at any address, * one regular (user-defined) breakpoint and * one internal breakpoint used by stepReturn() */ Breakpoint regularBP = null; Breakpoint oneShotBP = null; synchronized( breakpoints ) { final List<Breakpoint> candidates = breakpoints.get( hiddenCPU.pc ); if ( candidates == null || candidates.isEmpty() ) { return; } for ( Breakpoint bp : candidates ) { if ( bp.matches( this ) ) { if ( bp.isOneShotBreakpoint() ) { if ( oneShotBP == null ) { oneShotBP = bp; } else { throw new RuntimeException("Internal error, more than one internal breakpoint at "+bp.getAddress()); } } else { if ( regularBP == null ) { regularBP = bp; } else { throw new RuntimeException("Internal error, more than one regular breakpoint at "+bp.getAddress()); } } } } } if ( regularBP != null || oneShotBP != null ) { // stop() will also remove ANY one-shot breakpoints from the list stop(null); if ( regularBP != null ) // only notify client code about the regular BP, internal BP is invisible to the user { final Breakpoint finalRegularBP = regularBP; // Closures can only access stuff declared final... listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.onBreakpoint( emulator , finalRegularBP ); } }); } } } private boolean isConditionalInstruction(int instructionWord) { final int opCode = (instructionWord & 0x1f); return ( opCode >= 0x10 && opCode <= 0x17); } @Override public void skipCurrentInstruction() { synchronized(CPU_LOCK) { int adr = cpu.pc.getWordAddressValue(); adr += calculateInstructionSizeInWords( adr , memory ); cpu.pc = Address.wordAddress( adr ); visibleCPU.populateFrom( cpu ); } afterCommandExecution( 0 , visibleCPU ); } public static int calculateInstructionSizeInWords(Address address,IReadOnlyMemory memory) { return calculateInstructionSizeInWords(address.getWordAddressValue() , memory ); } public static int calculateInstructionSizeInWords(int address,IReadOnlyMemory memory) { @SuppressWarnings("deprecation") final int instructionWord = memory.read( address ); final int opCode = (instructionWord & 0x1f); int instructionSizeInWords=1; // +1 word for instruction itself switch( opCode ) { case 0x00: // skip special opcode instructionSizeInWords += getOperandsSizeInWordsForSpecialInstruction( instructionWord ); break; case 0x01: // SET case 0x02: // ADD case 0x03: // SUB case 0x04: // MUL case 0x05: // MLI case 0x06: // DIV case 0x07: // DVI case 0x08: // MOD case 0x09: // MDI case 0x0a: // AND case 0x0b: // BOR case 0x0c: // XOR case 0x0d: // SHR case 0x0e: // ASR case 0x0f: // SHL case 0x10: // IFB case 0x11: // IFC case 0x12: // IFE case 0x13: // IFN case 0x14: // IFG case 0x15: // IFA case 0x16: // IFL case 0x17: // IFU instructionSizeInWords += getOperandsSizeInWordsForBasicInstruction(instructionWord); break; case 0x18: // UNKNOWN case 0x19: // UNKNOWN; instructionSizeInWords += getOperandsSizeInWordsForUnknownInstruction( instructionWord ); break; case 0x1a: // ADX case 0x1b: // SBX instructionSizeInWords += getOperandsSizeInWordsForBasicInstruction(instructionWord); break; case 0x1c: // UNKNOWN case 0x1d: // UNKNOWN instructionSizeInWords += getOperandsSizeInWordsForUnknownInstruction( instructionWord ); break; case 0x1e: // STI case 0x1f: // STD instructionSizeInWords += getOperandsSizeInWordsForBasicInstruction( instructionWord ); break; default: instructionSizeInWords += getOperandsSizeInWordsForUnknownInstruction( instructionWord ); break; } return instructionSizeInWords; } private static int getOperandsSizeInWordsForBasicInstruction(int instructionWord) { // PC is already pointing at word AFTER current instruction here ! return getOperandSizeInWords(OperandPosition.SOURCE_OPERAND,instructionWord,false)+getOperandSizeInWords(OperandPosition.TARGET_OPERAND,instructionWord,false) ; } private static int getOperandsSizeInWordsForUnknownInstruction(int instructionWord) { // PC is already pointing at word AFTER current instruction here ! return 0; } private static int getOperandsSizeInWordsForSpecialInstruction(int instructionWord) { // PC is already pointing at word AFTER current instruction here ! return getOperandSizeInWords(OperandPosition.SOURCE_OPERAND,instructionWord,true); } private static int getOperandSizeInWords(OperandPosition position, int instructionWord,boolean isSpecialOpCode) { /* SET b,a * * b is always handled by the processor after a, and is the lower five bits. * In bits (in LSB-0 format), a basic instruction has the format: * * aaaaaabbbbbooooo * * b = TARGET operand * a = SOURCE operand * * Special opcodes always have their lower five bits unset, have one value and a * five bit opcode. In binary, they have the format: * * aaaaaaooooo00000 * * The value (a) is in the same six bit format as defined earlier. */ final int operandBits; if ( position == OperandPosition.SOURCE_OPERAND || isSpecialOpCode ) { // SET b , a ==> a operandBits = (instructionWord >>> 10) & ( 1+2+4+8+16+32); // SET b,a ==> b } else { operandBits = (instructionWord >>> 5) & ( 1+2+4+8+16); // SET b,a ==> b } if ( operandBits <= 0x07 ) { return 0; // operandDesc( registers[ operandBits ] ); } if ( operandBits <= 0x0f ) { return 0; // operandDesc( memory[ registers[ operandBits - 0x08 ] ] , 1 ); } if ( operandBits <= 0x17 ) { return 1; // operandDesc( memory[ registers[ operandBits - 0x10 ]+nextWord ] ,1 ); } switch( operandBits ) { case 0x18: // POP / [SP++] return 0 ; // operandDesc( memory[ sp ] , 1 ); case 0x19: return 0; // operandDesc( memory[ sp] , 1 ); case 0x1a: return 1; // operandDesc( memory[ sp + nextWord ] , 1 ); case 0x1b: return 0; // operandDesc( sp ); case 0x1c: return 0; // operandDesc( pc ); case 0x1d: return 0; // operandDesc( ex ); case 0x1e: return 1; // operandDesc( memory[ nextWord ] ,1 ); case 0x1f: return 1; // operandDesc( memory[ pc++ ] , 1 ); } // literal value: -1...30 ( 0x20 - 0x3f ) return 0; // operandDesc( operandBits - 0x21 , 0 ); } @Override public boolean canStepReturn() { return isJSR( memory.read( cpu.pc ) ); } @Override public void stepReturn() { if ( ! canStepReturn() ) { throw new IllegalStateException("PC is not at a JSR instruction, cannot skip return"); } final int currentInstructionSizeInWords = calculateInstructionSizeInWords( cpu.pc.getWordAddressValue() , memory ); final Address nextInstruction = cpu.pc.plus( Size.words( currentInstructionSizeInWords ) , true ); addBreakpoint( new OneShotBreakpoint( nextInstruction ) ); start(); } protected static boolean isJSR(int instructionWord) { final int basicOpCode = (instructionWord & 0x1f); if ( basicOpCode != 0 ) { return false; } final int specialOpCode = ( instructionWord >>> 5 ) &0x1f; return specialOpCode == 0x01; // JSR } private IDevice getDeviceForSlot(int hardwareSlot) { synchronized( devices ) { if ( hardwareSlot>=0 && hardwareSlot<devices.size()) { return devices.get(hardwareSlot); } } return null; } protected static final class OperandDesc { public final int value; public final int cycleCount; // how long it takes to perform the operation public OperandDesc(int value) { this.value = value & 0xffff; this.cycleCount = 0; } public OperandDesc(int value,int cycleCount) { this.value = value & 0xffff; this.cycleCount = cycleCount; } } protected static OperandDesc operandDesc(int value) { return new OperandDesc( value ); } protected static OperandDesc operandDesc(int value,int cycleCount) { return new OperandDesc( value , cycleCount ); } /* (non-Javadoc) * @see de.codesourcery.jasm16.emulator.IEmulator#loadMemory(de.codesourcery.jasm16.Address, byte[]) */ @Override public void loadMemory(final Address startingOffset, final byte[] data) { stop(null); if ( clockThread.isRunnable.get() ) { throw new IllegalStateException("Emulation not stopped?"); } memory.clear(); MemUtils.bulkLoad( memory , startingOffset , data ); // notify listeners listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.afterMemoryLoad( emulator , startingOffset , data.length ); } }); } protected interface IEmulationListenerInvoker { public void invoke(IEmulator emulator, IEmulationListener listener); } /* (non-Javadoc) * @see de.codesourcery.jasm16.emulator.IEmulator#calibrate() */ @Override public synchronized void calibrate() { listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.beforeCalibration( emulator ); } }); final double EXPECTED_CYCLES_PER_SECOND = 100000; // 100 kHz final double expectedNanosPerCycle = (1000.0d * 1000000.0d) / EXPECTED_CYCLES_PER_SECOND; out.info("Measuring delay loop..."); /* * Warm-up JVM / JIT. */ double sum =0.0d; for ( int i = 0 ; i < 5 ; i++ ) { final double tmp = clockThread.measureDelayLoopInNanos(); sum+= tmp; } /* * Repeatedly measure the execution time * for a single delay-loop iteration. */ final int LOOP_COUNT=5; sum =0.0d; for ( int i = 0 ; i < LOOP_COUNT ; i++ ) { final double tmp = clockThread.measureDelayLoopInNanos(); sum+= tmp; } final double nanosPerDelayLoopExecution = sum / LOOP_COUNT; out.info("one delay-loop iteration = "+nanosPerDelayLoopExecution+" nanoseconds."); final double loopIterationsPerCycle = expectedNanosPerCycle / nanosPerDelayLoopExecution; clockThread.adjustmentFactor = 1.0d; clockThread.oneCycleDelay = (int) Math.round( loopIterationsPerCycle ); out.info("one CPU cycle = "+clockThread.oneCycleDelay+" delay-loop iterations."); listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.afterCalibration( emulator ); } }); } @Override public IReadOnlyCPU getCPU() { synchronized( CPU_LOCK ) { final CPU result = new CPU(this.memory); result.populateFrom( this.visibleCPU ); return result; } } @Override public IReadOnlyMemory getMemory() { return memory; } @Override public void addEmulationListener(IEmulationListener listener) { listenerHelper.addEmulationListener( listener ); } public void removeAllEmulationListeners() { listenerHelper.removeAllEmulationListeners(); } @Override public void removeEmulationListener(IEmulationListener listener) { listenerHelper.removeEmulationListener( listener ); } private Breakpoint extractRegularBreakpoint(List<Breakpoint> bps) { Breakpoint result = null; for ( Breakpoint bp : bps ) { if ( ! bp.isOneShotBreakpoint() ) { if ( result != null ) { throw new IllegalStateException("More than one " + " regular breakpoint at address "+bp.getAddress()); } result = bp; } } return result; } @Override public void addBreakpoint(final Breakpoint bp) { if (bp == null) { throw new IllegalArgumentException("breakpoint must not be NULL."); } Breakpoint replacedBreakpoint; synchronized( breakpoints ) { List<Breakpoint> list = breakpoints.get( bp.getAddress() ); if ( list == null ) { list = new ArrayList<Breakpoint>(); breakpoints.put( bp.getAddress() , list ); } replacedBreakpoint = extractRegularBreakpoint( list ); if ( replacedBreakpoint != null ) { list.remove( replacedBreakpoint ); } list.add( bp ); } // notify listeners if ( replacedBreakpoint != null && ! replacedBreakpoint.isOneShotBreakpoint() ) { listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.breakpointDeleted( emulator , bp ); } }); } if ( ! bp.isOneShotBreakpoint() ) { listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.breakpointAdded( emulator , bp ); } }); } } @Override public void breakpointChanged(final Breakpoint bp) { Breakpoint existing; synchronized( breakpoints ) { final List<Breakpoint> list = breakpoints.get( bp.getAddress() ); if ( list != null ) { existing = extractRegularBreakpoint( list ); } else { existing = null; } } if ( existing == null ) { LOG.warn("breakpointChanged(): Unknown breakpoint "+bp); return; } listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.breakpointChanged( emulator , bp ); } }); } @Override public void deleteAllBreakpoints() { final List<Breakpoint> copy=new ArrayList<>(); synchronized( breakpoints ) { for ( List<Breakpoint> bp : breakpoints.values() ) { copy.addAll( bp ); } } for ( Breakpoint bp : copy ) { deleteBreakpoint( bp , false ); } listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.allBreakpointsDeleted( emulator ); } }); } @Override public void deleteBreakpoint(final Breakpoint bp) { deleteBreakpoint(bp,true); } private void deleteBreakpoint(final Breakpoint bp,boolean notifyListeners) { if (bp == null) { throw new IllegalArgumentException("breakpoint must not be NULL."); } Breakpoint existing; synchronized( breakpoints ) { final List<Breakpoint> list = breakpoints.get( bp.getAddress() ); if ( list != null ) { final int idx = list.indexOf( bp ); if ( idx != -1 ) { existing = list.remove( idx ); } else { existing = null; } if ( list.isEmpty() ) { breakpoints.remove( bp.getAddress() ); } } else { existing = null; } } // notify listeners if ( notifyListeners && existing != null && ! existing.isOneShotBreakpoint() ) { listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.breakpointDeleted( emulator , bp ); } }); } } @Override public List<Breakpoint> getBreakPoints() { final List<Breakpoint> result = new ArrayList<Breakpoint>(); synchronized( breakpoints ) { for ( List<Breakpoint> subList : breakpoints.values() ) { for ( Breakpoint bp : subList ) { if ( ! bp.isOneShotBreakpoint() ) { result.add( bp ); } } } } return result; } @Override public Breakpoint getBreakPoint(Address address) { if (address == null) { throw new IllegalArgumentException("address must not be NULL."); } synchronized( breakpoints ) { final List<Breakpoint> list = breakpoints.get( address ); if ( list == null ) { return null; } return extractRegularBreakpoint( list ); } } @Override public void unmapRegion(IMemoryRegion region) { synchronized( CPU_LOCK ) { this.memory.unmapRegion( region ); if ( out.isDebugEnabled() ) { out.debug("Unmapped memory region "+region); this.memory.dumpMemoryLayout(out); } } } @Override public void mapRegion(IMemoryRegion region) { synchronized( CPU_LOCK ) { this.memory.mapRegion( region ); if ( out.isDebugEnabled() ) { out.debug("Mapped memory region "+region); this.memory.dumpMemoryLayout( out ); } } } @Override public boolean triggerInterrupt(IInterrupt interrupt) { synchronized( CPU_LOCK ) { return cpu.triggerInterrupt( interrupt ); } } public int addOrReplaceDevice(IDevice device) throws DeviceErrorException { if (device == null) { throw new IllegalArgumentException("device must not be null"); } int existingSlot = -1; IDevice existingDevice = null; synchronized( devices ) { existingSlot = findDeviceSlotByDescriptor( device.getDeviceDescriptor() ); if ( existingSlot != -1 ) { existingDevice = devices.get( existingSlot ); } } final boolean requiresAdd; if ( existingDevice != null ) { // call beforeRemoveDevice() outside of synchronized block existingDevice.beforeRemoveDevice( this ); synchronized( devices ) { existingSlot = devices.indexOf( existingDevice ); if ( existingSlot == -1 ) { requiresAdd = true; } else { devices.remove( existingSlot ); devices.add( existingSlot , device ); requiresAdd = false; } } } else { requiresAdd = true; } if ( requiresAdd ) { return addDevice( device ); } // replaced device.afterAddDevice( this ); return existingSlot; } public List<IDevice> getDevicesByDescriptor(DeviceDescriptor desc) { if (desc == null) { throw new IllegalArgumentException("descriptor must not be null"); } final List<IDevice> result = new ArrayList<>(); synchronized( devices ) { for ( IDevice device : devices ) { if ( device.getDeviceDescriptor().matches( desc ) ) { result.add( device ); } } } return result; } private int findDeviceSlotByDescriptor(DeviceDescriptor descriptor) { int existingSlot = -1; synchronized( devices ) { int i = 0; for ( IDevice existing : devices ) { if ( existing.getDeviceDescriptor().matches( descriptor) ) { if ( existingSlot != -1 ) { throw new IllegalStateException("Found more than one existing device with descriptor "+descriptor ); } existingSlot = i; } i++; } } return existingSlot; } @Override public int addDevice(IDevice device) throws DeviceErrorException { if (device == null) { throw new IllegalArgumentException("device must not be null"); } final int slotNo; synchronized( devices ) { if ( ! device.supportsMultipleInstances() && findDeviceSlotByDescriptor( device.getDeviceDescriptor() ) != -1 ) { throw new IllegalStateException("Already one instance of device "+device.getDeviceDescriptor()+" registered."); } if ( devices.size() >= 65535 ) { throw new IllegalStateException("Already 65535 devices registered"); } slotNo = devices.size(); devices.add( device ); out.debug("Added device "+device); printDevices(); } boolean success = false; try { device.afterAddDevice( this ); success = true; } catch(RuntimeException e) { if ( e instanceof DeviceErrorException ) { throw e; } LOG.error("Device "+device+" failed in afterAddDevice() call",e); throw new DeviceErrorException( "afterAddDevice() failed: "+e.getMessage() , device , e ); } finally { if ( ! success ) { synchronized( devices ) { devices.remove( device ); } } } return slotNo; } private void printDevices() { synchronized( devices ) { int slot = 0; for ( IDevice d : devices ) { out.debug("Slot #"+slot+":"); out.debug( d.getDeviceDescriptor().toString(" ",true)); slot++; } } } @Override public List<IDevice> getDevices() { synchronized( devices ) { return new ArrayList<IDevice>( devices ); } } @Override public void removeDevice(IDevice device) { if (device == null) { throw new IllegalArgumentException("device must not be null"); } final boolean isRegistered; synchronized( devices ) { isRegistered = devices.contains( device ); } if ( isRegistered ) { try { device.beforeRemoveDevice( this ); } catch(RuntimeException e) { if ( e instanceof DeviceErrorException) { throw (DeviceErrorException) e; } LOG.error("Device "+device+" failed in beforeRemoveDevice() call",e); throw new DeviceErrorException( "breforeRemoveDevice() failed: "+e.getMessage() , device , e ); } } else { return; } synchronized( devices ) { devices.remove( device ); } if ( isRegistered ) { out.debug("Removed device "+device); printDevices(); } } @Override public EmulationSpeed getEmulationSpeed() { return emulationSpeed; } @Override public void setEmulationSpeed(final EmulationSpeed newSpeed) { if (newSpeed == null) { throw new IllegalArgumentException("speed must not be NULL."); } if ( this.emulationSpeed == newSpeed ) { return; } if ( newSpeed == EmulationSpeed.REAL_SPEED && ! isCalibrated() ) { calibrate(); } final EmulationSpeed oldSpeed = this.emulationSpeed; final boolean wasRunning = stop(); clockThread.changeSpeed( newSpeed ); this.emulationSpeed = newSpeed; listenerHelper.notifyListeners( new IEmulationListenerInvoker() { @Override public void invoke(IEmulator emulator, IEmulationListener listener) { listener.onEmulationSpeedChange( oldSpeed , newSpeed ); } }); if ( wasRunning ) { start(); } } @Override public boolean isCalibrated() { return clockThread.oneCycleDelay != -1; } @Override public Throwable getLastEmulationError() { return lastEmulationError; } private static <T> void safePut(BlockingQueue<T> queue, T value) { while(true) { try { queue.put(value); return; } catch (InterruptedException e) {} } } @Override public synchronized void dispose() { out.info("Disposing Emulator ..."); stop(); // terminate clock thread clockThread.sendToClockThread( Command.terminateClockThread() ); // notify listeners and remove them afterwards listenerHelper.emulatorDisposed(); // remove all devices for ( IDevice d : getDevices() ) { try { removeDevice( d ); } catch(Exception e) { LOG.error("dispose(): Failed to remove "+d); } } out.info("Emulator disposed."); } @Override public void setOutput(ILogger out) { if (out == null) { throw new IllegalArgumentException("out must not be null"); } this.loggerDelegate = out; } @Override public ILogger getOutput() { return out; } @Override public void setMemoryProtectionEnabled(boolean enabled) { checkMemoryWrites = enabled; memory.setCheckWriteAccess( enabled ); } @Override public boolean isMemoryProtectionEnabled() { return checkMemoryWrites; } @Override public void setIgnoreAccessToUnknownDevices(boolean yesNo) { this.ignoreAccessToUnknownDevices = yesNo; } protected final class CPU implements ICPU { // transient, only used inside of executeOneInstruction() code path public int currentInstructionPtr; public final MainMemory memory; /* Register A = Index 0 * Register B = Index 1 * Register C = Index 2 * Register X = Index 3 * Register Y = Index 4 * Register Z = Index 5 * Register I = Index 6 * Register J = Index 7 */ public final int[] commonRegisters = new int[ 8 ]; public int ex; public Address pc; public Address sp; public Address interruptAddress; public boolean queueInterrupts; public IInterrupt currentInterrupt; public final List<IInterrupt> interruptQueue= new ArrayList<IInterrupt>(); public int currentCycle; public CPU(MainMemory memory) { pc = sp = interruptAddress = WordAddress.ZERO; this.memory = memory; } public void populateFrom(CPU other) { System.arraycopy( other.commonRegisters , 0 , this.commonRegisters , 0 , 8 ); this.ex = other.ex; this.pc = other.pc; this.sp = other.sp; this.interruptAddress = other.interruptAddress; this.queueInterrupts = other.queueInterrupts; this.currentInterrupt = other.currentInterrupt; this.interruptQueue.clear(); this.interruptQueue.addAll(other.interruptQueue); this.currentCycle = other.currentCycle; } public boolean triggerInterrupt(IInterrupt interrupt) { if ( ! interruptsEnabled() ) { return false; } synchronized ( interruptQueue ) { if ( currentInterrupt == null && ! isQueueInterrupts() ) { currentInterrupt = interrupt; } else { // there's either already an IRQ waiting to be processed or the CPU is currently told to queue interrupts if ( interruptQueue.size() >= INTERRUPT_QUEUE_SIZE ) { throw new InterruptQueueFullException("Interrupt queue full ("+interruptQueue.size()+" entries already) , can't store "+interrupt); } setQueueInterrupts( true ); interruptQueue.add( interrupt ); } } return true; } public IInterrupt getNextProcessableInterrupt(boolean removeFromQueue) { synchronized( interruptQueue ) { if ( currentInterrupt != null ) { if ( ! removeFromQueue ) { return currentInterrupt; } final IInterrupt irq = currentInterrupt; currentInterrupt = null; return irq; } if ( ! interruptQueue.isEmpty() && ! isQueueInterrupts() ) { if ( removeFromQueue ) { return interruptQueue.remove(0); } return interruptQueue.get(0); } } return null; } public void reset() { currentCycle = 0; queueInterrupts = false; interruptQueue.clear(); sp = pc = interruptAddress = WordAddress.ZERO; ex = 0; for ( int i = 0 ; i < commonRegisters.length ; i++ ) { commonRegisters[i]=0; } } @Override public Address getPC() { return pc; } @Override public Address getSP() { return sp; } @Override public int getEX() { return ex; } @Override public Address getInterruptAddress() { return interruptAddress; } @Override public int getCurrentCycleCount() { return currentCycle; } @Override public void setRegisterValue(Register reg, int value) { switch( reg ) { case A: commonRegisters[0] = value & 0xffff; break; case B: commonRegisters[1] = value & 0xffff; break; case C: commonRegisters[2] = value & 0xffff; break; case EX: ex = value & 0xffff; break; case I: commonRegisters[6] = value & 0xffff; break; case J: commonRegisters[7] = value & 0xffff; break; case PC: pc = Address.wordAddress( value & 0xffff ); break; case SP: sp = Address.wordAddress( value & 0xffff ); break; case X: commonRegisters[3] = value & 0xffff; break; case Y: commonRegisters[4] = value & 0xffff; break; case Z: commonRegisters[5] = value & 0xffff; break; default: throw new RuntimeException("Unreachable code reached: "+reg); } } @Override public int getRegisterValue(Register reg) { switch( reg ) { case A: return commonRegisters[0]; case B: return commonRegisters[1]; case C: return commonRegisters[2]; case EX: return ex; case I: return commonRegisters[6]; case J: return commonRegisters[7]; case PC: return pc.getWordAddressValue(); case SP: return sp.getWordAddressValue(); case X: return commonRegisters[3]; case Y: return commonRegisters[4]; case Z: return commonRegisters[5]; default: throw new RuntimeException("Unreachable code reached: "+reg); } } @Override public void setQueueInterrupts(boolean yesNo) { this.queueInterrupts = yesNo; } @Override public boolean isQueueInterrupts() { return queueInterrupts; } @Override public boolean interruptsEnabled() { return interruptAddress != null && interruptAddress.getValue() != 0; } @Override public List<IInterrupt> getInterruptQueue() { return interruptQueue; } // ============== public int executeInstruction() { currentInstructionPtr = pc.getValue(); final int instructionWord = readNextWordAndAdvance(); final int opCode = (instructionWord & 0x1f); /* * |--- Basic opcodes (5 bits) ---------------------------------------------------- * |C | VAL | NAME | DESCRIPTION * +---+------+----------+--------------------------------------------------------- * |- | 0x00 | n/a | special instruction - see below * |1 | 0x01 | SET b, a | sets b to a * |2 | 0x02 | ADD b, a | sets b to b+a, sets EX to 0x0001 if there's an overflow, 0x0 otherwise * |2 | 0x03 | SUB b, a | sets b to b-a, sets EX to 0xffff if there's an underflow, 0x0 otherwise * |2 | 0x04 | MUL b, a | sets b to b*a, sets EX to ((b*a)>>16)&0xffff (treats b, a as unsigned) * |2 | 0x05 | MLI b, a | like MUL, but treat b, a as signed * |3 | 0x06 | DIV b, a | sets b to b/a, sets EX to ((b<<16)/a)&0xffff. if a==0, sets b and EX to 0 instead. (treats b, a as unsigned) * |3 | 0x07 | DVI b, a | like DIV, but treat b, a as signed. Rounds towards 0 * |3 | 0x08 | MOD b, a | sets b to b%a. if a==0, sets b to 0 instead. * |3 | 0x09 | MDI b, a | like MOD, but treat b, a as signed. Rounds towards 0 * |1 | 0x0a | AND b, a | sets b to b&a * |1 | 0x0b | BOR b, a | sets b to b|a * |1 | 0x0c | XOR b, a | sets b to b^a * |2 | 0x0d | SHR b, a | sets b to b>>>a, sets EX to ((b<<16)>>a)&0xffff (logical shift) * |2 | 0x0e | ASR b, a | sets b to b>>a, sets EX to ((b<<16)>>>a)&0xffff (arithmetic shift) (treats b as signed) * |2 | 0x0f | SHL b, a | sets b to b<<a, sets EX to ((b<<a)>>16)&0xffff * | * |2+| 0x10 | IFB b, a | performs next instruction only if (b&a)!=0 * |2+| 0x11 | IFC b, a | performs next instruction only if (b&a)==0 * |2+| 0x12 | IFE b, a | performs next instruction only if b==a * |2+| 0x13 | IFN b, a | performs next instruction only if b!=a * |2+| 0x14 | IFG b, a | performs next instruction only if b>a * |2+| 0x15 | IFA b, a | performs next instruction only if b>a (signed) * |2+| 0x16 | IFL b, a | performs next instruction only if b<a * |2+| 0x17 | IFU b, a | performs next instruction only if b<a (signed) * |- | 0x18 | - | * |- | 0x19 | - | * |3 | 0x1a | ADX b, a | sets b to b+a+EX, sets EX to 0x0001 if there is an over-flow, 0x0 otherwise * |3 | 0x1b | SBX b, a | sets b to b-a+EX, sets EX to 0xFFFF if there is an under-flow, 0x0 otherwise * |- | 0x1c | - | * |- | 0x1d | - | * |2 | 0x1e | STI b, a | sets b to a, then increases I and J by 1 * |2 | 0x1f | STD b, a | sets b to a, then decreases I and J by 1 * +---+------+----------+---------------------------------------------------------- */ switch( opCode ) { case 0x00: return handleSpecialOpCode( instructionWord ); case 0x01: return handleSET( instructionWord ); case 0x02: return handleADD( instructionWord ); case 0x03: return handleSUB( instructionWord ); case 0x04: return handleMUL( instructionWord ); case 0x05: return handleMLI( instructionWord ); case 0x06: return handleDIV( instructionWord ); case 0x07: return handleDVI( instructionWord ); case 0x08: return handleMOD( instructionWord ); case 0x09: return handleMDI( instructionWord ); case 0x0a: return handleAND( instructionWord ); case 0x0b: return handleBOR( instructionWord ); case 0x0c: return handleXOR( instructionWord ); case 0x0d: return handleSHR( instructionWord ); case 0x0e: return handleASR( instructionWord ); case 0x0f: return handleSHL( instructionWord ); case 0x10: return handleIFB( instructionWord ); case 0x11: return handleIFC( instructionWord ); case 0x12: return handleIFE( instructionWord ); case 0x13: return handleIFN( instructionWord ); case 0x14: return handleIFG( instructionWord ); case 0x15: return handleIFA( instructionWord ); case 0x16: return handleIFL( instructionWord ); case 0x17: return handleIFU( instructionWord ); case 0x18: case 0x19: return handleUnknownOpCode( instructionWord ); case 0x1a: return handleADX( instructionWord ); case 0x1b: return handleSBX( instructionWord ); case 0x1c: case 0x1d: return handleUnknownOpCode( instructionWord ); case 0x1e: return handleSTI( instructionWord ); case 0x1f: return handleSTD( instructionWord ); default: return handleUnknownOpCode( instructionWord ); } } private int handleSTD(int instructionWord) { // sets b to a, then decreases I and J by 1 // a,b,c,x,y,z,i,j final OperandDesc source = loadSourceOperand( instructionWord ); final int cycles = 2+storeTargetOperand( instructionWord , source.value )+source.cycleCount; int address = --commonRegisters[6]; // registers[6]-=1; <<< I if ( address < 0 ) { commonRegisters[6] = (int) WordAddress.MAX_ADDRESS; } address = --commonRegisters[7]; // registers[7]-=1; <<< J if ( address < 0 ) { commonRegisters[7]= (int) WordAddress.MAX_ADDRESS; } return cycles; } private int handleSTI(int instructionWord) { // sets b to a, then increases I and J by 1 // a,b,c,x,y,z,i,j final OperandDesc source = loadSourceOperand( instructionWord ); final int cycles = 2+storeTargetOperand( instructionWord , source.value )+source.cycleCount; int newWordAddress = ++commonRegisters[6]; // registers[6]+=1; <<< I if ( newWordAddress > WordAddress.MAX_ADDRESS ) { commonRegisters[6] = 0; } newWordAddress = ++commonRegisters[7]; // registers[7]+=1; <<< J if ( newWordAddress > WordAddress.MAX_ADDRESS ) { commonRegisters[7] = 0; } return cycles; } private int handleSBX(int instructionWord) { // sets b to b-a+EX, sets EX to 0xFFFF if there is an under-flow, 0x0001 if there's an overflow, 0x0 otherwise OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int b = target.value; final int a = source.value; int result = b-a+ex; if ( result < 0 ) { ex = 0xffff; } else if ( result > 0xffff ) { ex = 0x0001; } else { ex = 0; } return 3+storeTargetOperand( instructionWord , result & 0xffff )+source.cycleCount; } private int handleADX(int instructionWord) { // sets b to b+a+EX, sets EX to 0x0001 if there is an over-flow, 0x0 otherwise OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc = target.value + source.value + ex; if ( acc > 0xffff) { ex = 0x0001; } else { ex = 0; } return 3+storeTargetOperand( instructionWord , acc & 0xffff )+source.cycleCount; } private int handleUnknownOpCode(int instructionWord) { final Disassembler dis = new Disassembler(); // assume worst-case , each instruction only is one word final int instructionCount = Address.calcDistanceInBytes( Address.wordAddress( 0 ) , pc ).toSizeInWords().getValue(); List<DisassembledLine> lines = dis.disassemble( memory , Address.wordAddress( 0 ) , instructionCount , true ); for (DisassembledLine line : lines) { out.info( Misc.toHexString( line.getAddress() )+": "+line.getContents()); } Address lastValid = lastValidInstruction; if ( lastValid == null ) { lastValid = pc; } final String msg = "Unknown opcode 0x"+Misc.toHexString( instructionWord )+ " at address "+"0x"+Misc.toHexString( pc )+ " (last valid PC: "+Misc.toHexString( lastValid )+")"; out.warn(msg ); throw new UnknownOpcodeException( msg , instructionWord & 0xffff ); } private int handleIFU(int instructionWord) { // performs next instruction only if b<a (signed) OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , true ); int penalty = 0; if ( signed( target.value ) >= signed( source.value ) ) { penalty = handleConditionFailure(); } return 2+target.cycleCount+source.cycleCount+penalty; } private int handleConditionFailure() { boolean skippedInstructionIsConditional = isConditionalInstruction( memory.read( currentInstructionPtr ) ); currentInstructionPtr += calculateInstructionSizeInWords( currentInstructionPtr , memory ); if ( skippedInstructionIsConditional ) { do { skippedInstructionIsConditional = isConditionalInstruction( memory.read( currentInstructionPtr ) ); currentInstructionPtr += calculateInstructionSizeInWords( currentInstructionPtr , memory ); } while ( skippedInstructionIsConditional ); return 2; } return 1; } private int handleIFL(int instructionWord) { // performs next instruction only if b<a OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , true ); int penalty = 0; if ( target.value >= source.value ) { penalty = handleConditionFailure(); } return 2+target.cycleCount+source.cycleCount+penalty; } private int handleIFA(int instructionWord) { // performs next instruction only if b>a (signed) OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , true ); int penalty = 0; if ( signed( target.value ) <= signed( source.value ) ) { penalty = handleConditionFailure(); } return 2+target.cycleCount+source.cycleCount+penalty; } private int handleIFG(int instructionWord) { // performs next instruction only if b>a OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , true ); int penalty=0; if ( target.value <= source.value ) { penalty = handleConditionFailure(); } return 2+target.cycleCount+source.cycleCount+penalty; } private int handleIFN(int instructionWord) { // performs next instruction only if b!=a OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , true ); int penalty = 0; if ( target.value == source.value ) { penalty = handleConditionFailure(); } return 2+target.cycleCount+source.cycleCount+penalty; } private int handleIFE(int instructionWord) { // performs next instruction only if b==a OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , true ); int penalty=0; if ( target.value != source.value ) { penalty = handleConditionFailure(); } return 2+target.cycleCount+source.cycleCount+penalty; } private int handleIFC(int instructionWord) { // performs next instruction only if (b&a)==0 OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , true ); int penalty = 0; if ( (target.value & source.value) != 0 ) { penalty = handleConditionFailure(); } return 2+target.cycleCount+source.cycleCount+penalty; } private int handleIFB(int instructionWord) { // performs next instruction only if (b&a)!=0 OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , true ); int penalty=0; if ( (target.value & source.value) == 0 ) { penalty = handleConditionFailure(); } return 2+target.cycleCount+source.cycleCount+penalty; } private int handleSHL(int instructionWord) { // sets b to b<<a, sets EX to ((b<<a)>>16)&0xffff OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc = target.value << source.value; ex = (( target.value << source.value)>>16 ) & 0xffff; return 1+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleASR(int instructionWord) { // ASR b,a // arithmetic shift, sign extension !!! // sets b to b>>a, sets EX to ((b<<16)>>>a)&0xffff (arithmetic shift) (treats b as signed) OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc = signed( target.value ) >> source.value; ex = (( signed( target.value ) << 16) >>> source.value ) & 0xffff; return 1+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleSHR(int instructionWord) { // sets b to b>>>a, sets EX to ((b<<16)>>a)&0xffff (logical shift) OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc = target.value >>> source.value; ex = (( target.value << 16) >> source.value ) & 0xffff; return 1+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleXOR(int instructionWord) { // sets b to b^a OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc = target.value ^ source.value; return 1+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleBOR(int instructionWord) { // sets b to b|a OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc = target.value | source.value; return 1+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleAND(int instructionWord) { // sets b to b&a OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc = target.value & source.value; return 1+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleMDI(int instructionWord) { // like MOD, but treat b, a as signed. Rounds towards 0 OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc; if ( source.value == 0 ) { acc=0; } else { acc = signed( target.value ) % signed( source.value ); } return 3+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleMOD(int instructionWord) { // sets b to b%a. if a==0, sets b to 0 instead. OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc; if ( source.value == 0 ) { acc=0; } else { acc = target.value % source.value; } return 3+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleDVI(int instructionWord) { // e DIV, but treat b, a as signed. Rounds towards 0 OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc; if ( source.value == 0 ) { ex = 0; acc=0; } else { acc = signed( target.value ) / signed( source.value ); ex = (( signed( target.value ) << 16) / signed( source.value) )& 0xffff; } return 3+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleDIV(int instructionWord) { /* set b (TARGET) ,a (SOURCE) * sets b to b/a, sets EX to ((b<<16)/a)&0xffff. if a==0, sets b and EX to 0 instead. (treats b, a as unsigned) */ OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc; if ( source.value == 0 ) { ex = 0; acc=0; } else { acc = target.value / source.value; long tv = target.value; long sv = source.value; ex = (int) ( (( tv << 16) / sv ) & 0xffff); } return 3+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleMLI(int instructionWord) { // like MUL, but treat b, a as signed OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int a = signed( target.value ); final int b = signed( source.value ); final int acc = a * b; ex = ((a * b) >> 16 ) & 0xffff; return 2+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int signed( int value) { if ( ( value & ( 1 << 15 ) ) != 0 ) { // MSB set => negative value return 0xffff0000 | value; } return value; } private int handleMUL(int instructionWord) { // sets b to b*a, sets EX to ((b*a)>>16)&0xffff (treats b, a as unsigned) OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc = target.value * source.value; ex = ((target.value * source.value) >> 16 ) & 0xffff; return 2+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleSUB(int instructionWord) { // sets b to b-a, sets EX to 0xffff if there's an underflow, 0x0 otherwise OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc = target.value - source.value; if ( acc < 0 ) { ex = 0xffff; } else { ex = 0; } return 2+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleADD(int instructionWord) { // sets b to b+a, sets EX to 0x0001 if there's an overflow, 0x0 otherwise OperandDesc source = loadSourceOperand( instructionWord ); OperandDesc target = loadTargetOperand( instructionWord , false , false ); final int acc = target.value + source.value; if ( acc > 0xffff) { ex = 0x0001; } else { ex = 0; } return 2+storeTargetOperand( instructionWord , acc )+source.cycleCount; } private int handleSET(int instructionWord) { final OperandDesc desc = loadSourceOperand( instructionWord ); return 1+storeTargetOperand( instructionWord , desc.value ) + desc.cycleCount; } private int handleSpecialOpCode(int instructionWord) { final int opCode = ( instructionWord >>> 5 ) &0x1f; /* * |--- Special opcodes: (5 bits) -------------------------------------------------- * | C | VAL | NAME | DESCRIPTION * |---+------+-------+------------------------------------------------------------- * | - | 0x00 | n/a | reserved for future expansion * | 3 | 0x01 | JSR a | pushes the address of the next instruction to the stack, then sets PC to a * | - | 0x02 | - | * | - | 0x03 | - | * | - | 0x04 | - | * | - | 0x05 | - | * | - | 0x06 | - | * | 9 | 0x07 | HCF a | use sparingly * | 4 | 0x08 | INT a | triggers a software interrupt with message a * | 1 | 0x09 | IAG a | sets a to IA * | 1 | 0x0a | IAS a | sets IA to a * | 3 | 0x0b | IAP a | if IA is 0, does nothing, otherwise pushes IA to the stack, * | | | | then sets IA to a * | 2 | 0x0c | IAQ a | if a is nonzero, interrupts will be added to the queue * | | | | instead of triggered. if a is zero, interrupts will be * | | | | triggered as normal again * | - | 0x0d | - | * | - | 0x0e | - | * | - | 0x0f | - | * | 2 | 0x10 | HWN a | sets a to number of connected hardware devices * | 4 | 0x11 | HWQ a | sets A, B, C, X, Y registers to information about hardware a * | | | | A+(B<<16) is a 32 bit word identifying the hardware id * | | | | C is the hardware version * | | | | X+(Y<<16) is a 32 bit word identifying the manufacturer * | 4+| 0x12 | HWI a | sends an interrupt to hardware a * | - | 0x13 | - | * | - | 0x14 | - | * | - | 0x15 | - | * | - | 0x16 | - | * | - | 0x17 | - | * | - | 0x18 | - | * | - | 0x19 | - | * | - | 0x1a | - | * | - | 0x1b | - | * | - | 0x1c | - | * | - | 0x1d | - | * | - | 0x1e | - | * | - | 0x1f | - | * |---+------+-------+------------------------------------------------------------- */ switch( opCode ) { case 0x00: return handleUnknownOpCode( instructionWord ); case 0x01: return handleJSR( instructionWord ); case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: return handleUnknownOpCode( instructionWord ); case 0x07: // HCF was removed in spec 1.7 // return handleHCF( instructionWord ); return handleUnknownOpCode( instructionWord ); case 0x08: return handleINT( instructionWord ); case 0x09: return handleIAG( instructionWord ); case 0x0a: return handleIAS( instructionWord ); case 0x0b: return handleRFI( instructionWord ); case 0x0c: return handleIAQ( instructionWord ); case 0x0d: case 0x0e: case 0x0f: return handleUnknownOpCode( instructionWord ); case 0x10: return handleHWN( instructionWord ); case 0x11: return handleHWQ( instructionWord ); case 0x12: return handleHWI( instructionWord ); case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: case 0x1f: default: return handleUnknownOpCode( instructionWord ); } } private int handleHWI(int instructionWord) { final OperandDesc operand = loadSourceOperand(instructionWord); final int hardwareSlot = operand.value; final IDevice device = getDeviceForSlot( hardwareSlot ); final int cyclesConsumed; if ( device == null ) { if ( ! ignoreAccessToUnknownDevices ) { LOG.error("handleHWI(): No device at slot #"+hardwareSlot); out.warn("No device at slot #"+hardwareSlot); throw new InvalidDeviceSlotNumberException("No device at slot #"+hardwareSlot); } cyclesConsumed = 0; } else { try { cyclesConsumed = device.handleInterrupt( Emulator.this, this , this.memory ); } catch(RuntimeException e) { if ( e instanceof DeviceErrorException) { throw e; } LOG.error("handleHWI(): Device "+device+" failed in handleInterrupt(): "+e.getMessage() , e ); throw new DeviceErrorException("Device "+device+" failed in handleInterrupt(): "+e.getMessage() , device , e ); } } return 4+operand.cycleCount+cyclesConsumed; } /* * * b is always handled by the processor after a, and is the lower five bits. * In bits (in LSB-0 format), a basic instruction has the format: * * aaaaaabbbbbooooo * * SET b,a * * b = TARGET operand * a = SOURCE operand * * --- Values: (5/6 bits) --------------------------------------------------------- * * | C | VALUE | DESCRIPTION * +---+-----------+---------------------------------------------------------------- * | 0 | 0x00-0x07 | register (A, B, C, X, Y, Z, I or J, in that order) * | 0 | 0x08-0x0f | [register] * | 1 | 0x10-0x17 | [register + next word] * | 0 | 0x18 | (PUSH / [--SP]) if in TARGET, or (POP / [SP++]) if in SOURCE * | 0 | 0x19 | [SP] / PEEK * | 1 | 0x1a | [SP + next word] / PICK n * | 0 | 0x1b | SP * | 0 | 0x1c | PC * | 0 | 0x1d | EX * | 1 | 0x1e | [next word] * | 1 | 0x1f | next word (literal) * | 0 | 0x20-0x3f | literal value 0xffff-0x1e (-1..30) (literal) (only for SOURCE) * +---+-----------+---------------------------------------------------------------- */ private int storeTargetOperand(int instructionWord,int value) { return storeTargetOperand( instructionWord , value , false ); } private int storeTargetOperand(int instructionWord,int value,boolean isSpecialOpcode) { final int operandBits; /* * Special opcodes always have their lower five bits unset, have one value and a * five bit opcode. * * In binary, they have the format: aaaaaaooooo00000 */ if ( isSpecialOpcode ) { operandBits = (instructionWord >>> 10) & ( 1+2+4+8+16+32); } else { operandBits = (instructionWord >>> 5) & ( 1+2+4+8+16); } if ( operandBits <= 07 ) { commonRegisters[ operandBits ] = value & 0xffff; return 0; } if ( operandBits <= 0x0f ) { memory.write( commonRegisters[ operandBits - 0x08 ] , value); return 1; } if ( operandBits <= 0x17 ) { final int nextWord = readNextWordAndAdvance(); writeMemoryWithOffsetAndWrapAround( commonRegisters[ operandBits - 0x10 ] , nextWord , value); return 1; } switch( operandBits ) { case 0x18: // (PUSH / [--SP]) if in b, or (POP / [SP++]) if in a push( value ); return 0; case 0x19: // PEEK/[SP] memory.write( sp , value ); return 0; case 0x1a: int nextWord = readNextWordAndAdvance(); Address dst = sp.plus( Address.wordAddress( nextWord ) , true); memory.write( dst , value ); return 1; case 0x1b: sp = Address.wordAddress( value & 0xffff ); return 0; case 0x1c: // PC currentInstructionPtr = value & 0xffff; return 0; case 0x1d: ex = value & 0xffff; return 0; case 0x1e: nextWord = readNextWordAndAdvance(); memory.write( nextWord , value); return 1; default: return handleIllegalTargetOperand(instructionWord); // assignment to literal value } } private int readNextWordAndAdvance() { final int word = memory.read( currentInstructionPtr ); currentInstructionPtr = (currentInstructionPtr+1) & 0xffff; return word; } private OperandDesc loadSourceOperand(int instructionWord) { /* SET b,a * * b = TARGET operand * a = SOURCE operand * * Special opcodes always have their lower five bits unset, have one value and a * five bit opcode. In binary, they have the format: aaaaaaooooo00000 * The value (a) is in the same six bit format as defined earlier. */ final int operandBits= (instructionWord >>> 10) & ( 1+2+4+8+16+32); if ( operandBits <= 0x07 ) { return operandDesc( commonRegisters[ operandBits ] ); } if ( operandBits <= 0x0f ) { return operandDesc( memory.read( commonRegisters[ operandBits - 0x08 ] ) , 1 ); } if ( operandBits <= 0x17 ) { final int nextWord = readNextWordAndAdvance(); return operandDesc( readMemoryWithOffsetAndWrapAround( commonRegisters[ operandBits - 0x10 ] , nextWord ) ,1 ); } switch( operandBits ) { case 0x18: // (PUSH / [--SP]) if in b, or (POP / [SP++]) if in a final OperandDesc tmp = operandDesc( memory.read( sp ) ); sp = sp.incrementByOne(true); return tmp; case 0x19: return operandDesc( memory.read( sp ) , 1 ); case 0x1a: int nextWord = readNextWordAndAdvance(); final Address dst = sp.plus( Address.wordAddress( nextWord ) , true ); return operandDesc( memory.read( dst ) , 1 ); case 0x1b: return operandDesc( sp.getValue() ); case 0x1c: return operandDesc( currentInstructionPtr ); // return operandDesc( pc.getValue() ); case 0x1d: return operandDesc( ex ); case 0x1e: nextWord = readNextWordAndAdvance(); return operandDesc( memory.read( nextWord ) ,1 ); case 0x1f: return operandDesc( readNextWordAndAdvance() , 1 ); } // literal value: -1...30 ( 0x20 - 0x3f ) return operandDesc( ( operandBits - 0x21 ) , 0 ); } private int readMemoryWithOffsetAndWrapAround(int address,int offset) { int realAddress =(int) ( ( address + offset ) % (WordAddress.MAX_ADDRESS +1 ) ); return memory.read( realAddress ); } private void writeMemoryWithOffsetAndWrapAround(int address,int offset,int value) { int realAddress =(int) ( ( address + offset ) % (WordAddress.MAX_ADDRESS +1 ) ); memory.write( realAddress , value ); } /** * * @param instructionWord * @param specialInstruction * @param performIncrementDecrement Whether this invocation should also increment/decrement registers as necessary or * whether this is handled by the caller (because a subsequent STORE will be performed ) * @return */ protected OperandDesc loadTargetOperand(int instructionWord,boolean specialInstruction,boolean performIncrementDecrement) { /* * SET b,a * * b = TARGET operand * a = SOURCE operand * * SOURCE is always handled by the processor BEFORE TARGET, and is the lower five bits. * In bits (in LSB-0 format), a basic instruction has the format: * * aaaaaabbbbbooooo * * SPECIAL opcodes always have their lower five bits unset, have one value and a * five bit opcode. In binary, they have the format: * * aaaaaaooooo00000 * * The value (a) is in the same six bit format as defined earlier. */ final int operandBits; if ( specialInstruction ) { operandBits= (instructionWord >>> 10) & ( 1+2+4+8+16+32); } else { operandBits= (instructionWord >>> 5) & ( 1+2+4+8+16); } if ( operandBits <= 0x07 ) { return operandDesc( commonRegisters[ operandBits ] ); } if ( operandBits <= 0x0f ) { return operandDesc( memory.read( commonRegisters[ operandBits - 0x08 ] ) , 1 ); } if ( operandBits <= 0x17 ) { final int nextWord; if ( performIncrementDecrement ) { nextWord = readNextWordAndAdvance(); } else { nextWord = memory.read( currentInstructionPtr ); } return operandDesc( readMemoryWithOffsetAndWrapAround( commonRegisters[ operandBits - 0x10 ] , nextWord ) ,1 ); } switch( operandBits ) { case 0x18: // (PUSH / [--SP++]) if in b return operandDesc( memory.read( sp.decrementByOne() ) , 1 ); case 0x19: return operandDesc( memory.read( sp ) , 1 ); case 0x1a: int nextWord = 0; if ( performIncrementDecrement ) { nextWord = readNextWordAndAdvance(); } else { nextWord = memory.read( currentInstructionPtr ); } final Address dst = sp.plus( Address.wordAddress( nextWord ) , true ); return operandDesc( memory.read( dst ) , 1 ); case 0x1b: return operandDesc( sp.getValue() ); case 0x1c: return operandDesc( currentInstructionPtr ); case 0x1d: return operandDesc( ex ); case 0x1e: if ( performIncrementDecrement ) { nextWord = readNextWordAndAdvance(); } else { nextWord = memory.read( currentInstructionPtr ); } return operandDesc( memory.read( nextWord ) ,1 ); case 0x1f: if ( performIncrementDecrement ) { nextWord = readNextWordAndAdvance(); } else { nextWord = memory.read( currentInstructionPtr ); } return operandDesc( nextWord , 1 ); } // literal value: -1...30 ( 0x20 - 0x3f ) return operandDesc( operandBits - 0x21 , 0 ); } private int handleHWQ(int instructionWord) { // Sets A, B, C, X, Y registers to information about hardware a. final OperandDesc operand = loadSourceOperand(instructionWord); final int hardwareSlot = operand.value; final IDevice device = getDeviceForSlot( hardwareSlot ); if ( device == null ) { if ( ! ignoreAccessToUnknownDevices ) { LOG.error("handleHWQ(): No device at slot #"+hardwareSlot); out.warn("No device at slot #"+hardwareSlot); throw new InvalidDeviceSlotNumberException("No device at slot #"+hardwareSlot); } commonRegisters[0] = 0xffff; commonRegisters[1] = 0xffff; commonRegisters[2] = 0xffff; commonRegisters[3] = 0xffff; commonRegisters[4] = 0xffff; } else { /* sets A, B, C, X, Y registers to information about hardware a * * A+(B<<16) is a 32 bit word identifying the hardware id * C is the hardware version * X+(Y<<16) is a 32 bit word identifying the manufacturer */ /* A+(B<<16) is a 32 bit word identifying the hardware id * * A = LSB hardware ID (16 bit) * B = MSB hardware ID (16 bit) * C = hardware version * X = LSB manufacturer ID (16 bit) * Y = MSB manufacturer ID (16 bit) */ final DeviceDescriptor descriptor = device.getDeviceDescriptor(); commonRegisters[0] = (int) descriptor.getID() & 0xffff; commonRegisters[1] = (int) ( ( descriptor.getID() >>> 16 ) & 0xffff ); commonRegisters[2] = descriptor.getVersion() & 0xffff; commonRegisters[3] = (int) descriptor.getManufacturer() & 0xffff; commonRegisters[4] = (int) ( ( descriptor.getManufacturer() >>> 16 ) & 0xffff ); } return 4+operand.cycleCount; } private int handleHWN(int instructionWord) { // sets a to number of connected hardware devices final int deviceCount; synchronized( devices ) { deviceCount=devices.size(); } return 2 + storeTargetOperand( instructionWord , deviceCount , true ); } private int handleIAQ(int instructionWord) { /* if a is nonzero, interrupts will be added to the queue * instead of triggered. if a is zero, interrupts will be * triggered as normal again */ final OperandDesc operand = loadSourceOperand( instructionWord ); setQueueInterrupts( operand.value != 0 ); return 2+operand.cycleCount; } private int handleRFI(int instructionWord) { /* * 3 | 0x0b | RFI a | disables interrupt queueing, pops A from the stack, then | | | pops PC from the stack */ setQueueInterrupts( false ); commonRegisters[0] = pop(); // pop A from stack currentInstructionPtr = pop(); // pop PC from stack return 3; } private int handleIllegalTargetOperand(int instructionWord) { final String msg = "Illegal target operand in instruction word 0x"+ Misc.toHexString( instructionWord )+" at address 0x"+Misc.toHexString( pc ); LOG.error("handleIllegalTargetOperand(): "+msg); out.warn( msg); throw new InvalidTargetOperandException( msg ); } private int handleIAS(int instructionWord) { // IAS a => sets IA to a final OperandDesc operand = loadSourceOperand( instructionWord ); interruptAddress = Address.wordAddress( operand.value ); return 1+operand.cycleCount; } private int handleIAG(int instructionWord) { // IAG a => sets A to IA return 1+storeTargetOperand( instructionWord , interruptAddress.getValue() , true ); } private int handleINT(int instructionWord) { final OperandDesc operand = loadSourceOperand( instructionWord ); triggerInterrupt(new SoftwareInterrupt( operand.value )); return 4+operand.cycleCount; } private int handleJSR(int instructionWord) { // pushes the address of the next instruction to the stack, then sets PC to a OperandDesc source= loadSourceOperand( instructionWord ); push( currentInstructionPtr ); currentInstructionPtr = source.value; return 3+source.cycleCount; } private int pop() { // SET a, [SP++] final int result = memory.read( sp ); sp= sp.incrementByOne(true); return result; } private void push(int value) { // SET [--SP] , blubb sp = sp.decrementByOne(); memory.write( sp , value ); } public boolean maybeProcessOneInterrupt() { if ( interruptsEnabled() ) { final IInterrupt irq = getNextProcessableInterrupt( true ); if ( irq != null ) { // push PC to stack // SET [ --SP ] , PC push( pc.getValue() ); // push A to stack push( commonRegisters[0] ); pc = interruptAddress; commonRegisters[0] = irq.getMessage() & 0xffff; return true; } } return false; } } // end of class: CPU }
fixed emulator glitch with arithmetic operations that use EX to return some additional result/flags and EX being the target (b) operand itself. In this case, the emulator must not write the operation's actual result to EX as well.
src/main/java/de/codesourcery/jasm16/emulator/Emulator.java
fixed emulator glitch with arithmetic operations that use EX to return some additional result/flags and EX being the target (b) operand itself.
<ide><path>rc/main/java/de/codesourcery/jasm16/emulator/Emulator.java <ide> } else { <ide> ex = 0; <ide> } <add> if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result <add> return 3+source.cycleCount; <add> } <ide> return 3+storeTargetOperand( instructionWord , result & 0xffff )+source.cycleCount; <ide> } <ide> <ide> ex = 0x0001; <ide> } else { <ide> ex = 0; <add> } <add> if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result <add> return 3+source.cycleCount; <ide> } <ide> return 3+storeTargetOperand( instructionWord , acc & 0xffff )+source.cycleCount; <ide> } <ide> <ide> final int acc = target.value << source.value; <ide> ex = (( target.value << source.value)>>16 ) & 0xffff; <add> if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result <add> return 1+source.cycleCount; <add> } <ide> return 1+storeTargetOperand( instructionWord , acc )+source.cycleCount; <ide> } <ide> <ide> <ide> final int acc = signed( target.value ) >> source.value; <ide> ex = (( signed( target.value ) << 16) >>> source.value ) & 0xffff; <add> if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result <add> return 1+source.cycleCount; <add> } <ide> return 1+storeTargetOperand( instructionWord , acc )+source.cycleCount; <ide> } <ide> <ide> <ide> final int acc = target.value >>> source.value; <ide> ex = (( target.value << 16) >> source.value ) & 0xffff; <add> <add> if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result <add> return 1+source.cycleCount; <add> } <ide> return 1+storeTargetOperand( instructionWord , acc )+source.cycleCount; <ide> } <ide> <ide> acc=0; <ide> } else { <ide> acc = signed( target.value ) / signed( source.value ); <add> // ((b<<16)/a)&0xffff <ide> ex = (( signed( target.value ) << 16) / signed( source.value) )& 0xffff; <ide> } <add> if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result <add> return 3+source.cycleCount; <add> } <ide> return 3+storeTargetOperand( instructionWord , acc )+source.cycleCount; <ide> } <ide> <ide> long sv = source.value; <ide> ex = (int) ( (( tv << 16) / sv ) & 0xffff); <ide> } <add> if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result <add> return 3+source.cycleCount; <add> } <ide> return 3+storeTargetOperand( instructionWord , acc )+source.cycleCount; <ide> } <ide> <ide> final int b = signed( source.value ); <ide> <ide> final int acc = a * b; <del> ex = ((a * b) >> 16 ) & 0xffff; <add> ex = ((a * b) >> 16 ) & 0xffff; <add> <add> if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result <add> return 2+source.cycleCount; <add> } <ide> return 2+storeTargetOperand( instructionWord , acc )+source.cycleCount; <ide> } <ide> <ide> <ide> final int acc = target.value * source.value; <ide> ex = ((target.value * source.value) >> 16 ) & 0xffff; <add> <add> if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result <add> return 2+source.cycleCount; <add> } <ide> return 2+storeTargetOperand( instructionWord , acc )+source.cycleCount; <ide> } <ide> <ide> } else { <ide> ex = 0; <ide> } <add> if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result <add> return 2+source.cycleCount; <add> } <ide> return 2+storeTargetOperand( instructionWord , acc )+source.cycleCount; <ide> } <ide> <ide> } else { <ide> ex = 0; <ide> } <add> if ( isEXTargetOperand( instructionWord ) ) { // Do not overwrite EX with result <add> return 2+source.cycleCount; <add> } <ide> return 2+storeTargetOperand( instructionWord , acc )+source.cycleCount; <ide> } <ide> <ide> return operandDesc( sp.getValue() ); <ide> case 0x1c: <ide> return operandDesc( currentInstructionPtr ); <del>// return operandDesc( pc.getValue() ); <ide> case 0x1d: <ide> return operandDesc( ex ); <ide> case 0x1e: <ide> int realAddress =(int) ( ( address + offset ) % (WordAddress.MAX_ADDRESS +1 ) ); <ide> memory.write( realAddress , value ); <ide> } <add> <add> protected final boolean isEXTargetOperand(int instructionWord) <add> { <add> final int operandBits; <add> if ( (instructionWord & 0b11111) == 0 ) { // special instruction <add> operandBits= (instructionWord >>> 10) & ( 1+2+4+8+16+32); <add> } else { <add> operandBits= (instructionWord >>> 5) & ( 1+2+4+8+16); <add> } <add> return operandBits == 0x1d; <add> } <ide> <ide> /** <ide> *
JavaScript
mit
5ffc949ac04f05cf9acf697f2fa151b872295489
0
medikoo/dbjs-dom
'use strict'; var aFrom = require('es5-ext/lib/Array/from') , compact = require('es5-ext/lib/Array/prototype/compact') , isCopy = require('es5-ext/lib/Array/prototype/is-copy') , copy = require('es5-ext/lib/Object/copy') , extend = require('es5-ext/lib/Object/extend') , d = require('es5-ext/lib/Object/descriptor') , isObject = require('es5-ext/lib/Object/is-object') , callable = require('es5-ext/lib/Object/valid-callable') , memoize = require('memoizee/lib/primitive') , makeEl = require('dom-ext/lib/Document/prototype/make-element') , append = require('dom-ext/lib/Element/prototype/append') , clear = require('dom-ext/lib/Element/prototype/clear') , remove = require('dom-ext/lib/Element/prototype/remove') , replaceCont = require('dom-ext/lib/Element/prototype/replace-content') , dispatchEvnt = require('dom-ext/lib/HTMLElement/prototype/dispatch-event-2') , ObjectType = require('dbjs').Object , serialize = require('dbjs/lib/utils/serialize') , DOMInput = require('../_controls/input') , eventOpts = require('../_event-options') , isArray = Array.isArray, map = Array.prototype.map , defineProperty = Object.defineProperty , getName = Object.getOwnPropertyDescriptor(DOMInput.prototype, 'name').get , File = require('dbjs/lib/objects')._get('File') , Input, render, renderItem; require('../'); require('memoizee/lib/ext/method'); render = function (options) { var el = this.make; return el('div', { class: 'dbjs-file' }, this.valueDOM = this.multiple ? el('ul') : el('span'), el('label', { class: 'dbjs-file-input' }, options.label, this.control = el('input', { type: 'file' }))); }; renderItem = function (file) { var el = this.make, data = {}; data.dom = el(this.multiple ? 'li' : 'span', { 'data-id': file._id_ }); append.call(data.dom, el('a', { href: file._url, target: '_blank' }, file._name), " ", data.control = el('input', { type: 'hidden', name: this.name, value: file._id_ }), el('a', { class: 'clear', onclick: this.removeItem.bind(this, data.dom) }, "x")); return data; }; Input = function (document, ns/*, options*/) { var options = Object(arguments[2]); this.make = makeEl.bind(document); this.controls = []; if (options.multiple) this.multiple = true; ((options.render == null) || callable(options.render)); defineProperty(this, 'renderItem', d((options.renderItem == null) ? renderItem : callable(options.renderItem))); DOMInput.call(this, document, ns, options); if (this.multiple) this.control.setAttribute('multiple', 'multiple'); this.control.setAttribute('accept', ns.accept.values.join(',')); }; Input.prototype = Object.create(DOMInput.prototype, extend({ constructor: d(Input), multiple: d(false), _value: d(null), controlAttributes: d(extend(copy(DOMInput.prototype.controlAttributes), { required: true })), dbAttributes: d(extend(copy(DOMInput.prototype.dbAttributes), { required: true })), _render: d(function (options) { this.dom = (options.render || render).call(this, options); this.controls.push(this.control); }), name: d.gs(getName, function (name) { this._name = name; name = this.name; this.controls.forEach(function (input) { input.name = name; }); }), inputValue: d.gs(function () { var value; if (!this.multiple) { if (this.control.files[0]) return this.control.files[0]; if (!this.valueDOM.firstChild) return null; return this.valueDOM.firstChild.getAttribute('data-id'); } value = map.call(this.valueDOM.childNodes, function (node) { var id = node.getAttribute('data-id'); if (!id) { throw new TypeError("Missing id (data-id attribute) on file item"); } return id; }).concat(aFrom(this.control.files)); return value.length ? value : null; }, function (nu) { var old = this.inputValue, changed; this._value = nu; if (this.multiple) { if (nu) { if (!old || !isCopy.call(nu, old)) { this.control.value = null; replaceCont.call(this.valueDOM, nu.map(this._renderItem)); changed = true; } } else { clear.call(this.valueDOM); } } else if (nu !== old) { this.control.value = null; if (nu) { replaceCont.call(this.valueDOM, this._renderItem(nu)); this.dom.classList.add('filled'); } else { clear.call(this.valueDOM); this.dom.classList.remove('filled'); } changed = true; } if (changed) { try { dispatchEvnt.call(this.control, 'change', eventOpts); } catch (ignore) {} } else { this.onChange(); } }), value: d.gs(function () { var value = this.inputValue; if (value == null) return null; if (this.multiple) return value.map(this.ns.toInputValue, this.ns); return this.ns.toInputValue(value); }, function (value) { if (value == null) { value = null; } else if (this.multiple) { if (!value._isSet_) throw new TypeError("Expected set value"); if (value._type_ === 'relation') { value = value.values.map(serialize).sort(function (a, b) { return value[a].order - value[b].order; }).map(function (key) { return value[key]._subject_; }); } else { value = value.values; } if (!value.length) value = null; else value = compact.call(value.map(this.ns.toInputValue, this.ns)); } else { value = this.ns.toInputValue(value); } this.inputValue = value; }), onChange: d(function () { var value, changed, valid, emitChanged, emitValid; value = this.inputValue; changed = (this.multiple && (this._value != null) && (value != null)) ? isCopy.call(value, this._value) : (value !== this._value); valid = this.required ? (value != null) : true; if (this.changed !== changed) { this.changed = changed; emitChanged = true; } if (this.valid !== valid) { this.valid = valid; emitValid = true; } this.emit('change', value); if (emitChanged) this.emit('change:changed', this.changed); if (emitValid) this.emit('change:valid', this.valid); }), removeItem: d(function (dom) { remove.call(dom); if (!this.multiple) this.dom.classList.remove('filled'); dispatchEvnt.call(this.control, 'change', eventOpts); }) }, memoize(function (file) { var data; file = File[file]; data = this.renderItem(file); this.controls.push(data.control); return data.dom; }, { method: '_renderItem' }))); module.exports = Object.defineProperties(File, { fromInputValue: d(function (value) { if (value == null) return null; if (isArray(value) && (value.length === 2)) { if (typeof value[0] === 'string') { if (isObject(value[1])) return value[1]; } else if (typeof value[1] === 'string') { if (isObject(value[0])) return value[0]; } return value; } if (isObject(value)) return value; value = value.trim(); if (!value) return null; if (!this.propertyIsEnumerable(value)) return null; if (this[value]._id_ !== value) return null; return this[value]; }), DOMInput: d(Input), toDOMInput: d(function (document/*, options*/) { var options = Object(arguments[1]); if (options.multiple || (options.type !== 'checkbox')) { return new this.DOMInput(document, this, options); } return ObjectType.toDOMInput(document, options); }) });
input/object/file.dom.js
'use strict'; var aFrom = require('es5-ext/lib/Array/from') , compact = require('es5-ext/lib/Array/prototype/compact') , isCopy = require('es5-ext/lib/Array/prototype/is-copy') , copy = require('es5-ext/lib/Object/copy') , extend = require('es5-ext/lib/Object/extend') , d = require('es5-ext/lib/Object/descriptor') , isObject = require('es5-ext/lib/Object/is-object') , callable = require('es5-ext/lib/Object/valid-callable') , memoize = require('memoizee/lib/primitive') , makeEl = require('dom-ext/lib/Document/prototype/make-element') , append = require('dom-ext/lib/Element/prototype/append') , clear = require('dom-ext/lib/Element/prototype/clear') , remove = require('dom-ext/lib/Element/prototype/remove') , replaceCont = require('dom-ext/lib/Element/prototype/replace-content') , dispatchEvnt = require('dom-ext/lib/HTMLElement/prototype/dispatch-event-2') , ObjectType = require('dbjs').Object , serialize = require('dbjs/lib/utils/serialize') , DOMInput = require('../_controls/input') , eventOpts = require('../_event-options') , isArray = Array.isArray, map = Array.prototype.map , defineProperty = Object.defineProperty , getName = Object.getOwnPropertyDescriptor(DOMInput.prototype, 'name').get , File = require('dbjs/lib/objects')._get('File') , Input, render, renderItem; require('../'); require('memoizee/lib/ext/method'); render = function (options) { var el = this.make; return el('div', { class: 'dbjs-file' }, this.valueDOM = this.multiple ? el('ul') : el('span'), el('label', { class: 'dbjs-file-input' }, options.label, this.control = el('input', { type: 'file' }))); }; renderItem = function (file) { var el = this.make, data = {}; data.dom = el(this.multiple ? 'li' : 'span', { 'data-id': file._id_ }); append.call(data.dom, el('a', { href: file._url, target: '_blank' }, file._name), " ", data.control = el('input', { type: 'hidden', name: this.name, value: file._id_ }), el('a', { class: 'clear', onclick: this.removeItem.bind(this, data.dom) }, "x")); return data; }; Input = function (document, ns/*, options*/) { var options = Object(arguments[2]); this.make = makeEl.bind(document); this.controls = []; if (options.multiple) this.multiple = true; ((options.render == null) || callable(options.render)); defineProperty(this, 'renderItem', d((options.renderItem == null) ? renderItem : callable(options.renderItem))); DOMInput.call(this, document, ns, options); if (this.multiple) this.control.setAttribute('multiple', 'multiple'); this.control.setAttribute('accept', ns.accept.values.join(',')); }; Input.prototype = Object.create(DOMInput.prototype, extend({ constructor: d(Input), multiple: d(false), _value: d(null), controlAttributes: d(extend(copy(DOMInput.prototype.controlAttributes), { required: true })), dbAttributes: d(extend(copy(DOMInput.prototype.dbAttributes), { required: true })), _render: d(function (options) { this.dom = (options.render || render).call(this, options); this.controls.push(this.control); }), name: d.gs(getName, function (name) { this._name = name; name = this.name; this.controls.forEach(function (input) { input.name = name; }); }), inputValue: d.gs(function () { var value; if (!this.multiple) { if (this.control.files[0]) return this.control.files[0]; if (!this.valueDOM.firstChild) return null; return this.valueDOM.firstChild.getAttribute('data-id'); } value = map.call(this.valueDOM.childNodes, function (node) { return node.getAttribute('data-id'); }).concat(aFrom(this.control.files)); return value.length ? value : null; }, function (nu) { var old = this.inputValue, changed; this._value = nu; if (this.multiple) { if (nu) { if (!old || !isCopy.call(nu, old)) { this.control.value = null; replaceCont.call(this.valueDOM, nu.map(this._renderItem)); changed = true; } } else { clear.call(this.valueDOM); } } else if (nu !== old) { this.control.value = null; if (nu) { replaceCont.call(this.valueDOM, this._renderItem(nu)); this.dom.classList.add('filled'); } else { clear.call(this.valueDOM); this.dom.classList.remove('filled'); } changed = true; } if (changed) { try { dispatchEvnt.call(this.control, 'change', eventOpts); } catch (ignore) {} } else { this.onChange(); } }), value: d.gs(function () { var value = this.inputValue; if (value == null) return null; if (this.multiple) return value.map(this.ns.toInputValue, this.ns); return this.ns.toInputValue(value); }, function (value) { if (value == null) { value = null; } else if (this.multiple) { if (!value._isSet_) throw new TypeError("Expected set value"); if (value._type_ === 'relation') { value = value.values.map(serialize).sort(function (a, b) { return value[a].order - value[b].order; }).map(function (key) { return value[key]._subject_; }); } else { value = value.values; } if (!value.length) value = null; else value = compact.call(value.map(this.ns.toInputValue, this.ns)); } else { value = this.ns.toInputValue(value); } this.inputValue = value; }), onChange: d(function () { var value, changed, valid, emitChanged, emitValid; value = this.inputValue; changed = (this.multiple && (this._value != null) && (value != null)) ? isCopy.call(value, this._value) : (value !== this._value); valid = this.required ? (value != null) : true; if (this.changed !== changed) { this.changed = changed; emitChanged = true; } if (this.valid !== valid) { this.valid = valid; emitValid = true; } this.emit('change', value); if (emitChanged) this.emit('change:changed', this.changed); if (emitValid) this.emit('change:valid', this.valid); }), removeItem: d(function (dom) { remove.call(dom); if (!this.multiple) this.dom.classList.remove('filled'); dispatchEvnt.call(this.control, 'change', eventOpts); }) }, memoize(function (file) { var data; file = File[file]; data = this.renderItem(file); this.controls.push(data.control); return data.dom; }, { method: '_renderItem' }))); module.exports = Object.defineProperties(File, { fromInputValue: d(function (value) { if (value == null) return null; if (isArray(value) && (value.length === 2)) { if (typeof value[0] === 'string') { if (isObject(value[1])) return value[1]; } else if (typeof value[1] === 'string') { if (isObject(value[0])) return value[0]; } return value; } if (isObject(value)) return value; value = value.trim(); if (!value) return null; if (!this.propertyIsEnumerable(value)) return null; if (this[value]._id_ !== value) return null; return this[value]; }), DOMInput: d(Input), toDOMInput: d(function (document/*, options*/) { var options = Object(arguments[1]); if (options.multiple || (options.type !== 'checkbox')) { return new this.DOMInput(document, this, options); } return ObjectType.toDOMInput(document, options); }) });
Throw on missing id
input/object/file.dom.js
Throw on missing id
<ide><path>nput/object/file.dom.js <ide> return this.valueDOM.firstChild.getAttribute('data-id'); <ide> } <ide> value = map.call(this.valueDOM.childNodes, function (node) { <del> return node.getAttribute('data-id'); <add> var id = node.getAttribute('data-id'); <add> if (!id) { <add> throw new TypeError("Missing id (data-id attribute) on file item"); <add> } <add> return id; <ide> }).concat(aFrom(this.control.files)); <ide> return value.length ? value : null; <ide> }, function (nu) {
JavaScript
mpl-2.0
753ecf4aceb407439cfed31af9135764fc9154bd
0
dequelabs/axe-core,dequelabs/axe-core,dequelabs/axe-core,dequelabs/axe-core
module.exports = { evaluate: 'function (node, options, virtualNode, context) {\n<%=source%>\n}', after: 'function (results, options) {\n<%=source%>\n}', gather: 'function (context, options) {\n<%=source%>\n}', matches: 'function (node, virtualNode, context) {\n<%=source%>\n}', source: '(function () {\n<%=source%>\n}())', commons: '<%=source%>' };
build/templates.js
module.exports = { evaluate: 'function (node, options, virtualNode, context) {\n<%=source%>\n}', after: 'function (results, options) {\n<%=source%>\n}', gather: 'function (context) {\n<%=source%>\n}', matches: 'function (node, virtualNode, context) {\n<%=source%>\n}', source: '(function () {\n<%=source%>\n}())', commons: '<%=source%>' };
fix: arguments for gather function in build template (#1605)
build/templates.js
fix: arguments for gather function in build template (#1605)
<ide><path>uild/templates.js <ide> module.exports = { <ide> evaluate: 'function (node, options, virtualNode, context) {\n<%=source%>\n}', <ide> after: 'function (results, options) {\n<%=source%>\n}', <del> gather: 'function (context) {\n<%=source%>\n}', <add> gather: 'function (context, options) {\n<%=source%>\n}', <ide> matches: 'function (node, virtualNode, context) {\n<%=source%>\n}', <ide> source: '(function () {\n<%=source%>\n}())', <ide> commons: '<%=source%>'
Java
mit
2ba791189d35cd8019b8f3f94fe4c95faf68bccd
0
Innovimax-SARL/mix-them
package innovimax.mixthem; import innovimax.mixthem.arguments.Arguments; import innovimax.mixthem.arguments.ArgumentException; import java.io.IOException; import java.util.zip.ZipException; import org.junit.Assert; import org.junit.Test; /* Created by innovimax-jim Basic tests for this application */ public class BasicTest { @Test public final void testPrintUsage() { Arguments.printUsage(); Assert.assertTrue(true); } @Test(expected=ArgumentException.class) public final void testEmptyArgs() throws ArgumentException, IOException, ZipException { try { final String args[] = {}; final Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testEmptyArgs: " + e.getMessage()); throw e; } } @Test(expected=ArgumentException.class) public final void testWrongArgs() throws ArgumentException, IOException, ZipException { try { final String args[] = { "ghost1", "ghost2" }; final Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testWrongArgs: " + e.getMessage()); throw e; } } @Test public final void testNoRule() throws ArgumentException, IOException, ZipException { final String args[] = { getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); Assert.assertTrue(true); } @Test public final void test1Rule() throws ArgumentException, IOException, ZipException { final String args[] = { "-1", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); Assert.assertTrue(true); } @Test(expected=ArgumentException.class) public final void testUnknownRule() throws ArgumentException, IOException, ZipException { try { final String args[] = { "-x", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testUnknownRule: " + e.getMessage()); throw e; } } @Test(expected=ArgumentException.class) public final void testUnexpectedParam() throws ArgumentException, IOException, ZipException { try { final String args[] = { "-1", "#val", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testUnexpectedParam: " + e.getMessage()); throw e; } } @Test(expected=ArgumentException.class) public final void testWrongSeedParam() throws ArgumentException, IOException, ZipException { try { final String args[] = { "-random-alt-line", "#val", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testWrongSeedParam: " + e.getMessage()); throw e; } } @Test public final void testValidSeedParam() throws ArgumentException, IOException, ZipException { final String args[] = { "-random-alt-line", "#1789", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() }; Arguments mixArgs = Arguments.checkArguments(args); Assert.assertTrue(true); } @Test(expected=ArgumentException.class) public final void testNotAParam() throws ArgumentException, IOException, ZipException { try { final String args[] = { "-random-alt-line", "1789", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testNotAParam: " + e.getMessage()); throw e; } } @Test public final void testOptionalParam() throws ArgumentException, IOException, ZipException { final String args[] = { "-random-alt-line", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); Assert.assertTrue(true); } @Test(expected=ArgumentException.class) public final void testZipEmptyArgs() throws ArgumentException, IOException, ZipException { try { final String args[] = { "--zip" }; Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testZipEmptyArgs: " + e.getMessage()); throw e; } } @Test(expected=ArgumentException.class) public final void testZipWrongArgs() throws ArgumentException, IOException, ZipException { try { final String args[] = { "--zip", "zip/ghost1" }; final Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testZipWrongArgs: " + e.getMessage()); throw e; } } @Test public final void testZipNoRule() throws ArgumentException, IOException, ZipException { final String args[] = { "--zip", getClass().getResource("zip/test001.zip").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); Assert.assertTrue(true); } @Test public final void testJar1Rule() throws ArgumentException, IOException, ZipException { final String args[] = { "-1", "--jar", getClass().getResource("zip/test001.jar").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); Assert.assertTrue(true); } @Test(expected=ArgumentException.class) public final void testZipOneFile() throws ArgumentException, IOException, ZipException { try { final String args[] = { "--zip", getClass().getResource("zip/wrong.zip").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testZipOneFile: " + e.getMessage()); throw e; } } @Test(expected=ArgumentException.class) public final void testJarEmpty() throws ArgumentException, IOException, ZipException { try { final String args[] = { "--jar", getClass().getResource("zip/empty.jar").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testJarEmpty: " + e.getMessage()); throw e; } } @Test(expected=ArgumentException.class) public final void testMandatoryParam() throws ArgumentException, IOException, ZipException { try { final String args[] = { "-file", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testMandatoryParam: " + e.getMessage()); throw e; } } }
src/test/java/innovimax/mixthem/BasicTest.java
package innovimax.mixthem; import innovimax.mixthem.arguments.Arguments; import innovimax.mixthem.arguments.ArgumentException; import java.io.IOException; import java.util.zip.ZipException; import org.junit.Assert; import org.junit.Test; /* Created by innovimax-jim Basic tests for this application */ public class BasicTest { @Test public final void testPrintUsage() { Arguments.printUsage(); Assert.assertTrue(true); } @Test(expected=ArgumentException.class) public final void testEmptyArgs() throws ArgumentException, IOException, ZipException { try { final String args[] = {}; final Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testEmptyArgs: " + e.getMessage()); throw e; } } @Test(expected=ArgumentException.class) public final void testWrongArgs() throws ArgumentException, IOException, ZipException { try { final String args[] = { "ghost1", "ghost2" }; final Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testWrongArgs: " + e.getMessage()); throw e; } } @Test public final void testNoRule() throws ArgumentException, IOException, ZipException { final String args[] = { getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); Assert.assertTrue(true); } @Test public final void test1Rule() throws ArgumentException, IOException, ZipException { final String args[] = { "-1", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); Assert.assertTrue(true); } @Test(expected=ArgumentException.class) public final void testUnknownRule() throws ArgumentException, IOException, ZipException { try { final String args[] = { "-x", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testUnknownRule: " + e.getMessage()); throw e; } } @Test(expected=ArgumentException.class) public final void testUnexpectedParam() throws ArgumentException, IOException, ZipException { try { final String args[] = { "-1", "#val", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testUnexpectedParam: " + e.getMessage()); throw e; } } @Test(expected=ArgumentException.class) public final void testWrongSeedParam() throws ArgumentException, IOException, ZipException { try { final String args[] = { "-random-alt-line", "#val", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testWrongSeedParam: " + e.getMessage()); throw e; } } @Test public final void testValidSeedParam() throws ArgumentException, IOException, ZipException { final String args[] = { "-random-alt-line", "#1789", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() }; Arguments mixArgs = Arguments.checkArguments(args); Assert.assertTrue(true); } @Test(expected=ArgumentException.class) public final void testNotAParam() throws ArgumentException, IOException, ZipException { try { final String args[] = { "-random-alt-line", "1789", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testNotAParam: " + e.getMessage()); throw e; } } @Test public final void testOptionalParam() throws ArgumentException, IOException, ZipException { final String args[] = { "-random-alt-line", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); Assert.assertTrue(true); } @Test(expected=ArgumentException.class) public final void testZipEmptyArgs() throws ArgumentException, IOException, ZipException { try { final String args[] = { "--zip" }; Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testZipEmptyArgs: " + e.getMessage()); throw e; } } @Test(expected=ArgumentException.class) public final void testZipWrongArgs() throws ArgumentException, IOException, ZipException { try { final String args[] = { "--zip", "zip/ghost1" }; final Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testZipWrongArgs: " + e.getMessage()); throw e; } } @Test public final void testZipNoRule() throws ArgumentException, IOException, ZipException { final String args[] = { "--zip", getClass().getResource("zip/test001.zip").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); Assert.assertTrue(true); } @Test public final void testJar1Rule() throws ArgumentException, IOException, ZipException { final String args[] = { "-1", "--jar", getClass().getResource("zip/test001.jar").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); Assert.assertTrue(true); } @Test(expected=ArgumentException.class) public final void testZipOneFile() throws ArgumentException, IOException, ZipException { try { final String args[] = { "--zip", getClass().getResource("zip/wrong.zip").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testZipOneFile: " + e.getMessage()); throw e; } } @Test(expected=ArgumentException.class) public final void testJarEmpty() throws ArgumentException, IOException, ZipException { try { final String args[] = { "--jar", getClass().getResource("zip/empty.jar").getFile() }; final Arguments mixArgs = Arguments.checkArguments(args); } catch (ArgumentException e) { System.out.println("testJarEmpty: " + e.getMessage()); throw e; } } }
Update BasicTest.java
src/test/java/innovimax/mixthem/BasicTest.java
Update BasicTest.java
<ide><path>rc/test/java/innovimax/mixthem/BasicTest.java <ide> } <ide> } <ide> <add> @Test(expected=ArgumentException.class) <add> public final void testMandatoryParam() throws ArgumentException, IOException, ZipException { <add> try { <add> final String args[] = { "-file", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() }; <add> final Arguments mixArgs = Arguments.checkArguments(args); <add> } catch (ArgumentException e) { <add> System.out.println("testMandatoryParam: " + e.getMessage()); <add> throw e; <add> } <add> } <add> <ide> }
Java
mit
e8e75c300c99032b1cf419f0ebb9914d2008d185
0
CyberPuck/RoboticsSimulator
package inputs; import utilities.Point; /** * Holds the user defined input for a circle path. * <p/> * Created by CyberPuck on 2016-03-01. */ public class CirclePathInput implements RobotInput { private InputMode mode = InputMode.PATH_CIRCLE; // Robot starting location private Point origin; // Radius of the circle private double radius; // inclination angle of the radius from the origin private double inclination; // end orientation of the robot private double endOrientation; // rate the robot needs to rotate to reach the end orientation private double rotationRate; // speed of the robot private double speed; // time to complete the circle private double time; // index for the path private int currentIndex; public CirclePathInput(Point origin, double radius, double inclination, double endOrientation, double rotationRate, double speed, double time) { this.origin = origin; this.radius = radius; this.inclination = inclination; this.endOrientation = endOrientation; this.rotationRate = rotationRate; this.speed = speed; this.time = time; } @Override public InputMode getMode() { return mode; } public double getEndOrientation() { return endOrientation; } public double getRotationRate() { return rotationRate; } public double getSpeed() { return speed; } public void setSpeed(double speed) { this.speed = speed; } public double getTime() { return time; } public Point getOrigin() { return origin; } public double getRadius() { return radius; } public double getInclination() { return inclination; } public int getCurrentIndex() { return currentIndex; } public void setCurrentIndex(int currentIndex) { this.currentIndex = currentIndex; } @Override public String toString() { return "CirclePathInput{" + "mode=" + mode + ", origin=" + origin + ", radius=" + radius + ", inclination=" + inclination + ", endOrientation=" + endOrientation + ", rotationRate=" + rotationRate + ", speed=" + speed + ", time=" + time + '}'; } }
src/main/src/inputs/CirclePathInput.java
package inputs; import utilities.Point; /** * Holds the user defined input for a circle path. * <p/> * Created by CyberPuck on 2016-03-01. */ public class CirclePathInput implements RobotInput { private InputMode mode = InputMode.PATH_CIRCLE; // Robot starting location private Point origin; // Radius of the circle private double radius; // inclination angle of the radius from the origin private double inclination; // end orientation of the robot private double endOrientation; // rate the robot needs to rotate to reach the end orientation private double rotationRate; // speed of the robot private double speed; // time to complete the circle private double time; public CirclePathInput(Point origin, double radius, double inclination, double endOrientation, double rotationRate, double speed, double time) { this.origin = origin; this.radius = radius; this.inclination = inclination; this.endOrientation = endOrientation; this.rotationRate = rotationRate; this.speed = speed; this.time = time; } @Override public InputMode getMode() { return mode; } public double getEndOrientation() { return endOrientation; } public double getRotationRate() { return rotationRate; } public double getSpeed() { return speed; } public void setSpeed(double speed) { this.speed = speed; } public double getTime() { return time; } public Point getOrigin() { return origin; } public double getRadius() { return radius; } public double getInclination() { return inclination; } @Override public String toString() { return "CirclePathInput{" + "mode=" + mode + ", origin=" + origin + ", radius=" + radius + ", inclination=" + inclination + ", endOrientation=" + endOrientation + ", rotationRate=" + rotationRate + ", speed=" + speed + ", time=" + time + '}'; } }
Adding current index to the circle input, for path following.
src/main/src/inputs/CirclePathInput.java
Adding current index to the circle input, for path following.
<ide><path>rc/main/src/inputs/CirclePathInput.java <ide> private double speed; <ide> // time to complete the circle <ide> private double time; <add> // index for the path <add> private int currentIndex; <ide> <ide> public CirclePathInput(Point origin, double radius, double inclination, double endOrientation, double rotationRate, double speed, double time) { <ide> this.origin = origin; <ide> return inclination; <ide> } <ide> <add> public int getCurrentIndex() { <add> return currentIndex; <add> } <add> <add> public void setCurrentIndex(int currentIndex) { <add> this.currentIndex = currentIndex; <add> } <add> <ide> @Override <ide> public String toString() { <ide> return "CirclePathInput{" +
JavaScript
mit
c52400089f95f50aff7e9173e8dab43a9f9cab58
0
ioBroker/ioBroker.text2command,ioBroker/ioBroker.text2command
import React, { Component, useEffect } from 'react'; import I18n from '@iobroker/adapter-react/i18n'; import { TextField, Switch, Typography } from '@material-ui/core'; import DialogSelectID from '@iobroker/adapter-react/Dialogs/SelectID'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import FormControl from '@material-ui/core/FormControl'; import PropTypes from 'prop-types'; export default class RightBar extends Component { defaultState = { words: 'Выберите правило', name: 'Выберите правило', interupt: false, editable: false, args: [ { default: 'Параметр 1', }, { default: 'Параметр 2', }, ], ack: { name: '', default: `${I18n.t('Confirmation text')}`, }, }; state = { localRule: this.defaultState, showDialog: false, }; componentDidUpdate(prevProps, prevState) { if ( prevProps.selectedRule?.name !== this.props.selectedRule?.name || prevState.localRule?.name !== this.state.localRule?.name ) { this.setState({ localRule: { ...this.props.selectedRule, interupt: true, }, }); } } createInput = ({ value, label, onChange, type, onClick, disabled = this.state.localRule === this.defaultState, keywords, key, onSwitchChange, }) => { if (!value && !label && !keywords) return; return type !== 'checkbox' ? ( <TextField label={label} id="outlined-basic" variant="outlined" size="small" disabled={disabled} value={value} onClick={onClick} onChange={onChange} key={key} /> ) : ( <FormControl> <FormControlLabel value={value} label={label} labelPlacement={'start'} control={ <Switch onClick={onSwitchChange} color={'primary'} disabled={disabled} /> } key={key} /> </FormControl> ); }; createOptionsData = (state = this.state) => { const { localRule: { words, interupt, args, ack, editable }, } = state; const { t } = I18n; const handlers = this.createTextInputHandlers(); const createInput = this.createInput; const isKeyWordsDisabled = () => { if (editable === 'undefined') return false; else if (editable === false) return true; }; return [ { title: `${t('Keywords')}:`, item: createInput({ value: this.state.localRule?.words || '', onChange: handlers.keywordsText, keywords: true, disabled: isKeyWordsDisabled(), key: 'keywords', }), id: 1, }, { title: `${t('Interupt')}:`, item: createInput({ label: 'Прервать обработку', type: 'checkbox' }), id: 2, }, { title: `${t('Param')}:`, item: createInput({ value: args && this.state.localRule.args[0]?.default, label: args && args[0]?.name, type: args && args[0]?.type, onClick: this.handleSetDialogClick.bind(this, args && args[0]), key: 'Param1', }), id: 3, }, { title: `${t('Param')}:`, item: createInput({ value: args && this.state.localRule.args[1]?.default, label: args && args[1]?.name, onChange: handlers.param2Text, onSwitchChange: handlers.param1OnSwitch, key: 'Param2', }), id: 4, }, { title: `${t('Confirmation text')}:`, item: createInput({ value: ack && ack.default, label: ack && ack.name, type: ack && ack.type, key: 'Confirmation text', onChange: handlers.confirmText, onSwitchChange: handlers.confirmOnSwitch, }), id: 5, }, ]; }; createTextInputHandlers = () => { const _this = this; return { keywordsText(event) { _this.setState({ localRule: { ..._this.state.localRule, words: event.target.value, }, }); }, param2Text(event) { _this.setState({ localRule: { ..._this.state.localRule, args: _this.state.localRule.args.map((arg, index) => index > 0 ? { ...arg, default: event.target.value, } : arg ), }, }); }, confirmText(event) { _this.setState({ localRule: { ..._this.state.localRule, ack: { ..._this.state.localRule.ack, default: event.target.value, }, }, }); }, param1OnSwitch() { _this.setState({ localRule: { ..._this.state.localRule, args: _this.state.localRule.args.map((arg, index) => !index ? { ...arg, default: !arg.default } : arg ), }, }); }, confirmOnSwitch() { _this.setState({ localRule: { ..._this.state.localRule, ack: { ..._this.state.localRule.ack, default: !_this.state.localRule.ack.default, }, }, }); }, }; }; handleSetDialogClick = arg => { if (arg.type === 'id') { this.setState({ showDialog: true, }); } }; handleDialogSelectIdSubmit = selected => { this.setState({ localRule: { ...this.state.localRule, args: this.state.localRule.args.map((arg, index) => !index ? { ...arg, default: selected, } : arg ), }, }); }; render() { const { localRule: { name }, newOptionsData, } = this.state; console.log(this.state); const handleSubmit = this.handleDialogSelectIdSubmit; return ( <div className="right-bar"> <div className="right-bar__container"> <Typography variant="h4" align="center" gutterBottom={true}> {name || 'Выберите правило'} </Typography> {this.createOptionsData().map(({ title, item, id }) => { if (!item) return null; return ( <div className="custom-card" key={id}> <Typography variant="h5" component="h2" align="left"> {title} </Typography> {item} </div> ); })} </div> {this.state.showDialog && ( <DialogSelectID connection={this.props.socket} title={'Select ID'} onClose={() => this.setState({ showDialog: false })} onOk={handleSubmit} /> )} </div> ); } } RightBar.propTypes = { selectedRule: PropTypes.oneOfType([PropTypes.object, PropTypes.string]), socket: PropTypes.object.isRequired, };
src/src/components/RightBar.js
import React, { Component, useEffect } from 'react'; import I18n from '@iobroker/adapter-react/i18n'; import { TextField, Switch, Typography } from '@material-ui/core'; import DialogSelectID from '@iobroker/adapter-react/Dialogs/SelectID'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import FormControl from '@material-ui/core/FormControl'; import PropTypes from 'prop-types'; export default class RightBar extends Component { defaultState = { words: 'Выберите правило', name: 'Выберите правило', interupt: false, editable: false, args: [ { default: 'Параметр 1', }, { default: 'Параметр 2', }, ], ack: { name: '', default: `${I18n.t('Confirmation text')}`, }, }; state = { localRule: this.defaultState, showDialog: false, }; componentDidUpdate(prevProps, prevState) { if ( prevProps.selectedRule?.name !== this.props.selectedRule?.name || prevState.localRule?.name !== this.state.localRule?.name ) { this.setState({ localRule: { ...this.props.selectedRule, interupt: true, }, }); } } createInput = ({ value, label, onChange, type, onClick, disabled = this.state.localRule === this.defaultState, keywords, key, onSwitchChange, }) => { if (!value && !label && !keywords) return; return type !== 'checkbox' ? ( <TextField label={label} id="outlined-basic" variant="outlined" size="small" disabled={disabled} value={value} onClick={onClick} onChange={onChange} key={key} /> ) : ( <FormControl> <FormControlLabel value={value} label={label} labelPlacement={'start'} control={<Switch onClick={onSwitchChange} />} key={key} /> </FormControl> ); }; createOptionsData = (state = this.state) => { const { localRule: { words, interupt, args, ack, editable }, } = state; console.log(this.state); const { t } = I18n; const createInput = this.createInput; const isKeyWordsDisabled = () => { if (editable === 'undefined') return false; else if (editable === false) return true; }; const handleTextInputChange = (event, name) => { this.setState({ localRule: { ...this.state.localRule, [name]: event.target.value, }, }); }; return [ { title: `${t('Keywords')}:`, item: createInput({ value: this.state.localRule?.words || '', onChange: event => handleTextInputChange(event, 'words'), keywords: true, disabled: isKeyWordsDisabled(), key: 'keywords', }), id: 1, }, { title: `${t('Interupt')}:`, item: ( <Switch size="medium" color={'primary'} checked={interupt} onClick={this.handleSwitchChange} /> ), id: 2, }, { title: `${t('Param')}:`, item: createInput({ value: args && this.state.localRule.args[0]?.default, label: args && args[0]?.name, type: args && args[0]?.type, onClick: this.handleSetDialogClick.bind(this, args && args[0]), key: 'Param1', onSwitchChange: () => console.log('ok'), }), id: 3, }, { title: `${t('Param')}:`, item: createInput({ value: args && this.state.localRule.args[1]?.default, label: args && args[1]?.name, onChange: event => this.setState({ localRule: { ...this.state.localRule, args: this.state.localRule.args.map((arg, index) => index > 0 ? { ...arg, default: event.target.value, } : arg ), }, }), key: 'Param2', }), id: 4, }, { title: `${t('Confirmation text')}:`, item: createInput({ value: ack && ack.default, label: ack && ack.name, type: ack && ack.type, key: 'Confirmation text', }), id: 5, }, ]; }; handleSwitchChange = () => { this.setState({ localRule: { ...this.state.localRule, interupt: !this.state.localRule.interupt, }, }); }; handleSetDialogClick = arg => { if (arg.type === 'id') { this.setState({ showDialog: true, }); } }; handleDialogSelectIdSubmit = selected => { this.setState({ localRule: { ...this.state.localRule, args: this.state.localRule.args.map((arg, index) => !index ? { ...arg, default: selected, } : arg ), }, }); }; render() { const { localRule: { name }, newOptionsData, } = this.state; const handleSubmit = this.handleDialogSelectIdSubmit; return ( <div className="right-bar"> <div className="right-bar__container"> <Typography variant="h4" align="center" gutterBottom={true}> {name || 'Выберите правило'} </Typography> {this.createOptionsData().map(({ title, item, id }) => { if (!item) return null; return ( <div className="custom-card" key={id}> <Typography variant="h5" component="h2" align="left"> {title} </Typography> {item} </div> ); })} </div> {this.state.showDialog && ( <DialogSelectID connection={this.props.socket} title={'Select ID'} onClose={() => this.setState({ showDialog: false })} onOk={handleSubmit} /> )} </div> ); } } RightBar.propTypes = { selectedRule: PropTypes.oneOfType([PropTypes.object, PropTypes.string]), socket: PropTypes.object.isRequired, };
finish basic handlers functionality
src/src/components/RightBar.js
finish basic handlers functionality
<ide><path>rc/src/components/RightBar.js <ide> value={value} <ide> label={label} <ide> labelPlacement={'start'} <del> control={<Switch onClick={onSwitchChange} />} <add> control={ <add> <Switch onClick={onSwitchChange} color={'primary'} disabled={disabled} /> <add> } <ide> key={key} <ide> /> <ide> </FormControl> <ide> localRule: { words, interupt, args, ack, editable }, <ide> } = state; <ide> <del> console.log(this.state); <del> <ide> const { t } = I18n; <add> <add> const handlers = this.createTextInputHandlers(); <ide> const createInput = this.createInput; <ide> <ide> const isKeyWordsDisabled = () => { <ide> else if (editable === false) return true; <ide> }; <ide> <del> const handleTextInputChange = (event, name) => { <del> this.setState({ <del> localRule: { <del> ...this.state.localRule, <del> [name]: event.target.value, <del> }, <del> }); <del> }; <del> <ide> return [ <ide> { <ide> title: `${t('Keywords')}:`, <ide> item: createInput({ <ide> value: this.state.localRule?.words || '', <del> onChange: event => handleTextInputChange(event, 'words'), <add> onChange: handlers.keywordsText, <ide> keywords: true, <ide> disabled: isKeyWordsDisabled(), <ide> key: 'keywords', <ide> }, <ide> { <ide> title: `${t('Interupt')}:`, <del> item: ( <del> <Switch <del> size="medium" <del> color={'primary'} <del> checked={interupt} <del> onClick={this.handleSwitchChange} <del> /> <del> ), <add> item: createInput({ label: 'Прервать обработку', type: 'checkbox' }), <ide> id: 2, <ide> }, <ide> { <ide> type: args && args[0]?.type, <ide> onClick: this.handleSetDialogClick.bind(this, args && args[0]), <ide> key: 'Param1', <del> onSwitchChange: () => console.log('ok'), <ide> }), <ide> id: 3, <ide> }, <ide> item: createInput({ <ide> value: args && this.state.localRule.args[1]?.default, <ide> label: args && args[1]?.name, <del> onChange: event => <del> this.setState({ <del> localRule: { <del> ...this.state.localRule, <del> args: this.state.localRule.args.map((arg, index) => <del> index > 0 <del> ? { <del> ...arg, <del> default: event.target.value, <del> } <del> : arg <del> ), <del> }, <del> }), <add> onChange: handlers.param2Text, <add> onSwitchChange: handlers.param1OnSwitch, <ide> key: 'Param2', <ide> }), <ide> id: 4, <ide> label: ack && ack.name, <ide> type: ack && ack.type, <ide> key: 'Confirmation text', <add> onChange: handlers.confirmText, <add> onSwitchChange: handlers.confirmOnSwitch, <ide> }), <ide> id: 5, <ide> }, <ide> ]; <ide> }; <ide> <del> handleSwitchChange = () => { <del> this.setState({ <del> localRule: { <del> ...this.state.localRule, <del> interupt: !this.state.localRule.interupt, <del> }, <del> }); <add> createTextInputHandlers = () => { <add> const _this = this; <add> <add> return { <add> keywordsText(event) { <add> _this.setState({ <add> localRule: { <add> ..._this.state.localRule, <add> words: event.target.value, <add> }, <add> }); <add> }, <add> param2Text(event) { <add> _this.setState({ <add> localRule: { <add> ..._this.state.localRule, <add> args: _this.state.localRule.args.map((arg, index) => <add> index > 0 <add> ? { <add> ...arg, <add> default: event.target.value, <add> } <add> : arg <add> ), <add> }, <add> }); <add> }, <add> confirmText(event) { <add> _this.setState({ <add> localRule: { <add> ..._this.state.localRule, <add> ack: { <add> ..._this.state.localRule.ack, <add> default: event.target.value, <add> }, <add> }, <add> }); <add> }, <add> param1OnSwitch() { <add> _this.setState({ <add> localRule: { <add> ..._this.state.localRule, <add> args: _this.state.localRule.args.map((arg, index) => <add> !index ? { ...arg, default: !arg.default } : arg <add> ), <add> }, <add> }); <add> }, <add> confirmOnSwitch() { <add> _this.setState({ <add> localRule: { <add> ..._this.state.localRule, <add> ack: { <add> ..._this.state.localRule.ack, <add> default: !_this.state.localRule.ack.default, <add> }, <add> }, <add> }); <add> }, <add> }; <ide> }; <ide> <ide> handleSetDialogClick = arg => { <ide> localRule: { name }, <ide> newOptionsData, <ide> } = this.state; <del> <add> console.log(this.state); <ide> const handleSubmit = this.handleDialogSelectIdSubmit; <ide> <ide> return (
Java
apache-2.0
2d78560751beb326dbda611819ceba82db309626
0
ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE
package uk.ac.ebi.quickgo.index.annotation; import uk.ac.ebi.quickgo.annotation.common.AnnotationDocument; import uk.ac.ebi.quickgo.index.common.DocumentReaderException; import com.google.common.base.Strings; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Matcher; import org.slf4j.Logger; import org.springframework.batch.item.ItemProcessor; import static java.util.Collections.singletonList; import static org.slf4j.LoggerFactory.getLogger; import static uk.ac.ebi.quickgo.index.annotation.AnnotationParsingHelper.*; import static uk.ac.ebi.quickgo.index.common.datafile.GOADataFileParsingHelper.*; /** * Converts an {@link Annotation} object into an {@link AnnotationDocument} object. * * Created 19/04/16 * @author Edd */ class AnnotationDocumentConverter implements ItemProcessor<Annotation, AnnotationDocument> { static final int DEFAULT_TAXON = 0; private static final Logger LOGGER = getLogger(AnnotationDocumentConverter.class); private static final String ANNOTATION_DATE_FORMAT = "yyyyMMdd"; private final DateTimeFormatter dateTimeFormatter; private final AtomicLong documentCounter; AnnotationDocumentConverter() { documentCounter = new AtomicLong(0L); this.dateTimeFormatter = DateTimeFormatter.ofPattern(ANNOTATION_DATE_FORMAT); } @Override public AnnotationDocument process(Annotation annotation) throws Exception { if (annotation == null) { throw new DocumentReaderException("Annotation object is null"); } Map<String, String> propertiesMap = convertLinePropertiesToMap(annotation.annotationProperties, PIPE, EQUALS); AnnotationDocument doc = new AnnotationDocument(); doc.id = Long.toString(documentCounter.getAndIncrement()); doc.geneProductId = constructGeneProductId(annotation); doc.qualifier = annotation.qualifier; doc.goId = annotation.goId; doc.reference = annotation.dbReferences; doc.assignedBy = annotation.assignedBy; doc.evidenceCode = annotation.evidenceCode; doc.extensions = annotation.annotationExtension; doc.withFrom = constructWithFrom(annotation); doc.interactingTaxonId = extractInteractingTaxonId(annotation); doc.goEvidence = propertiesMap.get(GO_EVIDENCE); doc.geneProductSubset = propertiesMap.get(DB_OBJECT_SUBSET); doc.symbol = propertiesMap.get(DB_OBJECT_SYMBOL); doc.geneProductType = propertiesMap.get(DB_OBJECT_TYPE); doc.taxonId = extractTaxonId(propertiesMap.get(TAXON_ID)); doc.targetSets = constructTargetSets(propertiesMap.get(TARGET_SET)); doc.goAspect = propertiesMap.get(GO_ASPECT); doc.date = createDateFromString(annotation); doc.taxonAncestors = constructTaxonAncestors(propertiesMap.get(TAXON_ANCESTORS)); return doc; } /** * <p>Creates a date from a date string. The date string is expected to be of the form: YYYYMMDD, * e.g., 20120123 for 23rd January 2012. Any problem parsing this date will have the error logged. * Since such errors are not critical, indexing will set the date to null in such circumstances * and continue. * <p>The {@link Date} instance created needs to be in UTC format, required by the underlying data repository, * into which the instance will be persisted. * * @param annotation the annotation whose date string, of the form YYYYMMDD, is to be converted to a {@link Date} * instance * @return a {@link Date} instance representing the date. */ private Date createDateFromString(Annotation annotation) { if (!Strings.isNullOrEmpty(annotation.date)) { try { LocalDate localDate = LocalDate.parse(annotation.date, dateTimeFormatter); return Date.from(localDate.atStartOfDay(ZoneOffset.UTC).toInstant()); } catch (IllegalArgumentException|DateTimeParseException iae) { LOGGER.error("Could not parse annotation date: " + annotation.date, iae); } } return null; } private int extractInteractingTaxonId(Annotation annotation) { if (!Strings.isNullOrEmpty(annotation.interactingTaxonId)) { Matcher matcher = INTERACTING_TAXON_REGEX.matcher(annotation.interactingTaxonId); if (matcher.matches()) { return Integer.parseInt(matcher.group(1)); } } return DEFAULT_TAXON; } private int extractTaxonId(String rawTaxonId) { if (!Strings.isNullOrEmpty(rawTaxonId)) { Matcher matcher = RAW_TAXON_REGEX.matcher(rawTaxonId); if (matcher.matches()) { return Integer.parseInt(matcher.group(1)); } } return DEFAULT_TAXON; } private List<Integer> constructTaxonAncestors(String rawAncestors) { if (!Strings.isNullOrEmpty(rawAncestors)) { Matcher matcher = RAW_TAXON_ANCESTORS_REGEX.matcher(rawAncestors); if (matcher.matches()) { return createNullableIntegerListFromDelimitedValues(rawAncestors, COMMA); } } return singletonList(DEFAULT_TAXON); } private List<Integer> createNullableIntegerListFromDelimitedValues(String value, String delimiter) { return value == null ? null : splitValueToIntegerList(value, delimiter); } // private List<String> constructExtensions(Annotation annotation) { // return createNullableStringListFromDelimitedValues(annotation.annotationExtension, PIPE); // } private List<String> constructWithFrom(Annotation annotation) { return createNullableStringListFromDelimitedValues(annotation.with, PIPE); } private List<String> createNullableStringListFromDelimitedValues(String value, String delimiter) { return value == null ? null : Arrays.asList(splitValue(value, delimiter)); } private String constructGeneProductId(Annotation annotation) { return annotation.db + COLON + annotation.dbObjectId; } private List<String> constructTargetSets(String value) { return createNullableStringListFromDelimitedValues(value, COMMA); } }
indexing/src/main/java/uk/ac/ebi/quickgo/index/annotation/AnnotationDocumentConverter.java
package uk.ac.ebi.quickgo.index.annotation; import uk.ac.ebi.quickgo.annotation.common.AnnotationDocument; import uk.ac.ebi.quickgo.index.common.DocumentReaderException; import com.google.common.base.Strings; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.*; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Matcher; import org.slf4j.Logger; import org.springframework.batch.item.ItemProcessor; import static java.util.Collections.singletonList; import static org.slf4j.LoggerFactory.getLogger; import static uk.ac.ebi.quickgo.index.annotation.AnnotationParsingHelper.*; import static uk.ac.ebi.quickgo.index.common.datafile.GOADataFileParsingHelper.*; /** * Converts an {@link Annotation} object into an {@link AnnotationDocument} object. * * Created 19/04/16 * @author Edd */ class AnnotationDocumentConverter implements ItemProcessor<Annotation, AnnotationDocument> { static final int DEFAULT_TAXON = 0; private static final Logger LOGGER = getLogger(AnnotationDocumentConverter.class); private static final String ANNOTATION_DATE_FORMAT = "yyyyMMdd"; private final DateTimeFormatter dateTimeFormatter; private final AtomicLong documentCounter; AnnotationDocumentConverter() { documentCounter = new AtomicLong(0L); this.dateTimeFormatter = DateTimeFormatter.ofPattern(ANNOTATION_DATE_FORMAT); } @Override public AnnotationDocument process(Annotation annotation) throws Exception { if (annotation == null) { throw new DocumentReaderException("Annotation object is null"); } Map<String, String> propertiesMap = convertLinePropertiesToMap(annotation.annotationProperties, PIPE, EQUALS); AnnotationDocument doc = new AnnotationDocument(); doc.id = Long.toString(documentCounter.getAndIncrement()); doc.geneProductId = constructGeneProductId(annotation); doc.qualifier = annotation.qualifier; doc.goId = annotation.goId; doc.reference = annotation.dbReferences; doc.assignedBy = annotation.assignedBy; doc.evidenceCode = annotation.evidenceCode; doc.extensions = constructExtensions(annotation); doc.withFrom = constructWithFrom(annotation); doc.interactingTaxonId = extractInteractingTaxonId(annotation); doc.goEvidence = propertiesMap.get(GO_EVIDENCE); doc.geneProductSubset = propertiesMap.get(DB_OBJECT_SUBSET); doc.symbol = propertiesMap.get(DB_OBJECT_SYMBOL); doc.geneProductType = propertiesMap.get(DB_OBJECT_TYPE); doc.taxonId = extractTaxonId(propertiesMap.get(TAXON_ID)); doc.targetSets = constructTargetSets(propertiesMap.get(TARGET_SET)); doc.goAspect = propertiesMap.get(GO_ASPECT); doc.date = createDateFromString(annotation); doc.taxonAncestors = constructTaxonAncestors(propertiesMap.get(TAXON_ANCESTORS)); return doc; } /** * <p>Creates a date from a date string. The date string is expected to be of the form: YYYYMMDD, * e.g., 20120123 for 23rd January 2012. Any problem parsing this date will have the error logged. * Since such errors are not critical, indexing will set the date to null in such circumstances * and continue. * <p>The {@link Date} instance created needs to be in UTC format, required by the underlying data repository, * into which the instance will be persisted. * * @param annotation the annotation whose date string, of the form YYYYMMDD, is to be converted to a {@link Date} * instance * @return a {@link Date} instance representing the date. */ private Date createDateFromString(Annotation annotation) { if (!Strings.isNullOrEmpty(annotation.date)) { try { LocalDate localDate = LocalDate.parse(annotation.date, dateTimeFormatter); return Date.from(localDate.atStartOfDay(ZoneOffset.UTC).toInstant()); } catch (IllegalArgumentException|DateTimeParseException iae) { LOGGER.error("Could not parse annotation date: " + annotation.date, iae); } } return null; } private int extractInteractingTaxonId(Annotation annotation) { if (!Strings.isNullOrEmpty(annotation.interactingTaxonId)) { Matcher matcher = INTERACTING_TAXON_REGEX.matcher(annotation.interactingTaxonId); if (matcher.matches()) { return Integer.parseInt(matcher.group(1)); } } return DEFAULT_TAXON; } private int extractTaxonId(String rawTaxonId) { if (!Strings.isNullOrEmpty(rawTaxonId)) { Matcher matcher = RAW_TAXON_REGEX.matcher(rawTaxonId); if (matcher.matches()) { return Integer.parseInt(matcher.group(1)); } } return DEFAULT_TAXON; } private List<Integer> constructTaxonAncestors(String rawAncestors) { if (!Strings.isNullOrEmpty(rawAncestors)) { Matcher matcher = RAW_TAXON_ANCESTORS_REGEX.matcher(rawAncestors); if (matcher.matches()) { return createNullableIntegerListFromDelimitedValues(rawAncestors, COMMA); } } return singletonList(DEFAULT_TAXON); } private List<Integer> createNullableIntegerListFromDelimitedValues(String value, String delimiter) { return value == null ? null : splitValueToIntegerList(value, delimiter); } private List<String> constructExtensions(Annotation annotation) { return createNullableStringListFromDelimitedValues(annotation.annotationExtension, PIPE); } private List<String> constructWithFrom(Annotation annotation) { return createNullableStringListFromDelimitedValues(annotation.with, PIPE); } private List<String> createNullableStringListFromDelimitedValues(String value, String delimiter) { return value == null ? null : Arrays.asList(splitValue(value, delimiter)); } private String constructGeneProductId(Annotation annotation) { return annotation.db + COLON + annotation.dbObjectId; } private List<String> constructTargetSets(String value) { return createNullableStringListFromDelimitedValues(value, COMMA); } }
The extension is now stored as a single element.
indexing/src/main/java/uk/ac/ebi/quickgo/index/annotation/AnnotationDocumentConverter.java
The extension is now stored as a single element.
<ide><path>ndexing/src/main/java/uk/ac/ebi/quickgo/index/annotation/AnnotationDocumentConverter.java <ide> import java.time.ZoneOffset; <ide> import java.time.format.DateTimeFormatter; <ide> import java.time.format.DateTimeParseException; <del>import java.util.*; <add>import java.util.Arrays; <add>import java.util.Date; <add>import java.util.List; <add>import java.util.Map; <ide> import java.util.concurrent.atomic.AtomicLong; <ide> import java.util.regex.Matcher; <ide> import org.slf4j.Logger; <ide> doc.reference = annotation.dbReferences; <ide> doc.assignedBy = annotation.assignedBy; <ide> doc.evidenceCode = annotation.evidenceCode; <del> doc.extensions = constructExtensions(annotation); <add> doc.extensions = annotation.annotationExtension; <ide> <ide> doc.withFrom = constructWithFrom(annotation); <ide> doc.interactingTaxonId = extractInteractingTaxonId(annotation); <ide> return value == null ? null : splitValueToIntegerList(value, delimiter); <ide> } <ide> <del> private List<String> constructExtensions(Annotation annotation) { <del> return createNullableStringListFromDelimitedValues(annotation.annotationExtension, PIPE); <del> } <add> // private List<String> constructExtensions(Annotation annotation) { <add> // return createNullableStringListFromDelimitedValues(annotation.annotationExtension, PIPE); <add> // } <ide> <ide> private List<String> constructWithFrom(Annotation annotation) { <ide> return createNullableStringListFromDelimitedValues(annotation.with, PIPE);
Java
apache-2.0
d5ba292d6b1be17bb814fba57e37db1ce2cdfefa
0
playframework/playframework,wsargent/playframework,mkurz/playframework,benmccann/playframework,aradchykov/playframework,rajeshpg/playframework,hagl/playframework,wegtam/playframework,mkurz/playframework,marcospereira/playframework,Shruti9520/playframework,wsargent/playframework,wsargent/playframework,marcospereira/playframework,zaneli/playframework,Shenker93/playframework,Shruti9520/playframework,aradchykov/playframework,hagl/playframework,ktoso/playframework,rajeshpg/playframework,marcospereira/playframework,wsargent/playframework,wegtam/playframework,zaneli/playframework,Shruti9520/playframework,Shenker93/playframework,ktoso/playframework,marcospereira/playframework,rajeshpg/playframework,aradchykov/playframework,playframework/playframework,aradchykov/playframework,mkurz/playframework,benmccann/playframework,wegtam/playframework,benmccann/playframework,Shenker93/playframework,hagl/playframework,playframework/playframework,zaneli/playframework,rajeshpg/playframework,hagl/playframework,ktoso/playframework,mkurz/playframework,richdougherty/playframework,richdougherty/playframework,benmccann/playframework,Shruti9520/playframework,ktoso/playframework,wegtam/playframework,richdougherty/playframework,Shenker93/playframework,zaneli/playframework,richdougherty/playframework
/* * Copyright (C) 2009-2016 Typesafe Inc. <http://www.typesafe.com> */ package play.db.jpa; import play.api.Play; import play.libs.F; import play.mvc.Http; import javax.persistence.EntityManager; import java.util.ArrayDeque; import java.util.Deque; import java.util.function.Supplier; /** * JPA Helpers. */ public class JPA { // Only used when there's no HTTP context static ThreadLocal<Deque<EntityManager>> currentEntityManager = new JPATransactionContext(); private static class JPATransactionContext extends ThreadLocal<Deque<EntityManager>> { @Override protected Deque<EntityManager> initialValue() { return new ArrayDeque<>(); } } private static final String CURRENT_ENTITY_MANAGER = "currentEntityManager"; /** * Create a default JPAApi with the given persistence unit configuration. * Automatically initialise the JPA entity manager factories. * * @param name the EntityManagerFactory's name * @param unitName the persistence unit's name * @return the configured JPAApi */ public static JPAApi createFor(String name, String unitName) { return new DefaultJPAApi(DefaultJPAConfig.of(name, unitName)).start(); } /** * Create a default JPAApi with name "default" and the given unit name. * Automatically initialise the JPA entity manager factories. * * @param unitName the persistence unit's name * @return the configured JPAApi */ public static JPAApi createFor(String unitName) { return new DefaultJPAApi(DefaultJPAConfig.of("default", unitName)).start(); } /** * Get JPA api for the current play application. * * @deprecated as of 2.5.0. Inject a JPAApi instead. * * @return the JPAApi */ @Deprecated public static JPAApi jpaApi() { return Play.current().injector().instanceOf(JPAApi.class); } /** * Get the EntityManager stack. */ @SuppressWarnings("unchecked") private static Deque<EntityManager> emStack(boolean threadLocalFallback) { Http.Context context = Http.Context.current.get(); if (context != null) { Object emsObject = context.args.get(CURRENT_ENTITY_MANAGER); if (emsObject != null) { return (Deque<EntityManager>) emsObject; } else { Deque<EntityManager> ems = new ArrayDeque<>(); context.args.put(CURRENT_ENTITY_MANAGER, ems); return ems; } } else { // Not a web request if (threadLocalFallback) { return currentEntityManager.get(); } else { throw new RuntimeException("No Http.Context is present. If you want to invoke this method outside of a HTTP request, you need to wrap the call with JPA.withTransaction instead."); } } } /** * Pushes or pops the EntityManager stack depending on the value of the * em argument. If em is null, then the current EntityManager is popped. If em * is non-null, then em is pushed onto the stack and becomes the current EntityManager. */ private static void pushOrPopEm(EntityManager em, boolean threadLocalFallback) { Deque<EntityManager> ems = emStack(threadLocalFallback); if (em != null) { ems.push(em); } else { if (ems.isEmpty()) { throw new IllegalStateException("Tried to remove the EntityManager, but none was set."); } ems.pop(); } } /** * Get the EntityManager for a particular persistence unit for this thread. * * @param key name of the EntityManager to return * @return the EntityManager */ public static EntityManager em(String key) { EntityManager em = jpaApi().em(key); if (em == null) { throw new RuntimeException("No JPA EntityManagerFactory configured for name [" + key + "]"); } return em; } /** * Get the default EntityManager for this thread. * * @throws RuntimeException if no EntityManager is bound to the current Http.Context or the current Thread. * @return the EntityManager */ public static EntityManager em() { Http.Context context = Http.Context.current.get(); Deque<EntityManager> ems = emStack(true); if (ems.isEmpty()) { if (context != null) { throw new RuntimeException("No EntityManager found in the context. Try to annotate your action method with @play.db.jpa.Transactional"); } else { throw new RuntimeException("No EntityManager bound to this thread. Try wrapping this call in JPA.withTransaction, or ensure that the HTTP context is setup on this thread."); } } return ems.peekFirst(); } /** * Bind an EntityManager to the current HTTP context. * If no HTTP context is available the EntityManager gets bound to the current thread instead. * * @param em the EntityManager to bind to this HTTP context. */ public static void bindForSync(EntityManager em) { pushOrPopEm(em, true); } /** * Bind an EntityManager to the current HTTP context. * * @param em the EntityManager to bind * @throws RuntimeException if no HTTP context is present. */ public static void bindForAsync(EntityManager em) { pushOrPopEm(em, false); } /** * Run a block of code in a JPA transaction. * * @deprecated as of 2.5.0. Inject a JPAApi instead. * * @param block Block of code to execute. * @param <T> return type of the block * @return the result of the block, having already committed the transaction (or rolled it back in case of exception) */ @Deprecated public static <T> T withTransaction(Supplier<T> block) { return jpaApi().withTransaction(block); } /** * Run a block of asynchronous code in a JPA transaction. * * @param block Block of code to execute. * @param <T> return type of the block * @return a future to the result of the block, having already committed the transaction * (or rolled it back in case of exception) * * @deprecated This may cause deadlocks */ @Deprecated public static <T> F.Promise<T> withTransactionAsync(Supplier<F.Promise<T>> block) { return jpaApi().withTransactionAsync(block); } /** * Run a block of code in a JPA transaction. * * @deprecated as of 2.5.0. Inject a JPAApi instead. * * @param block Block of code to execute. */ @Deprecated public static void withTransaction(final Runnable block) { jpaApi().withTransaction(block); } /** * Run a block of code in a JPA transaction. * * @deprecated as of 2.5.0. Inject a JPAApi instead. * * @param name The persistence unit name * @param readOnly Is the transaction read-only? * @param block Block of code to execute. * @param <T> return type of the provided block * @return a future to the result of the block, having already committed the transaction * (or rolled it back in case of exception) */ @Deprecated public static <T> T withTransaction(String name, boolean readOnly, Supplier<T> block) { return jpaApi().withTransaction(name, readOnly, block); } /** * Run a block of asynchronous code in a JPA transaction. * * @param name The persistence unit name * @param readOnly Is the transaction read-only? * @param block Block of code to execute. * @param <T> return type of the block * @return a future to the result of the block, having already committed the transaction * (or rolled it back in case of exception) * * @deprecated This may cause deadlocks */ @Deprecated public static <T> F.Promise<T> withTransactionAsync(String name, boolean readOnly, Supplier<F.Promise<T>> block) { return jpaApi().withTransactionAsync(name, readOnly, block); } }
framework/src/play-java-jpa/src/main/java/play/db/jpa/JPA.java
/* * Copyright (C) 2009-2016 Typesafe Inc. <http://www.typesafe.com> */ package play.db.jpa; import play.*; import play.api.Application; import play.api.Play; import play.libs.F; import play.mvc.Http; import java.util.function.Supplier; import java.util.ArrayDeque; import java.util.Deque; import javax.persistence.*; /** * JPA Helpers. */ public class JPA { // Only used when there's no HTTP context static ThreadLocal<Deque<EntityManager>> currentEntityManager = new JPATransactionContext(); private static class JPATransactionContext extends ThreadLocal<Deque<EntityManager>> { @Override protected Deque<EntityManager> initialValue() { return new ArrayDeque<>(); } } private static final String CURRENT_ENTITY_MANAGER = "currentEntityManager"; /** * Create a default JPAApi with the given persistence unit configuration. * Automatically initialise the JPA entity manager factories. * * @param name the EntityManagerFactory's name * @param unitName the persistence unit's name * @return the configured JPAApi */ public static JPAApi createFor(String name, String unitName) { return new DefaultJPAApi(DefaultJPAConfig.of(name, unitName)).start(); } /** * Create a default JPAApi with name "default" and the given unit name. * Automatically initialise the JPA entity manager factories. * * @param unitName the persistence unit's name * @return the configured JPAApi */ public static JPAApi createFor(String unitName) { return new DefaultJPAApi(DefaultJPAConfig.of("default", unitName)).start(); } /** * Get JPA api for the current play application. * * @return the JPAApi */ public static JPAApi jpaApi() { return Play.current().injector().instanceOf(JPAApi.class); } /** * Get the EntityManager stack. */ @SuppressWarnings("unchecked") private static Deque<EntityManager> emStack(boolean threadLocalFallback) { Http.Context context = Http.Context.current.get(); if (context != null) { Object emsObject = context.args.get(CURRENT_ENTITY_MANAGER); if (emsObject != null) { return (Deque<EntityManager>) emsObject; } else { Deque<EntityManager> ems = new ArrayDeque<>(); context.args.put(CURRENT_ENTITY_MANAGER, ems); return ems; } } else { // Not a web request if (threadLocalFallback) { return currentEntityManager.get(); } else { throw new RuntimeException("No Http.Context is present. If you want to invoke this method outside of a HTTP request, you need to wrap the call with JPA.withTransaction instead."); } } } /** * Pushes or pops the EntityManager stack depending on the value of the * em argument. If em is null, then the current EntityManager is popped. If em * is non-null, then em is pushed onto the stack and becomes the current EntityManager. */ private static void pushOrPopEm(EntityManager em, boolean threadLocalFallback) { Deque<EntityManager> ems = emStack(threadLocalFallback); if (em != null) { ems.push(em); } else { if (ems.isEmpty()) { throw new IllegalStateException("Tried to remove the EntityManager, but none was set."); } ems.pop(); } } /** * Get the EntityManager for a particular persistence unit for this thread. * * @param key name of the EntityManager to return * @return the EntityManager */ public static EntityManager em(String key) { EntityManager em = jpaApi().em(key); if (em == null) { throw new RuntimeException("No JPA EntityManagerFactory configured for name [" + key + "]"); } return em; } /** * Get the default EntityManager for this thread. * * @throws RuntimeException if no EntityManager is bound to the current Http.Context or the current Thread. * @return the EntityManager */ public static EntityManager em() { Http.Context context = Http.Context.current.get(); Deque<EntityManager> ems = emStack(true); if (ems.isEmpty()) { if (context != null) { throw new RuntimeException("No EntityManager found in the context. Try to annotate your action method with @play.db.jpa.Transactional"); } else { throw new RuntimeException("No EntityManager bound to this thread. Try wrapping this call in JPA.withTransaction, or ensure that the HTTP context is setup on this thread."); } } return ems.peekFirst(); } /** * Bind an EntityManager to the current HTTP context. * If no HTTP context is available the EntityManager gets bound to the current thread instead. * * @param em the EntityManager to bind to this HTTP context. */ public static void bindForSync(EntityManager em) { pushOrPopEm(em, true); } /** * Bind an EntityManager to the current HTTP context. * * @param em the EntityManager to bind * @throws RuntimeException if no HTTP context is present. */ public static void bindForAsync(EntityManager em) { pushOrPopEm(em, false); } /** * Run a block of code in a JPA transaction. * * @param block Block of code to execute. * @param <T> return type of the block * @return the result of the block, having already committed the transaction (or rolled it back in case of exception) */ public static <T> T withTransaction(Supplier<T> block) { return jpaApi().withTransaction(block); } /** * Run a block of asynchronous code in a JPA transaction. * * @param block Block of code to execute. * @param <T> return type of the block * @return a future to the result of the block, having already committed the transaction * (or rolled it back in case of exception) * * @deprecated This may cause deadlocks */ @Deprecated public static <T> F.Promise<T> withTransactionAsync(Supplier<F.Promise<T>> block) { return jpaApi().withTransactionAsync(block); } /** * Run a block of code in a JPA transaction. * * @param block Block of code to execute. */ public static void withTransaction(final Runnable block) { jpaApi().withTransaction(block); } /** * Run a block of code in a JPA transaction. * * @param name The persistence unit name * @param readOnly Is the transaction read-only? * @param block Block of code to execute. * @param <T> return type of the provided block * @return a future to the result of the block, having already committed the transaction * (or rolled it back in case of exception) */ public static <T> T withTransaction(String name, boolean readOnly, Supplier<T> block) { return jpaApi().withTransaction(name, readOnly, block); } /** * Run a block of asynchronous code in a JPA transaction. * * @param name The persistence unit name * @param readOnly Is the transaction read-only? * @param block Block of code to execute. * @param <T> return type of the block * @return a future to the result of the block, having already committed the transaction * (or rolled it back in case of exception) * * @deprecated This may cause deadlocks */ @Deprecated public static <T> F.Promise<T> withTransactionAsync(String name, boolean readOnly, Supplier<F.Promise<T>> block) { return jpaApi().withTransactionAsync(name, readOnly, block); } }
Deprecate static JPA methods
framework/src/play-java-jpa/src/main/java/play/db/jpa/JPA.java
Deprecate static JPA methods
<ide><path>ramework/src/play-java-jpa/src/main/java/play/db/jpa/JPA.java <ide> */ <ide> package play.db.jpa; <ide> <del>import play.*; <del>import play.api.Application; <ide> import play.api.Play; <ide> import play.libs.F; <ide> import play.mvc.Http; <ide> <del>import java.util.function.Supplier; <add>import javax.persistence.EntityManager; <ide> import java.util.ArrayDeque; <ide> import java.util.Deque; <del> <del>import javax.persistence.*; <add>import java.util.function.Supplier; <ide> <ide> /** <ide> * JPA Helpers. <ide> /** <ide> * Get JPA api for the current play application. <ide> * <add> * @deprecated as of 2.5.0. Inject a JPAApi instead. <add> * <ide> * @return the JPAApi <ide> */ <add> @Deprecated <ide> public static JPAApi jpaApi() { <ide> return Play.current().injector().instanceOf(JPAApi.class); <ide> } <ide> /** <ide> * Run a block of code in a JPA transaction. <ide> * <add> * @deprecated as of 2.5.0. Inject a JPAApi instead. <add> * <ide> * @param block Block of code to execute. <ide> * @param <T> return type of the block <ide> * @return the result of the block, having already committed the transaction (or rolled it back in case of exception) <ide> */ <add> @Deprecated <ide> public static <T> T withTransaction(Supplier<T> block) { <ide> return jpaApi().withTransaction(block); <ide> } <ide> /** <ide> * Run a block of code in a JPA transaction. <ide> * <del> * @param block Block of code to execute. <del> */ <add> * @deprecated as of 2.5.0. Inject a JPAApi instead. <add> * <add> * @param block Block of code to execute. <add> */ <add> @Deprecated <ide> public static void withTransaction(final Runnable block) { <ide> jpaApi().withTransaction(block); <ide> } <ide> <ide> /** <ide> * Run a block of code in a JPA transaction. <add> * <add> * @deprecated as of 2.5.0. Inject a JPAApi instead. <ide> * <ide> * @param name The persistence unit name <ide> * @param readOnly Is the transaction read-only? <ide> * @return a future to the result of the block, having already committed the transaction <ide> * (or rolled it back in case of exception) <ide> */ <add> @Deprecated <ide> public static <T> T withTransaction(String name, boolean readOnly, Supplier<T> block) { <ide> return jpaApi().withTransaction(name, readOnly, block); <ide> }
JavaScript
mit
2b02fe7c1aa437db7986911de32eabd7a70c6e97
0
Deseteral/oudjo,Deseteral/oudjo
Polymer({ ready: function() { var self = this; this.$["button-previous"].onclick = function() { $.get("/player/previous", function(data, status) { self.updateStatus(self, JSON.parse(data)); }); }; this.$["button-play"].onclick = function() { $.get("/player/play", function(data, status) { self.updateStatus(self, JSON.parse(data)); }); }; this.$["button-next"].onclick = function() { $.get("/player/next", function(data, status) { self.updateStatus(self, JSON.parse(data)); }); }; this.$["button-mute"].onclick = function() { self.mute(self); }; this.$["volume-slider"].addEventListener("change", function(e) { var vol = parseInt(self.$["volume-slider"].value); self.updateVolumeServer(self, vol); }); window.setInterval(function() { $.get("/player/status", function(data, status) { self.updateStatus(self, JSON.parse(data)); }); }, 500); }, updateStatus: function(self, status) { // if the song has changed if (self.playerStatus === undefined || self.playerStatus.currentSong.id != status.currentSong.id) { self.playerStatus = status; self.$["song-title"].innerHTML = status.currentSong.title; self.$["song-artist"].innerHTML = status.currentSong.artist; self.$["album-art"].src = "/song/" + status.currentSong.id + "/art"; self.updateVolumeView(self, status.volume); } if (status.isPlaying) { self.$["play-icon"].icon = "av:pause"; self.$["song-progressbar"].value = status.progress; if (status.volume != self.playerStatus.volume) { self.updateVolumeView(self, status.volume); } } else { self.$["play-icon"].icon = "av:play-arrow"; } }, updateVolumeView: function(self, vol) { self.$["volume-slider"].value = vol; if (vol === 0) self.$["button-mute"].icon = "av:volume-off"; else if (vol > 0 && vol < 33) self.$["button-mute"].icon = "av:volume-mute"; else if (vol >= 33 && vol < 66) self.$["button-mute"].icon = "av:volume-down"; else if (vol >= 66) self.$["button-mute"].icon = "av:volume-up"; }, updateVolumeServer: function(self, volume) { $.post("/player/volume/" + volume, function(data) { var status = JSON.parse(data); self.updateVolumeView(self, status.volume); }); }, mute: function(self) { var currentVolume = self.$["volume-slider"].value; if (currentVolume === 0) { self.updateVolumeView(self, self.volumeBeforeMute); } else { self.volumeBeforeMute = currentVolume; self.updateVolumeView(self, 0); } self.updateVolumeServer(self, self.$["volume-slider"].value); }, volumeBeforeMute: 100, playerStatus: undefined });
src/main/resources/view/custom_components/oudjo-controller/oudjo-controller.js
Polymer({ ready: function() { var self = this; this.$["button-previous"].onclick = function() { $.get("/player/previous", function(data, status) { self.updateStatus(self, JSON.parse(data)); }); }; this.$["button-play"].onclick = function() { $.get("/player/play", function(data, status) { self.updateStatus(self, JSON.parse(data)); }); }; this.$["button-next"].onclick = function() { $.get("/player/next", function(data, status) { self.updateStatus(self, JSON.parse(data)); }); }; this.$["button-mute"].onclick = function() { self.mute(self); }; this.$["volume-slider"].addEventListener("change", function(e) { var vol = parseInt(self.$["volume-slider"].value); self.updateVolumeServer(self, vol); }); window.setInterval(function() { $.get("/player/status", function(data, status) { self.updateStatus(self, JSON.parse(data)); }); }, 500); }, updateStatus: function(self, status) { // if the song has changed if (self.playerStatus === undefined || self.playerStatus.currentSong.id != status.currentSong.id) { self.playerStatus = status; self.$["song-title"].innerHTML = status.currentSong.title; self.$["song-artist"].innerHTML = status.currentSong.artist; self.$["album-art"].src = "/song/" + status.currentSong.id + "/art"; self.updateVolumeView(self, status.volume); } if (status.isPlaying) { self.$["play-icon"].icon = "av:pause"; self.$["song-progressbar"].value = status.progress; } else { self.$["play-icon"].icon = "av:play-arrow"; } }, updateVolumeView: function(self, vol) { self.$["volume-slider"].value = vol; if (vol === 0) self.$["button-mute"].icon = "av:volume-off"; else if (vol > 0 && vol < 33) self.$["button-mute"].icon = "av:volume-mute"; else if (vol >= 33 && vol < 66) self.$["button-mute"].icon = "av:volume-down"; else if (vol >= 66) self.$["button-mute"].icon = "av:volume-up"; }, updateVolumeServer: function(self, volume) { $.post("/player/volume/" + volume, function(data) { var status = JSON.parse(data); self.updateVolumeView(self, status.volume); }); }, mute: function(self) { var currentVolume = self.$["volume-slider"].value; if (currentVolume === 0) { self.updateVolumeView(self, self.volumeBeforeMute); } else { self.volumeBeforeMute = currentVolume; self.updateVolumeView(self, 0); } self.updateVolumeServer(self, self.$["volume-slider"].value); }, volumeBeforeMute: 100, playerStatus: undefined });
Fixed volume slider not updating
src/main/resources/view/custom_components/oudjo-controller/oudjo-controller.js
Fixed volume slider not updating
<ide><path>rc/main/resources/view/custom_components/oudjo-controller/oudjo-controller.js <ide> if (status.isPlaying) { <ide> self.$["play-icon"].icon = "av:pause"; <ide> self.$["song-progressbar"].value = status.progress; <add> <add> if (status.volume != self.playerStatus.volume) { <add> self.updateVolumeView(self, status.volume); <add> } <ide> } else { <ide> self.$["play-icon"].icon = "av:play-arrow"; <ide> }
Java
epl-1.0
e68427100dc60cf196c4c3f848b3005a78aec349
0
angrilove/capsule,isdom/capsule,puniverse/capsule,lookfirst/capsule,trance1st/capsule,victorbriz/capsule,tal-m/capsule,guiquanz/capsule,puniverse/capsule,tal-m/capsule,victorbriz/capsule,leolujuyi/capsule,lookfirst/capsule,kevintvh/capsule,lookfirst/capsule,kevintvh/capsule,trance1st/capsule,angrilove/capsule,lookfirst/capsule,leolujuyi/capsule,lookfirst/capsule,isdom/capsule,guiquanz/capsule
/* * Capsule * Copyright (c) 2014-2015, Parallel Universe Software Co. All rights reserved. * * This program and the accompanying materials are licensed under the terms * of the Eclipse Public License v1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ import co.paralleluniverse.capsule.Jar; import co.paralleluniverse.capsule.test.CapsuleTestUtils; import co.paralleluniverse.capsule.test.CapsuleTestUtils.StringPrintStream; import static co.paralleluniverse.capsule.test.CapsuleTestUtils.*; import co.paralleluniverse.common.ZipFS; import com.google.common.jimfs.Jimfs; import java.io.IOException; import java.io.InputStream; import static java.nio.charset.StandardCharsets.UTF_8; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.jar.JarInputStream; import org.junit.After; import org.junit.Test; import static org.junit.Assert.*; import static org.junit.Assume.*; import org.junit.Before; import static com.google.common.truth.Truth.*; import org.joor.Reflect; import org.junit.Ignore; //import static org.mockito.Mockito.*; public class CapsuleTest { /* * As a general rule, we prefer system tests, and only create unit tests for particular methods that, * while tested for integration, whose arguments don't get enough coverage in the system tests (like parsing methods and the like). * * All the tests in this test suite use an in-memory file system, and don't write to the disk at all. */ private final FileSystem fs = Jimfs.newFileSystem(); private final Path cache = fs.getPath("/cache"); private final Path tmp = fs.getPath("/tmp"); private static final ClassLoader MY_CLASSLOADER = Capsule.class.getClassLoader(); private Properties props; @Before public void setUp() throws Exception { props = new Properties(System.getProperties()); setProperties(props); setCacheDir(cache); resetOutputStreams(); TestCapsule.reset(); } @After public void tearDown() throws Exception { fs.close(); } //<editor-fold desc="System Tests"> /////////// System Tests /////////////////////////////////// @Test public void testSimpleExtract() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .addEntry("foo.jar", emptyInputStream()) .addEntry("a.class", emptyInputStream()) .addEntry("b.txt", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()) .addEntry("lib/b.class", emptyInputStream()) .addEntry("q/w/x.txt", emptyInputStream()) .addEntry("d\\f\\y.txt", emptyInputStream()) // test with Windows path .addEntry("META-INF/x.txt", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); // dumpFileSystem(fs); assertEquals(args, getAppArgs(pb)); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assertEquals("com.acme.Foo", getProperty(pb, "capsule.app")); assertEquals("com.acme.Foo", getEnv(pb, "CAPSULE_APP")); assertEquals(appCache, path(getProperty(pb, "capsule.dir"))); assertEquals(absolutePath("capsule.jar"), path(getProperty(pb, "capsule.jar"))); assertEquals(appCache, path(getEnv(pb, "CAPSULE_DIR"))); assertEquals(absolutePath("capsule.jar"), path(getEnv(pb, "CAPSULE_JAR"))); assertEquals(list("com.acme.Foo", "hi", "there"), getMainAndArgs(pb)); assertTrue(Files.isDirectory(cache)); assertTrue(Files.isDirectory(cache.resolve("apps"))); assertTrue(Files.isDirectory(appCache)); assertTrue(Files.isRegularFile(appCache.resolve(".extracted"))); assertTrue(Files.isRegularFile(appCache.resolve("foo.jar"))); assertTrue(Files.isRegularFile(appCache.resolve("b.txt"))); assertTrue(Files.isDirectory(appCache.resolve("lib"))); assertTrue(Files.isRegularFile(appCache.resolve("lib").resolve("a.jar"))); assertTrue(!Files.isRegularFile(appCache.resolve("a.class"))); assertTrue(!Files.isRegularFile(appCache.resolve("lib").resolve("b.class"))); assertTrue(!Files.isDirectory(appCache.resolve("META-INF"))); assertTrue(!Files.isRegularFile(appCache.resolve("META-INF").resolve("x.txt"))); assertTrue(Files.isDirectory(appCache.resolve("q").resolve("w"))); assertTrue(Files.isDirectory(appCache.resolve("d").resolve("f"))); assertTrue(Files.isRegularFile(appCache.resolve("q").resolve("w").resolve("x.txt"))); assertTrue(Files.isRegularFile(appCache.resolve("d").resolve("f").resolve("y.txt"))); assert_().that(getClassPath(pb)).has().item(absolutePath("capsule.jar")); assert_().that(getClassPath(pb)).has().item(appCache); assert_().that(getClassPath(pb)).has().item(appCache.resolve("foo.jar")); assert_().that(getClassPath(pb)).has().noneOf(appCache.resolve("lib").resolve("a.jar")); } @Test public void testNoExtract() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .addEntry("foo.txt", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertEquals(args, getAppArgs(pb)); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assertTrue(!Files.isDirectory(appCache)); } @Test public void testJDKClassPath() throws Exception { assumeTrue(!isCI()); Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") //.setAttribute("Extract-Capsule", "false") .setAttribute("JDK-Required", "true") .setListAttribute("App-Class-Path", list("$JAVA_HOME/lib/tools.jar", "lib/*")) .addEntry("foo.jar", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()) .addEntry("lib/b.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path javaHome = path(capsule.getJavaHome().toString()); // different FS assertEquals(args, getAppArgs(pb)); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assert_().that(javaHome.toString()).contains("jdk"); assert_().that(javaHome.toString()).doesNotContain("jre"); assert_().that(getClassPath(pb)).has().allOf( javaHome.resolve("lib/tools.jar"), appCache, appCache.resolve("foo.jar"), appCache.resolve("lib").resolve("a.jar"), appCache.resolve("lib").resolve("b.jar")); } @Test public void testLogLevel() throws Exception { setSTDERR(DEVNULL); Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("Extract-Capsule", "false") .setAttribute("Capsule-Log-Level", "verbose"); newCapsule(jar); assertTrue(Capsule.isLogging(2)); assertTrue(!Capsule.isLogging(3)); props.setProperty("capsule.log", "none"); newCapsule(jar); assertTrue(Capsule.isLogging(0)); assertTrue(!Capsule.isLogging(1)); props.setProperty("capsule.log", "quiet"); newCapsule(jar); assertTrue(Capsule.isLogging(1)); assertTrue(!Capsule.isLogging(2)); props.setProperty("capsule.log", ""); newCapsule(jar); assertTrue(Capsule.isLogging(1)); assertTrue(!Capsule.isLogging(2)); props.setProperty("capsule.log", "verbose"); newCapsule(jar); assertTrue(Capsule.isLogging(2)); assertTrue(!Capsule.isLogging(3)); props.setProperty("capsule.log", "debug"); newCapsule(jar); assertTrue(Capsule.isLogging(3)); } @Test public void testCapsuleJavaHome() throws Exception { props.setProperty("capsule.java.home", "/my/1.7.0.jdk/home"); Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("Extract-Capsule", "false") .addEntry("foo.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertEquals("/my/1.7.0.jdk/home/bin/java" + (Capsule.isWindows() ? ".exe" : ""), pb.command().get(0)); } @Test public void testCapsuleJavaCmd() throws Exception { props.setProperty("capsule.java.cmd", "/my/java/home/gogo"); Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("Extract-Capsule", "false") .addEntry("foo.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertEquals("/my/java/home/gogo", pb.command().get(0)); } @Test public void testClassPath() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("App-Class-Path", list("lib/a.jar", "lib/b.jar", "lib2/*.jar")) .addEntry("foo.jar", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()) .addEntry("lib/b.jar", emptyInputStream()) .addEntry("lib2/c.jar", emptyInputStream()) .addEntry("lib2/d.jar", emptyInputStream()) .addEntry("lib2/e.txt", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assertTrue(Files.isDirectory(appCache.resolve("lib"))); assertTrue(Files.isRegularFile(appCache.resolve("lib").resolve("a.jar"))); assertTrue(Files.isRegularFile(appCache.resolve("lib2").resolve("c.jar"))); assertTrue(Files.isRegularFile(appCache.resolve("lib2").resolve("d.jar"))); assertTrue(Files.isRegularFile(appCache.resolve("lib2").resolve("e.txt"))); assert_().that(getClassPath(pb)).has().item(absolutePath("capsule.jar")); assert_().that(getClassPath(pb)).has().item(appCache); assert_().that(getClassPath(pb)).has().item(appCache.resolve("foo.jar")); assert_().that(getClassPath(pb)).has().item(appCache.resolve("lib").resolve("a.jar")); assert_().that(getClassPath(pb)).has().item(appCache.resolve("lib").resolve("b.jar")); assert_().that(getClassPath(pb)).has().item(appCache.resolve("lib2").resolve("c.jar")); assert_().that(getClassPath(pb)).has().item(appCache.resolve("lib2").resolve("d.jar")); assert_().that(getClassPath(pb)).has().noneOf(appCache.resolve("lib2").resolve("e.txt")); } @Test public void testNatives1() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("Library-Path-A", list("lib/a.so")) .setListAttribute("Library-Path-P", list("lib/b.so")) .addEntry("foo.jar", emptyInputStream()) .addEntry("lib/a.so", emptyInputStream()) .addEntry("lib/b.so", emptyInputStream()) .addEntry("lib/c.jar", emptyInputStream()) .addEntry("lib/d.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); int len = paths(getProperty(pb, "java.library.path")).size(); assert_().that(paths(getProperty(pb, "java.library.path")).get(0)).isEqualTo(appCache.resolve("lib").resolve("b.so")); assert_().that(paths(getProperty(pb, "java.library.path")).get(len - 2)).isEqualTo(appCache.resolve("lib").resolve("a.so")); assert_().that(paths(getProperty(pb, "java.library.path")).get(len - 1)).isEqualTo(appCache); } @Test public void testNatives2() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("Library-Path-A", list("lib/a.so")) .setListAttribute("Library-Path-P", list("lib/b.so")) .addEntry("foo.jar", emptyInputStream()) .addEntry("lib/a.so", emptyInputStream()) .addEntry("lib/b.so", emptyInputStream()) .addEntry("lib/c.jar", emptyInputStream()) .addEntry("lib/d.jar", emptyInputStream()); props.setProperty("java.library.path", "/foo/bar"); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assert_().that(paths(getProperty(pb, "java.library.path"))).isEqualTo(list( appCache.resolve("lib").resolve("b.so"), path("/foo", "bar"), appCache.resolve("lib").resolve("a.so"), appCache)); } @Test public void testNativesWithDeps() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("Linux", "Native-Dependencies", list("com.acme:baz-linux:3.4=libbaz.so")) .setListAttribute("Windows", "Native-Dependencies", list("com.acme:baz-win:3.4=libbaz.dll")) .setListAttribute("MacOS", "Native-Dependencies", list("com.acme:baz-macos:3.4=libbaz.dylib")) .addEntry("foo.jar", emptyInputStream()) .addEntry("lib/a.so", emptyInputStream()) .addEntry("lib/b.so", emptyInputStream()) .addEntry("lib/c.jar", emptyInputStream()) .addEntry("lib/d.jar", emptyInputStream()); Path bazLinuxPath = mockDep("com.acme:baz-linux:3.4", "so"); Path bazWindowsPath = mockDep("com.acme:baz-win:3.4", "dll"); Path bazMacPath = mockDep("com.acme:baz-macos:3.4", "dylib"); Files.createDirectories(bazLinuxPath.getParent()); Files.createFile(bazLinuxPath); Files.createFile(bazWindowsPath); Files.createFile(bazMacPath); props.setProperty("java.library.path", "/foo/bar"); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assert_().that(paths(getProperty(pb, "java.library.path"))).has().item(appCache); if (Capsule.isUnix()) assertTrue(Files.isRegularFile(appCache.resolve("libbaz.so"))); else if (Capsule.isWindows()) assertTrue(Files.isRegularFile(appCache.resolve("libbaz.dll"))); else if (Capsule.isMac()) assertTrue(Files.isRegularFile(appCache.resolve("libbaz.dylib"))); } @Test public void testBootClassPath1() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("Boot-Class-Path-A", list("lib/a.jar")) .setListAttribute("Boot-Class-Path-P", list("lib/b.jar")) .setListAttribute("Boot-Class-Path", list("lib/c.jar", "lib/d.jar")) .addEntry("foo.jar", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()) .addEntry("lib/b.jar", emptyInputStream()) .addEntry("lib/c.jar", emptyInputStream()) .addEntry("lib/d.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assert_().that(paths(getOption(pb, "-Xbootclasspath"))).has().item(appCache.resolve("lib").resolve("c.jar")); assert_().that(paths(getOption(pb, "-Xbootclasspath"))).has().item(appCache.resolve("lib").resolve("d.jar")); assert_().that(paths(getOption(pb, "-Xbootclasspath/a"))).isEqualTo(list(appCache.resolve("lib").resolve("a.jar"))); assert_().that(paths(getOption(pb, "-Xbootclasspath/p"))).isEqualTo(list(appCache.resolve("lib").resolve("b.jar"))); } @Test public void testBootClassPath2() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("Boot-Class-Path-A", list("lib/a.jar")) .setListAttribute("Boot-Class-Path-P", list("lib/b.jar")) .setListAttribute("Boot-Class-Path", list("lib/c.jar", "lib/d.jar")) .addEntry("foo.jar", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()) .addEntry("lib/b.jar", emptyInputStream()) .addEntry("lib/c.jar", emptyInputStream()) .addEntry("lib/d.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list("-Xbootclasspath:/foo/bar"); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assert_().that(getOption(pb, "-Xbootclasspath")).isEqualTo("/foo/bar"); assert_().that(paths(getOption(pb, "-Xbootclasspath"))).has().noneOf(appCache.resolve("lib").resolve("c.jar")); assert_().that(paths(getOption(pb, "-Xbootclasspath"))).has().noneOf(appCache.resolve("lib").resolve("d.jar")); assert_().that(paths(getOption(pb, "-Xbootclasspath/a"))).isEqualTo(list(appCache.resolve("lib").resolve("a.jar"))); assert_().that(paths(getOption(pb, "-Xbootclasspath/p"))).isEqualTo(list(appCache.resolve("lib").resolve("b.jar"))); } @Test public void testBootClassPathWithDeps() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("Boot-Class-Path-A", list("com.acme:baz:3.4")) .setListAttribute("Boot-Class-Path-P", list("lib/b.jar")) .setListAttribute("Boot-Class-Path", list("lib/c.jar", "com.acme:bar:1.2")) .addEntry("foo.jar", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()) .addEntry("lib/b.jar", emptyInputStream()) .addEntry("lib/c.jar", emptyInputStream()); List<Path> barPath = mockDep("com.acme:bar:1.2", "jar", "com.acme:bar:1.2"); List<Path> bazPath = mockDep("com.acme:baz:3.4", "jar", "com.acme:baz:3.4"); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assert_().that(paths(getOption(pb, "-Xbootclasspath"))).has().item(appCache.resolve("lib").resolve("c.jar")); assert_().that(paths(getOption(pb, "-Xbootclasspath"))).has().allFrom(barPath); assert_().that(paths(getOption(pb, "-Xbootclasspath/a"))).has().allFrom(bazPath); assert_().that(paths(getOption(pb, "-Xbootclasspath/p"))).isEqualTo(list(appCache.resolve("lib").resolve("b.jar"))); } @Test public void testBootClassPathWithEmbeddedDeps() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("Boot-Class-Path-P", list("lib/b.jar")) .setListAttribute("Boot-Class-Path", list("lib/c.jar", "com.acme:bar:1.2")) .addEntry("foo.jar", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()) .addEntry("lib/b.jar", emptyInputStream()) .addEntry("lib/c.jar", emptyInputStream()) .addEntry("bar-1.2.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assert_().that(paths(getOption(pb, "-Xbootclasspath"))).has().item(appCache.resolve("lib").resolve("c.jar")); assert_().that(paths(getOption(pb, "-Xbootclasspath"))).has().item(appCache.resolve("bar-1.2.jar")); assert_().that(paths(getOption(pb, "-Xbootclasspath/p"))).isEqualTo(list(appCache.resolve("lib").resolve("b.jar"))); } @Test public void testDependencies1() throws Exception { List<String> deps = list("com.acme:bar:1.2", "com.acme:baz:3.4:jdk8"); Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("Dependencies", deps) .setListAttribute("App-Class-Path", list("com.acme:wat:5.8", "com.acme:woo")) .addEntry("foo.jar", emptyInputStream()); final List<Path> paths = new ArrayList<>(); paths.add(mockDep("com.acme:bar:1.2", "jar")); paths.addAll(mockDep("com.acme:baz:3.4:jdk8", "jar", "com.google:guava:18.0")); paths.add(mockDep("com.acme:wat:5.8", "jar")); paths.addAll(mockDep("com.acme:woo", "jar", "org.apache:tomcat:8.0", "io.jetty:jetty:123.0")); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assert_().that(getClassPath(pb)).has().allFrom(paths); } public void whenDepManagerThenDontResolveEmbeddedDeps() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("Boot-Class-Path", list("lib/c.jar", "com.acme:bar:1.2")) .addEntry("foo.jar", emptyInputStream()) .addEntry("bar-1.2.jar", emptyInputStream()); Path barPath = mockDep("com.acme:bar:1.2", "jar"); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); List<String> args = list("hi", "there"); List<String> cmdLine = list(); ProcessBuilder pb = newCapsule(jar).prepareForLaunch(cmdLine, args); assert_().that(paths(getOption(pb, "-Xbootclasspath"))).has().noneOf(appCache.resolve("bar-1.2.jar")); assert_().that(paths(getOption(pb, "-Xbootclasspath"))).has().item(barPath); } @Test public void testCapsuleInClassPath() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("App-Class-Path", list("lib/a.jar", "lib/b.jar")) .setAttribute("Capsule-In-Class-Path", "false") .addEntry("foo.jar", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()) .addEntry("lib/b.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assertTrue(Files.isDirectory(appCache.resolve("lib"))); assertTrue(Files.isRegularFile(appCache.resolve("lib").resolve("a.jar"))); assert_().that(getClassPath(pb)).has().noneOf(absolutePath("capsule.jar")); assert_().that(getClassPath(pb)).has().allOf( appCache, appCache.resolve("foo.jar"), appCache.resolve("lib").resolve("a.jar"), appCache.resolve("lib").resolve("b.jar")); } @Test public void testSystemProperties() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("System-Properties", "bar baz=33 foo=y") .addEntry("foo.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list("-Dfoo=x", "-Dzzz"); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertEquals("x", getProperty(pb, "foo")); assertEquals("", getProperty(pb, "bar")); assertEquals("", getProperty(pb, "zzz")); assertEquals("33", getProperty(pb, "baz")); } @Test public void testPlatformSepcific() throws Exception { props.setProperty("capsule.java.home", "/my/1.8.0.jdk/home"); Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("Linux", "System-Properties", "bar baz=33 foo=y os=lin") .setAttribute("MacOS", "System-Properties", "bar baz=33 foo=y os=mac") .setAttribute("Windows", "System-Properties", "bar baz=33 foo=y os=win") .setAttribute("Java-8", "System-Properties", "jjj=8") .setAttribute("Java-7", "System-Properties", "jjj=7") .addEntry("foo.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list("-Dfoo=x", "-Dzzz"); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertEquals("x", getProperty(pb, "foo")); assertEquals("", getProperty(pb, "bar")); assertEquals("", getProperty(pb, "zzz")); assertEquals("33", getProperty(pb, "baz")); assertEquals("8", getProperty(pb, "jjj")); if (Capsule.isWindows()) assertEquals("win", getProperty(pb, "os")); else if (Capsule.isUnix()) assertEquals("lin", getProperty(pb, "os")); if (Capsule.isMac()) assertEquals("mac", getProperty(pb, "os")); } @Test public void testJVMArgs() throws Exception { props.setProperty("capsule.jvm.args", "-Xfoo500 -Xbar:120"); Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("JVM-Args", "-Xmx100 -Xms10 -Xfoo400") .addEntry("foo.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list("-Xms15"); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertTrue(getJvmArgs(pb).contains("-Xmx100")); assertTrue(getJvmArgs(pb).contains("-Xms15")); assertTrue(!getJvmArgs(pb).contains("-Xms10")); assertTrue(getJvmArgs(pb).contains("-Xfoo500")); assertTrue(getJvmArgs(pb).contains("-Xbar:120")); } @Test public void testAgents() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("Java-Agents", "ja1.jar ja2.jar=a=1,b=2 com.acme:bar=x=hi") .setAttribute("Native-Agents", "na1=c=3,d=4 na2") .addEntry("foo.jar", emptyInputStream()); Path barPath = mockDep("com.acme:bar", "jar", "com.acme:bar:1.2").get(0); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assert_().that(getJvmArgs(pb)).has().allOf("-javaagent:" + appCache.resolve("ja1.jar")); assert_().that(getJvmArgs(pb)).has().item("-javaagent:" + appCache.resolve("ja2.jar") + "=a=1,b=2"); assert_().that(getJvmArgs(pb)).has().item("-javaagent:" + barPath + "=x=hi"); assert_().that(getJvmArgs(pb)).has().item("-agentpath:" + appCache.resolve("na1." + Capsule.getNativeLibExtension()) + "=c=3,d=4"); assert_().that(getJvmArgs(pb)).has().item("-agentpath:" + appCache.resolve("na2." + Capsule.getNativeLibExtension())); } @Test public void testMode() throws Exception { props.setProperty("capsule.mode", "ModeX"); Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("System-Properties", "bar baz=33 foo=y") .setAttribute("ModeX", "System-Properties", "bar baz=55 foo=w") .setAttribute("ModeX", "Description", "This is a secret mode") .setAttribute("ModeX-Linux", "System-Properties", "bar baz=55 foo=w os=lin") .setAttribute("ModeX-MacOS", "System-Properties", "bar baz=55 foo=w os=mac") .setAttribute("ModeX-Windows", "System-Properties", "bar baz=55 foo=w os=win") .addEntry("foo.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list("-Dfoo=x", "-Dzzz"); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertEquals("x", getProperty(pb, "foo")); assertEquals("", getProperty(pb, "bar")); assertEquals("", getProperty(pb, "zzz")); assertEquals("55", getProperty(pb, "baz")); assertEquals(new HashSet<String>(list("ModeX")), capsule.getModes()); assertEquals("This is a secret mode", capsule.getModeDescription("ModeX")); if (Capsule.isWindows()) assertEquals("win", getProperty(pb, "os")); else if (Capsule.isUnix()) assertEquals("lin", getProperty(pb, "os")); if (Capsule.isMac()) assertEquals("mac", getProperty(pb, "os")); } @Test(expected = Exception.class) public void testMode2() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("System-Properties", "bar baz=33 foo=y") .setAttribute("ModeX", "Application-Class", "com.acme.Bar") .addEntry("foo.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); newCapsule(jar).prepareForLaunch(cmdLine, args); } @Test public void testApplicationArtifact() throws Exception { Jar bar = new Jar() .setAttribute("Main-Class", "com.acme.Bar") .addEntry("com/acme/Bar.class", emptyInputStream()); Path barPath = mockDep("com.acme:bar:1.2", "jar"); Files.createDirectories(barPath.getParent()); bar.write(barPath); Jar jar = newCapsuleJar() .setAttribute("Application", "com.acme:bar:1.2"); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assert_().that(getClassPath(pb)).has().item(barPath); assertEquals("com.acme.Bar", getMainClass(pb)); } @Test public void testEmbeddedArtifact() throws Exception { Jar bar = new Jar() .setAttribute("Main-Class", "com.acme.Bar") .setAttribute("Class-Path", "lib/liba.jar lib/libb.jar") .addEntry("com/acme/Bar.class", emptyInputStream()); Jar jar = newCapsuleJar() .setAttribute("Application", "bar.jar") .setAttribute("Application-Name", "AcmeFoo") .setAttribute("Application-Version", "1.0") .addEntry("bar.jar", bar.toByteArray()) .addEntry("lib/liba.jar", emptyInputStream()) .addEntry("lib/libb.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("AcmeFoo_1.0"); assert_().that(getClassPath(pb)).has().item(appCache.resolve("bar.jar")); assert_().that(getClassPath(pb)).has().item(appCache.resolve("lib").resolve("liba.jar")); assert_().that(getClassPath(pb)).has().item(appCache.resolve("lib").resolve("libb.jar")); assertEquals("com.acme.Bar", getMainClass(pb)); } @Test public void testScript() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("Dependencies", "com.acme:bar:1.2") .setAttribute("Linux", "Application-Script", "scr.sh") .setAttribute("MacOS", "Application-Script", "scr.sh") .setAttribute("Windows", "Application-Script", "scr.bat") .addEntry("scr.sh", emptyInputStream()) .addEntry("scr.bat", emptyInputStream()) .addEntry("foo.jar", emptyInputStream()); Path barPath = mockDep("com.acme:bar:1.2", "jar"); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assertEquals(list(appCache.resolve(Capsule.isWindows() ? "scr.bat" : "scr.sh").toString(), "hi", "there"), pb.command()); assertEquals(getEnv(pb, "CLASSPATH"), absolutePath("capsule.jar") + PS + appCache + PS + appCache.resolve("foo.jar") + PS + barPath); } @Test public void testReallyExecutableCapsule() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Main-Class", "MyCapsule") .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("System-Properties", "bar baz=33 foo=y") .setAttribute("JVM-Args", "-Xmx100 -Xms10") .setReallyExecutable(true) .addEntry("a.class", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list("-Dfoo=x", "-Dzzz", "-Xms15"); Path capsuleJar = absolutePath("capsule.jar"); jar.write(capsuleJar); Capsule.newCapsule(MY_CLASSLOADER, capsuleJar).prepareForLaunch(cmdLine, args); } @Test public void testSimpleCaplet1() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Main-Class", "MyCapsule") .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("System-Properties", "bar baz=33 foo=y") .setAttribute("JVM-Args", "-Xmx100 -Xms10") .addClass(MyCapsule.class); List<String> args = list("hi", "there"); List<String> cmdLine = list("-Dfoo=x", "-Dzzz", "-Xms15"); Path capsuleJar = absolutePath("capsule.jar"); jar.write(capsuleJar); Capsule capsule = Capsule.newCapsule(MY_CLASSLOADER, capsuleJar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertEquals("x", getProperty(pb, "foo")); assertEquals("", getProperty(pb, "bar")); assertEquals("", getProperty(pb, "zzz")); assertEquals("44", getProperty(pb, "baz")); assertTrue(getJvmArgs(pb).contains("-Xmx3000")); assertTrue(!getJvmArgs(pb).contains("-Xmx100")); assertTrue(getJvmArgs(pb).contains("-Xms15")); assertTrue(!getJvmArgs(pb).contains("-Xms10")); } @Test public void testSimpleCaplet2() throws Exception { Jar jar = newCapsuleJar() .setListAttribute("Caplets", list("MyCapsule")) .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("System-Properties", "bar baz=33 foo=y") .setAttribute("JVM-Args", "-Xmx100 -Xms10") .addClass(MyCapsule.class); List<String> args = list("hi", "there"); List<String> cmdLine = list("-Dfoo=x", "-Dzzz", "-Xms15"); Path capsuleJar = absolutePath("capsule.jar"); jar.write(capsuleJar); Capsule capsule = Capsule.newCapsule(MY_CLASSLOADER, capsuleJar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertEquals("x", getProperty(pb, "foo")); assertEquals("", getProperty(pb, "bar")); assertEquals("", getProperty(pb, "zzz")); assertEquals("44", getProperty(pb, "baz")); assertTrue(getJvmArgs(pb).contains("-Xmx3000")); assertTrue(!getJvmArgs(pb).contains("-Xmx100")); assertTrue(getJvmArgs(pb).contains("-Xms15")); assertTrue(!getJvmArgs(pb).contains("-Xms10")); } @Test public void testEmbeddedCaplet() throws Exception { Jar bar = newCapsuleJar() .setListAttribute("Caplets", list("MyCapsule")) .addClass(MyCapsule.class); Jar jar = newCapsuleJar() .setListAttribute("Caplets", list("com.acme:mycapsule:0.9")) .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("System-Properties", "bar baz=33 foo=y") .setAttribute("JVM-Args", "-Xmx100 -Xms10") .addEntry("mycapsule-0.9.jar", bar.toByteArray()); List<String> args = list("hi", "there"); List<String> cmdLine = list("-Dfoo=x", "-Dzzz", "-Xms15"); Path capsuleJar = absolutePath("capsule.jar"); jar.write(capsuleJar); Capsule capsule = Capsule.newCapsule(MY_CLASSLOADER, capsuleJar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertEquals("x", getProperty(pb, "foo")); assertEquals("", getProperty(pb, "bar")); assertEquals("", getProperty(pb, "zzz")); assertEquals("44", getProperty(pb, "baz")); assertTrue(getJvmArgs(pb).contains("-Xmx3000")); assertTrue(!getJvmArgs(pb).contains("-Xmx100")); assertTrue(getJvmArgs(pb).contains("-Xms15")); assertTrue(!getJvmArgs(pb).contains("-Xms10")); } @Test public void testWrapperCapsule() throws Exception { Jar wrapper = newCapsuleJar() .setAttribute("Caplets", "MyCapsule") .setAttribute("System-Properties", "p1=555") .addClass(Capsule.class) .addClass(MyCapsule.class); Jar app = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("System-Properties", "p1=111") .setListAttribute("App-Class-Path", list("lib/a.jar")) .addClass(Capsule.class) .addEntry("foo.jar", emptyInputStream()) .addEntry("a.class", emptyInputStream()) .addEntry("b.txt", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()) .addEntry("lib/b.class", emptyInputStream()) .addEntry("META-INF/x.txt", emptyInputStream()); Path fooPath = mockDep("com.acme:foo", "jar", "com.acme:foo:1.0").get(0); Files.createDirectories(fooPath.getParent()); app.write(fooPath); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(wrapper).setTarget("com.acme:foo"); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertTrue(capsule.hasCaplet("MyCapsule")); assertTrue(capsule.toString() != null); // exercise toString // dumpFileSystem(fs); assertTrue(pb != null); String appId = capsule.getAppId(); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assertEquals("com.acme.Foo", getProperty(pb, "capsule.app")); assertEquals(appCache.toString(), getProperty(pb, "capsule.dir")); assertEquals(list("com.acme.Foo", "hi", "there"), getMainAndArgs(pb)); assertTrue(Files.isDirectory(cache)); assertTrue(Files.isDirectory(cache.resolve("apps"))); assertTrue(Files.isDirectory(appCache)); assertTrue(Files.isRegularFile(appCache.resolve(".extracted"))); assertTrue(Files.isRegularFile(appCache.resolve("foo.jar"))); assertTrue(Files.isRegularFile(appCache.resolve("b.txt"))); assertTrue(Files.isDirectory(appCache.resolve("lib"))); assertTrue(Files.isRegularFile(appCache.resolve("lib").resolve("a.jar"))); assertTrue(!Files.isRegularFile(appCache.resolve("a.class"))); assertTrue(!Files.isRegularFile(appCache.resolve("lib").resolve("b.class"))); assertTrue(!Files.isDirectory(appCache.resolve("META-INF"))); assertTrue(!Files.isRegularFile(appCache.resolve("META-INF").resolve("x.txt"))); assert_().that(getClassPath(pb)).has().allOf( fooPath, appCache, appCache.resolve("foo.jar"), appCache.resolve("lib").resolve("a.jar")); assertEquals("111", getProperty(pb, "p1")); } @Test public void testWrapperCapsuleNonCapsuleApp() throws Exception { Jar wrapper = newCapsuleJar() .setAttribute("Main-Class", "MyCapsule") .setAttribute("System-Properties", "p1=555") .addClass(Capsule.class) .addClass(MyCapsule.class); Jar app = new Jar() .setAttribute("Main-Class", "com.acme.Foo") .setAttribute("System-Properties", "p1=111") .setAttribute("Class-Path", "lib/a.jar lib/b.jar") .addEntry("a.class", emptyInputStream()) .addEntry("b.txt", emptyInputStream()) .addEntry("META-INF/x.txt", emptyInputStream()); Path fooPath = path("foo-1.0.jar"); app.write(fooPath); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(wrapper).setTarget(fooPath); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); // dumpFileSystem(fs); assertTrue(pb != null); String appId = capsule.getAppId(); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assertEquals(list("com.acme.Foo", "hi", "there"), getMainAndArgs(pb)); //assertTrue(!Files.exists(appCache)); assertTrue(!Files.exists(appCache.resolve("b.txt"))); assertTrue(!Files.exists(appCache.resolve("a.class"))); assert_().that(getClassPath(pb)).has().allOf( fooPath.toAbsolutePath(), path("lib").resolve("a.jar").toAbsolutePath(), path("lib").resolve("b.jar").toAbsolutePath()); assert_().that(getClassPath(pb)).has().noneOf( absolutePath("capsule.jar"), appCache.resolve("lib").resolve("a.jar"), appCache.resolve("lib").resolve("b.jar")); assertEquals("555", getProperty(pb, "p1")); } @Test(expected = IllegalArgumentException.class) public void testWrapperCapsuleNoMain() throws Exception { Jar wrapper = newCapsuleJar() .setAttribute("Main-Class", "MyCapsule") .setAttribute("System-Properties", "p1=555") .addClass(Capsule.class) .addClass(MyCapsule.class); Jar app = new Jar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("System-Properties", "p1=111") .setListAttribute("App-Class-Path", list("lib/a.jar")) .addClass(Capsule.class) .addEntry("foo.jar", emptyInputStream()); Path fooPath = path("foo-1.0.jar"); app.write(fooPath); newCapsule(wrapper).setTarget(fooPath); } @Test public void testProcessCommandLineOptions() throws Exception { List<String> args = new ArrayList<>(list("-java-home", "/foo/bar", "-reset", "-jvm-args=a b c", "-java-cmd", "gogo", "hi", "there")); List<String> jvmArgs = list("-Dcapsule.java.cmd=wow"); processCmdLineOptions(args, jvmArgs); assertEquals("/foo/bar", props.getProperty("capsule.java.home")); assertEquals("true", props.getProperty("capsule.reset")); assertEquals("a b c", props.getProperty("capsule.jvm.args")); assertEquals(null, props.getProperty("capsule.java.cmd")); // overriden assertEquals(list("hi", "there"), args); } private static void processCmdLineOptions(List<String> args, List<String> jvmArgs) { Reflect.on(Capsule.class).call("processCmdLineOptions", args, jvmArgs); } @Test public void testTrampoline() throws Exception { props.setProperty("capsule.java.home", "/my/1.7.0.jdk/home"); props.setProperty("capsule.trampoline", "true"); Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("Extract-Capsule", "false") .addEntry("foo.jar", emptyInputStream()); Class<?> capsuleClass = loadCapsule(jar); setProperties(capsuleClass, props); StringPrintStream out = setSTDOUT(capsuleClass, new StringPrintStream()); int exit = main0(capsuleClass, "hi", "there!"); assertEquals(0, exit); String res = out.toString(); assert_().that(res).matches("[^\n]+\n\\z"); // a single line, teminated with a newline assert_().that(res).startsWith("'" + "/my/1.7.0.jdk/home/bin/java" + (Capsule.isWindows() ? ".exe" : "") + "'"); assert_().that(res).endsWith("'com.acme.Foo' 'hi' 'there!'\n"); } private static int main0(Class<?> clazz, String... args) { return Reflect.on(clazz).call("main0", (Object) args).get(); } private static boolean runActions(Object capsule, List<String> args) { return Reflect.on(capsule.getClass()).call("runActions", capsule, args).get(); } @Test public void testPrintHelp() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("Application-Version", "12.34") .addEntry("foo.jar", emptyInputStream()); props.setProperty("capsule.help", ""); Class<?> capsuleClass = loadCapsule(jar); setProperties(capsuleClass, props); StringPrintStream out = setSTDERR(capsuleClass, new StringPrintStream()); Object capsule = newCapsule(capsuleClass); boolean found = runActions(capsule, null); String res = out.toString(); assert_().that(found).isTrue(); assert_().that(res).contains("USAGE: "); } @Test public void testPrintCapsuleVersion() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("Application-Version", "12.34") .addEntry("foo.jar", emptyInputStream()); props.setProperty("capsule.version", ""); Class<?> capsuleClass = loadCapsule(jar); setProperties(capsuleClass, props); StringPrintStream out = setSTDOUT(capsuleClass, new StringPrintStream()); Object capsule = newCapsule(capsuleClass); boolean found = runActions(capsule, null); String res = out.toString(); assert_().that(found).isTrue(); assert_().that(res).contains("Application com.acme.Foo_12.34"); assert_().that(res).contains("Version: 12.34"); } @Test public void testPrintModes() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("Application-Version", "12.34") .setAttribute("ModeX", "System-Properties", "bar baz=55 foo=w") .setAttribute("ModeX", "Description", "This is a secret mode") .setAttribute("ModeY", "Description", "This is another secret mode") .setAttribute("ModeZ", "Foo", "xxx") .setAttribute("ModeX-Linux", "System-Properties", "bar baz=55 foo=w os=lin") .setAttribute("ModeX-MacOS", "System-Properties", "bar baz=55 foo=w os=mac") .setAttribute("ModeX-Windows", "System-Properties", "bar baz=55 foo=w os=win") .setAttribute("ModeY-Java-15", "Description", "This is a secret mode") .addEntry("foo.jar", emptyInputStream()); props.setProperty("capsule.modes", ""); Class<?> capsuleClass = loadCapsule(jar); setProperties(capsuleClass, props); StringPrintStream out = setSTDOUT(capsuleClass, new StringPrintStream()); Object capsule = newCapsule(capsuleClass); boolean found = runActions(capsule, null); String res = out.toString(); assert_().that(found).isTrue(); assert_().that(res).contains("* ModeX: This is a secret mode"); assert_().that(res).contains("* ModeY: This is another secret mode"); assert_().that(res).contains("* ModeZ"); assert_().that(res).doesNotContain("* ModeX-Linux"); assert_().that(res).doesNotContain("* ModeY-Java-15"); } @Test public void testMerge() throws Exception { Jar wrapper = newCapsuleJar() .setAttribute("Caplets", "MyCapsule") .setAttribute("System-Properties", "p1=555") .addClass(MyCapsule.class); Jar app = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("System-Properties", "p1=111") .setListAttribute("App-Class-Path", list("lib/a.jar")) .addClass(Capsule.class) .addEntry("foo.jar", emptyInputStream()) .addEntry("a.class", emptyInputStream()) .addEntry("b.txt", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()) .addEntry("lib/b.class", emptyInputStream()) .addEntry("META-INF/x.txt", emptyInputStream()); Class<?> capsuleClass = loadCapsule(wrapper); setProperties(capsuleClass, props); Path fooPath = mockDep(capsuleClass, "com.acme:foo", "jar", "com.acme:foo:1.0").get(0); Files.createDirectories(fooPath.getParent()); app.write(fooPath); props.setProperty("capsule.merge", "out.jar"); props.setProperty("capsule.log", "verbose"); int exit = main0(capsuleClass, "com.acme:foo"); assertEquals(0, exit); assertTrue(Files.isRegularFile(path("out.jar"))); Jar out = new Jar(path("out.jar")); assert_().that(out.getAttribute("Main-Class")).isEqualTo("TestCapsule"); assert_().that(out.getListAttribute("Caplets")).isEqualTo(list("MyCapsule")); assert_().that(out.getMapAttribute("System-Properties", "")).isEqualTo(map("p1", "111")); FileSystem jar = ZipFS.newZipFileSystem(path("out.jar")); assertTrue(Files.isRegularFile(jar.getPath("Capsule.class"))); assertTrue(Files.isRegularFile(jar.getPath("TestCapsule.class"))); assertTrue(Files.isRegularFile(jar.getPath("MyCapsule.class"))); assertTrue(Files.isRegularFile(jar.getPath("foo.jar"))); assertTrue(Files.isRegularFile(jar.getPath("a.class"))); assertTrue(Files.isRegularFile(jar.getPath("b.txt"))); assertTrue(Files.isRegularFile(jar.getPath("lib/a.jar"))); assertTrue(Files.isRegularFile(jar.getPath("lib/b.class"))); assertTrue(Files.isRegularFile(jar.getPath("META-INF/x.txt"))); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Unit Tests"> /////////// Unit Tests /////////////////////////////////// @Test public void testParseJavaVersion() { int[] ver; ver = Capsule.parseJavaVersion("1.8.0"); assertArrayEquals(ver, ints(1, 8, 0, 0, 0)); assertEquals("1.8.0", Capsule.toJavaVersionString(ver)); ver = Capsule.parseJavaVersion("1.8"); assertArrayEquals(ver, ints(1, 8, 0, 0, 0)); assertEquals("1.8.0", Capsule.toJavaVersionString(ver)); ver = Capsule.parseJavaVersion("1.8.0_30"); assertArrayEquals(ver, ints(1, 8, 0, 30, 0)); assertEquals("1.8.0_30", Capsule.toJavaVersionString(ver)); ver = Capsule.parseJavaVersion("1.8.0-rc"); assertArrayEquals(ver, ints(1, 8, 0, 0, -1)); assertEquals("1.8.0-rc", Capsule.toJavaVersionString(ver)); ver = Capsule.parseJavaVersion("1.8.0_30-ea"); assertArrayEquals(ver, ints(1, 8, 0, 30, -3)); assertEquals("1.8.0_30-ea", Capsule.toJavaVersionString(ver)); } @Test public void testCompareVersions() { assertTrue(Capsule.compareVersions("1.8.0_30-ea", "1.8.0_30") < 0); assertTrue(Capsule.compareVersions("1.8.0_30-ea", "1.8.0_20") > 0); assertTrue(Capsule.compareVersions("1.8.0-ea", "1.8.0_20") < 0); assertTrue(Capsule.compareVersions("1.8.0-ea", "1.8.0") < 0); assertTrue(Capsule.compareVersions("1.8.0-ea", "1.7.0") > 0); } @Test public void testShortJavaVersion() { assertEquals("1.8.0", Capsule.shortJavaVersion("8")); assertEquals("1.8.0", Capsule.shortJavaVersion("1.8")); assertEquals("1.8.0", Capsule.shortJavaVersion("1.8.0")); } @Test public void isJavaDir() { assertEquals("1.7.0", Capsule.isJavaDir("jre7")); assertEquals("1.7.0_45", Capsule.isJavaDir("jdk1.7.0_45")); assertEquals("1.7.0_51", Capsule.isJavaDir("jdk1.7.0_51.jdk")); assertEquals("1.7.0", Capsule.isJavaDir("1.7.0.jdk")); assertEquals("1.8.0", Capsule.isJavaDir("jdk1.8.0.jdk")); assertEquals("1.7.0", Capsule.isJavaDir("java-7-openjdk-amd64")); assertEquals("1.8.0", Capsule.isJavaDir("java-8-oracle")); assertEquals("1.8.0", Capsule.isJavaDir("jdk-8-oracle")); assertEquals("1.8.0", Capsule.isJavaDir("jre-8-oracle")); assertEquals("1.8.0", Capsule.isJavaDir("jdk-8-oracle-x64")); } @Test public void testDelete() throws Exception { Files.createDirectories(path("a", "b", "c")); Files.createDirectories(path("a", "b1")); Files.createDirectories(path("a", "b", "c1")); Files.createFile(path("a", "x")); Files.createFile(path("a", "b", "x")); Files.createFile(path("a", "b1", "x")); Files.createFile(path("a", "b", "c", "x")); Files.createFile(path("a", "b", "c1", "x")); assertTrue(Files.exists(path("a"))); assertTrue(Files.isDirectory(path("a"))); //Files.delete(path("a")); Capsule.delete(path("a")); assertTrue(!Files.exists(path("a"))); } @Test public void testListDir() throws Exception { Files.createDirectories(path("a", "b", "c")); Files.createDirectories(path("a", "b1")); Files.createDirectories(path("a", "b", "c1")); Files.createFile(path("a", "x")); Files.createFile(path("a", "b", "x")); Files.createFile(path("a", "b1", "x")); Files.createFile(path("a", "b", "c", "x")); Files.createFile(path("a", "b", "c1", "x")); assertEquals(list(path("a", "b"), path("a", "b1"), path("a", "x")), Capsule.listDir(path("a"), null, false)); assertEquals(list(path("a", "x")), Capsule.listDir(path("a"), null, true)); assertEquals(set(path("a", "x"), path("a", "b", "x"), path("a", "b1", "x"), path("a", "b", "c", "x"), path("a", "b", "c1", "x")), set(Capsule.listDir(path("a"), "**", true))); assertEquals(list(path("a", "b1", "x")), Capsule.listDir(path("a"), "b?/*", false)); } @Test public void testGlob() throws Exception { FileSystem fs1 = FileSystems.getDefault(); PathMatcher pathMatcher = fs1.getPathMatcher("glob:java{.exe,}"); assertTrue(pathMatcher.matches(fs1.getPath("java"))); assertTrue(pathMatcher.matches(fs1.getPath("java.exe"))); assertTrue(!pathMatcher.matches(fs1.getPath(".java.exe"))); assertTrue(!pathMatcher.matches(fs1.getPath("java.exe1"))); assertTrue(!pathMatcher.matches(fs1.getPath("java."))); } @Ignore @SuppressWarnings("LocalVariableHidesMemberVariable") public void testDependencyToLocalJar() throws Exception { FileSystem fs; Path root, lib, group, file; fs = Jimfs.newFileSystem(); root = Files.createDirectories(fs.getPath("test")); lib = Files.createDirectory(root.resolve("lib")); group = Files.createDirectory(lib.resolve("com.acme")); file = Files.createFile(group.resolve("foo-3.1.mmm")); assertEquals(file, dependencyToLocalJar(root, "com.acme:foo:3.1", "mmm")); fs = Jimfs.newFileSystem(); root = Files.createDirectories(fs.getPath("test")); lib = Files.createDirectory(root.resolve("lib")); file = Files.createFile(lib.resolve("com.acme-foo-3.1.mmm")); assertEquals(file, dependencyToLocalJar(root, "com.acme:foo:3.1", "mmm")); fs = Jimfs.newFileSystem(); root = Files.createDirectories(fs.getPath("test")); lib = Files.createDirectory(root.resolve("lib")); file = Files.createFile(lib.resolve("foo-3.1.mmm")); assertEquals(file, dependencyToLocalJar(root, "com.acme:foo:3.1", "mmm")); fs = Jimfs.newFileSystem(); root = Files.createDirectories(fs.getPath("test")); group = Files.createDirectory(root.resolve("com.acme")); file = Files.createFile(group.resolve("foo-3.1.mmm")); assertEquals(file, dependencyToLocalJar(root, "com.acme:foo:3.1", "mmm")); fs = Jimfs.newFileSystem(); root = Files.createDirectories(fs.getPath("test")); file = Files.createFile(root.resolve("com.acme-foo-3.1.mmm")); assertEquals(file, dependencyToLocalJar(root, "com.acme:foo:3.1", "mmm")); fs = Jimfs.newFileSystem(); root = Files.createDirectories(fs.getPath("test")); file = Files.createFile(root.resolve("foo-3.1.mmm")); assertEquals(file, dependencyToLocalJar(root, "com.acme:foo:3.1", "mmm")); } private static Path dependencyToLocalJar(Path root, String dep, String type) { return Reflect.on(Capsule.class).call("dependencyToLocalJar", root, dep, type).get(); } @Test public void testExpandVars1() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo"); props.setProperty("a.b.c", "777"); props.setProperty("my.prop", "888"); Capsule capsule = newCapsule(jar); capsule.prepareForLaunch(null, null); String cj = absolutePath("capsule.jar").toString(); String cd = cache.resolve("apps").resolve("com.acme.Foo").toString(); String cid = capsule.getAppId(); assertEquals(cj + "abc" + cj + "def " + cj, expand(capsule, "${CAPSULE_JAR}" + "abc" + "${CAPSULE_JAR}" + "def" + " $CAPSULE_JAR")); assertEquals(cid + " abc" + cid + "def" + cid, expand(capsule, "$CAPSULE_APP" + " abc" + "${CAPSULE_APP}" + "def" + "${CAPSULE_APP}")); assertEquals(cd + "abc " + cd + " def" + cd, expand(capsule, "${CAPSULE_DIR}" + "abc " + "$CAPSULE_DIR" + " def" + "${CAPSULE_DIR}")); assertEquals(cd + "abc" + cid + "def" + cj + "888777", expand(capsule, "${CAPSULE_DIR}" + "abc" + "${CAPSULE_APP}" + "def" + "${CAPSULE_JAR}${my.prop}${a.b.c}")); assertEquals("888", expand(capsule, "${my.prop}")); assertEquals(cj, expand(capsule, "$CAPSULE_JAR")); try { expand(capsule, "${foo.bar.baz}"); fail(); } catch (RuntimeException e) { } } private String expand(Capsule c, String s) { return Reflect.on(c).call("expand", s).get(); } @Test public void testExpandArgs() throws Exception { assertEquals(list("x", "y", "z"), Capsule.expandArgs(list("x", "y", "z"), CapsuleTest.<String>list())); assertEquals(list("a", "b", "c"), Capsule.expandArgs(CapsuleTest.<String>list(), list("a", "b", "c"))); assertEquals(list("x", "y", "z", "a", "b", "c"), Capsule.expandArgs(list("x", "y", "z"), list("a", "b", "c"))); assertEquals(list("x", "a", "b", "c", "z"), Capsule.expandArgs(list("x", "$*", "z"), list("a", "b", "c"))); assertEquals(list("b", "a", "c"), Capsule.expandArgs(list("$2", "$1", "$3"), list("a", "b", "c"))); } @Test public void testParseAttribute() { assertEquals("abcd 123", Capsule.parse("abcd 123", Capsule.T_STRING(), null)); assertEquals(true, Capsule.parse("TRUE", Capsule.T_BOOL(), null)); assertEquals(true, Capsule.parse("true", Capsule.T_BOOL(), null)); assertEquals(false, Capsule.parse("FALSE", Capsule.T_BOOL(), null)); assertEquals(false, Capsule.parse("false", Capsule.T_BOOL(), null)); assertEquals(15L, (long) Capsule.parse("15", Capsule.T_LONG(), null)); try { Capsule.parse("15abs", Capsule.T_LONG(), null); fail(); } catch (RuntimeException e) { } assertEquals(1.2, Capsule.parse("1.2", Capsule.T_DOUBLE(), null), 0.0001); try { Capsule.parse("1.2a", Capsule.T_DOUBLE(), null); fail(); } catch (RuntimeException e) { } assertEquals(list("abcd", "123"), Capsule.parse("abcd 123", Capsule.T_LIST(Capsule.T_STRING()), null)); assertEquals(list("ab", "cd", "ef", "g", "hij", "kl"), Capsule.parse("ab cd ef g hij kl ", Capsule.T_LIST(Capsule.T_STRING()), null)); assertEquals(list(true, false, true, false), Capsule.parse("TRUE false true FALSE", Capsule.T_LIST(Capsule.T_BOOL()), null)); assertEquals(list(123L, 456L, 7L), Capsule.parse("123 456 7", Capsule.T_LIST(Capsule.T_LONG()), null)); assertEquals(list(1.23, 3.45), Capsule.parse("1.23 3.45", Capsule.T_LIST(Capsule.T_DOUBLE()), null)); assertEquals(map("ab", "1", "cd", "xx", "ef", "32", "g", "xx", "hij", "", "kl", ""), Capsule.parse("ab=1 cd ef=32 g hij= kl= ", Capsule.T_MAP(Capsule.T_STRING(), Capsule.T_STRING(), "xx"), null)); try { Capsule.parse("ab=1 cd ef=32 g hij= kl= ", Capsule.T_MAP(Capsule.T_STRING(), Capsule.T_STRING(), null), null); fail(); } catch (Exception e) { } assertEquals(map("ab", true, "cd", true, "ef", false, "g", true), Capsule.parse("ab=true cd ef=false g", Capsule.T_MAP(Capsule.T_STRING(), Capsule.T_BOOL(), true), null)); try { Capsule.parse("ab=true cd ef=false g", Capsule.T_MAP(Capsule.T_STRING(), Capsule.T_BOOL(), null), null); fail(); } catch (Exception e) { } assertEquals(map("ab", 12L, "cd", 17L, "ef", 54L, "g", 17L), Capsule.parse("ab=12 cd ef=54 g", Capsule.T_MAP(Capsule.T_STRING(), Capsule.T_LONG(), 17), null)); try { Capsule.parse("ab=12 cd ef=54 g", Capsule.T_MAP(Capsule.T_STRING(), Capsule.T_LONG(), null), null); fail(); } catch (Exception e) { } try { Capsule.parse("ab=12 cd=xy ef=54 g=z", Capsule.T_MAP(Capsule.T_STRING(), Capsule.T_LONG(), 17), null); fail(); } catch (Exception e) { } assertEquals(map("ab", 12.0, "cd", 100.0, "ef", 5.4, "g", 100.0), Capsule.parse("ab=12 cd ef=5.4 g", Capsule.T_MAP(Capsule.T_STRING(), Capsule.T_DOUBLE(), 100), null)); try { Capsule.parse("ab=12.1 cd ef=5.4 g", Capsule.T_MAP(Capsule.T_STRING(), Capsule.T_DOUBLE(), null), null); fail(); } catch (Exception e) { } try { Capsule.parse("ab=12 cd=xy ef=54 g=z", Capsule.T_MAP(Capsule.T_STRING(), Capsule.T_DOUBLE(), 17.0), null); fail(); } catch (Exception e) { } assertEquals(map(12.3, 12L, 1.01, 17L, 2.05, 54L, 4.0, 17L), Capsule.parse("12.3=12 1.01 2.05=54 4.0", Capsule.T_MAP(Capsule.T_DOUBLE(), Capsule.T_LONG(), 17), null)); } @Test @SuppressWarnings("deprecation") public void testPathingJar() throws Exception { Files.createDirectories(tmp); List<Path> cp = list(path("/a.jar"), path("/b.jar"), path("/c.jar")); Path pathingJar = Capsule.createPathingJar(tmp, cp); try { List<Path> cp2; try (JarInputStream jis = new JarInputStream(Files.newInputStream(pathingJar))) { cp2 = toPath(Arrays.asList(jis.getManifest().getMainAttributes().getValue("Class-Path").split(" "))); } assertEquals(cp, toAbsolutePath(cp2)); for (Path p : cp2) assertTrue(!p.isAbsolute()); } finally { Files.delete(pathingJar); } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Utilities"> /////////// Utilities /////////////////////////////////// // may be called once per test (always writes jar into /capsule.jar) private Capsule newCapsule(Jar jar) { return (Capsule) CapsuleTestUtils.newCapsule(jar, path("capsule.jar")); } private Class<?> loadCapsule(Jar jar) throws IOException { jar = makeRealCapsuleJar(jar); Class<?> clazz = CapsuleTestUtils.loadCapsule(jar, path("capsule.jar")); setProperties(clazz, props); setCacheDir(clazz, cache); return clazz; } private Object newCapsule(Class<?> capsuleClass) { return CapsuleTestUtils.newCapsule(capsuleClass, path("capsule.jar")); } private Jar newCapsuleJar() { return new Jar() .setAttribute("Manifest-Version", "1.0") .setAttribute("Main-Class", "TestCapsule"); } private Jar makeRealCapsuleJar(Jar jar) throws IOException { return jar.addClass(Capsule.class) .addClass(TestCapsule.class); } private Capsule setTarget(Capsule capsule, String artifact) { return Reflect.on(capsule).call("setTarget", artifact).get(); } private Capsule setTarget(Capsule capsule, Path jar) { return Reflect.on(capsule).call("setTarget", jar).get(); } private Path path(String first, String... more) { return fs.getPath(first, more); } private Path absolutePath(String first, String... more) { return fs.getPath(first, more).toAbsolutePath(); } private InputStream emptyInputStream() { return Jar.toInputStream("", UTF_8); } private List<Path> paths(String cp) { final List<Path> res = new ArrayList<>(); for (String p : cp.split(":")) res.add(path(p)); return res; } private List<Path> getClassPath(ProcessBuilder pb) { final List<String> cmd = pb.command(); final int i = cmd.indexOf("-classpath"); if (i < 0) return null; final String cp = cmd.get(i + 1); // return Arrays.asList(cp.split(":")); return paths(cp); } private String getProperty(ProcessBuilder pb, String prop) { return getOption(pb, "-D" + prop, '='); } private String getEnv(ProcessBuilder pb, String envVar) { return pb.environment().get(envVar); } private String getOption(ProcessBuilder pb, String opt) { return getOption(pb, opt, ':'); } private String getOption(ProcessBuilder pb, String opt, char separator) { final List<String> jvmargs = getJvmArgs(pb); for (String a : jvmargs) { if (a.startsWith(opt)) { String res = getAfter(a, separator); return res != null ? res : ""; } } return null; } private List<String> getJvmArgs(ProcessBuilder pb) { boolean classpath = false; int i = 0; for (String x : pb.command().subList(1, pb.command().size())) { if (x.equals("-jar") || (!x.startsWith("-") && !classpath)) break; if (x.equals("-classpath") || x.equals("-cp")) classpath = true; else classpath = false; i++; } return pb.command().subList(1, i + 1); } private String getMainJar(ProcessBuilder pb) { final List<String> cmd = pb.command(); final int start = getJvmArgs(pb).size() + 1; if (cmd.get(start).equals("-jar")) return cmd.get(start + 1); return null; } private String getMainClass(ProcessBuilder pb) { final List<String> cmd = pb.command(); final int start = getJvmArgs(pb).size() + 1; if (cmd.get(start).equals("-jar")) return null; return cmd.get(start); } private List<String> getAppArgs(ProcessBuilder pb) { List<String> jvmArgs = getJvmArgs(pb); final List<String> cmd = pb.command(); final int start = jvmArgs.size() + 1; return cmd.subList(start + (cmd.get(start).equals("-jar") ? 2 : 1), cmd.size()); } private static List<String> getMainAndArgs(ProcessBuilder pb) { List<String> cmd = pb.command(); cmd = cmd.subList(1, cmd.size()); boolean prevClassPath = false; int i = 0; for (String c : cmd) { if (c.startsWith("-") || prevClassPath) i++; else break; prevClassPath = c.equals("-classpath"); } return cmd.subList(i, cmd.size()); } private List<Path> toPath(List<String> ps) { final List<Path> pss = new ArrayList<Path>(ps.size()); for (String p : ps) pss.add(path(p)); return pss; } private List<Path> toAbsolutePath(List<Path> ps) { final List<Path> pss = new ArrayList<Path>(ps.size()); for (Path p : ps) pss.add(p.toAbsolutePath().normalize()); return pss; } private static String getBefore(String s, char separator) { final int i = s.indexOf(separator); if (i < 0) return s; return s.substring(0, i); } private static String getAfter(String s, char separator) { final int i = s.indexOf(separator); if (i < 0) return null; return s.substring(i + 1); } private static <T extends Comparable<? super T>> List<T> sort(List<T> list) { final List<T> c = new ArrayList<>(list); Collections.<T>sort(c); return c; } private static <T> Set<T> set(Collection<T> list) { return new HashSet<>(list); } @SafeVarargs private static <T> List<T> list(T... xs) { return Arrays.asList(xs); } @SafeVarargs private static <T> Set<T> set(T... xs) { return set(Arrays.asList(xs)); } private static String[] strings(String... xs) { return xs; } private static int[] ints(int... xs) { return xs; } @SuppressWarnings("unchecked") private static <K, V> Map<K, V> map(Object... ss) { final Map<K, V> m = new HashMap<>(); for (int i = 0; i < ss.length / 2; i++) m.put((K) ss[i * 2], (V) ss[i * 2 + 1]); return Collections.unmodifiableMap(m); } private Path mockDep(String dep, String type) { return mockDep(dep, type, dep).get(0); } private List<Path> mockDep(String dep, String type, String... artifacts) { return mockDep(TestCapsule.class, dep, type, artifacts); } private List<Path> mockDep(Class<?> testCapsuleClass, String dep, String type, String... artifacts) { List<Path> as = new ArrayList<>(artifacts.length); for (String a : artifacts) as.add(artifact(a, type)); try { testCapsuleClass.getMethod("mock", String.class, String.class, List.class).invoke(null, dep, type, as); } catch (ReflectiveOperationException e) { throw rethrow(e); } return as; } private Path artifact(String x, String type) { String[] coords = x.split(":"); String group = coords[0]; String artifact = coords[1]; String artifactDir = artifact.split("-")[0]; // arbitrary String version = coords[2] + (coords.length > 3 ? "-" + coords[3] : ""); return cache.resolve("deps").resolve(group).resolve(artifactDir).resolve(artifact + "-" + version + '.' + type); } private static void dumpFileSystem(FileSystem fs) { try { Files.walkFileTree(fs.getRootDirectories().iterator().next(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { System.out.println("-- " + file); return super.visitFile(file, attrs); } }); } catch (IOException e) { throw new RuntimeException(e); } } private static final String PS = System.getProperty("path.separator"); //</editor-fold> }
capsule/src/test/java/CapsuleTest.java
/* * Capsule * Copyright (c) 2014-2015, Parallel Universe Software Co. All rights reserved. * * This program and the accompanying materials are licensed under the terms * of the Eclipse Public License v1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ import co.paralleluniverse.capsule.Jar; import co.paralleluniverse.capsule.test.CapsuleTestUtils; import co.paralleluniverse.capsule.test.CapsuleTestUtils.StringPrintStream; import static co.paralleluniverse.capsule.test.CapsuleTestUtils.*; import co.paralleluniverse.common.ZipFS; import com.google.common.jimfs.Jimfs; import java.io.IOException; import java.io.InputStream; import static java.nio.charset.StandardCharsets.UTF_8; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.jar.JarInputStream; import org.junit.After; import org.junit.Test; import static org.junit.Assert.*; import static org.junit.Assume.*; import org.junit.Before; import static com.google.common.truth.Truth.*; import org.joor.Reflect; import org.junit.Ignore; //import static org.mockito.Mockito.*; public class CapsuleTest { /* * As a general rule, we prefer system tests, and only create unit tests for particular methods that, * while tested for integration, whose arguments don't get enough coverage in the system tests (like parsing methods and the like). * * All the tests in this test suite use an in-memory file system, and don't write to the disk at all. */ private final FileSystem fs = Jimfs.newFileSystem(); private final Path cache = fs.getPath("/cache"); private final Path tmp = fs.getPath("/tmp"); private static final ClassLoader MY_CLASSLOADER = Capsule.class.getClassLoader(); private Properties props; @Before public void setUp() throws Exception { props = new Properties(System.getProperties()); setProperties(props); setCacheDir(cache); resetOutputStreams(); TestCapsule.reset(); } @After public void tearDown() throws Exception { fs.close(); } //<editor-fold desc="System Tests"> /////////// System Tests /////////////////////////////////// @Test public void testSimpleExtract() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .addEntry("foo.jar", emptyInputStream()) .addEntry("a.class", emptyInputStream()) .addEntry("b.txt", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()) .addEntry("lib/b.class", emptyInputStream()) .addEntry("q/w/x.txt", emptyInputStream()) .addEntry("d\\f\\y.txt", emptyInputStream()) // test with Windows path .addEntry("META-INF/x.txt", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); // dumpFileSystem(fs); assertEquals(args, getAppArgs(pb)); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assertEquals("com.acme.Foo", getProperty(pb, "capsule.app")); assertEquals("com.acme.Foo", getEnv(pb, "CAPSULE_APP")); assertEquals(appCache, path(getProperty(pb, "capsule.dir"))); assertEquals(absolutePath("capsule.jar"), path(getProperty(pb, "capsule.jar"))); assertEquals(appCache, path(getEnv(pb, "CAPSULE_DIR"))); assertEquals(absolutePath("capsule.jar"), path(getEnv(pb, "CAPSULE_JAR"))); assertEquals(list("com.acme.Foo", "hi", "there"), getMainAndArgs(pb)); assertTrue(Files.isDirectory(cache)); assertTrue(Files.isDirectory(cache.resolve("apps"))); assertTrue(Files.isDirectory(appCache)); assertTrue(Files.isRegularFile(appCache.resolve(".extracted"))); assertTrue(Files.isRegularFile(appCache.resolve("foo.jar"))); assertTrue(Files.isRegularFile(appCache.resolve("b.txt"))); assertTrue(Files.isDirectory(appCache.resolve("lib"))); assertTrue(Files.isRegularFile(appCache.resolve("lib").resolve("a.jar"))); assertTrue(!Files.isRegularFile(appCache.resolve("a.class"))); assertTrue(!Files.isRegularFile(appCache.resolve("lib").resolve("b.class"))); assertTrue(!Files.isDirectory(appCache.resolve("META-INF"))); assertTrue(!Files.isRegularFile(appCache.resolve("META-INF").resolve("x.txt"))); assertTrue(Files.isDirectory(appCache.resolve("q").resolve("w"))); assertTrue(Files.isDirectory(appCache.resolve("d").resolve("f"))); assertTrue(Files.isRegularFile(appCache.resolve("q").resolve("w").resolve("x.txt"))); assertTrue(Files.isRegularFile(appCache.resolve("d").resolve("f").resolve("y.txt"))); assert_().that(getClassPath(pb)).has().item(absolutePath("capsule.jar")); assert_().that(getClassPath(pb)).has().item(appCache); assert_().that(getClassPath(pb)).has().item(appCache.resolve("foo.jar")); assert_().that(getClassPath(pb)).has().noneOf(appCache.resolve("lib").resolve("a.jar")); } @Test public void testNoExtract() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .addEntry("foo.txt", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertEquals(args, getAppArgs(pb)); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assertTrue(!Files.isDirectory(appCache)); } @Test public void testJDKClassPath() throws Exception { assumeTrue(!isCI()); Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") //.setAttribute("Extract-Capsule", "false") .setAttribute("JDK-Required", "true") .setListAttribute("App-Class-Path", list("$JAVA_HOME/lib/tools.jar", "lib/*")) .addEntry("foo.jar", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()) .addEntry("lib/b.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path javaHome = path(capsule.getJavaHome().toString()); // different FS assertEquals(args, getAppArgs(pb)); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assert_().that(javaHome.toString()).contains("jdk"); assert_().that(javaHome.toString()).doesNotContain("jre"); assert_().that(getClassPath(pb)).has().allOf( javaHome.resolve("lib/tools.jar"), appCache, appCache.resolve("foo.jar"), appCache.resolve("lib").resolve("a.jar"), appCache.resolve("lib").resolve("b.jar")); } @Test public void testLogLevel() throws Exception { setSTDERR(DEVNULL); Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("Extract-Capsule", "false") .setAttribute("Capsule-Log-Level", "verbose"); newCapsule(jar); assertTrue(Capsule.isLogging(2)); assertTrue(!Capsule.isLogging(3)); props.setProperty("capsule.log", "none"); newCapsule(jar); assertTrue(Capsule.isLogging(0)); assertTrue(!Capsule.isLogging(1)); props.setProperty("capsule.log", "quiet"); newCapsule(jar); assertTrue(Capsule.isLogging(1)); assertTrue(!Capsule.isLogging(2)); props.setProperty("capsule.log", ""); newCapsule(jar); assertTrue(Capsule.isLogging(1)); assertTrue(!Capsule.isLogging(2)); props.setProperty("capsule.log", "verbose"); newCapsule(jar); assertTrue(Capsule.isLogging(2)); assertTrue(!Capsule.isLogging(3)); props.setProperty("capsule.log", "debug"); newCapsule(jar); assertTrue(Capsule.isLogging(3)); } @Test public void testCapsuleJavaHome() throws Exception { props.setProperty("capsule.java.home", "/my/1.7.0.jdk/home"); Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("Extract-Capsule", "false") .addEntry("foo.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertEquals("/my/1.7.0.jdk/home/bin/java" + (Capsule.isWindows() ? ".exe" : ""), pb.command().get(0)); } @Test public void testCapsuleJavaCmd() throws Exception { props.setProperty("capsule.java.cmd", "/my/java/home/gogo"); Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("Extract-Capsule", "false") .addEntry("foo.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertEquals("/my/java/home/gogo", pb.command().get(0)); } @Test public void testClassPath() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("App-Class-Path", list("lib/a.jar", "lib/b.jar", "lib2/*.jar")) .addEntry("foo.jar", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()) .addEntry("lib/b.jar", emptyInputStream()) .addEntry("lib2/c.jar", emptyInputStream()) .addEntry("lib2/d.jar", emptyInputStream()) .addEntry("lib2/e.txt", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assertTrue(Files.isDirectory(appCache.resolve("lib"))); assertTrue(Files.isRegularFile(appCache.resolve("lib").resolve("a.jar"))); assertTrue(Files.isRegularFile(appCache.resolve("lib2").resolve("c.jar"))); assertTrue(Files.isRegularFile(appCache.resolve("lib2").resolve("d.jar"))); assertTrue(Files.isRegularFile(appCache.resolve("lib2").resolve("e.txt"))); assert_().that(getClassPath(pb)).has().item(absolutePath("capsule.jar")); assert_().that(getClassPath(pb)).has().item(appCache); assert_().that(getClassPath(pb)).has().item(appCache.resolve("foo.jar")); assert_().that(getClassPath(pb)).has().item(appCache.resolve("lib").resolve("a.jar")); assert_().that(getClassPath(pb)).has().item(appCache.resolve("lib").resolve("b.jar")); assert_().that(getClassPath(pb)).has().item(appCache.resolve("lib2").resolve("c.jar")); assert_().that(getClassPath(pb)).has().item(appCache.resolve("lib2").resolve("d.jar")); assert_().that(getClassPath(pb)).has().noneOf(appCache.resolve("lib2").resolve("e.txt")); } @Test public void testNatives1() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("Library-Path-A", list("lib/a.so")) .setListAttribute("Library-Path-P", list("lib/b.so")) .addEntry("foo.jar", emptyInputStream()) .addEntry("lib/a.so", emptyInputStream()) .addEntry("lib/b.so", emptyInputStream()) .addEntry("lib/c.jar", emptyInputStream()) .addEntry("lib/d.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); int len = paths(getProperty(pb, "java.library.path")).size(); assert_().that(paths(getProperty(pb, "java.library.path")).get(0)).isEqualTo(appCache.resolve("lib").resolve("b.so")); assert_().that(paths(getProperty(pb, "java.library.path")).get(len - 2)).isEqualTo(appCache.resolve("lib").resolve("a.so")); assert_().that(paths(getProperty(pb, "java.library.path")).get(len - 1)).isEqualTo(appCache); } @Test public void testNatives2() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("Library-Path-A", list("lib/a.so")) .setListAttribute("Library-Path-P", list("lib/b.so")) .addEntry("foo.jar", emptyInputStream()) .addEntry("lib/a.so", emptyInputStream()) .addEntry("lib/b.so", emptyInputStream()) .addEntry("lib/c.jar", emptyInputStream()) .addEntry("lib/d.jar", emptyInputStream()); props.setProperty("java.library.path", "/foo/bar"); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assert_().that(paths(getProperty(pb, "java.library.path"))).isEqualTo(list( appCache.resolve("lib").resolve("b.so"), path("/foo", "bar"), appCache.resolve("lib").resolve("a.so"), appCache)); } @Test public void testNativesWithDeps() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("Linux", "Native-Dependencies", list("com.acme:baz-linux:3.4=libbaz.so")) .setListAttribute("Windows", "Native-Dependencies", list("com.acme:baz-win:3.4=libbaz.dll")) .setListAttribute("MacOS", "Native-Dependencies", list("com.acme:baz-macos:3.4=libbaz.dylib")) .addEntry("foo.jar", emptyInputStream()) .addEntry("lib/a.so", emptyInputStream()) .addEntry("lib/b.so", emptyInputStream()) .addEntry("lib/c.jar", emptyInputStream()) .addEntry("lib/d.jar", emptyInputStream()); Path bazLinuxPath = mockDep("com.acme:baz-linux:3.4", "so"); Path bazWindowsPath = mockDep("com.acme:baz-win:3.4", "dll"); Path bazMacPath = mockDep("com.acme:baz-macos:3.4", "dylib"); Files.createDirectories(bazLinuxPath.getParent()); Files.createFile(bazLinuxPath); Files.createFile(bazWindowsPath); Files.createFile(bazMacPath); props.setProperty("java.library.path", "/foo/bar"); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assert_().that(paths(getProperty(pb, "java.library.path"))).has().item(appCache); if (Capsule.isUnix()) assertTrue(Files.isRegularFile(appCache.resolve("libbaz.so"))); else if (Capsule.isWindows()) assertTrue(Files.isRegularFile(appCache.resolve("libbaz.dll"))); else if (Capsule.isMac()) assertTrue(Files.isRegularFile(appCache.resolve("libbaz.dylib"))); } @Test public void testBootClassPath1() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("Boot-Class-Path-A", list("lib/a.jar")) .setListAttribute("Boot-Class-Path-P", list("lib/b.jar")) .setListAttribute("Boot-Class-Path", list("lib/c.jar", "lib/d.jar")) .addEntry("foo.jar", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()) .addEntry("lib/b.jar", emptyInputStream()) .addEntry("lib/c.jar", emptyInputStream()) .addEntry("lib/d.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assert_().that(paths(getOption(pb, "-Xbootclasspath"))).has().item(appCache.resolve("lib").resolve("c.jar")); assert_().that(paths(getOption(pb, "-Xbootclasspath"))).has().item(appCache.resolve("lib").resolve("d.jar")); assert_().that(paths(getOption(pb, "-Xbootclasspath/a"))).isEqualTo(list(appCache.resolve("lib").resolve("a.jar"))); assert_().that(paths(getOption(pb, "-Xbootclasspath/p"))).isEqualTo(list(appCache.resolve("lib").resolve("b.jar"))); } @Test public void testBootClassPath2() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("Boot-Class-Path-A", list("lib/a.jar")) .setListAttribute("Boot-Class-Path-P", list("lib/b.jar")) .setListAttribute("Boot-Class-Path", list("lib/c.jar", "lib/d.jar")) .addEntry("foo.jar", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()) .addEntry("lib/b.jar", emptyInputStream()) .addEntry("lib/c.jar", emptyInputStream()) .addEntry("lib/d.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list("-Xbootclasspath:/foo/bar"); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assert_().that(getOption(pb, "-Xbootclasspath")).isEqualTo("/foo/bar"); assert_().that(paths(getOption(pb, "-Xbootclasspath"))).has().noneOf(appCache.resolve("lib").resolve("c.jar")); assert_().that(paths(getOption(pb, "-Xbootclasspath"))).has().noneOf(appCache.resolve("lib").resolve("d.jar")); assert_().that(paths(getOption(pb, "-Xbootclasspath/a"))).isEqualTo(list(appCache.resolve("lib").resolve("a.jar"))); assert_().that(paths(getOption(pb, "-Xbootclasspath/p"))).isEqualTo(list(appCache.resolve("lib").resolve("b.jar"))); } @Test public void testBootClassPathWithDeps() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("Boot-Class-Path-A", list("com.acme:baz:3.4")) .setListAttribute("Boot-Class-Path-P", list("lib/b.jar")) .setListAttribute("Boot-Class-Path", list("lib/c.jar", "com.acme:bar:1.2")) .addEntry("foo.jar", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()) .addEntry("lib/b.jar", emptyInputStream()) .addEntry("lib/c.jar", emptyInputStream()); List<Path> barPath = mockDep("com.acme:bar:1.2", "jar", "com.acme:bar:1.2"); List<Path> bazPath = mockDep("com.acme:baz:3.4", "jar", "com.acme:baz:3.4"); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assert_().that(paths(getOption(pb, "-Xbootclasspath"))).has().item(appCache.resolve("lib").resolve("c.jar")); assert_().that(paths(getOption(pb, "-Xbootclasspath"))).has().allFrom(barPath); assert_().that(paths(getOption(pb, "-Xbootclasspath/a"))).has().allFrom(bazPath); assert_().that(paths(getOption(pb, "-Xbootclasspath/p"))).isEqualTo(list(appCache.resolve("lib").resolve("b.jar"))); } @Test public void testBootClassPathWithEmbeddedDeps() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("Boot-Class-Path-P", list("lib/b.jar")) .setListAttribute("Boot-Class-Path", list("lib/c.jar", "com.acme:bar:1.2")) .addEntry("foo.jar", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()) .addEntry("lib/b.jar", emptyInputStream()) .addEntry("lib/c.jar", emptyInputStream()) .addEntry("bar-1.2.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assert_().that(paths(getOption(pb, "-Xbootclasspath"))).has().item(appCache.resolve("lib").resolve("c.jar")); assert_().that(paths(getOption(pb, "-Xbootclasspath"))).has().item(appCache.resolve("bar-1.2.jar")); assert_().that(paths(getOption(pb, "-Xbootclasspath/p"))).isEqualTo(list(appCache.resolve("lib").resolve("b.jar"))); } @Test public void testDependencies1() throws Exception { List<String> deps = list("com.acme:bar:1.2", "com.acme:baz:3.4:jdk8"); Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("Dependencies", deps) .setListAttribute("App-Class-Path", list("com.acme:wat:5.8", "com.acme:woo")) .addEntry("foo.jar", emptyInputStream()); final List<Path> paths = new ArrayList<>(); paths.add(mockDep("com.acme:bar:1.2", "jar")); paths.addAll(mockDep("com.acme:baz:3.4:jdk8", "jar", "com.google:guava:18.0")); paths.add(mockDep("com.acme:wat:5.8", "jar")); paths.addAll(mockDep("com.acme:woo", "jar", "org.apache:tomcat:8.0", "io.jetty:jetty:123.0")); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assert_().that(getClassPath(pb)).has().allFrom(paths); } public void whenDepManagerThenDontResolveEmbeddedDeps() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("Boot-Class-Path", list("lib/c.jar", "com.acme:bar:1.2")) .addEntry("foo.jar", emptyInputStream()) .addEntry("bar-1.2.jar", emptyInputStream()); Path barPath = mockDep("com.acme:bar:1.2", "jar"); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); List<String> args = list("hi", "there"); List<String> cmdLine = list(); ProcessBuilder pb = newCapsule(jar).prepareForLaunch(cmdLine, args); assert_().that(paths(getOption(pb, "-Xbootclasspath"))).has().noneOf(appCache.resolve("bar-1.2.jar")); assert_().that(paths(getOption(pb, "-Xbootclasspath"))).has().item(barPath); } @Test public void testCapsuleInClassPath() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setListAttribute("App-Class-Path", list("lib/a.jar", "lib/b.jar")) .setAttribute("Capsule-In-Class-Path", "false") .addEntry("foo.jar", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()) .addEntry("lib/b.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assertTrue(Files.isDirectory(appCache.resolve("lib"))); assertTrue(Files.isRegularFile(appCache.resolve("lib").resolve("a.jar"))); assert_().that(getClassPath(pb)).has().noneOf(absolutePath("capsule.jar")); assert_().that(getClassPath(pb)).has().allOf( appCache, appCache.resolve("foo.jar"), appCache.resolve("lib").resolve("a.jar"), appCache.resolve("lib").resolve("b.jar")); } @Test public void testSystemProperties() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("System-Properties", "bar baz=33 foo=y") .addEntry("foo.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list("-Dfoo=x", "-Dzzz"); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertEquals("x", getProperty(pb, "foo")); assertEquals("", getProperty(pb, "bar")); assertEquals("", getProperty(pb, "zzz")); assertEquals("33", getProperty(pb, "baz")); } @Test public void testPlatformSepcific() throws Exception { props.setProperty("capsule.java.home", "/my/1.8.0.jdk/home"); Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("Linux", "System-Properties", "bar baz=33 foo=y os=lin") .setAttribute("MacOS", "System-Properties", "bar baz=33 foo=y os=mac") .setAttribute("Windows", "System-Properties", "bar baz=33 foo=y os=win") .setAttribute("Java-8", "System-Properties", "jjj=8") .setAttribute("Java-7", "System-Properties", "jjj=7") .addEntry("foo.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list("-Dfoo=x", "-Dzzz"); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertEquals("x", getProperty(pb, "foo")); assertEquals("", getProperty(pb, "bar")); assertEquals("", getProperty(pb, "zzz")); assertEquals("33", getProperty(pb, "baz")); assertEquals("8", getProperty(pb, "jjj")); if (Capsule.isWindows()) assertEquals("win", getProperty(pb, "os")); else if (Capsule.isUnix()) assertEquals("lin", getProperty(pb, "os")); if (Capsule.isMac()) assertEquals("mac", getProperty(pb, "os")); } @Test public void testJVMArgs() throws Exception { props.setProperty("capsule.jvm.args", "-Xfoo500 -Xbar:120"); Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("JVM-Args", "-Xmx100 -Xms10 -Xfoo400") .addEntry("foo.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list("-Xms15"); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertTrue(getJvmArgs(pb).contains("-Xmx100")); assertTrue(getJvmArgs(pb).contains("-Xms15")); assertTrue(!getJvmArgs(pb).contains("-Xms10")); assertTrue(getJvmArgs(pb).contains("-Xfoo500")); assertTrue(getJvmArgs(pb).contains("-Xbar:120")); } @Test public void testAgents() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("Java-Agents", "ja1.jar ja2.jar=a=1,b=2 com.acme:bar=x=hi") .setAttribute("Native-Agents", "na1=c=3,d=4 na2") .addEntry("foo.jar", emptyInputStream()); Path barPath = mockDep("com.acme:bar", "jar", "com.acme:bar:1.2").get(0); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assert_().that(getJvmArgs(pb)).has().allOf("-javaagent:" + appCache.resolve("ja1.jar")); assert_().that(getJvmArgs(pb)).has().item("-javaagent:" + appCache.resolve("ja2.jar") + "=a=1,b=2"); assert_().that(getJvmArgs(pb)).has().item("-javaagent:" + barPath + "=x=hi"); assert_().that(getJvmArgs(pb)).has().item("-agentpath:" + appCache.resolve("na1." + Capsule.getNativeLibExtension()) + "=c=3,d=4"); assert_().that(getJvmArgs(pb)).has().item("-agentpath:" + appCache.resolve("na2." + Capsule.getNativeLibExtension())); } @Test public void testMode() throws Exception { props.setProperty("capsule.mode", "ModeX"); Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("System-Properties", "bar baz=33 foo=y") .setAttribute("ModeX", "System-Properties", "bar baz=55 foo=w") .setAttribute("ModeX", "Description", "This is a secret mode") .setAttribute("ModeX-Linux", "System-Properties", "bar baz=55 foo=w os=lin") .setAttribute("ModeX-MacOS", "System-Properties", "bar baz=55 foo=w os=mac") .setAttribute("ModeX-Windows", "System-Properties", "bar baz=55 foo=w os=win") .addEntry("foo.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list("-Dfoo=x", "-Dzzz"); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertEquals("x", getProperty(pb, "foo")); assertEquals("", getProperty(pb, "bar")); assertEquals("", getProperty(pb, "zzz")); assertEquals("55", getProperty(pb, "baz")); assertEquals(new HashSet<String>(list("ModeX")), capsule.getModes()); assertEquals("This is a secret mode", capsule.getModeDescription("ModeX")); if (Capsule.isWindows()) assertEquals("win", getProperty(pb, "os")); else if (Capsule.isUnix()) assertEquals("lin", getProperty(pb, "os")); if (Capsule.isMac()) assertEquals("mac", getProperty(pb, "os")); } @Test(expected = Exception.class) public void testMode2() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("System-Properties", "bar baz=33 foo=y") .setAttribute("ModeX", "Application-Class", "com.acme.Bar") .addEntry("foo.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); newCapsule(jar).prepareForLaunch(cmdLine, args); } @Test public void testApplicationArtifact() throws Exception { Jar bar = new Jar() .setAttribute("Main-Class", "com.acme.Bar") .addEntry("com/acme/Bar.class", emptyInputStream()); Path barPath = mockDep("com.acme:bar:1.2", "jar"); Files.createDirectories(barPath.getParent()); bar.write(barPath); Jar jar = newCapsuleJar() .setAttribute("Application", "com.acme:bar:1.2"); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assert_().that(getClassPath(pb)).has().item(barPath); assertEquals("com.acme.Bar", getMainClass(pb)); } @Test public void testEmbeddedArtifact() throws Exception { Jar bar = new Jar() .setAttribute("Main-Class", "com.acme.Bar") .setAttribute("Class-Path", "lib/liba.jar lib/libb.jar") .addEntry("com/acme/Bar.class", emptyInputStream()); Jar jar = newCapsuleJar() .setAttribute("Application", "bar.jar") .setAttribute("Application-Name", "AcmeFoo") .setAttribute("Application-Version", "1.0") .addEntry("bar.jar", bar.toByteArray()) .addEntry("lib/liba.jar", emptyInputStream()) .addEntry("lib/libb.jar", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("AcmeFoo_1.0"); assert_().that(getClassPath(pb)).has().item(appCache.resolve("bar.jar")); assert_().that(getClassPath(pb)).has().item(appCache.resolve("lib").resolve("liba.jar")); assert_().that(getClassPath(pb)).has().item(appCache.resolve("lib").resolve("libb.jar")); assertEquals("com.acme.Bar", getMainClass(pb)); } @Test public void testScript() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("Dependencies", "com.acme:bar:1.2") .setAttribute("Linux", "Application-Script", "scr.sh") .setAttribute("MacOS", "Application-Script", "scr.sh") .setAttribute("Windows", "Application-Script", "scr.bat") .addEntry("scr.sh", emptyInputStream()) .addEntry("scr.bat", emptyInputStream()) .addEntry("foo.jar", emptyInputStream()); Path barPath = mockDep("com.acme:bar:1.2", "jar"); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(jar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assertEquals(list(appCache.resolve(Capsule.isWindows() ? "scr.bat" : "scr.sh").toString(), "hi", "there"), pb.command()); assertEquals(getEnv(pb, "CLASSPATH"), absolutePath("capsule.jar") + PS + appCache + PS + appCache.resolve("foo.jar") + PS + barPath); } @Test public void testReallyExecutableCapsule() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Main-Class", "MyCapsule") .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("System-Properties", "bar baz=33 foo=y") .setAttribute("JVM-Args", "-Xmx100 -Xms10") .setReallyExecutable(true) .addEntry("a.class", emptyInputStream()); List<String> args = list("hi", "there"); List<String> cmdLine = list("-Dfoo=x", "-Dzzz", "-Xms15"); Path capsuleJar = absolutePath("capsule.jar"); jar.write(capsuleJar); Capsule.newCapsule(MY_CLASSLOADER, capsuleJar).prepareForLaunch(cmdLine, args); } @Test public void testSimpleCaplet1() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Main-Class", "MyCapsule") .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("System-Properties", "bar baz=33 foo=y") .setAttribute("JVM-Args", "-Xmx100 -Xms10") .addClass(MyCapsule.class); List<String> args = list("hi", "there"); List<String> cmdLine = list("-Dfoo=x", "-Dzzz", "-Xms15"); Path capsuleJar = absolutePath("capsule.jar"); jar.write(capsuleJar); Capsule capsule = Capsule.newCapsule(MY_CLASSLOADER, capsuleJar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertEquals("x", getProperty(pb, "foo")); assertEquals("", getProperty(pb, "bar")); assertEquals("", getProperty(pb, "zzz")); assertEquals("44", getProperty(pb, "baz")); assertTrue(getJvmArgs(pb).contains("-Xmx3000")); assertTrue(!getJvmArgs(pb).contains("-Xmx100")); assertTrue(getJvmArgs(pb).contains("-Xms15")); assertTrue(!getJvmArgs(pb).contains("-Xms10")); } @Test public void testSimpleCaplet2() throws Exception { Jar jar = newCapsuleJar() .setListAttribute("Caplets", list("MyCapsule")) .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("System-Properties", "bar baz=33 foo=y") .setAttribute("JVM-Args", "-Xmx100 -Xms10") .addClass(MyCapsule.class); List<String> args = list("hi", "there"); List<String> cmdLine = list("-Dfoo=x", "-Dzzz", "-Xms15"); Path capsuleJar = absolutePath("capsule.jar"); jar.write(capsuleJar); Capsule capsule = Capsule.newCapsule(MY_CLASSLOADER, capsuleJar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertEquals("x", getProperty(pb, "foo")); assertEquals("", getProperty(pb, "bar")); assertEquals("", getProperty(pb, "zzz")); assertEquals("44", getProperty(pb, "baz")); assertTrue(getJvmArgs(pb).contains("-Xmx3000")); assertTrue(!getJvmArgs(pb).contains("-Xmx100")); assertTrue(getJvmArgs(pb).contains("-Xms15")); assertTrue(!getJvmArgs(pb).contains("-Xms10")); } @Test public void testEmbeddedCaplet() throws Exception { Jar bar = newCapsuleJar() .setListAttribute("Caplets", list("MyCapsule")) .addClass(MyCapsule.class); Jar jar = newCapsuleJar() .setListAttribute("Caplets", list("com.acme:mycapsule:0.9")) .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("System-Properties", "bar baz=33 foo=y") .setAttribute("JVM-Args", "-Xmx100 -Xms10") .addEntry("mycapsule-0.9.jar", bar.toByteArray()); List<String> args = list("hi", "there"); List<String> cmdLine = list("-Dfoo=x", "-Dzzz", "-Xms15"); Path capsuleJar = absolutePath("capsule.jar"); jar.write(capsuleJar); Capsule capsule = Capsule.newCapsule(MY_CLASSLOADER, capsuleJar); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertEquals("x", getProperty(pb, "foo")); assertEquals("", getProperty(pb, "bar")); assertEquals("", getProperty(pb, "zzz")); assertEquals("44", getProperty(pb, "baz")); assertTrue(getJvmArgs(pb).contains("-Xmx3000")); assertTrue(!getJvmArgs(pb).contains("-Xmx100")); assertTrue(getJvmArgs(pb).contains("-Xms15")); assertTrue(!getJvmArgs(pb).contains("-Xms10")); } @Test public void testWrapperCapsule() throws Exception { Jar wrapper = newCapsuleJar() .setAttribute("Caplets", "MyCapsule") .setAttribute("System-Properties", "p1=555") .addClass(Capsule.class) .addClass(MyCapsule.class); Jar app = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("System-Properties", "p1=111") .setListAttribute("App-Class-Path", list("lib/a.jar")) .addClass(Capsule.class) .addEntry("foo.jar", emptyInputStream()) .addEntry("a.class", emptyInputStream()) .addEntry("b.txt", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()) .addEntry("lib/b.class", emptyInputStream()) .addEntry("META-INF/x.txt", emptyInputStream()); Path fooPath = mockDep("com.acme:foo", "jar", "com.acme:foo:1.0").get(0); Files.createDirectories(fooPath.getParent()); app.write(fooPath); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(wrapper).setTarget("com.acme:foo"); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); assertTrue(capsule.hasCaplet("MyCapsule")); assertTrue(capsule.toString() != null); // exercise toString // dumpFileSystem(fs); assertTrue(pb != null); String appId = capsule.getAppId(); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assertEquals("com.acme.Foo", getProperty(pb, "capsule.app")); assertEquals(appCache.toString(), getProperty(pb, "capsule.dir")); assertEquals(list("com.acme.Foo", "hi", "there"), getMainAndArgs(pb)); assertTrue(Files.isDirectory(cache)); assertTrue(Files.isDirectory(cache.resolve("apps"))); assertTrue(Files.isDirectory(appCache)); assertTrue(Files.isRegularFile(appCache.resolve(".extracted"))); assertTrue(Files.isRegularFile(appCache.resolve("foo.jar"))); assertTrue(Files.isRegularFile(appCache.resolve("b.txt"))); assertTrue(Files.isDirectory(appCache.resolve("lib"))); assertTrue(Files.isRegularFile(appCache.resolve("lib").resolve("a.jar"))); assertTrue(!Files.isRegularFile(appCache.resolve("a.class"))); assertTrue(!Files.isRegularFile(appCache.resolve("lib").resolve("b.class"))); assertTrue(!Files.isDirectory(appCache.resolve("META-INF"))); assertTrue(!Files.isRegularFile(appCache.resolve("META-INF").resolve("x.txt"))); assert_().that(getClassPath(pb)).has().allOf( fooPath, appCache, appCache.resolve("foo.jar"), appCache.resolve("lib").resolve("a.jar")); assertEquals("111", getProperty(pb, "p1")); } @Test public void testWrapperCapsuleNonCapsuleApp() throws Exception { Jar wrapper = newCapsuleJar() .setAttribute("Main-Class", "MyCapsule") .setAttribute("System-Properties", "p1=555") .addClass(Capsule.class) .addClass(MyCapsule.class); Jar app = new Jar() .setAttribute("Main-Class", "com.acme.Foo") .setAttribute("System-Properties", "p1=111") .setAttribute("Class-Path", "lib/a.jar lib/b.jar") .addEntry("a.class", emptyInputStream()) .addEntry("b.txt", emptyInputStream()) .addEntry("META-INF/x.txt", emptyInputStream()); Path fooPath = path("foo-1.0.jar"); app.write(fooPath); List<String> args = list("hi", "there"); List<String> cmdLine = list(); Capsule capsule = newCapsule(wrapper).setTarget(fooPath); ProcessBuilder pb = capsule.prepareForLaunch(cmdLine, args); // dumpFileSystem(fs); assertTrue(pb != null); String appId = capsule.getAppId(); Path appCache = cache.resolve("apps").resolve("com.acme.Foo"); assertEquals(list("com.acme.Foo", "hi", "there"), getMainAndArgs(pb)); //assertTrue(!Files.exists(appCache)); assertTrue(!Files.exists(appCache.resolve("b.txt"))); assertTrue(!Files.exists(appCache.resolve("a.class"))); assert_().that(getClassPath(pb)).has().allOf( fooPath.toAbsolutePath(), path("lib").resolve("a.jar").toAbsolutePath(), path("lib").resolve("b.jar").toAbsolutePath()); assert_().that(getClassPath(pb)).has().noneOf( absolutePath("capsule.jar"), appCache.resolve("lib").resolve("a.jar"), appCache.resolve("lib").resolve("b.jar")); assertEquals("555", getProperty(pb, "p1")); } @Test(expected = IllegalArgumentException.class) public void testWrapperCapsuleNoMain() throws Exception { Jar wrapper = newCapsuleJar() .setAttribute("Main-Class", "MyCapsule") .setAttribute("System-Properties", "p1=555") .addClass(Capsule.class) .addClass(MyCapsule.class); Jar app = new Jar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("System-Properties", "p1=111") .setListAttribute("App-Class-Path", list("lib/a.jar")) .addClass(Capsule.class) .addEntry("foo.jar", emptyInputStream()); Path fooPath = path("foo-1.0.jar"); app.write(fooPath); newCapsule(wrapper).setTarget(fooPath); } @Test public void testProcessCommandLineOptions() throws Exception { List<String> args = new ArrayList<>(list("-java-home", "/foo/bar", "-reset", "-jvm-args=a b c", "-java-cmd", "gogo", "hi", "there")); List<String> jvmArgs = list("-Dcapsule.java.cmd=wow"); processCmdLineOptions(args, jvmArgs); assertEquals("/foo/bar", props.getProperty("capsule.java.home")); assertEquals("true", props.getProperty("capsule.reset")); assertEquals("a b c", props.getProperty("capsule.jvm.args")); assertEquals(null, props.getProperty("capsule.java.cmd")); // overriden assertEquals(list("hi", "there"), args); } private static void processCmdLineOptions(List<String> args, List<String> jvmArgs) { Reflect.on(Capsule.class).call("processCmdLineOptions", args, jvmArgs); } @Test public void testTrampoline() throws Exception { props.setProperty("capsule.java.home", "/my/1.7.0.jdk/home"); props.setProperty("capsule.trampoline", "true"); Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("Extract-Capsule", "false") .addEntry("foo.jar", emptyInputStream()); Class<?> capsuleClass = loadCapsule(jar); setProperties(capsuleClass, props); StringPrintStream out = setSTDOUT(capsuleClass, new StringPrintStream()); int exit = main0(capsuleClass, "hi", "there!"); assertEquals(0, exit); String res = out.toString(); assert_().that(res).matches("[^\n]+\n\\z"); // a single line, teminated with a newline assert_().that(res).startsWith("'" + "/my/1.7.0.jdk/home/bin/java" + (Capsule.isWindows() ? ".exe" : "") + "'"); assert_().that(res).endsWith("'com.acme.Foo' 'hi' 'there!'\n"); } private static int main0(Class<?> clazz, String... args) { return Reflect.on(clazz).call("main0", (Object) args).get(); } private static boolean runActions(Object capsule, List<String> args) { return Reflect.on(capsule.getClass()).call("runActions", capsule, args).get(); } @Test public void testPrintHelp() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("Application-Version", "12.34") .addEntry("foo.jar", emptyInputStream()); props.setProperty("capsule.help", ""); Class<?> capsuleClass = loadCapsule(jar); setProperties(capsuleClass, props); StringPrintStream out = setSTDERR(capsuleClass, new StringPrintStream()); Object capsule = newCapsule(capsuleClass); boolean found = runActions(capsule, null); String res = out.toString(); assert_().that(found).isTrue(); assert_().that(res).contains("USAGE: "); } @Test public void testPrintCapsuleVersion() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("Application-Version", "12.34") .addEntry("foo.jar", emptyInputStream()); props.setProperty("capsule.version", ""); Class<?> capsuleClass = loadCapsule(jar); setProperties(capsuleClass, props); StringPrintStream out = setSTDOUT(capsuleClass, new StringPrintStream()); Object capsule = newCapsule(capsuleClass); boolean found = runActions(capsule, null); String res = out.toString(); assert_().that(found).isTrue(); assert_().that(res).contains("Application com.acme.Foo_12.34"); assert_().that(res).contains("Version: 12.34"); } @Test public void testPrintModes() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("Application-Version", "12.34") .setAttribute("ModeX", "System-Properties", "bar baz=55 foo=w") .setAttribute("ModeX", "Description", "This is a secret mode") .setAttribute("ModeY", "Description", "This is another secret mode") .setAttribute("ModeZ", "Foo", "xxx") .setAttribute("ModeX-Linux", "System-Properties", "bar baz=55 foo=w os=lin") .setAttribute("ModeX-MacOS", "System-Properties", "bar baz=55 foo=w os=mac") .setAttribute("ModeX-Windows", "System-Properties", "bar baz=55 foo=w os=win") .setAttribute("ModeY-Java-15", "Description", "This is a secret mode") .addEntry("foo.jar", emptyInputStream()); props.setProperty("capsule.modes", ""); Class<?> capsuleClass = loadCapsule(jar); setProperties(capsuleClass, props); StringPrintStream out = setSTDOUT(capsuleClass, new StringPrintStream()); Object capsule = newCapsule(capsuleClass); boolean found = runActions(capsule, null); String res = out.toString(); assert_().that(found).isTrue(); assert_().that(res).contains("* ModeX: This is a secret mode"); assert_().that(res).contains("* ModeY: This is another secret mode"); assert_().that(res).contains("* ModeZ"); assert_().that(res).doesNotContain("* ModeX-Linux"); assert_().that(res).doesNotContain("* ModeY-Java-15"); } @Test public void testMerge() throws Exception { Jar wrapper = newCapsuleJar() .setAttribute("Caplets", "MyCapsule") .setAttribute("System-Properties", "p1=555") .addClass(MyCapsule.class); Jar app = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo") .setAttribute("System-Properties", "p1=111") .setListAttribute("App-Class-Path", list("lib/a.jar")) .addClass(Capsule.class) .addEntry("foo.jar", emptyInputStream()) .addEntry("a.class", emptyInputStream()) .addEntry("b.txt", emptyInputStream()) .addEntry("lib/a.jar", emptyInputStream()) .addEntry("lib/b.class", emptyInputStream()) .addEntry("META-INF/x.txt", emptyInputStream()); Class<?> capsuleClass = loadCapsule(wrapper); setProperties(capsuleClass, props); Path fooPath = mockDep(capsuleClass, "com.acme:foo", "jar", "com.acme:foo:1.0").get(0); Files.createDirectories(fooPath.getParent()); app.write(fooPath); props.setProperty("capsule.merge", "out.jar"); props.setProperty("capsule.log", "verbose"); int exit = main0(capsuleClass, "com.acme:foo"); assertEquals(0, exit); assertTrue(Files.isRegularFile(path("out.jar"))); Jar out = new Jar(path("out.jar")); assert_().that(out.getAttribute("Main-Class")).isEqualTo("TestCapsule"); assert_().that(out.getListAttribute("Caplets")).isEqualTo(list("MyCapsule")); assert_().that(out.getMapAttribute("System-Properties", "")).isEqualTo(map("p1", "111")); FileSystem jar = ZipFS.newZipFileSystem(path("out.jar")); assertTrue(Files.isRegularFile(jar.getPath("Capsule.class"))); assertTrue(Files.isRegularFile(jar.getPath("TestCapsule.class"))); assertTrue(Files.isRegularFile(jar.getPath("MyCapsule.class"))); assertTrue(Files.isRegularFile(jar.getPath("foo.jar"))); assertTrue(Files.isRegularFile(jar.getPath("a.class"))); assertTrue(Files.isRegularFile(jar.getPath("b.txt"))); assertTrue(Files.isRegularFile(jar.getPath("lib/a.jar"))); assertTrue(Files.isRegularFile(jar.getPath("lib/b.class"))); assertTrue(Files.isRegularFile(jar.getPath("META-INF/x.txt"))); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Unit Tests"> /////////// Unit Tests /////////////////////////////////// @Test public void testParseJavaVersion() { int[] ver; ver = Capsule.parseJavaVersion("1.8.0"); assertArrayEquals(ver, ints(1, 8, 0, 0, 0)); assertEquals("1.8.0", Capsule.toJavaVersionString(ver)); ver = Capsule.parseJavaVersion("1.8"); assertArrayEquals(ver, ints(1, 8, 0, 0, 0)); assertEquals("1.8.0", Capsule.toJavaVersionString(ver)); ver = Capsule.parseJavaVersion("1.8.0_30"); assertArrayEquals(ver, ints(1, 8, 0, 30, 0)); assertEquals("1.8.0_30", Capsule.toJavaVersionString(ver)); ver = Capsule.parseJavaVersion("1.8.0-rc"); assertArrayEquals(ver, ints(1, 8, 0, 0, -1)); assertEquals("1.8.0-rc", Capsule.toJavaVersionString(ver)); ver = Capsule.parseJavaVersion("1.8.0_30-ea"); assertArrayEquals(ver, ints(1, 8, 0, 30, -3)); assertEquals("1.8.0_30-ea", Capsule.toJavaVersionString(ver)); } @Test public void testCompareVersions() { assertTrue(Capsule.compareVersions("1.8.0_30-ea", "1.8.0_30") < 0); assertTrue(Capsule.compareVersions("1.8.0_30-ea", "1.8.0_20") > 0); assertTrue(Capsule.compareVersions("1.8.0-ea", "1.8.0_20") < 0); assertTrue(Capsule.compareVersions("1.8.0-ea", "1.8.0") < 0); assertTrue(Capsule.compareVersions("1.8.0-ea", "1.7.0") > 0); } @Test public void testShortJavaVersion() { assertEquals("1.8.0", Capsule.shortJavaVersion("8")); assertEquals("1.8.0", Capsule.shortJavaVersion("1.8")); assertEquals("1.8.0", Capsule.shortJavaVersion("1.8.0")); } @Test public void isJavaDir() { assertEquals("1.7.0", Capsule.isJavaDir("jre7")); assertEquals("1.7.0_45", Capsule.isJavaDir("jdk1.7.0_45")); assertEquals("1.7.0_51", Capsule.isJavaDir("jdk1.7.0_51.jdk")); assertEquals("1.7.0", Capsule.isJavaDir("1.7.0.jdk")); assertEquals("1.8.0", Capsule.isJavaDir("jdk1.8.0.jdk")); assertEquals("1.7.0", Capsule.isJavaDir("java-7-openjdk-amd64")); assertEquals("1.8.0", Capsule.isJavaDir("java-8-oracle")); assertEquals("1.8.0", Capsule.isJavaDir("jdk-8-oracle")); assertEquals("1.8.0", Capsule.isJavaDir("jre-8-oracle")); assertEquals("1.8.0", Capsule.isJavaDir("jdk-8-oracle-x64")); } @Test public void testDelete() throws Exception { Files.createDirectories(path("a", "b", "c")); Files.createDirectories(path("a", "b1")); Files.createDirectories(path("a", "b", "c1")); Files.createFile(path("a", "x")); Files.createFile(path("a", "b", "x")); Files.createFile(path("a", "b1", "x")); Files.createFile(path("a", "b", "c", "x")); Files.createFile(path("a", "b", "c1", "x")); assertTrue(Files.exists(path("a"))); assertTrue(Files.isDirectory(path("a"))); //Files.delete(path("a")); Capsule.delete(path("a")); assertTrue(!Files.exists(path("a"))); } @Test public void testListDir() throws Exception { Files.createDirectories(path("a", "b", "c")); Files.createDirectories(path("a", "b1")); Files.createDirectories(path("a", "b", "c1")); Files.createFile(path("a", "x")); Files.createFile(path("a", "b", "x")); Files.createFile(path("a", "b1", "x")); Files.createFile(path("a", "b", "c", "x")); Files.createFile(path("a", "b", "c1", "x")); assertEquals(list(path("a", "b"), path("a", "b1"), path("a", "x")), Capsule.listDir(path("a"), null, false)); assertEquals(list(path("a", "x")), Capsule.listDir(path("a"), null, true)); assertEquals(set(path("a", "x"), path("a", "b", "x"), path("a", "b1", "x"), path("a", "b", "c", "x"), path("a", "b", "c1", "x")), set(Capsule.listDir(path("a"), "**", true))); assertEquals(list(path("a", "b1", "x")), Capsule.listDir(path("a"), "b?/*", false)); } @Test public void testGlob() throws Exception { FileSystem fs1 = FileSystems.getDefault(); PathMatcher pathMatcher = fs1.getPathMatcher("glob:java{.exe,}"); assertTrue(pathMatcher.matches(fs1.getPath("java"))); assertTrue(pathMatcher.matches(fs1.getPath("java.exe"))); assertTrue(!pathMatcher.matches(fs1.getPath(".java.exe"))); assertTrue(!pathMatcher.matches(fs1.getPath("java.exe1"))); assertTrue(!pathMatcher.matches(fs1.getPath("java."))); } @Ignore @SuppressWarnings("LocalVariableHidesMemberVariable") public void testDependencyToLocalJar() throws Exception { FileSystem fs; Path root, lib, group, file; fs = Jimfs.newFileSystem(); root = Files.createDirectories(fs.getPath("test")); lib = Files.createDirectory(root.resolve("lib")); group = Files.createDirectory(lib.resolve("com.acme")); file = Files.createFile(group.resolve("foo-3.1.mmm")); assertEquals(file, dependencyToLocalJar(root, "com.acme:foo:3.1", "mmm")); fs = Jimfs.newFileSystem(); root = Files.createDirectories(fs.getPath("test")); lib = Files.createDirectory(root.resolve("lib")); file = Files.createFile(lib.resolve("com.acme-foo-3.1.mmm")); assertEquals(file, dependencyToLocalJar(root, "com.acme:foo:3.1", "mmm")); fs = Jimfs.newFileSystem(); root = Files.createDirectories(fs.getPath("test")); lib = Files.createDirectory(root.resolve("lib")); file = Files.createFile(lib.resolve("foo-3.1.mmm")); assertEquals(file, dependencyToLocalJar(root, "com.acme:foo:3.1", "mmm")); fs = Jimfs.newFileSystem(); root = Files.createDirectories(fs.getPath("test")); group = Files.createDirectory(root.resolve("com.acme")); file = Files.createFile(group.resolve("foo-3.1.mmm")); assertEquals(file, dependencyToLocalJar(root, "com.acme:foo:3.1", "mmm")); fs = Jimfs.newFileSystem(); root = Files.createDirectories(fs.getPath("test")); file = Files.createFile(root.resolve("com.acme-foo-3.1.mmm")); assertEquals(file, dependencyToLocalJar(root, "com.acme:foo:3.1", "mmm")); fs = Jimfs.newFileSystem(); root = Files.createDirectories(fs.getPath("test")); file = Files.createFile(root.resolve("foo-3.1.mmm")); assertEquals(file, dependencyToLocalJar(root, "com.acme:foo:3.1", "mmm")); } private static Path dependencyToLocalJar(Path root, String dep, String type) { return Reflect.on(Capsule.class).call("dependencyToLocalJar", root, dep, type).get(); } @Test public void testExpandVars1() throws Exception { Jar jar = newCapsuleJar() .setAttribute("Application-Class", "com.acme.Foo"); props.setProperty("a.b.c", "777"); props.setProperty("my.prop", "888"); Capsule capsule = newCapsule(jar); capsule.prepareForLaunch(null, null); String cj = absolutePath("capsule.jar").toString(); String cd = cache.resolve("apps").resolve("com.acme.Foo").toString(); String cid = capsule.getAppId(); assertEquals(cj + "abc" + cj + "def " + cj, expand(capsule, "${CAPSULE_JAR}" + "abc" + "${CAPSULE_JAR}" + "def" + " $CAPSULE_JAR")); assertEquals(cid + " abc" + cid + "def" + cid, expand(capsule, "$CAPSULE_APP" + " abc" + "${CAPSULE_APP}" + "def" + "${CAPSULE_APP}")); assertEquals(cd + "abc " + cd + " def" + cd, expand(capsule, "${CAPSULE_DIR}" + "abc " + "$CAPSULE_DIR" + " def" + "${CAPSULE_DIR}")); assertEquals(cd + "abc" + cid + "def" + cj + "888777", expand(capsule, "${CAPSULE_DIR}" + "abc" + "${CAPSULE_APP}" + "def" + "${CAPSULE_JAR}${my.prop}${a.b.c}")); assertEquals("888", expand(capsule, "${my.prop}")); assertEquals(cj, expand(capsule, "$CAPSULE_JAR")); try { expand(capsule, "${foo.bar.baz}"); fail(); } catch (RuntimeException e) { } } private String expand(Capsule c, String s) { return Reflect.on(c).call("expand", s).get(); } @Test public void testExpandArgs() throws Exception { assertEquals(list("x", "y", "z"), Capsule.expandArgs(list("x", "y", "z"), CapsuleTest.<String>list())); assertEquals(list("a", "b", "c"), Capsule.expandArgs(CapsuleTest.<String>list(), list("a", "b", "c"))); assertEquals(list("x", "y", "z", "a", "b", "c"), Capsule.expandArgs(list("x", "y", "z"), list("a", "b", "c"))); assertEquals(list("x", "a", "b", "c", "z"), Capsule.expandArgs(list("x", "$*", "z"), list("a", "b", "c"))); assertEquals(list("b", "a", "c"), Capsule.expandArgs(list("$2", "$1", "$3"), list("a", "b", "c"))); } @Test public void testParseAttribute() { assertEquals("abcd 123", Capsule.parse("abcd 123", Capsule.T_STRING(), null)); assertEquals(true, Capsule.parse("TRUE", Capsule.T_BOOL(), null)); assertEquals(true, Capsule.parse("true", Capsule.T_BOOL(), null)); assertEquals(false, Capsule.parse("FALSE", Capsule.T_BOOL(), null)); assertEquals(false, Capsule.parse("false", Capsule.T_BOOL(), null)); assertEquals(15L, (long) Capsule.parse("15", Capsule.T_LONG(), null)); try { Capsule.parse("15abs", Capsule.T_LONG(), null); fail(); } catch (RuntimeException e) { } assertEquals(1.2, Capsule.parse("1.2", Capsule.T_DOUBLE(), null), 0.0001); try { Capsule.parse("1.2a", Capsule.T_DOUBLE(), null); fail(); } catch (RuntimeException e) { } assertEquals(list("abcd", "123"), Capsule.parse("abcd 123", Capsule.T_LIST(Capsule.T_STRING()), null)); assertEquals(list("ab", "cd", "ef", "g", "hij", "kl"), Capsule.parse("ab cd ef g hij kl ", Capsule.T_LIST(Capsule.T_STRING()), null)); assertEquals(list(true, false, true, false), Capsule.parse("TRUE false true FALSE", Capsule.T_LIST(Capsule.T_BOOL()), null)); assertEquals(list(123L, 456L, 7L), Capsule.parse("123 456 7", Capsule.T_LIST(Capsule.T_LONG()), null)); assertEquals(list(1.23, 3.45), Capsule.parse("1.23 3.45", Capsule.T_LIST(Capsule.T_DOUBLE()), null)); assertEquals(map("ab", "1", "cd", "xx", "ef", "32", "g", "xx", "hij", "", "kl", ""), Capsule.parse("ab=1 cd ef=32 g hij= kl= ", Capsule.T_MAP(Capsule.T_STRING(), Capsule.T_STRING(), "xx"), null)); try { Capsule.parse("ab=1 cd ef=32 g hij= kl= ", Capsule.T_MAP(Capsule.T_STRING(), Capsule.T_STRING(), null), null); fail(); } catch (Exception e) { } assertEquals(map("ab", true, "cd", true, "ef", false, "g", true), Capsule.parse("ab=true cd ef=false g", Capsule.T_MAP(Capsule.T_STRING(), Capsule.T_BOOL(), true), null)); try { Capsule.parse("ab=true cd ef=false g", Capsule.T_MAP(Capsule.T_STRING(), Capsule.T_BOOL(), null), null); fail(); } catch (Exception e) { } assertEquals(map("ab", 12L, "cd", 17L, "ef", 54L, "g", 17L), Capsule.parse("ab=12 cd ef=54 g", Capsule.T_MAP(Capsule.T_STRING(), Capsule.T_LONG(), 17), null)); try { Capsule.parse("ab=12 cd ef=54 g", Capsule.T_MAP(Capsule.T_STRING(), Capsule.T_LONG(), null), null); fail(); } catch (Exception e) { } try { Capsule.parse("ab=12 cd=xy ef=54 g=z", Capsule.T_MAP(Capsule.T_STRING(), Capsule.T_LONG(), 17), null); fail(); } catch (Exception e) { } assertEquals(map("ab", 12.0, "cd", 100.0, "ef", 5.4, "g", 100.0), Capsule.parse("ab=12 cd ef=5.4 g", Capsule.T_MAP(Capsule.T_STRING(), Capsule.T_DOUBLE(), 100), null)); try { Capsule.parse("ab=12.1 cd ef=5.4 g", Capsule.T_MAP(Capsule.T_STRING(), Capsule.T_DOUBLE(), null), null); fail(); } catch (Exception e) { } try { Capsule.parse("ab=12 cd=xy ef=54 g=z", Capsule.T_MAP(Capsule.T_STRING(), Capsule.T_DOUBLE(), 17.0), null); fail(); } catch (Exception e) { } assertEquals(map(12.3, 12L, 1.01, 17L, 2.05, 54L, 4.0, 17L), Capsule.parse("12.3=12 1.01 2.05=54 4.0", Capsule.T_MAP(Capsule.T_DOUBLE(), Capsule.T_LONG(), 17), null)); } @Test @SuppressWarnings("deprecation") public void testPathingJar() throws Exception { Files.createDirectories(tmp); List<Path> cp = list(path("/a.jar"), path("/b.jar"), path("/c.jar")); Path pathingJar = Capsule.createPathingJar(tmp, cp); try { List<Path> cp2; try (JarInputStream jis = new JarInputStream(Files.newInputStream(pathingJar))) { cp2 = toPath(Arrays.asList(jis.getManifest().getMainAttributes().getValue("Class-Path").split(" "))); } assertEquals(cp, toAbsolutePath(cp2)); for (Path p : cp2) assertTrue(!p.isAbsolute()); } finally { Files.delete(pathingJar); } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Utilities"> /////////// Utilities /////////////////////////////////// // may be called once per test (always writes jar into /capsule.jar) private Capsule newCapsule(Jar jar) { return (Capsule) CapsuleTestUtils.newCapsule(jar, path("capsule.jar")); } private Class<?> loadCapsule(Jar jar) throws IOException { jar = makeRealCapsuleJar(jar); return CapsuleTestUtils.loadCapsule(jar, path("capsule.jar")); } private Object newCapsule(Class<?> capsuleClass) { return CapsuleTestUtils.newCapsule(capsuleClass, path("capsule.jar")); } private Jar newCapsuleJar() { return new Jar() .setAttribute("Manifest-Version", "1.0") .setAttribute("Main-Class", "TestCapsule"); } private Jar makeRealCapsuleJar(Jar jar) throws IOException { return jar.addClass(Capsule.class) .addClass(TestCapsule.class); } private Capsule setTarget(Capsule capsule, String artifact) { return Reflect.on(capsule).call("setTarget", artifact).get(); } private Capsule setTarget(Capsule capsule, Path jar) { return Reflect.on(capsule).call("setTarget", jar).get(); } private Path path(String first, String... more) { return fs.getPath(first, more); } private Path absolutePath(String first, String... more) { return fs.getPath(first, more).toAbsolutePath(); } private InputStream emptyInputStream() { return Jar.toInputStream("", UTF_8); } private List<Path> paths(String cp) { final List<Path> res = new ArrayList<>(); for (String p : cp.split(":")) res.add(path(p)); return res; } private List<Path> getClassPath(ProcessBuilder pb) { final List<String> cmd = pb.command(); final int i = cmd.indexOf("-classpath"); if (i < 0) return null; final String cp = cmd.get(i + 1); // return Arrays.asList(cp.split(":")); return paths(cp); } private String getProperty(ProcessBuilder pb, String prop) { return getOption(pb, "-D" + prop, '='); } private String getEnv(ProcessBuilder pb, String envVar) { return pb.environment().get(envVar); } private String getOption(ProcessBuilder pb, String opt) { return getOption(pb, opt, ':'); } private String getOption(ProcessBuilder pb, String opt, char separator) { final List<String> jvmargs = getJvmArgs(pb); for (String a : jvmargs) { if (a.startsWith(opt)) { String res = getAfter(a, separator); return res != null ? res : ""; } } return null; } private List<String> getJvmArgs(ProcessBuilder pb) { boolean classpath = false; int i = 0; for (String x : pb.command().subList(1, pb.command().size())) { if (x.equals("-jar") || (!x.startsWith("-") && !classpath)) break; if (x.equals("-classpath") || x.equals("-cp")) classpath = true; else classpath = false; i++; } return pb.command().subList(1, i + 1); } private String getMainJar(ProcessBuilder pb) { final List<String> cmd = pb.command(); final int start = getJvmArgs(pb).size() + 1; if (cmd.get(start).equals("-jar")) return cmd.get(start + 1); return null; } private String getMainClass(ProcessBuilder pb) { final List<String> cmd = pb.command(); final int start = getJvmArgs(pb).size() + 1; if (cmd.get(start).equals("-jar")) return null; return cmd.get(start); } private List<String> getAppArgs(ProcessBuilder pb) { List<String> jvmArgs = getJvmArgs(pb); final List<String> cmd = pb.command(); final int start = jvmArgs.size() + 1; return cmd.subList(start + (cmd.get(start).equals("-jar") ? 2 : 1), cmd.size()); } private static List<String> getMainAndArgs(ProcessBuilder pb) { List<String> cmd = pb.command(); cmd = cmd.subList(1, cmd.size()); boolean prevClassPath = false; int i = 0; for (String c : cmd) { if (c.startsWith("-") || prevClassPath) i++; else break; prevClassPath = c.equals("-classpath"); } return cmd.subList(i, cmd.size()); } private List<Path> toPath(List<String> ps) { final List<Path> pss = new ArrayList<Path>(ps.size()); for (String p : ps) pss.add(path(p)); return pss; } private List<Path> toAbsolutePath(List<Path> ps) { final List<Path> pss = new ArrayList<Path>(ps.size()); for (Path p : ps) pss.add(p.toAbsolutePath().normalize()); return pss; } private static String getBefore(String s, char separator) { final int i = s.indexOf(separator); if (i < 0) return s; return s.substring(0, i); } private static String getAfter(String s, char separator) { final int i = s.indexOf(separator); if (i < 0) return null; return s.substring(i + 1); } private static <T extends Comparable<? super T>> List<T> sort(List<T> list) { final List<T> c = new ArrayList<>(list); Collections.<T>sort(c); return c; } private static <T> Set<T> set(Collection<T> list) { return new HashSet<>(list); } @SafeVarargs private static <T> List<T> list(T... xs) { return Arrays.asList(xs); } @SafeVarargs private static <T> Set<T> set(T... xs) { return set(Arrays.asList(xs)); } private static String[] strings(String... xs) { return xs; } private static int[] ints(int... xs) { return xs; } @SuppressWarnings("unchecked") private static <K, V> Map<K, V> map(Object... ss) { final Map<K, V> m = new HashMap<>(); for (int i = 0; i < ss.length / 2; i++) m.put((K) ss[i * 2], (V) ss[i * 2 + 1]); return Collections.unmodifiableMap(m); } private Path mockDep(String dep, String type) { return mockDep(dep, type, dep).get(0); } private List<Path> mockDep(String dep, String type, String... artifacts) { return mockDep(TestCapsule.class, dep, type, artifacts); } private List<Path> mockDep(Class<?> testCapsuleClass, String dep, String type, String... artifacts) { List<Path> as = new ArrayList<>(artifacts.length); for (String a : artifacts) as.add(artifact(a, type)); try { testCapsuleClass.getMethod("mock", String.class, String.class, List.class).invoke(null, dep, type, as); } catch (ReflectiveOperationException e) { throw rethrow(e); } return as; } private Path artifact(String x, String type) { String[] coords = x.split(":"); String group = coords[0]; String artifact = coords[1]; String artifactDir = artifact.split("-")[0]; // arbitrary String version = coords[2] + (coords.length > 3 ? "-" + coords[3] : ""); return cache.resolve("deps").resolve(group).resolve(artifactDir).resolve(artifact + "-" + version + '.' + type); } private static void dumpFileSystem(FileSystem fs) { try { Files.walkFileTree(fs.getRootDirectories().iterator().next(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { System.out.println("-- " + file); return super.visitFile(file, attrs); } }); } catch (IOException e) { throw new RuntimeException(e); } } private static final String PS = System.getProperty("path.separator"); //</editor-fold> }
Fix test fixture (!!)
capsule/src/test/java/CapsuleTest.java
Fix test fixture (!!)
<ide><path>apsule/src/test/java/CapsuleTest.java <ide> <ide> private Class<?> loadCapsule(Jar jar) throws IOException { <ide> jar = makeRealCapsuleJar(jar); <del> return CapsuleTestUtils.loadCapsule(jar, path("capsule.jar")); <add> Class<?> clazz = CapsuleTestUtils.loadCapsule(jar, path("capsule.jar")); <add> setProperties(clazz, props); <add> setCacheDir(clazz, cache); <add> return clazz; <ide> } <ide> <ide> private Object newCapsule(Class<?> capsuleClass) {
Java
agpl-3.0
e9f3064de2ae35754af5e6b5862593886e18cead
0
mnip91/proactive-component-monitoring,lpellegr/programming,paraita/programming,PaulKh/scale-proactive,acontes/scheduling,acontes/scheduling,mnip91/proactive-component-monitoring,PaulKh/scale-proactive,paraita/programming,lpellegr/programming,fviale/programming,mnip91/programming-multiactivities,jrochas/scale-proactive,paraita/programming,lpellegr/programming,ow2-proactive/programming,acontes/programming,mnip91/programming-multiactivities,fviale/programming,mnip91/programming-multiactivities,jrochas/scale-proactive,ow2-proactive/programming,ow2-proactive/programming,PaulKh/scale-proactive,mnip91/programming-multiactivities,acontes/scheduling,fviale/programming,PaulKh/scale-proactive,paraita/programming,lpellegr/programming,lpellegr/programming,mnip91/programming-multiactivities,acontes/scheduling,PaulKh/scale-proactive,jrochas/scale-proactive,jrochas/scale-proactive,fviale/programming,paraita/programming,fviale/programming,jrochas/scale-proactive,acontes/scheduling,acontes/scheduling,acontes/programming,acontes/programming,acontes/programming,paraita/programming,fviale/programming,jrochas/scale-proactive,mnip91/proactive-component-monitoring,ow2-proactive/programming,acontes/programming,PaulKh/scale-proactive,mnip91/proactive-component-monitoring,mnip91/proactive-component-monitoring,jrochas/scale-proactive,acontes/programming,ow2-proactive/programming,ow2-proactive/programming,mnip91/programming-multiactivities,acontes/scheduling,acontes/programming,PaulKh/scale-proactive,mnip91/proactive-component-monitoring,lpellegr/programming
/* * ################################################################ * * ProActive: The Java(TM) library for Parallel, Distributed, * Concurrent computing with Security and Mobility * * Copyright (C) 1997-2002 INRIA/University of Nice-Sophia Antipolis * Contact: [email protected] * * 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 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 * * Initial developer(s): The ProActive Team * http://www.inria.fr/oasis/ProActive/contacts.html * Contributor(s): * * ################################################################ */ package org.objectweb.proactive.core.body; import org.objectweb.proactive.Active; import org.objectweb.proactive.Body; import org.objectweb.proactive.EndActive; import org.objectweb.proactive.InitActive; import org.objectweb.proactive.RunActive; import org.objectweb.proactive.core.body.migration.MigratableBody; import org.objectweb.proactive.core.mop.ConstructorCall; import org.objectweb.proactive.core.mop.ConstructorCallExecutionFailedException; /** * This class is the default implementation of the Body interface. * An implementation of the Body interface, which lets the reified object * explicitely manage the queue of pending requests through its live() routine. * * @author ProActive Team * @version 1.0, 2001/10/23 * @since ProActive 0.9 * @see org.objectweb.proactive.Body * @see AbstractBody * @see org.objectweb.proactive.core.body.migration.AbstractMigratableBody * */ public class ActiveBody extends MigratableBody implements Runnable, java.io.Serializable { // // -- STATIC MEMBERS ----------------------------------------------- // // // -- PROTECTED MEMBERS ----------------------------------------------- // // // -- PRIVATE MEMBERS ----------------------------------------------- // private transient InitActive initActive; // used only once when active object is started first time private RunActive runActive; private EndActive endActive; // // -- CONSTRUCTORS ----------------------------------------------- // /** * Doesn't build anything, just for having one no-arg constructor */ public ActiveBody() { } /** * Build the body object, then fires its service thread */ public ActiveBody(ConstructorCall c, String nodeURL, Active activity, MetaObjectFactory factory) throws java.lang.reflect.InvocationTargetException, ConstructorCallExecutionFailedException { // Creates the reified object super(c.execute(), nodeURL, factory); // InitActive Object reifiedObject = localBodyStrategy.getReifiedObject(); if (activity != null && activity instanceof InitActive) { initActive = (InitActive) activity; } else if (reifiedObject instanceof InitActive) { initActive = (InitActive) reifiedObject; } // RunActive if (activity != null && activity instanceof RunActive) { runActive = (RunActive) activity; } else if (reifiedObject instanceof RunActive) { runActive = (RunActive) reifiedObject; } else { runActive = new FIFORunActive(); } // EndActive if (activity != null && activity instanceof EndActive) { endActive = (EndActive) activity; } else if (reifiedObject instanceof EndActive) { endActive = (EndActive) reifiedObject; } else { endActive = null; } startBody(); } // // -- PUBLIC METHODS ----------------------------------------------- // // // -- implements Runnable ----------------------------------------------- // /** * The method executed by the active thread that will eventually launch the live * method of the active object of the default live method of this body. */ public void run() { activityStarted(); // execute the initialization if needed. Only once if (initActive != null) { initActive.initActivity(this); initActive = null; // we won't do it again } // run the activity of the body try { runActive.runActivity(this); // the body terminate its activity if (isActive()) { // serve remaining requests if non dead while (!(localBodyStrategy.getRequestQueue().isEmpty())) { serve(localBodyStrategy.getRequestQueue().removeOldest()); } } } catch (Exception e) { System.out.println("Exception occured in live method of body "+toString()+". Now terminating the body"); e.printStackTrace(); terminate(); } finally { if (isActive()) activityStopped(); // execute the end of activity if not after migration if ((! hasJustMigrated) && endActive != null) { endActive.endActivity(this); } } } // // -- PROTECTED METHODS ----------------------------------------------- // /** * Creates the active thread and start it using this runnable body. */ protected void startBody() { Thread t = new Thread(this, shortClassName(getName())+" on "+getNodeURL()); t.start(); } /** * Signals that the activity of this body, managed by the active thread has just stopped. */ protected void activityStopped() { super.activityStopped(); runActive = null; } // // -- PRIVATE METHODS ----------------------------------------------- // private static String shortClassName(String fqn) { int n = fqn.lastIndexOf('.'); if (n == -1 || n == fqn.length()-1) return fqn; return fqn.substring(n+1); } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { out.defaultWriteObject(); } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { in.defaultReadObject(); startBody(); } // // -- INNER CLASSES ----------------------------------------------- // private class FIFORunActive implements RunActive, java.io.Serializable { public void runActivity(Body body) { while (isActive()) { serve(localBodyStrategy.getRequestQueue().blockingRemoveOldest()); } } } }
src/org/objectweb/proactive/core/body/ActiveBody.java
/* * ################################################################ * * ProActive: The Java(TM) library for Parallel, Distributed, * Concurrent computing with Security and Mobility * * Copyright (C) 1997-2002 INRIA/University of Nice-Sophia Antipolis * Contact: [email protected] * * 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 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 * * Initial developer(s): The ProActive Team * http://www.inria.fr/oasis/ProActive/contacts.html * Contributor(s): * * ################################################################ */ package org.objectweb.proactive.core.body; import org.objectweb.proactive.Active; import org.objectweb.proactive.Body; import org.objectweb.proactive.EndActive; import org.objectweb.proactive.InitActive; import org.objectweb.proactive.RunActive; import org.objectweb.proactive.core.body.migration.MigratableBody; import org.objectweb.proactive.core.mop.ConstructorCall; import org.objectweb.proactive.core.mop.ConstructorCallExecutionFailedException; /** * This class is the default implementation of the Body interface. * An implementation of the Body interface, which lets the reified object * explicitely manage the queue of pending requests through its live() routine. * * @author ProActive Team * @version 1.0, 2001/10/23 * @since ProActive 0.9 * @see org.objectweb.proactive.Body * @see AbstractBody * @see AbstractMigratableBody * */ public class ActiveBody extends MigratableBody implements Runnable, java.io.Serializable { // // -- STATIC MEMBERS ----------------------------------------------- // // // -- PROTECTED MEMBERS ----------------------------------------------- // // // -- PRIVATE MEMBERS ----------------------------------------------- // private transient InitActive initActive; // used only once when active object is started first time private RunActive runActive; private EndActive endActive; // // -- CONSTRUCTORS ----------------------------------------------- // /** * Doesn't build anything, just for having one no-arg constructor */ public ActiveBody() { } /** * Build the body object, then fires its service thread */ public ActiveBody(ConstructorCall c, String nodeURL, Active activity, MetaObjectFactory factory) throws java.lang.reflect.InvocationTargetException, ConstructorCallExecutionFailedException { // Creates the reified object super(c.execute(), nodeURL, factory); // InitActive Object reifiedObject = localBodyStrategy.getReifiedObject(); if (activity != null && activity instanceof InitActive) { initActive = (InitActive) activity; } else if (reifiedObject instanceof InitActive) { initActive = (InitActive) reifiedObject; } // RunActive if (activity != null && activity instanceof RunActive) { runActive = (RunActive) activity; } else if (reifiedObject instanceof RunActive) { runActive = (RunActive) reifiedObject; } else { runActive = new FIFORunActive(); } // EndActive if (activity != null && activity instanceof EndActive) { endActive = (EndActive) activity; } else if (reifiedObject instanceof EndActive) { endActive = (EndActive) reifiedObject; } else { endActive = null; } startBody(); } // // -- PUBLIC METHODS ----------------------------------------------- // // // -- implements Runnable ----------------------------------------------- // /** * The method executed by the active thread that will eventually launch the live * method of the active object of the default live method of this body. */ public void run() { activityStarted(); // execute the initialization if needed. Only once if (initActive != null) { initActive.initActivity(this); initActive = null; // we won't do it again } // run the activity of the body try { runActive.runActivity(this); // the body terminate its activity if (isActive()) { // serve remaining requests if non dead while (!(localBodyStrategy.getRequestQueue().isEmpty())) { serve(localBodyStrategy.getRequestQueue().removeOldest()); } } } catch (Exception e) { System.out.println("Exception occured in live method of body "+toString()+". Now terminating the body"); e.printStackTrace(); terminate(); } finally { if (isActive()) activityStopped(); // execute the end of activity if not after migration if ((! hasJustMigrated) && endActive != null) { endActive.endActivity(this); } } } // // -- PROTECTED METHODS ----------------------------------------------- // /** * Creates the active thread and start it using this runnable body. */ protected void startBody() { Thread t = new Thread(this, shortClassName(getName())+" on "+getNodeURL()); t.start(); } /** * Signals that the activity of this body, managed by the active thread has just stopped. */ protected void activityStopped() { super.activityStopped(); runActive = null; } // // -- PRIVATE METHODS ----------------------------------------------- // private static String shortClassName(String fqn) { int n = fqn.lastIndexOf('.'); if (n == -1 || n == fqn.length()-1) return fqn; return fqn.substring(n+1); } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { out.defaultWriteObject(); } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { in.defaultReadObject(); startBody(); } // // -- INNER CLASSES ----------------------------------------------- // private class FIFORunActive implements RunActive, java.io.Serializable { public void runActivity(Body body) { while (isActive()) { serve(localBodyStrategy.getRequestQueue().blockingRemoveOldest()); } } } }
Not modified since last commit git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@124 28e8926c-6b08-0410-baaa-805c5e19b8d6
src/org/objectweb/proactive/core/body/ActiveBody.java
Not modified since last commit
<ide><path>rc/org/objectweb/proactive/core/body/ActiveBody.java <ide> * @since ProActive 0.9 <ide> * @see org.objectweb.proactive.Body <ide> * @see AbstractBody <del> * @see AbstractMigratableBody <add> * @see org.objectweb.proactive.core.body.migration.AbstractMigratableBody <ide> * <ide> */ <ide> public class ActiveBody extends MigratableBody implements Runnable, java.io.Serializable {
Java
apache-2.0
9f1f0e4701c237109380bc981373d691d5e66dfb
0
adgear/secor,adgear/secor
/** * 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 com.pinterest.secor.consumer; import com.pinterest.secor.common.FileRegistry; import com.pinterest.secor.common.OffsetTracker; import com.pinterest.secor.common.SecorConfig; import com.pinterest.secor.message.Message; import com.pinterest.secor.message.ParsedMessage; import com.pinterest.secor.parser.MessageParser; import com.pinterest.secor.uploader.Uploader; import com.pinterest.secor.uploader.UploadManager; import com.pinterest.secor.reader.MessageReader; import com.pinterest.secor.util.ReflectionUtil; import com.pinterest.secor.writer.MessageWriter; import kafka.consumer.ConsumerTimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.Thread; /** * Consumer is a top-level component coordinating reading, writing, and uploading Kafka log * messages. It is implemented as a thread with the intent of running multiple consumer * concurrently. * * Note that consumer is not fixed with a specific topic partition. Kafka rebalancing mechanism * allocates topic partitions to consumers dynamically to accommodate consumer population changes. * * @author Pawel Garbacki ([email protected]) */ public class Consumer extends Thread { private static final Logger LOG = LoggerFactory.getLogger(Consumer.class); private SecorConfig mConfig; private MessageReader mMessageReader; private MessageWriter mMessageWriter; private MessageParser mMessageParser; private OffsetTracker mOffsetTracker; private Uploader mUploader; // TODO(pawel): we should keep a count per topic partition. private double mUnparsableMessages; public Consumer(SecorConfig config) { mConfig = config; } private void init() throws Exception { mOffsetTracker = new OffsetTracker(); mMessageReader = new MessageReader(mConfig, mOffsetTracker); FileRegistry fileRegistry = new FileRegistry(mConfig); UploadManager uploadManager = ReflectionUtil.createUploadManager(mConfig.getUploadManagerClass(), mConfig); mUploader = new Uploader(mConfig, mOffsetTracker, fileRegistry, uploadManager); mMessageWriter = new MessageWriter(mConfig, mOffsetTracker, fileRegistry); mMessageParser = ReflectionUtil.createMessageParser(mConfig.getMessageParserClass(), mConfig); mUnparsableMessages = 0.; } @Override public void run() { try { // init() cannot be called in the constructor since it contains logic dependent on the // thread id. init(); } catch (Exception e) { throw new RuntimeException("Failed to initialize the consumer", e); } // check upload policy every N seconds or 10,000 messages/consumer timeouts long checkEveryNSeconds = Math.min(10 * 60, mConfig.getMaxFileAgeSeconds() / 2); long checkMessagesPerSecond = mConfig.getMessagesPerSecond(); long nMessages = 0; long lastChecked = System.currentTimeMillis(); while (true) { boolean hasMoreMessages = consumeNextMessage(); if (!hasMoreMessages) { break; } long now = System.currentTimeMillis(); if (nMessages++ % checkMessagesPerSecond == 0 || (now - lastChecked) > checkEveryNSeconds * 1000) { lastChecked = now; checkUploadPolicy(); } } checkUploadPolicy(); } private void checkUploadPolicy() { try { mUploader.applyPolicy(); } catch(org.apache.http.NoHttpResponseException e) { LOG.warn("Ignoring HTTP failure:"); e.printStackTrace(); } catch (Exception e) { throw new RuntimeException("Failed to apply upload policy", e); } } // @return whether there are more messages left to consume private boolean consumeNextMessage() { Message rawMessage = null; try { boolean hasNext = mMessageReader.hasNext(); if (!hasNext) { return false; } rawMessage = mMessageReader.read(); } catch (ConsumerTimeoutException e) { // We wait for a new message with a timeout to periodically apply the upload policy // even if no messages are delivered. LOG.trace("Consumer timed out", e); } if (rawMessage != null) { // Before parsing, update the offset and remove any redundant data try { mMessageWriter.adjustOffset(rawMessage); } catch (IOException e) { throw new RuntimeException("Failed to adjust offset.", e); } ParsedMessage parsedMessage = null; try { parsedMessage = mMessageParser.parse(rawMessage); final double DECAY = 0.999; mUnparsableMessages *= DECAY; } catch (Throwable e) { mUnparsableMessages++; final double MAX_UNPARSABLE_MESSAGES = 1000.; if (mUnparsableMessages > MAX_UNPARSABLE_MESSAGES) { throw new RuntimeException("Failed to parse message " + rawMessage, e); } LOG.warn("Failed to parse message {}", rawMessage, e); } if (parsedMessage != null) { try { mMessageWriter.write(parsedMessage); } catch (Exception e) { throw new RuntimeException("Failed to write message " + parsedMessage, e); } } } return true; } /** * Helper to get the offset tracker (used in tests) * * @param topic * @param partition * @return */ public OffsetTracker getOffsetTracker() { return this.mOffsetTracker; } }
src/main/java/com/pinterest/secor/consumer/Consumer.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 com.pinterest.secor.consumer; import com.pinterest.secor.common.FileRegistry; import com.pinterest.secor.common.OffsetTracker; import com.pinterest.secor.common.SecorConfig; import com.pinterest.secor.message.Message; import com.pinterest.secor.message.ParsedMessage; import com.pinterest.secor.parser.MessageParser; import com.pinterest.secor.uploader.Uploader; import com.pinterest.secor.uploader.UploadManager; import com.pinterest.secor.reader.MessageReader; import com.pinterest.secor.util.ReflectionUtil; import com.pinterest.secor.writer.MessageWriter; import kafka.consumer.ConsumerTimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.Thread; /** * Consumer is a top-level component coordinating reading, writing, and uploading Kafka log * messages. It is implemented as a thread with the intent of running multiple consumer * concurrently. * * Note that consumer is not fixed with a specific topic partition. Kafka rebalancing mechanism * allocates topic partitions to consumers dynamically to accommodate consumer population changes. * * @author Pawel Garbacki ([email protected]) */ public class Consumer extends Thread { private static final Logger LOG = LoggerFactory.getLogger(Consumer.class); private SecorConfig mConfig; private MessageReader mMessageReader; private MessageWriter mMessageWriter; private MessageParser mMessageParser; private OffsetTracker mOffsetTracker; private Uploader mUploader; // TODO(pawel): we should keep a count per topic partition. private double mUnparsableMessages; public Consumer(SecorConfig config) { mConfig = config; } private void init() throws Exception { mOffsetTracker = new OffsetTracker(); mMessageReader = new MessageReader(mConfig, mOffsetTracker); FileRegistry fileRegistry = new FileRegistry(mConfig); UploadManager uploadManager = ReflectionUtil.createUploadManager(mConfig.getUploadManagerClass(), mConfig); mUploader = new Uploader(mConfig, mOffsetTracker, fileRegistry, uploadManager); mMessageWriter = new MessageWriter(mConfig, mOffsetTracker, fileRegistry); mMessageParser = ReflectionUtil.createMessageParser(mConfig.getMessageParserClass(), mConfig); mUnparsableMessages = 0.; } @Override public void run() { try { // init() cannot be called in the constructor since it contains logic dependent on the // thread id. init(); } catch (Exception e) { throw new RuntimeException("Failed to initialize the consumer", e); } // check upload policy every N seconds or 10,000 messages/consumer timeouts long checkEveryNSeconds = Math.min(10 * 60, mConfig.getMaxFileAgeSeconds() / 2); long checkMessagesPerSecond = mConfig.getMessagesPerSecond(); long nMessages = 0; long lastChecked = System.currentTimeMillis(); while (true) { boolean hasMoreMessages = consumeNextMessage(); if (!hasMoreMessages) { break; } long now = System.currentTimeMillis(); if (nMessages++ % checkMessagesPerSecond == 0 || (now - lastChecked) > checkEveryNSeconds * 1000) { lastChecked = now; checkUploadPolicy(); } } checkUploadPolicy(); } private void checkUploadPolicy() { try { mUploader.applyPolicy(); } catch (Exception e) { throw new RuntimeException("Failed to apply upload policy", e); } } // @return whether there are more messages left to consume private boolean consumeNextMessage() { Message rawMessage = null; try { boolean hasNext = mMessageReader.hasNext(); if (!hasNext) { return false; } rawMessage = mMessageReader.read(); } catch (ConsumerTimeoutException e) { // We wait for a new message with a timeout to periodically apply the upload policy // even if no messages are delivered. LOG.trace("Consumer timed out", e); } if (rawMessage != null) { // Before parsing, update the offset and remove any redundant data try { mMessageWriter.adjustOffset(rawMessage); } catch (IOException e) { throw new RuntimeException("Failed to adjust offset.", e); } ParsedMessage parsedMessage = null; try { parsedMessage = mMessageParser.parse(rawMessage); final double DECAY = 0.999; mUnparsableMessages *= DECAY; } catch (Throwable e) { mUnparsableMessages++; final double MAX_UNPARSABLE_MESSAGES = 1000.; if (mUnparsableMessages > MAX_UNPARSABLE_MESSAGES) { throw new RuntimeException("Failed to parse message " + rawMessage, e); } LOG.warn("Failed to parse message {}", rawMessage, e); } if (parsedMessage != null) { try { mMessageWriter.write(parsedMessage); } catch (Exception e) { throw new RuntimeException("Failed to write message " + parsedMessage, e); } } } return true; } /** * Helper to get the offset tracker (used in tests) * * @param topic * @param partition * @return */ public OffsetTracker getOffsetTracker() { return this.mOffsetTracker; } }
Ignore hopefully-transient HTTP errors.
src/main/java/com/pinterest/secor/consumer/Consumer.java
Ignore hopefully-transient HTTP errors.
<ide><path>rc/main/java/com/pinterest/secor/consumer/Consumer.java <ide> private void checkUploadPolicy() { <ide> try { <ide> mUploader.applyPolicy(); <add> } catch(org.apache.http.NoHttpResponseException e) { <add> LOG.warn("Ignoring HTTP failure:"); <add> e.printStackTrace(); <ide> } catch (Exception e) { <ide> throw new RuntimeException("Failed to apply upload policy", e); <ide> }
Java
lgpl-2.1
b1882299a37fd1256862bbf630f8051818312a74
0
agentlab/ru.agentlab.maia
/******************************************************************************* * Copyright (c) 2016 AgentLab. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package ru.agentlab.maia.agent.converter; import java.util.Arrays; import java.util.Collection; import java.util.stream.Stream; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import org.semanticweb.owlapi.vocab.Namespaces; /** * Test method {@link Converter#splitDatatypeLiteral(String)} which split literal into 3 parts: * <ol> * <li>Literal value; * <li>Literal language; * <li>Literal datatype; * </ol> * <p> * Test cases: * <!-- @formatter:off --> * <table border="thin single black collapse"> * <thead> * <tr><th rowspan="2">## <th>Input <th colspan="3">Output <th rowspan="2">Comment * <tr> <th>Parameter <th>Literal <th>Language<th>Datatype * <thead> * <tbody> * <tr><td> 0 <td>"" <td>"" <td>null <td>null <td>test empty string * <tr><td> 1 <td>"^^rdf:XMLLiteral" <td>"" <td>null <td>"rdf:XMLLiteral" <td>test only datatype * <tr><td> 2 <td>"^^&lt;RDF#XMLLiteral&gt;" <td>"" <td>null <td>"&lt;RDF#XMLLiteral&gt;"<td>test only full datatype * <tr><td> 3 <td>"@ru" <td>"" <td>"ru" <td>null <td>test only language * <tr><td> 4 <td>"@ru-RU" <td>"" <td>"ru-RU" <td>null <td>test only language * <tr><td> 5 <td>"@en^^rdf:XMLLiteral" <td>"" <td>"en" <td>"rdf:XMLLiteral" <td>test language and datatype * <tr><td> 6 <td>"@en^^&lt;RDFS#Literal&gt;" <td>"" <td>"en" <td>"&lt;RDFS#Literal&gt;" <td>test language and full datatype * <tr><td colspan="6"> * <tr><td> 7 <td>"some" <td>"some" <td>null <td>null <td>test single word string * <tr><td> 8 <td>"test^^rdf:XMLLiteral" <td>"test" <td>null <td>"rdf:XMLLiteral" <td>test single word and datatype * <tr><td> 9 <td>"test^^&lt;RDF#XMLLiteral&gt;" <td>"test" <td>null <td>"&lt;RDF#XMLLiteral>" <td>test single word and full datatype * <tr><td>10 <td>"тест@ru" <td>"тест" <td>"ru" <td>null <td>test single word and language * <tr><td>11 <td>"тест@ru-RU" <td>"тест" <td>"ru-RU" <td>null <td>test single word and language * <tr><td>12 <td>"test@en^^rdf:XMLLiteral" <td>"test" <td>"en" <td>"rdf:XMLLiteral" <td>test single word language and datatype * <tr><td>13 <td>"test@en^^&lt;RDF#XMLLiteral&gt;"<td>"test" <td>"en" <td>"&lt;RDF#XMLLiteral&gt;"<td>test single word language and full datatype * <tr><td colspan="6"> * <tr><td>14 <td>"some more" <td>"some more" <td>null <td>null <td>test multiple words string * <tr><td>15 <td>"test w 2^^rdf:XMLLiteral" <td>"test w 2" <td>null <td>"rdf:XMLLiteral" <td>test multiple words and datatype * <tr><td>16 <td>"test^^&lt;OWL#XMLLiteral&gt;" <td>"test" <td>null <td>"&lt;OWL#XMLLiteral&gt;"<td>test multiple words and full datatype * <tr><td>17 <td>"тест 2 3@ru" <td>"тест 2 3" <td>"ru" <td>null <td>test multiple words and language * <tr><td>18 <td>"тест qwe@ru-RU" <td>"тест qwe" <td>"ru-RU" <td>null <td>test multiple words and language * <tr><td>19 <td>"test@en^^rdf:XMLLiteral" <td>"test" <td>"en" <td>"rdf:XMLLiteral" <td>test multiple words language and datatype * <tr><td>20 <td>"test@en^^&lt;XSD#XMLLiteral&gt;"<td>"test" <td>"en" <td>"&lt;XSD#XMLLiteral&gt;"<td>test multiple words language and full datatype * <tr><td colspan="6"> * <tr><td>21 <td>"som\r\n\tmore" <td>"som\r\n\tmore" <td>null <td>null <td>test \r\n\t in literal * <tr><td>22 <td>"2^2^^owl:real" <td>"2^2" <td>null <td>"owl:real" <td>test ^ in literal * <tr><td>23 <td>"2^^2^^owl:real" <td>"2^^2" <td>null <td>"owl:real" <td>test ^^ in literal * <tr><td>24 <td>"2^^2@^^owl:real" <td>"2^^2" <td>"" <td>"owl:real" <td>test ^^ and @ in literal * <tr><td>25 <td>"[email protected]@en^^xsd:real" <td>"[email protected]" <td>"en" <td>"xsd:real" <td>test @ in literal * </tbody> * </table> * <!-- @formatter:on --> * Used Namespaces: * <ul> * <li>RDF = http://www.w3.org/1999/02/22-rdf-syntax-ns# * <li>RDFS = http://www.w3.org/2000/01/rdf-schema# * <li>OWL = http://www.w3.org/2002/07/owl# * <li>XSD = http://www.w3.org/2001/XMLSchema# * </ul> * * * @author Dmitriy Shishkin <[email protected]> */ @RunWith(Parameterized.class) public class ConverterSplitDatatypeLiteralTest { private final static String RDF = Namespaces.RDF.toString(); private final static String RDFS = Namespaces.RDFS.toString(); private final static String OWL = Namespaces.OWL.toString(); private final static String XSD = Namespaces.XSD.toString(); // @formatter:off // Name is not working because some of the test strings have \r\n symbols @Parameters//(name="When parameter is [{0}] then result is [{1}]") public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { /* ------------------------------------------------------------------------------------------------------------------------------------- *| ## | Input Parameter | Literal | Language | Datatype | Comment | *--------------------------------------------------------------------------------------------------------------------------------------*/ // Empty word /* 0 */ { "", "", null, null }, // test empty string /* 1 */ { "^^rdf:XMLLiteral", "", null, "rdf:XMLLiteral" }, // test only datatype /* 2 */ { "^^<" + RDF + "XMLLiteral>", "", null, "<" + RDF + "XMLLiteral>" },// test only full datatype /* 3 */ { "@ru", "", "ru", null }, // test only language /* 4 */ { "@ru-RU", "", "ru-RU", null }, // test only language /* 5 */ { "@en^^rdf:XMLLiteral", "", "en", "rdf:XMLLiteral" }, // test language and datatype /* 6 */ { "@en^^<" + RDFS + "Literal>", "", "en", "<" + RDFS + "Literal>" }, // test language and full datatype // Single word /* 7 */ { "some", "some", null, null }, // test single word string /* 8 */ { "test^^rdf:XMLLiteral", "test", null, "rdf:XMLLiteral" }, // test single word and datatype /* 9 */ { "test^^<" + RDF + "XMLLiteral>", "test", null, "<" + RDF + "XMLLiteral>" },// test single word and full datatype /* 10 */ { "тест@ru", "тест", "ru", null }, // test single word and language /* 11 */ { "тест@ru-RU", "тест", "ru-RU", null }, // test single word and language /* 12 */ { "test@en^^rdf:XMLLiteral", "test", "en", "rdf:XMLLiteral" }, // test single word, language and datatype /* 13 */ { "test@en^^<" + RDF + "XMLLiteral>", "test", "en", "<" + RDF + "XMLLiteral>" },// test single word, language and full datatype // Multiple words /* 14 */ { "some more", "some more", null, null }, // test multiple words string /* 15 */ { "test w 2^^rdf:XMLLiteral", "test w 2", null, "rdf:XMLLiteral" }, // test multiple words and datatype /* 16 */ { "test^^<" + OWL + "XMLLiteral>", "test", null, "<" + OWL + "XMLLiteral>" },// test multiple words and full datatype /* 17 */ { "тест 2 3@ru", "тест 2 3", "ru", null }, // test multiple words and language /* 18 */ { "тест qwe@ru-RU", "тест qwe", "ru-RU", null }, // test multiple words and language /* 19 */ { "test@en^^rdf:XMLLiteral", "test", "en", "rdf:XMLLiteral" }, // test multiple words, language and datatype /* 20 */ { "test@en^^<" + XSD + "XMLLiteral>", "test", "en", "<" + XSD + "XMLLiteral>" },// test multiple words, language and full datatype // Special characters /* 21 */ { "som\r\n\tmore", "som\r\n\tmore",null, null }, // test \r\n\t in literal /* 22 */ { "2^2^^owl:real", "2^2", null, "owl:real" }, // test ^ in literal /* 23 */ { "2^^2^^owl:real", "2^^2", null, "owl:real" }, // test ^^ in literal /* 24 */ { "2^^2@^^owl:real", "2^^2", "", "owl:real" }, // test ^^ and @ in literal /* 25 */ { "[email protected]@en^^xsd:real", "[email protected]","en", "xsd:real" }, // test @ in literal }); } // @formatter:on @Parameter(0) public String parameter; @Parameter(1) public String value; @Parameter(2) public String language; @Parameter(3) public String datatype; @Test public void anyEmptyLiteralShouldThrow() { System.out.println("[" + parameter + "]"); String[] splitted = Converter.splitDatatypeLiteral(parameter); Stream.of(splitted).forEach(s -> System.out.println(" [" + s + "]")); Assert.assertEquals(3, splitted.length); Assert.assertEquals(value, splitted[0]); Assert.assertEquals(language, splitted[1]); Assert.assertEquals(datatype, splitted[2]); } }
tests/ru.agentlab.maia.agent.test/src/ru/agentlab/maia/agent/converter/ConverterSplitDatatypeLiteralTest.java
/******************************************************************************* * Copyright (c) 2016 AgentLab. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package ru.agentlab.maia.agent.converter; import java.util.Arrays; import java.util.Collection; import java.util.stream.Stream; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import org.semanticweb.owlapi.vocab.Namespaces; /** * Test method which split literal into 3 parts: * <ol> * <li>Literal value; * <li>Literal language; * <li>Literal datatype; * </ol> * * @author Dmitriy Shishkin <[email protected]> */ @RunWith(Parameterized.class) public class ConverterSplitDatatypeLiteralTest { private final static String RDF = Namespaces.RDF.toString(); private final static String RDFS = Namespaces.RDFS.toString(); private final static String OWL = Namespaces.OWL.toString(); private final static String XSD = Namespaces.XSD.toString(); // @formatter:off // Name is not working because some of the test strings have \r\n symbols @Parameters//(name="When parameter is [{0}] then result is [{1}]") public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { /* -------------------------------------------------------------------------------------------------------------------------------------------- *| ## | Input Parameter | Literal | Language | Datatype | Comment | *---------------------------------------------------------------------------------------------------------------------------------------------*/ // Empty word /* 0 */ { "", "", null, null }, // test empty string /* 1 */ { "^^rdf:XMLLiteral", "", null, "rdf:XMLLiteral" }, // test only datatype /* 2 */ { "^^<" + RDF + "XMLLiteral>", "", null, "<" + RDF + "XMLLiteral>" }, // test only full datatype /* 3 */ { "@ru", "", "ru", null }, // test only language /* 4 */ { "@ru-RU", "", "ru-RU", null }, // test only language /* 5 */ { "@en^^rdf:XMLLiteral", "", "en", "rdf:XMLLiteral" }, // test language and datatype /* 6 */ { "@en^^<" + RDFS + "Literal>", "", "en", "<" + RDFS + "Literal>" }, // test language and full datatype // Single word /* 7 */ { "some", "some", null, null }, // test single word string /* 8 */ { "test^^rdf:XMLLiteral", "test", null, "rdf:XMLLiteral" }, // test single word and datatype /* 9 */ { "test^^<" + RDF + "XMLLiteral>", "test", null, "<" + RDF + "XMLLiteral>" }, // test single word and full datatype /* 10 */ { "тест@ru", "тест", "ru", null }, // test single word and language /* 11 */ { "тест@ru-RU", "тест", "ru-RU", null }, // test single word and language /* 12 */ { "test@en^^rdf:XMLLiteral", "test", "en", "rdf:XMLLiteral" }, // test single word, language and datatype /* 13 */ { "test@en^^<" + RDF + "XMLLiteral>", "test", "en", "<" + RDF + "XMLLiteral>" }, // test single word, language and full datatype // Multiple words /* 14 */ { "some more", "some more", null, null }, // test multiple words string /* 15 */ { "test w 2^^rdf:XMLLiteral", "test w 2", null, "rdf:XMLLiteral" }, // test multiple words and datatype /* 16 */ { "test^^<" + OWL + "XMLLiteral>", "test", null, "<" + OWL + "XMLLiteral>" }, // test multiple words and full datatype /* 17 */ { "тест 2 3@ru", "тест 2 3", "ru", null }, // test multiple words and language /* 18 */ { "тест qwe@ru-RU", "тест qwe", "ru-RU", null }, // test multiple words and language /* 19 */ { "test@en^^rdf:XMLLiteral", "test", "en", "rdf:XMLLiteral" }, // test multiple words, language and datatype /* 20 */ { "test@en^^<" + XSD + "XMLLiteral>", "test", "en", "<" + XSD + "XMLLiteral>" }, // test multiple words, language and full datatype // Special characters /* 21 */ { "som\r\n\tmore", "som\r\n\tmore",null, null }, // test \r\n\t in literal /* 22 */ { "2^2^^owl:real", "2^2", null, "owl:real" }, // test ^ in literal /* 23 */ { "2^^2^^owl:real", "2^^2", null, "owl:real" }, // test ^^ in literal /* 24 */ { "2^^2@^^owl:real", "2^^2", "", "owl:real" }, // test ^^ and @ in literal /* 25 */ { "[email protected]@en^^xsd:real", "[email protected]","en", "xsd:real" }, // test @ in literal }); } // @formatter:on @Parameter(0) public String parameter; @Parameter(1) public String value; @Parameter(2) public String language; @Parameter(3) public String datatype; @Test public void anyEmptyLiteralShouldThrow() { System.out.println("[" + parameter + "]"); String[] splitted = Converter.splitDatatypeLiteral(parameter); Stream.of(splitted).forEach(s -> System.out.println(" [" + s + "]")); Assert.assertEquals(3, splitted.length); Assert.assertEquals(value, splitted[0]); Assert.assertEquals(language, splitted[1]); Assert.assertEquals(datatype, splitted[2]); } }
add java doc
tests/ru.agentlab.maia.agent.test/src/ru/agentlab/maia/agent/converter/ConverterSplitDatatypeLiteralTest.java
add java doc
<ide><path>ests/ru.agentlab.maia.agent.test/src/ru/agentlab/maia/agent/converter/ConverterSplitDatatypeLiteralTest.java <ide> import org.semanticweb.owlapi.vocab.Namespaces; <ide> <ide> /** <del> * Test method which split literal into 3 parts: <add> * Test method {@link Converter#splitDatatypeLiteral(String)} which split literal into 3 parts: <ide> * <ol> <ide> * <li>Literal value; <ide> * <li>Literal language; <ide> * <li>Literal datatype; <ide> * </ol> <add> * <p> <add> * Test cases: <add> * <!-- @formatter:off --> <add> * <table border="thin single black collapse"> <add> * <thead> <add> * <tr><th rowspan="2">## <th>Input <th colspan="3">Output <th rowspan="2">Comment <add> * <tr> <th>Parameter <th>Literal <th>Language<th>Datatype <add> * <thead> <add> * <tbody> <add> * <tr><td> 0 <td>"" <td>"" <td>null <td>null <td>test empty string <add> * <tr><td> 1 <td>"^^rdf:XMLLiteral" <td>"" <td>null <td>"rdf:XMLLiteral" <td>test only datatype <add> * <tr><td> 2 <td>"^^&lt;RDF#XMLLiteral&gt;" <td>"" <td>null <td>"&lt;RDF#XMLLiteral&gt;"<td>test only full datatype <add> * <tr><td> 3 <td>"@ru" <td>"" <td>"ru" <td>null <td>test only language <add> * <tr><td> 4 <td>"@ru-RU" <td>"" <td>"ru-RU" <td>null <td>test only language <add> * <tr><td> 5 <td>"@en^^rdf:XMLLiteral" <td>"" <td>"en" <td>"rdf:XMLLiteral" <td>test language and datatype <add> * <tr><td> 6 <td>"@en^^&lt;RDFS#Literal&gt;" <td>"" <td>"en" <td>"&lt;RDFS#Literal&gt;" <td>test language and full datatype <add> * <tr><td colspan="6"> <add> * <tr><td> 7 <td>"some" <td>"some" <td>null <td>null <td>test single word string <add> * <tr><td> 8 <td>"test^^rdf:XMLLiteral" <td>"test" <td>null <td>"rdf:XMLLiteral" <td>test single word and datatype <add> * <tr><td> 9 <td>"test^^&lt;RDF#XMLLiteral&gt;" <td>"test" <td>null <td>"&lt;RDF#XMLLiteral>" <td>test single word and full datatype <add> * <tr><td>10 <td>"тест@ru" <td>"тест" <td>"ru" <td>null <td>test single word and language <add> * <tr><td>11 <td>"тест@ru-RU" <td>"тест" <td>"ru-RU" <td>null <td>test single word and language <add> * <tr><td>12 <td>"test@en^^rdf:XMLLiteral" <td>"test" <td>"en" <td>"rdf:XMLLiteral" <td>test single word language and datatype <add> * <tr><td>13 <td>"test@en^^&lt;RDF#XMLLiteral&gt;"<td>"test" <td>"en" <td>"&lt;RDF#XMLLiteral&gt;"<td>test single word language and full datatype <add> * <tr><td colspan="6"> <add> * <tr><td>14 <td>"some more" <td>"some more" <td>null <td>null <td>test multiple words string <add> * <tr><td>15 <td>"test w 2^^rdf:XMLLiteral" <td>"test w 2" <td>null <td>"rdf:XMLLiteral" <td>test multiple words and datatype <add> * <tr><td>16 <td>"test^^&lt;OWL#XMLLiteral&gt;" <td>"test" <td>null <td>"&lt;OWL#XMLLiteral&gt;"<td>test multiple words and full datatype <add> * <tr><td>17 <td>"тест 2 3@ru" <td>"тест 2 3" <td>"ru" <td>null <td>test multiple words and language <add> * <tr><td>18 <td>"тест qwe@ru-RU" <td>"тест qwe" <td>"ru-RU" <td>null <td>test multiple words and language <add> * <tr><td>19 <td>"test@en^^rdf:XMLLiteral" <td>"test" <td>"en" <td>"rdf:XMLLiteral" <td>test multiple words language and datatype <add> * <tr><td>20 <td>"test@en^^&lt;XSD#XMLLiteral&gt;"<td>"test" <td>"en" <td>"&lt;XSD#XMLLiteral&gt;"<td>test multiple words language and full datatype <add> * <tr><td colspan="6"> <add> * <tr><td>21 <td>"som\r\n\tmore" <td>"som\r\n\tmore" <td>null <td>null <td>test \r\n\t in literal <add> * <tr><td>22 <td>"2^2^^owl:real" <td>"2^2" <td>null <td>"owl:real" <td>test ^ in literal <add> * <tr><td>23 <td>"2^^2^^owl:real" <td>"2^^2" <td>null <td>"owl:real" <td>test ^^ in literal <add> * <tr><td>24 <td>"2^^2@^^owl:real" <td>"2^^2" <td>"" <td>"owl:real" <td>test ^^ and @ in literal <add> * <tr><td>25 <td>"[email protected]@en^^xsd:real" <td>"[email protected]" <td>"en" <td>"xsd:real" <td>test @ in literal <add> * </tbody> <add> * </table> <add> * <!-- @formatter:on --> <add> * Used Namespaces: <add> * <ul> <add> * <li>RDF = http://www.w3.org/1999/02/22-rdf-syntax-ns# <add> * <li>RDFS = http://www.w3.org/2000/01/rdf-schema# <add> * <li>OWL = http://www.w3.org/2002/07/owl# <add> * <li>XSD = http://www.w3.org/2001/XMLSchema# <add> * </ul> <add> * <ide> * <ide> * @author Dmitriy Shishkin <[email protected]> <ide> */ <ide> @Parameters//(name="When parameter is [{0}] then result is [{1}]") <ide> public static Collection<Object[]> data() { <ide> return Arrays.asList(new Object[][] { <del> /* -------------------------------------------------------------------------------------------------------------------------------------------- <del> *| ## | Input Parameter | Literal | Language | Datatype | Comment | <del> *---------------------------------------------------------------------------------------------------------------------------------------------*/ <add> /* ------------------------------------------------------------------------------------------------------------------------------------- <add> *| ## | Input Parameter | Literal | Language | Datatype | Comment | <add> *--------------------------------------------------------------------------------------------------------------------------------------*/ <ide> // Empty word <del> /* 0 */ { "", "", null, null }, // test empty string <del> /* 1 */ { "^^rdf:XMLLiteral", "", null, "rdf:XMLLiteral" }, // test only datatype <del> /* 2 */ { "^^<" + RDF + "XMLLiteral>", "", null, "<" + RDF + "XMLLiteral>" }, // test only full datatype <del> /* 3 */ { "@ru", "", "ru", null }, // test only language <del> /* 4 */ { "@ru-RU", "", "ru-RU", null }, // test only language <del> /* 5 */ { "@en^^rdf:XMLLiteral", "", "en", "rdf:XMLLiteral" }, // test language and datatype <del> /* 6 */ { "@en^^<" + RDFS + "Literal>", "", "en", "<" + RDFS + "Literal>" }, // test language and full datatype <add> /* 0 */ { "", "", null, null }, // test empty string <add> /* 1 */ { "^^rdf:XMLLiteral", "", null, "rdf:XMLLiteral" }, // test only datatype <add> /* 2 */ { "^^<" + RDF + "XMLLiteral>", "", null, "<" + RDF + "XMLLiteral>" },// test only full datatype <add> /* 3 */ { "@ru", "", "ru", null }, // test only language <add> /* 4 */ { "@ru-RU", "", "ru-RU", null }, // test only language <add> /* 5 */ { "@en^^rdf:XMLLiteral", "", "en", "rdf:XMLLiteral" }, // test language and datatype <add> /* 6 */ { "@en^^<" + RDFS + "Literal>", "", "en", "<" + RDFS + "Literal>" }, // test language and full datatype <ide> // Single word <del> /* 7 */ { "some", "some", null, null }, // test single word string <del> /* 8 */ { "test^^rdf:XMLLiteral", "test", null, "rdf:XMLLiteral" }, // test single word and datatype <del> /* 9 */ { "test^^<" + RDF + "XMLLiteral>", "test", null, "<" + RDF + "XMLLiteral>" }, // test single word and full datatype <del> /* 10 */ { "тест@ru", "тест", "ru", null }, // test single word and language <del> /* 11 */ { "тест@ru-RU", "тест", "ru-RU", null }, // test single word and language <del> /* 12 */ { "test@en^^rdf:XMLLiteral", "test", "en", "rdf:XMLLiteral" }, // test single word, language and datatype <del> /* 13 */ { "test@en^^<" + RDF + "XMLLiteral>", "test", "en", "<" + RDF + "XMLLiteral>" }, // test single word, language and full datatype <add> /* 7 */ { "some", "some", null, null }, // test single word string <add> /* 8 */ { "test^^rdf:XMLLiteral", "test", null, "rdf:XMLLiteral" }, // test single word and datatype <add> /* 9 */ { "test^^<" + RDF + "XMLLiteral>", "test", null, "<" + RDF + "XMLLiteral>" },// test single word and full datatype <add> /* 10 */ { "тест@ru", "тест", "ru", null }, // test single word and language <add> /* 11 */ { "тест@ru-RU", "тест", "ru-RU", null }, // test single word and language <add> /* 12 */ { "test@en^^rdf:XMLLiteral", "test", "en", "rdf:XMLLiteral" }, // test single word, language and datatype <add> /* 13 */ { "test@en^^<" + RDF + "XMLLiteral>", "test", "en", "<" + RDF + "XMLLiteral>" },// test single word, language and full datatype <ide> // Multiple words <del> /* 14 */ { "some more", "some more", null, null }, // test multiple words string <del> /* 15 */ { "test w 2^^rdf:XMLLiteral", "test w 2", null, "rdf:XMLLiteral" }, // test multiple words and datatype <del> /* 16 */ { "test^^<" + OWL + "XMLLiteral>", "test", null, "<" + OWL + "XMLLiteral>" }, // test multiple words and full datatype <del> /* 17 */ { "тест 2 3@ru", "тест 2 3", "ru", null }, // test multiple words and language <del> /* 18 */ { "тест qwe@ru-RU", "тест qwe", "ru-RU", null }, // test multiple words and language <del> /* 19 */ { "test@en^^rdf:XMLLiteral", "test", "en", "rdf:XMLLiteral" }, // test multiple words, language and datatype <del> /* 20 */ { "test@en^^<" + XSD + "XMLLiteral>", "test", "en", "<" + XSD + "XMLLiteral>" }, // test multiple words, language and full datatype <add> /* 14 */ { "some more", "some more", null, null }, // test multiple words string <add> /* 15 */ { "test w 2^^rdf:XMLLiteral", "test w 2", null, "rdf:XMLLiteral" }, // test multiple words and datatype <add> /* 16 */ { "test^^<" + OWL + "XMLLiteral>", "test", null, "<" + OWL + "XMLLiteral>" },// test multiple words and full datatype <add> /* 17 */ { "тест 2 3@ru", "тест 2 3", "ru", null }, // test multiple words and language <add> /* 18 */ { "тест qwe@ru-RU", "тест qwe", "ru-RU", null }, // test multiple words and language <add> /* 19 */ { "test@en^^rdf:XMLLiteral", "test", "en", "rdf:XMLLiteral" }, // test multiple words, language and datatype <add> /* 20 */ { "test@en^^<" + XSD + "XMLLiteral>", "test", "en", "<" + XSD + "XMLLiteral>" },// test multiple words, language and full datatype <ide> // Special characters <del> /* 21 */ { "som\r\n\tmore", "som\r\n\tmore",null, null }, // test \r\n\t in literal <del> /* 22 */ { "2^2^^owl:real", "2^2", null, "owl:real" }, // test ^ in literal <del> /* 23 */ { "2^^2^^owl:real", "2^^2", null, "owl:real" }, // test ^^ in literal <del> /* 24 */ { "2^^2@^^owl:real", "2^^2", "", "owl:real" }, // test ^^ and @ in literal <del> /* 25 */ { "[email protected]@en^^xsd:real", "[email protected]","en", "xsd:real" }, // test @ in literal <add> /* 21 */ { "som\r\n\tmore", "som\r\n\tmore",null, null }, // test \r\n\t in literal <add> /* 22 */ { "2^2^^owl:real", "2^2", null, "owl:real" }, // test ^ in literal <add> /* 23 */ { "2^^2^^owl:real", "2^^2", null, "owl:real" }, // test ^^ in literal <add> /* 24 */ { "2^^2@^^owl:real", "2^^2", "", "owl:real" }, // test ^^ and @ in literal <add> /* 25 */ { "[email protected]@en^^xsd:real", "[email protected]","en", "xsd:real" }, // test @ in literal <ide> }); <ide> } <ide> // @formatter:on
Java
apache-2.0
e21b1861dc02d58fd4e86bc8361227275ed3043a
0
novoda/download-manager,xufeifandj/download-manager
package com.novoda.downloadmanager.lib; import android.content.ContentValues; import android.content.Context; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.support.annotation.NonNull; import com.novoda.notils.logger.simple.Log; /** * Creates and updated database on demand when opening it. * Helper class to create database the first time the provider is * initialized and upgrade it when a new version of the provider needs * an updated version of the database. */ final class DatabaseHelper extends SQLiteOpenHelper { /** * Current database version */ private static final int DB_VERSION = 1; public DatabaseHelper(Context context, String dbName) { super(context, dbName, null, DB_VERSION); } /** * Creates database the first time we try to open it. */ @Override public void onCreate(@NonNull SQLiteDatabase db) { Log.v("populating new database"); createDownloadsTable(db); createHeadersTable(db); createBatchesTable(db); createDownloadsByBatchView(db); makeCacheDownloadsInvisible(db); } /** * Updates the database format when a content provider is used * with a database that was created with a different format. * <p/> * Note: to support downgrades, creating a table should always drop it first if it already * exists. */ @Override public void onUpgrade(@NonNull SQLiteDatabase db, int oldVersion, final int newVersion) { // no upgrade path yet } /** * Creates the table that'll hold the download information. */ private void createDownloadsTable(SQLiteDatabase db) { try { db.execSQL("DROP TABLE IF EXISTS " + DownloadContract.Downloads.DOWNLOADS_TABLE_NAME); db.execSQL( "CREATE TABLE " + DownloadContract.Downloads.DOWNLOADS_TABLE_NAME + "(" + DownloadContract.Downloads._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + DownloadContract.Downloads.COLUMN_URI + " TEXT, " + Constants.RETRY_AFTER_X_REDIRECT_COUNT + " INTEGER, " + DownloadContract.Downloads.COLUMN_APP_DATA + " TEXT, " + DownloadContract.Downloads.COLUMN_NO_INTEGRITY + " BOOLEAN, " + DownloadContract.Downloads.COLUMN_FILE_NAME_HINT + " TEXT, " + DownloadContract.Downloads.COLUMN_DATA + " TEXT, " + DownloadContract.Downloads.COLUMN_MIME_TYPE + " TEXT, " + DownloadContract.Downloads.COLUMN_DESTINATION + " INTEGER, " + Constants.NO_SYSTEM_FILES + " BOOLEAN, " + DownloadContract.Downloads.COLUMN_CONTROL + " INTEGER, " + DownloadContract.Downloads.COLUMN_STATUS + " INTEGER, " + DownloadContract.Downloads.COLUMN_FAILED_CONNECTIONS + " INTEGER, " + DownloadContract.Downloads.COLUMN_LAST_MODIFICATION + " BIGINT, " + DownloadContract.Downloads.COLUMN_NOTIFICATION_CLASS + " TEXT, " + DownloadContract.Downloads.COLUMN_NOTIFICATION_EXTRAS + " TEXT, " + DownloadContract.Downloads.COLUMN_COOKIE_DATA + " TEXT, " + DownloadContract.Downloads.COLUMN_USER_AGENT + " TEXT, " + DownloadContract.Downloads.COLUMN_REFERER + " TEXT, " + DownloadContract.Downloads.COLUMN_TOTAL_BYTES + " INTEGER NOT NULL DEFAULT -1, " + DownloadContract.Downloads.COLUMN_CURRENT_BYTES + " INTEGER NOT NULL DEFAULT 0, " + Constants.ETAG + " TEXT, " + Constants.UID + " INTEGER, " + DownloadContract.Downloads.COLUMN_OTHER_UID + " INTEGER, " + DownloadContract.Downloads.COLUMN_ALLOW_ROAMING + " INTEGER NOT NULL DEFAULT 0, " + DownloadContract.Downloads.COLUMN_ALLOWED_NETWORK_TYPES + " INTEGER NOT NULL DEFAULT 0, " + DownloadContract.Downloads.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI + " INTEGER NOT NULL DEFAULT 1, " + DownloadContract.Downloads.COLUMN_BYPASS_RECOMMENDED_SIZE_LIMIT + " INTEGER NOT NULL DEFAULT 0, " + DownloadContract.Downloads.COLUMN_MEDIAPROVIDER_URI + " TEXT, " + DownloadContract.Downloads.COLUMN_DELETED + " BOOLEAN NOT NULL DEFAULT 0, " + DownloadContract.Downloads.COLUMN_ERROR_MSG + " TEXT, " + DownloadContract.Downloads.COLUMN_ALLOW_METERED + " INTEGER NOT NULL DEFAULT 1, " + DownloadContract.Downloads.COLUMN_BATCH_ID + " INTEGER, " + Constants.MEDIA_SCANNED + " BOOLEAN);"); } catch (SQLException ex) { Log.e("couldn't create table in downloads database"); throw ex; } } /** * Set all existing downloads to the cache partition to be invisible in the downloads UI. */ private void makeCacheDownloadsInvisible(SQLiteDatabase db) { ContentValues values = new ContentValues(); values.put(DownloadContract.Downloads.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, false); String cacheSelection = DownloadContract.Downloads.COLUMN_DESTINATION + " != " + DownloadsDestination.DESTINATION_EXTERNAL; db.update(DownloadContract.Downloads.DOWNLOADS_TABLE_NAME, values, cacheSelection, null); } private void createHeadersTable(SQLiteDatabase db) { db.execSQL("DROP TABLE IF EXISTS " + DownloadContract.RequestHeaders.HEADERS_DB_TABLE); db.execSQL( "CREATE TABLE " + DownloadContract.RequestHeaders.HEADERS_DB_TABLE + "(" + DownloadContract.RequestHeaders._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + DownloadContract.RequestHeaders.COLUMN_DOWNLOAD_ID + " INTEGER NOT NULL," + DownloadContract.RequestHeaders.COLUMN_HEADER + " TEXT NOT NULL," + DownloadContract.RequestHeaders.COLUMN_VALUE + " TEXT NOT NULL" + ");"); } private void createBatchesTable(SQLiteDatabase db) { db.execSQL("DROP TABLE IF EXISTS " + DownloadContract.Batches.BATCHES_TABLE_NAME); db.execSQL( "CREATE TABLE " + DownloadContract.Batches.BATCHES_TABLE_NAME + "(" + DownloadContract.Batches._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + DownloadContract.Batches.COLUMN_TITLE + " TEXT NOT NULL," + DownloadContract.Batches.COLUMN_DESCRIPTION + " TEXT," + DownloadContract.Batches.COLUMN_BIG_PICTURE + " TEXT," + DownloadContract.Batches.COLUMN_STATUS + " INTEGER," + DownloadContract.Batches.COLUMN_VISIBILITY + " INTEGER," + DownloadContract.Batches.COLUMN_DELETED + " BOOLEAN NOT NULL DEFAULT 0, " + DownloadContract.Batches.COLUMN_TOTAL_BYTES + " INTEGER NOT NULL DEFAULT -1, " + DownloadContract.Batches.COLUMN_CURRENT_BYTES + " INTEGER NOT NULL DEFAULT 0 " + ");"); } private void createDownloadsByBatchView(SQLiteDatabase db) { db.execSQL("DROP VIEW IF EXISTS " + DownloadContract.DownloadsByBatch.VIEW_NAME_DOWNLOADS_BY_BATCH); db.execSQL("CREATE VIEW " + DownloadContract.DownloadsByBatch.VIEW_NAME_DOWNLOADS_BY_BATCH + " AS SELECT DISTINCT " + projectionFrom(DOWNLOAD_BY_BATCH_VIEW_COLUMNS) + " FROM " + DownloadContract.Downloads.DOWNLOADS_TABLE_NAME + " INNER JOIN " + DownloadContract.Batches.BATCHES_TABLE_NAME + " ON " + DownloadContract.Downloads.DOWNLOADS_TABLE_NAME + "." + DownloadContract.Downloads.COLUMN_BATCH_ID + " = " + DownloadContract.Batches.BATCHES_TABLE_NAME + "." + DownloadContract.Batches._ID + ";" ); } /** * columns to request from DownloadProvider. */ public static final String[] DOWNLOAD_BY_BATCH_VIEW_COLUMNS = new String[]{ DownloadContract.Downloads.DOWNLOADS_TABLE_NAME + "." + DownloadContract.Downloads._ID + " AS _id ", DownloadContract.Downloads.COLUMN_DATA, DownloadContract.Downloads.COLUMN_MEDIAPROVIDER_URI, DownloadContract.Downloads.COLUMN_DESTINATION, DownloadContract.Downloads.COLUMN_URI, DownloadContract.Downloads.COLUMN_STATUS, DownloadContract.Downloads.DOWNLOADS_TABLE_NAME + "." + DownloadContract.Downloads.COLUMN_DELETED, DownloadContract.Downloads.COLUMN_FILE_NAME_HINT, DownloadContract.Downloads.COLUMN_MIME_TYPE, DownloadContract.Downloads.COLUMN_TOTAL_BYTES, DownloadContract.Downloads.COLUMN_LAST_MODIFICATION, DownloadContract.Downloads.COLUMN_CURRENT_BYTES, DownloadContract.Downloads.COLUMN_NOTIFICATION_EXTRAS, DownloadContract.Downloads.COLUMN_BATCH_ID, DownloadContract.Batches.COLUMN_TITLE, DownloadContract.Batches.COLUMN_DESCRIPTION, DownloadContract.Batches.COLUMN_BIG_PICTURE, DownloadContract.Batches.COLUMN_VISIBILITY, DownloadContract.Batches.COLUMN_STATUS, DownloadContract.Batches.BATCHES_TABLE_NAME + "." + DownloadContract.Batches.COLUMN_DELETED, DownloadContract.Batches.COLUMN_TOTAL_BYTES, DownloadContract.Batches.COLUMN_CURRENT_BYTES }; private String projectionFrom(String[] array) { if (array == null) { return "null"; } if (array.length == 0) { return "[]"; } StringBuilder sb = new StringBuilder(array.length * 7); sb.append(array[0]); for (int i = 1; i < array.length; i++) { sb.append(", "); sb.append(array[i]); } return sb.toString(); } }
library/src/main/java/com/novoda/downloadmanager/lib/DatabaseHelper.java
package com.novoda.downloadmanager.lib; import android.content.ContentValues; import android.content.Context; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.support.annotation.NonNull; import com.novoda.notils.logger.simple.Log; /** * Creates and updated database on demand when opening it. * Helper class to create database the first time the provider is * initialized and upgrade it when a new version of the provider needs * an updated version of the database. */ final class DatabaseHelper extends SQLiteOpenHelper { /** * Current database version */ private static final int DB_VERSION = 1; public DatabaseHelper(Context context, String dbName) { super(context, dbName, null, DB_VERSION); } /** * Creates database the first time we try to open it. */ @Override public void onCreate(@NonNull SQLiteDatabase db) { Log.v("populating new database"); createDownloadsTable(db); createHeadersTable(db); createBatchesTable(db); createDownloadsByBatchView(db); makeCacheDownloadsInvisible(db); } /** * Updates the database format when a content provider is used * with a database that was created with a different format. * <p/> * Note: to support downgrades, creating a table should always drop it first if it already * exists. */ @Override public void onUpgrade(@NonNull SQLiteDatabase db, int oldVersion, final int newVersion) { // no upgrade path yet } /** * Creates the table that'll hold the download information. */ private void createDownloadsTable(SQLiteDatabase db) { try { db.execSQL("DROP TABLE IF EXISTS " + DownloadContract.Downloads.DOWNLOADS_TABLE_NAME); db.execSQL("CREATE TABLE " + DownloadContract.Downloads.DOWNLOADS_TABLE_NAME + "(" + DownloadContract.Downloads._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + DownloadContract.Downloads.COLUMN_URI + " TEXT, " + Constants.RETRY_AFTER_X_REDIRECT_COUNT + " INTEGER, " + DownloadContract.Downloads.COLUMN_APP_DATA + " TEXT, " + DownloadContract.Downloads.COLUMN_NO_INTEGRITY + " BOOLEAN, " + DownloadContract.Downloads.COLUMN_FILE_NAME_HINT + " TEXT, " + DownloadContract.Downloads.COLUMN_DATA + " TEXT, " + DownloadContract.Downloads.COLUMN_MIME_TYPE + " TEXT, " + DownloadContract.Downloads.COLUMN_DESTINATION + " INTEGER, " + Constants.NO_SYSTEM_FILES + " BOOLEAN, " + DownloadContract.Downloads.COLUMN_CONTROL + " INTEGER, " + DownloadContract.Downloads.COLUMN_STATUS + " INTEGER, " + DownloadContract.Downloads.COLUMN_FAILED_CONNECTIONS + " INTEGER, " + DownloadContract.Downloads.COLUMN_LAST_MODIFICATION + " BIGINT, " + DownloadContract.Downloads.COLUMN_NOTIFICATION_CLASS + " TEXT, " + DownloadContract.Downloads.COLUMN_NOTIFICATION_EXTRAS + " TEXT, " + DownloadContract.Downloads.COLUMN_COOKIE_DATA + " TEXT, " + DownloadContract.Downloads.COLUMN_USER_AGENT + " TEXT, " + DownloadContract.Downloads.COLUMN_REFERER + " TEXT, " + DownloadContract.Downloads.COLUMN_TOTAL_BYTES + " INTEGER NOT NULL DEFAULT -1, " + DownloadContract.Downloads.COLUMN_CURRENT_BYTES + " INTEGER NOT NULL DEFAULT 0, " + Constants.ETAG + " TEXT, " + Constants.UID + " INTEGER, " + DownloadContract.Downloads.COLUMN_OTHER_UID + " INTEGER, " + DownloadContract.Downloads.COLUMN_ALLOW_ROAMING + " INTEGER NOT NULL DEFAULT 0, " + DownloadContract.Downloads.COLUMN_ALLOWED_NETWORK_TYPES + " INTEGER NOT NULL DEFAULT 0, " + DownloadContract.Downloads.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI + " INTEGER NOT NULL DEFAULT 1, " + DownloadContract.Downloads.COLUMN_BYPASS_RECOMMENDED_SIZE_LIMIT + " INTEGER NOT NULL DEFAULT 0, " + DownloadContract.Downloads.COLUMN_MEDIAPROVIDER_URI + " TEXT, " + DownloadContract.Downloads.COLUMN_DELETED + " BOOLEAN NOT NULL DEFAULT 0, " + DownloadContract.Downloads.COLUMN_ERROR_MSG + " TEXT, " + DownloadContract.Downloads.COLUMN_ALLOW_METERED + " INTEGER NOT NULL DEFAULT 1, " + DownloadContract.Downloads.COLUMN_BATCH_ID + " INTEGER, " + Constants.MEDIA_SCANNED + " BOOLEAN);"); } catch (SQLException ex) { Log.e("couldn't create table in downloads database"); throw ex; } } /** * Set all existing downloads to the cache partition to be invisible in the downloads UI. */ private void makeCacheDownloadsInvisible(SQLiteDatabase db) { ContentValues values = new ContentValues(); values.put(DownloadContract.Downloads.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, false); String cacheSelection = DownloadContract.Downloads.COLUMN_DESTINATION + " != " + DownloadsDestination.DESTINATION_EXTERNAL; db.update(DownloadContract.Downloads.DOWNLOADS_TABLE_NAME, values, cacheSelection, null); } private void createHeadersTable(SQLiteDatabase db) { db.execSQL("DROP TABLE IF EXISTS " + DownloadContract.RequestHeaders.HEADERS_DB_TABLE); db.execSQL( "CREATE TABLE " + DownloadContract.RequestHeaders.HEADERS_DB_TABLE + "(" + DownloadContract.RequestHeaders._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + DownloadContract.RequestHeaders.COLUMN_DOWNLOAD_ID + " INTEGER NOT NULL," + DownloadContract.RequestHeaders.COLUMN_HEADER + " TEXT NOT NULL," + DownloadContract.RequestHeaders.COLUMN_VALUE + " TEXT NOT NULL" + ");"); } private void createBatchesTable(SQLiteDatabase db) { db.execSQL("DROP TABLE IF EXISTS " + DownloadContract.Batches.BATCHES_TABLE_NAME); db.execSQL( "CREATE TABLE " + DownloadContract.Batches.BATCHES_TABLE_NAME + "(" + DownloadContract.Batches._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + DownloadContract.Batches.COLUMN_TITLE + " TEXT NOT NULL," + DownloadContract.Batches.COLUMN_DESCRIPTION + " TEXT," + DownloadContract.Batches.COLUMN_BIG_PICTURE + " TEXT," + DownloadContract.Batches.COLUMN_STATUS + " INTEGER," + DownloadContract.Batches.COLUMN_VISIBILITY + " INTEGER," + DownloadContract.Batches.COLUMN_DELETED + " BOOLEAN NOT NULL DEFAULT 0, " + DownloadContract.Batches.COLUMN_TOTAL_BYTES + " INTEGER NOT NULL DEFAULT -1, " + DownloadContract.Batches.COLUMN_CURRENT_BYTES + " INTEGER NOT NULL DEFAULT 0 " + ");"); } private void createDownloadsByBatchView(SQLiteDatabase db) { db.execSQL("DROP VIEW IF EXISTS " + DownloadContract.DownloadsByBatch.VIEW_NAME_DOWNLOADS_BY_BATCH); db.execSQL("CREATE VIEW " + DownloadContract.DownloadsByBatch.VIEW_NAME_DOWNLOADS_BY_BATCH + " AS SELECT DISTINCT " + projectionFrom(DOWNLOAD_BY_BATCH_VIEW_COLUMNS) + " FROM " + DownloadContract.Downloads.DOWNLOADS_TABLE_NAME + " INNER JOIN " + DownloadContract.Batches.BATCHES_TABLE_NAME + " ON " + DownloadContract.Downloads.DOWNLOADS_TABLE_NAME + "." + DownloadContract.Downloads.COLUMN_BATCH_ID + " = " + DownloadContract.Batches.BATCHES_TABLE_NAME + "." + DownloadContract.Batches._ID + ";" ); } /** * columns to request from DownloadProvider. */ public static final String[] DOWNLOAD_BY_BATCH_VIEW_COLUMNS = new String[]{ DownloadContract.Downloads.DOWNLOADS_TABLE_NAME + "." + DownloadContract.Downloads._ID + " AS _id ", DownloadContract.Downloads.COLUMN_DATA, DownloadContract.Downloads.COLUMN_MEDIAPROVIDER_URI, DownloadContract.Downloads.COLUMN_DESTINATION, DownloadContract.Downloads.COLUMN_URI, DownloadContract.Downloads.COLUMN_STATUS, DownloadContract.Downloads.DOWNLOADS_TABLE_NAME + "." + DownloadContract.Downloads.COLUMN_DELETED, DownloadContract.Downloads.COLUMN_FILE_NAME_HINT, DownloadContract.Downloads.COLUMN_MIME_TYPE, DownloadContract.Downloads.COLUMN_TOTAL_BYTES, DownloadContract.Downloads.COLUMN_LAST_MODIFICATION, DownloadContract.Downloads.COLUMN_CURRENT_BYTES, DownloadContract.Downloads.COLUMN_NOTIFICATION_EXTRAS, DownloadContract.Downloads.COLUMN_BATCH_ID, DownloadContract.Batches.COLUMN_TITLE, DownloadContract.Batches.COLUMN_DESCRIPTION, DownloadContract.Batches.COLUMN_BIG_PICTURE, DownloadContract.Batches.COLUMN_VISIBILITY, DownloadContract.Batches.COLUMN_STATUS, DownloadContract.Batches.BATCHES_TABLE_NAME + "." + DownloadContract.Batches.COLUMN_DELETED, DownloadContract.Batches.COLUMN_TOTAL_BYTES, DownloadContract.Batches.COLUMN_CURRENT_BYTES }; private String projectionFrom(String[] array) { if (array == null) { return "null"; } if (array.length == 0) { return "[]"; } StringBuilder sb = new StringBuilder(array.length * 7); sb.append(array[0]); for (int i = 1; i < array.length; i++) { sb.append(", "); sb.append(array[i]); } return sb.toString(); } }
formatating
library/src/main/java/com/novoda/downloadmanager/lib/DatabaseHelper.java
formatating
<ide><path>ibrary/src/main/java/com/novoda/downloadmanager/lib/DatabaseHelper.java <ide> private void createDownloadsTable(SQLiteDatabase db) { <ide> try { <ide> db.execSQL("DROP TABLE IF EXISTS " + DownloadContract.Downloads.DOWNLOADS_TABLE_NAME); <del> db.execSQL("CREATE TABLE " + DownloadContract.Downloads.DOWNLOADS_TABLE_NAME + "(" + <del> DownloadContract.Downloads._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + <del> DownloadContract.Downloads.COLUMN_URI + " TEXT, " + <del> Constants.RETRY_AFTER_X_REDIRECT_COUNT + " INTEGER, " + <del> DownloadContract.Downloads.COLUMN_APP_DATA + " TEXT, " + <del> DownloadContract.Downloads.COLUMN_NO_INTEGRITY + " BOOLEAN, " + <del> DownloadContract.Downloads.COLUMN_FILE_NAME_HINT + " TEXT, " + <del> DownloadContract.Downloads.COLUMN_DATA + " TEXT, " + <del> DownloadContract.Downloads.COLUMN_MIME_TYPE + " TEXT, " + <del> DownloadContract.Downloads.COLUMN_DESTINATION + " INTEGER, " + <del> Constants.NO_SYSTEM_FILES + " BOOLEAN, " + <del> DownloadContract.Downloads.COLUMN_CONTROL + " INTEGER, " + <del> DownloadContract.Downloads.COLUMN_STATUS + " INTEGER, " + <del> DownloadContract.Downloads.COLUMN_FAILED_CONNECTIONS + " INTEGER, " + <del> DownloadContract.Downloads.COLUMN_LAST_MODIFICATION + " BIGINT, " + <del> DownloadContract.Downloads.COLUMN_NOTIFICATION_CLASS + " TEXT, " + <del> DownloadContract.Downloads.COLUMN_NOTIFICATION_EXTRAS + " TEXT, " + <del> DownloadContract.Downloads.COLUMN_COOKIE_DATA + " TEXT, " + <del> DownloadContract.Downloads.COLUMN_USER_AGENT + " TEXT, " + <del> DownloadContract.Downloads.COLUMN_REFERER + " TEXT, " + <del> DownloadContract.Downloads.COLUMN_TOTAL_BYTES + " INTEGER NOT NULL DEFAULT -1, " + <del> DownloadContract.Downloads.COLUMN_CURRENT_BYTES + " INTEGER NOT NULL DEFAULT 0, " + <del> Constants.ETAG + " TEXT, " + <del> Constants.UID + " INTEGER, " + <del> DownloadContract.Downloads.COLUMN_OTHER_UID + " INTEGER, " + <del> DownloadContract.Downloads.COLUMN_ALLOW_ROAMING + " INTEGER NOT NULL DEFAULT 0, " + <del> DownloadContract.Downloads.COLUMN_ALLOWED_NETWORK_TYPES + " INTEGER NOT NULL DEFAULT 0, " + <del> DownloadContract.Downloads.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI + " INTEGER NOT NULL DEFAULT 1, " + <del> DownloadContract.Downloads.COLUMN_BYPASS_RECOMMENDED_SIZE_LIMIT + " INTEGER NOT NULL DEFAULT 0, " + <del> DownloadContract.Downloads.COLUMN_MEDIAPROVIDER_URI + " TEXT, " + <del> DownloadContract.Downloads.COLUMN_DELETED + " BOOLEAN NOT NULL DEFAULT 0, " + <del> DownloadContract.Downloads.COLUMN_ERROR_MSG + " TEXT, " + <del> DownloadContract.Downloads.COLUMN_ALLOW_METERED + " INTEGER NOT NULL DEFAULT 1, " + <del> DownloadContract.Downloads.COLUMN_BATCH_ID + " INTEGER, " + <del> Constants.MEDIA_SCANNED + " BOOLEAN);"); <add> db.execSQL( <add> "CREATE TABLE " + DownloadContract.Downloads.DOWNLOADS_TABLE_NAME + "(" + <add> DownloadContract.Downloads._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + <add> DownloadContract.Downloads.COLUMN_URI + " TEXT, " + <add> Constants.RETRY_AFTER_X_REDIRECT_COUNT + " INTEGER, " + <add> DownloadContract.Downloads.COLUMN_APP_DATA + " TEXT, " + <add> DownloadContract.Downloads.COLUMN_NO_INTEGRITY + " BOOLEAN, " + <add> DownloadContract.Downloads.COLUMN_FILE_NAME_HINT + " TEXT, " + <add> DownloadContract.Downloads.COLUMN_DATA + " TEXT, " + <add> DownloadContract.Downloads.COLUMN_MIME_TYPE + " TEXT, " + <add> DownloadContract.Downloads.COLUMN_DESTINATION + " INTEGER, " + <add> Constants.NO_SYSTEM_FILES + " BOOLEAN, " + <add> DownloadContract.Downloads.COLUMN_CONTROL + " INTEGER, " + <add> DownloadContract.Downloads.COLUMN_STATUS + " INTEGER, " + <add> DownloadContract.Downloads.COLUMN_FAILED_CONNECTIONS + " INTEGER, " + <add> DownloadContract.Downloads.COLUMN_LAST_MODIFICATION + " BIGINT, " + <add> DownloadContract.Downloads.COLUMN_NOTIFICATION_CLASS + " TEXT, " + <add> DownloadContract.Downloads.COLUMN_NOTIFICATION_EXTRAS + " TEXT, " + <add> DownloadContract.Downloads.COLUMN_COOKIE_DATA + " TEXT, " + <add> DownloadContract.Downloads.COLUMN_USER_AGENT + " TEXT, " + <add> DownloadContract.Downloads.COLUMN_REFERER + " TEXT, " + <add> DownloadContract.Downloads.COLUMN_TOTAL_BYTES + " INTEGER NOT NULL DEFAULT -1, " + <add> DownloadContract.Downloads.COLUMN_CURRENT_BYTES + " INTEGER NOT NULL DEFAULT 0, " + <add> Constants.ETAG + " TEXT, " + <add> Constants.UID + " INTEGER, " + <add> DownloadContract.Downloads.COLUMN_OTHER_UID + " INTEGER, " + <add> DownloadContract.Downloads.COLUMN_ALLOW_ROAMING + " INTEGER NOT NULL DEFAULT 0, " + <add> DownloadContract.Downloads.COLUMN_ALLOWED_NETWORK_TYPES + " INTEGER NOT NULL DEFAULT 0, " + <add> DownloadContract.Downloads.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI + " INTEGER NOT NULL DEFAULT 1, " + <add> DownloadContract.Downloads.COLUMN_BYPASS_RECOMMENDED_SIZE_LIMIT + " INTEGER NOT NULL DEFAULT 0, " + <add> DownloadContract.Downloads.COLUMN_MEDIAPROVIDER_URI + " TEXT, " + <add> DownloadContract.Downloads.COLUMN_DELETED + " BOOLEAN NOT NULL DEFAULT 0, " + <add> DownloadContract.Downloads.COLUMN_ERROR_MSG + " TEXT, " + <add> DownloadContract.Downloads.COLUMN_ALLOW_METERED + " INTEGER NOT NULL DEFAULT 1, " + <add> DownloadContract.Downloads.COLUMN_BATCH_ID + " INTEGER, " + <add> Constants.MEDIA_SCANNED + " BOOLEAN);"); <ide> } catch (SQLException ex) { <ide> Log.e("couldn't create table in downloads database"); <ide> throw ex;
Java
bsd-3-clause
dc864456dd9db9d5d1d8333bf99ecc4899d232fe
0
firebase/flutterfire,firebase/flutterfire,firebase/flutterfire,firebase/flutterfire,firebase/flutterfire,firebase/flutterfire,firebase/flutterfire,firebase/flutterfire,firebase/flutterfire,firebase/flutterfire
// Copyright 2019 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. package io.flutter.plugins.firebasedynamiclinks; import android.app.Activity; import android.content.Intent; import android.net.Uri; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.dynamiclinks.DynamicLink; import com.google.firebase.dynamiclinks.FirebaseDynamicLinks; import com.google.firebase.dynamiclinks.PendingDynamicLinkData; import com.google.firebase.dynamiclinks.ShortDynamicLink; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.Result; import io.flutter.plugin.common.PluginRegistry.NewIntentListener; import io.flutter.plugin.common.PluginRegistry.Registrar; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Flutter plugin accessing for Firebase Dynamic Links API. * * <p>Instantiate this in an add to app scenario to gracefully handle activity and context changes. */ public class FirebaseDynamicLinksPlugin implements FlutterPlugin, ActivityAware, MethodCallHandler, NewIntentListener { private Activity activity; private MethodChannel channel; private FirebaseDynamicLinksPlugin(Activity activity, MethodChannel channel) { this.activity = activity; this.channel = channel; } /** * Default Constructor. * * <p>Use this when adding the plugin to your FlutterEngine */ public FirebaseDynamicLinksPlugin() {} /** * Registers a plugin with the v1 embedding api {@code io.flutter.plugin.common}. * * <p>Calling this will register the plugin with the passed registrar. However, plugins * initialized this way won't react to changes in activity or context. * * @param registrar attaches this plugin's {@link * io.flutter.plugin.common.MethodChannel.MethodCallHandler} to the registrar's {@link * io.flutter.plugin.common.BinaryMessenger}. */ public static void registerWith(Registrar registrar) { final MethodChannel channel = createChannel(registrar.messenger()); final FirebaseDynamicLinksPlugin plugin = new FirebaseDynamicLinksPlugin(registrar.activity(), channel); registrar.addNewIntentListener(plugin); channel.setMethodCallHandler(plugin); } private static MethodChannel createChannel(final BinaryMessenger messenger) { return new MethodChannel(messenger, "plugins.flutter.io/firebase_dynamic_links"); } @Override public boolean onNewIntent(Intent intent) { FirebaseDynamicLinks.getInstance() .getDynamicLink(intent) .addOnSuccessListener( new OnSuccessListener<PendingDynamicLinkData>() { @Override public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) { if (pendingDynamicLinkData != null) { Map<String, Object> dynamicLink = getMapFromPendingDynamicLinkData(pendingDynamicLinkData); channel.invokeMethod("onLinkSuccess", dynamicLink); } } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(Exception e) { Map<String, Object> exception = new HashMap<>(); exception.put("code", e.getClass().getSimpleName()); exception.put("message", e.getMessage()); exception.put("details", null); channel.invokeMethod("onLinkError", exception); } }); return false; } @Override public void onAttachedToEngine(FlutterPluginBinding binding) { channel = createChannel(binding.getBinaryMessenger()); channel.setMethodCallHandler(this); } @Override public void onDetachedFromEngine(FlutterPluginBinding binding) { channel.setMethodCallHandler(null); } @Override public void onAttachedToActivity(ActivityPluginBinding binding) { activity = binding.getActivity(); binding.addOnNewIntentListener(this); } @Override public void onDetachedFromActivityForConfigChanges() { activity = null; } @Override public void onReattachedToActivityForConfigChanges(ActivityPluginBinding binding) { activity = binding.getActivity(); binding.addOnNewIntentListener(this); } @Override public void onDetachedFromActivity() { activity = null; } @Override public void onMethodCall(MethodCall call, Result result) { switch (call.method) { case "DynamicLinkParameters#buildUrl": DynamicLink.Builder urlBuilder = setupParameters(call); result.success(urlBuilder.buildDynamicLink().getUri().toString()); break; case "DynamicLinkParameters#buildShortLink": DynamicLink.Builder shortLinkBuilder = setupParameters(call); buildShortDynamicLink(shortLinkBuilder, call, createShortLinkListener(result)); break; case "DynamicLinkParameters#shortenUrl": DynamicLink.Builder builder = FirebaseDynamicLinks.getInstance().createDynamicLink(); Uri url = Uri.parse((String) call.argument("url")); builder.setLongLink(url); buildShortDynamicLink(builder, call, createShortLinkListener(result)); break; case "FirebaseDynamicLinks#getDynamicLink": handleGetDynamicLink(result, Uri.parse((String) call.argument("url"))); break; case "FirebaseDynamicLinks#getInitialLink": handleGetInitialDynamicLink(result); break; default: result.notImplemented(); break; } } private Map<String, Object> getMapFromPendingDynamicLinkData( PendingDynamicLinkData pendingDynamicLinkData) { Map<String, Object> dynamicLink = new HashMap<>(); Uri link = pendingDynamicLinkData.getLink(); dynamicLink.put("link", link != null ? link.toString() : null); Map<String, Object> androidData = new HashMap<>(); androidData.put("clickTimestamp", pendingDynamicLinkData.getClickTimestamp()); androidData.put("minimumVersion", pendingDynamicLinkData.getMinimumAppVersion()); dynamicLink.put("android", androidData); return dynamicLink; } private void addDynamicLinkListener(Task<PendingDynamicLinkData> task, final Result result) { task.addOnSuccessListener( new OnSuccessListener<PendingDynamicLinkData>() { @Override public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) { if (pendingDynamicLinkData != null) { Map<String, Object> dynamicLink = getMapFromPendingDynamicLinkData(pendingDynamicLinkData); result.success(dynamicLink); return; } result.success(null); } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(Exception e) { result.error(e.getClass().getSimpleName(), e.getMessage(), null); } }); } private void handleGetDynamicLink(final Result result, Uri uri) { addDynamicLinkListener(FirebaseDynamicLinks.getInstance().getDynamicLink(uri), result); } private void handleGetInitialDynamicLink(final Result result) { // If there's no activity or initial Intent, then there's no initial dynamic link. if (activity == null || activity.getIntent() == null) { result.success(null); return; } addDynamicLinkListener( FirebaseDynamicLinks.getInstance().getDynamicLink(activity.getIntent()), result); } private OnCompleteListener<ShortDynamicLink> createShortLinkListener(final Result result) { return new OnCompleteListener<ShortDynamicLink>() { @Override public void onComplete(Task<ShortDynamicLink> task) { if (task.isSuccessful()) { Map<String, Object> url = new HashMap<>(); url.put("url", task.getResult().getShortLink().toString()); List<String> warnings = new ArrayList<>(); if (task.getResult().getWarnings() != null) { for (ShortDynamicLink.Warning warning : task.getResult().getWarnings()) { warnings.add(warning.getMessage()); } } url.put("warnings", warnings); result.success(url); } else { Exception exception = task.getException(); String errMsg = "Unable to create short link"; if (exception != null && exception.getLocalizedMessage() != null) { errMsg = exception.getLocalizedMessage(); } result.error("short_link_error", errMsg, null); } } }; } private void buildShortDynamicLink( DynamicLink.Builder builder, MethodCall call, OnCompleteListener<ShortDynamicLink> listener) { Integer suffix = null; Map<String, Object> dynamicLinkParametersOptions = call.argument("dynamicLinkParametersOptions"); if (dynamicLinkParametersOptions != null) { Integer shortDynamicLinkPathLength = (Integer) dynamicLinkParametersOptions.get("shortDynamicLinkPathLength"); if (shortDynamicLinkPathLength != null) { switch (shortDynamicLinkPathLength) { case 0: suffix = ShortDynamicLink.Suffix.UNGUESSABLE; break; case 1: suffix = ShortDynamicLink.Suffix.SHORT; break; default: break; } } } if (suffix != null) { builder.buildShortDynamicLink(suffix).addOnCompleteListener(listener); } else { builder.buildShortDynamicLink().addOnCompleteListener(listener); } } private DynamicLink.Builder setupParameters(MethodCall call) { DynamicLink.Builder dynamicLinkBuilder = FirebaseDynamicLinks.getInstance().createDynamicLink(); String uriPrefix = call.argument("uriPrefix"); String link = call.argument("link"); dynamicLinkBuilder.setDomainUriPrefix(uriPrefix); dynamicLinkBuilder.setLink(Uri.parse(link)); Map<String, Object> androidParameters = call.argument("androidParameters"); if (androidParameters != null) { String packageName = valueFor("packageName", androidParameters); String fallbackUrl = valueFor("fallbackUrl", androidParameters); Integer minimumVersion = valueFor("minimumVersion", androidParameters); DynamicLink.AndroidParameters.Builder builder = new DynamicLink.AndroidParameters.Builder(packageName); if (fallbackUrl != null) builder.setFallbackUrl(Uri.parse(fallbackUrl)); if (minimumVersion != null) builder.setMinimumVersion(minimumVersion); dynamicLinkBuilder.setAndroidParameters(builder.build()); } Map<String, Object> googleAnalyticsParameters = call.argument("googleAnalyticsParameters"); if (googleAnalyticsParameters != null) { String campaign = valueFor("campaign", googleAnalyticsParameters); String content = valueFor("content", googleAnalyticsParameters); String medium = valueFor("medium", googleAnalyticsParameters); String source = valueFor("source", googleAnalyticsParameters); String term = valueFor("term", googleAnalyticsParameters); DynamicLink.GoogleAnalyticsParameters.Builder builder = new DynamicLink.GoogleAnalyticsParameters.Builder(); if (campaign != null) builder.setCampaign(campaign); if (content != null) builder.setContent(content); if (medium != null) builder.setMedium(medium); if (source != null) builder.setSource(source); if (term != null) builder.setTerm(term); dynamicLinkBuilder.setGoogleAnalyticsParameters(builder.build()); } Map<String, Object> iosParameters = call.argument("iosParameters"); if (iosParameters != null) { String bundleId = valueFor("bundleId", iosParameters); String appStoreId = valueFor("appStoreId", iosParameters); String customScheme = valueFor("customScheme", iosParameters); String fallbackUrl = valueFor("fallbackUrl", iosParameters); String ipadBundleId = valueFor("ipadBundleId", iosParameters); String ipadFallbackUrl = valueFor("ipadFallbackUrl", iosParameters); String minimumVersion = valueFor("minimumVersion", iosParameters); DynamicLink.IosParameters.Builder builder = new DynamicLink.IosParameters.Builder(bundleId); if (appStoreId != null) builder.setAppStoreId(appStoreId); if (customScheme != null) builder.setCustomScheme(customScheme); if (fallbackUrl != null) builder.setFallbackUrl(Uri.parse(fallbackUrl)); if (ipadBundleId != null) builder.setIpadBundleId(ipadBundleId); if (ipadFallbackUrl != null) builder.setIpadFallbackUrl(Uri.parse(ipadFallbackUrl)); if (minimumVersion != null) builder.setMinimumVersion(minimumVersion); dynamicLinkBuilder.setIosParameters(builder.build()); } Map<String, Object> itunesConnectAnalyticsParameters = call.argument("itunesConnectAnalyticsParameters"); if (itunesConnectAnalyticsParameters != null) { String affiliateToken = valueFor("affiliateToken", itunesConnectAnalyticsParameters); String campaignToken = valueFor("campaignToken", itunesConnectAnalyticsParameters); String providerToken = valueFor("providerToken", itunesConnectAnalyticsParameters); DynamicLink.ItunesConnectAnalyticsParameters.Builder builder = new DynamicLink.ItunesConnectAnalyticsParameters.Builder(); if (affiliateToken != null) builder.setAffiliateToken(affiliateToken); if (campaignToken != null) builder.setCampaignToken(campaignToken); if (providerToken != null) builder.setProviderToken(providerToken); dynamicLinkBuilder.setItunesConnectAnalyticsParameters(builder.build()); } Map<String, Object> navigationInfoParameters = call.argument("navigationInfoParameters"); if (navigationInfoParameters != null) { Boolean forcedRedirectEnabled = valueFor("forcedRedirectEnabled", navigationInfoParameters); DynamicLink.NavigationInfoParameters.Builder builder = new DynamicLink.NavigationInfoParameters.Builder(); if (forcedRedirectEnabled != null) builder.setForcedRedirectEnabled(forcedRedirectEnabled); dynamicLinkBuilder.setNavigationInfoParameters(builder.build()); } Map<String, Object> socialMetaTagParameters = call.argument("socialMetaTagParameters"); if (socialMetaTagParameters != null) { String description = valueFor("description", socialMetaTagParameters); String imageUrl = valueFor("imageUrl", socialMetaTagParameters); String title = valueFor("title", socialMetaTagParameters); DynamicLink.SocialMetaTagParameters.Builder builder = new DynamicLink.SocialMetaTagParameters.Builder(); if (description != null) builder.setDescription(description); if (imageUrl != null) builder.setImageUrl(Uri.parse(imageUrl)); if (title != null) builder.setTitle(title); dynamicLinkBuilder.setSocialMetaTagParameters(builder.build()); } return dynamicLinkBuilder; } private static <T> T valueFor(String key, Map<String, Object> map) { @SuppressWarnings("unchecked") T result = (T) map.get(key); return result; } }
packages/firebase_dynamic_links/android/src/main/java/io/flutter/plugins/firebasedynamiclinks/FirebaseDynamicLinksPlugin.java
// Copyright 2019 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. package io.flutter.plugins.firebasedynamiclinks; import android.app.Activity; import android.content.Intent; import android.net.Uri; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.dynamiclinks.DynamicLink; import com.google.firebase.dynamiclinks.FirebaseDynamicLinks; import com.google.firebase.dynamiclinks.PendingDynamicLinkData; import com.google.firebase.dynamiclinks.ShortDynamicLink; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.Result; import io.flutter.plugin.common.PluginRegistry.NewIntentListener; import io.flutter.plugin.common.PluginRegistry.Registrar; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Flutter plugin accessing for Firebase Dynamic Links API. * * <p>Instantiate this in an add to app scenario to gracefully handle activity and context changes. */ public class FirebaseDynamicLinksPlugin implements FlutterPlugin, ActivityAware, MethodCallHandler, NewIntentListener { private Activity activity; private MethodChannel channel; private FirebaseDynamicLinksPlugin(Activity activity, MethodChannel channel) { this.activity = activity; this.channel = channel; } /** * Default Constructor. * * <p>Use this when adding the plugin to your FlutterEngine */ public FirebaseDynamicLinksPlugin() {} /** * Registers a plugin with the v1 embedding api {@code io.flutter.plugin.common}. * * <p>Calling this will register the plugin with the passed registrar. However, plugins * initialized this way won't react to changes in activity or context. * * @param registrar attaches this plugin's {@link * io.flutter.plugin.common.MethodChannel.MethodCallHandler} to the registrar's {@link * io.flutter.plugin.common.BinaryMessenger}. */ public static void registerWith(Registrar registrar) { final MethodChannel channel = createChannel(registrar.messenger()); final FirebaseDynamicLinksPlugin plugin = new FirebaseDynamicLinksPlugin(registrar.activity(), channel); registrar.addNewIntentListener(plugin); channel.setMethodCallHandler(plugin); } private static MethodChannel createChannel(final BinaryMessenger messenger) { return new MethodChannel(messenger, "plugins.flutter.io/firebase_dynamic_links"); } @Override public boolean onNewIntent(Intent intent) { FirebaseDynamicLinks.getInstance() .getDynamicLink(intent) .addOnSuccessListener( new OnSuccessListener<PendingDynamicLinkData>() { @Override public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) { if (pendingDynamicLinkData != null) { Map<String, Object> dynamicLink = getMapFromPendingDynamicLinkData(pendingDynamicLinkData); channel.invokeMethod("onLinkSuccess", dynamicLink); } } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(Exception e) { Map<String, Object> exception = new HashMap<>(); exception.put("code", e.getClass().getSimpleName()); exception.put("message", e.getMessage()); exception.put("details", null); channel.invokeMethod("onLinkError", exception); } }); return false; } @Override public void onAttachedToEngine(FlutterPluginBinding binding) { channel = createChannel(binding.getBinaryMessenger()); channel.setMethodCallHandler(this); } @Override public void onDetachedFromEngine(FlutterPluginBinding binding) { channel.setMethodCallHandler(null); } @Override public void onAttachedToActivity(ActivityPluginBinding binding) { activity = binding.getActivity(); binding.addOnNewIntentListener(this); } @Override public void onDetachedFromActivityForConfigChanges() { activity = null; } @Override public void onReattachedToActivityForConfigChanges(ActivityPluginBinding binding) { activity = binding.getActivity(); binding.addOnNewIntentListener(this); } @Override public void onDetachedFromActivity() { activity = null; } @Override public void onMethodCall(MethodCall call, Result result) { switch (call.method) { case "DynamicLinkParameters#buildUrl": DynamicLink.Builder urlBuilder = setupParameters(call); result.success(urlBuilder.buildDynamicLink().getUri().toString()); break; case "DynamicLinkParameters#buildShortLink": DynamicLink.Builder shortLinkBuilder = setupParameters(call); buildShortDynamicLink(shortLinkBuilder, call, createShortLinkListener(result)); break; case "DynamicLinkParameters#shortenUrl": DynamicLink.Builder builder = FirebaseDynamicLinks.getInstance().createDynamicLink(); Uri url = Uri.parse((String) call.argument("url")); builder.setLongLink(url); buildShortDynamicLink(builder, call, createShortLinkListener(result)); break; case "FirebaseDynamicLinks#getDynamicLink": handleGetDynamicLink(result, Uri.parse((String) call.argument("url"))); break; case "FirebaseDynamicLinks#getInitialLink": handleGetInitialDynamicLink(result); break; default: result.notImplemented(); break; } } private Map<String, Object> getMapFromPendingDynamicLinkData( PendingDynamicLinkData pendingDynamicLinkData) { Map<String, Object> dynamicLink = new HashMap<>(); Uri link = pendingDynamicLinkData.getLink(); dynamicLink.put("link", link != null ? link.toString() : null); Map<String, Object> androidData = new HashMap<>(); androidData.put("clickTimestamp", pendingDynamicLinkData.getClickTimestamp()); androidData.put("minimumVersion", pendingDynamicLinkData.getMinimumAppVersion()); dynamicLink.put("android", androidData); return dynamicLink; } private void addDynamicLinkListener(Task<PendingDynamicLinkData> task, final Result result) { task.addOnSuccessListener( new OnSuccessListener<PendingDynamicLinkData>() { @Override public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) { if (pendingDynamicLinkData != null) { Map<String, Object> dynamicLink = getMapFromPendingDynamicLinkData(pendingDynamicLinkData); result.success(dynamicLink); return; } result.success(null); } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(Exception e) { result.error(e.getClass().getSimpleName(), e.getMessage(), null); } }); } private void handleGetDynamicLink(final Result result, Uri uri) { addDynamicLinkListener(FirebaseDynamicLinks.getInstance().getDynamicLink(uri), result); } private void handleGetInitialDynamicLink(final Result result) { // If there's no activity, then there's no initial dynamic link. if (activity == null) { result.success(null); return; } addDynamicLinkListener( FirebaseDynamicLinks.getInstance().getDynamicLink(activity.getIntent()), result); } private OnCompleteListener<ShortDynamicLink> createShortLinkListener(final Result result) { return new OnCompleteListener<ShortDynamicLink>() { @Override public void onComplete(Task<ShortDynamicLink> task) { if (task.isSuccessful()) { Map<String, Object> url = new HashMap<>(); url.put("url", task.getResult().getShortLink().toString()); List<String> warnings = new ArrayList<>(); if (task.getResult().getWarnings() != null) { for (ShortDynamicLink.Warning warning : task.getResult().getWarnings()) { warnings.add(warning.getMessage()); } } url.put("warnings", warnings); result.success(url); } else { Exception exception = task.getException(); String errMsg = "Unable to create short link"; if (exception != null && exception.getLocalizedMessage() != null) { errMsg = exception.getLocalizedMessage(); } result.error("short_link_error", errMsg, null); } } }; } private void buildShortDynamicLink( DynamicLink.Builder builder, MethodCall call, OnCompleteListener<ShortDynamicLink> listener) { Integer suffix = null; Map<String, Object> dynamicLinkParametersOptions = call.argument("dynamicLinkParametersOptions"); if (dynamicLinkParametersOptions != null) { Integer shortDynamicLinkPathLength = (Integer) dynamicLinkParametersOptions.get("shortDynamicLinkPathLength"); if (shortDynamicLinkPathLength != null) { switch (shortDynamicLinkPathLength) { case 0: suffix = ShortDynamicLink.Suffix.UNGUESSABLE; break; case 1: suffix = ShortDynamicLink.Suffix.SHORT; break; default: break; } } } if (suffix != null) { builder.buildShortDynamicLink(suffix).addOnCompleteListener(listener); } else { builder.buildShortDynamicLink().addOnCompleteListener(listener); } } private DynamicLink.Builder setupParameters(MethodCall call) { DynamicLink.Builder dynamicLinkBuilder = FirebaseDynamicLinks.getInstance().createDynamicLink(); String uriPrefix = call.argument("uriPrefix"); String link = call.argument("link"); dynamicLinkBuilder.setDomainUriPrefix(uriPrefix); dynamicLinkBuilder.setLink(Uri.parse(link)); Map<String, Object> androidParameters = call.argument("androidParameters"); if (androidParameters != null) { String packageName = valueFor("packageName", androidParameters); String fallbackUrl = valueFor("fallbackUrl", androidParameters); Integer minimumVersion = valueFor("minimumVersion", androidParameters); DynamicLink.AndroidParameters.Builder builder = new DynamicLink.AndroidParameters.Builder(packageName); if (fallbackUrl != null) builder.setFallbackUrl(Uri.parse(fallbackUrl)); if (minimumVersion != null) builder.setMinimumVersion(minimumVersion); dynamicLinkBuilder.setAndroidParameters(builder.build()); } Map<String, Object> googleAnalyticsParameters = call.argument("googleAnalyticsParameters"); if (googleAnalyticsParameters != null) { String campaign = valueFor("campaign", googleAnalyticsParameters); String content = valueFor("content", googleAnalyticsParameters); String medium = valueFor("medium", googleAnalyticsParameters); String source = valueFor("source", googleAnalyticsParameters); String term = valueFor("term", googleAnalyticsParameters); DynamicLink.GoogleAnalyticsParameters.Builder builder = new DynamicLink.GoogleAnalyticsParameters.Builder(); if (campaign != null) builder.setCampaign(campaign); if (content != null) builder.setContent(content); if (medium != null) builder.setMedium(medium); if (source != null) builder.setSource(source); if (term != null) builder.setTerm(term); dynamicLinkBuilder.setGoogleAnalyticsParameters(builder.build()); } Map<String, Object> iosParameters = call.argument("iosParameters"); if (iosParameters != null) { String bundleId = valueFor("bundleId", iosParameters); String appStoreId = valueFor("appStoreId", iosParameters); String customScheme = valueFor("customScheme", iosParameters); String fallbackUrl = valueFor("fallbackUrl", iosParameters); String ipadBundleId = valueFor("ipadBundleId", iosParameters); String ipadFallbackUrl = valueFor("ipadFallbackUrl", iosParameters); String minimumVersion = valueFor("minimumVersion", iosParameters); DynamicLink.IosParameters.Builder builder = new DynamicLink.IosParameters.Builder(bundleId); if (appStoreId != null) builder.setAppStoreId(appStoreId); if (customScheme != null) builder.setCustomScheme(customScheme); if (fallbackUrl != null) builder.setFallbackUrl(Uri.parse(fallbackUrl)); if (ipadBundleId != null) builder.setIpadBundleId(ipadBundleId); if (ipadFallbackUrl != null) builder.setIpadFallbackUrl(Uri.parse(ipadFallbackUrl)); if (minimumVersion != null) builder.setMinimumVersion(minimumVersion); dynamicLinkBuilder.setIosParameters(builder.build()); } Map<String, Object> itunesConnectAnalyticsParameters = call.argument("itunesConnectAnalyticsParameters"); if (itunesConnectAnalyticsParameters != null) { String affiliateToken = valueFor("affiliateToken", itunesConnectAnalyticsParameters); String campaignToken = valueFor("campaignToken", itunesConnectAnalyticsParameters); String providerToken = valueFor("providerToken", itunesConnectAnalyticsParameters); DynamicLink.ItunesConnectAnalyticsParameters.Builder builder = new DynamicLink.ItunesConnectAnalyticsParameters.Builder(); if (affiliateToken != null) builder.setAffiliateToken(affiliateToken); if (campaignToken != null) builder.setCampaignToken(campaignToken); if (providerToken != null) builder.setProviderToken(providerToken); dynamicLinkBuilder.setItunesConnectAnalyticsParameters(builder.build()); } Map<String, Object> navigationInfoParameters = call.argument("navigationInfoParameters"); if (navigationInfoParameters != null) { Boolean forcedRedirectEnabled = valueFor("forcedRedirectEnabled", navigationInfoParameters); DynamicLink.NavigationInfoParameters.Builder builder = new DynamicLink.NavigationInfoParameters.Builder(); if (forcedRedirectEnabled != null) builder.setForcedRedirectEnabled(forcedRedirectEnabled); dynamicLinkBuilder.setNavigationInfoParameters(builder.build()); } Map<String, Object> socialMetaTagParameters = call.argument("socialMetaTagParameters"); if (socialMetaTagParameters != null) { String description = valueFor("description", socialMetaTagParameters); String imageUrl = valueFor("imageUrl", socialMetaTagParameters); String title = valueFor("title", socialMetaTagParameters); DynamicLink.SocialMetaTagParameters.Builder builder = new DynamicLink.SocialMetaTagParameters.Builder(); if (description != null) builder.setDescription(description); if (imageUrl != null) builder.setImageUrl(Uri.parse(imageUrl)); if (title != null) builder.setTitle(title); dynamicLinkBuilder.setSocialMetaTagParameters(builder.build()); } return dynamicLinkBuilder; } private static <T> T valueFor(String key, Map<String, Object> map) { @SuppressWarnings("unchecked") T result = (T) map.get(key); return result; } }
fix(dynamic-links, android): null-check intent before calling getDynamicLink (#6911)
packages/firebase_dynamic_links/android/src/main/java/io/flutter/plugins/firebasedynamiclinks/FirebaseDynamicLinksPlugin.java
fix(dynamic-links, android): null-check intent before calling getDynamicLink (#6911)
<ide><path>ackages/firebase_dynamic_links/android/src/main/java/io/flutter/plugins/firebasedynamiclinks/FirebaseDynamicLinksPlugin.java <ide> } <ide> <ide> private void handleGetInitialDynamicLink(final Result result) { <del> // If there's no activity, then there's no initial dynamic link. <del> if (activity == null) { <add> // If there's no activity or initial Intent, then there's no initial dynamic link. <add> if (activity == null || activity.getIntent() == null) { <ide> result.success(null); <ide> return; <ide> }
Java
apache-2.0
ac2de2e6df31b5c03a371f8aa51cee72cb2d3f10
0
Aino-io/agent-wso2-esb
/* * Copyright 2016 Aino.io * * 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.aino.agents.wso2.mediator; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.synapse.MessageContext; import org.apache.synapse.core.axis2.Axis2MessageContext; import org.apache.synapse.mediators.AbstractMediator; import org.apache.synapse.mediators.MediatorProperty; import org.apache.synapse.util.xpath.SynapseXPath; import org.jaxen.JaxenException; import io.aino.agents.core.Agent; import io.aino.agents.core.Transaction; import io.aino.agents.core.config.InvalidAgentConfigException; import io.aino.agents.wso2.mediator.util.Enum; import io.aino.agents.wso2.mediator.util.Id; import io.aino.agents.wso2.mediator.util.IdPropertyBuilder; import io.aino.agents.wso2.mediator.util.MediatorLocation; import static io.aino.agents.wso2.mediator.config.AinoMediatorConfigConstants.*; /** * Aino.io WSO2 ESB mediator. */ public class AinoMediator extends AbstractMediator { public Agent ainoAgent; //private final LogMediator logMediator; //private Enum.LogLevel level = Enum.LogLevel.CUSTOM; //private Enum.LogCategory category; private String separator; private String operation; private String message; private String esbServerName; private String fromApplication; private String toApplication; private String payloadType; private Enum.Status status; //private String flowId; private final MediatorLocation mediatorLocation; private List<MediatorProperty> customProperties; private final List<Id> idList = new ArrayList<Id>(); @SuppressWarnings("serial") private class DataFieldList extends ArrayList<String> { public DataFieldList(List<String> data) { this.addAll(data); } public boolean doesNotContain(String item) { return !this.contains(item); } } private DataFieldList dataFields = new DataFieldList(Arrays.asList( "from", "to", "message", "status", "timestamp", "operation", "ids", "flowId", "payloadType" )); /** * Constructor. * * @param ml mediator location * @param agent aino agent instance */ public AinoMediator(MediatorLocation ml, Agent agent) { this.mediatorLocation = ml; this.ainoAgent = agent; } private static MediatorProperty getMediatorProperty(String name, String value, String expression) throws JaxenException { MediatorProperty mp = new MediatorProperty(); mp.setName(name); mp.setValue(value); if(null == expression){ return mp; } invokePropertyExpression(expression, mp); return mp; } private static Object invokePropertyExpression(String expression, MediatorProperty mp) { try { // Workaround for a peculiar WSO2 update approach where an // intermediate (SynapsePath) class was added into the class // hierarchy Class<?> parameterClass = getParameterClass(); Class<?> synapseXPathClass = getSynapseXpathClass(); Method setExpression = MediatorProperty.class.getMethod("setExpression", parameterClass); return setExpression.invoke(mp, synapseXPathClass.getConstructor(String.class).newInstance(expression)); } catch (Exception e) { throw new InvalidAgentConfigException( "Unable to initialize a AinoMediator due to a reflection-related exception.", e); } } private static Class<?> getSynapseXpathClass(){ return getClassForName("org.apache.synapse.util.xpath.SynapseXPath"); } private static Class<?> getParameterClass(){ return getClassForName(getParameterClassName()); } private static Class<?> getClassForName(String name){ try { return Class.forName(name); } catch (ClassNotFoundException e) { throw new RuntimeException("Could not instantiate class: " + name); } } private static String getParameterClassName(){ String esb480OrLater = "org.apache.synapse.config.xml.SynapsePath"; String beforeEsb480 = "org.apache.synapse.util.xpath.SynapseXPath"; try { // If running in ESB v4.8.0 or newer Class.forName(esb480OrLater); return esb480OrLater; } catch (ClassNotFoundException e) { // If running in ESB older than v4.8.0 return beforeEsb480; } } /** * Adds id xpath with id type key. * * @param typeKey type key * @param xPath xpath of ids */ public void addId(String typeKey, SynapseXPath xPath) { idList.add(new Id(typeKey, xPath)); } /** * Adds custom list of {@link MediatorProperty}. * They will be logged by ESB. * * @param properties properties to add */ public void setProperties(List<MediatorProperty> properties) { customProperties = properties; } /** * Gets all custom {@link MediatorProperty}. * * @return custom properties */ public List<MediatorProperty> getProperties() { return customProperties; } @Override public boolean mediate(MessageContext context) { try { initTransportHeadersMap(context); Transaction transaction = createTransaction(context); new IdPropertyBuilder(this.idList).buildToContext(context, transaction); processTransaction(context, transaction); logToEsb(context, transaction); } catch (Exception e) { log.error("Error occurred while trying to log to aino.io!", e); } return true; } private void logToEsb(MessageContext context, Transaction transaction) { StringBuilder sb = new StringBuilder(); for (MediatorProperty prop : customProperties) { sb.append(prop.getName()).append(" = ").append(prop.getValue()); sb.append(this.separator); } if(transaction != null) { appendNormalFieldsToLogMessage(transaction, sb); appendIdsToLogMessage(transaction, sb); } log.info(sb.toString()); } private void appendIdsToLogMessage(Transaction transaction, StringBuilder sb) { sb.append("ids = ["); for(String idName : transaction.getIds().keySet()) { sb.append(idName).append(": ["); List<String> ids = transaction.getIds().get(idName); sb.append(StringUtils.join(ids, ",")).append("],"); } sb.append("]"); } private void appendNormalFieldsToLogMessage(Transaction transaction, StringBuilder sb) { appendNameAndValueToLogMessage("operation",ainoAgent.getAgentConfig().getOperations().getEntry(transaction.getOperationKey()), sb); appendNameAndValueToLogMessage("flowId", transaction.getFlowId(), sb); appendNameAndValueToLogMessage("message", transaction.getMessage(), sb); appendNameAndValueToLogMessage("status", transaction.getStatus(), sb); appendNameAndValueToLogMessage("payloadType", ainoAgent.getAgentConfig().getPayloadTypes().getEntry(transaction.getPayloadTypeKey()), sb); appendNameAndValueToLogMessage("from", ainoAgent.getAgentConfig().getApplications().getEntry(transaction.getFromKey()), sb); appendNameAndValueToLogMessage("to", ainoAgent.getAgentConfig().getApplications().getEntry(transaction.getToKey()), sb); appendNameAndValueToLogMessage("ainoTimestamp", String.valueOf(transaction.getTimestamp()), sb); } private void appendNameAndValueToLogMessage(String name, String value, StringBuilder sb) { sb.append(name) .append(" = ") .append(value) .append(this.separator); } private void processTransaction(MessageContext context, Transaction transaction) { if(transaction == null) { return; } addFieldsToTransaction(transaction); for (MediatorProperty property : customProperties) { if (isMetadataProperty(property)) { String propertyValue = property.getValue() != null ? property.getValue() : property.getEvaluatedExpression(context); transaction.addMetadata(property.getName(), propertyValue); } } ainoAgent.addTransaction(transaction); } private boolean isMetadataProperty(MediatorProperty prop) { if(prop == null) return false; return this.dataFields.doesNotContain(prop.getName()); } private void addFieldsToTransaction(Transaction transaction) { transaction.setFromKey(this.fromApplication); transaction.setToKey(this.toApplication); transaction.setMessage(this.message); transaction.setOperationKey(this.operation); transaction.setStatus(this.status == null ? "" : this.status.toString()); transaction.setPayloadTypeKey(this.payloadType); } private Transaction createTransaction(MessageContext context) { String flowId = validateOrSetAinoFlowId(context); String operationKey = validateOrSetAinoOperationName(context); Transaction transaction = null; if (ainoAgent.isEnabled()) { transaction = ainoAgent.newTransaction(); transaction.setFlowId(flowId); transaction.setOperationKey(operationKey); transaction.addMetadata("artifactName", mediatorLocation.getArtifactName()); transaction.addMetadata("esbServerName", esbServerName); transaction.addMetadata("artifactType", mediatorLocation.getArtifactType()); transaction.addMetadata("artifactName", mediatorLocation.getArtifactName()); transaction.addMetadata("lineNumber", Integer.toString(mediatorLocation.getLineNumber())); if (status == Enum.Status.FAILURE) { addErrorMetadata(context, transaction); } } return transaction; } private void addErrorMetadata(MessageContext context, Transaction transaction) { if (context.getProperty("ERROR_CODE") != null) { transaction.addMetadata("errorCode", context.getProperty("ERROR_CODE").toString()); } if (context.getProperty("ERROR_MESSAGE") != null) { transaction.addMetadata("errorMessage", context.getProperty("ERROR_MESSAGE").toString()); } if (context.getProperty("ERROR_DETAIL") != null) { transaction.addMetadata("errorDetails", context.getProperty("ERROR_DETAIL").toString()); } if (context.getProperty("ERROR_EXCEPTION") != null) { transaction.addMetadata("errorException", context.getProperty("ERROR_EXCEPTION").toString()); } } /** * Creates a transport headers map if one does not exist. * * @param context */ private Map<String,String> initTransportHeadersMap(MessageContext context) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) context).getAxis2MessageContext(); Map<String,String> headersMap = (Map<String, String>) axis2MessageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headersMap == null) { headersMap = new HashMap<String, String>(); context.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, headersMap); } return headersMap; } private String validateOrSetAinoOperationName(MessageContext context) { String ainoOperationName = getOperationNameFromTransportHeaders(context); if (null == ainoOperationName) { ainoOperationName = getOperationNameFromMessageContext(context); } if(null != ainoOperationName){ return ainoOperationName; } if(null == operation){ log.warn("The AinoMediator encountered an operation it isn't registered for. Undefined operation."); return null; } return getOperationNameFromMediator(context); } private String getOperationNameFromMediator(MessageContext context) { Map<String, String> headersMap = getTransportHeadersMap(context); headersMap.put(AINO_OPERATION_NAME_PROPERTY_NAME, operation); return operation; } private String getOperationNameFromTransportHeaders(MessageContext context){ // This logic is in place for situations where the message is coming back from a system which doesn't return custom transport headers. try { Map<String, String> headersMap = getTransportHeadersMap(context); return headersMap.get(AINO_OPERATION_NAME_PROPERTY_NAME); } catch (ClassCastException ignored) { return null; } } private String getOperationNameFromMessageContext(MessageContext context){ try { String name = (String) context.getProperty(AINO_OPERATION_NAME_PROPERTY_NAME); Map<String, String> headersMap = getTransportHeadersMap(context); headersMap.put(AINO_OPERATION_NAME_PROPERTY_NAME, name); return name; } catch (ClassCastException ignored) { return null; } } @SuppressWarnings("unchecked") private Map<String, String> getTransportHeadersMap(MessageContext context) { return initTransportHeadersMap(context); } private String validateOrSetAinoFlowId(MessageContext context) { Map<String, String> headersMap = getTransportHeadersMap(context); String flowId = headersMap.get(AINO_FLOW_ID_PROPERTY_NAME); if(null == flowId){ flowId = getFlowIdFromMessageContext(context); } if(null == flowId){ flowId = ((Axis2MessageContext) context).getAxis2MessageContext().getMessageID(); } headersMap.put(AINO_FLOW_ID_PROPERTY_NAME, flowId); return flowId; } private String getFlowIdFromMessageContext(MessageContext context) { try { String flowId = (String) context.getProperty(AINO_FLOW_ID_PROPERTY_NAME); Map<String, String> headersMap = getTransportHeadersMap(context); headersMap.put(AINO_FLOW_ID_PROPERTY_NAME, flowId); return flowId; } catch (ClassCastException e) { return null; } } /** * Gets mediator location. * * @return mediator location */ public MediatorLocation getMediatorLocation() { return mediatorLocation; } private void assertValidLogLevel(Enum.LogLevel level) { if (level == null) { StringBuilder sb = new StringBuilder("AinoMediator level must me one of: "); sb.append(Arrays.toString(Enum.LogLevel.values())); throw new IllegalArgumentException(sb.toString()); } } private Enum.LogLevel parseLogLevel(String levelString) { if (StringUtils.isEmpty(levelString)) { return Enum.LogLevel.CUSTOM; } return Enum.LogLevel.getLogLevel(levelString); } /** * Gets separator used in logging. * Separator is used in between properties. * * @return separator */ public String getSeparator() { return separator; } /** * Sets separator used in logging. * * @param separator separator */ public void setSeparator(String separator) { if (StringUtils.isEmpty(separator)) { separator = ","; } this.separator = separator; } /** * Gets operation key configured to this mediator. * * @return operation key */ public String getOperation() { return operation; } /** * Sets operation key. * * @param operation operation key */ public void setOperation(String operation) { this.operation = operation; } /** * Gets message configured to this mediator. * * @return message */ public String getMessage() { return message; } /** * Sets message. * * @param message message to set */ public void setMessage(String message) { this.message = message; } /** * Gets the server name of ESB. * * @return name of server */ public String getEsbServerName() { return esbServerName; } /** * Sets the server name of ESB. * * @param esbServerName server name */ public void setEsbServerName(String esbServerName) { this.esbServerName = esbServerName; } /** * Gets configured 'to application'. * * @return to applcation key */ public String getFromApplication() { return fromApplication; } /** * Sets 'from' application. * * @param fromApplication from application key */ public void setFromApplication(String fromApplication) { this.fromApplication = fromApplication; } /** * Gets configured 'to' application. * * @return to application key */ public String getToApplication() { return toApplication; } /** * Sets 'to' application. * * @param toApplication to application key */ public void setToApplication(String toApplication) { this.toApplication = toApplication; } /** * Sets payload type. * * @param payloadTypeKey payload type key */ public void setPayloadType(String payloadTypeKey) { this.payloadType = payloadTypeKey; } /** * Gets payload type. * * @return payload type key */ public String getPayloadType() { return this.payloadType; } /** * Gets status. * * @return status (success, failure, unknown) */ public String getStatus() { if (status == null) { return null; } return status.toString(); } /** * Sets status. * Valid values are: "success", "failure" and "unknown". * * @param statusString status * @throws IllegalArgumentException when status is invalid */ public void setStatus(String statusString) { Enum.Status status = Enum.Status.getStatus(statusString); if (status == null) { StringBuilder sb = new StringBuilder("AinoMediator status must me one of: "); sb.append(Arrays.toString(Enum.Status.values())); throw new InvalidAgentConfigException(sb.toString()); } this.status = status; } /** * Gets list of {@link Id}s. * * @return ids */ public List<Id> getIdList() { return idList; } /** * Sets 'to' or 'from' application, based on direction. * * @param direction direction * @param applicationKey application key */ public void setApplication(Enum.ApplicationDirection direction, String applicationKey) { switch (direction) { case TO: this.setToApplication(applicationKey); break; case FROM: this.setFromApplication(applicationKey); break; } } }
src/main/java/io/aino/agents/wso2/mediator/AinoMediator.java
/* * Copyright 2016 Aino.io * * 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.aino.agents.wso2.mediator; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.synapse.MessageContext; import org.apache.synapse.core.axis2.Axis2MessageContext; import org.apache.synapse.mediators.AbstractMediator; import org.apache.synapse.mediators.MediatorProperty; import org.apache.synapse.util.xpath.SynapseXPath; import org.jaxen.JaxenException; import io.aino.agents.core.Agent; import io.aino.agents.core.Transaction; import io.aino.agents.core.config.InvalidAgentConfigException; import io.aino.agents.wso2.mediator.util.Enum; import io.aino.agents.wso2.mediator.util.Id; import io.aino.agents.wso2.mediator.util.IdPropertyBuilder; import io.aino.agents.wso2.mediator.util.MediatorLocation; import static io.aino.agents.wso2.mediator.config.AinoMediatorConfigConstants.*; /** * Aino.io WSO2 ESB mediator. */ public class AinoMediator extends AbstractMediator { public Agent ainoAgent; //private final LogMediator logMediator; //private Enum.LogLevel level = Enum.LogLevel.CUSTOM; //private Enum.LogCategory category; private String separator; private String operation; private String message; private String esbServerName; private String fromApplication; private String toApplication; private String payloadType; private Enum.Status status; //private String flowId; private final MediatorLocation mediatorLocation; private List<MediatorProperty> customProperties; private final List<Id> idList = new ArrayList<Id>(); @SuppressWarnings("serial") private class DataFieldList extends ArrayList<String> { public DataFieldList(List<String> data) { this.addAll(data); } public boolean doesNotContain(String item) { return !this.contains(item); } } private DataFieldList dataFields = new DataFieldList(Arrays.asList( "from", "to", "message", "status", "timestamp", "operation", "ids", "flowId", "payloadType" )); /** * Constructor. * * @param ml mediator location * @param agent aino agent instance */ public AinoMediator(MediatorLocation ml, Agent agent) { this.mediatorLocation = ml; this.ainoAgent = agent; } private static MediatorProperty getMediatorProperty(String name, String value, String expression) throws JaxenException { MediatorProperty mp = new MediatorProperty(); mp.setName(name); mp.setValue(value); if(null == expression){ return mp; } invokePropertyExpression(expression, mp); return mp; } private static Object invokePropertyExpression(String expression, MediatorProperty mp) { try { // Workaround for a peculiar WSO2 update approach where an // intermediate (SynapsePath) class was added into the class // hierarchy Class<?> parameterClass = getParameterClass(); Class<?> synapseXPathClass = getSynapseXpathClass(); Method setExpression = MediatorProperty.class.getMethod("setExpression", parameterClass); return setExpression.invoke(mp, synapseXPathClass.getConstructor(String.class).newInstance(expression)); } catch (Exception e) { throw new InvalidAgentConfigException( "Unable to initialize a AinoMediator due to a reflection-related exception.", e); } } private static Class<?> getSynapseXpathClass(){ return getClassForName("org.apache.synapse.util.xpath.SynapseXPath"); } private static Class<?> getParameterClass(){ return getClassForName(getParameterClassName()); } private static Class<?> getClassForName(String name){ try { return Class.forName(name); } catch (ClassNotFoundException e) { throw new RuntimeException("Could not instantiate class: " + name); } } private static String getParameterClassName(){ String esb480OrLater = "org.apache.synapse.config.xml.SynapsePath"; String beforeEsb480 = "org.apache.synapse.util.xpath.SynapseXPath"; try { // If running in ESB v4.8.0 or newer Class.forName(esb480OrLater); return esb480OrLater; } catch (ClassNotFoundException e) { // If running in ESB older than v4.8.0 return beforeEsb480; } } /** * Adds id xpath with id type key. * * @param typeKey type key * @param xPath xpath of ids */ public void addId(String typeKey, SynapseXPath xPath) { idList.add(new Id(typeKey, xPath)); } /** * Adds custom list of {@link MediatorProperty}. * They will be logged by ESB. * * @param properties properties to add */ public void setProperties(List<MediatorProperty> properties) { customProperties = properties; } /** * Gets all custom {@link MediatorProperty}. * * @return custom properties */ public List<MediatorProperty> getProperties() { return customProperties; } @Override public boolean mediate(MessageContext context) { initTransportHeadersMap(context); Transaction transaction = createTransaction(context); new IdPropertyBuilder(this.idList).buildToContext(context, transaction); processTransaction(context, transaction); logToEsb(context, transaction); return true; } private void logToEsb(MessageContext context, Transaction transaction) { StringBuilder sb = new StringBuilder(); for (MediatorProperty prop : customProperties) { sb.append(prop.getName()).append(" = ").append(prop.getValue()); sb.append(this.separator); } if(transaction != null) { appendNormalFieldsToLogMessage(transaction, sb); appendIdsToLogMessage(transaction, sb); } log.info(sb.toString()); } private void appendIdsToLogMessage(Transaction transaction, StringBuilder sb) { sb.append("ids = ["); for(String idName : transaction.getIds().keySet()) { sb.append(idName).append(": ["); List<String> ids = transaction.getIds().get(idName); sb.append(StringUtils.join(ids, ",")).append("],"); } sb.append("]"); } private void appendNormalFieldsToLogMessage(Transaction transaction, StringBuilder sb) { appendNameAndValueToLogMessage("operation",ainoAgent.getAgentConfig().getOperations().getEntry(transaction.getOperationKey()), sb); appendNameAndValueToLogMessage("flowId", transaction.getFlowId(), sb); appendNameAndValueToLogMessage("message", transaction.getMessage(), sb); appendNameAndValueToLogMessage("status", transaction.getStatus(), sb); appendNameAndValueToLogMessage("payloadType", ainoAgent.getAgentConfig().getPayloadTypes().getEntry(transaction.getPayloadTypeKey()), sb); appendNameAndValueToLogMessage("from", ainoAgent.getAgentConfig().getApplications().getEntry(transaction.getFromKey()), sb); appendNameAndValueToLogMessage("to", ainoAgent.getAgentConfig().getApplications().getEntry(transaction.getToKey()), sb); appendNameAndValueToLogMessage("ainoTimestamp", String.valueOf(transaction.getTimestamp()), sb); } private void appendNameAndValueToLogMessage(String name, String value, StringBuilder sb) { sb.append(name) .append(" = ") .append(value) .append(this.separator); } private void processTransaction(MessageContext context, Transaction transaction) { if(transaction == null) { return; } addFieldsToTransaction(transaction); for (MediatorProperty property : customProperties) { if (isMetadataProperty(property)) { String propertyValue = property.getValue() != null ? property.getValue() : property.getEvaluatedExpression(context); transaction.addMetadata(property.getName(), propertyValue); } } ainoAgent.addTransaction(transaction); } private boolean isMetadataProperty(MediatorProperty prop) { if(prop == null) return false; return this.dataFields.doesNotContain(prop.getName()); } private void addFieldsToTransaction(Transaction transaction) { transaction.setFromKey(this.fromApplication); transaction.setToKey(this.toApplication); transaction.setMessage(this.message); transaction.setOperationKey(this.operation); transaction.setStatus(this.status == null ? "" : this.status.toString()); transaction.setPayloadTypeKey(this.payloadType); } private Transaction createTransaction(MessageContext context) { String flowId = validateOrSetAinoFlowId(context); String operationKey = validateOrSetAinoOperationName(context); Transaction transaction = null; if (ainoAgent.isEnabled()) { transaction = ainoAgent.newTransaction(); transaction.setFlowId(flowId); transaction.setOperationKey(operationKey); transaction.addMetadata("artifactName", mediatorLocation.getArtifactName()); transaction.addMetadata("esbServerName", esbServerName); transaction.addMetadata("artifactType", mediatorLocation.getArtifactType()); transaction.addMetadata("artifactName", mediatorLocation.getArtifactName()); transaction.addMetadata("lineNumber", Integer.toString(mediatorLocation.getLineNumber())); if (status == Enum.Status.FAILURE) { addErrorMetadata(context, transaction); } } return transaction; } private void addErrorMetadata(MessageContext context, Transaction transaction) { if (context.getProperty("ERROR_CODE") != null) { transaction.addMetadata("errorCode", context.getProperty("ERROR_CODE").toString()); } if (context.getProperty("ERROR_MESSAGE") != null) { transaction.addMetadata("errorMessage", context.getProperty("ERROR_MESSAGE").toString()); } if (context.getProperty("ERROR_DETAIL") != null) { transaction.addMetadata("errorDetails", context.getProperty("ERROR_DETAIL").toString()); } if (context.getProperty("ERROR_EXCEPTION") != null) { transaction.addMetadata("errorException", context.getProperty("ERROR_EXCEPTION").toString()); } } /** * Creates a transport headers map if one does not exist. * * @param context */ private Map<String,String> initTransportHeadersMap(MessageContext context) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) context).getAxis2MessageContext(); Map<String,String> headersMap = (Map<String, String>) axis2MessageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headersMap == null) { headersMap = new HashMap<String, String>(); context.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, headersMap); } return headersMap; } private String validateOrSetAinoOperationName(MessageContext context) { String ainoOperationName = getOperationNameFromTransportHeaders(context); if (null == ainoOperationName) { ainoOperationName = getOperationNameFromMessageContext(context); } if(null != ainoOperationName){ return ainoOperationName; } if(null == operation){ log.warn("The AinoMediator encountered an operation it isn't registered for. Undefined operation."); return null; } return getOperationNameFromMediator(context); } private String getOperationNameFromMediator(MessageContext context) { Map<String, String> headersMap = getTransportHeadersMap(context); headersMap.put(AINO_OPERATION_NAME_PROPERTY_NAME, operation); return operation; } private String getOperationNameFromTransportHeaders(MessageContext context){ // This logic is in place for situations where the message is coming back from a system which doesn't return custom transport headers. try { Map<String, String> headersMap = getTransportHeadersMap(context); return headersMap.get(AINO_OPERATION_NAME_PROPERTY_NAME); } catch (ClassCastException ignored) { return null; } } private String getOperationNameFromMessageContext(MessageContext context){ try { String name = (String) context.getProperty(AINO_OPERATION_NAME_PROPERTY_NAME); Map<String, String> headersMap = getTransportHeadersMap(context); headersMap.put(AINO_OPERATION_NAME_PROPERTY_NAME, name); return name; } catch (ClassCastException ignored) { return null; } } @SuppressWarnings("unchecked") private Map<String, String> getTransportHeadersMap(MessageContext context) { return initTransportHeadersMap(context); } private String validateOrSetAinoFlowId(MessageContext context) { Map<String, String> headersMap = getTransportHeadersMap(context); String flowId = headersMap.get(AINO_FLOW_ID_PROPERTY_NAME); if(null == flowId){ flowId = getFlowIdFromMessageContext(context); } if(null == flowId){ flowId = ((Axis2MessageContext) context).getAxis2MessageContext().getMessageID(); } headersMap.put(AINO_FLOW_ID_PROPERTY_NAME, flowId); return flowId; } private String getFlowIdFromMessageContext(MessageContext context) { try { String flowId = (String) context.getProperty(AINO_FLOW_ID_PROPERTY_NAME); Map<String, String> headersMap = getTransportHeadersMap(context); headersMap.put(AINO_FLOW_ID_PROPERTY_NAME, flowId); return flowId; } catch (ClassCastException e) { return null; } } /** * Gets mediator location. * * @return mediator location */ public MediatorLocation getMediatorLocation() { return mediatorLocation; } private void assertValidLogLevel(Enum.LogLevel level) { if (level == null) { StringBuilder sb = new StringBuilder("AinoMediator level must me one of: "); sb.append(Arrays.toString(Enum.LogLevel.values())); throw new IllegalArgumentException(sb.toString()); } } private Enum.LogLevel parseLogLevel(String levelString) { if (StringUtils.isEmpty(levelString)) { return Enum.LogLevel.CUSTOM; } return Enum.LogLevel.getLogLevel(levelString); } /** * Gets separator used in logging. * Separator is used in between properties. * * @return separator */ public String getSeparator() { return separator; } /** * Sets separator used in logging. * * @param separator separator */ public void setSeparator(String separator) { if (StringUtils.isEmpty(separator)) { separator = ","; } this.separator = separator; } /** * Gets operation key configured to this mediator. * * @return operation key */ public String getOperation() { return operation; } /** * Sets operation key. * * @param operation operation key */ public void setOperation(String operation) { this.operation = operation; } /** * Gets message configured to this mediator. * * @return message */ public String getMessage() { return message; } /** * Sets message. * * @param message message to set */ public void setMessage(String message) { this.message = message; } /** * Gets the server name of ESB. * * @return name of server */ public String getEsbServerName() { return esbServerName; } /** * Sets the server name of ESB. * * @param esbServerName server name */ public void setEsbServerName(String esbServerName) { this.esbServerName = esbServerName; } /** * Gets configured 'to application'. * * @return to applcation key */ public String getFromApplication() { return fromApplication; } /** * Sets 'from' application. * * @param fromApplication from application key */ public void setFromApplication(String fromApplication) { this.fromApplication = fromApplication; } /** * Gets configured 'to' application. * * @return to application key */ public String getToApplication() { return toApplication; } /** * Sets 'to' application. * * @param toApplication to application key */ public void setToApplication(String toApplication) { this.toApplication = toApplication; } /** * Sets payload type. * * @param payloadTypeKey payload type key */ public void setPayloadType(String payloadTypeKey) { this.payloadType = payloadTypeKey; } /** * Gets payload type. * * @return payload type key */ public String getPayloadType() { return this.payloadType; } /** * Gets status. * * @return status (success, failure, unknown) */ public String getStatus() { if (status == null) { return null; } return status.toString(); } /** * Sets status. * Valid values are: "success", "failure" and "unknown". * * @param statusString status * @throws IllegalArgumentException when status is invalid */ public void setStatus(String statusString) { Enum.Status status = Enum.Status.getStatus(statusString); if (status == null) { StringBuilder sb = new StringBuilder("AinoMediator status must me one of: "); sb.append(Arrays.toString(Enum.Status.values())); throw new InvalidAgentConfigException(sb.toString()); } this.status = status; } /** * Gets list of {@link Id}s. * * @return ids */ public List<Id> getIdList() { return idList; } /** * Sets 'to' or 'from' application, based on direction. * * @param direction direction * @param applicationKey application key */ public void setApplication(Enum.ApplicationDirection direction, String applicationKey) { switch (direction) { case TO: this.setToApplication(applicationKey); break; case FROM: this.setFromApplication(applicationKey); break; } } }
try-catch to mediate() so that mediation would not stop in any circumstance
src/main/java/io/aino/agents/wso2/mediator/AinoMediator.java
try-catch to mediate() so that mediation would not stop in any circumstance
<ide><path>rc/main/java/io/aino/agents/wso2/mediator/AinoMediator.java <ide> <ide> @Override <ide> public boolean mediate(MessageContext context) { <del> initTransportHeadersMap(context); <del> <del> <del> Transaction transaction = createTransaction(context); <del> new IdPropertyBuilder(this.idList).buildToContext(context, transaction); <del> <del> processTransaction(context, transaction); <del> logToEsb(context, transaction); <add> try { <add> initTransportHeadersMap(context); <add> <add> <add> Transaction transaction = createTransaction(context); <add> new IdPropertyBuilder(this.idList).buildToContext(context, transaction); <add> <add> processTransaction(context, transaction); <add> logToEsb(context, transaction); <add> } catch (Exception e) { <add> log.error("Error occurred while trying to log to aino.io!", e); <add> } <ide> <ide> return true; <ide> }
Java
apache-2.0
64066bf22d1ca07c153ec6a06e42d844c61c3584
0
SyncFree/SwiftCloud,SyncFree/SwiftCloud,SyncFree/SwiftCloud,SyncFree/SwiftCloud
/***************************************************************************** * Copyright 2011-2012 INRIA * Copyright 2011-2012 Universidade Nova de Lisboa * * 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 swift.client; import java.util.Arrays; 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 java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicLong; import swift.clocks.CausalityClock; import swift.clocks.CausalityClock.CMP_CLOCK; import swift.clocks.ClockFactory; import swift.clocks.IncrementalTripleTimestampGenerator; import swift.clocks.Timestamp; import swift.clocks.TimestampMapping; import swift.clocks.TripleTimestamp; import swift.crdt.CRDTIdentifier; import swift.crdt.interfaces.BulkGetProgressListener; import swift.crdt.interfaces.CRDT; import swift.crdt.interfaces.CRDTUpdate; import swift.crdt.interfaces.CachePolicy; import swift.crdt.interfaces.IsolationLevel; import swift.crdt.interfaces.ObjectUpdatesListener; import swift.crdt.interfaces.TxnHandle; import swift.crdt.interfaces.TxnLocalCRDT; import swift.crdt.interfaces.TxnStatus; import swift.crdt.operations.CRDTObjectUpdatesGroup; import swift.exceptions.NetworkException; import swift.exceptions.NoSuchObjectException; import swift.exceptions.VersionNotFoundException; import swift.exceptions.WrongTypeException; import swift.utils.DummyLog; import swift.utils.TransactionsLog; import sys.utils.Threading; /** * Implementation of abstract SwiftCloud transaction with unspecified isolation * level. It keeps track of its state and mediates between the application and * {@link TxnManager} communicating with the store. Implementations define the * read algorithm for CRDT and transaction dependencies, and should ensure * session guarantees between transactions. * <p> * Transaction is <em>read-only transaction</em> if it does not issue any update * operation; transaction is <em>update transaction</em> otherwise. Update * transaction uses timestamp for its updates. * <p> * A transaction is first locally committed with a client timestamp, and then * globally committed with a stable system timestamp assigned by server to * facilitate efficient timestamps summary. The mapping between these timestamps * is defined within a TimestamMapping object of the transaction. * <p> * This base implementation primarily keeps track of transaction states and * updates on objects. * <p> * Instances shall be generated using and managed by {@link TxnManager} * implementation. Thread-safe. * * @author mzawirski */ abstract class AbstractTxnHandle implements TxnHandle, Comparable<AbstractTxnHandle> { protected final TxnManager manager; protected final boolean readOnly; protected final IsolationLevel isolationLevel; protected CachePolicy cachePolicy; protected final TimestampMapping timestampMapping; protected final CausalityClock updatesDependencyClock; protected final IncrementalTripleTimestampGenerator timestampSource; protected final Map<CRDTIdentifier, CRDTObjectUpdatesGroup<?>> localObjectOperations; protected TxnStatus status; protected CommitListener commitListener; protected final Map<TxnLocalCRDT<?>, ObjectUpdatesListener> objectUpdatesListeners; protected final TransactionsLog durableLog; protected final long id; protected final long serial; protected final String sessionId; protected static final AtomicLong serialGenerator = new AtomicLong(); /** * Creates an update transaction. * * @param manager * manager maintaining this transaction * @param sessionId * id of the client session issuing this transaction * @param durableLog * durable log for recovery * @param cachePolicy * cache policy used by this transaction * @param timestampMapping * timestamp and timestamp mapping information used for all * updates of this transaction */ AbstractTxnHandle(final TxnManager manager, final String sessionId, final TransactionsLog durableLog, final IsolationLevel isolationLevel, final CachePolicy cachePolicy, final TimestampMapping timestampMapping) { this.manager = manager; this.readOnly = false; this.sessionId = sessionId; this.durableLog = durableLog; this.id = timestampMapping.getClientTimestamp().getCounter(); this.isolationLevel = isolationLevel; this.cachePolicy = cachePolicy; this.timestampMapping = timestampMapping; this.updatesDependencyClock = ClockFactory.newClock(); this.timestampSource = new IncrementalTripleTimestampGenerator(timestampMapping); this.localObjectOperations = new HashMap<CRDTIdentifier, CRDTObjectUpdatesGroup<?>>(); this.status = TxnStatus.PENDING; this.objectUpdatesListeners = new HashMap<TxnLocalCRDT<?>, ObjectUpdatesListener>(); this.serial = serialGenerator.getAndIncrement(); } /** * Creates a read-only transaction. * * @param manager * manager maintaining this transaction * @param sessionId * id of the client session issuing this transaction * @param durableLog * durable log for recovery * @param cachePolicy * cache policy used by this transaction */ AbstractTxnHandle(final TxnManager manager, final String sessionId, final IsolationLevel isolationLevel, final CachePolicy cachePolicy) { this.manager = manager; this.readOnly = true; this.sessionId = sessionId; this.durableLog = new DummyLog(); this.id = -1; this.isolationLevel = isolationLevel; this.cachePolicy = cachePolicy; this.timestampMapping = null; this.updatesDependencyClock = ClockFactory.newClock(); this.timestampSource = null; this.localObjectOperations = new HashMap<CRDTIdentifier, CRDTObjectUpdatesGroup<?>>(); this.status = TxnStatus.PENDING; this.objectUpdatesListeners = new HashMap<TxnLocalCRDT<?>, ObjectUpdatesListener>(); this.serial = serialGenerator.getAndIncrement(); } @Override public <V extends CRDT<V>, T extends TxnLocalCRDT<V>> T get(CRDTIdentifier id, boolean create, Class<V> classOfV) throws WrongTypeException, NoSuchObjectException, VersionNotFoundException, NetworkException { return get(id, create, classOfV, null); } @Override @SuppressWarnings("unchecked") public <V extends CRDT<V>, T extends TxnLocalCRDT<V>> T get(CRDTIdentifier id, boolean create, Class<V> classOfV, ObjectUpdatesListener listener) throws WrongTypeException, NoSuchObjectException, VersionNotFoundException, NetworkException { assertStatus(TxnStatus.PENDING); try { if (SwiftImpl.DEFAULT_LISTENER_FOR_GET && listener == null) listener = SwiftImpl.DEFAULT_LISTENER; return getImpl(id, create, classOfV, listener); } catch (ClassCastException x) { throw new WrongTypeException(x.getMessage()); } } @Override public void commit() { final Semaphore commitSem = new Semaphore(0); commitAsync(new CommitListener() { @Override public void onGlobalCommit(TxnHandle transaction) { commitSem.release(); } }); commitSem.acquireUninterruptibly(); } @Override public synchronized void commitAsync(final CommitListener listener) { assertStatus(TxnStatus.PENDING); this.commitListener = listener; manager.commitTxn(this); } @Override public synchronized void rollback() { assertStatus(TxnStatus.PENDING); status = TxnStatus.CANCELLED; logStatusChange(); manager.discardTxn(this); } protected void logStatusChange() { durableLog.writeEntry(getId(), status); } public synchronized TxnStatus getStatus() { return status; } @Override public synchronized TripleTimestamp nextTimestamp() { assertStatus(TxnStatus.PENDING); assertNotReadOnly(); return timestampSource.generateNew(); } @Override public synchronized <V extends CRDT<V>> void registerOperation(CRDTIdentifier id, CRDTUpdate<V> op) { assertStatus(TxnStatus.PENDING); assertNotReadOnly(); @SuppressWarnings("unchecked") CRDTObjectUpdatesGroup<V> operationsGroup = (CRDTObjectUpdatesGroup<V>) localObjectOperations.get(id); if (operationsGroup == null) { operationsGroup = new CRDTObjectUpdatesGroup<V>(id, getTimestampMapping(), null, getUpdatesDependencyClock()); localObjectOperations.put(id, operationsGroup); } operationsGroup.append(op); durableLog.writeEntry(getId(), op); } @Override public synchronized <V extends CRDT<V>> void registerObjectCreation(CRDTIdentifier id, V creationState) { if (isReadOnly()) { return; } final CRDTObjectUpdatesGroup<V> operationsGroup = new CRDTObjectUpdatesGroup<V>(id, timestampMapping, creationState, getUpdatesDependencyClock()); if (localObjectOperations.put(id, operationsGroup) != null) { throw new IllegalStateException("Object creation operation was preceded by some another operation"); } durableLog.writeEntry(getId(), id); } /** * @return timestamp mapping used by all updates of this transaction; note * that it may be mutated */ TimestampMapping getTimestampMapping() { return timestampMapping; } /** * Marks transaction as locally committed. */ synchronized void markLocallyCommitted() { assertStatus(TxnStatus.PENDING); status = TxnStatus.COMMITTED_LOCAL; logStatusChange(); // Flush the log before returning to the client call. durableLog.flush(); } /** * Adds a (new) system timestamp to this transaction and marks transaction * as globally committed. * * @param globalTimestamp * a system timestamp for this transaction; ignored for read-only * transaction */ void markGloballyCommitted(final Timestamp systemTimestamp) { boolean justGloballyCommitted = false; synchronized (this) { assertStatus(TxnStatus.COMMITTED_LOCAL, TxnStatus.COMMITTED_GLOBAL); if (status == TxnStatus.COMMITTED_LOCAL) { justGloballyCommitted = true; status = TxnStatus.COMMITTED_GLOBAL; } if (systemTimestamp != null) { timestampMapping.addSystemTimestamp(systemTimestamp); } } if (systemTimestamp != null) { durableLog.writeEntry(getId(), systemTimestamp); } logStatusChange(); if (justGloballyCommitted) { if (commitListener != null) { // TODO: wouldn't it be safer to call it from a different // thread? commitListener.onGlobalCommit(this); } } } /** * @return true when the transaction is read-only */ boolean isReadOnly() { return readOnly; } /** * @return a collection of update operations group on objects updated by * this transactions; empty for read-only transaction */ synchronized Collection<CRDTObjectUpdatesGroup<?>> getAllUpdates() { assertStatus(TxnStatus.CANCELLED, TxnStatus.COMMITTED_LOCAL, TxnStatus.COMMITTED_GLOBAL); return localObjectOperations.values(); } /** * @return an update operations group on object updated by this transaction; * null if object is not updated by this transaction */ synchronized CRDTObjectUpdatesGroup<?> getObjectUpdates(CRDTIdentifier id) { assertStatus(TxnStatus.COMMITTED_LOCAL, TxnStatus.COMMITTED_GLOBAL); return localObjectOperations.get(id); } synchronized CausalityClock getUpdatesDependencyClock() { return updatesDependencyClock; } String getSessionId() { return sessionId; } /** * Implementation of read request, can use {@link #manager} for that * purposes. Implementation is responsible for maintaining dependency clock * of the transaction using * {@link #updateUpdatesDependencyClock(CausalityClock)} to ensure that it * depends on every version read by the transaction. */ protected abstract <V extends CRDT<V>, T extends TxnLocalCRDT<V>> T getImpl(CRDTIdentifier id, boolean create, Class<V> classOfV, ObjectUpdatesListener updatesListener) throws WrongTypeException, NoSuchObjectException, VersionNotFoundException, NetworkException; /** * Updates dependency clock of the transaction. * * @param clock * clock to include in the dependency clock of this transaction * @throws IllegalStateException * when transaction is not pending or locally committed * @return true if the provided clock included some new events */ protected boolean updateUpdatesDependencyClock(final CausalityClock clock) { assertStatus(TxnStatus.PENDING, TxnStatus.COMMITTED_LOCAL); if (updatesDependencyClock.merge(clock).is(CMP_CLOCK.CMP_CONCURRENT, CMP_CLOCK.CMP_ISDOMINATED)) { durableLog.writeEntry(getId(), clock); return true; } return false; } protected synchronized void assertStatus(final TxnStatus... expectedStatuses) { for (final TxnStatus expectedStatus : expectedStatuses) { if (status == expectedStatus) { return; } } throw new IllegalStateException("Unexpected transaction status: was " + status + ", expected " + Arrays.asList(expectedStatuses)); } protected void assertNotReadOnly() { if (readOnly) { throw new IllegalStateException("update request for read-only transaction"); } } @Override public String toString() { return (readOnly ? "read-only" : "update") + " transaction ts=" + timestampMapping; } protected long getId() { return id; } protected long getSerial() { return serial; } @Override public int compareTo(AbstractTxnHandle o) { return Long.signum(orderingScore() - o.orderingScore()); } private long orderingScore() { return getTimestampMapping() == null ? 0 : getTimestampMapping().getClientTimestamp().getCounter(); } @Override public Map<CRDTIdentifier, TxnLocalCRDT<?>> bulkGet(Set<CRDTIdentifier> ids, final boolean readOnly, long timeout, final BulkGetProgressListener listener) { final Map<CRDTIdentifier, TxnLocalCRDT<?>> res = Collections .synchronizedMap(new HashMap<CRDTIdentifier, TxnLocalCRDT<?>>()); if (ids.isEmpty()) return res; for (final CRDTIdentifier i : ids) execute(new Runnable() { @Override public void run() { TxnLocalCRDT<?> val; try { val = get(i, readOnly, null); res.put(i, val); if (listener != null) listener.onGet(AbstractTxnHandle.this, i, val); } catch (Exception e) { e.printStackTrace(); res.put(i, null); } Threading.synchronizedNotifyAllOn(res); } }); while (res.size() != ids.size()) { Threading.synchronizedWaitOn(res, 100); } return res; } public Map<CRDTIdentifier, TxnLocalCRDT<?>> bulkGet(CRDTIdentifier... crdtIdentifiers) { long timeout = Long.MAX_VALUE; Set<CRDTIdentifier> ids = new HashSet<CRDTIdentifier>(Arrays.asList(crdtIdentifiers)); return this.bulkGet(ids, false, timeout, null); } public IsolationLevel getIsolationLevel() { return isolationLevel; } private void execute(Runnable r) { ((SwiftImpl) manager).execute(r); } }
src-core/swift/client/AbstractTxnHandle.java
/***************************************************************************** * Copyright 2011-2012 INRIA * Copyright 2011-2012 Universidade Nova de Lisboa * * 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 swift.client; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicLong; import swift.clocks.CausalityClock; import swift.clocks.CausalityClock.CMP_CLOCK; import swift.clocks.ClockFactory; import swift.clocks.IncrementalTripleTimestampGenerator; import swift.clocks.Timestamp; import swift.clocks.TimestampMapping; import swift.clocks.TripleTimestamp; import swift.crdt.CRDTIdentifier; import swift.crdt.interfaces.BulkGetProgressListener; import swift.crdt.interfaces.CRDT; import swift.crdt.interfaces.CRDTUpdate; import swift.crdt.interfaces.CachePolicy; import swift.crdt.interfaces.IsolationLevel; import swift.crdt.interfaces.ObjectUpdatesListener; import swift.crdt.interfaces.TxnHandle; import swift.crdt.interfaces.TxnLocalCRDT; import swift.crdt.interfaces.TxnStatus; import swift.crdt.operations.CRDTObjectUpdatesGroup; import swift.exceptions.NetworkException; import swift.exceptions.NoSuchObjectException; import swift.exceptions.VersionNotFoundException; import swift.exceptions.WrongTypeException; import swift.utils.DummyLog; import swift.utils.TransactionsLog; import sys.utils.Threading; /** * Implementation of abstract SwiftCloud transaction with unspecified isolation * level. It keeps track of its state and mediates between the application and * {@link TxnManager} communicating with the store. Implementations define the * read algorithm for CRDT and transaction dependencies, and should ensure * session guarantees between transactions. * <p> * Transaction is <em>read-only transaction</em> if it does not issue any update * operation; transaction is <em>update transaction</em> otherwise. Update * transaction uses timestamp for its updates. * <p> * A transaction is first locally committed with a client timestamp, and then * globally committed with a stable system timestamp assigned by server to * facilitate efficient timestamps summary. The mapping between these timestamps * is defined within a TimestamMapping object of the transaction. * <p> * This base implementation primarily keeps track of transaction states and * updates on objects. * <p> * Instances shall be generated using and managed by {@link TxnManager} * implementation. Thread-safe. * * @author mzawirski */ abstract class AbstractTxnHandle implements TxnHandle, Comparable<AbstractTxnHandle> { protected final TxnManager manager; protected final boolean readOnly; protected final IsolationLevel isolationLevel; protected CachePolicy cachePolicy; protected final TimestampMapping timestampMapping; protected final CausalityClock updatesDependencyClock; protected final IncrementalTripleTimestampGenerator timestampSource; protected final Map<CRDTIdentifier, CRDTObjectUpdatesGroup<?>> localObjectOperations; protected TxnStatus status; protected CommitListener commitListener; protected final Map<TxnLocalCRDT<?>, ObjectUpdatesListener> objectUpdatesListeners; protected final TransactionsLog durableLog; protected final long id; protected final long serial; protected final String sessionId; protected static final AtomicLong serialGenerator = new AtomicLong(); /** * Creates an update transaction. * * @param manager * manager maintaining this transaction * @param sessionId * id of the client session issuing this transaction * @param durableLog * durable log for recovery * @param cachePolicy * cache policy used by this transaction * @param timestampMapping * timestamp and timestamp mapping information used for all * updates of this transaction */ AbstractTxnHandle(final TxnManager manager, final String sessionId, final TransactionsLog durableLog, final IsolationLevel isolationLevel, final CachePolicy cachePolicy, final TimestampMapping timestampMapping) { this.manager = manager; this.readOnly = false; this.sessionId = sessionId; this.durableLog = durableLog; this.id = timestampMapping.getClientTimestamp().getCounter(); this.isolationLevel = isolationLevel; this.cachePolicy = cachePolicy; this.timestampMapping = timestampMapping; this.updatesDependencyClock = ClockFactory.newClock(); this.timestampSource = new IncrementalTripleTimestampGenerator(timestampMapping); this.localObjectOperations = new HashMap<CRDTIdentifier, CRDTObjectUpdatesGroup<?>>(); this.status = TxnStatus.PENDING; this.objectUpdatesListeners = new HashMap<TxnLocalCRDT<?>, ObjectUpdatesListener>(); this.serial = serialGenerator.getAndIncrement(); } /** * Creates a read-only transaction. * * @param manager * manager maintaining this transaction * @param sessionId * id of the client session issuing this transaction * @param durableLog * durable log for recovery * @param cachePolicy * cache policy used by this transaction */ AbstractTxnHandle(final TxnManager manager, final String sessionId, final IsolationLevel isolationLevel, final CachePolicy cachePolicy) { this.manager = manager; this.readOnly = true; this.sessionId = sessionId; this.durableLog = new DummyLog(); this.id = -1; this.isolationLevel = isolationLevel; this.cachePolicy = cachePolicy; this.timestampMapping = null; this.updatesDependencyClock = ClockFactory.newClock(); this.timestampSource = null; this.localObjectOperations = new HashMap<CRDTIdentifier, CRDTObjectUpdatesGroup<?>>(); this.status = TxnStatus.PENDING; this.objectUpdatesListeners = new HashMap<TxnLocalCRDT<?>, ObjectUpdatesListener>(); this.serial = serialGenerator.getAndIncrement(); } @Override public <V extends CRDT<V>, T extends TxnLocalCRDT<V>> T get(CRDTIdentifier id, boolean create, Class<V> classOfV) throws WrongTypeException, NoSuchObjectException, VersionNotFoundException, NetworkException { return get(id, create, classOfV, null); } @Override @SuppressWarnings("unchecked") public <V extends CRDT<V>, T extends TxnLocalCRDT<V>> T get(CRDTIdentifier id, boolean create, Class<V> classOfV, ObjectUpdatesListener listener) throws WrongTypeException, NoSuchObjectException, VersionNotFoundException, NetworkException { assertStatus(TxnStatus.PENDING); try { if (SwiftImpl.DEFAULT_LISTENER_FOR_GET && listener == null) listener = SwiftImpl.DEFAULT_LISTENER; return getImpl(id, create, classOfV, listener); } catch (ClassCastException x) { throw new WrongTypeException(x.getMessage()); } } @Override public void commit() { final Semaphore commitSem = new Semaphore(0); commitAsync(new CommitListener() { @Override public void onGlobalCommit(TxnHandle transaction) { commitSem.release(); } }); commitSem.acquireUninterruptibly(); } @Override public synchronized void commitAsync(final CommitListener listener) { assertStatus(TxnStatus.PENDING); this.commitListener = listener; manager.commitTxn(this); } @Override public synchronized void rollback() { assertStatus(TxnStatus.PENDING); status = TxnStatus.CANCELLED; logStatusChange(); manager.discardTxn(this); } protected void logStatusChange() { durableLog.writeEntry(getId(), status); } public synchronized TxnStatus getStatus() { return status; } @Override public synchronized TripleTimestamp nextTimestamp() { assertStatus(TxnStatus.PENDING); assertNotReadOnly(); return timestampSource.generateNew(); } @Override public synchronized <V extends CRDT<V>> void registerOperation(CRDTIdentifier id, CRDTUpdate<V> op) { assertStatus(TxnStatus.PENDING); assertNotReadOnly(); @SuppressWarnings("unchecked") CRDTObjectUpdatesGroup<V> operationsGroup = (CRDTObjectUpdatesGroup<V>) localObjectOperations.get(id); if (operationsGroup == null) { operationsGroup = new CRDTObjectUpdatesGroup<V>(id, getTimestampMapping(), null, getUpdatesDependencyClock()); localObjectOperations.put(id, operationsGroup); } operationsGroup.append(op); durableLog.writeEntry(getId(), op); } @Override public synchronized <V extends CRDT<V>> void registerObjectCreation(CRDTIdentifier id, V creationState) { if (isReadOnly()) { return; } final CRDTObjectUpdatesGroup<V> operationsGroup = new CRDTObjectUpdatesGroup<V>(id, timestampMapping, creationState, getUpdatesDependencyClock()); if (localObjectOperations.put(id, operationsGroup) != null) { throw new IllegalStateException("Object creation operation was preceded by some another operation"); } durableLog.writeEntry(getId(), id); } /** * @return timestamp mapping used by all updates of this transaction; note * that it may be mutated */ TimestampMapping getTimestampMapping() { return timestampMapping; } /** * Marks transaction as locally committed. */ synchronized void markLocallyCommitted() { assertStatus(TxnStatus.PENDING); status = TxnStatus.COMMITTED_LOCAL; logStatusChange(); // Flush the log before returning to the client call. durableLog.flush(); } /** * Adds a (new) system timestamp to this transaction and marks transaction * as globally committed. * * @param globalTimestamp * a system timestamp for this transaction; ignored for read-only * transaction */ void markGloballyCommitted(final Timestamp systemTimestamp) { boolean justGloballyCommitted = false; synchronized (this) { assertStatus(TxnStatus.COMMITTED_LOCAL, TxnStatus.COMMITTED_GLOBAL); if (status == TxnStatus.COMMITTED_LOCAL) { justGloballyCommitted = true; status = TxnStatus.COMMITTED_GLOBAL; } if (systemTimestamp != null) { timestampMapping.addSystemTimestamp(systemTimestamp); } } if (systemTimestamp != null) { durableLog.writeEntry(getId(), systemTimestamp); } logStatusChange(); if (justGloballyCommitted) { if (commitListener != null) { // TODO: wouldn't it be safer to call it from a different // thread? commitListener.onGlobalCommit(this); } } } /** * @return true when the transaction is read-only */ boolean isReadOnly() { return readOnly; } /** * @return a collection of update operations group on objects updated by * this transactions; empty for read-only transaction */ synchronized Collection<CRDTObjectUpdatesGroup<?>> getAllUpdates() { assertStatus(TxnStatus.CANCELLED, TxnStatus.COMMITTED_LOCAL, TxnStatus.COMMITTED_GLOBAL); return localObjectOperations.values(); } /** * @return an update operations group on object updated by this transaction; * null if object is not updated by this transaction */ synchronized CRDTObjectUpdatesGroup<?> getObjectUpdates(CRDTIdentifier id) { assertStatus(TxnStatus.COMMITTED_LOCAL, TxnStatus.COMMITTED_GLOBAL); return localObjectOperations.get(id); } synchronized CausalityClock getUpdatesDependencyClock() { return updatesDependencyClock; } String getSessionId() { return sessionId; } /** * Implementation of read request, can use {@link #manager} for that * purposes. Implementation is responsible for maintaining dependency clock * of the transaction using * {@link #updateUpdatesDependencyClock(CausalityClock)} to ensure that it * depends on every version read by the transaction. */ protected abstract <V extends CRDT<V>, T extends TxnLocalCRDT<V>> T getImpl(CRDTIdentifier id, boolean create, Class<V> classOfV, ObjectUpdatesListener updatesListener) throws WrongTypeException, NoSuchObjectException, VersionNotFoundException, NetworkException; /** * Updates dependency clock of the transaction. * * @param clock * clock to include in the dependency clock of this transaction * @throws IllegalStateException * when transaction is not pending or locally committed * @return true if the provided clock included some new events */ protected boolean updateUpdatesDependencyClock(final CausalityClock clock) { assertStatus(TxnStatus.PENDING, TxnStatus.COMMITTED_LOCAL); if (updatesDependencyClock.merge(clock).is(CMP_CLOCK.CMP_CONCURRENT, CMP_CLOCK.CMP_ISDOMINATED)) { durableLog.writeEntry(getId(), clock); return true; } return false; } protected synchronized void assertStatus(final TxnStatus... expectedStatuses) { for (final TxnStatus expectedStatus : expectedStatuses) { if (status == expectedStatus) { return; } } throw new IllegalStateException("Unexpected transaction status: was " + status + ", expected " + Arrays.asList(expectedStatuses)); } protected void assertNotReadOnly() { if (readOnly) { throw new IllegalStateException("update request for read-only transaction"); } } @Override public String toString() { return (readOnly ? "read-only" : "update") + " transaction ts=" + timestampMapping; } protected long getId() { return id; } protected long getSerial() { return serial; } @Override public int compareTo(AbstractTxnHandle o) { return Long.signum(orderingScore() - o.orderingScore()); } private long orderingScore() { return getTimestampMapping() == null ? 0 : getTimestampMapping().getClientTimestamp().getCounter(); } @Override public Map<CRDTIdentifier, TxnLocalCRDT<?>> bulkGet(Set<CRDTIdentifier> ids, final boolean readOnly, long timeout, final BulkGetProgressListener listener) { final ConcurrentHashMap<CRDTIdentifier, TxnLocalCRDT<?>> res = new ConcurrentHashMap<CRDTIdentifier, TxnLocalCRDT<?>>(); if (ids.isEmpty()) return res; for (final CRDTIdentifier i : ids) execute(new Runnable() { @Override public void run() { TxnLocalCRDT<?> val; try { val = get(i, readOnly, null); res.put(i, val); if (listener != null) listener.onGet(AbstractTxnHandle.this, i, val); } catch (Exception e) { res.put(i, null); e.printStackTrace(); } Threading.synchronizedNotifyAllOn(res); } }); while (res.size() != ids.size()) { Threading.synchronizedWaitOn(res, 100); } return res; } public Map<CRDTIdentifier, TxnLocalCRDT<?>> bulkGet(CRDTIdentifier... crdtIdentifiers) { long timeout = Long.MAX_VALUE; Set<CRDTIdentifier> ids = new HashSet<CRDTIdentifier>(Arrays.asList(crdtIdentifiers)); return this.bulkGet(ids, false, timeout, null); } public IsolationLevel getIsolationLevel() { return isolationLevel; } private void execute(Runnable r) { ((SwiftImpl) manager).execute(r); } }
Corrected NullPointerException bug on bulkGet. The return map could not store null values to indicate failure to get a crdt...
src-core/swift/client/AbstractTxnHandle.java
Corrected NullPointerException bug on bulkGet.
<ide><path>rc-core/swift/client/AbstractTxnHandle.java <ide> <ide> import java.util.Arrays; <ide> import java.util.Collection; <add>import java.util.Collections; <ide> import java.util.HashMap; <ide> import java.util.HashSet; <ide> import java.util.Map; <ide> import java.util.Set; <del>import java.util.concurrent.ConcurrentHashMap; <ide> import java.util.concurrent.Semaphore; <ide> import java.util.concurrent.atomic.AtomicLong; <ide> <ide> @Override <ide> public Map<CRDTIdentifier, TxnLocalCRDT<?>> bulkGet(Set<CRDTIdentifier> ids, final boolean readOnly, long timeout, <ide> final BulkGetProgressListener listener) { <del> final ConcurrentHashMap<CRDTIdentifier, TxnLocalCRDT<?>> res = new ConcurrentHashMap<CRDTIdentifier, TxnLocalCRDT<?>>(); <add> final Map<CRDTIdentifier, TxnLocalCRDT<?>> res = Collections <add> .synchronizedMap(new HashMap<CRDTIdentifier, TxnLocalCRDT<?>>()); <ide> <ide> if (ids.isEmpty()) <ide> return res; <ide> if (listener != null) <ide> listener.onGet(AbstractTxnHandle.this, i, val); <ide> } catch (Exception e) { <add> e.printStackTrace(); <ide> res.put(i, null); <del> e.printStackTrace(); <ide> } <ide> Threading.synchronizedNotifyAllOn(res); <ide> }
Java
apache-2.0
6a41e85e3c9377ef03587f553d6351d687956a91
0
mglukhikh/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,adedayo/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,caot/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,blademainer/intellij-community,blademainer/intellij-community,allotria/intellij-community,samthor/intellij-community,FHannes/intellij-community,slisson/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,FHannes/intellij-community,kool79/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,kool79/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,samthor/intellij-community,allotria/intellij-community,xfournet/intellij-community,kool79/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,izonder/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,allotria/intellij-community,vladmm/intellij-community,allotria/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,caot/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,da1z/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,adedayo/intellij-community,semonte/intellij-community,allotria/intellij-community,supersven/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,izonder/intellij-community,holmes/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,signed/intellij-community,diorcety/intellij-community,slisson/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,signed/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,izonder/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,hurricup/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,slisson/intellij-community,da1z/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,ryano144/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,diorcety/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,da1z/intellij-community,da1z/intellij-community,fitermay/intellij-community,holmes/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,adedayo/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,supersven/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,caot/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,caot/intellij-community,izonder/intellij-community,holmes/intellij-community,hurricup/intellij-community,signed/intellij-community,jagguli/intellij-community,caot/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,holmes/intellij-community,supersven/intellij-community,signed/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,semonte/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,caot/intellij-community,semonte/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,caot/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,xfournet/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,slisson/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,kdwink/intellij-community,da1z/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,allotria/intellij-community,semonte/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,retomerz/intellij-community,izonder/intellij-community,allotria/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,izonder/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,blademainer/intellij-community,supersven/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,allotria/intellij-community,Lekanich/intellij-community,signed/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,vladmm/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,retomerz/intellij-community,asedunov/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,diorcety/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,apixandru/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,da1z/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,supersven/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,holmes/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,supersven/intellij-community,adedayo/intellij-community,ryano144/intellij-community,ibinti/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,supersven/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,kool79/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,samthor/intellij-community,semonte/intellij-community,kool79/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,vladmm/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,caot/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,slisson/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,semonte/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,kdwink/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,amith01994/intellij-community,amith01994/intellij-community,ryano144/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,caot/intellij-community,nicolargo/intellij-community,slisson/intellij-community,vladmm/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,supersven/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,jagguli/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,holmes/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,semonte/intellij-community,semonte/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,robovm/robovm-studio,signed/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,signed/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,slisson/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,holmes/intellij-community,xfournet/intellij-community,FHannes/intellij-community,samthor/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,caot/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,holmes/intellij-community,robovm/robovm-studio,adedayo/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,samthor/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,holmes/intellij-community,da1z/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,hurricup/intellij-community,retomerz/intellij-community,samthor/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,samthor/intellij-community,fitermay/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,dslomov/intellij-community,asedunov/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,petteyg/intellij-community,blademainer/intellij-community,allotria/intellij-community,slisson/intellij-community,da1z/intellij-community,FHannes/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,da1z/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,amith01994/intellij-community,ryano144/intellij-community,signed/intellij-community,FHannes/intellij-community,retomerz/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,kool79/intellij-community,jagguli/intellij-community,hurricup/intellij-community,da1z/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,vladmm/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,petteyg/intellij-community,kool79/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,fnouama/intellij-community,blademainer/intellij-community,petteyg/intellij-community,signed/intellij-community,tmpgit/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,holmes/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,signed/intellij-community,robovm/robovm-studio,fnouama/intellij-community,fitermay/intellij-community,signed/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,caot/intellij-community,fnouama/intellij-community
/* * User: anna * Date: 29-May-2008 */ package com.intellij.coverage.actions; import com.intellij.codeInsight.hint.HintManager; import com.intellij.codeInsight.hint.ImplementationViewComponent; import com.intellij.coverage.CoverageDataManager; import com.intellij.coverage.CoverageSuite; import com.intellij.coverage.CoverageSuitesBundle; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.PanelWithText; import com.intellij.openapi.ui.popup.ComponentPopupBuilder; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiUtilCore; import com.intellij.rt.coverage.data.LineCoverage; import com.intellij.rt.coverage.data.LineData; import com.intellij.ui.popup.NotLookupOrSearchCondition; import com.intellij.util.ArrayUtil; import com.intellij.util.PlatformIcons; import com.intellij.util.containers.HashSet; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.*; public class ShowCoveringTestsAction extends AnAction { private static final Logger LOG = Logger.getInstance("#" + ShowCoveringTestsAction.class.getName()); private final String myClassFQName; private final LineData myLineData; public ShowCoveringTestsAction(final String classFQName, LineData lineData) { super("Show tests covering line", "Show tests covering line", PlatformIcons.TEST_SOURCE_FOLDER); myClassFQName = classFQName; myLineData = lineData; } public void actionPerformed(final AnActionEvent e) { final DataContext context = e.getDataContext(); final Project project = PlatformDataKeys.PROJECT.getData(context); LOG.assertTrue(project != null); final Editor editor = PlatformDataKeys.EDITOR.getData(context); LOG.assertTrue(editor != null); final CoverageSuitesBundle currentSuite = CoverageDataManager.getInstance(project).getCurrentSuitesBundle(); LOG.assertTrue(currentSuite != null); final File[] traceFiles = getTraceFiles(project); final Set<String> tests = new HashSet<String>(); Runnable runnable = new Runnable() { public void run() { for (File traceFile : traceFiles) { DataInputStream in = null; try { in = new DataInputStream(new FileInputStream(traceFile)); extractTests(traceFile, in, tests); } catch (Exception ex) { LOG.error(traceFile.getName(), ex); } finally { try { in.close(); } catch (IOException ex) { LOG.error(ex); } } } } }; if (ProgressManager.getInstance().runProcessWithProgressSynchronously(runnable, "Extract information about tests", false, project)) { //todo cache them? show nothing found message final String[] testNames = ArrayUtil.toStringArray(tests); Arrays.sort(testNames); if (testNames.length == 0) { HintManager.getInstance().showErrorHint(editor, "Failed to load covered tests"); return; } final List<PsiElement> elements = currentSuite.getCoverageEngine().findTestsByNames(testNames, project); final ImplementationViewComponent component; final String title = "Tests covering line " + myClassFQName + ":" + myLineData.getLineNumber(); final ComponentPopupBuilder popupBuilder; if (!elements.isEmpty()) { component = new ImplementationViewComponent(PsiUtilCore.toPsiElementArray(elements), 0); popupBuilder = JBPopupFactory.getInstance().createComponentPopupBuilder(component, component.getPreferredFocusableComponent()) .setDimensionServiceKey(project, "ShowTestsPopup", false); } else { component = null; final JPanel panel = new PanelWithText("Following test" + (testNames.length > 1 ? "s" : "") + " could not be found: " + StringUtil.join(testNames, ",").replace("_", ".")); popupBuilder = JBPopupFactory.getInstance().createComponentPopupBuilder(panel, null); } final JBPopup popup = popupBuilder.setRequestFocusCondition(project, NotLookupOrSearchCondition.INSTANCE) .setProject(project) .setResizable(true) .setMovable(true) .setTitle(title) .createPopup(); popup.showInBestPositionFor(editor); if (component != null) { component.setHint(popup, title); } } } private void extractTests(final File traceFile, final DataInputStream in, final Set<String> tests) throws IOException { long traceSize = in.readInt(); for (int i = 0; i < traceSize; i++) { final String className = in.readUTF(); final int linesSize = in.readInt(); for(int l = 0; l < linesSize; l++) { final int line = in.readInt(); if (Comparing.strEqual(className, myClassFQName)) { if (myLineData.getLineNumber() == line) { tests.add(FileUtil.getNameWithoutExtension(traceFile)); return; } } } } } @Override public void update(final AnActionEvent e) { final Presentation presentation = e.getPresentation(); presentation.setEnabled(false); if (myLineData != null && myLineData.getStatus() != LineCoverage.NONE) { final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext()); if (project != null) { final File[] files = getTraceFiles(project); if (files != null && files.length > 0) { presentation.setEnabled(CoverageDataManager.getInstance(project).getCurrentSuitesBundle().isCoverageByTestEnabled()); } } } } @Nullable private static File[] getTraceFiles(Project project) { final CoverageSuitesBundle currentSuite = CoverageDataManager.getInstance(project).getCurrentSuitesBundle(); if (currentSuite == null) return null; final List<File> files = new ArrayList<File>(); for (CoverageSuite coverageSuite : currentSuite.getSuites()) { final String filePath = coverageSuite.getCoverageDataFileName(); final String dirName = FileUtil.getNameWithoutExtension(new File(filePath).getName()); final File parentDir = new File(filePath).getParentFile(); final File tracesDir = new File(parentDir, dirName); final File[] suiteFiles = tracesDir.listFiles(); if (suiteFiles != null) { Collections.addAll(files, suiteFiles); } } return files.isEmpty() ? null : files.toArray(new File[files.size()]); } }
plugins/coverage-common/src/com/intellij/coverage/actions/ShowCoveringTestsAction.java
/* * User: anna * Date: 29-May-2008 */ package com.intellij.coverage.actions; import com.intellij.codeInsight.hint.HintManager; import com.intellij.codeInsight.hint.ImplementationViewComponent; import com.intellij.coverage.CoverageDataManager; import com.intellij.coverage.CoverageSuite; import com.intellij.coverage.CoverageSuitesBundle; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.PanelWithText; import com.intellij.openapi.ui.popup.ComponentPopupBuilder; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiUtilCore; import com.intellij.rt.coverage.data.LineCoverage; import com.intellij.rt.coverage.data.LineData; import com.intellij.ui.popup.NotLookupOrSearchCondition; import com.intellij.util.ArrayUtil; import com.intellij.util.PlatformIcons; import com.intellij.util.containers.HashSet; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.*; public class ShowCoveringTestsAction extends AnAction { private static final Logger LOG = Logger.getInstance("#" + ShowCoveringTestsAction.class.getName()); private final String myClassFQName; private final LineData myLineData; public ShowCoveringTestsAction(final String classFQName, LineData lineData) { super("Show tests covering line", "Show tests covering line", PlatformIcons.TEST_SOURCE_FOLDER); myClassFQName = classFQName; myLineData = lineData; } public void actionPerformed(final AnActionEvent e) { final DataContext context = e.getDataContext(); final Project project = PlatformDataKeys.PROJECT.getData(context); LOG.assertTrue(project != null); final Editor editor = PlatformDataKeys.EDITOR.getData(context); LOG.assertTrue(editor != null); final CoverageSuitesBundle currentSuite = CoverageDataManager.getInstance(project).getCurrentSuitesBundle(); LOG.assertTrue(currentSuite != null); final File[] traceFiles = getTraceFiles(project); final Set<String> tests = new HashSet<String>(); Runnable runnable = new Runnable() { public void run() { for (File traceFile : traceFiles) { DataInputStream in = null; try { in = new DataInputStream(new FileInputStream(traceFile)); extractTests(traceFile, in, tests); } catch (Exception ex) { LOG.error(traceFile.getName(), ex); } finally { try { in.close(); } catch (IOException ex) { LOG.error(ex); } } } } }; if (ProgressManager.getInstance().runProcessWithProgressSynchronously(runnable, "Extract information about tests", false, project)) { //todo cache them? show nothing found message final String[] testNames = ArrayUtil.toStringArray(tests); Arrays.sort(testNames); if (testNames.length == 0) { HintManager.getInstance().showErrorHint(editor, "Failed to load covered tests"); return; } final List<PsiElement> elements = currentSuite.getCoverageEngine().findTestsByNames(testNames, project); final ImplementationViewComponent component; final String title = "Tests covering line " + myClassFQName + ":" + myLineData.getLineNumber(); final ComponentPopupBuilder popupBuilder; if (!elements.isEmpty()) { component = new ImplementationViewComponent(PsiUtilCore.toPsiElementArray(elements), 0); popupBuilder = JBPopupFactory.getInstance().createComponentPopupBuilder(component, component.getPrefferedFocusableComponent()) .setDimensionServiceKey(project, "ShowTestsPopup", false); } else { component = null; final JPanel panel = new PanelWithText("Following test" + (testNames.length > 1 ? "s" : "") + " could not be found: " + StringUtil.join(testNames, ",").replace("_", ".")); popupBuilder = JBPopupFactory.getInstance().createComponentPopupBuilder(panel, null); } final JBPopup popup = popupBuilder.setRequestFocusCondition(project, NotLookupOrSearchCondition.INSTANCE) .setProject(project) .setResizable(true) .setMovable(true) .setTitle(title) .createPopup(); popup.showInBestPositionFor(editor); if (component != null) { component.setHint(popup, title); } } } private void extractTests(final File traceFile, final DataInputStream in, final Set<String> tests) throws IOException { long traceSize = in.readInt(); for (int i = 0; i < traceSize; i++) { final String className = in.readUTF(); final int linesSize = in.readInt(); for(int l = 0; l < linesSize; l++) { final int line = in.readInt(); if (Comparing.strEqual(className, myClassFQName)) { if (myLineData.getLineNumber() == line) { tests.add(FileUtil.getNameWithoutExtension(traceFile)); return; } } } } } @Override public void update(final AnActionEvent e) { final Presentation presentation = e.getPresentation(); presentation.setEnabled(false); if (myLineData != null && myLineData.getStatus() != LineCoverage.NONE) { final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext()); if (project != null) { final File[] files = getTraceFiles(project); if (files != null && files.length > 0) { presentation.setEnabled(CoverageDataManager.getInstance(project).getCurrentSuitesBundle().isCoverageByTestEnabled()); } } } } @Nullable private static File[] getTraceFiles(Project project) { final CoverageSuitesBundle currentSuite = CoverageDataManager.getInstance(project).getCurrentSuitesBundle(); if (currentSuite == null) return null; final List<File> files = new ArrayList<File>(); for (CoverageSuite coverageSuite : currentSuite.getSuites()) { final String filePath = coverageSuite.getCoverageDataFileName(); final String dirName = FileUtil.getNameWithoutExtension(new File(filePath).getName()); final File parentDir = new File(filePath).getParentFile(); final File tracesDir = new File(parentDir, dirName); final File[] suiteFiles = tracesDir.listFiles(); if (suiteFiles != null) { Collections.addAll(files, suiteFiles); } } return files.isEmpty() ? null : files.toArray(new File[files.size()]); } }
IDEA-92207 Make it possible to focus QuickView, Diagrams, Show Implementations, etc popups called from lists, trees, etc
plugins/coverage-common/src/com/intellij/coverage/actions/ShowCoveringTestsAction.java
IDEA-92207 Make it possible to focus QuickView, Diagrams, Show Implementations, etc popups called from lists, trees, etc
<ide><path>lugins/coverage-common/src/com/intellij/coverage/actions/ShowCoveringTestsAction.java <ide> final ComponentPopupBuilder popupBuilder; <ide> if (!elements.isEmpty()) { <ide> component = new ImplementationViewComponent(PsiUtilCore.toPsiElementArray(elements), 0); <del> popupBuilder = JBPopupFactory.getInstance().createComponentPopupBuilder(component, component.getPrefferedFocusableComponent()) <add> popupBuilder = JBPopupFactory.getInstance().createComponentPopupBuilder(component, component.getPreferredFocusableComponent()) <ide> .setDimensionServiceKey(project, "ShowTestsPopup", false); <ide> } else { <ide> component = null;
JavaScript
agpl-3.0
649ab26da819738660954d34c506cfd39eaf0bc6
0
lmcro/xo-web,lmcro/xo-web,lmcro/xo-web,vatesfr/xo-web,vatesfr/xo-web
// These global variables are not a problem because the algorithm is // synchronous. let permissionsByObject let getObject // ------------------------------------------------------------------- const authorized = () => true // eslint-disable-line no-unused-vars const forbiddden = () => false // eslint-disable-line no-unused-vars const and = (...checkers) => (object, permission) => { // eslint-disable-line no-unused-vars for (const checker of checkers) { if (!checker(object, permission)) { return false } } return true } const or = (...checkers) => (object, permission) => { // eslint-disable-line no-unused-vars for (const checker of checkers) { if (checker(object, permission)) { return true } } return false } // ------------------------------------------------------------------- const checkMember = memberName => (object, permission) => { const member = object[memberName] return checkAuthorization(member, permission) } const checkSelf = ({ id }, permission) => { const permissionsForObject = permissionsByObject[id] return ( permissionsForObject && permissionsForObject[permission] ) } // =================================================================== const checkAuthorizationByTypes = { host: or(checkSelf, checkMember('$pool')), message: checkMember('$object'), network: or(checkSelf, checkMember('$pool')), SR: or(checkSelf, checkMember('$pool')), task: checkMember('$host'), VBD: checkMember('VDI'), // Access to a VDI is granted if the user has access to the // containing SR or to a linked VM. VDI (vdi, permission) { // Check authorization for the containing SR. if (checkAuthorization(vdi.$SR, permission)) { return true } // Check authorization for each of the connected VMs. for (const vbdId of vdi.$VBDs) { if (checkAuthorization(getObject(vbdId).VM, permission)) { return true } } return false }, 'VDI-snapshot': checkMember('$snapshot_of'), VIF: or(checkMember('$network'), checkMember('$VM')), VM: or(checkSelf, checkMember('$container')), 'VM-snapshot': checkMember('$snapshot_of'), 'VM-template': authorized } // Hoisting is important for this function. function checkAuthorization (objectId, permission) { const object = getObject(objectId) if (!object) { return false } const checker = checkAuthorizationByTypes[object.type] || checkSelf return checker(object, permission) } // ------------------------------------------------------------------- export default ( permissionsByObject_, getObject_, permissions ) => { // Assign global variables. permissionsByObject = permissionsByObject_ getObject = getObject_ try { for (const [objectId, permission] of permissions) { if (!checkAuthorization(objectId, permission)) { return false } } return true } finally { // Free the global variables. permissionsByObject = getObject = null } }
packages/xo-acl-resolver/src/index.js
// These global variables are not a problem because the algorithm is // synchronous. let permissionsByObject let getObject // ------------------------------------------------------------------- const authorized = () => true // eslint-disable-line no-unused-vars const forbiddden = () => false // eslint-disable-line no-unused-vars const and = (...checkers) => (object, permission) => { // eslint-disable-line no-unused-vars for (const checker of checkers) { if (!checker(object, permission)) { return false } } return true } const or = (...checkers) => (object, permission) => { // eslint-disable-line no-unused-vars for (const checker of checkers) { if (checker(object, permission)) { return true } } return false } // ------------------------------------------------------------------- const checkMember = memberName => (object, permission) => { const member = object[memberName] return checkAuthorization(member, permission) } const checkSelf = ({ id }, permission) => { const permissionsForObject = permissionsByObject[id] return ( permissionsForObject && permissionsForObject[permission] ) } // =================================================================== const checkAuthorizationByTypes = { host: or(checkSelf, checkMember('$pool')), message: checkMember('$object'), network: or(checkSelf, checkMember('$pool')), SR: or(checkSelf, checkMember('$pool')), task: checkMember('$host'), VBD: checkMember('VDI'), // Access to a VDI is granted if the user has access to the // containing SR or to a linked VM. VDI (vdi, permission) { // Check authorization for the containing SR. if (checkAuthorization(vdi.$SR, permission)) { return true } // Check authorization for each of the connected VMs. for (const vbdId of vdi.$VBDs) { if (checkAuthorization(getObject(vbdId).VM, permission)) { return true } } return false }, 'VDI-snapshot': checkMember('$snapshot_of'), VIF: or(checkMember('$network'), checkMember('$VM')), VM: or(checkSelf, checkMember('$container')), 'VM-snapshot': checkMember('$snapshot_of'), 'VM-template': authorized } // Hoisting is important for this function. function checkAuthorization (objectId, permission) { const object = getObject(objectId) const checker = checkAuthorizationByTypes[object.type] || checkSelf return checker(object, permission) } // ------------------------------------------------------------------- export default ( permissionsByObject_, getObject_, permissions ) => { // Assign global variables. permissionsByObject = permissionsByObject_ getObject = getObject_ try { for (const [objectId, permission] of permissions) { if (!checkAuthorization(objectId, permission)) { return false } } return true } finally { // Free the global variables. permissionsByObject = getObject = null } }
feat: gracefully handle missing objects
packages/xo-acl-resolver/src/index.js
feat: gracefully handle missing objects
<ide><path>ackages/xo-acl-resolver/src/index.js <ide> // Hoisting is important for this function. <ide> function checkAuthorization (objectId, permission) { <ide> const object = getObject(objectId) <add> if (!object) { <add> return false <add> } <add> <ide> const checker = checkAuthorizationByTypes[object.type] || checkSelf <ide> <ide> return checker(object, permission)
Java
mit
2fa21a82a2298344a47a296cc4a02c2f6d2c84bc
0
yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods
// Identifier.java // // (c) 1999-2000 PAL Development Core Team // // This package may be distributed under the // terms of the Lesser GNU General Public License (LGPL) package net.maizegenetics.pal.ids; import java.io.Serializable; import net.maizegenetics.prefs.TasselPrefs; /** * An identifier for some sampled data. This will most often be for example, the * accession number of a DNA sequence, or the taxonomic name that the sequence * represents, et cetera. * * @author terry */ public class Identifier implements Serializable, Comparable { private static final long serialVersionUID = -7873729831795750538L; public static final String DELIMITER = ":"; private final String myName; private final String[] myNameTokens; public static Identifier ANONYMOUS = new Identifier(""); public Identifier(String name) { myName = name; myNameTokens = name.split(DELIMITER); } public static Identifier getMergedInstance(Identifier id1, Identifier id2) { String[] first = id1.getFullNameTokens(); String[] second = id2.getFullNameTokens(); int count = Math.min(first.length, second.length); for (int i = 0; i < count; i++) { if (!first[i].equals(second[i])) { StringBuilder builder = new StringBuilder(); for (int x = 0; x < i; x++) { if (x != 0) { builder.append(DELIMITER); } builder.append(first[x]); return new Identifier(builder.toString()); } } } return id1; } public String toString() { return getName(); } // implements Comparable interface @Override public int compareTo(Object c) { if (c instanceof Identifier) { return compareTo(((Identifier) c).getFullNameTokens()); } else { throw new ClassCastException(); } } @Override public boolean equals(Object c) { TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES type = TasselPrefs.getIDJoinStrict(); if (c instanceof Identifier) { if (type == TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES.Strict) { return getFullName().equals(((Identifier) c).getFullName()); } else { return compareTo(c) == 0; } } else if (c instanceof String) { if (type == TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES.Strict) { return getFullName().equals(((String) c)); } else { return compareTo((String) c) == 0; } } else { return false; } } public int compareTo(String c) { return compareTo(c.split(DELIMITER)); } public int compareTo(String[] fullNameTokens) { TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES type = TasselPrefs.getIDJoinStrict(); int count = Math.min(myNameTokens.length, fullNameTokens.length); if (type == TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES.NumLevels) { count = Math.min(count, TasselPrefs.getIDJoinNumLevels()); } for (int i = 0; i < count; i++) { int current = myNameTokens[i].compareTo(fullNameTokens[i]); if (current != 0) { return current; } } if (type == TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES.Strict) { if (myNameTokens.length < fullNameTokens.length) { return -1; } else if (fullNameTokens.length < myNameTokens.length) { return 1; } else { return 0; } } else { return 0; } } public String getName() { return getNameLevel(0); } public String getFullName() { return myName; } public String getFullName(String delimiter) { if (delimiter.equals(DELIMITER)) { return myName; } return myName.replaceAll(DELIMITER, delimiter); } public String[] getFullNameTokens() { return myNameTokens; } /** * Returns requested level of name starting at index 0. 0 will generally be * most specific classification. * * @param index * @return Specified level. */ public String getNameLevel(int index) { if (index < myNameTokens.length) { return myNameTokens[index]; } return null; } /** * Returns name up to specified level (not including specified level. Levels * start at index 0. * * @param index * @return name up to specified level exclusive. */ public String getNameToLevel(int index) { return getNameToLevel(index, DELIMITER); } public String getNameToLevel(int index, String delimiter) { int upto = 0; if (index > myNameTokens.length) { upto = myNameTokens.length; } else { upto = index; } if (upto == 0) { return null; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < upto; i++) { if (i != 0) { builder.append(delimiter); } builder.append(myNameTokens[i]); } return builder.toString(); } /** * Returns number of name levels. * * @return number of name levels. */ public int getNumNameLevels() { return myNameTokens.length; } }
src/net/maizegenetics/pal/ids/Identifier.java
// Identifier.java // // (c) 1999-2000 PAL Development Core Team // // This package may be distributed under the // terms of the Lesser GNU General Public License (LGPL) package net.maizegenetics.pal.ids; import java.io.Serializable; import net.maizegenetics.prefs.TasselPrefs; /** * An identifier for some sampled data. This will most often be for example, the * accession number of a DNA sequence, or the taxonomic name that the sequence * represents, et cetera. * * @author terry */ public class Identifier implements Serializable, Comparable { private static final long serialVersionUID = -7873729831795750538L; public static final String DELIMITER = ":"; private final String myName; public static Identifier ANONYMOUS = new Identifier(""); public Identifier(String name) { myName = name; } public static Identifier getMergedInstance(Identifier id1, Identifier id2) { String[] first = id1.getFullName().split(DELIMITER); String[] second = id2.getFullName().split(DELIMITER); int count = Math.min(first.length, second.length); for (int i = 0; i < count; i++) { if (!first[i].equals(second[i])) { StringBuilder builder = new StringBuilder(); for (int x = 0; x < i; x++) { if (x != 0) { builder.append(DELIMITER); } builder.append(first[x]); return new Identifier(builder.toString()); } } } return id1; } public String toString() { return getName(); } // implements Comparable interface @Override public int compareTo(Object c) { if (c instanceof Identifier) { return compareTo(((Identifier) c).getFullName()); } else { throw new ClassCastException(); } } @Override public boolean equals(Object c) { TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES type = TasselPrefs.getIDJoinStrict(); if (c instanceof Identifier) { if (type == TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES.Strict) { return getFullName().equals(((Identifier) c).getFullName()); } else { return compareTo(c) == 0; } } else if (c instanceof String) { if (type == TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES.Strict) { return getFullName().equals(((String) c)); } else { return compareTo((String) c) == 0; } } else { return false; } } public int compareTo(String c) { TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES type = TasselPrefs.getIDJoinStrict(); String[] first = myName.split(DELIMITER); //these split commands are taking 99% of time, when testing a 32K taxa set String[] second = c.split(DELIMITER); //these split commands are taking 99% of time, when testing a 32K taxa set int count = Math.min(first.length, second.length); if (type == TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES.NumLevels) { count = Math.min(count, TasselPrefs.getIDJoinNumLevels()); } for (int i = 0; i < count; i++) { int current = first[i].compareTo(second[i]); if (current != 0) { return current; } } if (type == TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES.Strict) { if (first.length < second.length) { return -1; } else if (second.length < first.length) { return 1; } else { return 0; } } else { return 0; } } public String getName() { return getNameLevel(0); } public String getFullName() { return myName; } public String getFullName(String delimiter) { if (delimiter.equals(DELIMITER)) { return myName; } return myName.replaceAll(DELIMITER, delimiter); } /** * Returns requested level of name starting at index 0. 0 will generally be * most specific classification. * * @param index * @return Specified level. */ public String getNameLevel(int index) { String[] temp = myName.split(DELIMITER); if (index < temp.length) { return temp[index]; } return null; } /** * Returns name up to specified level (not including specified level. Levels * start at index 0. * * @param index * @return name up to specified level exclusive. */ public String getNameToLevel(int index) { return getNameToLevel(index, DELIMITER); } public String getNameToLevel(int index, String delimiter) { String[] temp = myName.split(DELIMITER); int upto = 0; if (index > temp.length) { upto = temp.length; } else { upto = index; } if (upto == 0) { return null; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < upto; i++) { if (i != 0) { builder.append(delimiter); } builder.append(temp[i]); } return builder.toString(); } /** * Returns number of name levels. * * @return number of name levels. */ public int getNumNameLevels() { return myName.split(DELIMITER).length; } }
Redesigned Identifier class to store both full name and tokens for efficient matching… myName = name; myNameTokens = name.split(DELIMITER);
src/net/maizegenetics/pal/ids/Identifier.java
Redesigned Identifier class to store both full name and tokens for efficient matching… myName = name; myNameTokens = name.split(DELIMITER);
<ide><path>rc/net/maizegenetics/pal/ids/Identifier.java <ide> private static final long serialVersionUID = -7873729831795750538L; <ide> public static final String DELIMITER = ":"; <ide> private final String myName; <add> private final String[] myNameTokens; <ide> public static Identifier ANONYMOUS = new Identifier(""); <ide> <ide> public Identifier(String name) { <ide> myName = name; <add> myNameTokens = name.split(DELIMITER); <ide> } <ide> <ide> public static Identifier getMergedInstance(Identifier id1, Identifier id2) { <del> String[] first = id1.getFullName().split(DELIMITER); <del> String[] second = id2.getFullName().split(DELIMITER); <add> String[] first = id1.getFullNameTokens(); <add> String[] second = id2.getFullNameTokens(); <ide> int count = Math.min(first.length, second.length); <ide> for (int i = 0; i < count; i++) { <ide> if (!first[i].equals(second[i])) { <ide> @Override <ide> public int compareTo(Object c) { <ide> if (c instanceof Identifier) { <del> return compareTo(((Identifier) c).getFullName()); <add> return compareTo(((Identifier) c).getFullNameTokens()); <ide> } else { <ide> throw new ClassCastException(); <ide> } <ide> } <ide> <ide> public int compareTo(String c) { <add> return compareTo(c.split(DELIMITER)); <add> } <add> <add> public int compareTo(String[] fullNameTokens) { <ide> <ide> TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES type = TasselPrefs.getIDJoinStrict(); <ide> <del> String[] first = myName.split(DELIMITER); //these split commands are taking 99% of time, when testing a 32K taxa set <del> String[] second = c.split(DELIMITER); //these split commands are taking 99% of time, when testing a 32K taxa set <del> int count = Math.min(first.length, second.length); <add> int count = Math.min(myNameTokens.length, fullNameTokens.length); <ide> if (type == TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES.NumLevels) { <ide> count = Math.min(count, TasselPrefs.getIDJoinNumLevels()); <ide> } <ide> for (int i = 0; i < count; i++) { <del> int current = first[i].compareTo(second[i]); <add> int current = myNameTokens[i].compareTo(fullNameTokens[i]); <ide> if (current != 0) { <ide> return current; <ide> } <ide> } <ide> <ide> if (type == TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES.Strict) { <del> if (first.length < second.length) { <add> if (myNameTokens.length < fullNameTokens.length) { <ide> return -1; <del> } else if (second.length < first.length) { <add> } else if (fullNameTokens.length < myNameTokens.length) { <ide> return 1; <ide> } else { <ide> return 0; <ide> return myName.replaceAll(DELIMITER, delimiter); <ide> } <ide> <add> public String[] getFullNameTokens() { <add> return myNameTokens; <add> } <add> <ide> /** <ide> * Returns requested level of name starting at index 0. 0 will generally be <ide> * most specific classification. <ide> * @return Specified level. <ide> */ <ide> public String getNameLevel(int index) { <del> String[] temp = myName.split(DELIMITER); <del> if (index < temp.length) { <del> return temp[index]; <add> if (index < myNameTokens.length) { <add> return myNameTokens[index]; <ide> } <ide> return null; <ide> } <ide> <ide> public String getNameToLevel(int index, String delimiter) { <ide> <del> String[] temp = myName.split(DELIMITER); <ide> int upto = 0; <del> if (index > temp.length) { <del> upto = temp.length; <add> if (index > myNameTokens.length) { <add> upto = myNameTokens.length; <ide> } else { <ide> upto = index; <ide> } <ide> if (i != 0) { <ide> builder.append(delimiter); <ide> } <del> builder.append(temp[i]); <add> builder.append(myNameTokens[i]); <ide> } <ide> <ide> return builder.toString(); <ide> * @return number of name levels. <ide> */ <ide> public int getNumNameLevels() { <del> return myName.split(DELIMITER).length; <add> return myNameTokens.length; <ide> } <ide> }