lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java
|
apache-2.0
|
23ddf8bc53725cf396dbf338a197fe766a2869f4
| 0 |
Fsero/elasticsearch,tkssharma/elasticsearch,vvcephei/elasticsearch,lydonchandra/elasticsearch,sdauletau/elasticsearch,Clairebi/ElasticsearchClone,brandonkearby/elasticsearch,hirdesh2008/elasticsearch,Flipkart/elasticsearch,StefanGor/elasticsearch,ZTE-PaaS/elasticsearch,pranavraman/elasticsearch,onegambler/elasticsearch,ulkas/elasticsearch,koxa29/elasticsearch,JervyShi/elasticsearch,iamjakob/elasticsearch,strapdata/elassandra,markwalkom/elasticsearch,codebunt/elasticsearch,Chhunlong/elasticsearch,SergVro/elasticsearch,TonyChai24/ESSource,adrianbk/elasticsearch,hanst/elasticsearch,cwurm/elasticsearch,skearns64/elasticsearch,Asimov4/elasticsearch,nknize/elasticsearch,jimhooker2002/elasticsearch,iantruslove/elasticsearch,MetSystem/elasticsearch,thecocce/elasticsearch,StefanGor/elasticsearch,szroland/elasticsearch,petmit/elasticsearch,onegambler/elasticsearch,MaineC/elasticsearch,djschny/elasticsearch,MjAbuz/elasticsearch,AndreKR/elasticsearch,F0lha/elasticsearch,hechunwen/elasticsearch,zeroctu/elasticsearch,knight1128/elasticsearch,amit-shar/elasticsearch,skearns64/elasticsearch,GlenRSmith/elasticsearch,zhaocloud/elasticsearch,ricardocerq/elasticsearch,onegambler/elasticsearch,trangvh/elasticsearch,mapr/elasticsearch,kkirsche/elasticsearch,andrestc/elasticsearch,adrianbk/elasticsearch,jimczi/elasticsearch,luiseduardohdbackup/elasticsearch,Kakakakakku/elasticsearch,lks21c/elasticsearch,liweinan0423/elasticsearch,robin13/elasticsearch,yongminxia/elasticsearch,achow/elasticsearch,mgalushka/elasticsearch,dpursehouse/elasticsearch,mbrukman/elasticsearch,nomoa/elasticsearch,cnfire/elasticsearch-1,mmaracic/elasticsearch,davidvgalbraith/elasticsearch,Collaborne/elasticsearch,Siddartha07/elasticsearch,hydro2k/elasticsearch,mm0/elasticsearch,liweinan0423/elasticsearch,Liziyao/elasticsearch,dantuffery/elasticsearch,Chhunlong/elasticsearch,jeteve/elasticsearch,alexshadow007/elasticsearch,rento19962/elasticsearch,amaliujia/elasticsearch,salyh/elasticsearch,scorpionvicky/elasticsearch,ydsakyclguozi/elasticsearch,Stacey-Gammon/elasticsearch,Charlesdong/elasticsearch,snikch/elasticsearch,Charlesdong/elasticsearch,nazarewk/elasticsearch,artnowo/elasticsearch,scorpionvicky/elasticsearch,kingaj/elasticsearch,janmejay/elasticsearch,brwe/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,aparo/elasticsearch,xingguang2013/elasticsearch,andrewvc/elasticsearch,amit-shar/elasticsearch,strapdata/elassandra-test,pranavraman/elasticsearch,milodky/elasticsearch,mohsinh/elasticsearch,combinatorist/elasticsearch,girirajsharma/elasticsearch,fubuki/elasticsearch,lmtwga/elasticsearch,abibell/elasticsearch,MetSystem/elasticsearch,Flipkart/elasticsearch,drewr/elasticsearch,cnfire/elasticsearch-1,pranavraman/elasticsearch,MisterAndersen/elasticsearch,pozhidaevak/elasticsearch,kingaj/elasticsearch,ThalaivaStars/OrgRepo1,mmaracic/elasticsearch,zhiqinghuang/elasticsearch,knight1128/elasticsearch,petmit/elasticsearch,abibell/elasticsearch,mikemccand/elasticsearch,nknize/elasticsearch,gmarz/elasticsearch,petabytedata/elasticsearch,henakamaMSFT/elasticsearch,kubum/elasticsearch,rhoml/elasticsearch,dantuffery/elasticsearch,lzo/elasticsearch-1,baishuo/elasticsearch_v2.1.0-baishuo,SergVro/elasticsearch,zhaocloud/elasticsearch,chirilo/elasticsearch,nknize/elasticsearch,ivansun1010/elasticsearch,kingaj/elasticsearch,marcuswr/elasticsearch-dateline,hirdesh2008/elasticsearch,jprante/elasticsearch,Rygbee/elasticsearch,Uiho/elasticsearch,zhiqinghuang/elasticsearch,fred84/elasticsearch,zhiqinghuang/elasticsearch,salyh/elasticsearch,KimTaehee/elasticsearch,mrorii/elasticsearch,springning/elasticsearch,LeoYao/elasticsearch,zkidkid/elasticsearch,queirozfcom/elasticsearch,chrismwendt/elasticsearch,easonC/elasticsearch,hirdesh2008/elasticsearch,brwe/elasticsearch,strapdata/elassandra5-rc,markwalkom/elasticsearch,mute/elasticsearch,henakamaMSFT/elasticsearch,salyh/elasticsearch,fred84/elasticsearch,naveenhooda2000/elasticsearch,s1monw/elasticsearch,lightslife/elasticsearch,wbowling/elasticsearch,ThiagoGarciaAlves/elasticsearch,kubum/elasticsearch,gingerwizard/elasticsearch,abibell/elasticsearch,elancom/elasticsearch,zkidkid/elasticsearch,MisterAndersen/elasticsearch,khiraiwa/elasticsearch,dataduke/elasticsearch,easonC/elasticsearch,fernandozhu/elasticsearch,dataduke/elasticsearch,mjhennig/elasticsearch,mortonsykes/elasticsearch,yuy168/elasticsearch,lks21c/elasticsearch,mapr/elasticsearch,mute/elasticsearch,himanshuag/elasticsearch,libosu/elasticsearch,nellicus/elasticsearch,sdauletau/elasticsearch,myelin/elasticsearch,dongjoon-hyun/elasticsearch,pablocastro/elasticsearch,btiernay/elasticsearch,scottsom/elasticsearch,smflorentino/elasticsearch,karthikjaps/elasticsearch,hafkensite/elasticsearch,jimhooker2002/elasticsearch,VukDukic/elasticsearch,mm0/elasticsearch,szroland/elasticsearch,szroland/elasticsearch,ESamir/elasticsearch,jimhooker2002/elasticsearch,kaneshin/elasticsearch,ZTE-PaaS/elasticsearch,masaruh/elasticsearch,acchen97/elasticsearch,phani546/elasticsearch,apepper/elasticsearch,peschlowp/elasticsearch,pritishppai/elasticsearch,xingguang2013/elasticsearch,Ansh90/elasticsearch,mortonsykes/elasticsearch,a2lin/elasticsearch,andrestc/elasticsearch,masterweb121/elasticsearch,umeshdangat/elasticsearch,jimhooker2002/elasticsearch,jpountz/elasticsearch,trangvh/elasticsearch,humandb/elasticsearch,golubev/elasticsearch,kenshin233/elasticsearch,hirdesh2008/elasticsearch,huypx1292/elasticsearch,hafkensite/elasticsearch,brwe/elasticsearch,yynil/elasticsearch,palecur/elasticsearch,golubev/elasticsearch,episerver/elasticsearch,yongminxia/elasticsearch,markllama/elasticsearch,mcku/elasticsearch,jsgao0/elasticsearch,jpountz/elasticsearch,spiegela/elasticsearch,Collaborne/elasticsearch,mmaracic/elasticsearch,mapr/elasticsearch,kkirsche/elasticsearch,Ansh90/elasticsearch,smflorentino/elasticsearch,ivansun1010/elasticsearch,diendt/elasticsearch,Uiho/elasticsearch,wittyameta/elasticsearch,himanshuag/elasticsearch,fubuki/elasticsearch,opendatasoft/elasticsearch,jimhooker2002/elasticsearch,jeteve/elasticsearch,sauravmondallive/elasticsearch,ImpressTV/elasticsearch,robin13/elasticsearch,i-am-Nathan/elasticsearch,rhoml/elasticsearch,libosu/elasticsearch,andrestc/elasticsearch,yynil/elasticsearch,xingguang2013/elasticsearch,ydsakyclguozi/elasticsearch,yanjunh/elasticsearch,KimTaehee/elasticsearch,Widen/elasticsearch,lchennup/elasticsearch,golubev/elasticsearch,mm0/elasticsearch,golubev/elasticsearch,koxa29/elasticsearch,luiseduardohdbackup/elasticsearch,hirdesh2008/elasticsearch,myelin/elasticsearch,markharwood/elasticsearch,mjason3/elasticsearch,kimimj/elasticsearch,amit-shar/elasticsearch,anti-social/elasticsearch,vroyer/elasticassandra,Chhunlong/elasticsearch,slavau/elasticsearch,peschlowp/elasticsearch,andrewvc/elasticsearch,gfyoung/elasticsearch,fernandozhu/elasticsearch,wimvds/elasticsearch,NBSW/elasticsearch,yanjunh/elasticsearch,springning/elasticsearch,IanvsPoplicola/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,kevinkluge/elasticsearch,Liziyao/elasticsearch,ESamir/elasticsearch,apepper/elasticsearch,sneivandt/elasticsearch,NBSW/elasticsearch,heng4fun/elasticsearch,combinatorist/elasticsearch,alexbrasetvik/elasticsearch,acchen97/elasticsearch,yuy168/elasticsearch,HarishAtGitHub/elasticsearch,lchennup/elasticsearch,andrejserafim/elasticsearch,brandonkearby/elasticsearch,ouyangkongtong/elasticsearch,Flipkart/elasticsearch,zeroctu/elasticsearch,ydsakyclguozi/elasticsearch,nilabhsagar/elasticsearch,pablocastro/elasticsearch,obourgain/elasticsearch,xpandan/elasticsearch,qwerty4030/elasticsearch,a2lin/elasticsearch,SergVro/elasticsearch,petabytedata/elasticsearch,huanzhong/elasticsearch,truemped/elasticsearch,gingerwizard/elasticsearch,hanswang/elasticsearch,petabytedata/elasticsearch,EasonYi/elasticsearch,MichaelLiZhou/elasticsearch,ydsakyclguozi/elasticsearch,mrorii/elasticsearch,kubum/elasticsearch,Collaborne/elasticsearch,smflorentino/elasticsearch,bestwpw/elasticsearch,hechunwen/elasticsearch,fforbeck/elasticsearch,winstonewert/elasticsearch,AleksKochev/elasticsearch,Kakakakakku/elasticsearch,kalburgimanjunath/elasticsearch,springning/elasticsearch,AshishThakur/elasticsearch,humandb/elasticsearch,vorce/es-metrics,khiraiwa/elasticsearch,nrkkalyan/elasticsearch,kalimatas/elasticsearch,winstonewert/elasticsearch,fekaputra/elasticsearch,TonyChai24/ESSource,jw0201/elastic,schonfeld/elasticsearch,jchampion/elasticsearch,markllama/elasticsearch,rajanm/elasticsearch,mm0/elasticsearch,diendt/elasticsearch,wangtuo/elasticsearch,LewayneNaidoo/elasticsearch,thecocce/elasticsearch,ckclark/elasticsearch,jpountz/elasticsearch,Chhunlong/elasticsearch,mcku/elasticsearch,palecur/elasticsearch,pritishppai/elasticsearch,huypx1292/elasticsearch,shreejay/elasticsearch,pritishppai/elasticsearch,truemped/elasticsearch,wuranbo/elasticsearch,gfyoung/elasticsearch,brwe/elasticsearch,MaineC/elasticsearch,iamjakob/elasticsearch,mkis-/elasticsearch,kimimj/elasticsearch,apepper/elasticsearch,ouyangkongtong/elasticsearch,kalimatas/elasticsearch,hirdesh2008/elasticsearch,diendt/elasticsearch,socialrank/elasticsearch,jeteve/elasticsearch,feiqitian/elasticsearch,henakamaMSFT/elasticsearch,wimvds/elasticsearch,nrkkalyan/elasticsearch,rento19962/elasticsearch,PhaedrusTheGreek/elasticsearch,truemped/elasticsearch,Charlesdong/elasticsearch,ThalaivaStars/OrgRepo1,SaiprasadKrishnamurthy/elasticsearch,wuranbo/elasticsearch,jw0201/elastic,slavau/elasticsearch,likaiwalkman/elasticsearch,nezirus/elasticsearch,yongminxia/elasticsearch,zeroctu/elasticsearch,hanswang/elasticsearch,linglaiyao1314/elasticsearch,phani546/elasticsearch,Shekharrajak/elasticsearch,alexbrasetvik/elasticsearch,strapdata/elassandra-test,njlawton/elasticsearch,18098924759/elasticsearch,HarishAtGitHub/elasticsearch,gmarz/elasticsearch,rento19962/elasticsearch,pranavraman/elasticsearch,jw0201/elastic,sreeramjayan/elasticsearch,jbertouch/elasticsearch,glefloch/elasticsearch,dataduke/elasticsearch,loconsolutions/elasticsearch,masaruh/elasticsearch,iantruslove/elasticsearch,pablocastro/elasticsearch,geidies/elasticsearch,adrianbk/elasticsearch,alexbrasetvik/elasticsearch,s1monw/elasticsearch,vietlq/elasticsearch,LewayneNaidoo/elasticsearch,ImpressTV/elasticsearch,fekaputra/elasticsearch,artnowo/elasticsearch,geidies/elasticsearch,VukDukic/elasticsearch,avikurapati/elasticsearch,Shekharrajak/elasticsearch,markllama/elasticsearch,bestwpw/elasticsearch,Fsero/elasticsearch,janmejay/elasticsearch,weipinghe/elasticsearch,achow/elasticsearch,rhoml/elasticsearch,vroyer/elassandra,maddin2016/elasticsearch,strapdata/elassandra-test,ulkas/elasticsearch,Chhunlong/elasticsearch,njlawton/elasticsearch,LeoYao/elasticsearch,overcome/elasticsearch,elasticdog/elasticsearch,rmuir/elasticsearch,jbertouch/elasticsearch,andrejserafim/elasticsearch,scorpionvicky/elasticsearch,markwalkom/elasticsearch,javachengwc/elasticsearch,artnowo/elasticsearch,uschindler/elasticsearch,caengcjd/elasticsearch,mbrukman/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,ImpressTV/elasticsearch,martinstuga/elasticsearch,likaiwalkman/elasticsearch,fred84/elasticsearch,tsohil/elasticsearch,tsohil/elasticsearch,martinstuga/elasticsearch,dylan8902/elasticsearch,Stacey-Gammon/elasticsearch,NBSW/elasticsearch,gingerwizard/elasticsearch,franklanganke/elasticsearch,sauravmondallive/elasticsearch,aparo/elasticsearch,kevinkluge/elasticsearch,mute/elasticsearch,huanzhong/elasticsearch,aparo/elasticsearch,strapdata/elassandra5-rc,18098924759/elasticsearch,libosu/elasticsearch,sdauletau/elasticsearch,wangtuo/elasticsearch,tsohil/elasticsearch,khiraiwa/elasticsearch,kubum/elasticsearch,gingerwizard/elasticsearch,truemped/elasticsearch,infusionsoft/elasticsearch,mcku/elasticsearch,snikch/elasticsearch,ckclark/elasticsearch,overcome/elasticsearch,episerver/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,MetSystem/elasticsearch,chrismwendt/elasticsearch,LewayneNaidoo/elasticsearch,myelin/elasticsearch,wbowling/elasticsearch,socialrank/elasticsearch,jimczi/elasticsearch,yongminxia/elasticsearch,kkirsche/elasticsearch,mohit/elasticsearch,linglaiyao1314/elasticsearch,kenshin233/elasticsearch,sreeramjayan/elasticsearch,tkssharma/elasticsearch,jsgao0/elasticsearch,yuy168/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,masterweb121/elasticsearch,huanzhong/elasticsearch,aglne/elasticsearch,lightslife/elasticsearch,petabytedata/elasticsearch,mkis-/elasticsearch,likaiwalkman/elasticsearch,sauravmondallive/elasticsearch,zhiqinghuang/elasticsearch,yongminxia/elasticsearch,dataduke/elasticsearch,uboness/elasticsearch,areek/elasticsearch,kubum/elasticsearch,dylan8902/elasticsearch,micpalmia/elasticsearch,rlugojr/elasticsearch,dongaihua/highlight-elasticsearch,markwalkom/elasticsearch,huypx1292/elasticsearch,henakamaMSFT/elasticsearch,tebriel/elasticsearch,masterweb121/elasticsearch,tebriel/elasticsearch,adrianbk/elasticsearch,mjason3/elasticsearch,marcuswr/elasticsearch-dateline,MisterAndersen/elasticsearch,YosuaMichael/elasticsearch,a2lin/elasticsearch,elancom/elasticsearch,maddin2016/elasticsearch,jaynblue/elasticsearch,elancom/elasticsearch,Shekharrajak/elasticsearch,mrorii/elasticsearch,alexbrasetvik/elasticsearch,djschny/elasticsearch,kubum/elasticsearch,Fsero/elasticsearch,ckclark/elasticsearch,Ansh90/elasticsearch,PhaedrusTheGreek/elasticsearch,libosu/elasticsearch,andrestc/elasticsearch,aparo/elasticsearch,kimimj/elasticsearch,iantruslove/elasticsearch,wittyameta/elasticsearch,himanshuag/elasticsearch,kingaj/elasticsearch,i-am-Nathan/elasticsearch,wimvds/elasticsearch,wenpos/elasticsearch,iacdingping/elasticsearch,djschny/elasticsearch,iantruslove/elasticsearch,truemped/elasticsearch,rmuir/elasticsearch,polyfractal/elasticsearch,Clairebi/ElasticsearchClone,dongaihua/highlight-elasticsearch,camilojd/elasticsearch,kcompher/elasticsearch,likaiwalkman/elasticsearch,alexkuk/elasticsearch,linglaiyao1314/elasticsearch,queirozfcom/elasticsearch,Stacey-Gammon/elasticsearch,wittyameta/elasticsearch,nknize/elasticsearch,nellicus/elasticsearch,overcome/elasticsearch,ulkas/elasticsearch,onegambler/elasticsearch,cnfire/elasticsearch-1,cnfire/elasticsearch-1,linglaiyao1314/elasticsearch,humandb/elasticsearch,rmuir/elasticsearch,kunallimaye/elasticsearch,vietlq/elasticsearch,jeteve/elasticsearch,NBSW/elasticsearch,sarwarbhuiyan/elasticsearch,naveenhooda2000/elasticsearch,diendt/elasticsearch,hafkensite/elasticsearch,njlawton/elasticsearch,easonC/elasticsearch,StefanGor/elasticsearch,heng4fun/elasticsearch,Microsoft/elasticsearch,dylan8902/elasticsearch,vinsonlou/elasticsearch,himanshuag/elasticsearch,kingaj/elasticsearch,kcompher/elasticsearch,infusionsoft/elasticsearch,sjohnr/elasticsearch,davidvgalbraith/elasticsearch,KimTaehee/elasticsearch,YosuaMichael/elasticsearch,strapdata/elassandra5-rc,acchen97/elasticsearch,vinsonlou/elasticsearch,wimvds/elasticsearch,andrewvc/elasticsearch,nellicus/elasticsearch,davidvgalbraith/elasticsearch,thecocce/elasticsearch,lzo/elasticsearch-1,VukDukic/elasticsearch,mm0/elasticsearch,sc0ttkclark/elasticsearch,mkis-/elasticsearch,episerver/elasticsearch,sarwarbhuiyan/elasticsearch,mcku/elasticsearch,girirajsharma/elasticsearch,vvcephei/elasticsearch,mgalushka/elasticsearch,qwerty4030/elasticsearch,apepper/elasticsearch,feiqitian/elasticsearch,hanswang/elasticsearch,kimimj/elasticsearch,Widen/elasticsearch,alexkuk/elasticsearch,markharwood/elasticsearch,MjAbuz/elasticsearch,Ansh90/elasticsearch,ricardocerq/elasticsearch,sc0ttkclark/elasticsearch,pranavraman/elasticsearch,jbertouch/elasticsearch,wayeast/elasticsearch,mute/elasticsearch,rajanm/elasticsearch,tahaemin/elasticsearch,wbowling/elasticsearch,JSCooke/elasticsearch,abibell/elasticsearch,sposam/elasticsearch,rmuir/elasticsearch,jprante/elasticsearch,Helen-Zhao/elasticsearch,TonyChai24/ESSource,naveenhooda2000/elasticsearch,heng4fun/elasticsearch,AshishThakur/elasticsearch,masterweb121/elasticsearch,Charlesdong/elasticsearch,mmaracic/elasticsearch,ThiagoGarciaAlves/elasticsearch,cwurm/elasticsearch,amit-shar/elasticsearch,gingerwizard/elasticsearch,koxa29/elasticsearch,mrorii/elasticsearch,MisterAndersen/elasticsearch,mute/elasticsearch,yynil/elasticsearch,sauravmondallive/elasticsearch,nomoa/elasticsearch,robin13/elasticsearch,jaynblue/elasticsearch,kunallimaye/elasticsearch,ImpressTV/elasticsearch,rlugojr/elasticsearch,shreejay/elasticsearch,feiqitian/elasticsearch,luiseduardohdbackup/elasticsearch,sjohnr/elasticsearch,vvcephei/elasticsearch,zeroctu/elasticsearch,elancom/elasticsearch,Liziyao/elasticsearch,kenshin233/elasticsearch,easonC/elasticsearch,ESamir/elasticsearch,GlenRSmith/elasticsearch,mortonsykes/elasticsearch,hanst/elasticsearch,markwalkom/elasticsearch,Collaborne/elasticsearch,HarishAtGitHub/elasticsearch,wangtuo/elasticsearch,koxa29/elasticsearch,gmarz/elasticsearch,schonfeld/elasticsearch,ThiagoGarciaAlves/elasticsearch,vietlq/elasticsearch,nellicus/elasticsearch,vrkansagara/elasticsearch,bawse/elasticsearch,chirilo/elasticsearch,likaiwalkman/elasticsearch,AshishThakur/elasticsearch,brandonkearby/elasticsearch,ImpressTV/elasticsearch,NBSW/elasticsearch,micpalmia/elasticsearch,lydonchandra/elasticsearch,nilabhsagar/elasticsearch,mikemccand/elasticsearch,18098924759/elasticsearch,franklanganke/elasticsearch,smflorentino/elasticsearch,iantruslove/elasticsearch,lmtwga/elasticsearch,gingerwizard/elasticsearch,infusionsoft/elasticsearch,TonyChai24/ESSource,sreeramjayan/elasticsearch,lks21c/elasticsearch,Collaborne/elasticsearch,sc0ttkclark/elasticsearch,jprante/elasticsearch,girirajsharma/elasticsearch,alexkuk/elasticsearch,artnowo/elasticsearch,adrianbk/elasticsearch,kalburgimanjunath/elasticsearch,xpandan/elasticsearch,geidies/elasticsearch,palecur/elasticsearch,ajhalani/elasticsearch,clintongormley/elasticsearch,areek/elasticsearch,vrkansagara/elasticsearch,VukDukic/elasticsearch,chrismwendt/elasticsearch,Brijeshrpatel9/elasticsearch,mm0/elasticsearch,alexshadow007/elasticsearch,jango2015/elasticsearch,nazarewk/elasticsearch,likaiwalkman/elasticsearch,mjason3/elasticsearch,snikch/elasticsearch,nilabhsagar/elasticsearch,yuy168/elasticsearch,avikurapati/elasticsearch,amit-shar/elasticsearch,girirajsharma/elasticsearch,KimTaehee/elasticsearch,dongjoon-hyun/elasticsearch,opendatasoft/elasticsearch,markllama/elasticsearch,wuranbo/elasticsearch,bawse/elasticsearch,wangyuxue/elasticsearch,tsohil/elasticsearch,pozhidaevak/elasticsearch,MichaelLiZhou/elasticsearch,GlenRSmith/elasticsearch,Ansh90/elasticsearch,MichaelLiZhou/elasticsearch,snikch/elasticsearch,kcompher/elasticsearch,JSCooke/elasticsearch,sdauletau/elasticsearch,brandonkearby/elasticsearch,hechunwen/elasticsearch,AndreKR/elasticsearch,hanst/elasticsearch,lmtwga/elasticsearch,MjAbuz/elasticsearch,raishiv/elasticsearch,iantruslove/elasticsearch,lightslife/elasticsearch,yynil/elasticsearch,gfyoung/elasticsearch,mohit/elasticsearch,sdauletau/elasticsearch,TonyChai24/ESSource,beiske/elasticsearch,lchennup/elasticsearch,IanvsPoplicola/elasticsearch,janmejay/elasticsearch,synhershko/elasticsearch,jpountz/elasticsearch,Uiho/elasticsearch,elancom/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,sreeramjayan/elasticsearch,ricardocerq/elasticsearch,elasticdog/elasticsearch,maddin2016/elasticsearch,wayeast/elasticsearch,Uiho/elasticsearch,koxa29/elasticsearch,easonC/elasticsearch,Flipkart/elasticsearch,gfyoung/elasticsearch,yuy168/elasticsearch,yongminxia/elasticsearch,JSCooke/elasticsearch,umeshdangat/elasticsearch,abibell/elasticsearch,Ansh90/elasticsearch,pritishppai/elasticsearch,pozhidaevak/elasticsearch,mnylen/elasticsearch,jsgao0/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,likaiwalkman/elasticsearch,YosuaMichael/elasticsearch,myelin/elasticsearch,fooljohnny/elasticsearch,MjAbuz/elasticsearch,obourgain/elasticsearch,milodky/elasticsearch,jsgao0/elasticsearch,gfyoung/elasticsearch,Siddartha07/elasticsearch,ouyangkongtong/elasticsearch,vingupta3/elasticsearch,mbrukman/elasticsearch,himanshuag/elasticsearch,pablocastro/elasticsearch,andrejserafim/elasticsearch,feiqitian/elasticsearch,rento19962/elasticsearch,infusionsoft/elasticsearch,JervyShi/elasticsearch,vorce/es-metrics,rlugojr/elasticsearch,alexksikes/elasticsearch,LeoYao/elasticsearch,ivansun1010/elasticsearch,mgalushka/elasticsearch,elasticdog/elasticsearch,spiegela/elasticsearch,lzo/elasticsearch-1,lmtwga/elasticsearch,snikch/elasticsearch,geidies/elasticsearch,ajhalani/elasticsearch,phani546/elasticsearch,weipinghe/elasticsearch,Brijeshrpatel9/elasticsearch,fernandozhu/elasticsearch,SergVro/elasticsearch,jaynblue/elasticsearch,mcku/elasticsearch,combinatorist/elasticsearch,Liziyao/elasticsearch,bestwpw/elasticsearch,apepper/elasticsearch,mgalushka/elasticsearch,mikemccand/elasticsearch,amaliujia/elasticsearch,scottsom/elasticsearch,tahaemin/elasticsearch,ajhalani/elasticsearch,karthikjaps/elasticsearch,Asimov4/elasticsearch,LewayneNaidoo/elasticsearch,wenpos/elasticsearch,AndreKR/elasticsearch,strapdata/elassandra-test,sc0ttkclark/elasticsearch,iantruslove/elasticsearch,codebunt/elasticsearch,yynil/elasticsearch,Siddartha07/elasticsearch,tkssharma/elasticsearch,JackyMai/elasticsearch,Shekharrajak/elasticsearch,strapdata/elassandra,MisterAndersen/elasticsearch,Charlesdong/elasticsearch,uschindler/elasticsearch,obourgain/elasticsearch,TonyChai24/ESSource,HarishAtGitHub/elasticsearch,mkis-/elasticsearch,kkirsche/elasticsearch,TonyChai24/ESSource,kcompher/elasticsearch,pranavraman/elasticsearch,dylan8902/elasticsearch,dylan8902/elasticsearch,liweinan0423/elasticsearch,zeroctu/elasticsearch,ouyangkongtong/elasticsearch,palecur/elasticsearch,sposam/elasticsearch,polyfractal/elasticsearch,sjohnr/elasticsearch,ydsakyclguozi/elasticsearch,kaneshin/elasticsearch,ivansun1010/elasticsearch,weipinghe/elasticsearch,palecur/elasticsearch,libosu/elasticsearch,chrismwendt/elasticsearch,bestwpw/elasticsearch,diendt/elasticsearch,girirajsharma/elasticsearch,kimimj/elasticsearch,kcompher/elasticsearch,phani546/elasticsearch,uschindler/elasticsearch,masterweb121/elasticsearch,wbowling/elasticsearch,Siddartha07/elasticsearch,dataduke/elasticsearch,weipinghe/elasticsearch,HarishAtGitHub/elasticsearch,mrorii/elasticsearch,awislowski/elasticsearch,mjhennig/elasticsearch,mikemccand/elasticsearch,areek/elasticsearch,fred84/elasticsearch,alexksikes/elasticsearch,kevinkluge/elasticsearch,Rygbee/elasticsearch,boliza/elasticsearch,strapdata/elassandra,Shepard1212/elasticsearch,vingupta3/elasticsearch,StefanGor/elasticsearch,raishiv/elasticsearch,lydonchandra/elasticsearch,i-am-Nathan/elasticsearch,LewayneNaidoo/elasticsearch,wittyameta/elasticsearch,scorpionvicky/elasticsearch,jaynblue/elasticsearch,sreeramjayan/elasticsearch,lzo/elasticsearch-1,szroland/elasticsearch,markharwood/elasticsearch,kimimj/elasticsearch,nazarewk/elasticsearch,hechunwen/elasticsearch,javachengwc/elasticsearch,marcuswr/elasticsearch-dateline,jeteve/elasticsearch,nellicus/elasticsearch,Charlesdong/elasticsearch,golubev/elasticsearch,lzo/elasticsearch-1,beiske/elasticsearch,pablocastro/elasticsearch,knight1128/elasticsearch,smflorentino/elasticsearch,djschny/elasticsearch,mohit/elasticsearch,kalimatas/elasticsearch,a2lin/elasticsearch,jsgao0/elasticsearch,pablocastro/elasticsearch,qwerty4030/elasticsearch,apepper/elasticsearch,loconsolutions/elasticsearch,scorpionvicky/elasticsearch,socialrank/elasticsearch,andrestc/elasticsearch,camilojd/elasticsearch,Clairebi/ElasticsearchClone,kunallimaye/elasticsearch,robin13/elasticsearch,naveenhooda2000/elasticsearch,thecocce/elasticsearch,djschny/elasticsearch,amit-shar/elasticsearch,alexbrasetvik/elasticsearch,kingaj/elasticsearch,Brijeshrpatel9/elasticsearch,glefloch/elasticsearch,iamjakob/elasticsearch,nrkkalyan/elasticsearch,huypx1292/elasticsearch,robin13/elasticsearch,huypx1292/elasticsearch,vvcephei/elasticsearch,codebunt/elasticsearch,sc0ttkclark/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,huypx1292/elasticsearch,milodky/elasticsearch,nazarewk/elasticsearch,s1monw/elasticsearch,abhijitiitr/es,shreejay/elasticsearch,rajanm/elasticsearch,kevinkluge/elasticsearch,mcku/elasticsearch,sc0ttkclark/elasticsearch,zkidkid/elasticsearch,tkssharma/elasticsearch,achow/elasticsearch,infusionsoft/elasticsearch,zhiqinghuang/elasticsearch,btiernay/elasticsearch,micpalmia/elasticsearch,queirozfcom/elasticsearch,Widen/elasticsearch,episerver/elasticsearch,hafkensite/elasticsearch,dantuffery/elasticsearch,jchampion/elasticsearch,xuzha/elasticsearch,iamjakob/elasticsearch,coding0011/elasticsearch,18098924759/elasticsearch,18098924759/elasticsearch,camilojd/elasticsearch,mute/elasticsearch,vorce/es-metrics,boliza/elasticsearch,kcompher/elasticsearch,markharwood/elasticsearch,dylan8902/elasticsearch,nezirus/elasticsearch,dongjoon-hyun/elasticsearch,onegambler/elasticsearch,jbertouch/elasticsearch,F0lha/elasticsearch,mrorii/elasticsearch,Ansh90/elasticsearch,beiske/elasticsearch,mapr/elasticsearch,Uiho/elasticsearch,JackyMai/elasticsearch,amaliujia/elasticsearch,alexksikes/elasticsearch,dantuffery/elasticsearch,Shekharrajak/elasticsearch,golubev/elasticsearch,wangyuxue/elasticsearch,kkirsche/elasticsearch,wittyameta/elasticsearch,martinstuga/elasticsearch,ThiagoGarciaAlves/elasticsearch,overcome/elasticsearch,wuranbo/elasticsearch,wittyameta/elasticsearch,rlugojr/elasticsearch,kalimatas/elasticsearch,Brijeshrpatel9/elasticsearch,iamjakob/elasticsearch,andrestc/elasticsearch,javachengwc/elasticsearch,djschny/elasticsearch,a2lin/elasticsearch,karthikjaps/elasticsearch,marcuswr/elasticsearch-dateline,vrkansagara/elasticsearch,abhijitiitr/es,clintongormley/elasticsearch,jw0201/elastic,boliza/elasticsearch,phani546/elasticsearch,MetSystem/elasticsearch,IanvsPoplicola/elasticsearch,yynil/elasticsearch,bawse/elasticsearch,kenshin233/elasticsearch,awislowski/elasticsearch,phani546/elasticsearch,F0lha/elasticsearch,JervyShi/elasticsearch,mohsinh/elasticsearch,kevinkluge/elasticsearch,mjhennig/elasticsearch,xpandan/elasticsearch,areek/elasticsearch,hanswang/elasticsearch,alexkuk/elasticsearch,wittyameta/elasticsearch,polyfractal/elasticsearch,hydro2k/elasticsearch,beiske/elasticsearch,lmtwga/elasticsearch,dpursehouse/elasticsearch,nezirus/elasticsearch,snikch/elasticsearch,milodky/elasticsearch,lightslife/elasticsearch,IanvsPoplicola/elasticsearch,Widen/elasticsearch,dongjoon-hyun/elasticsearch,sscarduzio/elasticsearch,jbertouch/elasticsearch,rhoml/elasticsearch,raishiv/elasticsearch,iamjakob/elasticsearch,bawse/elasticsearch,franklanganke/elasticsearch,EasonYi/elasticsearch,shreejay/elasticsearch,yanjunh/elasticsearch,markharwood/elasticsearch,Microsoft/elasticsearch,hanst/elasticsearch,Fsero/elasticsearch,scottsom/elasticsearch,hydro2k/elasticsearch,markharwood/elasticsearch,rajanm/elasticsearch,slavau/elasticsearch,franklanganke/elasticsearch,strapdata/elassandra5-rc,achow/elasticsearch,Kakakakakku/elasticsearch,fforbeck/elasticsearch,i-am-Nathan/elasticsearch,IanvsPoplicola/elasticsearch,sauravmondallive/elasticsearch,caengcjd/elasticsearch,pozhidaevak/elasticsearch,wayeast/elasticsearch,slavau/elasticsearch,drewr/elasticsearch,HarishAtGitHub/elasticsearch,beiske/elasticsearch,PhaedrusTheGreek/elasticsearch,ydsakyclguozi/elasticsearch,MetSystem/elasticsearch,petmit/elasticsearch,khiraiwa/elasticsearch,rento19962/elasticsearch,alexkuk/elasticsearch,Flipkart/elasticsearch,franklanganke/elasticsearch,lydonchandra/elasticsearch,nellicus/elasticsearch,njlawton/elasticsearch,hirdesh2008/elasticsearch,naveenhooda2000/elasticsearch,raishiv/elasticsearch,wimvds/elasticsearch,kimchy/elasticsearch,jchampion/elasticsearch,btiernay/elasticsearch,fubuki/elasticsearch,Liziyao/elasticsearch,cnfire/elasticsearch-1,jaynblue/elasticsearch,zeroctu/elasticsearch,tsohil/elasticsearch,alexshadow007/elasticsearch,hafkensite/elasticsearch,tcucchietti/elasticsearch,kevinkluge/elasticsearch,loconsolutions/elasticsearch,gingerwizard/elasticsearch,clintongormley/elasticsearch,GlenRSmith/elasticsearch,kimimj/elasticsearch,tkssharma/elasticsearch,iacdingping/elasticsearch,AshishThakur/elasticsearch,xpandan/elasticsearch,yanjunh/elasticsearch,JervyShi/elasticsearch,Rygbee/elasticsearch,koxa29/elasticsearch,winstonewert/elasticsearch,jimczi/elasticsearch,btiernay/elasticsearch,kunallimaye/elasticsearch,lmtwga/elasticsearch,dpursehouse/elasticsearch,HarishAtGitHub/elasticsearch,cnfire/elasticsearch-1,s1monw/elasticsearch,springning/elasticsearch,vietlq/elasticsearch,combinatorist/elasticsearch,jpountz/elasticsearch,zhaocloud/elasticsearch,kalimatas/elasticsearch,hanst/elasticsearch,qwerty4030/elasticsearch,mkis-/elasticsearch,vroyer/elassandra,vroyer/elasticassandra,ajhalani/elasticsearch,MjAbuz/elasticsearch,onegambler/elasticsearch,KimTaehee/elasticsearch,kalburgimanjunath/elasticsearch,andrejserafim/elasticsearch,fooljohnny/elasticsearch,lydonchandra/elasticsearch,chirilo/elasticsearch,Rygbee/elasticsearch,petabytedata/elasticsearch,Chhunlong/elasticsearch,Asimov4/elasticsearch,humandb/elasticsearch,masaruh/elasticsearch,springning/elasticsearch,Stacey-Gammon/elasticsearch,glefloch/elasticsearch,knight1128/elasticsearch,18098924759/elasticsearch,peschlowp/elasticsearch,petabytedata/elasticsearch,mjason3/elasticsearch,fooljohnny/elasticsearch,sposam/elasticsearch,lightslife/elasticsearch,PhaedrusTheGreek/elasticsearch,lchennup/elasticsearch,drewr/elasticsearch,VukDukic/elasticsearch,ivansun1010/elasticsearch,markllama/elasticsearch,iacdingping/elasticsearch,Siddartha07/elasticsearch,sposam/elasticsearch,sposam/elasticsearch,mmaracic/elasticsearch,anti-social/elasticsearch,gmarz/elasticsearch,wayeast/elasticsearch,onegambler/elasticsearch,vingupta3/elasticsearch,MaineC/elasticsearch,camilojd/elasticsearch,glefloch/elasticsearch,xuzha/elasticsearch,socialrank/elasticsearch,elasticdog/elasticsearch,PhaedrusTheGreek/elasticsearch,zhaocloud/elasticsearch,kingaj/elasticsearch,nrkkalyan/elasticsearch,pritishppai/elasticsearch,mohit/elasticsearch,hafkensite/elasticsearch,lightslife/elasticsearch,jango2015/elasticsearch,elancom/elasticsearch,wayeast/elasticsearch,lmtwga/elasticsearch,smflorentino/elasticsearch,sscarduzio/elasticsearch,xuzha/elasticsearch,vrkansagara/elasticsearch,Fsero/elasticsearch,GlenRSmith/elasticsearch,huanzhong/elasticsearch,xpandan/elasticsearch,rajanm/elasticsearch,jpountz/elasticsearch,wangtuo/elasticsearch,ZTE-PaaS/elasticsearch,tcucchietti/elasticsearch,Liziyao/elasticsearch,Helen-Zhao/elasticsearch,vingupta3/elasticsearch,pablocastro/elasticsearch,amaliujia/elasticsearch,rmuir/elasticsearch,aglne/elasticsearch,zkidkid/elasticsearch,javachengwc/elasticsearch,martinstuga/elasticsearch,Liziyao/elasticsearch,alexbrasetvik/elasticsearch,mcku/elasticsearch,sjohnr/elasticsearch,jprante/elasticsearch,humandb/elasticsearch,tkssharma/elasticsearch,maddin2016/elasticsearch,alexshadow007/elasticsearch,wbowling/elasticsearch,mkis-/elasticsearch,nomoa/elasticsearch,nilabhsagar/elasticsearch,kalburgimanjunath/elasticsearch,caengcjd/elasticsearch,MjAbuz/elasticsearch,schonfeld/elasticsearch,peschlowp/elasticsearch,mm0/elasticsearch,karthikjaps/elasticsearch,ZTE-PaaS/elasticsearch,avikurapati/elasticsearch,Siddartha07/elasticsearch,avikurapati/elasticsearch,sarwarbhuiyan/elasticsearch,cwurm/elasticsearch,andrejserafim/elasticsearch,fekaputra/elasticsearch,caengcjd/elasticsearch,jango2015/elasticsearch,zeroctu/elasticsearch,lzo/elasticsearch-1,maddin2016/elasticsearch,dongjoon-hyun/elasticsearch,mapr/elasticsearch,wenpos/elasticsearch,masterweb121/elasticsearch,strapdata/elassandra5-rc,MichaelLiZhou/elasticsearch,humandb/elasticsearch,kaneshin/elasticsearch,synhershko/elasticsearch,clintongormley/elasticsearch,fekaputra/elasticsearch,vingupta3/elasticsearch,Kakakakakku/elasticsearch,queirozfcom/elasticsearch,vroyer/elassandra,overcome/elasticsearch,milodky/elasticsearch,khiraiwa/elasticsearch,truemped/elasticsearch,heng4fun/elasticsearch,linglaiyao1314/elasticsearch,Collaborne/elasticsearch,nilabhsagar/elasticsearch,trangvh/elasticsearch,lydonchandra/elasticsearch,C-Bish/elasticsearch,codebunt/elasticsearch,brwe/elasticsearch,nomoa/elasticsearch,gmarz/elasticsearch,tahaemin/elasticsearch,abhijitiitr/es,diendt/elasticsearch,Shekharrajak/elasticsearch,knight1128/elasticsearch,awislowski/elasticsearch,MichaelLiZhou/elasticsearch,achow/elasticsearch,ckclark/elasticsearch,EasonYi/elasticsearch,dpursehouse/elasticsearch,abibell/elasticsearch,loconsolutions/elasticsearch,coding0011/elasticsearch,khiraiwa/elasticsearch,markwalkom/elasticsearch,vvcephei/elasticsearch,karthikjaps/elasticsearch,mapr/elasticsearch,Brijeshrpatel9/elasticsearch,opendatasoft/elasticsearch,hechunwen/elasticsearch,aglne/elasticsearch,mjhennig/elasticsearch,fforbeck/elasticsearch,ThalaivaStars/OrgRepo1,fubuki/elasticsearch,KimTaehee/elasticsearch,lchennup/elasticsearch,wenpos/elasticsearch,tahaemin/elasticsearch,AleksKochev/elasticsearch,kenshin233/elasticsearch,kkirsche/elasticsearch,loconsolutions/elasticsearch,kimchy/elasticsearch,socialrank/elasticsearch,KimTaehee/elasticsearch,caengcjd/elasticsearch,ThalaivaStars/OrgRepo1,ulkas/elasticsearch,MichaelLiZhou/elasticsearch,jimczi/elasticsearch,yanjunh/elasticsearch,chirilo/elasticsearch,iacdingping/elasticsearch,YosuaMichael/elasticsearch,tebriel/elasticsearch,ulkas/elasticsearch,sjohnr/elasticsearch,iamjakob/elasticsearch,schonfeld/elasticsearch,YosuaMichael/elasticsearch,umeshdangat/elasticsearch,fred84/elasticsearch,mnylen/elasticsearch,girirajsharma/elasticsearch,AshishThakur/elasticsearch,JackyMai/elasticsearch,pranavraman/elasticsearch,janmejay/elasticsearch,strapdata/elassandra,Kakakakakku/elasticsearch,wangyuxue/elasticsearch,ivansun1010/elasticsearch,EasonYi/elasticsearch,dpursehouse/elasticsearch,micpalmia/elasticsearch,caengcjd/elasticsearch,kalburgimanjunath/elasticsearch,ouyangkongtong/elasticsearch,himanshuag/elasticsearch,elasticdog/elasticsearch,javachengwc/elasticsearch,HonzaKral/elasticsearch,fekaputra/elasticsearch,martinstuga/elasticsearch,tebriel/elasticsearch,mgalushka/elasticsearch,vorce/es-metrics,ThiagoGarciaAlves/elasticsearch,Uiho/elasticsearch,nezirus/elasticsearch,Brijeshrpatel9/elasticsearch,mortonsykes/elasticsearch,vrkansagara/elasticsearch,polyfractal/elasticsearch,xingguang2013/elasticsearch,Shepard1212/elasticsearch,andrejserafim/elasticsearch,mjhennig/elasticsearch,tcucchietti/elasticsearch,sarwarbhuiyan/elasticsearch,fforbeck/elasticsearch,F0lha/elasticsearch,JervyShi/elasticsearch,slavau/elasticsearch,njlawton/elasticsearch,lchennup/elasticsearch,skearns64/elasticsearch,andrestc/elasticsearch,AleksKochev/elasticsearch,slavau/elasticsearch,jw0201/elastic,kenshin233/elasticsearch,overcome/elasticsearch,sscarduzio/elasticsearch,LeoYao/elasticsearch,bestwpw/elasticsearch,socialrank/elasticsearch,Shepard1212/elasticsearch,sposam/elasticsearch,geidies/elasticsearch,iacdingping/elasticsearch,springning/elasticsearch,C-Bish/elasticsearch,xingguang2013/elasticsearch,mbrukman/elasticsearch,MaineC/elasticsearch,tebriel/elasticsearch,jaynblue/elasticsearch,abibell/elasticsearch,queirozfcom/elasticsearch,tcucchietti/elasticsearch,ulkas/elasticsearch,javachengwc/elasticsearch,lks21c/elasticsearch,spiegela/elasticsearch,beiske/elasticsearch,zhaocloud/elasticsearch,hydro2k/elasticsearch,bestwpw/elasticsearch,strapdata/elassandra-test,abhijitiitr/es,lightslife/elasticsearch,jango2015/elasticsearch,aglne/elasticsearch,markllama/elasticsearch,ImpressTV/elasticsearch,Fsero/elasticsearch,marcuswr/elasticsearch-dateline,LeoYao/elasticsearch,polyfractal/elasticsearch,mohsinh/elasticsearch,bestwpw/elasticsearch,trangvh/elasticsearch,EasonYi/elasticsearch,boliza/elasticsearch,Clairebi/ElasticsearchClone,sneivandt/elasticsearch,xuzha/elasticsearch,i-am-Nathan/elasticsearch,cwurm/elasticsearch,Microsoft/elasticsearch,mohsinh/elasticsearch,knight1128/elasticsearch,vrkansagara/elasticsearch,abhijitiitr/es,infusionsoft/elasticsearch,jw0201/elastic,Clairebi/ElasticsearchClone,ouyangkongtong/elasticsearch,episerver/elasticsearch,huanzhong/elasticsearch,jeteve/elasticsearch,hanswang/elasticsearch,Rygbee/elasticsearch,acchen97/elasticsearch,wayeast/elasticsearch,combinatorist/elasticsearch,mjhennig/elasticsearch,ThalaivaStars/OrgRepo1,sscarduzio/elasticsearch,wimvds/elasticsearch,SergVro/elasticsearch,rmuir/elasticsearch,djschny/elasticsearch,mortonsykes/elasticsearch,weipinghe/elasticsearch,tcucchietti/elasticsearch,JackyMai/elasticsearch,PhaedrusTheGreek/elasticsearch,rajanm/elasticsearch,lchennup/elasticsearch,18098924759/elasticsearch,rhoml/elasticsearch,coding0011/elasticsearch,sauravmondallive/elasticsearch,dylan8902/elasticsearch,adrianbk/elasticsearch,davidvgalbraith/elasticsearch,fubuki/elasticsearch,areek/elasticsearch,Shepard1212/elasticsearch,feiqitian/elasticsearch,btiernay/elasticsearch,lmenezes/elasticsearch,AleksKochev/elasticsearch,MetSystem/elasticsearch,tsohil/elasticsearch,strapdata/elassandra,cnfire/elasticsearch-1,HonzaKral/elasticsearch,linglaiyao1314/elasticsearch,wenpos/elasticsearch,himanshuag/elasticsearch,luiseduardohdbackup/elasticsearch,Charlesdong/elasticsearch,clintongormley/elasticsearch,schonfeld/elasticsearch,queirozfcom/elasticsearch,amaliujia/elasticsearch,fernandozhu/elasticsearch,C-Bish/elasticsearch,Fsero/elasticsearch,pritishppai/elasticsearch,drewr/elasticsearch,fooljohnny/elasticsearch,kaneshin/elasticsearch,luiseduardohdbackup/elasticsearch,NBSW/elasticsearch,mgalushka/elasticsearch,MjAbuz/elasticsearch,mnylen/elasticsearch,acchen97/elasticsearch,masaruh/elasticsearch,henakamaMSFT/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,spiegela/elasticsearch,uboness/elasticsearch,glefloch/elasticsearch,EasonYi/elasticsearch,tkssharma/elasticsearch,davidvgalbraith/elasticsearch,anti-social/elasticsearch,ckclark/elasticsearch,strapdata/elassandra-test,ricardocerq/elasticsearch,wuranbo/elasticsearch,uboness/elasticsearch,AndreKR/elasticsearch,Asimov4/elasticsearch,kevinkluge/elasticsearch,camilojd/elasticsearch,springning/elasticsearch,Clairebi/ElasticsearchClone,rento19962/elasticsearch,iacdingping/elasticsearch,rlugojr/elasticsearch,franklanganke/elasticsearch,alexksikes/elasticsearch,drewr/elasticsearch,dantuffery/elasticsearch,uboness/elasticsearch,szroland/elasticsearch,knight1128/elasticsearch,infusionsoft/elasticsearch,Siddartha07/elasticsearch,avikurapati/elasticsearch,kalburgimanjunath/elasticsearch,bawse/elasticsearch,hydro2k/elasticsearch,SergVro/elasticsearch,spiegela/elasticsearch,C-Bish/elasticsearch,Brijeshrpatel9/elasticsearch,xingguang2013/elasticsearch,acchen97/elasticsearch,peschlowp/elasticsearch,tebriel/elasticsearch,JSCooke/elasticsearch,dataduke/elasticsearch,Flipkart/elasticsearch,kaneshin/elasticsearch,codebunt/elasticsearch,sreeramjayan/elasticsearch,franklanganke/elasticsearch,salyh/elasticsearch,petmit/elasticsearch,wimvds/elasticsearch,opendatasoft/elasticsearch,EasonYi/elasticsearch,jimczi/elasticsearch,chirilo/elasticsearch,AshishThakur/elasticsearch,Kakakakakku/elasticsearch,wbowling/elasticsearch,hydro2k/elasticsearch,achow/elasticsearch,scottsom/elasticsearch,fekaputra/elasticsearch,kcompher/elasticsearch,Asimov4/elasticsearch,yongminxia/elasticsearch,s1monw/elasticsearch,artnowo/elasticsearch,sneivandt/elasticsearch,uschindler/elasticsearch,zhiqinghuang/elasticsearch,kubum/elasticsearch,humandb/elasticsearch,Microsoft/elasticsearch,coding0011/elasticsearch,salyh/elasticsearch,masaruh/elasticsearch,aparo/elasticsearch,queirozfcom/elasticsearch,mbrukman/elasticsearch,hydro2k/elasticsearch,AleksKochev/elasticsearch,drewr/elasticsearch,sscarduzio/elasticsearch,mmaracic/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,mbrukman/elasticsearch,caengcjd/elasticsearch,zkidkid/elasticsearch,mnylen/elasticsearch,ThiagoGarciaAlves/elasticsearch,Widen/elasticsearch,LeoYao/elasticsearch,chrismwendt/elasticsearch,jsgao0/elasticsearch,ajhalani/elasticsearch,mohsinh/elasticsearch,socialrank/elasticsearch,kunallimaye/elasticsearch,camilojd/elasticsearch,Helen-Zhao/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,btiernay/elasticsearch,amit-shar/elasticsearch,F0lha/elasticsearch,hanswang/elasticsearch,mikemccand/elasticsearch,ckclark/elasticsearch,rento19962/elasticsearch,janmejay/elasticsearch,hanswang/elasticsearch,lks21c/elasticsearch,vroyer/elasticassandra,codebunt/elasticsearch,jimhooker2002/elasticsearch,mohit/elasticsearch,winstonewert/elasticsearch,anti-social/elasticsearch,pritishppai/elasticsearch,mnylen/elasticsearch,qwerty4030/elasticsearch,feiqitian/elasticsearch,fooljohnny/elasticsearch,vietlq/elasticsearch,shreejay/elasticsearch,ESamir/elasticsearch,ESamir/elasticsearch,liweinan0423/elasticsearch,kimchy/elasticsearch,kunallimaye/elasticsearch,jchampion/elasticsearch,Asimov4/elasticsearch,vorce/es-metrics,hanst/elasticsearch,boliza/elasticsearch,alexksikes/elasticsearch,ESamir/elasticsearch,nazarewk/elasticsearch,winstonewert/elasticsearch,jango2015/elasticsearch,huanzhong/elasticsearch,fooljohnny/elasticsearch,schonfeld/elasticsearch,acchen97/elasticsearch,aglne/elasticsearch,sc0ttkclark/elasticsearch,Shekharrajak/elasticsearch,jimhooker2002/elasticsearch,chirilo/elasticsearch,AndreKR/elasticsearch,nezirus/elasticsearch,ckclark/elasticsearch,sarwarbhuiyan/elasticsearch,StefanGor/elasticsearch,MetSystem/elasticsearch,brandonkearby/elasticsearch,fekaputra/elasticsearch,Helen-Zhao/elasticsearch,mute/elasticsearch,sdauletau/elasticsearch,wangtuo/elasticsearch,linglaiyao1314/elasticsearch,markllama/elasticsearch,sneivandt/elasticsearch,masterweb121/elasticsearch,heng4fun/elasticsearch,schonfeld/elasticsearch,liweinan0423/elasticsearch,mnylen/elasticsearch,Uiho/elasticsearch,kaneshin/elasticsearch,fforbeck/elasticsearch,AndreKR/elasticsearch,scottsom/elasticsearch,LeoYao/elasticsearch,Rygbee/elasticsearch,awislowski/elasticsearch,alexshadow007/elasticsearch,nellicus/elasticsearch,Collaborne/elasticsearch,trangvh/elasticsearch,yuy168/elasticsearch,jchampion/elasticsearch,xpandan/elasticsearch,vietlq/elasticsearch,JervyShi/elasticsearch,xuzha/elasticsearch,iacdingping/elasticsearch,libosu/elasticsearch,ZTE-PaaS/elasticsearch,wayeast/elasticsearch,aparo/elasticsearch,xingguang2013/elasticsearch,karthikjaps/elasticsearch,anti-social/elasticsearch,mgalushka/elasticsearch,drewr/elasticsearch,martinstuga/elasticsearch,MaineC/elasticsearch,raishiv/elasticsearch,opendatasoft/elasticsearch,nknize/elasticsearch,nomoa/elasticsearch,clintongormley/elasticsearch,mjhennig/elasticsearch,wbowling/elasticsearch,beiske/elasticsearch,vingupta3/elasticsearch,mnylen/elasticsearch,F0lha/elasticsearch,awislowski/elasticsearch,pozhidaevak/elasticsearch,sneivandt/elasticsearch,lzo/elasticsearch-1,NBSW/elasticsearch,dataduke/elasticsearch,petmit/elasticsearch,btiernay/elasticsearch,geidies/elasticsearch,skearns64/elasticsearch,aglne/elasticsearch,karthikjaps/elasticsearch,weipinghe/elasticsearch,areek/elasticsearch,jango2015/elasticsearch,Widen/elasticsearch,tsohil/elasticsearch,easonC/elasticsearch,kalburgimanjunath/elasticsearch,YosuaMichael/elasticsearch,HonzaKral/elasticsearch,ricardocerq/elasticsearch,Helen-Zhao/elasticsearch,jbertouch/elasticsearch,luiseduardohdbackup/elasticsearch,sjohnr/elasticsearch,Shepard1212/elasticsearch,sdauletau/elasticsearch,ouyangkongtong/elasticsearch,yuy168/elasticsearch,JSCooke/elasticsearch,cwurm/elasticsearch,YosuaMichael/elasticsearch,kunallimaye/elasticsearch,zhaocloud/elasticsearch,huanzhong/elasticsearch,areek/elasticsearch,opendatasoft/elasticsearch,lydonchandra/elasticsearch,obourgain/elasticsearch,rhoml/elasticsearch,milodky/elasticsearch,PhaedrusTheGreek/elasticsearch,hafkensite/elasticsearch,hechunwen/elasticsearch,micpalmia/elasticsearch,amaliujia/elasticsearch,mbrukman/elasticsearch,tahaemin/elasticsearch,anti-social/elasticsearch,Stacey-Gammon/elasticsearch,alexkuk/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,weipinghe/elasticsearch,polyfractal/elasticsearch,umeshdangat/elasticsearch,loconsolutions/elasticsearch,JackyMai/elasticsearch,thecocce/elasticsearch,zhiqinghuang/elasticsearch,myelin/elasticsearch,nrkkalyan/elasticsearch,MichaelLiZhou/elasticsearch,skearns64/elasticsearch,vvcephei/elasticsearch,szroland/elasticsearch,thecocce/elasticsearch,Microsoft/elasticsearch,ThalaivaStars/OrgRepo1,xuzha/elasticsearch,nrkkalyan/elasticsearch,ulkas/elasticsearch,uschindler/elasticsearch,fubuki/elasticsearch,nrkkalyan/elasticsearch,ImpressTV/elasticsearch,adrianbk/elasticsearch,jango2015/elasticsearch,vingupta3/elasticsearch,HonzaKral/elasticsearch,jchampion/elasticsearch,luiseduardohdbackup/elasticsearch,tahaemin/elasticsearch,kenshin233/elasticsearch,jprante/elasticsearch,sposam/elasticsearch,vietlq/elasticsearch,strapdata/elassandra-test,slavau/elasticsearch,coding0011/elasticsearch,petabytedata/elasticsearch,mjason3/elasticsearch,tahaemin/elasticsearch,C-Bish/elasticsearch,Chhunlong/elasticsearch,truemped/elasticsearch,Rygbee/elasticsearch,jeteve/elasticsearch,sarwarbhuiyan/elasticsearch,achow/elasticsearch,fernandozhu/elasticsearch,umeshdangat/elasticsearch,sarwarbhuiyan/elasticsearch,Widen/elasticsearch,skearns64/elasticsearch,elancom/elasticsearch,lmenezes/elasticsearch,apepper/elasticsearch,obourgain/elasticsearch,janmejay/elasticsearch,davidvgalbraith/elasticsearch
|
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search 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.elasticsearch.cluster.routing;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.cluster.*;
import org.elasticsearch.cluster.routing.strategy.ShardsRoutingStrategy;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.threadpool.ThreadPool;
import java.util.concurrent.Future;
import static org.elasticsearch.cluster.ClusterState.*;
import static org.elasticsearch.common.unit.TimeValue.*;
/**
* @author kimchy (shay.banon)
*/
public class RoutingService extends AbstractLifecycleComponent<RoutingService> implements ClusterStateListener {
private final ThreadPool threadPool;
private final ClusterService clusterService;
private final ShardsRoutingStrategy shardsRoutingStrategy;
private final TimeValue schedule;
private volatile boolean routingTableDirty = false;
private volatile Future scheduledRoutingTableFuture;
@Inject public RoutingService(Settings settings, ThreadPool threadPool, ClusterService clusterService, ShardsRoutingStrategy shardsRoutingStrategy) {
super(settings);
this.threadPool = threadPool;
this.clusterService = clusterService;
this.shardsRoutingStrategy = shardsRoutingStrategy;
this.schedule = componentSettings.getAsTime("schedule", timeValueSeconds(10));
}
@Override protected void doStart() throws ElasticSearchException {
clusterService.add(this);
}
@Override protected void doStop() throws ElasticSearchException {
if (scheduledRoutingTableFuture != null) {
scheduledRoutingTableFuture.cancel(true);
scheduledRoutingTableFuture = null;
}
clusterService.remove(this);
}
@Override protected void doClose() throws ElasticSearchException {
}
@Override public void clusterChanged(ClusterChangedEvent event) {
if (event.source().equals(RoutingTableUpdater.CLUSTER_UPDATE_TASK_SOURCE)) {
// that's us, ignore this event
return;
}
if (event.state().nodes().localNodeMaster()) {
// we are master, schedule the routing table updater
if (scheduledRoutingTableFuture == null) {
// a new master (us), make sure we reroute shards
routingTableDirty = true;
scheduledRoutingTableFuture = threadPool.scheduleWithFixedDelay(new RoutingTableUpdater(), schedule);
}
if (event.nodesRemoved() || event.routingTableChanged()) {
// if nodes were removed, we don't want to wait for the scheduled task
// since we want to get primary election as fast as possible
// also, if the routing table changed, it means that we have new indices, or shard have started
// or failed, we want to apply this as fast as possible
routingTableDirty = true;
threadPool.execute(new RoutingTableUpdater());
} else {
if (event.nodesAdded()) {
routingTableDirty = true;
}
}
} else {
if (scheduledRoutingTableFuture != null) {
scheduledRoutingTableFuture.cancel(true);
scheduledRoutingTableFuture = null;
}
}
}
private class RoutingTableUpdater implements Runnable {
private static final String CLUSTER_UPDATE_TASK_SOURCE = "routing-table-updater";
@Override public void run() {
try {
if (!routingTableDirty) {
return;
}
if (lifecycle.stopped()) {
return;
}
clusterService.submitStateUpdateTask(CLUSTER_UPDATE_TASK_SOURCE, new ClusterStateUpdateTask() {
@Override public ClusterState execute(ClusterState currentState) {
RoutingTable newRoutingTable = shardsRoutingStrategy.reroute(currentState);
if (newRoutingTable == currentState.routingTable()) {
// no state changed
return currentState;
}
return newClusterStateBuilder().state(currentState).routingTable(newRoutingTable).build();
}
});
routingTableDirty = false;
} catch (Exception e) {
logger.warn("Failed to reroute routing table", e);
}
}
}
}
|
modules/elasticsearch/src/main/java/org/elasticsearch/cluster/routing/RoutingService.java
|
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search 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.elasticsearch.cluster.routing;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.cluster.*;
import org.elasticsearch.cluster.routing.strategy.ShardsRoutingStrategy;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.threadpool.ThreadPool;
import java.util.concurrent.Future;
import static org.elasticsearch.cluster.ClusterState.*;
import static org.elasticsearch.common.unit.TimeValue.*;
/**
* @author kimchy (shay.banon)
*/
public class RoutingService extends AbstractLifecycleComponent<RoutingService> implements ClusterStateListener {
private final ThreadPool threadPool;
private final ClusterService clusterService;
private final ShardsRoutingStrategy shardsRoutingStrategy;
private final TimeValue schedule;
private volatile boolean routingTableDirty = false;
private volatile Future scheduledRoutingTableFuture;
@Inject public RoutingService(Settings settings, ThreadPool threadPool, ClusterService clusterService, ShardsRoutingStrategy shardsRoutingStrategy) {
super(settings);
this.threadPool = threadPool;
this.clusterService = clusterService;
this.shardsRoutingStrategy = shardsRoutingStrategy;
this.schedule = componentSettings.getAsTime("schedule", timeValueSeconds(10));
}
@Override protected void doStart() throws ElasticSearchException {
clusterService.add(this);
}
@Override protected void doStop() throws ElasticSearchException {
if (scheduledRoutingTableFuture != null) {
scheduledRoutingTableFuture.cancel(true);
scheduledRoutingTableFuture = null;
}
clusterService.remove(this);
}
@Override protected void doClose() throws ElasticSearchException {
}
@Override public void clusterChanged(ClusterChangedEvent event) {
if (event.source().equals(RoutingTableUpdater.CLUSTER_UPDATE_TASK_SOURCE)) {
// that's us, ignore this event
return;
}
if (event.state().nodes().localNodeMaster()) {
// we are master, schedule the routing table updater
if (scheduledRoutingTableFuture == null) {
scheduledRoutingTableFuture = threadPool.scheduleWithFixedDelay(new RoutingTableUpdater(), schedule);
}
if (event.nodesRemoved() || event.routingTableChanged()) {
// if nodes were removed, we don't want to wait for the scheduled task
// since we want to get primary election as fast as possible
// also, if the routing table changed, it means that we have new indices, or shard have started
// or failed, we want to apply this as fast as possible
routingTableDirty = true;
threadPool.execute(new RoutingTableUpdater());
} else {
if (event.nodesAdded()) {
routingTableDirty = true;
}
}
} else {
if (scheduledRoutingTableFuture != null) {
scheduledRoutingTableFuture.cancel(true);
scheduledRoutingTableFuture = null;
}
}
}
private class RoutingTableUpdater implements Runnable {
private static final String CLUSTER_UPDATE_TASK_SOURCE = "routing-table-updater";
@Override public void run() {
try {
if (!routingTableDirty) {
return;
}
if (lifecycle.stopped()) {
return;
}
clusterService.submitStateUpdateTask(CLUSTER_UPDATE_TASK_SOURCE, new ClusterStateUpdateTask() {
@Override public ClusterState execute(ClusterState currentState) {
RoutingTable newRoutingTable = shardsRoutingStrategy.reroute(currentState);
if (newRoutingTable == currentState.routingTable()) {
// no state changed
return currentState;
}
return newClusterStateBuilder().state(currentState).routingTable(newRoutingTable).build();
}
});
routingTableDirty = false;
} catch (Exception e) {
logger.warn("Failed to reroute routing table", e);
}
}
}
}
|
do a reroute when a node becomes master
|
modules/elasticsearch/src/main/java/org/elasticsearch/cluster/routing/RoutingService.java
|
do a reroute when a node becomes master
|
<ide><path>odules/elasticsearch/src/main/java/org/elasticsearch/cluster/routing/RoutingService.java
<ide> if (event.state().nodes().localNodeMaster()) {
<ide> // we are master, schedule the routing table updater
<ide> if (scheduledRoutingTableFuture == null) {
<add> // a new master (us), make sure we reroute shards
<add> routingTableDirty = true;
<ide> scheduledRoutingTableFuture = threadPool.scheduleWithFixedDelay(new RoutingTableUpdater(), schedule);
<ide> }
<ide> if (event.nodesRemoved() || event.routingTableChanged()) {
|
|
Java
|
apache-2.0
|
4f57082c7b8a795e8b49ea5a34cbbfe7fac85604
| 0 |
qtproject/qtqa-gerrit,gerrit-review/gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,gerrit-review/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,gerrit-review/gerrit
|
// Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.change;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.eclipse.jgit.lib.ObjectIdSerialization.readNotNull;
import static org.eclipse.jgit.lib.ObjectIdSerialization.writeNotNull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.cache.Cache;
import com.google.common.cache.Weigher;
import com.google.common.collect.FluentIterable;
import com.google.gerrit.extensions.client.ChangeKind;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.cache.CacheModule;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.git.InMemoryInserter;
import com.google.gerrit.server.git.MergeUtil;
import com.google.gerrit.server.project.ProjectCache;
import com.google.gerrit.server.project.ProjectState;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Module;
import com.google.inject.name.Named;
import org.eclipse.jgit.errors.LargeObjectException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.merge.ThreeWayMerger;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
public class ChangeKindCacheImpl implements ChangeKindCache {
private static final Logger log =
LoggerFactory.getLogger(ChangeKindCacheImpl.class);
private static final String ID_CACHE = "change_kind";
public static Module module() {
return new CacheModule() {
@Override
protected void configure() {
bind(ChangeKindCache.class).to(ChangeKindCacheImpl.class);
persist(ID_CACHE, Key.class, ChangeKind.class)
.maximumWeight(2 << 20)
.weigher(ChangeKindWeigher.class);
}
};
}
@VisibleForTesting
public static class NoCache implements ChangeKindCache {
private final boolean useRecursiveMerge;
private final ChangeData.Factory changeDataFactory;
private final ProjectCache projectCache;
private final GitRepositoryManager repoManager;
@Inject
NoCache(
@GerritServerConfig Config serverConfig,
ChangeData.Factory changeDataFactory,
ProjectCache projectCache,
GitRepositoryManager repoManager) {
this.useRecursiveMerge = MergeUtil.useRecursiveMerge(serverConfig);
this.changeDataFactory = changeDataFactory;
this.projectCache = projectCache;
this.repoManager = repoManager;
}
@Override
public ChangeKind getChangeKind(ProjectState project, Repository repo,
ObjectId prior, ObjectId next) {
try {
Key key = new Key(prior, next, useRecursiveMerge);
return new Loader(key, repo).call();
} catch (IOException e) {
log.warn("Cannot check trivial rebase of new patch set " + next.name()
+ " in " + project.getProject().getName(), e);
return ChangeKind.REWORK;
}
}
@Override
public ChangeKind getChangeKind(ReviewDb db, Change change,
PatchSet patch) {
return getChangeKindInternal(this, db, change, patch, changeDataFactory,
projectCache, repoManager);
}
@Override
public ChangeKind getChangeKind(Repository repo, ChangeData cd,
PatchSet patch) {
return getChangeKindInternal(this, repo, cd, patch, projectCache);
}
}
public static class Key implements Serializable {
private static final long serialVersionUID = 1L;
private transient ObjectId prior;
private transient ObjectId next;
private transient String strategyName;
private Key(ObjectId prior, ObjectId next, boolean useRecursiveMerge) {
checkNotNull(next, "next");
String strategyName = MergeUtil.mergeStrategyName(
true, useRecursiveMerge);
this.prior = prior.copy();
this.next = next.copy();
this.strategyName = strategyName;
}
public Key(ObjectId prior, ObjectId next, String strategyName) {
this.prior = prior;
this.next = next;
this.strategyName = strategyName;
}
public ObjectId getPrior() {
return prior;
}
public ObjectId getNext() {
return next;
}
public String getStrategyName() {
return strategyName;
}
@Override
public boolean equals(Object o) {
if (o instanceof Key) {
Key k = (Key) o;
return Objects.equals(prior, k.prior)
&& Objects.equals(next, k.next)
&& Objects.equals(strategyName, k.strategyName);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(prior, next, strategyName);
}
private void writeObject(ObjectOutputStream out) throws IOException {
writeNotNull(out, prior);
writeNotNull(out, next);
out.writeUTF(strategyName);
}
private void readObject(ObjectInputStream in) throws IOException {
prior = readNotNull(in);
next = readNotNull(in);
strategyName = in.readUTF();
}
}
private static class Loader implements Callable<ChangeKind> {
private final Key key;
private final Repository repo;
private Loader(Key key, Repository repo) {
this.key = key;
this.repo = repo;
}
@Override
public ChangeKind call() throws IOException {
if (Objects.equals(key.prior, key.next)) {
return ChangeKind.NO_CODE_CHANGE;
}
try (RevWalk walk = new RevWalk(repo)) {
RevCommit prior = walk.parseCommit(key.prior);
walk.parseBody(prior);
RevCommit next = walk.parseCommit(key.next);
walk.parseBody(next);
if (!next.getFullMessage().equals(prior.getFullMessage())) {
if (isSameDeltaAndTree(prior, next)) {
return ChangeKind.NO_CODE_CHANGE;
}
return ChangeKind.REWORK;
}
if (isSameDeltaAndTree(prior, next)) {
return ChangeKind.NO_CHANGE;
}
if ((prior.getParentCount() != 1 || next.getParentCount() != 1)
&& (!onlyFirstParentChanged(prior, next)
|| prior.getParentCount() == 0)) {
// Trivial rebases done by machine only work well on 1 parent.
return ChangeKind.REWORK;
}
// A trivial rebase can be detected by looking for the next commit
// having the same tree as would exist when the prior commit is
// cherry-picked onto the next commit's new first parent.
try (ObjectInserter ins = new InMemoryInserter(repo)) {
ThreeWayMerger merger =
MergeUtil.newThreeWayMerger(repo, ins, key.strategyName);
merger.setBase(prior.getParent(0));
if (merger.merge(next.getParent(0), prior)
&& merger.getResultTreeId().equals(next.getTree())) {
if (prior.getParentCount() == 1) {
return ChangeKind.TRIVIAL_REBASE;
}
return ChangeKind.MERGE_FIRST_PARENT_UPDATE;
}
} catch (LargeObjectException e) {
// Some object is too large for the merge attempt to succeed. Assume
// it was a rework.
}
return ChangeKind.REWORK;
}
}
public static boolean onlyFirstParentChanged(RevCommit prior, RevCommit next) {
return !sameFirstParents(prior, next) && sameRestOfParents(prior, next);
}
private static boolean sameFirstParents(RevCommit prior, RevCommit next) {
if (prior.getParentCount() == 0) {
return next.getParentCount() == 0;
}
return prior.getParent(0).equals(next.getParent(0));
}
private static boolean sameRestOfParents(RevCommit prior, RevCommit next) {
Set<RevCommit> priorRestParents = allExceptFirstParent(prior.getParents());
Set<RevCommit> nextRestParents = allExceptFirstParent(next.getParents());
return priorRestParents.equals(nextRestParents);
}
private static Set<RevCommit> allExceptFirstParent(RevCommit[] parents) {
return FluentIterable.from(Arrays.asList(parents)).skip(1).toSet();
}
private static boolean isSameDeltaAndTree(RevCommit prior, RevCommit next) {
if (next.getTree() != prior.getTree()) {
return false;
}
if (prior.getParentCount() != next.getParentCount()) {
return false;
} else if (prior.getParentCount() == 0) {
return true;
}
// Make sure that the prior/next delta is the same - not just the tree.
// This is done by making sure that the parent trees are equal.
for (int i = 0; i < prior.getParentCount(); i++) {
if (next.getParent(i).getTree() != prior.getParent(i).getTree()) {
return false;
}
}
return true;
}
}
public static class ChangeKindWeigher implements Weigher<Key, ChangeKind> {
@Override
public int weigh(Key key, ChangeKind changeKind) {
return 16 + 2 * 36 + 2 * key.strategyName.length() // Size of Key, 64 bit JVM
+ 2 * changeKind.name().length(); // Size of ChangeKind, 64 bit JVM
}
}
private final Cache<Key, ChangeKind> cache;
private final boolean useRecursiveMerge;
private final ChangeData.Factory changeDataFactory;
private final ProjectCache projectCache;
private final GitRepositoryManager repoManager;
@Inject
ChangeKindCacheImpl(
@GerritServerConfig Config serverConfig,
@Named(ID_CACHE) Cache<Key, ChangeKind> cache,
ChangeData.Factory changeDataFactory,
ProjectCache projectCache,
GitRepositoryManager repoManager) {
this.cache = cache;
this.useRecursiveMerge = MergeUtil.useRecursiveMerge(serverConfig);
this.changeDataFactory = changeDataFactory;
this.projectCache = projectCache;
this.repoManager = repoManager;
}
@Override
public ChangeKind getChangeKind(ProjectState project, Repository repo,
ObjectId prior, ObjectId next) {
try {
Key key = new Key(prior, next, useRecursiveMerge);
return cache.get(key, new Loader(key, repo));
} catch (ExecutionException e) {
log.warn("Cannot check trivial rebase of new patch set " + next.name()
+ " in " + project.getProject().getName(), e);
return ChangeKind.REWORK;
}
}
@Override
public ChangeKind getChangeKind(ReviewDb db, Change change, PatchSet patch) {
return getChangeKindInternal(this, db, change, patch, changeDataFactory,
projectCache, repoManager);
}
@Override
public ChangeKind getChangeKind(Repository repo, ChangeData cd,
PatchSet patch) {
return getChangeKindInternal(this, repo, cd, patch, projectCache);
}
private static ChangeKind getChangeKindInternal(
ChangeKindCache cache,
Repository repo,
ChangeData change,
PatchSet patch,
ProjectCache projectCache) {
ChangeKind kind = ChangeKind.REWORK;
// Trivial case: if we're on the first patch, we don't need to use
// the repository.
if (patch.getId().get() > 1) {
try {
ProjectState projectState = projectCache.checkedGet(change.project());
Collection<PatchSet> patchSetCollection = change.patchSets();
PatchSet priorPs = patch;
for (PatchSet ps : patchSetCollection) {
if (ps.getId().get() < patch.getId().get() &&
(ps.getId().get() > priorPs.getId().get() ||
priorPs == patch)) {
// We only want the previous patch set, so walk until the last one
priorPs = ps;
}
}
// If we still think the previous patch is the current patch,
// we only have one patch set. Return the default.
// This can happen if a user creates a draft, uploads a second patch,
// and deletes the draft.
if (priorPs != patch) {
kind =
cache.getChangeKind(projectState, repo,
ObjectId.fromString(priorPs.getRevision().get()),
ObjectId.fromString(patch.getRevision().get()));
}
} catch (IOException | OrmException e) {
// Do nothing; assume we have a complex change
log.warn("Unable to get change kind for patchSet " + patch.getPatchSetId() +
"of change " + change.getId(), e);
}
}
return kind;
}
private static ChangeKind getChangeKindInternal(
ChangeKindCache cache,
ReviewDb db,
Change change,
PatchSet patch,
ChangeData.Factory changeDataFactory,
ProjectCache projectCache,
GitRepositoryManager repoManager) {
// TODO - dborowitz: add NEW_CHANGE type for default.
ChangeKind kind = ChangeKind.REWORK;
// Trivial case: if we're on the first patch, we don't need to open
// the repository.
if (patch.getId().get() > 1) {
try (Repository repo = repoManager.openRepository(change.getProject())) {
kind = getChangeKindInternal(cache, repo,
changeDataFactory.create(db, change), patch,
projectCache);
} catch (IOException e) {
// Do nothing; assume we have a complex change
log.warn("Unable to get change kind for patchSet " + patch.getPatchSetId() +
"of change " + change.getChangeId(), e);
}
}
return kind;
}
}
|
gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeKindCacheImpl.java
|
// Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.change;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.eclipse.jgit.lib.ObjectIdSerialization.readNotNull;
import static org.eclipse.jgit.lib.ObjectIdSerialization.writeNotNull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.cache.Cache;
import com.google.common.cache.Weigher;
import com.google.common.collect.FluentIterable;
import com.google.gerrit.extensions.client.ChangeKind;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.cache.CacheModule;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.git.InMemoryInserter;
import com.google.gerrit.server.git.MergeUtil;
import com.google.gerrit.server.project.ProjectCache;
import com.google.gerrit.server.project.ProjectState;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Module;
import com.google.inject.name.Named;
import org.eclipse.jgit.errors.LargeObjectException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.merge.ThreeWayMerger;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
public class ChangeKindCacheImpl implements ChangeKindCache {
private static final Logger log =
LoggerFactory.getLogger(ChangeKindCacheImpl.class);
private static final String ID_CACHE = "change_kind";
public static Module module() {
return new CacheModule() {
@Override
protected void configure() {
bind(ChangeKindCache.class).to(ChangeKindCacheImpl.class);
persist(ID_CACHE, Key.class, ChangeKind.class)
.maximumWeight(2 << 20)
.weigher(ChangeKindWeigher.class);
}
};
}
@VisibleForTesting
public static class NoCache implements ChangeKindCache {
private final boolean useRecursiveMerge;
private final ChangeData.Factory changeDataFactory;
private final ProjectCache projectCache;
private final GitRepositoryManager repoManager;
@Inject
NoCache(
@GerritServerConfig Config serverConfig,
ChangeData.Factory changeDataFactory,
ProjectCache projectCache,
GitRepositoryManager repoManager) {
this.useRecursiveMerge = MergeUtil.useRecursiveMerge(serverConfig);
this.changeDataFactory = changeDataFactory;
this.projectCache = projectCache;
this.repoManager = repoManager;
}
@Override
public ChangeKind getChangeKind(ProjectState project, Repository repo,
ObjectId prior, ObjectId next) {
try {
Key key = new Key(prior, next, useRecursiveMerge);
return new Loader(key, repo).call();
} catch (IOException e) {
log.warn("Cannot check trivial rebase of new patch set " + next.name()
+ " in " + project.getProject().getName(), e);
return ChangeKind.REWORK;
}
}
@Override
public ChangeKind getChangeKind(ReviewDb db, Change change,
PatchSet patch) {
return getChangeKindInternal(this, db, change, patch, changeDataFactory,
projectCache, repoManager);
}
@Override
public ChangeKind getChangeKind(Repository repo, ChangeData cd,
PatchSet patch) {
return getChangeKindInternal(this, repo, cd, patch, projectCache);
}
}
public static class Key implements Serializable {
private static final long serialVersionUID = 1L;
private transient ObjectId prior;
private transient ObjectId next;
private transient String strategyName;
private Key(ObjectId prior, ObjectId next, boolean useRecursiveMerge) {
checkNotNull(next, "next");
String strategyName = MergeUtil.mergeStrategyName(
true, useRecursiveMerge);
this.prior = prior.copy();
this.next = next.copy();
this.strategyName = strategyName;
}
public Key(ObjectId prior, ObjectId next, String strategyName) {
this.prior = prior;
this.next = next;
this.strategyName = strategyName;
}
public ObjectId getPrior() {
return prior;
}
public ObjectId getNext() {
return next;
}
public String getStrategyName() {
return strategyName;
}
@Override
public boolean equals(Object o) {
if (o instanceof Key) {
Key k = (Key) o;
return Objects.equals(prior, k.prior)
&& Objects.equals(next, k.next)
&& Objects.equals(strategyName, k.strategyName);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(prior, next, strategyName);
}
private void writeObject(ObjectOutputStream out) throws IOException {
writeNotNull(out, prior);
writeNotNull(out, next);
out.writeUTF(strategyName);
}
private void readObject(ObjectInputStream in) throws IOException {
prior = readNotNull(in);
next = readNotNull(in);
strategyName = in.readUTF();
}
}
private static class Loader implements Callable<ChangeKind> {
private final Key key;
private final Repository repo;
private Loader(Key key, Repository repo) {
this.key = key;
this.repo = repo;
}
@Override
public ChangeKind call() throws IOException {
if (Objects.equals(key.prior, key.next)) {
return ChangeKind.NO_CODE_CHANGE;
}
try (RevWalk walk = new RevWalk(repo)) {
RevCommit prior = walk.parseCommit(key.prior);
walk.parseBody(prior);
RevCommit next = walk.parseCommit(key.next);
walk.parseBody(next);
if (!next.getFullMessage().equals(prior.getFullMessage())) {
if (isSameDeltaAndTree(prior, next)) {
return ChangeKind.NO_CODE_CHANGE;
}
return ChangeKind.REWORK;
}
if (isSameDeltaAndTree(prior, next)) {
return ChangeKind.NO_CHANGE;
}
if ((prior.getParentCount() != 1 || next.getParentCount() != 1)
&& (prior.getParentCount() == 0
|| !onlyFirstParentChanged(prior, next))) {
// Trivial rebases done by machine only work well on 1 parent.
return ChangeKind.REWORK;
}
// A trivial rebase can be detected by looking for the next commit
// having the same tree as would exist when the prior commit is
// cherry-picked onto the next commit's new first parent.
try (ObjectInserter ins = new InMemoryInserter(repo)) {
ThreeWayMerger merger =
MergeUtil.newThreeWayMerger(repo, ins, key.strategyName);
merger.setBase(prior.getParent(0));
if (merger.merge(next.getParent(0), prior)
&& merger.getResultTreeId().equals(next.getTree())) {
if (prior.getParentCount() == 1) {
return ChangeKind.TRIVIAL_REBASE;
}
return ChangeKind.MERGE_FIRST_PARENT_UPDATE;
}
} catch (LargeObjectException e) {
// Some object is too large for the merge attempt to succeed. Assume
// it was a rework.
}
return ChangeKind.REWORK;
}
}
public static boolean onlyFirstParentChanged(RevCommit prior, RevCommit next) {
return !sameFirstParents(prior, next) && sameRestOfParents(prior, next);
}
private static boolean sameFirstParents(RevCommit prior, RevCommit next) {
if (prior.getParentCount() == 0) {
return next.getParentCount() == 0;
}
return prior.getParent(0).equals(next.getParent(0));
}
private static boolean sameRestOfParents(RevCommit prior, RevCommit next) {
Set<RevCommit> priorRestParents = allExceptFirstParent(prior.getParents());
Set<RevCommit> nextRestParents = allExceptFirstParent(next.getParents());
return priorRestParents.equals(nextRestParents);
}
private static Set<RevCommit> allExceptFirstParent(RevCommit[] parents) {
return FluentIterable.from(Arrays.asList(parents)).skip(1).toSet();
}
private static boolean isSameDeltaAndTree(RevCommit prior, RevCommit next) {
if (next.getTree() != prior.getTree()) {
return false;
}
if (prior.getParentCount() != next.getParentCount()) {
return false;
} else if (prior.getParentCount() == 0) {
return true;
}
// Make sure that the prior/next delta is the same - not just the tree.
// This is done by making sure that the parent trees are equal.
for (int i = 0; i < prior.getParentCount(); i++) {
if (next.getParent(i).getTree() != prior.getParent(i).getTree()) {
return false;
}
}
return true;
}
}
public static class ChangeKindWeigher implements Weigher<Key, ChangeKind> {
@Override
public int weigh(Key key, ChangeKind changeKind) {
return 16 + 2 * 36 + 2 * key.strategyName.length() // Size of Key, 64 bit JVM
+ 2 * changeKind.name().length(); // Size of ChangeKind, 64 bit JVM
}
}
private final Cache<Key, ChangeKind> cache;
private final boolean useRecursiveMerge;
private final ChangeData.Factory changeDataFactory;
private final ProjectCache projectCache;
private final GitRepositoryManager repoManager;
@Inject
ChangeKindCacheImpl(
@GerritServerConfig Config serverConfig,
@Named(ID_CACHE) Cache<Key, ChangeKind> cache,
ChangeData.Factory changeDataFactory,
ProjectCache projectCache,
GitRepositoryManager repoManager) {
this.cache = cache;
this.useRecursiveMerge = MergeUtil.useRecursiveMerge(serverConfig);
this.changeDataFactory = changeDataFactory;
this.projectCache = projectCache;
this.repoManager = repoManager;
}
@Override
public ChangeKind getChangeKind(ProjectState project, Repository repo,
ObjectId prior, ObjectId next) {
try {
Key key = new Key(prior, next, useRecursiveMerge);
return cache.get(key, new Loader(key, repo));
} catch (ExecutionException e) {
log.warn("Cannot check trivial rebase of new patch set " + next.name()
+ " in " + project.getProject().getName(), e);
return ChangeKind.REWORK;
}
}
@Override
public ChangeKind getChangeKind(ReviewDb db, Change change, PatchSet patch) {
return getChangeKindInternal(this, db, change, patch, changeDataFactory,
projectCache, repoManager);
}
@Override
public ChangeKind getChangeKind(Repository repo, ChangeData cd,
PatchSet patch) {
return getChangeKindInternal(this, repo, cd, patch, projectCache);
}
private static ChangeKind getChangeKindInternal(
ChangeKindCache cache,
Repository repo,
ChangeData change,
PatchSet patch,
ProjectCache projectCache) {
ChangeKind kind = ChangeKind.REWORK;
// Trivial case: if we're on the first patch, we don't need to use
// the repository.
if (patch.getId().get() > 1) {
try {
ProjectState projectState = projectCache.checkedGet(change.project());
Collection<PatchSet> patchSetCollection = change.patchSets();
PatchSet priorPs = patch;
for (PatchSet ps : patchSetCollection) {
if (ps.getId().get() < patch.getId().get() &&
(ps.getId().get() > priorPs.getId().get() ||
priorPs == patch)) {
// We only want the previous patch set, so walk until the last one
priorPs = ps;
}
}
// If we still think the previous patch is the current patch,
// we only have one patch set. Return the default.
// This can happen if a user creates a draft, uploads a second patch,
// and deletes the draft.
if (priorPs != patch) {
kind =
cache.getChangeKind(projectState, repo,
ObjectId.fromString(priorPs.getRevision().get()),
ObjectId.fromString(patch.getRevision().get()));
}
} catch (IOException | OrmException e) {
// Do nothing; assume we have a complex change
log.warn("Unable to get change kind for patchSet " + patch.getPatchSetId() +
"of change " + change.getId(), e);
}
}
return kind;
}
private static ChangeKind getChangeKindInternal(
ChangeKindCache cache,
ReviewDb db,
Change change,
PatchSet patch,
ChangeData.Factory changeDataFactory,
ProjectCache projectCache,
GitRepositoryManager repoManager) {
// TODO - dborowitz: add NEW_CHANGE type for default.
ChangeKind kind = ChangeKind.REWORK;
// Trivial case: if we're on the first patch, we don't need to open
// the repository.
if (patch.getId().get() > 1) {
try (Repository repo = repoManager.openRepository(change.getProject())) {
kind = getChangeKindInternal(cache, repo,
changeDataFactory.create(db, change), patch,
projectCache);
} catch (IOException e) {
// Do nothing; assume we have a complex change
log.warn("Unable to get change kind for patchSet " + patch.getPatchSetId() +
"of change " + change.getChangeId(), e);
}
}
return kind;
}
}
|
Revert "Fix java.lang.ArrayIndexOutOfBoundsException when checking for parent"
Doesn't fix the problem it was supposed to fix (issue 5866).
This reverts commit c74e28aea54f71bc56dda16754714a714e2869ac.
Change-Id: I34e55f9c1d08fd5babf8ec3e1debf32b72abbc2b
|
gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeKindCacheImpl.java
|
Revert "Fix java.lang.ArrayIndexOutOfBoundsException when checking for parent"
|
<ide><path>errit-server/src/main/java/com/google/gerrit/server/change/ChangeKindCacheImpl.java
<ide> }
<ide>
<ide> if ((prior.getParentCount() != 1 || next.getParentCount() != 1)
<del> && (prior.getParentCount() == 0
<del> || !onlyFirstParentChanged(prior, next))) {
<add> && (!onlyFirstParentChanged(prior, next)
<add> || prior.getParentCount() == 0)) {
<ide> // Trivial rebases done by machine only work well on 1 parent.
<ide> return ChangeKind.REWORK;
<ide> }
|
|
JavaScript
|
unlicense
|
de4bc61a021a7ff5ba7cc05e3898f7f99e88aa2b
| 0 |
fvdm/nodejs-spark
|
/*
Name: spark.js
Description: Read and control Spark Cores with node.js
Author: Franklin van de Meent (https://frankl.in)
Feedback: https://github.com/fvdm/nodejs-spark/issues
Source: https://github.com/fvdm/nodejs-spark
Service: Spark (https://www.spark.io)
License: Unlicense (Public Domain)
https://github.com/fvdm/nodejs-spark/blob/master/LICENSE
*/
var http = require ('httpreq');
var EventSource = require ('eventsource');
// Default settings
var app = {
timeout: 10000
};
// Security details must not be public
var auth = {
username: null,
password: null,
access_token: null,
access_token_expires: null
};
// List devices
app.devices = function (cb) {
talk ({
path: 'devices',
callback: cb
});
};
// One device
app.device = function (device) {
return {
info: function (cb) {
talk ({
path: 'devices/'+ device,
callback: cb
});
},
variable: function (variable, cb) {
talk ({
path: 'devices/'+ device +'/'+ variable,
callback: cb
});
},
func: function (func, arg, cb) {
var vars = null;
if (typeof arg === 'function') {
cb = arg;
} else if (typeof arg === 'string' || typeof arg === 'numeric') {
vars = {
args: arg };
}
talk ({
method: 'POST',
path: 'devices/'+ device +'/'+ func,
query: vars,
callback: cb
});
},
events: function (cbMessage, cbError, cbOpen) {
var es = new EventSource (
'https://api.particle.io/v1/devices/'+ device +'/events',
{
headers: {
Authorization: 'Bearer '+ auth.access_token
}
}
);
if (cbOpen) {
es.onopen = cbOpen;
}
if (cbError) {
es.onerror = cbError;
}
if (cbMessage) {
es.onmessage = function (ev) {
cbMessage (fixEvent (ev));
};
}
}
};
};
// Claim device
app.claimDevice = function (deviceId, cb) {
talk ({
method: 'POST',
path: 'devices',
query: {
id: deviceId
},
callback: cb
});
};
// Account events
app.events = function (cbMessage, cbError, cbOpen) {
var es = new EventSource (
'https://api.particle.io/v1/devices/events',
{
headers: {
Authorization: 'Bearer '+ auth.access_token
}
}
);
if (cbOpen) {
es.onopen = cbOpen;
}
if (cbError) {
es.onerror = cbError;
}
if (cbMessage) {
es.onmessage = function (ev) {
cbMessage (fixEvent (ev));
};
}
};
// Publish event to all devices
app.publishEvent = function (name, data, priv, ttl, cb) {
talk ({
method: 'POST',
path: 'devices/events',
query: {
name: name,
data: data || '',
private: priv ? 'true' : 'false',
ttl: ttl || 60,
callback: cb
}
});
};
// List or generate access_token
app.accessToken = {};
app.accessToken.list = function (callback) {
talk ({
path: 'access_token',
auth: true,
callback: callback
});
};
app.accessToken.generate = function (cb) {
if (auth.username && auth.password) {
var vars = {
grant_type: 'password',
username: auth.username,
password: auth.password
};
talk ({
method: 'POST',
path: 'oauth/token',
body: vars,
auth: true,
callback: cb
});
return;
}
cb (new Error ('no credentials'));
};
app.accessToken.delete = function (token, cb) {
talk ({
method: 'DELETE',
path: 'access_tokens/'+ token,
auth: true,
callback: cb
});
};
// process response
function doResponse (err, res, props) {
var data = null;
var error = null;
if (err) {
error = new Error ('request failed');
error.error = err;
}
if (!err) {
try {
data = JSON.parse (res.body);
} catch (e) {
error = new Error ('invalid response');
error.error = e;
}
if (res.statusCode !== 200 && data && data.code) {
error = new Error ('api error');
error.code = data.code;
error.error = data.error;
error.error_description = data.error_description;
}
}
if (typeof props.callback === 'function') {
props.callback (error, data);
}
}
/**
* Communicate
*
* @param props {object}
* @param [props.method = GET] {string} - HTTP method
* @param [props.path = /] {string} - Request path
* @param [props.query] {object}
* @param [props.body] {mixed}
* @param [props.callback] {function}
* @param [props.auth] {object}
* @param [props.contentType] {string}
* @param [props.userAgent] {string}
* @param [props.headers] {object}
* @param [props.timeout] = 10000] {number}
* @returns {void}
*/
function talk (props) {
var options = {
url: 'https://api.particle.io/v1/' + props.path,
method: props.method || 'GET',
parameters: props.query || {},
body: props.body || null,
headers: {
'User-Agent': props.userAgent || 'spark.js (https://github.com/fvdm/nodejs-spark)'
},
timeout: props.timeout || app.timeout
};
// http basic auth
if (props.auth && (!auth.username || !auth.password)) {
doCallback (new Error ('no credentials'));
return;
}
if (props.auth) {
options.auth = auth.username +':'+ auth.password;
} else {
options.headers.Authorization = 'Bearer '+ auth.access_token;
}
// override headers
if (typeof props.headers === 'object' && Object.keys (props.headers) .length >= 1) {
for (var key in props.headers) {
options.headers [key] = props.headers [key];
}
}
// run
http.doRequest (options, function (err, res) {
doResponse (err, res, props);
});
}
/**
* Fix events
* it is impossible to overwrite ev.data without the for..loop
*
* @param ev {object} - Event object
* @returns {object}
*/
function fixEvent (ev) {
var ev2 = {};
var key;
for (key in ev) {
ev2 [key] = ev [key];
}
try {
ev2.data = JSON.parse (ev2.data);
} catch (e) {
// skip
}
try {
ev2.data.data = JSON.parse (ev2.data.data);
} catch (e) {
// skip
}
return ev2;
}
// export
// either ( 'access_token_string', [1000] )
// or ( {username: 'john', password: 'doe'}, [1000] )
module.exports = function (access_token, timeout) {
if (typeof accessToken === 'string') {
auth.access_token = access_token;
app.timeout = timeout || app.timeout;
return app;
}
app.timeout = access_token.timeout || timeout || app.timeout;
auth.username = access_token.username;
auth.password = access_token.password;
app.accessToken.generate (function (err, token) {
if (!err) {
auth.access_token = token.access_token;
auth.access_token_expires = token.expires_in;
}
});
return app;
};
|
spark.js
|
/*
Name: spark.js
Description: Read and control Spark Cores with node.js
Author: Franklin van de Meent (https://frankl.in)
Feedback: https://github.com/fvdm/nodejs-spark/issues
Source: https://github.com/fvdm/nodejs-spark
Service: Spark (https://www.spark.io)
License: Unlicense (Public Domain)
https://github.com/fvdm/nodejs-spark/blob/master/LICENSE
*/
var http = require ('httpreq');
var EventSource = require ('eventsource');
// Default settings
var app = {
timeout: 10000
};
// Security details must not be public
var auth = {
username: null,
password: null,
access_token: null,
access_token_expires: null
};
// List devices
app.devices = function (cb) {
talk ({
path: 'devices',
callback: cb
});
};
// One device
app.device = function (device) {
return {
info: function (cb) {
talk ({
path: 'devices/'+ device,
callback: cb
});
},
variable: function (variable, cb) {
talk ({
path: 'devices/'+ device +'/'+ variable,
callback: cb
});
},
func: function (func, arg, cb) {
var vars = null;
if (typeof arg === 'function') {
cb = arg;
} else if (typeof arg === 'string' || typeof arg === 'numeric') {
vars = {
args: arg };
}
talk ({
method: 'POST',
path: 'devices/'+ device +'/'+ func,
query: vars,
callback: cb
});
},
events: function (cbMessage, cbError, cbOpen) {
var es = new EventSource (
'https://api.particle.io/v1/devices/'+ device +'/events',
{
headers: {
Authorization: 'Bearer '+ auth.access_token
}
}
);
if (cbOpen) {
es.onopen = cbOpen;
}
if (cbError) {
es.onerror = cbError;
}
if (cbMessage) {
es.onmessage = function (ev) {
cbMessage (fixEvent (ev));
};
}
}
};
};
// Claim device
app.claimDevice = function (deviceId, cb) {
talk ({
method: 'POST',
path: 'devices',
query: {
id: deviceId
},
callback: cb
});
};
// Account events
app.events = function (cbMessage, cbError, cbOpen) {
var es = new EventSource (
'https://api.particle.io/v1/devices/events',
{
headers: {
Authorization: 'Bearer '+ auth.access_token
}
}
);
if (cbOpen) {
es.onopen = cbOpen;
}
if (cbError) {
es.onerror = cbError;
}
if (cbMessage) {
es.onmessage = function (ev) {
cbMessage (fixEvent (ev));
};
}
};
// Publish event to all devices
app.publishEvent = function (name, data, priv, ttl, cb) {
talk ({
method: 'POST',
path: 'devices/events',
query: {
name: name,
data: data || '',
private: priv ? 'true' : 'false',
ttl: ttl || 60,
callback: cb
}
});
};
// List or generate access_token
app.accessToken = {};
app.accessToken.list = function (callback) {
talk ({
path: 'access_token',
auth: true,
callback: callback
});
};
app.accessToken.generate = function (cb) {
if (auth.username && auth.password) {
var vars = {
grant_type: 'password',
username: auth.username,
password: auth.password
};
talk ({
method: 'POST',
path: 'oauth/token',
body: vars,
auth: true,
callback: cb
});
return;
}
cb (new Error ('no credentials'));
};
app.accessToken.delete = function (token, cb) {
talk ({
method: 'DELETE',
path: 'access_tokens/'+ token,
auth: true,
callback: cb
});
};
// process response
function doResponse (err, res, props) {
var data = null;
var error = null;
if (err) {
error = new Error ('request failed');
error.error = err;
}
if (!err) {
try {
data = JSON.parse (res.body);
} catch (e) {
error = new Error ('invalid response');
error.error = e;
}
if (res.statusCode !== 200 && data && data.code) {
error = new Error ('api error');
error.code = data.code;
error.error = data.error;
error.error_description = data.error_description;
}
}
if (typeof props.callback === 'function') {
props.callback (error, data);
}
}
// Communicate
// method GET POST PUT DELETE GET
// path method path /
// query query fields {}
// body body fields or data
// callback function( err, data )
// auth use {username: 'john', password: 'doe'}
// contentType change Content-Type !GET: application/x-www-form-urlencoded
// userAgent change User-Agent
// headers custom headers {}
// timeout override timeout ms 10000
function talk (props) {
var options = {
url: 'https://api.particle.io/v1/' + props.path,
method: props.method || 'GET',
parameters: props.query || {},
body: props.body || null,
headers: {
'User-Agent': props.userAgent || 'spark.js (https://github.com/fvdm/nodejs-spark)'
},
timeout: props.timeout || app.timeout
};
// http basic auth
if (props.auth && (!auth.username || !auth.password)) {
doCallback (new Error ('no credentials'));
return;
}
if (props.auth) {
options.auth = auth.username +':'+ auth.password;
} else {
options.headers.Authorization = 'Bearer '+ auth.access_token;
}
// override headers
if (typeof props.headers === 'object' && Object.keys (props.headers) .length >= 1) {
for (var key in props.headers) {
options.headers [key] = props.headers [key];
}
}
// run
http.doRequest (options, function (err, res) {
doResponse (err, res, props);
});
}
// Fix events - it is impossible to overwrite ev.data without the for..loop
function fixEvent (ev) {
var ev2 = {};
var key;
for (key in ev) {
ev2 [key] = ev [key];
}
try {
ev2.data = JSON.parse (ev2.data);
} catch (e) {
// skip
}
try {
ev2.data.data = JSON.parse (ev2.data.data);
} catch (e) {
// skip
}
return ev2;
}
// export
// either ( 'access_token_string', [1000] )
// or ( {username: 'john', password: 'doe'}, [1000] )
module.exports = function (access_token, timeout) {
if (typeof accessToken === 'string') {
auth.access_token = access_token;
app.timeout = timeout || app.timeout;
return app;
}
app.timeout = access_token.timeout || timeout || app.timeout;
auth.username = access_token.username;
auth.password = access_token.password;
app.accessToken.generate (function (err, token) {
if (!err) {
auth.access_token = token.access_token;
auth.access_token_expires = token.expires_in;
}
});
return app;
};
|
JSdoc talk() and fixEvent()
|
spark.js
|
JSdoc talk() and fixEvent()
|
<ide><path>park.js
<ide> }
<ide> }
<ide>
<del>// Communicate
<del>// method GET POST PUT DELETE GET
<del>// path method path /
<del>// query query fields {}
<del>// body body fields or data
<del>// callback function( err, data )
<del>// auth use {username: 'john', password: 'doe'}
<del>// contentType change Content-Type !GET: application/x-www-form-urlencoded
<del>// userAgent change User-Agent
<del>// headers custom headers {}
<del>// timeout override timeout ms 10000
<add>
<add>/**
<add> * Communicate
<add> *
<add> * @param props {object}
<add> * @param [props.method = GET] {string} - HTTP method
<add> * @param [props.path = /] {string} - Request path
<add> * @param [props.query] {object}
<add> * @param [props.body] {mixed}
<add> * @param [props.callback] {function}
<add> * @param [props.auth] {object}
<add> * @param [props.contentType] {string}
<add> * @param [props.userAgent] {string}
<add> * @param [props.headers] {object}
<add> * @param [props.timeout] = 10000] {number}
<add> * @returns {void}
<add> */
<ide>
<ide> function talk (props) {
<ide> var options = {
<ide> });
<ide> }
<ide>
<del>// Fix events - it is impossible to overwrite ev.data without the for..loop
<add>
<add>/**
<add> * Fix events
<add> * it is impossible to overwrite ev.data without the for..loop
<add> *
<add> * @param ev {object} - Event object
<add> * @returns {object}
<add> */
<add>
<ide> function fixEvent (ev) {
<ide> var ev2 = {};
<ide> var key;
|
|
JavaScript
|
mit
|
20cd89193a74eaaaef3d68c01d95c3a897f7a1af
| 0 |
andela-ogaruba/AndelaAPI
|
'use strict';
// Lists controller
angular.module('admin').controller('TestsController', ['$scope', '$http', 'Authentication', '$stateParams', '$location', '$modal', '$log', 'Tests',
function($scope, $http, Authentication, $stateParams, $location, $modal, $log, Tests) {
$scope.choiceOne = [{
id: 'choice1'
}, {
id: 'choice2'
}]; //answer to question one
$scope.choiceTwo = [{
id: 'choice1'
}, {
id: 'choice2'
}]; //answer to question two
$scope.optionOne = []; //options for question one
$scope.optionTwo = []; //options for question two
$scope.questions = [];
$scope.selected = '';
$scope.testName = '';
$scope.answered = false;
$scope.answeredTwo = false;
$scope.setShow = function(val) {
$scope.selected = val;
};
$scope.isSelected = function(val) {
return val === $scope.selected;
};
$scope.addNewChoice = function(num) {
var newItemNo;
if (num === 1) {
newItemNo = $scope.choiceOne.length + 1;
$scope.choiceOne.push({
id: 'choice' + newItemNo
});
} else {
newItemNo = $scope.choiceTwo.length + 1;
$scope.choiceTwo.push({
id: 'choice' + newItemNo
});
}
};
$scope.deleteChoice = function(index, num) {
if (num === 1) {
if (parseInt($scope.test.answerOne, 10) === $scope.choiceOne.length - 1) {
$scope.test.answerOne = $scope.test.answerOne - 1;
}
doDelete($scope.choiceOne, $scope.optionOne, index);
} else {
if (parseInt($scope.test.answerTwo, 10) === $scope.choiceTwo.length - 1) {
$scope.test.answerTwo = $scope.test.answerTwo - 1;
}
doDelete($scope.choiceTwo, $scope.optionTwo, index);
}
};
var doDelete = function(choiceArr, optionArr, index) {
choiceArr.splice(index, 1);
optionArr.splice(index, 1);
for (var i in choiceArr) {
choiceArr[i].id = 'choice' + i;
}
};
$scope.showAddChoice = function(choice, num) {
if (num === 1)
return choice.id === $scope.choiceOne[$scope.choiceOne.length - 1].id;
else
return choice.id === $scope.choiceTwo[$scope.choiceTwo.length - 1].id;
};
$scope.changeAnsVal = function(index, num) {
if (num === 1) {
$scope.answered = true;
} else {
$scope.answeredTwo = true;
}
};
$scope.createTest = function() {
var test = new Tests({
questions: $scope.questions,
optionOne: $scope.optionOne,
optionTwo: $scope.optionTwo,
testName: $scope.testName,
answerOne: $scope.test.answerOne,
answerTwo: $scope.test.answerTwo
});
test.$save(function(response) {
$location.path('/admin/test');
}, function(response) {
$scope.error = response.message;
});
};
$scope.createQuestion = function() {
var test = new Tests({
_id: $stateParams.testId,
question: $scope.question,
option: $scope.optionOne,
answer: $scope.test.answerOne
});
test.$save(function(response) {
$location.path('/admin/test');
}, function(err) {
$scope.error = err.message;
});
};
$scope.viewTests = function() {
var tests = Tests.query(function success(response) {
$scope.tests = response;
});
};
$scope.viewTest = function() {
Tests.get({
testId: $stateParams.testId
}, function success(response) {
$scope.test = response;
$scope.testNameEditorEnabled = false;
$scope.questionEditorEnabled = [];
$scope.editableQuestion = [];
$scope.optionEditorEnabled = [];
$scope.editableOption = [];
$scope.displayerrmsg = [];
for (var i in $scope.test.questions) {
$scope.questionEditorEnabled[i] = false;
$scope.optionEditorEnabled[i] = [];
$scope.editableOption[i] = [];
for (var j in $scope.test.questions[i].questOptions) {
$scope.optionEditorEnabled[i][j] = false;
$scope.editableOption[i][j] = {};
}
}
$scope.enableEditor = function(field, index, optionIndex) {
if (field === 'testName') {
$scope.testNameEditorEnabled = true;
$scope.editabletestName = $scope.test.testName;
}
if (field === 'question') {
$scope.questionEditorEnabled[index] = true;
$scope.editableQuestion[index] = $scope.test.questions[index].question;
}
if (field === 'option') {
$scope.optionEditorEnabled[index][optionIndex] = true;
$scope.editableOption[index][optionIndex].option =
$scope.test.questions[index].questOptions[optionIndex].option;
}
};
$scope.disableEditor = function(field, index, optionIndex) {
if (field === 'testName') {
$scope.testNameEditorEnabled = false;
}
if (field === 'question') {
$scope.questionEditorEnabled[index] = false;
}
if (field === 'option') {
$scope.optionEditorEnabled[index][optionIndex] = false;
}
};
// Checks to see if all answers are set to same (false/true).
// Returns true if all are the same
var checkAllanswers = function(questOptions) {
var firstOption = questOptions[0].answer
for (var i in questOptions) {
if (firstOption !== questOptions[i].answer) {
return false;
}
}
return true;
};
$scope.save = function(field, index, optionIndex) {
if (field === 'testName') {
$scope.test.testName = $scope.editabletestName;
$scope.changeTestName($scope.test);
}
if (field === 'question') {
$scope.test.questions[index].question = $scope.editableQuestion[index];
$scope.updateQuestion($scope.test, index);
}
if (field === 'option') {
$scope.test.questions[index].questOptions[optionIndex].option =
$scope.editableOption[index][optionIndex].option;
if ($scope.editableOption[index][optionIndex].answer === undefined ||
$scope.editableOption[index][optionIndex].answer === 'undefined') {
$scope.editableOption[index][optionIndex].answer = false;
}
// if the option's answer field changes, then change others to it's oppossite
if ($scope.editableOption[index][optionIndex].answer === true) {
for (var i in $scope.test.questions[index].questOptions) {
if (i === optionIndex) {
continue;
}
$scope.test.questions[index].questOptions[i].answer = false;
}
}
$scope.test.questions[index].questOptions[optionIndex].answer =
$scope.editableOption[index][optionIndex].answer;
// Set error message if no answer is selected
if (checkAllanswers($scope.test.questions[index].questOptions)) {
$scope.displayerrmsg[index] = true;
} else {
$scope.displayerrmsg[index] = false;
}
$scope.updateQuestion($scope.test, index);
}
$scope.disableEditor(field, index, optionIndex);
};
} //ends test.get() success callbk
);
};
$scope.changeTestName = function(test) {
test.$update({
_id: test._id
}, function success() {},
function(errorResponse) {
$scope.error = errorResponse;
});
};
$scope.updateQuestion = function(test, quesIndex) {
var question = test.questions[quesIndex];
$http.put('/admin/test/' + test._id + '/' + test.questions[quesIndex]._id, question).success(function(response) {}).error(function(response) {
$scope.error = response.message;
});
};
$scope.deleteTest = function(test, index) {
$scope.tests.splice(index, 1);
test.$remove({
_id: test._id
}, function success() {}, function(response) {
$scope.error = response.message;
});
};
$scope.deleteQuestion = function(testId, questionId, index) {
$scope.test.questions.splice(index, 1);
$http.delete('/admin/test/' + testId + '/' + questionId).success(function(response) {
$scope.success = true;
}).error(function(response) {
$scope.error = response.message;
});
};
$scope.deleteOption = function(testId, questionId, optionId, queIndex, index) {
$scope.test.questions[queIndex].questOptions.splice(index, 1);
$http.delete('/admin/test/' + testId + '/' + questionId + '/' + optionId).success(function(response) {
$scope.success = true;
}).error(function(response) {
$scope.error = response.message;
});
};
}
]);
|
public/modules/admin/controllers/admin.client.tests.controller.js
|
'use strict';
// Lists controller
angular.module('admin').controller('TestsController', ['$scope', '$http', 'Authentication', '$stateParams', '$location', '$modal', '$log', 'Tests',
function($scope, $http, Authentication, $stateParams, $location, $modal, $log, Tests) {
$scope.choiceOne = [{
id: 'choice1'
}, {
id: 'choice2'
}]; //answer to question one
$scope.choiceTwo = [{
id: 'choice1'
}, {
id: 'choice2'
}]; //answer to question two
$scope.optionOne = []; //options for question one
$scope.optionTwo = []; //options for question two
$scope.questions = [];
$scope.selected = '';
$scope.testName = '';
$scope.answered = false;
$scope.answeredTwo = false;
$scope.setShow = function(val) {
$scope.selected = val;
};
$scope.isSelected = function(val) {
return val === $scope.selected;
};
$scope.addNewChoice = function(num) {
var newItemNo;
if (num === 1) {
newItemNo = $scope.choiceOne.length + 1;
$scope.choiceOne.push({
id: 'choice' + newItemNo
});
} else {
newItemNo = $scope.choiceTwo.length + 1;
$scope.choiceTwo.push({
id: 'choice' + newItemNo
});
}
};
$scope.deleteChoice = function(index, num) {
if (num === 1) {
if (parseInt($scope.test.answerOne, 10) === $scope.choiceOne.length - 1) {
$scope.test.answerOne = $scope.test.answerOne - 1;
}
doDelete($scope.choiceOne, $scope.optionOne, index);
} else {
if (parseInt($scope.test.answerTwo, 10) === $scope.choiceTwo.length - 1) {
$scope.test.answerTwo = $scope.test.answerTwo - 1;
}
doDelete($scope.choiceTwo, $scope.optionTwo, index);
}
};
var doDelete = function(choiceArr, optionArr, index) {
choiceArr.splice(index, 1);
optionArr.splice(index, 1);
for (var i in choiceArr) {
choiceArr[i].id = 'choice' + i;
}
};
$scope.showAddChoice = function(choice, num) {
if (num === 1)
return choice.id === $scope.choiceOne[$scope.choiceOne.length - 1].id;
else
return choice.id === $scope.choiceTwo[$scope.choiceTwo.length - 1].id;
};
$scope.changeAnsVal = function(index, num) {
if (num === 1) {
$scope.answered = true;
} else {
$scope.answeredTwo = true;
}
};
$scope.createTest = function() {
console.log("message");
var test = new Tests({
questions: $scope.questions,
optionOne: $scope.optionOne,
optionTwo: $scope.optionTwo,
testName: $scope.testName,
answerOne: $scope.test.answerOne,
answerTwo: $scope.test.answerTwo
});
console.log('message', test);
test.$save(function(response) {
$location.path('/admin/test');
}, function(response) {
$scope.error = response.message;
});
};
$scope.createQuestion = function() {
var test = new Tests({
_id: $stateParams.testId,
question: $scope.question,
option: $scope.optionOne,
answer: $scope.test.answerOne
});
test.$save(function(response) {
$location.path('/admin/test');
}, function(err) {
$scope.error = err.message;
});
};
$scope.viewTests = function() {
var tests = Tests.query(function success(response) {
$scope.tests = response;
});
};
$scope.viewTest = function() {
Tests.get({
testId: $stateParams.testId
}, function success(response) {
$scope.test = response;
$scope.testNameEditorEnabled = false;
$scope.questionEditorEnabled = [];
$scope.editableQuestion = [];
$scope.optionEditorEnabled = [];
$scope.editableOption = [];
$scope.displayerrmsg = [];
for (var i in $scope.test.questions) {
$scope.questionEditorEnabled[i] = false;
$scope.optionEditorEnabled[i] = [];
$scope.editableOption[i] = [];
for (var j in $scope.test.questions[i].questOptions) {
$scope.optionEditorEnabled[i][j] = false;
$scope.editableOption[i][j] = {};
}
}
$scope.enableEditor = function(field, index, optionIndex) {
if (field === 'testName') {
$scope.testNameEditorEnabled = true;
$scope.editabletestName = $scope.test.testName;
}
if (field === 'question') {
$scope.questionEditorEnabled[index] = true;
$scope.editableQuestion[index] = $scope.test.questions[index].question;
}
if (field === 'option') {
$scope.optionEditorEnabled[index][optionIndex] = true;
$scope.editableOption[index][optionIndex].option =
$scope.test.questions[index].questOptions[optionIndex].option;
}
};
$scope.disableEditor = function(field, index, optionIndex) {
if (field === 'testName') {
$scope.testNameEditorEnabled = false;
}
if (field === 'question') {
$scope.questionEditorEnabled[index] = false;
}
if (field === 'option') {
$scope.optionEditorEnabled[index][optionIndex] = false;
}
};
// Checks to see if all answers are set to same (false/true).
// Returns true if all are the same
var checkAllanswers = function(questOptions) {
var firstOption = questOptions[0].answer
for (var i in questOptions) {
if (firstOption !== questOptions[i].answer) {
return false;
}
}
return true;
};
$scope.save = function(field, index, optionIndex) {
if (field === 'testName') {
$scope.test.testName = $scope.editabletestName;
$scope.changeTestName($scope.test);
}
if (field === 'question') {
$scope.test.questions[index].question = $scope.editableQuestion[index];
$scope.updateQuestion($scope.test, index);
}
if (field === 'option') {
$scope.test.questions[index].questOptions[optionIndex].option =
$scope.editableOption[index][optionIndex].option;
if ($scope.editableOption[index][optionIndex].answer === undefined ||
$scope.editableOption[index][optionIndex].answer === 'undefined') {
$scope.editableOption[index][optionIndex].answer = false;
}
// if the option's answer field changes, then change others to it's oppossite
if ($scope.editableOption[index][optionIndex].answer === true) {
for (var i in $scope.test.questions[index].questOptions) {
if (i === optionIndex) {
continue;
}
$scope.test.questions[index].questOptions[i].answer = false;
}
}
$scope.test.questions[index].questOptions[optionIndex].answer =
$scope.editableOption[index][optionIndex].answer;
// Set error message if no answer is selected
if (checkAllanswers($scope.test.questions[index].questOptions)) {
$scope.displayerrmsg[index] = true;
} else {
$scope.displayerrmsg[index] = false;
}
$scope.updateQuestion($scope.test, index);
}
$scope.disableEditor(field, index, optionIndex);
};
} //ends test.get() success callbk
);
};
$scope.changeTestName = function(test) {
test.$update({
_id: test._id
}, function success() {},
function(errorResponse) {
$scope.error = errorResponse;
});
};
$scope.updateQuestion = function(test, quesIndex) {
var question = test.questions[quesIndex];
$http.put('/admin/test/' + test._id + '/' + test.questions[quesIndex]._id, question).success(function(response) {}).error(function(response) {
$scope.error = response.message;
});
};
$scope.deleteTest = function(test, index) {
$scope.tests.splice(index, 1);
test.$remove({
_id: test._id
}, function success() {}, function(response) {
$scope.error = response.message;
});
};
$scope.deleteQuestion = function(testId, questionId, index) {
$scope.test.questions.splice(index, 1);
$http.delete('/admin/test/' + testId + '/' + questionId).success(function(response) {
$scope.success = true;
}).error(function(response) {
$scope.error = response.message;
});
};
$scope.deleteOption = function(testId, questionId, optionId, queIndex, index) {
$scope.test.questions[queIndex].questOptions.splice(index, 1);
$http.delete('/admin/test/' + testId + '/' + questionId + '/' + optionId).success(function(response) {
$scope.success = true;
}).error(function(response) {
$scope.error = response.message;
});
};
}
]);
|
Fixed Issue with Admin Creating Test
|
public/modules/admin/controllers/admin.client.tests.controller.js
|
Fixed Issue with Admin Creating Test
|
<ide><path>ublic/modules/admin/controllers/admin.client.tests.controller.js
<ide> };
<ide>
<ide> $scope.createTest = function() {
<del> console.log("message");
<ide> var test = new Tests({
<ide> questions: $scope.questions,
<ide> optionOne: $scope.optionOne,
<ide> answerOne: $scope.test.answerOne,
<ide> answerTwo: $scope.test.answerTwo
<ide> });
<del> console.log('message', test);
<ide> test.$save(function(response) {
<ide> $location.path('/admin/test');
<ide> }, function(response) {
|
|
JavaScript
|
mit
|
c7dcc9de0036d1006c9a38a3eaec4f1968fea76e
| 0 |
tobes31415/processing-pipeline,tobes31415/processing-pipeline
|
export default function Deferred()
{
var self = {};
self.promise = new Promise(function(resolve, reject)
{
self.resolve = resolve;
self.reject = reject;
});
return self;
}
|
libSrc/deferred.js
|
export default function Deferred()
{
var self = this ||
{};
self.promise = new Promise(function(resolve, reject)
{
self.resolve = resolve;
self.reject = reject;
});
return self;
}
|
Webpack causes the deferred to behave as a singleton, fixed now
|
libSrc/deferred.js
|
Webpack causes the deferred to behave as a singleton, fixed now
|
<ide><path>ibSrc/deferred.js
<ide> export default function Deferred()
<ide> {
<del> var self = this ||
<del> {};
<add> var self = {};
<ide> self.promise = new Promise(function(resolve, reject)
<ide> {
<ide> self.resolve = resolve;
|
|
Java
|
apache-2.0
|
0fd9f4c7e629fea2406e17091e8aac4377aabc9a
| 0 |
ShootGame/Arcade2
|
/*
* Copyright 2018 Aleksander Jagiełł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 pl.themolka.arcade.item;
import com.google.common.collect.ImmutableMap;
import org.bukkit.inventory.ItemFlag;
import pl.themolka.arcade.dom.Element;
import pl.themolka.arcade.parser.Context;
import pl.themolka.arcade.parser.ElementParser;
import pl.themolka.arcade.parser.EnumParser;
import pl.themolka.arcade.parser.InstallableParser;
import pl.themolka.arcade.parser.Parser;
import pl.themolka.arcade.parser.ParserException;
import pl.themolka.arcade.parser.ParserLibrary;
import pl.themolka.arcade.parser.ParserNotSupportedException;
import pl.themolka.arcade.parser.Produces;
import pl.themolka.arcade.parser.Result;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
@Produces(ItemFlag.class)
public class ItemFlagParser extends ElementParser<ItemFlag>
implements InstallableParser {
private static final Map<String, ItemFlag> BINDINGS = ImmutableMap.<String, ItemFlag>builder()
.put("hide destroy keys", ItemFlag.HIDE_DESTROYS)
.put("hide destroyable keys", ItemFlag.HIDE_DESTROYS)
.put("hide enchantments", ItemFlag.HIDE_ENCHANTS)
.put("hide place keys", ItemFlag.HIDE_PLACED_ON)
.put("hide place on keys", ItemFlag.HIDE_PLACED_ON)
.put("hide placeable keys", ItemFlag.HIDE_PLACED_ON)
.put("hide placeable on keys", ItemFlag.HIDE_PLACED_ON)
.put("hide effects", ItemFlag.HIDE_POTION_EFFECTS)
.build();
private Parser<ItemFlag> flagParser;
@Override
public void install(ParserLibrary library) throws ParserNotSupportedException {
this.flagParser = library.enumType(ItemFlag.class);
}
@Override
public Set<Object> expect() {
return Collections.singleton("item flag");
}
@Override
protected Result<ItemFlag> parseElement(Context context, Element element, String name, String value) throws ParserException {
String input = EnumParser.toPrettyValue(value);
ItemFlag maybeBinding = BINDINGS.get(input);
if (maybeBinding != null) {
return Result.fine(element, name, value, maybeBinding);
}
return this.flagParser.parseWithDefinition(context, element, name, value);
}
}
|
src/main/java/pl/themolka/arcade/item/ItemFlagParser.java
|
/*
* Copyright 2018 Aleksander Jagiełł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 pl.themolka.arcade.item;
import com.google.common.collect.ImmutableMap;
import org.bukkit.inventory.ItemFlag;
import pl.themolka.arcade.dom.Element;
import pl.themolka.arcade.parser.Context;
import pl.themolka.arcade.parser.ElementParser;
import pl.themolka.arcade.parser.EnumParser;
import pl.themolka.arcade.parser.InstallableParser;
import pl.themolka.arcade.parser.Parser;
import pl.themolka.arcade.parser.ParserException;
import pl.themolka.arcade.parser.ParserLibrary;
import pl.themolka.arcade.parser.ParserNotSupportedException;
import pl.themolka.arcade.parser.Produces;
import pl.themolka.arcade.parser.Result;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
@Produces(ItemFlagParser.class)
public class ItemFlagParser extends ElementParser<ItemFlag>
implements InstallableParser {
private static final Map<String, ItemFlag> BINDINGS = ImmutableMap.<String, ItemFlag>builder()
.put("hide destroy keys", ItemFlag.HIDE_DESTROYS)
.put("hide destroyable keys", ItemFlag.HIDE_DESTROYS)
.put("hide enchantments", ItemFlag.HIDE_ENCHANTS)
.put("hide place keys", ItemFlag.HIDE_PLACED_ON)
.put("hide place on keys", ItemFlag.HIDE_PLACED_ON)
.put("hide placeable keys", ItemFlag.HIDE_PLACED_ON)
.put("hide placeable on keys", ItemFlag.HIDE_PLACED_ON)
.put("hide effects", ItemFlag.HIDE_POTION_EFFECTS)
.build();
private Parser<ItemFlag> flagParser;
@Override
public void install(ParserLibrary library) throws ParserNotSupportedException {
this.flagParser = library.enumType(ItemFlag.class);
}
@Override
public Set<Object> expect() {
return Collections.singleton("item flag");
}
@Override
protected Result<ItemFlag> parseElement(Context context, Element element, String name, String value) throws ParserException {
String input = EnumParser.toPrettyValue(value);
ItemFlag maybeBinding = BINDINGS.get(input);
if (maybeBinding != null) {
return Result.fine(element, name, value, maybeBinding);
}
return this.flagParser.parseWithDefinition(context, element, name, value);
}
}
|
Fix typo
|
src/main/java/pl/themolka/arcade/item/ItemFlagParser.java
|
Fix typo
|
<ide><path>rc/main/java/pl/themolka/arcade/item/ItemFlagParser.java
<ide> import java.util.Map;
<ide> import java.util.Set;
<ide>
<del>@Produces(ItemFlagParser.class)
<add>@Produces(ItemFlag.class)
<ide> public class ItemFlagParser extends ElementParser<ItemFlag>
<ide> implements InstallableParser {
<ide> private static final Map<String, ItemFlag> BINDINGS = ImmutableMap.<String, ItemFlag>builder()
|
|
Java
|
apache-2.0
|
ea62df23634838d536e4faeea1c461a10635ce14
| 0 |
melsiddieg/cellbase,opencb/cellbase,dapregi/cellbase,jpdna/cellbase,Swaathik/cellbase,opencb/cellbase,dapregi/cellbase,jpdna/cellbase,jpdna/cellbase,opencb/cellbase,dapregi/cellbase,opencb/cellbase,opencb/cellbase,dapregi/cellbase,melsiddieg/cellbase,melsiddieg/cellbase,Swaathik/cellbase,Swaathik/cellbase,jpdna/cellbase,melsiddieg/cellbase,melsiddieg/cellbase,Swaathik/cellbase,jpdna/cellbase,Swaathik/cellbase,Swaathik/cellbase,melsiddieg/cellbase,opencb/cellbase,opencb/cellbase,jpdna/cellbase,melsiddieg/cellbase,dapregi/cellbase,Swaathik/cellbase,dapregi/cellbase,dapregi/cellbase
|
package org.opencb.cellbase.mongodb.loader;
import com.mongodb.BulkWriteResult;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
import org.apache.commons.lang.StringUtils;
import org.opencb.cellbase.core.CellBaseConfiguration;
import org.opencb.cellbase.core.loader.CellBaseLoader;
import org.opencb.cellbase.core.loader.LoadRunner;
import org.opencb.cellbase.core.loader.LoaderException;
import org.opencb.cellbase.mongodb.MongoDBCollectionConfiguration;
import org.opencb.datastore.core.QueryOptions;
import org.opencb.datastore.core.QueryResult;
import org.opencb.datastore.mongodb.MongoDBCollection;
import org.opencb.datastore.mongodb.MongoDBConfiguration;
import org.opencb.datastore.mongodb.MongoDataStore;
import org.opencb.datastore.mongodb.MongoDataStoreManager;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
/**
* Created by parce on 18/02/15.
*/
public class MongoDBCellBaseLoader extends CellBaseLoader {
private MongoDataStoreManager mongoDataStoreManager;
private MongoDataStore mongoDataStore;
private MongoDBCollection mongoDBCollection;
private Path indexScriptFolder;
private int[] chunkSizes;
public MongoDBCellBaseLoader(BlockingQueue<List<String>> queue, String data, String database,
Map<String, String> params) {
this(queue, data, database, params, null);
}
public MongoDBCellBaseLoader(BlockingQueue<List<String>> queue, String data, String database,
Map<String, String> params, CellBaseConfiguration cellBaseConfiguration) {
super(queue, data, database, params, cellBaseConfiguration);
if(loaderParams.get("mongodb-index-folder") != null) {
indexScriptFolder = Paths.get(loaderParams.get("mongodb-index-folder"));
}
}
@Override
public void init() throws LoaderException {
/*
* OpenCB 'datastore' project is used to load data into MongoDB. The following code:
* 1. creates a Manager to connect to a physical server
* 2. a 'datastore' object connects to a specific database
* 3. finally a connection to the collection is stored in 'mongoDBCollection'
*/
mongoDataStoreManager = new MongoDataStoreManager(cellBaseConfiguration.getDatabase().getHost(),
Integer.parseInt(cellBaseConfiguration.getDatabase().getPort()));
MongoDBConfiguration mongoDBConfiguration;
if(loaderParams != null && loaderParams.get("authenticationDatabase") != null) {
mongoDBConfiguration = MongoDBConfiguration.builder()
.add("username", cellBaseConfiguration.getDatabase().getUser())
.add("password", cellBaseConfiguration.getDatabase().getPassword())
.add("authenticationDatabase", loaderParams.get("authenticationDatabase")).build();
logger.debug("MongoDB 'authenticationDatabase' database parameter set to '{}'",
loaderParams.get("authenticationDatabase"));
}else {
mongoDBConfiguration = MongoDBConfiguration.builder()
.add("username", cellBaseConfiguration.getDatabase().getUser())
.add("password", cellBaseConfiguration.getDatabase().getPassword()).build();
}
logger.debug("MongoDB credentials are user: '{}', password: '{}'",
cellBaseConfiguration.getDatabase().getUser(), cellBaseConfiguration.getDatabase().getPassword());
mongoDataStore = mongoDataStoreManager.get(database, mongoDBConfiguration);
String collectionName = getCollectionName(data);
mongoDBCollection = mongoDataStore.getCollection(collectionName);
logger.debug("Connection to MongoDB datastore '{}' created, collection '{}' is used",
mongoDataStore.getDatabaseName(), collectionName);
// Some collections need to add an extra _chunkIds field to speed up some queries
getChunkSizes(collectionName);
logger.debug("Chunk sizes '{}' used for collection '{}'", Arrays.toString(chunkSizes), collectionName);
}
private String getCollectionName(String data) throws LoaderException {
String collectionName;
switch (data) {
case "genome_info":
collectionName = "genome_info";
break;
case "genome_sequence":
collectionName = "genome_sequence";
break;
case "gene":
collectionName = "gene";
break;
case "variation":
collectionName = "variation";
break;
case "regulatory_region":
collectionName = "regulatory_region";
break;
case "protein":
collectionName = "protein";
break;
case "protein_protein_interaction":
collectionName = "protein_protein_interaction";
break;
case "conservation":
collectionName = "conservation";
break;
case "cosmic":
case "clinvar":
case "gwas":
case "clinical":
collectionName = "clinical";
break;
default:
throw new LoaderException("Unknown data to load: '" + data + "'");
}
return collectionName;
}
private void getChunkSizes(String collectionName) {
if (collectionName != null) {
switch (collectionName) {
case "genome_sequence":
chunkSizes = new int[]{MongoDBCollectionConfiguration.GENOME_SEQUENCE_CHUNK_SIZE};
break;
case "gene":
chunkSizes = new int[]{MongoDBCollectionConfiguration.GENE_CHUNK_SIZE};
break;
case "variation":
chunkSizes = new int[]{MongoDBCollectionConfiguration.VARIATION_CHUNK_SIZE,
10 * MongoDBCollectionConfiguration.VARIATION_CHUNK_SIZE};
break;
case "regulatory_region":
chunkSizes = new int[]{MongoDBCollectionConfiguration.REGULATORY_REGION_CHUNK_SIZE};
break;
case "conservation":
chunkSizes = new int[]{MongoDBCollectionConfiguration.CONSERVATION_CHUNK_SIZE};
break;
default:
break;
}
}
}
@Override
public Integer call() {
Integer loadedObjects = 0;
boolean finished = false;
while (!finished) {
try {
List<String> batch = blockingQueue.take();
if (batch == LoadRunner.POISON_PILL) {
finished = true;
} else {
List<DBObject> dbObjectsBatch = new ArrayList<>(batch.size());
for (String jsonLine : batch) {
DBObject dbObject = (DBObject) JSON.parse(jsonLine);
addChunkId(dbObject);
dbObjectsBatch.add(dbObject);
}
loadedObjects += load(dbObjectsBatch);
}
} catch (InterruptedException e) {
logger.error("Loader thread interrupted: " + e.getMessage());
} catch (Exception e) {
logger.error("Error Loading batch: " + e.getMessage());
}
}
logger.debug("'load' finished. " + loadedObjects + " records loaded");
return loadedObjects;
}
@Override
public void createIndex(String data) throws LoaderException {
Path indexFilePath = getIndexFilePath(data);
if(indexFilePath != null) {
try {
runCreateIndexProcess(indexFilePath);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
logger.warn("No index found for '{}'", data); }
}
public int load(List<DBObject> batch) {
// TODO: queryOptions?
QueryResult<BulkWriteResult> result = mongoDBCollection.insert(batch, new QueryOptions());
return result.first().getInsertedCount();
}
private void addChunkId(DBObject dbObject) {
if (chunkSizes != null && chunkSizes.length > 0) {
List<String> chunkIds = new ArrayList<>();
for (int chunkSize : chunkSizes) {
int chunkStart = (Integer) dbObject.get("start") / chunkSize;
int chunkEnd = (Integer) dbObject.get("end") / chunkSize;
String chunkIdSuffix = chunkSize / 1000 + "k";
for (int i = chunkStart; i <= chunkEnd; i++) {
if(dbObject.containsField("chromosome")) {
chunkIds.add(dbObject.get("chromosome") + "_" + i + "_" + chunkIdSuffix);
}else {
chunkIds.add(dbObject.get("sequenceName") + "_" + i + "_" + chunkIdSuffix);
}
}
}
dbObject.put("_chunkIds", chunkIds);
}
}
@Override
public void close() {
mongoDataStoreManager.close(database);
}
private Path getIndexFilePath(String data) throws LoaderException {
if(indexScriptFolder == null || data == null) {
logger.error("No path can be provided for index, check index folder '{}' and data '{}'",
indexScriptFolder, data);
return null;
}
String indexFileName = null;
switch (data) {
case "genome_info":
indexFileName = null;
break;
case "genome_sequence":
indexFileName = "genome_sequence-indexes.js";
break;
case "gene":
indexFileName = "gene-indexes.js";
break;
case "variation":
indexFileName = "variation-indexes.js";
break;
case "regulatory_region":
indexFileName = "regulatory_region-indexes.js";
break;
case "protein":
indexFileName = "protein-indexes.js";
break;
case "conservation":
indexFileName = "conserved_region-indexes.js";
break;
case "cosmic":
case "clinvar":
case "gwas":
case "clinical":
indexFileName = "clinical";
break;
default:
break;
}
if(indexFileName == null) {
return null;
}
return indexScriptFolder.resolve(indexFileName);
}
protected boolean runCreateIndexProcess(Path indexFilePath) throws IOException, InterruptedException {
List<String> args = new ArrayList<>();
args.add("mongo");
args.add("--host");
args.add(cellBaseConfiguration.getDatabase().getHost());
if(cellBaseConfiguration.getDatabase().getUser() != null && !cellBaseConfiguration.getDatabase().getUser().equals("")) {
args.addAll(Arrays.asList(
"-u", cellBaseConfiguration.getDatabase().getUser(),
"-p", cellBaseConfiguration.getDatabase().getPassword()
));
}
if(loaderParams != null && loaderParams.get("authenticationDatabase") != null) {
args.add("--authenticationDatabase");
args.add(loaderParams.get("authenticationDatabase"));
logger.debug("MongoDB 'authenticationDatabase' database parameter set to '{}'",
loaderParams.get("authenticationDatabase"));
}
args.add(database);
args.add(indexFilePath.toString());
ProcessBuilder processBuilder = new ProcessBuilder(args);
logger.debug("Executing command: '{}'", StringUtils.join(processBuilder.command(), " "));
// processBuilder.redirectErrorStream(true);
// if (logFilePath != null) {
// processBuilder.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(logFilePath)));
// }
Process process = processBuilder.start();
process.waitFor();
// Check process output
boolean executedWithoutErrors = true;
int genomeInfoExitValue = process.exitValue();
if (genomeInfoExitValue != 0) {
logger.warn("Error executing {}, error code: {}", indexFilePath, genomeInfoExitValue);
executedWithoutErrors = false;
}
return executedWithoutErrors;
}
// private ProcessBuilder getProcessBuilder(List<String> args, String logFilePath) {
// ProcessBuilder builder = new ProcessBuilder(args);
//
// builder.redirectErrorStream(true);
// if (logFilePath != null) {
// builder.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(logFilePath)));
// }
//
// return builder;
// }
}
|
cellbase-mongodb/src/main/java/org/opencb/cellbase/mongodb/loader/MongoDBCellBaseLoader.java
|
package org.opencb.cellbase.mongodb.loader;
import com.mongodb.BulkWriteResult;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
import org.apache.commons.lang.StringUtils;
import org.opencb.cellbase.core.CellBaseConfiguration;
import org.opencb.cellbase.core.loader.CellBaseLoader;
import org.opencb.cellbase.core.loader.LoadRunner;
import org.opencb.cellbase.core.loader.LoaderException;
import org.opencb.cellbase.mongodb.MongoDBCollectionConfiguration;
import org.opencb.datastore.core.QueryOptions;
import org.opencb.datastore.core.QueryResult;
import org.opencb.datastore.mongodb.MongoDBCollection;
import org.opencb.datastore.mongodb.MongoDBConfiguration;
import org.opencb.datastore.mongodb.MongoDataStore;
import org.opencb.datastore.mongodb.MongoDataStoreManager;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
/**
* Created by parce on 18/02/15.
*/
public class MongoDBCellBaseLoader extends CellBaseLoader {
private MongoDataStoreManager mongoDataStoreManager;
private MongoDataStore mongoDataStore;
private MongoDBCollection mongoDBCollection;
private Path indexScriptFolder;
private int[] chunkSizes;
public MongoDBCellBaseLoader(BlockingQueue<List<String>> queue, String data, String database,
Map<String, String> params) {
this(queue, data, database, params, null);
}
public MongoDBCellBaseLoader(BlockingQueue<List<String>> queue, String data, String database,
Map<String, String> params, CellBaseConfiguration cellBaseConfiguration) {
super(queue, data, database, params, cellBaseConfiguration);
if(loaderParams.get("mongodb-index-folder") != null) {
indexScriptFolder = Paths.get(loaderParams.get("mongodb-index-folder"));
}
}
@Override
public void init() throws LoaderException {
/*
* OpenCB 'datastore' project is used to load data into MongoDB. The following code:
* 1. creates a Manager to connect to a physical server
* 2. a 'datastore' object connects to a specific database
* 3. finally a connection to the collection is stored in 'mongoDBCollection'
*/
mongoDataStoreManager = new MongoDataStoreManager(cellBaseConfiguration.getDatabase().getHost(),
Integer.parseInt(cellBaseConfiguration.getDatabase().getPort()));
MongoDBConfiguration mongoDBConfiguration;
if(loaderParams != null && loaderParams.get("authenticationDatabase") != null) {
mongoDBConfiguration = MongoDBConfiguration.builder()
.add("username", cellBaseConfiguration.getDatabase().getUser())
.add("password", cellBaseConfiguration.getDatabase().getPassword())
.add("authenticationDatabase", loaderParams.get("authenticationDatabase")).build();
logger.debug("MongoDB 'authenticationDatabase' database parameter set to '{}'",
loaderParams.get("authenticationDatabase"));
}else {
mongoDBConfiguration = MongoDBConfiguration.builder()
.add("username", cellBaseConfiguration.getDatabase().getUser())
.add("password", cellBaseConfiguration.getDatabase().getPassword()).build();
}
logger.debug("MongoDB credentials are user: '{}', password: '{}'",
cellBaseConfiguration.getDatabase().getUser(), cellBaseConfiguration.getDatabase().getPassword());
mongoDataStore = mongoDataStoreManager.get(database, mongoDBConfiguration);
String collectionName = getCollectionName(data);
mongoDBCollection = mongoDataStore.getCollection(collectionName);
logger.debug("Connection to MongoDB datastore '{}' created, collection '{}' is used",
mongoDataStore.getDatabaseName(), collectionName);
// Some collections need to add an extra _chunkIds field to speed up some queries
getChunkSizes(collectionName);
logger.debug("Chunk sizes '{}' used for collection '{}'", Arrays.toString(chunkSizes), collectionName);
}
private String getCollectionName(String data) throws LoaderException {
String collectionName;
switch (data) {
case "genome_info":
collectionName = "genome_info";
break;
case "genome_sequence":
collectionName = "genome_sequence";
break;
case "gene":
collectionName = "gene";
break;
case "variation":
collectionName = "variation";
break;
case "regulatory_region":
collectionName = "regulatory_region";
break;
case "protein":
collectionName = "protein";
break;
case "conservation":
collectionName = "conservation";
break;
case "cosmic":
case "clinvar":
case "gwas":
case "clinical":
collectionName = "clinical";
break;
default:
throw new LoaderException("Unknown data to load: '" + data + "'");
}
return collectionName;
}
private void getChunkSizes(String collectionName) {
if (collectionName != null) {
switch (collectionName) {
case "genome_sequence":
chunkSizes = new int[]{MongoDBCollectionConfiguration.GENOME_SEQUENCE_CHUNK_SIZE};
break;
case "gene":
chunkSizes = new int[]{MongoDBCollectionConfiguration.GENE_CHUNK_SIZE};
break;
case "variation":
chunkSizes = new int[]{MongoDBCollectionConfiguration.VARIATION_CHUNK_SIZE,
10 * MongoDBCollectionConfiguration.VARIATION_CHUNK_SIZE};
break;
case "regulatory_region":
chunkSizes = new int[]{MongoDBCollectionConfiguration.REGULATORY_REGION_CHUNK_SIZE};
break;
case "conservation":
chunkSizes = new int[]{MongoDBCollectionConfiguration.CONSERVATION_CHUNK_SIZE};
break;
default:
break;
}
}
}
@Override
public Integer call() {
Integer loadedObjects = 0;
boolean finished = false;
while (!finished) {
try {
List<String> batch = blockingQueue.take();
if (batch == LoadRunner.POISON_PILL) {
finished = true;
} else {
List<DBObject> dbObjectsBatch = new ArrayList<>(batch.size());
for (String jsonLine : batch) {
DBObject dbObject = (DBObject) JSON.parse(jsonLine);
addChunkId(dbObject);
dbObjectsBatch.add(dbObject);
}
loadedObjects += load(dbObjectsBatch);
}
} catch (InterruptedException e) {
logger.error("Loader thread interrupted: " + e.getMessage());
} catch (Exception e) {
logger.error("Error Loading batch: " + e.getMessage());
}
}
logger.debug("'load' finished. " + loadedObjects + " records loaded");
return loadedObjects;
}
@Override
public void createIndex(String data) throws LoaderException {
Path indexFilePath = getIndexFilePath(data);
if(indexFilePath != null) {
try {
runCreateIndexProcess(indexFilePath);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
logger.warn("No index found for '{}'", data); }
}
public int load(List<DBObject> batch) {
// TODO: queryOptions?
QueryResult<BulkWriteResult> result = mongoDBCollection.insert(batch, new QueryOptions());
return result.first().getInsertedCount();
}
private void addChunkId(DBObject dbObject) {
if (chunkSizes != null && chunkSizes.length > 0) {
List<String> chunkIds = new ArrayList<>();
for (int chunkSize : chunkSizes) {
int chunkStart = (Integer) dbObject.get("start") / chunkSize;
int chunkEnd = (Integer) dbObject.get("end") / chunkSize;
String chunkIdSuffix = chunkSize / 1000 + "k";
for (int i = chunkStart; i <= chunkEnd; i++) {
if(dbObject.containsField("chromosome")) {
chunkIds.add(dbObject.get("chromosome") + "_" + i + "_" + chunkIdSuffix);
}else {
chunkIds.add(dbObject.get("sequenceName") + "_" + i + "_" + chunkIdSuffix);
}
}
}
dbObject.put("_chunkIds", chunkIds);
}
}
@Override
public void close() {
mongoDataStoreManager.close(database);
}
private Path getIndexFilePath(String data) throws LoaderException {
if(indexScriptFolder == null || data == null) {
logger.error("No path can be provided for index, check index folder '{}' and data '{}'",
indexScriptFolder, data);
return null;
}
String indexFileName = null;
switch (data) {
case "genome_info":
indexFileName = null;
break;
case "genome_sequence":
indexFileName = "genome_sequence-indexes.js";
break;
case "gene":
indexFileName = "gene-indexes.js";
break;
case "variation":
indexFileName = "variation-indexes.js";
break;
case "regulatory_region":
indexFileName = "regulatory_region-indexes.js";
break;
case "protein":
indexFileName = "protein-indexes.js";
break;
case "conservation":
indexFileName = "conserved_region-indexes.js";
break;
case "cosmic":
case "clinvar":
case "gwas":
case "clinical":
indexFileName = "clinical";
break;
default:
break;
}
if(indexFileName == null) {
return null;
}
return indexScriptFolder.resolve(indexFileName);
}
protected boolean runCreateIndexProcess(Path indexFilePath) throws IOException, InterruptedException {
List<String> args = new ArrayList<>();
args.add("mongo");
args.add("--host");
args.add(cellBaseConfiguration.getDatabase().getHost());
if(cellBaseConfiguration.getDatabase().getUser() != null && !cellBaseConfiguration.getDatabase().getUser().equals("")) {
args.addAll(Arrays.asList(
"-u", cellBaseConfiguration.getDatabase().getUser(),
"-p", cellBaseConfiguration.getDatabase().getPassword()
));
}
if(loaderParams != null && loaderParams.get("authenticationDatabase") != null) {
args.add("--authenticationDatabase");
args.add(loaderParams.get("authenticationDatabase"));
logger.debug("MongoDB 'authenticationDatabase' database parameter set to '{}'",
loaderParams.get("authenticationDatabase"));
}
args.add(database);
args.add(indexFilePath.toString());
ProcessBuilder processBuilder = new ProcessBuilder(args);
logger.debug("Executing command: '{}'", StringUtils.join(processBuilder.command(), " "));
// processBuilder.redirectErrorStream(true);
// if (logFilePath != null) {
// processBuilder.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(logFilePath)));
// }
Process process = processBuilder.start();
process.waitFor();
// Check process output
boolean executedWithoutErrors = true;
int genomeInfoExitValue = process.exitValue();
if (genomeInfoExitValue != 0) {
logger.warn("Error executing {}, error code: {}", indexFilePath, genomeInfoExitValue);
executedWithoutErrors = false;
}
return executedWithoutErrors;
}
// private ProcessBuilder getProcessBuilder(List<String> args, String logFilePath) {
// ProcessBuilder builder = new ProcessBuilder(args);
//
// builder.redirectErrorStream(true);
// if (logFilePath != null) {
// builder.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(logFilePath)));
// }
//
// return builder;
// }
}
|
CellBase 'protein_protein_interaction' collection name fixed
|
cellbase-mongodb/src/main/java/org/opencb/cellbase/mongodb/loader/MongoDBCellBaseLoader.java
|
CellBase 'protein_protein_interaction' collection name fixed
|
<ide><path>ellbase-mongodb/src/main/java/org/opencb/cellbase/mongodb/loader/MongoDBCellBaseLoader.java
<ide> break;
<ide> case "protein":
<ide> collectionName = "protein";
<add> break;
<add> case "protein_protein_interaction":
<add> collectionName = "protein_protein_interaction";
<ide> break;
<ide> case "conservation":
<ide> collectionName = "conservation";
|
|
JavaScript
|
apache-2.0
|
b72d6cbc860e3540dbd6fc2e0d4b0ff8fefd4402
| 0 |
GoogleCloudPlatform/PerfKitExplorer,GoogleCloudPlatform/PerfKitExplorer,GoogleCloudPlatform/PerfKitExplorer,GoogleCloudPlatform/PerfKitExplorer
|
/**
* @copyright Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @fileoverview dashboardService is an angular service used to maintain the
* data related to the dashboard and to manage the dashboard's widgets.
* @author [email protected] (Joe Allan Muharsky)
*/
goog.provide('p3rf.perfkit.explorer.components.dashboard.DashboardService');
goog.require('p3rf.perfkit.explorer.components.error.ErrorModel');
goog.require('p3rf.perfkit.explorer.components.error.ErrorService');
goog.require('p3rf.perfkit.explorer.components.error.ErrorTypes');
goog.require('p3rf.perfkit.explorer.components.config.ConfigService');
goog.require('p3rf.perfkit.explorer.components.container.ContainerWidgetConfig');
goog.require('p3rf.perfkit.explorer.components.container.ContainerWidgetModel');
goog.require('p3rf.perfkit.explorer.components.dashboard.DashboardInstance');
goog.require('p3rf.perfkit.explorer.components.dashboard.DashboardDataService');
goog.require('p3rf.perfkit.explorer.components.dashboard.DashboardModel');
goog.require('p3rf.perfkit.explorer.components.dashboard.DashboardParam');
goog.require('p3rf.perfkit.explorer.components.dashboard.DashboardVersionService');
goog.require('p3rf.perfkit.explorer.components.explorer.ExplorerStateService');
goog.require('p3rf.perfkit.explorer.components.explorer.sidebar.SidebarTabService');
goog.require('p3rf.perfkit.explorer.components.util.ArrayUtilService');
goog.require('p3rf.perfkit.explorer.components.widget.WidgetFactoryService');
goog.require('p3rf.perfkit.explorer.components.widget.query.builder.QueryBuilderService');
goog.require('p3rf.perfkit.explorer.models.ChartWidgetConfig');
goog.require('p3rf.perfkit.explorer.models.ResultsDataStatus');
goog.require('p3rf.perfkit.explorer.models.WidgetConfig');
goog.require('p3rf.perfkit.explorer.models.WidgetType');
goog.require('p3rf.perfkit.explorer.models.perfkit_simple_builder.QueryTablePartitioning');
goog.require('goog.array');
goog.require('goog.asserts');
goog.scope(function() {
const explorer = p3rf.perfkit.explorer;
const ArrayUtilService = explorer.components.util.ArrayUtilService;
const ChartWidgetConfig = explorer.models.ChartWidgetConfig;
const ConfigService = explorer.components.config.ConfigService;
const ContainerWidgetConfig = explorer.components.container.ContainerWidgetConfig;
const DashboardInstance = explorer.components.dashboard.DashboardInstance;
const DashboardModel = explorer.components.dashboard.DashboardModel;
const DashboardParam = explorer.components.dashboard.DashboardParam;
const DashboardDataService = explorer.components.dashboard.DashboardDataService;
const ExplorerStateService = explorer.components.explorer.ExplorerStateService;
const SidebarTabService = explorer.components.explorer.sidebar.SidebarTabService;
const ErrorService = explorer.components.error.ErrorService;
const ErrorTypes = explorer.components.error.ErrorTypes;
const QueryBuilderService = (
explorer.components.widget.query.builder.QueryBuilderService);
const QueryTablePartitioning = (
explorer.models.perfkit_simple_builder.QueryTablePartitioning);
const ResultsDataStatus = explorer.models.ResultsDataStatus;
const WidgetConfig = explorer.models.WidgetConfig;
const WidgetFactoryService = explorer.components.widget.WidgetFactoryService;
const WidgetType = explorer.models.WidgetType;
/**
* See module docstring for more information about purpose and usage.
*
* @param {!ArrayUtilService} arrayUtilService
* @param {!ErrorService} errorService
* @param {!WidgetFactoryService} widgetFactoryService
* @param {!DashboardDataService} dashboardDataService
* @param {!QueryBuilderService} queryBuilderService
* @param {!ConfigService} configService
* @param {!ExplorerStateService} explorerStateService
* @param {!SidebarTabService} sidebarTabService
* @param {!angular.$filter} $filter
* @param {!angular.$location} $location
* @param {!angular.Scope} $rootScope
* @param {!angular.$timeout} $timeout
* @param {!angular.$window} $window
* @constructor
* @ngInject
*/
explorer.components.dashboard.DashboardService = function(arrayUtilService,
errorService, widgetFactoryService, dashboardDataService,
queryBuilderService, dashboardVersionService, configService,
explorerStateService, sidebarTabService, $filter, $location, $rootScope,
$timeout, $window, $state, $stateParams) {
/** @private {!angular.$filter} */
this.filter_ = $filter;
/** @private {!angular.Scope} */
this.rootScope_ = $rootScope;
/** @private {!angular.$timeout} */
this.timeout_ = $timeout;
/** @export {!ConfigService} */
this.config = configService;
/** @private {!ArrayUtilService} */
this.arrayUtilService_ = arrayUtilService;
/** @private {!ErrorService} */
this.errorService_ = errorService;
/** @private {!ExplorerStateService} */
this.explorerStateService_ = explorerStateService;
/** @private {!SidebarTabService} */
this.sidebarTabService_ = sidebarTabService;
/** @export {!WidgetFactoryService} */
this.widgetFactorySvc = widgetFactoryService;
/** @private {!DashboardDataService} */
this.dashboardDataService_ = dashboardDataService;
/** @private {!explorer.components.dashboard.DashboardVersionService} */
this.dashboardVersionService_ = dashboardVersionService;
/** @private {!QueryBuilderService} */
this.queryBuilderService_ = queryBuilderService;
/** @private {!angular.$location} */
this.location_ = $location;
/** @private {!ui.router.$state} */
this.$state_ = $state;
/** @private {!ui.router.$stateParams} */
this.$stateParams_ = $stateParams;
/** @export {Array.<!DashboardParam>} */
this.params = [];
/** @export {string} */
this.DEFAULT_TABLE_PARTITION = QueryTablePartitioning.ONETABLE;
/** @export {boolean} */
this.isDashboardLoading = false;
/** @export {Array.<!QueryTablePartitioning>} */
this.TABLE_PARTITIONS = [
{'partition': QueryTablePartitioning.ONETABLE,
'label': 'Single Table',
'tooltip': 'All data is stored in a single table.'},
{'partition': QueryTablePartitioning.PERDAY,
'label': 'Table per Day',
'tooltip': 'Each table represents a day. Ex: results_20141024.'}
];
Object.defineProperty(this, 'current', {
/** @export {function(): explorer.components.dashboard.DashboardInstance} */
get: function() {
return explorerStateService.selectedDashboard;
}
});
Object.defineProperty(this, 'containers', {
/** @export {function(): ?Array.<ContainerWidgetConfig>} */
get: function() {
if (this.current) {
return this.current.model.children;
} else {
return null;
}
}
});
Object.defineProperty(this, 'selectedWidget', {
/** @export {function(): ?WidgetConfig} */
get: function() {
return this.explorerStateService_.widgets.selected;
}
});
Object.defineProperty(this, 'selectedContainer', {
/** @export {function(): ?explorer.components.container.ContainerWidgetModel} */
get: function() {
return this.explorerStateService_.containers.selected;
}
});
/** @export {!Array.<!explorer.components.error.ErrorModel>} */
this.errors = [];
};
const DashboardService = explorer.components.dashboard.DashboardService;
/**
* Empties the list of params.
* @private
*/
DashboardService.prototype.clearParams = function() {
while (this.params.length > 0) {
this.params.pop();
}
};
/**
* Fetches a dashboard and puts it in the scope.
* @param {string} dashboardId
* @export
*/
DashboardService.prototype.fetchDashboard = function(dashboardId) {
var promise = this.dashboardDataService_.fetchDashboard(dashboardId);
this.isDashboardLoading = true;
promise.then(angular.bind(this, function(dashboardConfig) {
this.isDashboardLoading = false;
this.setDashboard(dashboardConfig);
}));
promise.then(null, angular.bind(this, function(error) {
this.isDashboardLoading = false;
this.errorService_.addDanger(error.message || error.data.message);
}));
};
/**
* Saves the current dashboard on the server.
*/
DashboardService.prototype.saveDashboard = function() {
let dashboard = this.current;
let promise = dashboard.model.id ?
this.dashboardDataService_.update(dashboard) :
this.dashboardDataService_.create(dashboard);
promise.then(angular.bind(this, function(dashboardJsonModel) {
// If it was a create, patch the dashboard with the model returned.
if (!dashboard.model.id) {
// TODO: Call fetchDashboard once cleanup and reloading are working
// as expected.
console.log('Dashboard saved with id:', dashboardJsonModel.id);
let uri = new goog.Uri(window.location.href);
uri.setParameterValue('dashboard', dashboardJsonModel.id);
uri.removeParameter('readOnly');
window.location = uri.toString();
}
}));
promise.then(null, angular.bind(this, function(error) {
this.errors.push(error);
console.log('Error while saving the dashboard', error);
}));
};
/**
* Iterates through the dashboard and applies functions to the contents.
* @param {!DashboardInstance} dashboard The dashboard config to iterate.
* @param {?function(ContainerWidgetConfig)} updateContainerFn The function to apply
* to each container.
* @param {?function(WidgetConfig)} updateWidgetFn The function to apply to each
* widget.
*/
DashboardService.prototype.updateDashboard = function(
dashboard, updateContainerFn, updateWidgetFn) {
angular.forEach(dashboard.model.children, function(containerConfig) {
updateContainerFn && updateContainerFn(containerConfig.model.container);
if (updateWidgetFn) {
angular.forEach(
containerConfig.model.container.children, function(widget) {
updateWidgetFn(widget);
});
}
});
};
/**
* Refreshes all widgets in the dashboard and re-applies parameters.
* @export
*/
DashboardService.prototype.refreshDashboard = function() {
this.initializeParams_();
this.timeout_(angular.bind(this, function() {
this.updateDashboard(
this.current, null, angular.bind(this, function(widget) {
this.refreshWidget(widget);
}));
}));
};
/**
* Saves a copy of the current dashboard. If the dashboard has no ID, this
* has the same effect as saveDashboard().
* @export
*/
DashboardService.prototype.saveDashboardCopy = function() {
this.current.model.id = '';
this.saveDashboard();
};
/**
* Set the current dashboard and the set the widgets array to reference the
* dashboard's widgets.
*
* @param {!DashboardInstance} dashboard
* @export
*/
DashboardService.prototype.setDashboard = function(dashboard) {
if (goog.isDefAndNotNull(this.explorerStateService_.selectedDashboard)) {
this.explorerStateService_.widgets.clear();
this.explorerStateService_.containers.clear();
}
this.explorerStateService_.selectedDashboard = dashboard;
if (goog.isDefAndNotNull(dashboard)) {
for (let container of dashboard.model.children) {
this.explorerStateService_.containers.all[container.model.id] = container;
if (container.model.id ===
this.explorerStateService_.containers.selectedId) {
container.state().selected = true;
if (!this.explorerStateService_.widgets.selectedId) {
this.selectWidget(null, container, true);
}
}
for (let widget of container.model.container.children) {
this.explorerStateService_.widgets.all[widget.model.id] = widget;
if (widget.model.id === this.explorerStateService_.widgets.selectedId) {
this.selectWidget(
widget, this.explorerStateService_.containers.selected, true);
}
}
}
this.initializeParams_();
}
};
/**
* Initializes the current dashboard's parameters.
*
* The DashboardModel stores the available params and default values for the
* dashboard, while the DashboardService stores the current effective values
* based on the querystring and default values.
*/
DashboardService.prototype.initializeParams_ = function() {
this.clearParams();
angular.forEach(
this.current.model.params, angular.bind(this, function(param) {
let paramValue = this.location_.search()[param.name] || param.value;
if (paramValue !== '') {
this.params.push(new DashboardParam(param.name, paramValue));
}
}));
};
/**
* Updates the selectedWidget property, the selected state of the widgets and
* select the widget's container.
*
* @param {WidgetConfig} widget
* @param {ContainerWidgetConfig} container
* @param {boolean=} opt_supressStateChange If true, will prevent the ui-router
* state change from taking place. This is used to select the widget at
* initial dashboard load-time.
* @export
*/
DashboardService.prototype.selectWidget = function(
widget, container, opt_supressStateChange) {
let currentContainer = this.explorerStateService_.containers.selected;
let currentWidget = this.explorerStateService_.widgets.selected;
if (currentWidget) {
currentWidget.state().selected = false;
}
if (currentContainer) {
currentContainer.state().selected = false;
}
if (widget) {
widget.state().selected = true;
this.explorerStateService_.widgets.selectedId = widget.model.id;
}
if (container) {
container.state().selected = true;
this.explorerStateService_.containers.selectedId = container.model.id;
}
if (!opt_supressStateChange) {
let params = {widget: null, container: null};
if (widget) { params.widget = widget.model.id; }
if (container) { params.container = container.model.id };
this.$state_.go('explorer-dashboard-edit', params, {location: false});
if (widget) {
this.location_.search('widget', widget.model.id);
} else {
this.location_.search('widget', null);
}
if (container) {
this.location_.search('container', container.model.id);
} else {
this.location_.search('container', null);
}
}
if (goog.isDefAndNotNull(widget)) {
this.sidebarTabService_.resolveSelectedTabForWidget();
this.timeout_(() => {
this.scrollWidgetIntoView(/** @type {!WidgetConfig} */ (widget));
});
} else if (goog.isDefAndNotNull(container)) {
this.sidebarTabService_.resolveSelectedTabForContainer();
this.timeout_(() => {
this.scrollContainerIntoView(/** @type {!ContainerWidgetConfig} */ (container));
});
} else {
this.timeout_(() => {
if (this.sidebarTabService_.selectedTab) {
this.sidebarTabService_.resolveSelectedTabForDashboard();
}
});
}
};
/**
* Scrolls the specified content element (typically a widget or container) into view.
* @param {!angular.JQLite} targetElement The element to scroll into view.
*/
DashboardService.prototype.scrollPageElementIntoView = function(targetElement) {
let contentElement = angular.element(document.getElementsByClassName('pk-page-content'));
if ((targetElement.length === 1) && (contentElement.length === 1)) {
goog.style.scrollIntoContainerView(targetElement[0], contentElement[0]);
}
};
/**
* Scrolls the specified container into view.
* @param {!ContainerWidgetConfig} container
*/
DashboardService.prototype.scrollContainerIntoView = function(container) {
let targetElement = angular.element(
document.getElementsByClassName('pk-container-' + container.model.id));
this.scrollPageElementIntoView(targetElement);
};
/**
* Scrolls the specified widget into view.
* @param {!WidgetConfig} widget
*/
DashboardService.prototype.scrollWidgetIntoView = function(widget) {
let targetElement = angular.element(
document.getElementsByClassName('pk-widget-' + widget.model.id));
this.scrollPageElementIntoView(targetElement);
};
/**
* Selects the specified container, and the first widget.
*
* @param {ContainerWidgetConfig} container
* @param {boolean=} opt_supressStateChange If true, will prevent the ui-router
* state change from taking place. This is used to select the container at
* initial dashboard load-time. Defaults to false.
* @param {boolean=} opt_autoSelectWidget If true, will select the first widget
* in the container. Defaults to true.
* @export
*/
DashboardService.prototype.selectContainer = function(
container, opt_supressStateChange = false, opt_autoSelectWidget = true) {
let widget;
let currentContainer = this.explorerStateService_.containers.selected;
if (currentContainer && currentContainer !== container) {
currentContainer.state().selected = false;
}
let currentWidget = this.explorerStateService_.widgets.selected;
if (currentWidget) {
currentWidget.state().selected = false;
}
if (container) {
container.state().selected = true;
this.explorerStateService_.containers.selectedId = container.model.id;
}
if (opt_autoSelectWidget) {
if (container && container.model.container.children &&
container.model.container.children.length > 0) {
widget = container.model.container.children[0];
}
if (widget) {
widget.state().selected = true;
this.explorerStateService_.widgets.selectedId = widget.model.id;
}
this.timeout_(() => {
this.scrollWidgetIntoView(widget);
});
}
if (!opt_supressStateChange) {
let params = {container: undefined};
if (widget) { params.widget = widget.model.id; }
if (container) { params.container = container.model.id };
this.$state_.go('explorer-dashboard-edit', params);
}
};
/**
* Rewrites the current widget's query based on the config.
* @param {!WidgetConfig} widget The widget to rewrite the query against.
* @param {boolean=} replaceParams If true, parameters (%%NAME%%) will be
* replaced with the current param value (from the dashboard or url).
* Defaults to false.
* @return {string} Rewritten query.
*/
DashboardService.prototype.rewriteQuery = function(widget, replaceParams) {
goog.asserts.assert(widget, 'Bad parameters: widget is missing.');
goog.asserts.assert(this.current, 'Bad state: No dashboard selected.');
let widgetConfig = widget.model.datasource.config;
let project_name = (this.arrayUtilService_.getFirst([
widgetConfig.results.project_id,
this.current.model.project_id,
this.config.default_project], false));
if (goog.isNull(project_name)) {
throw 'Project name not found.';
}
let dataset_name = (this.arrayUtilService_.getFirst([
widgetConfig.results.dataset_name,
this.current.model.dataset_name,
this.config.default_dataset], false));
if (goog.isNull(dataset_name)) {
throw 'Dataset name not found.';
}
let table_name = (this.arrayUtilService_.getFirst([
widgetConfig.results.table_name,
this.current.model.table_name,
this.config.default_table], false));
if (goog.isNull(table_name)) {
throw 'Table name not found.';
}
let table_partition = (this.arrayUtilService_.getFirst([
widgetConfig.results.table_partition,
this.current.model.table_partition,
this.DEFAULT_TABLE_PARTITION], false));
if (goog.isNull(table_partition)) {
throw 'Table partition not found.';
}
this.initializeParams_();
let params = replaceParams ? this.params : null;
return this.queryBuilderService_.getSql(
widget.model.datasource.config,
/** @type {string} */ (project_name),
/** @type {string} */ (dataset_name),
/** @type {string} */ (table_name),
/** @type {!QueryTablePartitioning} */ (table_partition), params);
};
/**
* Rebuilds the current widget's query based on the config.
*
* If the query is a custom query, it will rewrite .query_exec to replace
* parameter tokens with values. If the query is a Query Builder query,
* it will rewrite .query tokens, and .query_exec with values.
*
* @param {!WidgetConfig} widget The widget to rewrite the query against.
*/
DashboardService.prototype.rebuildQuery = function(widget) {
if (widget.model.datasource.custom_query !== true) {
widget.model.datasource.query = (
this.rewriteQuery(widget, false));
widget.model.datasource.query_exec = (
this.rewriteQuery(widget, true));
} else {
widget.model.datasource.query_exec = (
this.queryBuilderService_.replaceTokens(widget.model.datasource.query,
this.params));
}
};
/**
* Updates the widget's query, if applicable, and changes the widget
* datasource status to TOFETCH.
*
* @param {!WidgetConfig} widget
* @export
*/
DashboardService.prototype.refreshWidget = function(widget) {
this.rebuildQuery(widget);
if (widget.model.datasource.query) {
this.timeout_(function() {
widget.state().datasource.status = ResultsDataStatus.TOFETCH;
});
}
};
/**
* Changes the widget datasource to accept a custom SQL statement.
*
* @param {!WidgetConfig} widget
* @param {!boolean} rewrite If true, rewrites the query based on the QueryBuilder
* settings. Otherwise, leaves the query as-is. Defaults to false.
* @export
*/
DashboardService.prototype.customizeSql = function(widget, rewrite) {
if (!widget.model.datasource) {
throw new Error('Selected widget doesn\'t have a datasource property.');
}
widget.state().datasource.status = ResultsDataStatus.NODATA;
if (rewrite === true) {
widget.model.datasource.query = this.rewriteQuery(widget, false);
}
widget.model.datasource.custom_query = true;
};
/**
* Changes the widget datasource to use the Query Builder UI.
*
* @param {!WidgetConfig} widget
* @export
*/
DashboardService.prototype.restoreBuilder = function(widget) {
widget.model.datasource.custom_query = false;
widget.model.datasource.query = this.rewriteQuery(widget, true);
};
/**
* Adds a new widget in the given container and adjust the number of columns
* if needed.
*
* @param {!ContainerWidgetConfig} container
* @return {!WidgetConfig}
* @export
*/
DashboardService.prototype.addWidget = function(
container, opt_autoSelect = true) {
return this.addWidgetAt(container, null, opt_autoSelect);
};
/**
* Adds a new widget in the given container and adjust the number of columns
* if needed.
*
* @param {!ContainerWidgetConfig} container
* @param {!WidgetConfig} widget
* @return {!WidgetConfig}
* @export
*/
DashboardService.prototype.addWidgetAfter = function(
container, widget, opt_autoSelect = true) {
goog.asserts.assert(container, 'Bad parameters: container is missing.');
let index = container.model.container.children.indexOf(widget);
return this.addWidgetAt(container, ++index, opt_autoSelect);
};
/**
* Adds a new widget in the given container and adjust the number of columns
* if needed.
*
* @param {!ContainerWidgetConfig} container
* @param {!WidgetConfig} widget
* @export
*/
DashboardService.prototype.addWidgetBefore = function(
container, widget, opt_autoSelect = true) {
goog.asserts.assert(container, 'Bad parameters: container is missing.');
let index = container.model.container.children.indexOf(widget);
this.addWidgetAt(container, index, opt_autoSelect);
};
/**
* Adds a new widget in the given container and adjust the number of columns
* if needed.
*
* @param {!ContainerWidgetConfig} container
* @param {?number=} opt_index
* @return {!WidgetConfig}
* @export
*/
DashboardService.prototype.addWidgetAt = function(
container, opt_index, opt_autoSelect = true) {
goog.asserts.assert(container, 'Bad parameters: container is missing.');
let children = container.model.container.children;
let columnsTaken = 0;
angular.forEach(children, function(widget) {
columnsTaken += widget.model.layout.columnspan;
});
// If there is exactly enough columns for the current widgets
if (columnsTaken === container.model.container.columns) {
// Add a column for the new widget
container.model.container.columns++;
}
// TODO: Add a simple widget instead of a chart when we have
// other widget types.
let widget = new ChartWidgetConfig(this.widgetFactorySvc);
widget.state().datasource.status = ResultsDataStatus.NODATA;
this.explorerStateService_.widgets.all[widget.model.id] = widget;
if (!goog.isDefAndNotNull(opt_index) || opt_index > children.length - 1) {
children.push(widget);
} else if (opt_index <= 0) {
goog.array.insertAt(children, widget, 0);
} else {
goog.array.insertAt(children, widget, opt_index);
}
widget.state().parent = container;
if (opt_autoSelect) {
this.selectWidget(widget, container);
}
return widget;
};
/**
* Creates a copy of the provided widget, and inserts it directly after the provided one.
* @param {!WidgetConfig} widget
* @param {!ContainerWidgetConfig} container
* @return {!WidgetConfig}
* @export
*/
DashboardService.prototype.cloneWidget = function(widget, container) {
let newModel = angular.copy(widget.model);
let newWidget = this.addWidgetAfter(container, widget);
newModel['id'] = newWidget.model.id;
newWidget.model = newModel;
return newWidget;
};
/**
* Remove a given widget from the given container.
*
* @param {!WidgetConfig} widget
* @param {!ContainerWidgetConfig} container
* @export
*/
DashboardService.prototype.removeWidget = function(widget, container) {
goog.asserts.assert(widget, 'Bad parameters: widget is missing.');
goog.asserts.assert(container, 'Bad parameters: container is missing.');
let index = container.model.container.children.indexOf(widget);
container.model.container.children.splice(index, 1);
delete this.explorerStateService_.widgets.all[widget.model.id];
if (container.model.container.children.length === 0) {
this.removeContainer(container);
} else {
container.model.container.columns -= widget.model.layout.columnspan;
}
this.unselectWidget();
};
/**
* Move a given widget to the specified container.
*
* @param {!WidgetConfig} widget
* @param {!ContainerWidgetConfig} targetContainer
* @export
*/
DashboardService.prototype.moveWidgetToContainer = function(
widget, targetContainer) {
goog.asserts.assert(widget, 'Bad parameters: widget is missing.');
goog.asserts.assert(targetContainer, 'Bad parameters: container is missing.');
let container = /** @type {ContainerWidgetConfig} */ (widget.state().parent);
let index = container.model.container.children.indexOf(widget);
container.model.container.children.splice(index, 1);
if (container.model.container.children.length === 0) {
this.removeContainer(container);
} else {
container.model.container.columns -= widget.model.layout.columnspan;
}
targetContainer.model.container.columns += widget.model.layout.columnspan;
targetContainer.model.container.children.push(widget);
widget.state().parent = targetContainer;
// Move the container selection to the target container. Don't change
// widget selection.
container.state().selected = false;
targetContainer.state().selected = true;
this.explorerStateService_.containers.selectedId = targetContainer.model.id;
if (widget.state().datasource) {
widget.state().datasource.status = ResultsDataStatus.TOFETCH;
}
};
/**
* Creates a new container and returns it.
*
* @param {boolean=} opt_autoCreateWidget If true, creates a widget inside
* the container. Defaults to true.
* @return {!ContainerWidgetConfig}
*/
DashboardService.prototype.newContainer = function(
opt_autoCreateWidget = true) {
let container = new ContainerWidgetConfig(this.widgetFactorySvc);
if (opt_autoCreateWidget) {
this.addWidget(container, false);
}
return container;
};
/**
* Removes a given container.
*
* @param {!ContainerWidgetConfig} container
* @export
*/
DashboardService.prototype.removeContainer = function(container) {
goog.asserts.assert(container, 'Bad parameters: container is missing.');
let index = this.containers.indexOf(container);
this.containers.splice(index, 1);
delete this.explorerStateService_.containers.all[container.model.id];
this.unselectWidget();
};
/**
* If clicking on a background UI element, unselect the current widget
* and container, if any.
*
* @param {Event} event
*/
DashboardService.prototype.onDashboardClick = function(event) {
// Check if this is called from an event handler. In this case, only
// unselect if the clicked element is a background element, and
// ignore if it's propagated from something else such as a widget or
// button. Assumes that all "background" elements are marked
// with the "pk-background" class.
if (event.target.classList.contains('pk-background')) {
this.unselectWidget();
}
};
/**
* Unselect the currently selected widget and container, if any.
*/
DashboardService.prototype.unselectWidget = function() {
this.selectWidget(null, null);
};
/**
* Swaps the widget with the one at the previous position if it exists.
*
* @param {!WidgetConfig} widget
* @export
*/
DashboardService.prototype.moveWidgetToPrevious = function(widget) {
goog.asserts.assert(widget, 'Bad parameters: widget is missing.');
this.arrayUtilService_.movePrevious(
widget.state().parent.model.container.children, widget);
};
/**
* Swaps the widget with the one at the next position if it exists.
*
* @param {!WidgetConfig} widget
* @export
*/
DashboardService.prototype.moveWidgetToNext = function(widget) {
goog.asserts.assert(widget, 'Bad parameters: widget is missing.');
this.arrayUtilService_.moveNext(
widget.state().parent.model.container.children, widget);
};
/**
* Moves the widget to the beginning of the array.
*
* @param {!WidgetConfig} widget
* @export
*/
DashboardService.prototype.moveWidgetToFirst = function(widget) {
goog.asserts.assert(widget, 'Bad parameters: widget is missing.');
this.arrayUtilService_.moveFirst(
widget.state().parent.model.container.children, widget);
};
/**
* Moves the widget to the end of the array.
*
* @param {!WidgetConfig} widget
* @export
*/
DashboardService.prototype.moveWidgetToLast = function(widget) {
goog.asserts.assert(widget, 'Bad parameters: widget is missing.');
this.arrayUtilService_.moveLast(
widget.state().parent.model.container.children, widget);
};
/**
* Move a widget up to the previous container.
*
* If the widget is the only contents of the first container, nothing happens.
* If there are other widgets in the container, a new top-level container will
* be added, and the widget will be it's sole contents.
*
* @param {!WidgetConfig} widget
* @export
*/
DashboardService.prototype.moveWidgetToPreviousContainer = function(widget) {
goog.asserts.assert(widget, 'Bad parameters: widget is missing.');
let container = /** @type {ContainerWidgetConfig} */ (widget.state().parent);
let containerIndex = this.containers.indexOf(container);
let targetContainer = null;
if (containerIndex === 0) {
if (container.model.container.children.length > 1) {
targetContainer = new ContainerWidgetConfig(this.widgetFactorySvc);
targetContainer.model.container.columns = 0;
goog.array.insertAt(this.containers, targetContainer, 0);
this.explorerStateService_.containers.add(targetContainer);
}
} else {
targetContainer = /** @type {ContainerWidgetConfig} */ (
this.containers[containerIndex - 1]);
}
if (targetContainer) {
this.moveWidgetToContainer(widget, targetContainer);
this.selectWidget(widget, targetContainer);
}
};
/**
* Move a widget down to the next container.
*
* If the widget is the only contents of the last container, nothing happens.
* If there are other widgets in the container, a new container will
* be added, and the widget will be it's sole contents.
*
* @param {!WidgetConfig} widget
* @export
*/
DashboardService.prototype.moveWidgetToNextContainer = function(widget) {
goog.asserts.assert(widget, 'Bad parameters: widget is missing.');
let container = /** @type {ContainerWidgetConfig} */ (widget.state().parent);
let containerIndex = this.containers.indexOf(container);
let targetContainer = null;
if (containerIndex === (this.containers.length - 1)) {
if (container.model.container.children.length > 1) {
targetContainer = new ContainerWidgetConfig(this.widgetFactorySvc);
targetContainer.model.container.columns = 0;
this.containers.push(targetContainer);
this.explorerStateService_.containers.add(targetContainer);
}
} else {
targetContainer = /** @type {ContainerWidgetConfig} */ (
this.containers[containerIndex + 1]);
}
if (targetContainer) {
this.moveWidgetToContainer(widget, targetContainer);
this.selectWidget(widget, targetContainer);
}
};
/**
* Triggers the delete confirmation for the currently selected dashboard.
* @export
*/
DashboardService.prototype.deleteDashboard = function() {
return this.dashboardDataService_.delete(this.current.model.id);
};
/**
* Adds an empty entry to the list of authorized writers.
* @export
*/
DashboardService.prototype.addWriter = function() {
this.current.model.writers.push({'email': ''});
};
/**
* Adds an empty entry to the list of dashboard parameters.
* @export
*/
DashboardService.prototype.addParam = function() {
this.current.model.params.push(new DashboardParam('', ''));
};
/**
* Returns a partition object matching the specified name.
* @param {string} partitionName
* @return {Object}
* @export
*/
DashboardService.prototype.getTablePartition = function(partitionName) {
return this.filter_('getByProperty')(
'partition', partitionName, this.TABLE_PARTITIONS);
};
/**
* Returns the title of the provided artifact, with tokens replaced with params.
* Tokens are identified by strings wrapped in the QueryBuilderService
* properties TOKEN_START_SYMBOL and TOKEN_END_SYMBOL.
*
* @param {string} value The string to replace.
* @returns {string} A title with tokens replaced with param values.
* @export
*/
DashboardService.prototype.replaceTokens = function(value) {
if (goog.isDefAndNotNull(this.current)) {
this.initializeParams_();
return this.queryBuilderService_.replaceTokens(value, this.params);
} else {
return '';
}
};
}); // goog.scope
|
client/components/dashboard/dashboard-service.js
|
/**
* @copyright Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @fileoverview dashboardService is an angular service used to maintain the
* data related to the dashboard and to manage the dashboard's widgets.
* @author [email protected] (Joe Allan Muharsky)
*/
goog.provide('p3rf.perfkit.explorer.components.dashboard.DashboardService');
goog.require('p3rf.perfkit.explorer.components.error.ErrorModel');
goog.require('p3rf.perfkit.explorer.components.error.ErrorService');
goog.require('p3rf.perfkit.explorer.components.error.ErrorTypes');
goog.require('p3rf.perfkit.explorer.components.config.ConfigService');
goog.require('p3rf.perfkit.explorer.components.container.ContainerWidgetConfig');
goog.require('p3rf.perfkit.explorer.components.container.ContainerWidgetModel');
goog.require('p3rf.perfkit.explorer.components.dashboard.DashboardInstance');
goog.require('p3rf.perfkit.explorer.components.dashboard.DashboardDataService');
goog.require('p3rf.perfkit.explorer.components.dashboard.DashboardModel');
goog.require('p3rf.perfkit.explorer.components.dashboard.DashboardParam');
goog.require('p3rf.perfkit.explorer.components.dashboard.DashboardVersionService');
goog.require('p3rf.perfkit.explorer.components.explorer.ExplorerStateService');
goog.require('p3rf.perfkit.explorer.components.explorer.sidebar.SidebarTabService');
goog.require('p3rf.perfkit.explorer.components.util.ArrayUtilService');
goog.require('p3rf.perfkit.explorer.components.widget.WidgetFactoryService');
goog.require('p3rf.perfkit.explorer.components.widget.query.builder.QueryBuilderService');
goog.require('p3rf.perfkit.explorer.models.ChartWidgetConfig');
goog.require('p3rf.perfkit.explorer.models.ResultsDataStatus');
goog.require('p3rf.perfkit.explorer.models.WidgetConfig');
goog.require('p3rf.perfkit.explorer.models.WidgetType');
goog.require('p3rf.perfkit.explorer.models.perfkit_simple_builder.QueryTablePartitioning');
goog.require('goog.array');
goog.require('goog.asserts');
goog.scope(function() {
const explorer = p3rf.perfkit.explorer;
const ArrayUtilService = explorer.components.util.ArrayUtilService;
const ChartWidgetConfig = explorer.models.ChartWidgetConfig;
const ConfigService = explorer.components.config.ConfigService;
const ContainerWidgetConfig = explorer.components.container.ContainerWidgetConfig;
const DashboardInstance = explorer.components.dashboard.DashboardInstance;
const DashboardModel = explorer.components.dashboard.DashboardModel;
const DashboardParam = explorer.components.dashboard.DashboardParam;
const DashboardDataService = explorer.components.dashboard.DashboardDataService;
const ExplorerStateService = explorer.components.explorer.ExplorerStateService;
const SidebarTabService = explorer.components.explorer.sidebar.SidebarTabService;
const ErrorService = explorer.components.error.ErrorService;
const ErrorTypes = explorer.components.error.ErrorTypes;
const QueryBuilderService = (
explorer.components.widget.query.builder.QueryBuilderService);
const QueryTablePartitioning = (
explorer.models.perfkit_simple_builder.QueryTablePartitioning);
const ResultsDataStatus = explorer.models.ResultsDataStatus;
const WidgetConfig = explorer.models.WidgetConfig;
const WidgetFactoryService = explorer.components.widget.WidgetFactoryService;
const WidgetType = explorer.models.WidgetType;
/**
* See module docstring for more information about purpose and usage.
*
* @param {!ArrayUtilService} arrayUtilService
* @param {!ErrorService} errorService
* @param {!WidgetFactoryService} widgetFactoryService
* @param {!DashboardDataService} dashboardDataService
* @param {!QueryBuilderService} queryBuilderService
* @param {!ConfigService} configService
* @param {!ExplorerStateService} explorerStateService
* @param {!SidebarTabService} sidebarTabService
* @param {!angular.$filter} $filter
* @param {!angular.$location} $location
* @param {!angular.Scope} $rootScope
* @param {!angular.$timeout} $timeout
* @param {!angular.$window} $window
* @constructor
* @ngInject
*/
explorer.components.dashboard.DashboardService = function(arrayUtilService,
errorService, widgetFactoryService, dashboardDataService,
queryBuilderService, dashboardVersionService, configService,
explorerStateService, sidebarTabService, $filter, $location, $rootScope,
$timeout, $window, $state, $stateParams) {
/** @private {!angular.$filter} */
this.filter_ = $filter;
/** @private {!angular.Scope} */
this.rootScope_ = $rootScope;
/** @private {!angular.$timeout} */
this.timeout_ = $timeout;
/** @export {!ConfigService} */
this.config = configService;
/** @private {!ArrayUtilService} */
this.arrayUtilService_ = arrayUtilService;
/** @private {!ErrorService} */
this.errorService_ = errorService;
/** @private {!ExplorerStateService} */
this.explorerStateService_ = explorerStateService;
/** @private {!SidebarTabService} */
this.sidebarTabService_ = sidebarTabService;
/** @export {!WidgetFactoryService} */
this.widgetFactorySvc = widgetFactoryService;
/** @private {!DashboardDataService} */
this.dashboardDataService_ = dashboardDataService;
/** @private {!explorer.components.dashboard.DashboardVersionService} */
this.dashboardVersionService_ = dashboardVersionService;
/** @private {!QueryBuilderService} */
this.queryBuilderService_ = queryBuilderService;
/** @private {!angular.$location} */
this.location_ = $location;
/** @private {!ui.router.$state} */
this.$state_ = $state;
/** @private {!ui.router.$stateParams} */
this.$stateParams_ = $stateParams;
/** @export {Array.<!DashboardParam>} */
this.params = [];
/** @export {string} */
this.DEFAULT_TABLE_PARTITION = QueryTablePartitioning.ONETABLE;
/** @export {boolean} */
this.isDashboardLoading = false;
/** @export {Array.<!QueryTablePartitioning>} */
this.TABLE_PARTITIONS = [
{'partition': QueryTablePartitioning.ONETABLE,
'label': 'Single Table',
'tooltip': 'All data is stored in a single table.'},
{'partition': QueryTablePartitioning.PERDAY,
'label': 'Table per Day',
'tooltip': 'Each table represents a day. Ex: results_20141024.'}
];
Object.defineProperty(this, 'current', {
/** @export {function(): explorer.components.dashboard.DashboardInstance} */
get: function() {
return explorerStateService.selectedDashboard;
}
});
Object.defineProperty(this, 'containers', {
/** @export {function(): ?Array.<ContainerWidgetConfig>} */
get: function() {
if (this.current) {
return this.current.model.children;
} else {
return null;
}
}
});
Object.defineProperty(this, 'selectedWidget', {
/** @export {function(): ?WidgetConfig} */
get: function() {
return this.explorerStateService_.widgets.selected;
}
});
Object.defineProperty(this, 'selectedContainer', {
/** @export {function(): ?explorer.components.container.ContainerWidgetModel} */
get: function() {
return this.explorerStateService_.containers.selected;
}
});
/** @export {!Array.<!explorer.components.error.ErrorModel>} */
this.errors = [];
};
const DashboardService = explorer.components.dashboard.DashboardService;
/**
* Empties the list of params.
* @private
*/
DashboardService.prototype.clearParams = function() {
while (this.params.length > 0) {
this.params.pop();
}
};
/**
* Fetches a dashboard and puts it in the scope.
* @param {string} dashboardId
* @export
*/
DashboardService.prototype.fetchDashboard = function(dashboardId) {
var promise = this.dashboardDataService_.fetchDashboard(dashboardId);
this.isDashboardLoading = true;
promise.then(angular.bind(this, function(dashboardConfig) {
this.isDashboardLoading = false;
this.setDashboard(dashboardConfig);
}));
promise.then(null, angular.bind(this, function(error) {
this.isDashboardLoading = false;
this.errorService_.addDanger(error.message || error.data.message);
}));
};
/**
* Saves the current dashboard on the server.
*/
DashboardService.prototype.saveDashboard = function() {
let dashboard = this.current;
let promise = dashboard.model.id ?
this.dashboardDataService_.update(dashboard) :
this.dashboardDataService_.create(dashboard);
promise.then(angular.bind(this, function(dashboardJsonModel) {
// If it was a create, patch the dashboard with the model returned.
if (!dashboard.model.id) {
// TODO: Call fetchDashboard once cleanup and reloading are working
// as expected.
console.log('Dashboard saved with id:', dashboardJsonModel.id);
let uri = new goog.Uri(window.location.href);
uri.setParameterValue('dashboard', dashboardJsonModel.id);
uri.removeParameter('readOnly');
window.location = uri.toString();
}
}));
promise.then(null, angular.bind(this, function(error) {
this.errors.push(error);
console.log('Error while saving the dashboard', error);
}));
};
/**
* Iterates through the dashboard and applies functions to the contents.
* @param {!DashboardInstance} dashboard The dashboard config to iterate.
* @param {?function(ContainerWidgetConfig)} updateContainerFn The function to apply
* to each container.
* @param {?function(WidgetConfig)} updateWidgetFn The function to apply to each
* widget.
*/
DashboardService.prototype.updateDashboard = function(
dashboard, updateContainerFn, updateWidgetFn) {
angular.forEach(dashboard.model.children, function(containerConfig) {
updateContainerFn && updateContainerFn(containerConfig.model.container);
if (updateWidgetFn) {
angular.forEach(
containerConfig.model.container.children, function(widget) {
updateWidgetFn(widget);
});
}
});
};
/**
* Refreshes all widgets in the dashboard and re-applies parameters.
* @export
*/
DashboardService.prototype.refreshDashboard = function() {
this.initializeParams_();
this.timeout_(angular.bind(this, function() {
this.updateDashboard(
this.current, null, angular.bind(this, function(widget) {
this.refreshWidget(widget);
}));
}));
};
/**
* Saves a copy of the current dashboard. If the dashboard has no ID, this
* has the same effect as saveDashboard().
* @export
*/
DashboardService.prototype.saveDashboardCopy = function() {
this.current.model.id = '';
this.saveDashboard();
};
/**
* Set the current dashboard and the set the widgets array to reference the
* dashboard's widgets.
*
* @param {!DashboardInstance} dashboard
* @export
*/
DashboardService.prototype.setDashboard = function(dashboard) {
this.explorerStateService_.selectedDashboard = dashboard;
if (dashboard) {
this.explorerStateService_.widgets.clear();
this.explorerStateService_.containers.clear();
for (let container of dashboard.model.children) {
this.explorerStateService_.containers.all[container.model.id] = container;
if (container.model.id ===
this.explorerStateService_.containers.selectedId) {
container.state().selected = true;
if (!this.explorerStateService_.widgets.selectedId) {
this.selectWidget(null, container, true);
}
}
for (let widget of container.model.container.children) {
this.explorerStateService_.widgets.all[widget.model.id] = widget;
if (widget.model.id === this.explorerStateService_.widgets.selectedId) {
this.selectWidget(
widget, this.explorerStateService_.containers.selected, true);
}
}
}
this.initializeParams_();
}
};
/**
* Initializes the current dashboard's parameters.
*
* The DashboardModel stores the available params and default values for the
* dashboard, while the DashboardService stores the current effective values
* based on the querystring and default values.
*/
DashboardService.prototype.initializeParams_ = function() {
this.clearParams();
angular.forEach(
this.current.model.params, angular.bind(this, function(param) {
let paramValue = this.location_.search()[param.name] || param.value;
if (paramValue !== '') {
this.params.push(new DashboardParam(param.name, paramValue));
}
}));
};
/**
* Updates the selectedWidget property, the selected state of the widgets and
* select the widget's container.
*
* @param {WidgetConfig} widget
* @param {ContainerWidgetConfig} container
* @param {boolean=} opt_supressStateChange If true, will prevent the ui-router
* state change from taking place. This is used to select the widget at
* initial dashboard load-time.
* @export
*/
DashboardService.prototype.selectWidget = function(
widget, container, opt_supressStateChange) {
let currentContainer = this.explorerStateService_.containers.selected;
let currentWidget = this.explorerStateService_.widgets.selected;
if (currentWidget) {
currentWidget.state().selected = false;
}
if (currentContainer) {
currentContainer.state().selected = false;
}
if (widget) {
widget.state().selected = true;
this.explorerStateService_.widgets.selectedId = widget.model.id;
}
if (container) {
container.state().selected = true;
this.explorerStateService_.containers.selectedId = container.model.id;
}
if (!opt_supressStateChange) {
let params = {widget: null, container: null};
if (widget) { params.widget = widget.model.id; }
if (container) { params.container = container.model.id };
this.$state_.go('explorer-dashboard-edit', params, {location: false});
if (widget) {
this.location_.search('widget', widget.model.id);
} else {
this.location_.search('widget', null);
}
if (container) {
this.location_.search('container', container.model.id);
} else {
this.location_.search('container', null);
}
}
if (goog.isDefAndNotNull(widget)) {
this.sidebarTabService_.resolveSelectedTabForWidget();
this.timeout_(() => {
this.scrollWidgetIntoView(/** @type {!WidgetConfig} */ (widget));
});
} else if (goog.isDefAndNotNull(container)) {
this.sidebarTabService_.resolveSelectedTabForContainer();
this.timeout_(() => {
this.scrollContainerIntoView(/** @type {!ContainerWidgetConfig} */ (container));
});
} else {
this.timeout_(() => {
if (this.sidebarTabService_.selectedTab) {
this.sidebarTabService_.resolveSelectedTabForDashboard();
}
});
}
};
/**
* Scrolls the specified content element (typically a widget or container) into view.
* @param {!angular.JQLite} targetElement The element to scroll into view.
*/
DashboardService.prototype.scrollPageElementIntoView = function(targetElement) {
let contentElement = angular.element(document.getElementsByClassName('pk-page-content'));
if ((targetElement.length === 1) && (contentElement.length === 1)) {
goog.style.scrollIntoContainerView(targetElement[0], contentElement[0]);
}
};
/**
* Scrolls the specified container into view.
* @param {!ContainerWidgetConfig} container
*/
DashboardService.prototype.scrollContainerIntoView = function(container) {
let targetElement = angular.element(
document.getElementsByClassName('pk-container-' + container.model.id));
this.scrollPageElementIntoView(targetElement);
};
/**
* Scrolls the specified widget into view.
* @param {!WidgetConfig} widget
*/
DashboardService.prototype.scrollWidgetIntoView = function(widget) {
let targetElement = angular.element(
document.getElementsByClassName('pk-widget-' + widget.model.id));
this.scrollPageElementIntoView(targetElement);
};
/**
* Selects the specified container, and the first widget.
*
* @param {ContainerWidgetConfig} container
* @param {boolean=} opt_supressStateChange If true, will prevent the ui-router
* state change from taking place. This is used to select the container at
* initial dashboard load-time. Defaults to false.
* @param {boolean=} opt_autoSelectWidget If true, will select the first widget
* in the container. Defaults to true.
* @export
*/
DashboardService.prototype.selectContainer = function(
container, opt_supressStateChange = false, opt_autoSelectWidget = true) {
let widget;
let currentContainer = this.explorerStateService_.containers.selected;
if (currentContainer && currentContainer !== container) {
currentContainer.state().selected = false;
}
let currentWidget = this.explorerStateService_.widgets.selected;
if (currentWidget) {
currentWidget.state().selected = false;
}
if (container) {
container.state().selected = true;
this.explorerStateService_.containers.selectedId = container.model.id;
}
if (opt_autoSelectWidget) {
if (container && container.model.container.children &&
container.model.container.children.length > 0) {
widget = container.model.container.children[0];
}
if (widget) {
widget.state().selected = true;
this.explorerStateService_.widgets.selectedId = widget.model.id;
}
this.timeout_(() => {
this.scrollWidgetIntoView(widget);
});
}
if (!opt_supressStateChange) {
let params = {container: undefined};
if (widget) { params.widget = widget.model.id; }
if (container) { params.container = container.model.id };
this.$state_.go('explorer-dashboard-edit', params);
}
};
/**
* Rewrites the current widget's query based on the config.
* @param {!WidgetConfig} widget The widget to rewrite the query against.
* @param {boolean=} replaceParams If true, parameters (%%NAME%%) will be
* replaced with the current param value (from the dashboard or url).
* Defaults to false.
* @return {string} Rewritten query.
*/
DashboardService.prototype.rewriteQuery = function(widget, replaceParams) {
goog.asserts.assert(widget, 'Bad parameters: widget is missing.');
goog.asserts.assert(this.current, 'Bad state: No dashboard selected.');
let widgetConfig = widget.model.datasource.config;
let project_name = (this.arrayUtilService_.getFirst([
widgetConfig.results.project_id,
this.current.model.project_id,
this.config.default_project], false));
if (goog.isNull(project_name)) {
throw 'Project name not found.';
}
let dataset_name = (this.arrayUtilService_.getFirst([
widgetConfig.results.dataset_name,
this.current.model.dataset_name,
this.config.default_dataset], false));
if (goog.isNull(dataset_name)) {
throw 'Dataset name not found.';
}
let table_name = (this.arrayUtilService_.getFirst([
widgetConfig.results.table_name,
this.current.model.table_name,
this.config.default_table], false));
if (goog.isNull(table_name)) {
throw 'Table name not found.';
}
let table_partition = (this.arrayUtilService_.getFirst([
widgetConfig.results.table_partition,
this.current.model.table_partition,
this.DEFAULT_TABLE_PARTITION], false));
if (goog.isNull(table_partition)) {
throw 'Table partition not found.';
}
this.initializeParams_();
let params = replaceParams ? this.params : null;
return this.queryBuilderService_.getSql(
widget.model.datasource.config,
/** @type {string} */ (project_name),
/** @type {string} */ (dataset_name),
/** @type {string} */ (table_name),
/** @type {!QueryTablePartitioning} */ (table_partition), params);
};
/**
* Rebuilds the current widget's query based on the config.
*
* If the query is a custom query, it will rewrite .query_exec to replace
* parameter tokens with values. If the query is a Query Builder query,
* it will rewrite .query tokens, and .query_exec with values.
*
* @param {!WidgetConfig} widget The widget to rewrite the query against.
*/
DashboardService.prototype.rebuildQuery = function(widget) {
if (widget.model.datasource.custom_query !== true) {
widget.model.datasource.query = (
this.rewriteQuery(widget, false));
widget.model.datasource.query_exec = (
this.rewriteQuery(widget, true));
} else {
widget.model.datasource.query_exec = (
this.queryBuilderService_.replaceTokens(widget.model.datasource.query,
this.params));
}
};
/**
* Updates the widget's query, if applicable, and changes the widget
* datasource status to TOFETCH.
*
* @param {!WidgetConfig} widget
* @export
*/
DashboardService.prototype.refreshWidget = function(widget) {
this.rebuildQuery(widget);
if (widget.model.datasource.query) {
this.timeout_(function() {
widget.state().datasource.status = ResultsDataStatus.TOFETCH;
});
}
};
/**
* Changes the widget datasource to accept a custom SQL statement.
*
* @param {!WidgetConfig} widget
* @param {!boolean} rewrite If true, rewrites the query based on the QueryBuilder
* settings. Otherwise, leaves the query as-is. Defaults to false.
* @export
*/
DashboardService.prototype.customizeSql = function(widget, rewrite) {
if (!widget.model.datasource) {
throw new Error('Selected widget doesn\'t have a datasource property.');
}
widget.state().datasource.status = ResultsDataStatus.NODATA;
if (rewrite === true) {
widget.model.datasource.query = this.rewriteQuery(widget, false);
}
widget.model.datasource.custom_query = true;
};
/**
* Changes the widget datasource to use the Query Builder UI.
*
* @param {!WidgetConfig} widget
* @export
*/
DashboardService.prototype.restoreBuilder = function(widget) {
widget.model.datasource.custom_query = false;
widget.model.datasource.query = this.rewriteQuery(widget, true);
};
/**
* Adds a new widget in the given container and adjust the number of columns
* if needed.
*
* @param {!ContainerWidgetConfig} container
* @return {!WidgetConfig}
* @export
*/
DashboardService.prototype.addWidget = function(
container, opt_autoSelect = true) {
return this.addWidgetAt(container, null, opt_autoSelect);
};
/**
* Adds a new widget in the given container and adjust the number of columns
* if needed.
*
* @param {!ContainerWidgetConfig} container
* @param {!WidgetConfig} widget
* @return {!WidgetConfig}
* @export
*/
DashboardService.prototype.addWidgetAfter = function(
container, widget, opt_autoSelect = true) {
goog.asserts.assert(container, 'Bad parameters: container is missing.');
let index = container.model.container.children.indexOf(widget);
return this.addWidgetAt(container, ++index, opt_autoSelect);
};
/**
* Adds a new widget in the given container and adjust the number of columns
* if needed.
*
* @param {!ContainerWidgetConfig} container
* @param {!WidgetConfig} widget
* @export
*/
DashboardService.prototype.addWidgetBefore = function(
container, widget, opt_autoSelect = true) {
goog.asserts.assert(container, 'Bad parameters: container is missing.');
let index = container.model.container.children.indexOf(widget);
this.addWidgetAt(container, index, opt_autoSelect);
};
/**
* Adds a new widget in the given container and adjust the number of columns
* if needed.
*
* @param {!ContainerWidgetConfig} container
* @param {?number=} opt_index
* @return {!WidgetConfig}
* @export
*/
DashboardService.prototype.addWidgetAt = function(
container, opt_index, opt_autoSelect = true) {
goog.asserts.assert(container, 'Bad parameters: container is missing.');
let children = container.model.container.children;
let columnsTaken = 0;
angular.forEach(children, function(widget) {
columnsTaken += widget.model.layout.columnspan;
});
// If there is exactly enough columns for the current widgets
if (columnsTaken === container.model.container.columns) {
// Add a column for the new widget
container.model.container.columns++;
}
// TODO: Add a simple widget instead of a chart when we have
// other widget types.
let widget = new ChartWidgetConfig(this.widgetFactorySvc);
widget.state().datasource.status = ResultsDataStatus.NODATA;
this.explorerStateService_.widgets.all[widget.model.id] = widget;
if (!goog.isDefAndNotNull(opt_index) || opt_index > children.length - 1) {
children.push(widget);
} else if (opt_index <= 0) {
goog.array.insertAt(children, widget, 0);
} else {
goog.array.insertAt(children, widget, opt_index);
}
widget.state().parent = container;
if (opt_autoSelect) {
this.selectWidget(widget, container);
}
return widget;
};
/**
* Creates a copy of the provided widget, and inserts it directly after the provided one.
* @param {!WidgetConfig} widget
* @param {!ContainerWidgetConfig} container
* @return {!WidgetConfig}
* @export
*/
DashboardService.prototype.cloneWidget = function(widget, container) {
let newModel = angular.copy(widget.model);
let newWidget = this.addWidgetAfter(container, widget);
newModel['id'] = newWidget.model.id;
newWidget.model = newModel;
return newWidget;
};
/**
* Remove a given widget from the given container.
*
* @param {!WidgetConfig} widget
* @param {!ContainerWidgetConfig} container
* @export
*/
DashboardService.prototype.removeWidget = function(widget, container) {
goog.asserts.assert(widget, 'Bad parameters: widget is missing.');
goog.asserts.assert(container, 'Bad parameters: container is missing.');
let index = container.model.container.children.indexOf(widget);
container.model.container.children.splice(index, 1);
delete this.explorerStateService_.widgets.all[widget.model.id];
if (container.model.container.children.length === 0) {
this.removeContainer(container);
} else {
container.model.container.columns -= widget.model.layout.columnspan;
}
this.unselectWidget();
};
/**
* Move a given widget to the specified container.
*
* @param {!WidgetConfig} widget
* @param {!ContainerWidgetConfig} targetContainer
* @export
*/
DashboardService.prototype.moveWidgetToContainer = function(
widget, targetContainer) {
goog.asserts.assert(widget, 'Bad parameters: widget is missing.');
goog.asserts.assert(targetContainer, 'Bad parameters: container is missing.');
let container = /** @type {ContainerWidgetConfig} */ (widget.state().parent);
let index = container.model.container.children.indexOf(widget);
container.model.container.children.splice(index, 1);
if (container.model.container.children.length === 0) {
this.removeContainer(container);
} else {
container.model.container.columns -= widget.model.layout.columnspan;
}
targetContainer.model.container.columns += widget.model.layout.columnspan;
targetContainer.model.container.children.push(widget);
widget.state().parent = targetContainer;
// Move the container selection to the target container. Don't change
// widget selection.
container.state().selected = false;
targetContainer.state().selected = true;
this.explorerStateService_.containers.selectedId = targetContainer.model.id;
if (widget.state().datasource) {
widget.state().datasource.status = ResultsDataStatus.TOFETCH;
}
};
/**
* Creates a new container and returns it.
*
* @param {boolean=} opt_autoCreateWidget If true, creates a widget inside
* the container. Defaults to true.
* @return {!ContainerWidgetConfig}
*/
DashboardService.prototype.newContainer = function(
opt_autoCreateWidget = true) {
let container = new ContainerWidgetConfig(this.widgetFactorySvc);
if (opt_autoCreateWidget) {
this.addWidget(container, false);
}
return container;
};
/**
* Removes a given container.
*
* @param {!ContainerWidgetConfig} container
* @export
*/
DashboardService.prototype.removeContainer = function(container) {
goog.asserts.assert(container, 'Bad parameters: container is missing.');
let index = this.containers.indexOf(container);
this.containers.splice(index, 1);
delete this.explorerStateService_.containers.all[container.model.id];
this.unselectWidget();
};
/**
* If clicking on a background UI element, unselect the current widget
* and container, if any.
*
* @param {Event} event
*/
DashboardService.prototype.onDashboardClick = function(event) {
// Check if this is called from an event handler. In this case, only
// unselect if the clicked element is a background element, and
// ignore if it's propagated from something else such as a widget or
// button. Assumes that all "background" elements are marked
// with the "pk-background" class.
if (event.target.classList.contains('pk-background')) {
this.unselectWidget();
}
};
/**
* Unselect the currently selected widget and container, if any.
*/
DashboardService.prototype.unselectWidget = function() {
this.selectWidget(null, null);
};
/**
* Swaps the widget with the one at the previous position if it exists.
*
* @param {!WidgetConfig} widget
* @export
*/
DashboardService.prototype.moveWidgetToPrevious = function(widget) {
goog.asserts.assert(widget, 'Bad parameters: widget is missing.');
this.arrayUtilService_.movePrevious(
widget.state().parent.model.container.children, widget);
};
/**
* Swaps the widget with the one at the next position if it exists.
*
* @param {!WidgetConfig} widget
* @export
*/
DashboardService.prototype.moveWidgetToNext = function(widget) {
goog.asserts.assert(widget, 'Bad parameters: widget is missing.');
this.arrayUtilService_.moveNext(
widget.state().parent.model.container.children, widget);
};
/**
* Moves the widget to the beginning of the array.
*
* @param {!WidgetConfig} widget
* @export
*/
DashboardService.prototype.moveWidgetToFirst = function(widget) {
goog.asserts.assert(widget, 'Bad parameters: widget is missing.');
this.arrayUtilService_.moveFirst(
widget.state().parent.model.container.children, widget);
};
/**
* Moves the widget to the end of the array.
*
* @param {!WidgetConfig} widget
* @export
*/
DashboardService.prototype.moveWidgetToLast = function(widget) {
goog.asserts.assert(widget, 'Bad parameters: widget is missing.');
this.arrayUtilService_.moveLast(
widget.state().parent.model.container.children, widget);
};
/**
* Move a widget up to the previous container.
*
* If the widget is the only contents of the first container, nothing happens.
* If there are other widgets in the container, a new top-level container will
* be added, and the widget will be it's sole contents.
*
* @param {!WidgetConfig} widget
* @export
*/
DashboardService.prototype.moveWidgetToPreviousContainer = function(widget) {
goog.asserts.assert(widget, 'Bad parameters: widget is missing.');
let container = /** @type {ContainerWidgetConfig} */ (widget.state().parent);
let containerIndex = this.containers.indexOf(container);
let targetContainer = null;
if (containerIndex === 0) {
if (container.model.container.children.length > 1) {
targetContainer = new ContainerWidgetConfig(this.widgetFactorySvc);
targetContainer.model.container.columns = 0;
goog.array.insertAt(this.containers, targetContainer, 0);
this.explorerStateService_.containers.add(targetContainer);
}
} else {
targetContainer = /** @type {ContainerWidgetConfig} */ (
this.containers[containerIndex - 1]);
}
if (targetContainer) {
this.moveWidgetToContainer(widget, targetContainer);
this.selectWidget(widget, targetContainer);
}
};
/**
* Move a widget down to the next container.
*
* If the widget is the only contents of the last container, nothing happens.
* If there are other widgets in the container, a new container will
* be added, and the widget will be it's sole contents.
*
* @param {!WidgetConfig} widget
* @export
*/
DashboardService.prototype.moveWidgetToNextContainer = function(widget) {
goog.asserts.assert(widget, 'Bad parameters: widget is missing.');
let container = /** @type {ContainerWidgetConfig} */ (widget.state().parent);
let containerIndex = this.containers.indexOf(container);
let targetContainer = null;
if (containerIndex === (this.containers.length - 1)) {
if (container.model.container.children.length > 1) {
targetContainer = new ContainerWidgetConfig(this.widgetFactorySvc);
targetContainer.model.container.columns = 0;
this.containers.push(targetContainer);
this.explorerStateService_.containers.add(targetContainer);
}
} else {
targetContainer = /** @type {ContainerWidgetConfig} */ (
this.containers[containerIndex + 1]);
}
if (targetContainer) {
this.moveWidgetToContainer(widget, targetContainer);
this.selectWidget(widget, targetContainer);
}
};
/**
* Triggers the delete confirmation for the currently selected dashboard.
* @export
*/
DashboardService.prototype.deleteDashboard = function() {
return this.dashboardDataService_.delete(this.current.model.id);
};
/**
* Adds an empty entry to the list of authorized writers.
* @export
*/
DashboardService.prototype.addWriter = function() {
this.current.model.writers.push({'email': ''});
};
/**
* Adds an empty entry to the list of dashboard parameters.
* @export
*/
DashboardService.prototype.addParam = function() {
this.current.model.params.push(new DashboardParam('', ''));
};
/**
* Returns a partition object matching the specified name.
* @param {string} partitionName
* @return {Object}
* @export
*/
DashboardService.prototype.getTablePartition = function(partitionName) {
return this.filter_('getByProperty')(
'partition', partitionName, this.TABLE_PARTITIONS);
};
/**
* Returns the title of the provided artifact, with tokens replaced with params.
* Tokens are identified by strings wrapped in the QueryBuilderService
* properties TOKEN_START_SYMBOL and TOKEN_END_SYMBOL.
*
* @param {string} value The string to replace.
* @returns {string} A title with tokens replaced with param values.
* @export
*/
DashboardService.prototype.replaceTokens = function(value) {
if (goog.isDefAndNotNull(this.current)) {
this.initializeParams_();
return this.queryBuilderService_.replaceTokens(value, this.params);
} else {
return '';
}
};
}); // goog.scope
|
Fix issue where URL widget selection wasn't working.
|
client/components/dashboard/dashboard-service.js
|
Fix issue where URL widget selection wasn't working.
|
<ide><path>lient/components/dashboard/dashboard-service.js
<ide> * @export
<ide> */
<ide> DashboardService.prototype.setDashboard = function(dashboard) {
<del> this.explorerStateService_.selectedDashboard = dashboard;
<del> if (dashboard) {
<add> if (goog.isDefAndNotNull(this.explorerStateService_.selectedDashboard)) {
<ide> this.explorerStateService_.widgets.clear();
<ide> this.explorerStateService_.containers.clear();
<del>
<add> }
<add> this.explorerStateService_.selectedDashboard = dashboard;
<add>
<add> if (goog.isDefAndNotNull(dashboard)) {
<ide> for (let container of dashboard.model.children) {
<ide> this.explorerStateService_.containers.all[container.model.id] = container;
<ide> if (container.model.id ===
|
|
Java
|
apache-2.0
|
93c23047593c2b388b3689cc85e4d0ca9a71af29
| 0 |
del-sol/libgdx,xpenatan/libgdx-LWJGL3,mumer92/libgdx,collinsmith/libgdx,petugez/libgdx,xoppa/libgdx,ryoenji/libgdx,realitix/libgdx,andyvand/libgdx,josephknight/libgdx,collinsmith/libgdx,Zonglin-Li6565/libgdx,bsmr-java/libgdx,js78/libgdx,UnluckyNinja/libgdx,zhimaijoy/libgdx,saltares/libgdx,ya7lelkom/libgdx,lordjone/libgdx,tell10glu/libgdx,bsmr-java/libgdx,bgroenks96/libgdx,hyvas/libgdx,srwonka/libGdx,MikkelTAndersen/libgdx,xranby/libgdx,SidneyXu/libgdx,djom20/libgdx,UnluckyNinja/libgdx,luischavez/libgdx,curtiszimmerman/libgdx,Dzamir/libgdx,snovak/libgdx,Senth/libgdx,Thotep/libgdx,Heart2009/libgdx,designcrumble/libgdx,ryoenji/libgdx,alireza-hosseini/libgdx,stickyd/libgdx,xranby/libgdx,collinsmith/libgdx,realitix/libgdx,Deftwun/libgdx,stinsonga/libgdx,azakhary/libgdx,Badazdz/libgdx,ztv/libgdx,antag99/libgdx,Thotep/libgdx,petugez/libgdx,Gliby/libgdx,lordjone/libgdx,bsmr-java/libgdx,ztv/libgdx,FyiurAmron/libgdx,MetSystem/libgdx,del-sol/libgdx,Dzamir/libgdx,gf11speed/libgdx,Senth/libgdx,Dzamir/libgdx,MovingBlocks/libgdx,TheAks999/libgdx,revo09/libgdx,junkdog/libgdx,lordjone/libgdx,youprofit/libgdx,yangweigbh/libgdx,haedri/libgdx-1,ThiagoGarciaAlves/libgdx,KrisLee/libgdx,gouessej/libgdx,bladecoder/libgdx,Zomby2D/libgdx,xranby/libgdx,del-sol/libgdx,firefly2442/libgdx,toloudis/libgdx,Deftwun/libgdx,nrallakis/libgdx,srwonka/libGdx,jberberick/libgdx,saltares/libgdx,fwolff/libgdx,SidneyXu/libgdx,gouessej/libgdx,toa5/libgdx,bladecoder/libgdx,Dzamir/libgdx,nave966/libgdx,srwonka/libGdx,srwonka/libGdx,Badazdz/libgdx,KrisLee/libgdx,haedri/libgdx-1,djom20/libgdx,Gliby/libgdx,youprofit/libgdx,ninoalma/libgdx,fwolff/libgdx,Wisienkas/libgdx,Heart2009/libgdx,TheAks999/libgdx,FyiurAmron/libgdx,jberberick/libgdx,shiweihappy/libgdx,kotcrab/libgdx,tommycli/libgdx,Arcnor/libgdx,tell10glu/libgdx,yangweigbh/libgdx,xpenatan/libgdx-LWJGL3,davebaol/libgdx,haedri/libgdx-1,samskivert/libgdx,309746069/libgdx,stickyd/libgdx,ttencate/libgdx,toloudis/libgdx,UnluckyNinja/libgdx,basherone/libgdxcn,GreenLightning/libgdx,Zonglin-Li6565/libgdx,srwonka/libGdx,gouessej/libgdx,gf11speed/libgdx,Xhanim/libgdx,fwolff/libgdx,flaiker/libgdx,alex-dorokhov/libgdx,alireza-hosseini/libgdx,nooone/libgdx,Deftwun/libgdx,MetSystem/libgdx,thepullman/libgdx,ThiagoGarciaAlves/libgdx,Arcnor/libgdx,nave966/libgdx,MovingBlocks/libgdx,titovmaxim/libgdx,nooone/libgdx,junkdog/libgdx,hyvas/libgdx,codepoke/libgdx,sarkanyi/libgdx,ricardorigodon/libgdx,codepoke/libgdx,jsjolund/libgdx,Thotep/libgdx,petugez/libgdx,petugez/libgdx,ninoalma/libgdx,kzganesan/libgdx,ninoalma/libgdx,hyvas/libgdx,copystudy/libgdx,tommycli/libgdx,Zonglin-Li6565/libgdx,luischavez/libgdx,sjosegarcia/libgdx,fiesensee/libgdx,kotcrab/libgdx,tommycli/libgdx,katiepino/libgdx,sarkanyi/libgdx,josephknight/libgdx,ztv/libgdx,noelsison2/libgdx,ThiagoGarciaAlves/libgdx,jsjolund/libgdx,309746069/libgdx,stickyd/libgdx,bgroenks96/libgdx,titovmaxim/libgdx,FyiurAmron/libgdx,toa5/libgdx,designcrumble/libgdx,sjosegarcia/libgdx,jasonwee/libgdx,copystudy/libgdx,collinsmith/libgdx,Arcnor/libgdx,kagehak/libgdx,EsikAntony/libgdx,ninoalma/libgdx,lordjone/libgdx,Xhanim/libgdx,JDReutt/libgdx,shiweihappy/libgdx,realitix/libgdx,BlueRiverInteractive/libgdx,Deftwun/libgdx,yangweigbh/libgdx,alex-dorokhov/libgdx,zommuter/libgdx,samskivert/libgdx,gdos/libgdx,309746069/libgdx,JFixby/libgdx,nrallakis/libgdx,gdos/libgdx,ya7lelkom/libgdx,ricardorigodon/libgdx,cypherdare/libgdx,davebaol/libgdx,mumer92/libgdx,PedroRomanoBarbosa/libgdx,xoppa/libgdx,Badazdz/libgdx,hyvas/libgdx,andyvand/libgdx,libgdx/libgdx,junkdog/libgdx,flaiker/libgdx,js78/libgdx,del-sol/libgdx,MetSystem/libgdx,FredGithub/libgdx,saqsun/libgdx,Thotep/libgdx,309746069/libgdx,sinistersnare/libgdx,fiesensee/libgdx,BlueRiverInteractive/libgdx,MadcowD/libgdx,lordjone/libgdx,Wisienkas/libgdx,flaiker/libgdx,Thotep/libgdx,billgame/libgdx,sarkanyi/libgdx,FredGithub/libgdx,Deftwun/libgdx,toa5/libgdx,revo09/libgdx,haedri/libgdx-1,ttencate/libgdx,del-sol/libgdx,czyzby/libgdx,fwolff/libgdx,curtiszimmerman/libgdx,gdos/libgdx,Senth/libgdx,andyvand/libgdx,noelsison2/libgdx,saqsun/libgdx,MadcowD/libgdx,xpenatan/libgdx-LWJGL3,tommyettinger/libgdx,jasonwee/libgdx,jberberick/libgdx,Zomby2D/libgdx,zhimaijoy/libgdx,kagehak/libgdx,shiweihappy/libgdx,nudelchef/libgdx,JFixby/libgdx,designcrumble/libgdx,Deftwun/libgdx,snovak/libgdx,azakhary/libgdx,js78/libgdx,nave966/libgdx,FredGithub/libgdx,MathieuDuponchelle/gdx,antag99/libgdx,saltares/libgdx,mumer92/libgdx,stinsonga/libgdx,sinistersnare/libgdx,nelsonsilva/libgdx,Gliby/libgdx,1yvT0s/libgdx,noelsison2/libgdx,fiesensee/libgdx,stickyd/libgdx,copystudy/libgdx,ryoenji/libgdx,cypherdare/libgdx,MadcowD/libgdx,toloudis/libgdx,noelsison2/libgdx,bgroenks96/libgdx,snovak/libgdx,FredGithub/libgdx,nave966/libgdx,ricardorigodon/libgdx,bladecoder/libgdx,lordjone/libgdx,Heart2009/libgdx,jsjolund/libgdx,saqsun/libgdx,PedroRomanoBarbosa/libgdx,sjosegarcia/libgdx,Zonglin-Li6565/libgdx,kagehak/libgdx,antag99/libgdx,nrallakis/libgdx,NathanSweet/libgdx,kagehak/libgdx,kotcrab/libgdx,nudelchef/libgdx,BlueRiverInteractive/libgdx,jasonwee/libgdx,saltares/libgdx,Zonglin-Li6565/libgdx,davebaol/libgdx,JDReutt/libgdx,ThiagoGarciaAlves/libgdx,samskivert/libgdx,FyiurAmron/libgdx,petugez/libgdx,Zonglin-Li6565/libgdx,andyvand/libgdx,revo09/libgdx,curtiszimmerman/libgdx,xranby/libgdx,Xhanim/libgdx,junkdog/libgdx,ttencate/libgdx,toa5/libgdx,NathanSweet/libgdx,samskivert/libgdx,alex-dorokhov/libgdx,sarkanyi/libgdx,ThiagoGarciaAlves/libgdx,Dzamir/libgdx,nudelchef/libgdx,firefly2442/libgdx,youprofit/libgdx,nrallakis/libgdx,samskivert/libgdx,js78/libgdx,srwonka/libGdx,MovingBlocks/libgdx,jberberick/libgdx,EsikAntony/libgdx,Thotep/libgdx,kagehak/libgdx,czyzby/libgdx,titovmaxim/libgdx,azakhary/libgdx,toloudis/libgdx,1yvT0s/libgdx,czyzby/libgdx,PedroRomanoBarbosa/libgdx,bsmr-java/libgdx,Zomby2D/libgdx,EsikAntony/libgdx,nelsonsilva/libgdx,GreenLightning/libgdx,snovak/libgdx,SidneyXu/libgdx,fwolff/libgdx,youprofit/libgdx,NathanSweet/libgdx,jsjolund/libgdx,GreenLightning/libgdx,antag99/libgdx,zommuter/libgdx,1yvT0s/libgdx,xoppa/libgdx,flaiker/libgdx,katiepino/libgdx,sinistersnare/libgdx,josephknight/libgdx,Heart2009/libgdx,libgdx/libgdx,kotcrab/libgdx,jasonwee/libgdx,yangweigbh/libgdx,sjosegarcia/libgdx,PedroRomanoBarbosa/libgdx,snovak/libgdx,anserran/libgdx,firefly2442/libgdx,ztv/libgdx,tell10glu/libgdx,MadcowD/libgdx,1yvT0s/libgdx,haedri/libgdx-1,saltares/libgdx,BlueRiverInteractive/libgdx,yangweigbh/libgdx,shiweihappy/libgdx,zommuter/libgdx,UnluckyNinja/libgdx,TheAks999/libgdx,collinsmith/libgdx,Badazdz/libgdx,ThiagoGarciaAlves/libgdx,Xhanim/libgdx,MathieuDuponchelle/gdx,Zomby2D/libgdx,luischavez/libgdx,PedroRomanoBarbosa/libgdx,junkdog/libgdx,Deftwun/libgdx,alex-dorokhov/libgdx,xpenatan/libgdx-LWJGL3,xpenatan/libgdx-LWJGL3,ya7lelkom/libgdx,sarkanyi/libgdx,JDReutt/libgdx,haedri/libgdx-1,gdos/libgdx,KrisLee/libgdx,tommyettinger/libgdx,MovingBlocks/libgdx,JDReutt/libgdx,petugez/libgdx,JDReutt/libgdx,katiepino/libgdx,kotcrab/libgdx,PedroRomanoBarbosa/libgdx,1yvT0s/libgdx,petugez/libgdx,realitix/libgdx,stickyd/libgdx,anserran/libgdx,shiweihappy/libgdx,MathieuDuponchelle/gdx,tommycli/libgdx,copystudy/libgdx,gouessej/libgdx,PedroRomanoBarbosa/libgdx,Gliby/libgdx,saqsun/libgdx,jsjolund/libgdx,libgdx/libgdx,Heart2009/libgdx,js78/libgdx,nelsonsilva/libgdx,katiepino/libgdx,noelsison2/libgdx,zhimaijoy/libgdx,nave966/libgdx,junkdog/libgdx,toa5/libgdx,hyvas/libgdx,luischavez/libgdx,zommuter/libgdx,Xhanim/libgdx,tommyettinger/libgdx,Xhanim/libgdx,hyvas/libgdx,bsmr-java/libgdx,toloudis/libgdx,djom20/libgdx,fiesensee/libgdx,nrallakis/libgdx,MetSystem/libgdx,tommycli/libgdx,andyvand/libgdx,Dzamir/libgdx,anserran/libgdx,gf11speed/libgdx,gf11speed/libgdx,stickyd/libgdx,alireza-hosseini/libgdx,FredGithub/libgdx,jberberick/libgdx,bgroenks96/libgdx,ztv/libgdx,EsikAntony/libgdx,andyvand/libgdx,billgame/libgdx,zhimaijoy/libgdx,MetSystem/libgdx,nrallakis/libgdx,revo09/libgdx,bsmr-java/libgdx,saqsun/libgdx,SidneyXu/libgdx,collinsmith/libgdx,alireza-hosseini/libgdx,MetSystem/libgdx,katiepino/libgdx,UnluckyNinja/libgdx,toa5/libgdx,collinsmith/libgdx,UnluckyNinja/libgdx,nooone/libgdx,luischavez/libgdx,copystudy/libgdx,fiesensee/libgdx,czyzby/libgdx,thepullman/libgdx,revo09/libgdx,yangweigbh/libgdx,Zonglin-Li6565/libgdx,codepoke/libgdx,nelsonsilva/libgdx,saqsun/libgdx,realitix/libgdx,nave966/libgdx,Xhanim/libgdx,copystudy/libgdx,copystudy/libgdx,andyvand/libgdx,titovmaxim/libgdx,noelsison2/libgdx,anserran/libgdx,curtiszimmerman/libgdx,alireza-hosseini/libgdx,sarkanyi/libgdx,kzganesan/libgdx,copystudy/libgdx,ryoenji/libgdx,Zomby2D/libgdx,ryoenji/libgdx,MadcowD/libgdx,Wisienkas/libgdx,Zonglin-Li6565/libgdx,fiesensee/libgdx,Heart2009/libgdx,SidneyXu/libgdx,gouessej/libgdx,KrisLee/libgdx,jasonwee/libgdx,gf11speed/libgdx,luischavez/libgdx,snovak/libgdx,lordjone/libgdx,1yvT0s/libgdx,Senth/libgdx,saqsun/libgdx,czyzby/libgdx,SidneyXu/libgdx,nooone/libgdx,jsjolund/libgdx,gdos/libgdx,curtiszimmerman/libgdx,codepoke/libgdx,josephknight/libgdx,Arcnor/libgdx,jasonwee/libgdx,djom20/libgdx,Heart2009/libgdx,Xhanim/libgdx,ya7lelkom/libgdx,toa5/libgdx,KrisLee/libgdx,samskivert/libgdx,gdos/libgdx,gouessej/libgdx,kzganesan/libgdx,GreenLightning/libgdx,JFixby/libgdx,andyvand/libgdx,kagehak/libgdx,fwolff/libgdx,lordjone/libgdx,ThiagoGarciaAlves/libgdx,katiepino/libgdx,bladecoder/libgdx,nrallakis/libgdx,tommycli/libgdx,ttencate/libgdx,ricardorigodon/libgdx,ryoenji/libgdx,katiepino/libgdx,MikkelTAndersen/libgdx,GreenLightning/libgdx,hyvas/libgdx,mumer92/libgdx,nave966/libgdx,curtiszimmerman/libgdx,codepoke/libgdx,kzganesan/libgdx,designcrumble/libgdx,kzganesan/libgdx,gf11speed/libgdx,cypherdare/libgdx,Gliby/libgdx,xoppa/libgdx,saltares/libgdx,tommyettinger/libgdx,luischavez/libgdx,EsikAntony/libgdx,ya7lelkom/libgdx,ricardorigodon/libgdx,KrisLee/libgdx,GreenLightning/libgdx,Wisienkas/libgdx,EsikAntony/libgdx,xpenatan/libgdx-LWJGL3,Gliby/libgdx,Dzamir/libgdx,xpenatan/libgdx-LWJGL3,nooone/libgdx,firefly2442/libgdx,josephknight/libgdx,mumer92/libgdx,saltares/libgdx,ricardorigodon/libgdx,MadcowD/libgdx,kotcrab/libgdx,tell10glu/libgdx,309746069/libgdx,ztv/libgdx,GreenLightning/libgdx,ninoalma/libgdx,ttencate/libgdx,azakhary/libgdx,mumer92/libgdx,nudelchef/libgdx,nave966/libgdx,FredGithub/libgdx,Gliby/libgdx,del-sol/libgdx,billgame/libgdx,shiweihappy/libgdx,MathieuDuponchelle/gdx,ztv/libgdx,nrallakis/libgdx,bsmr-java/libgdx,titovmaxim/libgdx,Badazdz/libgdx,nudelchef/libgdx,sarkanyi/libgdx,tell10glu/libgdx,samskivert/libgdx,nudelchef/libgdx,anserran/libgdx,FredGithub/libgdx,MadcowD/libgdx,codepoke/libgdx,designcrumble/libgdx,kzganesan/libgdx,JFixby/libgdx,djom20/libgdx,josephknight/libgdx,JFixby/libgdx,youprofit/libgdx,zhimaijoy/libgdx,thepullman/libgdx,alex-dorokhov/libgdx,xranby/libgdx,kagehak/libgdx,cypherdare/libgdx,fwolff/libgdx,MovingBlocks/libgdx,billgame/libgdx,basherone/libgdxcn,MikkelTAndersen/libgdx,mumer92/libgdx,FredGithub/libgdx,FyiurAmron/libgdx,srwonka/libGdx,jberberick/libgdx,designcrumble/libgdx,ya7lelkom/libgdx,309746069/libgdx,MikkelTAndersen/libgdx,tell10glu/libgdx,bgroenks96/libgdx,EsikAntony/libgdx,flaiker/libgdx,noelsison2/libgdx,TheAks999/libgdx,tell10glu/libgdx,ricardorigodon/libgdx,alex-dorokhov/libgdx,anserran/libgdx,basherone/libgdxcn,Badazdz/libgdx,Wisienkas/libgdx,czyzby/libgdx,Senth/libgdx,jasonwee/libgdx,hyvas/libgdx,haedri/libgdx-1,Wisienkas/libgdx,JFixby/libgdx,titovmaxim/libgdx,realitix/libgdx,josephknight/libgdx,tommycli/libgdx,ttencate/libgdx,1yvT0s/libgdx,KrisLee/libgdx,PedroRomanoBarbosa/libgdx,sjosegarcia/libgdx,flaiker/libgdx,josephknight/libgdx,sjosegarcia/libgdx,youprofit/libgdx,cypherdare/libgdx,antag99/libgdx,katiepino/libgdx,ninoalma/libgdx,youprofit/libgdx,stickyd/libgdx,djom20/libgdx,alex-dorokhov/libgdx,TheAks999/libgdx,NathanSweet/libgdx,yangweigbh/libgdx,jsjolund/libgdx,sarkanyi/libgdx,Deftwun/libgdx,jasonwee/libgdx,firefly2442/libgdx,bgroenks96/libgdx,del-sol/libgdx,thepullman/libgdx,bgroenks96/libgdx,TheAks999/libgdx,FyiurAmron/libgdx,stickyd/libgdx,ttencate/libgdx,thepullman/libgdx,basherone/libgdxcn,MikkelTAndersen/libgdx,tell10glu/libgdx,petugez/libgdx,NathanSweet/libgdx,1yvT0s/libgdx,xoppa/libgdx,zommuter/libgdx,luischavez/libgdx,flaiker/libgdx,MathieuDuponchelle/gdx,xranby/libgdx,ninoalma/libgdx,del-sol/libgdx,FyiurAmron/libgdx,MikkelTAndersen/libgdx,Badazdz/libgdx,GreenLightning/libgdx,alex-dorokhov/libgdx,flaiker/libgdx,xranby/libgdx,Arcnor/libgdx,Heart2009/libgdx,billgame/libgdx,xpenatan/libgdx-LWJGL3,thepullman/libgdx,toloudis/libgdx,js78/libgdx,firefly2442/libgdx,Arcnor/libgdx,collinsmith/libgdx,Thotep/libgdx,yangweigbh/libgdx,nudelchef/libgdx,davebaol/libgdx,js78/libgdx,jsjolund/libgdx,JFixby/libgdx,Senth/libgdx,designcrumble/libgdx,curtiszimmerman/libgdx,nelsonsilva/libgdx,fiesensee/libgdx,nooone/libgdx,toloudis/libgdx,BlueRiverInteractive/libgdx,ztv/libgdx,MovingBlocks/libgdx,jberberick/libgdx,antag99/libgdx,MetSystem/libgdx,alireza-hosseini/libgdx,ya7lelkom/libgdx,BlueRiverInteractive/libgdx,revo09/libgdx,alireza-hosseini/libgdx,saltares/libgdx,thepullman/libgdx,designcrumble/libgdx,bsmr-java/libgdx,MetSystem/libgdx,curtiszimmerman/libgdx,junkdog/libgdx,basherone/libgdxcn,zhimaijoy/libgdx,haedri/libgdx-1,saqsun/libgdx,gouessej/libgdx,Gliby/libgdx,FyiurAmron/libgdx,TheAks999/libgdx,Senth/libgdx,titovmaxim/libgdx,TheAks999/libgdx,kagehak/libgdx,azakhary/libgdx,js78/libgdx,nudelchef/libgdx,djom20/libgdx,309746069/libgdx,realitix/libgdx,JDReutt/libgdx,bladecoder/libgdx,MovingBlocks/libgdx,thepullman/libgdx,fwolff/libgdx,sinistersnare/libgdx,titovmaxim/libgdx,libgdx/libgdx,alireza-hosseini/libgdx,zhimaijoy/libgdx,billgame/libgdx,gf11speed/libgdx,shiweihappy/libgdx,xoppa/libgdx,zhimaijoy/libgdx,zommuter/libgdx,KrisLee/libgdx,BlueRiverInteractive/libgdx,azakhary/libgdx,tommycli/libgdx,firefly2442/libgdx,mumer92/libgdx,MikkelTAndersen/libgdx,kzganesan/libgdx,kotcrab/libgdx,Senth/libgdx,MikkelTAndersen/libgdx,djom20/libgdx,stinsonga/libgdx,sjosegarcia/libgdx,UnluckyNinja/libgdx,MovingBlocks/libgdx,JDReutt/libgdx,junkdog/libgdx,zommuter/libgdx,davebaol/libgdx,tommyettinger/libgdx,revo09/libgdx,gdos/libgdx,MathieuDuponchelle/gdx,antag99/libgdx,UnluckyNinja/libgdx,sinistersnare/libgdx,czyzby/libgdx,fiesensee/libgdx,gouessej/libgdx,snovak/libgdx,youprofit/libgdx,realitix/libgdx,SidneyXu/libgdx,nelsonsilva/libgdx,MathieuDuponchelle/gdx,shiweihappy/libgdx,xoppa/libgdx,xoppa/libgdx,codepoke/libgdx,SidneyXu/libgdx,Thotep/libgdx,billgame/libgdx,ya7lelkom/libgdx,gf11speed/libgdx,xranby/libgdx,JDReutt/libgdx,anserran/libgdx,sjosegarcia/libgdx,noelsison2/libgdx,stinsonga/libgdx,codepoke/libgdx,davebaol/libgdx,MathieuDuponchelle/gdx,snovak/libgdx,BlueRiverInteractive/libgdx,MadcowD/libgdx,bgroenks96/libgdx,zommuter/libgdx,EsikAntony/libgdx,billgame/libgdx,ricardorigodon/libgdx,ninoalma/libgdx,antag99/libgdx,stinsonga/libgdx,toa5/libgdx,Badazdz/libgdx,gdos/libgdx,basherone/libgdxcn,ryoenji/libgdx,kotcrab/libgdx,MathieuDuponchelle/gdx,Wisienkas/libgdx,samskivert/libgdx,revo09/libgdx,JFixby/libgdx,309746069/libgdx,anserran/libgdx,srwonka/libGdx,firefly2442/libgdx,ThiagoGarciaAlves/libgdx,czyzby/libgdx,libgdx/libgdx,ttencate/libgdx,sinistersnare/libgdx,Wisienkas/libgdx,toloudis/libgdx,jberberick/libgdx,Dzamir/libgdx
|
/*******************************************************************************
* Copyright 2010 Mario Zechner ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Sprite;
import com.badlogic.gdx.graphics.SpriteCache;
import com.badlogic.gdx.tests.utils.GdxTest;
import static com.badlogic.gdx.graphics.Texture.TextureFilter.*;
import static com.badlogic.gdx.graphics.Texture.TextureWrap.*;
public class SpriteCacheOffsetTest extends GdxTest implements InputProcessor {
private int tileMapWidth = 10;
private int tileMapHeight = 5;
private int tileSize = 32;
private SpriteCache cache;
public void create () {
Sprite sprite = new Sprite(Gdx.graphics.newTexture(Gdx.files.internal("data/badlogicsmall.jpg"), Linear, Linear,
ClampToEdge, ClampToEdge));
sprite.setSize(tileSize, tileSize);
cache = new SpriteCache(1000);
for (int y = 0; y < tileMapHeight; y++) {
cache.beginCache();
for (int x = 0; x < tileMapWidth; x++) {
sprite.setPosition(x * tileSize, y * tileSize);
cache.add(sprite);
}
cache.endCache();
sprite.rotate(90);
}
}
public void render () {
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
cache.begin();
for (int y = 1; y < tileMapHeight - 1; y++)
cache.draw(y, 1, tileMapWidth - 2);
cache.end();
}
public boolean keyDown (int keycode) {
return false;
}
public boolean keyUp (int keycode) {
return false;
}
public boolean keyTyped (char character) {
return false;
}
public boolean touchDown (int x, int y, int pointer) {
return false;
}
public boolean touchUp (int x, int y, int pointer) {
return false;
}
public boolean touchDragged (int x, int y, int pointer) {
return false;
}
public boolean needsGL20 () {
return false;
}
}
|
tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteCacheOffsetTest.java
|
/*******************************************************************************
* Copyright 2010 Mario Zechner ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.Sprite;
import com.badlogic.gdx.graphics.SpriteCache;
import com.badlogic.gdx.tests.utils.GdxTest;
import static com.badlogic.gdx.graphics.Texture.TextureFilter.*;
import static com.badlogic.gdx.graphics.Texture.TextureWrap.*;
public class SpriteCacheOffsetTest extends GdxTest implements InputProcessor {
private int tileMapWidth = 10;
private int tileMapHeight = 5;
private int tileSize = 32;
private SpriteCache cache;
public void create () {
Sprite sprite = new Sprite(Gdx.graphics.newTexture(Gdx.files.internal("data/badlogicsmall.jpg"), Linear, Linear,
ClampToEdge, ClampToEdge));
sprite.setSize(tileSize, tileSize);
cache = new SpriteCache(1000);
for (int y = 0; y < tileMapHeight; y++) {
cache.beginCache();
for (int x = 0; x < tileMapWidth; x++) {
sprite.setPosition(x * tileSize, y * tileSize);
cache.add(sprite);
}
cache.endCache();
sprite.rotate(90);
}
}
public void render () {
cache.begin();
for (int y = 1; y < tileMapHeight - 1; y++)
cache.draw(y, 1, tileMapWidth - 2);
cache.end();
}
public boolean keyDown (int keycode) {
return false;
}
public boolean keyUp (int keycode) {
return false;
}
public boolean keyTyped (char character) {
return false;
}
public boolean touchDown (int x, int y, int pointer) {
return false;
}
public boolean touchUp (int x, int y, int pointer) {
return false;
}
public boolean touchDragged (int x, int y, int pointer) {
return false;
}
public boolean needsGL20 () {
return false;
}
}
|
[fixed] Clear screen for SpriteCacheOffsetTest.
|
tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteCacheOffsetTest.java
|
[fixed] Clear screen for SpriteCacheOffsetTest.
|
<ide><path>ests/gdx-tests/src/com/badlogic/gdx/tests/SpriteCacheOffsetTest.java
<ide>
<ide> import com.badlogic.gdx.Gdx;
<ide> import com.badlogic.gdx.InputProcessor;
<add>import com.badlogic.gdx.graphics.GL10;
<ide> import com.badlogic.gdx.graphics.Sprite;
<ide> import com.badlogic.gdx.graphics.SpriteCache;
<ide> import com.badlogic.gdx.tests.utils.GdxTest;
<ide> }
<ide>
<ide> public void render () {
<add> Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
<ide> cache.begin();
<ide> for (int y = 1; y < tileMapHeight - 1; y++)
<ide> cache.draw(y, 1, tileMapWidth - 2);
|
|
Java
|
mit
|
e89a490b320348b9dcb61628e3e8a509a775f888
| 0 |
valesken/CaughtUp
|
package news.caughtup.caughtup.ui.prime;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import io.fabric.sdk.android.services.network.HttpRequest;
import news.caughtup.caughtup.R;
import news.caughtup.caughtup.entities.ResponseObject;
import news.caughtup.caughtup.entities.User;
import news.caughtup.caughtup.ws.remote.Callback;
import news.caughtup.caughtup.ws.remote.RestProxy;
public class EditProfileFragment extends Fragment {
private static final int REQUEST_CAMERA = 1;
private static final int SELECT_FILE = 2;
private User user;
private ImageView profilePicView;
private TextView userNameView;
private Spinner genderSpinner;
private EditText ageView;
private EditText fullNameView;
private EditText emailView;
private EditText locationView;
private EditText aboutMeView;
private View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_edit_profile, container, false);
user = HomeActivity.getCurrentUser();
System.out.println("Email: " + user.getEmail());
System.out.println("Full Name: " + user.getFullName());
//get references to views region
profilePicView = (ImageView) rootView.findViewById(R.id.edit_profile_photo_image_view);
userNameView = (TextView) rootView.findViewById(R.id.edit_profile_username_text_view);
genderSpinner = (Spinner) rootView.findViewById(R.id.edit_profile_gender_edit_text);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.gender_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
genderSpinner.setAdapter(adapter);
ageView = (EditText) rootView.findViewById(R.id.edit_profile_age_edit_text);
fullNameView = (EditText) rootView.findViewById(R.id.edit_profile_full_name_edit_text);
emailView = (EditText) rootView.findViewById(R.id.edit_profile_email_edit_text);
locationView = (EditText) rootView.findViewById(R.id.edit_profile_location_edit_text);
aboutMeView = (EditText) rootView.findViewById(R.id.edit_profile_about_me_edit_text);
//end region
setUpCurrentUserInfo();
RelativeLayout editProfilePicture = (RelativeLayout) rootView.findViewById(R.id.edit_profile_picture_relative_layout);
editProfilePicture.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
selectPhoto();
return false;
}
});
//region setup button listeners
Button changePasswordButton = (Button) rootView.findViewById(R.id.edit_profile_change_password_button);
changePasswordButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ChangePasswordFragment changePasswordFragment = new ChangePasswordFragment();
HomeActivity.executeTransaction(changePasswordFragment, "change_password", R.string.change_password_title);
}
});
Button saveChangesButton = (Button) rootView.findViewById(R.id.edit_profile_save_button);
saveChangesButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RestProxy proxy = RestProxy.getProxy();
Callback callback = getUpdatedUserCallback();
JSONObject jsonObject = createJSON();
Log.e("JSON Object", jsonObject.toString());
if (!validateEmail(emailView.getText().toString())) {
Toast.makeText(getActivity(),
getActivity().getResources().getString(R.string.invalid_email_address),
Toast.LENGTH_SHORT)
.show();
} else {
proxy.putCall(String.format("/profile/%s?picture=false", user.getName()),
jsonObject.toString(), callback);
}
}
});
//end region
return rootView;
}
private void setUpCurrentUserInfo() {
// Profile Picture
int imageResourceId = user.getProfileImageId();
if(imageResourceId > 0) {
profilePicView.setImageDrawable(getActivity().getResources().getDrawable(imageResourceId, null));
} else {
profilePicView.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.profile_pic_2, null));
}
// Username
userNameView.setText(user.getName());
// Gender
String gender = user.getGender();
if(gender != null && !gender.isEmpty()) {
switch (gender.toLowerCase()) {
case "male":
genderSpinner.setSelection(1);
break;
case "female":
genderSpinner.setSelection(2);
break;
default:
genderSpinner.setSelection(0);
break;
}
}
// Age
int age = user.getAge();
if(age > 1) {
ageView.setText(String.format("%d", age));
}
// Full Name
String fullName = user.getFullName();
if(fullName != null && !fullName.isEmpty()) {
fullNameView.setText(user.getFullName());
}
// Email
String email = user.getEmail();
if(email != null && !email.isEmpty()) {
emailView.setText(email);
}
// Location
String location = user.getLocation();
if(location != null && !location.isEmpty()) {
locationView.setText(location);
}
// About me
String aboutMe = user.getAboutMe();
if(aboutMe != null && !aboutMe.isEmpty()) {
aboutMeView.setText(aboutMe);
}
}
private Callback getUpdatedUserCallback() {
return new Callback() {
@Override
public void process(ResponseObject responseObject) {
if (responseObject.getResponseCode() == 200) {
JSONObject jsonObject = responseObject.getJsonObject();
try {
if (jsonObject.getString("message").equals("Success")) {
updateUser();
} else {
Toast.makeText(getActivity().getApplicationContext(),
getActivity().getResources().getString(R.string.update_user_server_error),
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity().getApplicationContext(),
getActivity().getResources().getString(R.string.update_user_server_error),
Toast.LENGTH_LONG).show();
}
}
};
}
private void updateUser() {
// Gender
String gender = genderSpinner.getSelectedItem().toString();
if(gender != null && !gender.isEmpty()) {
user.setGender(gender);
}
// Age
int age = Integer.parseInt(ageView.getText().toString());
if (age > 1) {
user.setAge(age);
}
// Full Name
String fullName = fullNameView.getText().toString();
if(fullName != null && !fullName.isEmpty()) {
user.setFullName(fullName);
}
// Email
String email = emailView.getText().toString();
if(email != null && !email.isEmpty()) {
user.setEmail(email);
}
// Location
String location = locationView.getText().toString();
if(location != null && !location.isEmpty()) {
user.setLocation(location);
}
// About me
String aboutMe = aboutMeView.getText().toString();
if(aboutMe != null && !aboutMe.isEmpty()) {
user.setAboutMe(aboutMe);
}
}
private JSONObject createJSON() {
JSONObject jsonObject = new JSONObject();
// Gender
try {
String gender = genderSpinner.getSelectedItem().toString();
if(gender != null && !gender.isEmpty()) {
jsonObject.put("gender", gender);
}
// Age
int age = Integer.parseInt(ageView.getText().toString());
if (age > 1) {
jsonObject.put("age", age);
}
// Full Name
String fullName = fullNameView.getText().toString();
if(fullName != null && !fullName.isEmpty()) {
jsonObject.put("fullName", fullName);
}
// Email
String email = emailView.getText().toString();
if(email != null && !email.isEmpty()) {
jsonObject.put("email", email);
}
// Location
String location = locationView.getText().toString();
if(location != null && !location.isEmpty()) {
jsonObject.put("location", location);
}
// About me
String aboutMe = aboutMeView.getText().toString();
if(aboutMe != null && !aboutMe.isEmpty()) {
jsonObject.put("aboutMe", aboutMe);
}
return jsonObject;
} catch (JSONException e) {
Log.e("JSONException", "Couldn't create JSON with updated user");
return null;
}
}
/**
* Validate an input string as an email
* @param email
* @return
*/
private boolean validateEmail(String email) {
Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
Matcher m = p.matcher(email);
return m.matches();
}
private void selectPhoto() {
final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == getActivity().RESULT_OK) {
JSONObject jsonObject = new JSONObject();
try {
Bitmap bitmap = null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
if (requestCode == REQUEST_CAMERA) {
Log.e("Inside REQUEST_CAMERA: ", "Handling an image");
bitmap = (Bitmap) data.getExtras().get("data");
} else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
CursorLoader cursorLoader = new CursorLoader(getActivity(), selectedImageUri,
projection, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
bitmap = BitmapFactory.decodeFile(selectedImagePath, options);
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); //compress to which format you want.
byte[] byte_arr = stream.toByteArray();
String imageStr = HttpRequest.Base64.encodeBytes(byte_arr);
jsonObject.put("image", imageStr);
jsonObject.put("type", "jpeg");
Callback callback = getUploadImageCallback();
RestProxy proxy = RestProxy.getProxy();
proxy.putCall(String.format("/profile/%s?picture=true", user.getName()), jsonObject.toString(), callback);
} catch (JSONException e) {
Log.e("JSONException", "Could not form correct JSON object");
}
}
}
private Callback getUploadImageCallback() {
return new Callback() {
@Override
public void process(ResponseObject responseObject) {
if (responseObject.getResponseCode() == 200) {
JSONObject jsonObject = responseObject.getJsonObject();
try {
String profilePicURL = jsonObject.getString("profile_picture_url");
Log.e("ProfilePicURl: ", profilePicURL);
//int imageId = getImageId();
//profilePicView.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.profile_pic_2, null));
//user.setProfileImageId(imageId);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity().getApplicationContext(),
getActivity().getResources().getString(R.string.update_user_server_error),
Toast.LENGTH_LONG).show();
}
}
};
}
private int getImageId() {
Random r = new Random();
int n;
do {
n = r.nextInt(Integer.MAX_VALUE);
} while (getResources().getDrawable(n, null) != null);
return n;
}
}
|
CaughtUp/app/src/main/java/news/caughtup/caughtup/ui/prime/EditProfileFragment.java
|
package news.caughtup.caughtup.ui.prime;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import news.caughtup.caughtup.R;
import news.caughtup.caughtup.entities.ResponseObject;
import news.caughtup.caughtup.entities.User;
import news.caughtup.caughtup.ws.remote.Callback;
import news.caughtup.caughtup.ws.remote.RestProxy;
public class EditProfileFragment extends Fragment {
private static final int REQUEST_CAMERA = 1;
private static final int SELECT_FILE = 2;
private User user;
private ImageView profilePicView;
private TextView userNameView;
private Spinner genderSpinner;
private EditText ageView;
private EditText fullNameView;
private EditText emailView;
private EditText locationView;
private EditText aboutMeView;
private View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_edit_profile, container, false);
user = HomeActivity.getCurrentUser();
System.out.println("Email: " + user.getEmail());
System.out.println("Full Name: " + user.getFullName());
//get references to views region
profilePicView = (ImageView) rootView.findViewById(R.id.edit_profile_photo_image_view);
userNameView = (TextView) rootView.findViewById(R.id.edit_profile_username_text_view);
genderSpinner = (Spinner) rootView.findViewById(R.id.edit_profile_gender_edit_text);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.gender_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
genderSpinner.setAdapter(adapter);
ageView = (EditText) rootView.findViewById(R.id.edit_profile_age_edit_text);
fullNameView = (EditText) rootView.findViewById(R.id.edit_profile_full_name_edit_text);
emailView = (EditText) rootView.findViewById(R.id.edit_profile_email_edit_text);
locationView = (EditText) rootView.findViewById(R.id.edit_profile_location_edit_text);
aboutMeView = (EditText) rootView.findViewById(R.id.edit_profile_about_me_edit_text);
//end region
setUpCurrentUserInfo();
RelativeLayout editProfilePicture = (RelativeLayout) rootView.findViewById(R.id.edit_profile_picture_relative_layout);
editProfilePicture.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
selectPhoto();
return false;
}
});
//region setup button listeners
Button changePasswordButton = (Button) rootView.findViewById(R.id.edit_profile_change_password_button);
changePasswordButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ChangePasswordFragment changePasswordFragment = new ChangePasswordFragment();
HomeActivity.executeTransaction(changePasswordFragment, "change_password", R.string.change_password_title);
}
});
Button saveChangesButton = (Button) rootView.findViewById(R.id.edit_profile_save_button);
saveChangesButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RestProxy proxy = RestProxy.getProxy();
Callback callback = getUpdatedUserCallback();
JSONObject jsonObject = createJSON();
Log.e("JSON Object", jsonObject.toString());
if (!validateEmail(emailView.getText().toString())) {
Toast.makeText(getActivity(),
getActivity().getResources().getString(R.string.invalid_email_address),
Toast.LENGTH_SHORT)
.show();
} else {
proxy.putCall(String.format("/profile/%s?picture=false", user.getName()),
jsonObject.toString(), callback);
}
}
});
//end region
return rootView;
}
private void setUpCurrentUserInfo() {
// Profile Picture
int imageResourceId = user.getProfileImageId();
if(imageResourceId > 0) {
profilePicView.setImageDrawable(getActivity().getResources().getDrawable(imageResourceId, null));
} else {
profilePicView.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.profile_pic_2, null));
}
// Username
userNameView.setText(user.getName());
// Gender
String gender = user.getGender();
if(gender != null && !gender.isEmpty()) {
switch (gender.toLowerCase()) {
case "male":
genderSpinner.setSelection(1);
break;
case "female":
genderSpinner.setSelection(2);
break;
default:
genderSpinner.setSelection(0);
break;
}
}
// Age
int age = user.getAge();
if(age > 1) {
ageView.setText(String.format("%d", age));
}
// Full Name
String fullName = user.getFullName();
if(fullName != null && !fullName.isEmpty()) {
fullNameView.setText(user.getFullName());
}
// Email
String email = user.getEmail();
if(email != null && !email.isEmpty()) {
emailView.setText(email);
}
// Location
String location = user.getLocation();
if(location != null && !location.isEmpty()) {
locationView.setText(location);
}
// About me
String aboutMe = user.getAboutMe();
if(aboutMe != null && !aboutMe.isEmpty()) {
aboutMeView.setText(aboutMe);
}
}
private Callback getUpdatedUserCallback() {
return new Callback() {
@Override
public void process(ResponseObject responseObject) {
if (responseObject.getResponseCode() == 200) {
JSONObject jsonObject = responseObject.getJsonObject();
try {
if (jsonObject.getString("message").equals("Success")) {
updateUser();
} else {
Toast.makeText(getActivity().getApplicationContext(),
getActivity().getResources().getString(R.string.update_user_server_error),
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity().getApplicationContext(),
getActivity().getResources().getString(R.string.update_user_server_error),
Toast.LENGTH_LONG).show();
}
}
};
}
private void updateUser() {
// Gender
String gender = genderSpinner.getSelectedItem().toString();
if(gender != null && !gender.isEmpty()) {
user.setGender(gender);
}
// Age
int age = Integer.parseInt(ageView.getText().toString());
if (age > 1) {
user.setAge(age);
}
// Full Name
String fullName = fullNameView.getText().toString();
if(fullName != null && !fullName.isEmpty()) {
user.setFullName(fullName);
}
// Email
String email = emailView.getText().toString();
if(email != null && !email.isEmpty()) {
user.setEmail(email);
}
// Location
String location = locationView.getText().toString();
if(location != null && !location.isEmpty()) {
user.setLocation(location);
}
// About me
String aboutMe = aboutMeView.getText().toString();
if(aboutMe != null && !aboutMe.isEmpty()) {
user.setAboutMe(aboutMe);
}
}
private JSONObject createJSON() {
JSONObject jsonObject = new JSONObject();
// Gender
try {
String gender = genderSpinner.getSelectedItem().toString();
if(gender != null && !gender.isEmpty()) {
jsonObject.put("gender", gender);
}
// Age
int age = Integer.parseInt(ageView.getText().toString());
if (age > 1) {
jsonObject.put("age", age);
}
// Full Name
String fullName = fullNameView.getText().toString();
if(fullName != null && !fullName.isEmpty()) {
jsonObject.put("fullName", fullName);
}
// Email
String email = emailView.getText().toString();
if(email != null && !email.isEmpty()) {
jsonObject.put("email", email);
}
// Location
String location = locationView.getText().toString();
if(location != null && !location.isEmpty()) {
jsonObject.put("location", location);
}
// About me
String aboutMe = aboutMeView.getText().toString();
if(aboutMe != null && !aboutMe.isEmpty()) {
jsonObject.put("aboutMe", aboutMe);
}
return jsonObject;
} catch (JSONException e) {
Log.e("JSONException", "Couldn't create JSON with updated user");
return null;
}
}
/**
* Validate an input string as an email
* @param email
* @return
*/
private boolean validateEmail(String email) {
Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
Matcher m = p.matcher(email);
return m.matches();
}
private void selectPhoto() {
final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
}
|
Uploading image from taking a picture works
|
CaughtUp/app/src/main/java/news/caughtup/caughtup/ui/prime/EditProfileFragment.java
|
Uploading image from taking a picture works
|
<ide><path>aughtUp/app/src/main/java/news/caughtup/caughtup/ui/prime/EditProfileFragment.java
<ide>
<ide> import android.app.AlertDialog;
<ide> import android.app.Fragment;
<add>import android.content.CursorLoader;
<ide> import android.content.DialogInterface;
<ide> import android.content.Intent;
<add>import android.database.Cursor;
<add>import android.graphics.Bitmap;
<add>import android.graphics.BitmapFactory;
<add>import android.graphics.Canvas;
<add>import android.graphics.ColorFilter;
<add>import android.graphics.drawable.Drawable;
<add>import android.net.Uri;
<ide> import android.os.Bundle;
<ide> import android.provider.MediaStore;
<ide> import android.util.Log;
<ide> import org.json.JSONException;
<ide> import org.json.JSONObject;
<ide>
<add>import java.io.ByteArrayOutputStream;
<add>import java.util.Random;
<ide> import java.util.regex.Matcher;
<ide> import java.util.regex.Pattern;
<ide>
<add>import io.fabric.sdk.android.services.network.HttpRequest;
<ide> import news.caughtup.caughtup.R;
<ide> import news.caughtup.caughtup.entities.ResponseObject;
<ide> import news.caughtup.caughtup.entities.User;
<ide> });
<ide> builder.show();
<ide> }
<add>
<add> @Override
<add> public void onActivityResult(int requestCode, int resultCode, Intent data) {
<add> super.onActivityResult(requestCode, resultCode, data);
<add> if (resultCode == getActivity().RESULT_OK) {
<add> JSONObject jsonObject = new JSONObject();
<add> try {
<add> Bitmap bitmap = null;
<add> ByteArrayOutputStream stream = new ByteArrayOutputStream();
<add> if (requestCode == REQUEST_CAMERA) {
<add> Log.e("Inside REQUEST_CAMERA: ", "Handling an image");
<add> bitmap = (Bitmap) data.getExtras().get("data");
<add> } else if (requestCode == SELECT_FILE) {
<add> Uri selectedImageUri = data.getData();
<add> String[] projection = {MediaStore.MediaColumns.DATA};
<add> CursorLoader cursorLoader = new CursorLoader(getActivity(), selectedImageUri,
<add> projection, null, null, null);
<add> Cursor cursor = cursorLoader.loadInBackground();
<add> int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
<add> cursor.moveToFirst();
<add> String selectedImagePath = cursor.getString(column_index);
<add> BitmapFactory.Options options = new BitmapFactory.Options();
<add> options.inJustDecodeBounds = true;
<add> bitmap = BitmapFactory.decodeFile(selectedImagePath, options);
<add> }
<add> bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); //compress to which format you want.
<add> byte[] byte_arr = stream.toByteArray();
<add> String imageStr = HttpRequest.Base64.encodeBytes(byte_arr);
<add> jsonObject.put("image", imageStr);
<add> jsonObject.put("type", "jpeg");
<add> Callback callback = getUploadImageCallback();
<add> RestProxy proxy = RestProxy.getProxy();
<add> proxy.putCall(String.format("/profile/%s?picture=true", user.getName()), jsonObject.toString(), callback);
<add> } catch (JSONException e) {
<add> Log.e("JSONException", "Could not form correct JSON object");
<add> }
<add> }
<add> }
<add>
<add> private Callback getUploadImageCallback() {
<add> return new Callback() {
<add> @Override
<add> public void process(ResponseObject responseObject) {
<add> if (responseObject.getResponseCode() == 200) {
<add> JSONObject jsonObject = responseObject.getJsonObject();
<add> try {
<add> String profilePicURL = jsonObject.getString("profile_picture_url");
<add> Log.e("ProfilePicURl: ", profilePicURL);
<add> //int imageId = getImageId();
<add> //profilePicView.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.profile_pic_2, null));
<add> //user.setProfileImageId(imageId);
<add> } catch (JSONException e) {
<add> e.printStackTrace();
<add> }
<add> } else {
<add> Toast.makeText(getActivity().getApplicationContext(),
<add> getActivity().getResources().getString(R.string.update_user_server_error),
<add> Toast.LENGTH_LONG).show();
<add> }
<add> }
<add> };
<add> }
<add>
<add> private int getImageId() {
<add> Random r = new Random();
<add> int n;
<add> do {
<add> n = r.nextInt(Integer.MAX_VALUE);
<add> } while (getResources().getDrawable(n, null) != null);
<add> return n;
<add> }
<ide> }
|
|
JavaScript
|
mit
|
bbc7a741fc52462d57a7002b85fa59d73f339e8c
| 0 |
2do2go/node-oauth,dongguangming/node-oauth,cblair/node-oauth,adjohnson916/node-oauth,kasparaasamets/node-oauth,JoliOS/node-oauth,Phanatic/node-oauth,hallta/node-oauth,ciaranj/node-oauth,craigspaeth/node-oauth,sktguha/node-oauth,compsol-michael/nodejs-with-pfx-integration,emertechie/node-oauth,Cellarise/oauth-rest-atlassian,bhargav175/node-oauth,WatchBeam/node-oauth,waffleio/node-oauth,apiaryio/node-oauth,jsha/node-oauth,gfogle/node-oauth,matuszeman/node-oauth,d2marcelo/node-oauth,mhart/node-oauth,hoist/node-oauth,hiddentao/node-oauth
|
var sha1= require('./sha1'),
http= require('http'),
URL= require('url'),
querystring= require('querystring');
exports.OAuth= function(requestUrl, accessUrl, authorizeUrl, consumerKey, consumerSecret, version, signatureMethod) {
this._requestUrl= requestUrl;
this._accessUrl= accessUrl;
this._authorizeUrl= authorizeUrl;
this._consumerKey= consumerKey;
this._consumerSecret= this._encodeData( consumerSecret );
this._version= version;
this._signatureMethod= signatureMethod;
};
exports.OAuth.prototype._getTimestamp= function() {
return Math.floor( (new Date()).getTime() / 1000 );
}
exports.OAuth.prototype._encodeData= function(toEncode){
if( toEncode == null || toEncode == "" ) return ""
else {
var result= encodeURIComponent(toEncode);
// Fix the mismatch between OAuth's RFC2396's and Javascript's beliefs in what is right and wrong ;)
return result.replace(/\!/g, "%21")
.replace(/\'/g, "%27")
.replace(/\(/g, "%28")
.replace(/\)/g, "%29")
.replace(/\*/g, "%2A");
}
}
exports.OAuth.prototype._decodeData= function(toDecode) {
if( toDecode != null ) {
toDecode = toDecode.replace(/\+/g, " ");
}
return decodeURIComponent( toDecode);
}
exports.OAuth.prototype._getSignature= function(method, url, parameters, tokenSecret) {
var signatureBase= this._createSignatureBase(method, url, parameters);
return this._createSignature( signatureBase, tokenSecret );
}
exports.OAuth.prototype._normalizeUrl= function(url) {
var parsedUrl= URL.parse(url, true)
var port ="";
if( parsedUrl.port ) {
if( (parsedUrl.protocol == "http:" && parsedUrl.port != "80" ) ||
(parsedUrl.protocol == "https:" && parsedUrl.port != "443") ) {
port= ":" + parsedUrl.port;
}
}
return parsedUrl.protocol + "//" + parsedUrl.hostname + port + parsedUrl.pathname;
}
// Takes a literal in, then returns a sorted array
exports.OAuth.prototype._sortRequestParams= function(argumentsHash) {
var argument_pairs= [];
for(var key in argumentsHash ) {
argument_pairs[argument_pairs.length]= [key, argumentsHash[key]];
}
// Sort by name, then value.
argument_pairs.sort(function(a,b) {
if ( a[0]== b[0] ) {
return a[1] < b[1] ? -1 : 1;
}
else return a[0] < b[0] ? -1 : 1;
});
return argument_pairs;
}
exports.OAuth.prototype._normaliseRequestParams= function(arguments) {
var argument_pairs= this._sortRequestParams( arguments );
var args= "";
for(var i=0;i<argument_pairs.length;i++) {
args+= argument_pairs[i][0];
args+= "="
args+= argument_pairs[i][1];
if( i < argument_pairs.length-1 ) args+= "&";
}
return args;
}
exports.OAuth.prototype._createSignatureBase= function(method, url, parameters) {
url= this._encodeData( this._normalizeUrl(url) );
parameters= this._encodeData(parameters);
return method.toUpperCase() + "&" + url + "&" + parameters;
}
exports.OAuth.prototype._createSignature= function(signatureBase, tokenSecret) {
if( tokenSecret === undefined ) var tokenSecret= "";
else tokenSecret= this._encodeData( tokenSecret );
var key= this._consumerSecret + "&" + tokenSecret;
//TODO: whilst we support different signature methods being passed
// we currenting only do SHA1-HMAC
var hash= sha1.HMACSHA1(key, signatureBase);
signature = this._encodeData(hash);
return signature;
}
exports.OAuth.prototype.NONCE_CHARS= ['a','b','c','d','e','f','g','h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v','w','x','y','z','A','B',
'C','D','E','F','G','H','I','J','K','L','M','N','O','P',
'Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3',
'4','5','6','7','8','9'];
exports.OAuth.prototype._getNonce= function(nonceSize) {
var result = [];
var chars= this.NONCE_CHARS;
var char_pos;
var nonce_chars_length= chars.length;
for (var i = 0; i < nonceSize; i++) {
char_pos= Math.floor(Math.random() * nonce_chars_length);
result[i]= chars[char_pos];
}
return result.join('');
}
exports.OAuth.prototype.getOauthAccessToken= function(oauth_token, oauth_token_secret, callback) {
var oauthParameters= {
"oauth_timestamp": this._getTimestamp(),
"oauth_nonce": this._getNonce(32),
"oauth_version": this._version,
"oauth_signature_method": this._signatureMethod,
"oauth_consumer_key": this._consumerKey,
"oauth_token": oauth_token
};
var method= "GET";
var sig= this._getSignature( method, this._accessUrl, this._normaliseRequestParams(oauthParameters), oauth_token_secret);
var orderedParameters= this._sortRequestParams( oauthParameters );
orderedParameters[orderedParameters.length]= ["oauth_signature", sig];
var query="";
for( var i= 0 ; i < orderedParameters.length; i++) {
query+= orderedParameters[i][0]+"="+ orderedParameters[i][1] + "&";
}
query= query.substring(0, query.length-1);
var oauthProvider= http.createClient(80, 'twitter.com');
var headers= {'Host': 'twitter.com'}
var request = oauthProvider.request("GET", "/oauth/access_token"+"?"+query, headers);
var data="";
var self= this;
request.addListener('response', function (response) {
response.setEncoding('utf8');
response.addListener('data', function (chunk) {
data+=chunk;
});
response.addListener('end', function () {
if( response.statusCode != 200 ) {
callback( response.statusCode +" : " + data );
} else {
var results= querystring.parse( data );
var oauth_token= results["oauth_token"];
results["oauth_token"]= undefined;
var oauth_token_secret= results["oauth_token_secret"];
results["oauth_token_secret"]= undefined;
callback(null, oauth_token, oauth_token_secret, results );
}
});
});
request.end();
}
exports.OAuth.prototype.getOAuthRequestToken= function(callback) {
var oauthParameters= {
"oauth_timestamp": this._getTimestamp(),
"oauth_nonce": this._getNonce(32),
"oauth_version": this._version,
"oauth_signature_method": this._signatureMethod,
"oauth_consumer_key": this._consumerKey
};
var method= "POST";
var sig= this._getSignature( method, this._requestUrl, this._normaliseRequestParams(oauthParameters));
var orderedParameters= this._sortRequestParams( oauthParameters );
orderedParameters[orderedParameters.length]= ["oauth_signature", sig];
var headers= {};
// build request authorization header
var authHeader="OAuth ";
for( var i= 0 ; i < orderedParameters.length; i++) {
authHeader+= orderedParameters[i][0]+"=\""+orderedParameters[i][1] +"\",";
}
authHeader= authHeader.substring(0, authHeader.length-1);
headers["Authorization"]= authHeader;
headers["Host"] = "twitter.com"
headers["Accept"]= "*/*"
headers["Connection"]= "close"
headers["User-Agent"]= "Express authentication"
headers["Content-length"]= 0
headers["Content-Type"]= "application/x-www-form-urlencoded"
var oauthProvider= http.createClient(80, 'twitter.com');
var request = oauthProvider.request(method, "/oauth/request_token", headers);
var data="";
var self= this;
request.addListener('response', function (response) {
response.setEncoding('utf8');
response.addListener('data', function (chunk) {
data+=chunk;
});
response.addListener('end', function () {
if( response.statusCode != 200 ) {
callback( response.statusCode +" : " + data );
} else {
var results= querystring.parse(data);
var oauth_token= results["oauth_token"];
var oauth_token_secret= results["oauth_token_secret"];
delete results["oauth_token"];
delete results["oauth_token_secret"];
callback(null, oauth_token, oauth_token_secret, (self._authorizeUrl + oauth_token), results );
}
});
});
request.end();
}
|
lib/oauth.js
|
var sha1= require('./sha1'),
http= require('http'),
URL= require('url');
exports.OAuth= function(requestUrl, accessUrl, authorizeUrl, consumerKey, consumerSecret, version, signatureMethod) {
this._requestUrl= requestUrl;
this._accessUrl= accessUrl;
this._authorizeUrl= authorizeUrl;
this._consumerKey= consumerKey;
this._consumerSecret= this._encodeData( consumerSecret );
this._version= version;
this._signatureMethod= signatureMethod;
};
exports.OAuth.prototype._getTimestamp= function() {
return Math.floor( (new Date()).getTime() / 1000 );
}
exports.OAuth.prototype._encodeData= function(toEncode){
if( toEncode == null || toEncode == "" ) return ""
else {
var result= encodeURIComponent(toEncode);
// Fix the mismatch between OAuth's RFC2396's and Javascript's beliefs in what is right and wrong ;)
return result.replace(/\!/g, "%21")
.replace(/\'/g, "%27")
.replace(/\(/g, "%28")
.replace(/\)/g, "%29")
.replace(/\*/g, "%2A");
}
}
exports.OAuth.prototype._decodeData= function(toDecode) {
if( toDecode != null ) {
toDecode = toDecode.replace(/\+/g, " ");
}
return decodeURIComponent( toDecode);
}
exports.OAuth.prototype._getSignature= function(method, url, parameters, tokenSecret) {
var signatureBase= this._createSignatureBase(method, url, parameters);
return this._createSignature( signatureBase, tokenSecret );
}
exports.OAuth.prototype._normalizeUrl= function(url) {
var parsedUrl= URL.parse(url, true)
var port ="";
if( parsedUrl.port ) {
if( (parsedUrl.protocol == "http:" && parsedUrl.port != "80" ) ||
(parsedUrl.protocol == "https:" && parsedUrl.port != "443") ) {
port= ":" + parsedUrl.port;
}
}
return parsedUrl.protocol + "//" + parsedUrl.hostname + port + parsedUrl.pathname;
}
exports.OAuth.prototype._splitQueryString= function(stringToSplit) {
var result= {};
var parameters= stringToSplit.split("&");
for(var key in parameters) {
var parameterPair= parameters[key].split("=");
result[parameterPair[0]]= parameterPair[1];
}
return result;
}
// Takes a literal in, then returns a sorted array
exports.OAuth.prototype._sortRequestParams= function(argumentsHash) {
var argument_pairs= [];
for(var key in argumentsHash ) {
argument_pairs[argument_pairs.length]= [key, argumentsHash[key]];
}
// Sort by name, then value.
argument_pairs.sort(function(a,b) {
if ( a[0]== b[0] ) {
return a[1] < b[1] ? -1 : 1;
}
else return a[0] < b[0] ? -1 : 1;
});
return argument_pairs;
}
exports.OAuth.prototype._normaliseRequestParams= function(arguments) {
var argument_pairs= this._sortRequestParams( arguments );
var args= "";
for(var i=0;i<argument_pairs.length;i++) {
args+= argument_pairs[i][0];
args+= "="
args+= argument_pairs[i][1];
if( i < argument_pairs.length-1 ) args+= "&";
}
return args;
}
exports.OAuth.prototype._createSignatureBase= function(method, url, parameters) {
url= this._encodeData( this._normalizeUrl(url) );
parameters= this._encodeData(parameters);
return method.toUpperCase() + "&" + url + "&" + parameters;
}
exports.OAuth.prototype._createSignature= function(signatureBase, tokenSecret) {
if( tokenSecret === undefined ) var tokenSecret= "";
else tokenSecret= this._encodeData( tokenSecret );
var key= this._consumerSecret + "&" + tokenSecret;
//TODO: whilst we support different signature methods being passed
// we currenting only do SHA1-HMAC
var hash= sha1.HMACSHA1(key, signatureBase);
signature = this._encodeData(hash);
return signature;
}
exports.OAuth.prototype.NONCE_CHARS= ['a','b','c','d','e','f','g','h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v','w','x','y','z','A','B',
'C','D','E','F','G','H','I','J','K','L','M','N','O','P',
'Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3',
'4','5','6','7','8','9'];
exports.OAuth.prototype._getNonce= function(nonceSize) {
var result = [];
var chars= this.NONCE_CHARS;
var char_pos;
var nonce_chars_length= chars.length;
for (var i = 0; i < nonceSize; i++) {
char_pos= Math.floor(Math.random() * nonce_chars_length);
result[i]= chars[char_pos];
}
return result.join('');
}
exports.OAuth.prototype.getOauthAccessToken= function(oauth_token, oauth_token_secret, callback) {
require('sys').puts('getOauthAccessToken')
var oauthParameters= {
"oauth_timestamp": this._getTimestamp(),
"oauth_nonce": this._getNonce(32),
"oauth_version": this._version,
"oauth_signature_method": this._signatureMethod,
"oauth_consumer_key": this._consumerKey,
"oauth_token": oauth_token
};
var method= "GET";
var sig= this._getSignature( method, this._accessUrl, this._normaliseRequestParams(oauthParameters), oauth_token_secret);
var orderedParameters= this._sortRequestParams( oauthParameters );
orderedParameters[orderedParameters.length]= ["oauth_signature", sig];
var query="";
for( var i= 0 ; i < orderedParameters.length; i++) {
query+= orderedParameters[i][0]+"="+ orderedParameters[i][1] + "&";
}
query= query.substring(0, query.length-1);
var oauthProvider= http.createClient(80, 'twitter.com');
var headers= {'Host': 'twitter.com'}
var request = oauthProvider.request("GET", "/oauth/access_token"+"?"+query, headers);
var data="";
var self= this;
request.addListener('response', function (response) {
response.setEncoding('utf8');
response.addListener('data', function (chunk) {
data+=chunk;
});
response.addListener('end', function () {
if( response.statusCode != 200 ) {
callback( response.statusCode +" : " + data );
} else {
var results= self._splitQueryString(data);
var oauth_token= results["oauth_token"];
results["oauth_token"]= undefined;
var oauth_token_secret= results["oauth_token_secret"];
results["oauth_token_secret"]= undefined;
callback(null, oauth_token, oauth_token_secret, results );
}
});
});
request.end();
}
exports.OAuth.prototype.getOAuthRequestToken= function(callback) {
require('sys').puts('getOauthRequestToken')
var oauthParameters= {
"oauth_timestamp": this._getTimestamp(),
"oauth_nonce": this._getNonce(32),
"oauth_version": this._version,
"oauth_signature_method": this._signatureMethod,
"oauth_consumer_key": this._consumerKey
};
var method= "POST";
require('sys').puts(this._requestUrl)
var sig= this._getSignature( method, this._requestUrl, this._normaliseRequestParams(oauthParameters));
var orderedParameters= this._sortRequestParams( oauthParameters );
orderedParameters[orderedParameters.length]= ["oauth_signature", sig];
var headers= {};
// build request authorization header
var authHeader="OAuth ";
for( var i= 0 ; i < orderedParameters.length; i++) {
authHeader+= orderedParameters[i][0]+"=\""+orderedParameters[i][1] +"\",";
}
authHeader= authHeader.substring(0, authHeader.length-1);
headers["Authorization"]= authHeader;
headers["Host"] = "twitter.com"
headers["Accept"]= "*/*"
headers["Connection"]= "close"
headers["User-Agent"]= "Express authentication"
headers["Content-length"]= 0
headers["Content-Type"]= "application/x-www-form-urlencoded"
var oauthProvider= http.createClient(80, 'twitter.com');
var request = oauthProvider.request(method, "/oauth/request_token", headers);
var data="";
var self= this;
request.addListener('response', function (response) {
response.setEncoding('utf8');
response.addListener('data', function (chunk) {
data+=chunk;
});
response.addListener('end', function () {
if( response.statusCode != 200 ) {
callback( response.statusCode +" : " + data );
} else {
var results= self._splitQueryString(data);
var oauth_token= results["oauth_token"];
var oauth_token_secret= results["oauth_token_secret"];
delete results["oauth_token"];
delete results["oauth_token_secret"];
callback(null, oauth_token, oauth_token_secret, (self._authorizeUrl + oauth_token), results );
}
});
});
request.end();
}
|
Removed un-neccessaryy custom query parsing code
|
lib/oauth.js
|
Removed un-neccessaryy custom query parsing code
|
<ide><path>ib/oauth.js
<ide> var sha1= require('./sha1'),
<ide> http= require('http'),
<del> URL= require('url');
<add> URL= require('url'),
<add> querystring= require('querystring');
<ide>
<ide> exports.OAuth= function(requestUrl, accessUrl, authorizeUrl, consumerKey, consumerSecret, version, signatureMethod) {
<ide> this._requestUrl= requestUrl;
<ide> }
<ide> }
<ide> return parsedUrl.protocol + "//" + parsedUrl.hostname + port + parsedUrl.pathname;
<del>}
<del>
<del>exports.OAuth.prototype._splitQueryString= function(stringToSplit) {
<del> var result= {};
<del> var parameters= stringToSplit.split("&");
<del> for(var key in parameters) {
<del> var parameterPair= parameters[key].split("=");
<del> result[parameterPair[0]]= parameterPair[1];
<del> }
<del> return result;
<ide> }
<ide>
<ide> // Takes a literal in, then returns a sorted array
<ide> }
<ide>
<ide> exports.OAuth.prototype.getOauthAccessToken= function(oauth_token, oauth_token_secret, callback) {
<del> require('sys').puts('getOauthAccessToken')
<ide> var oauthParameters= {
<ide> "oauth_timestamp": this._getTimestamp(),
<ide> "oauth_nonce": this._getNonce(32),
<ide> if( response.statusCode != 200 ) {
<ide> callback( response.statusCode +" : " + data );
<ide> } else {
<del> var results= self._splitQueryString(data);
<add> var results= querystring.parse( data );
<ide> var oauth_token= results["oauth_token"];
<ide> results["oauth_token"]= undefined;
<ide> var oauth_token_secret= results["oauth_token_secret"];
<ide> request.end();
<ide> }
<ide>
<del>exports.OAuth.prototype.getOAuthRequestToken= function(callback) {
<del> require('sys').puts('getOauthRequestToken')
<del>
<add>exports.OAuth.prototype.getOAuthRequestToken= function(callback) {
<ide> var oauthParameters= {
<ide> "oauth_timestamp": this._getTimestamp(),
<ide> "oauth_nonce": this._getNonce(32),
<ide> "oauth_consumer_key": this._consumerKey
<ide> };
<ide> var method= "POST";
<del> require('sys').puts(this._requestUrl)
<ide> var sig= this._getSignature( method, this._requestUrl, this._normaliseRequestParams(oauthParameters));
<ide>
<ide>
<ide> if( response.statusCode != 200 ) {
<ide> callback( response.statusCode +" : " + data );
<ide> } else {
<del> var results= self._splitQueryString(data);
<add> var results= querystring.parse(data);
<ide>
<ide> var oauth_token= results["oauth_token"];
<ide> var oauth_token_secret= results["oauth_token_secret"];
|
|
JavaScript
|
mit
|
485963a77517223e4718b281407d1fdd5cedf455
| 0 |
verlok/lazyload
|
const LazyLoad = require('../src/lazyLoad');
test("Public methods", () => {
const ll = new LazyLoad();
['update',
'handleScroll',
'destroy'].forEach((methodName) => {
expect(typeof ll[methodName]).toBe('function');
});
});
describe("Constructor", () => {
test("...with default options", () => {
const ll = new LazyLoad();
expect(ll._settings).toEqual({
elements_selector: "img",
container: window,
threshold: 300,
throttle: 150,
data_src: "original",
data_srcset: "original-set",
class_loading: "loading",
class_loaded: "loaded",
skip_invisible: true,
callback_load: null,
callback_error: null,
callback_set: null,
callback_processed: null
});
});
test("...with custom options", () => {
const ll = new LazyLoad({
data_src: "data-src",
data_srcset: "data-srcset"
});
expect(ll._settings).toEqual({
elements_selector: "img",
container: window,
threshold: 300,
throttle: 150,
data_src: "data-src",
data_srcset: "data-srcset",
class_loading: "loading",
class_loaded: "loaded",
skip_invisible: true,
callback_load: null,
callback_error: null,
callback_set: null,
callback_processed: null
});
});
test("...of different instances", () => {
const ll1 = new LazyLoad({
elements_selector: ".lazy1 img",
data_src: "data-src",
data_srcset: "data-srcset"
});
const ll2 = new LazyLoad({
elements_selector: ".lazy2 img",
data_src: "data-src",
data_srcset: "data-srcset"
});
expect(ll1._settings.elements_selector).toBe(".lazy1 img");
expect(ll2._settings.elements_selector).toBe(".lazy2 img");
});
});
test("QueryOriginNode is valid", () => {
const scrollArea = document.createElement('div');
scrollArea.classList.add('scrollArea');
window.document.documentElement.appendChild(scrollArea);
const ll1 = new LazyLoad();
const ll2 = new LazyLoad({
container: scrollArea
});
expect(ll1._queryOriginNode.nodeType).toBe(9);
expect(ll2._queryOriginNode.nodeType).toBe(1);
});
test("Update is called at instance creation", () => {
LazyLoad.prototype.update = jest.fn();
var ll = new LazyLoad();
var ll2 = new LazyLoad();
expect(LazyLoad.prototype.update).toHaveBeenCalledTimes(2);
});
test("Scroll is managed", () => {
LazyLoad.prototype.handleScroll = jest.fn();
window.scrollTo(0, 1);
expect(LazyLoad.prototype.update).toHaveBeenCalled();
});
test("Resize is managed", () => {
LazyLoad.prototype.handleScroll = jest.fn();
window.resizeTo(800, 600);
expect(LazyLoad.prototype.update).toHaveBeenCalled();
});
describe("_mergeObjects", () => {
var mergeFunct = LazyLoad.prototype._mergeObjects;
test("...with empty objects", () => {
expect(mergeFunct({}, {})).toEqual({});
});
test("...with empty first object", () => {
expect(mergeFunct({}, {
pippo: "cane"
})).toEqual({
pippo: "cane"
});
});
test("...with empty second object", () => {
expect(mergeFunct({
pippo: "cane"
}, {})).toEqual({
pippo: "cane"
});
});
test("...with matching property", () => {
expect(mergeFunct({
pippo: "cane"
}, {
pippo: "canuto"
})).toEqual({
pippo: "canuto"
});
});
test("...with only one matching property", () => {
expect(mergeFunct({
pippo: "cane",
orazio: "cavallo"
}, {
pippo: "canuto"
})).toEqual({
pippo: "canuto",
orazio: "cavallo"
});
});
});
/*
* Can't test _isInsideViewport because the DOM implementation is not correct
* (same test on codepen returns true)
* will test using Jasmine/Sinon/Karma, maybe
*/
/*
describe("_isInsideViewport", () => {
test("...affermative - window container - position static - no threshold", () => {
const img = document.createElement('img');
img.src="http://placehold.it/1x1";
img.style="width:300px; height:300px;";
document.body.appendChild(img);
var ll = new LazyLoad();
expect(ll._isInsideViewport(img, window, 0)).toBe(true);
});
});
*/
describe("_setSourcesForPicture", () => {
let p, s1, s2, i;
let testFunct = LazyLoad.prototype._setSourcesForPicture;
let img1 = "http://placehold.it/1x1";
let img100 = "http://placehold.it/100x100";
let img200 = "http://placehold.it/200x200";
let img400 = "http://placehold.it/400x400";
let dataSrcSetPartialAttr = 'original-set';
let dataSrcSetAttr = 'data-' + dataSrcSetPartialAttr;
let srcsetAttr = 'srcset';
beforeEach(() => {
p = document.createElement('picture');
p.appendChild(s1 = document.createElement('source'));
p.appendChild(s2 = document.createElement('source'));
p.appendChild(i = document.createElement('img'));
});
test("...with initially empty srcset", () => {
s1.setAttribute(dataSrcSetAttr, img200);
s2.setAttribute(dataSrcSetAttr, img400);
testFunct(i, dataSrcSetPartialAttr);
expect(s1.getAttribute(srcsetAttr)).toBe(img200);
expect(s2.getAttribute(srcsetAttr)).toBe(img400);
});
test("...with initial value in srcset", () => {
s1.setAttribute(srcsetAttr, img1);
s2.setAttribute(srcsetAttr, img1);
s1.setAttribute(dataSrcSetAttr, img200);
s2.setAttribute(dataSrcSetAttr, img400);
testFunct(i, dataSrcSetPartialAttr);
expect(s1.getAttribute(srcsetAttr)).toBe(img200);
expect(s2.getAttribute(srcsetAttr)).toBe(img400);
});
test("...with initial value in srcset and empty data-srcset", () => {
s1.setAttribute(srcsetAttr, img1);
s2.setAttribute(srcsetAttr, img1);
s1.setAttribute(dataSrcSetAttr, "");
s2.setAttribute(dataSrcSetAttr, "");
testFunct(i, dataSrcSetPartialAttr);
expect(s1.getAttribute(srcsetAttr)).toBe(img1);
expect(s2.getAttribute(srcsetAttr)).toBe(img1);
});
});
describe("_setSources for image", () => {
let i;
let fakeInstance = {_setSourcesForPicture: jest.fn()};
let testFunct = LazyLoad.prototype._setSources.bind(fakeInstance);
let img1 = "http://placehold.it/1x1";
let img100 = "http://placehold.it/100x100";
let img200 = "http://placehold.it/200x200";
let img400 = "http://placehold.it/400x400";
let dataSrcPartialAttr = 'original';
let dataSrcSetPartialAttr = 'original-set';
let dataSrcAttr = 'data-' + dataSrcPartialAttr;
let dataSrcSetAttr = 'data-' + dataSrcSetPartialAttr;
let srcAttr = 'src';
let srcSetAttr = 'srcset';
beforeEach(() => {
i = document.createElement('img');
});
test("...with initially empty src and srcset", () => {
fakeInstance._setSourcesForPicture.mockClear();
i.setAttribute(dataSrcAttr, img200);
i.setAttribute(dataSrcSetAttr, img400);
testFunct(i, dataSrcSetPartialAttr, dataSrcPartialAttr);
expect(i.getAttribute(srcAttr)).toBe(img200);
expect(i.getAttribute(srcSetAttr)).toBe(img400);
expect(fakeInstance._setSourcesForPicture).toHaveBeenCalledTimes(1);
});
test("...with initial values in src and srcset", () => {
fakeInstance._setSourcesForPicture.mockClear();
i.setAttribute(srcAttr, img1);
i.setAttribute(srcSetAttr, img1);
i.setAttribute(dataSrcAttr, img200);
i.setAttribute(dataSrcSetAttr, img400);
testFunct(i, dataSrcSetPartialAttr, dataSrcPartialAttr);
expect(i.getAttribute(srcAttr)).toBe(img200);
expect(i.getAttribute(srcSetAttr)).toBe(img400);
expect(fakeInstance._setSourcesForPicture).toHaveBeenCalledTimes(1);
});
test("...with initial values in src and srcset and empty data-*", () => {
fakeInstance._setSourcesForPicture.mockClear();
i.setAttribute(srcAttr, img200);
i.setAttribute(srcSetAttr, img400);
i.setAttribute(dataSrcAttr, "");
i.setAttribute(dataSrcSetAttr, "");
testFunct(i, dataSrcSetPartialAttr, dataSrcPartialAttr);
expect(i.getAttribute(srcAttr)).toBe(img200);
expect(i.getAttribute(srcSetAttr)).toBe(img400);
expect(fakeInstance._setSourcesForPicture).toHaveBeenCalledTimes(1);
});
});
|
__test__/lazyload.test.js
|
const LazyLoad = require('../src/lazyLoad');
test("Public methods", () => {
const ll = new LazyLoad();
['update',
'handleScroll',
'destroy'].forEach((methodName) => {
expect(typeof ll[methodName]).toBe('function');
});
});
describe("Constructor", () => {
test("...with default options", () => {
const ll = new LazyLoad();
expect(ll._settings).toEqual({
elements_selector: "img",
container: window,
threshold: 300,
throttle: 150,
data_src: "original",
data_srcset: "original-set",
class_loading: "loading",
class_loaded: "loaded",
skip_invisible: true,
callback_load: null,
callback_error: null,
callback_set: null,
callback_processed: null
});
});
test("...with custom options", () => {
const ll = new LazyLoad({
data_src: "data-src",
data_srcset: "data-srcset"
});
expect(ll._settings).toEqual({
elements_selector: "img",
container: window,
threshold: 300,
throttle: 150,
data_src: "data-src",
data_srcset: "data-srcset",
class_loading: "loading",
class_loaded: "loaded",
skip_invisible: true,
callback_load: null,
callback_error: null,
callback_set: null,
callback_processed: null
});
});
test("...of different instances", () => {
const ll1 = new LazyLoad({
elements_selector: ".lazy1 img",
data_src: "data-src",
data_srcset: "data-srcset"
});
const ll2 = new LazyLoad({
elements_selector: ".lazy2 img",
data_src: "data-src",
data_srcset: "data-srcset"
});
expect(ll1._settings.elements_selector).toBe(".lazy1 img");
expect(ll2._settings.elements_selector).toBe(".lazy2 img");
});
});
test("QueryOriginNode is valid", () => {
const scrollArea = document.createElement('div');
scrollArea.classList.add('scrollArea');
window.document.documentElement.appendChild(scrollArea);
const ll1 = new LazyLoad();
const ll2 = new LazyLoad({
container: scrollArea
});
expect(ll1._queryOriginNode.nodeType).toBe(9);
expect(ll2._queryOriginNode.nodeType).toBe(1);
});
test("Update is called at instance creation", () => {
LazyLoad.prototype.update = jest.fn();
var ll = new LazyLoad();
var ll2 = new LazyLoad();
expect(LazyLoad.prototype.update).toHaveBeenCalledTimes(2);
});
test("Scroll is managed", () => {
LazyLoad.prototype.handleScroll = jest.fn();
window.scrollTo(0, 1);
expect(LazyLoad.prototype.update).toHaveBeenCalled();
});
test("Resize is managed", () => {
LazyLoad.prototype.handleScroll = jest.fn();
window.resizeTo(800, 600);
expect(LazyLoad.prototype.update).toHaveBeenCalled();
});
describe("_mergeObjects", () => {
var mergeFunct = LazyLoad.prototype._mergeObjects;
test("...with empty objects", () => {
expect(mergeFunct({}, {})).toEqual({});
});
test("...with empty first object", () => {
expect(mergeFunct({}, {
pippo: "cane"
})).toEqual({
pippo: "cane"
});
});
test("...with empty second object", () => {
expect(mergeFunct({
pippo: "cane"
}, {})).toEqual({
pippo: "cane"
});
});
test("...with matching property", () => {
expect(mergeFunct({
pippo: "cane"
}, {
pippo: "canuto"
})).toEqual({
pippo: "canuto"
});
});
test("...with only one matching property", () => {
expect(mergeFunct({
pippo: "cane",
orazio: "cavallo"
}, {
pippo: "canuto"
})).toEqual({
pippo: "canuto",
orazio: "cavallo"
});
});
});
/*
* Can't test _isInsideViewport because the DOM implementation is not correct
* (same test on codepen returns true)
* will test using Jasmine/Sinon/Karma, maybe
*/
/*
describe("_isInsideViewport", () => {
test("...affermative - window container - position static - no threshold", () => {
const img = document.createElement('img');
img.src="http://placehold.it/1x1";
img.style="width:300px; height:300px;";
document.body.appendChild(img);
var ll = new LazyLoad();
expect(ll._isInsideViewport(img, window, 0)).toBe(true);
});
});
*/
describe("_setSourcesForPicture", () => {
let p, s1, s2, i;
let testFunct = LazyLoad.prototype._setSourcesForPicture;
let img1 = "http://placehold.it/1x1";
let img100 = "http://placehold.it/100x100";
let img200 = "http://placehold.it/200x200";
let img400 = "http://placehold.it/400x400";
beforeEach(() => {
p = document.createElement('picture');
p.appendChild(s1 = document.createElement('source'));
p.appendChild(s2 = document.createElement('source'));
p.appendChild(i = document.createElement('img'));
});
test("...with initially empty srcset", () => {
s1.setAttribute('data-original-set', img200);
s2.setAttribute('data-original-set', img400);
testFunct(i, 'original-set');
expect(s1.getAttribute('srcset')).toBe(img200);
expect(s2.getAttribute('srcset')).toBe(img400);
});
test("...with initial value in srcset", () => {
s1.setAttribute('srcset', img1);
s2.setAttribute('srcset', img1);
s1.setAttribute('data-original-set', img200);
s2.setAttribute('data-original-set', img400);
testFunct(i, 'original-set');
expect(s1.getAttribute('srcset')).toBe(img200);
expect(s2.getAttribute('srcset')).toBe(img400);
});
test("...with initial value in srcset and empty data-srcset", () => {
s1.setAttribute('srcset', img1);
s2.setAttribute('srcset', img1);
s1.setAttribute('data-original-set', "");
s2.setAttribute('data-original-set', "");
testFunct(i, 'original-set');
expect(s1.getAttribute('srcset')).toBe(img1);
expect(s2.getAttribute('srcset')).toBe(img1);
});
});
|
Tested setSources for image
|
__test__/lazyload.test.js
|
Tested setSources for image
|
<ide><path>_test__/lazyload.test.js
<ide> let img100 = "http://placehold.it/100x100";
<ide> let img200 = "http://placehold.it/200x200";
<ide> let img400 = "http://placehold.it/400x400";
<add> let dataSrcSetPartialAttr = 'original-set';
<add> let dataSrcSetAttr = 'data-' + dataSrcSetPartialAttr;
<add> let srcsetAttr = 'srcset';
<ide> beforeEach(() => {
<ide> p = document.createElement('picture');
<ide> p.appendChild(s1 = document.createElement('source'));
<ide> p.appendChild(i = document.createElement('img'));
<ide> });
<ide> test("...with initially empty srcset", () => {
<del> s1.setAttribute('data-original-set', img200);
<del> s2.setAttribute('data-original-set', img400);
<del> testFunct(i, 'original-set');
<del> expect(s1.getAttribute('srcset')).toBe(img200);
<del> expect(s2.getAttribute('srcset')).toBe(img400);
<add> s1.setAttribute(dataSrcSetAttr, img200);
<add> s2.setAttribute(dataSrcSetAttr, img400);
<add> testFunct(i, dataSrcSetPartialAttr);
<add> expect(s1.getAttribute(srcsetAttr)).toBe(img200);
<add> expect(s2.getAttribute(srcsetAttr)).toBe(img400);
<ide> });
<ide> test("...with initial value in srcset", () => {
<del> s1.setAttribute('srcset', img1);
<del> s2.setAttribute('srcset', img1);
<del> s1.setAttribute('data-original-set', img200);
<del> s2.setAttribute('data-original-set', img400);
<del> testFunct(i, 'original-set');
<del> expect(s1.getAttribute('srcset')).toBe(img200);
<del> expect(s2.getAttribute('srcset')).toBe(img400);
<add> s1.setAttribute(srcsetAttr, img1);
<add> s2.setAttribute(srcsetAttr, img1);
<add> s1.setAttribute(dataSrcSetAttr, img200);
<add> s2.setAttribute(dataSrcSetAttr, img400);
<add> testFunct(i, dataSrcSetPartialAttr);
<add> expect(s1.getAttribute(srcsetAttr)).toBe(img200);
<add> expect(s2.getAttribute(srcsetAttr)).toBe(img400);
<ide> });
<ide> test("...with initial value in srcset and empty data-srcset", () => {
<del> s1.setAttribute('srcset', img1);
<del> s2.setAttribute('srcset', img1);
<del> s1.setAttribute('data-original-set', "");
<del> s2.setAttribute('data-original-set', "");
<del> testFunct(i, 'original-set');
<del> expect(s1.getAttribute('srcset')).toBe(img1);
<del> expect(s2.getAttribute('srcset')).toBe(img1);
<del> });
<del>});
<add> s1.setAttribute(srcsetAttr, img1);
<add> s2.setAttribute(srcsetAttr, img1);
<add> s1.setAttribute(dataSrcSetAttr, "");
<add> s2.setAttribute(dataSrcSetAttr, "");
<add> testFunct(i, dataSrcSetPartialAttr);
<add> expect(s1.getAttribute(srcsetAttr)).toBe(img1);
<add> expect(s2.getAttribute(srcsetAttr)).toBe(img1);
<add> });
<add>});
<add>
<add>describe("_setSources for image", () => {
<add> let i;
<add> let fakeInstance = {_setSourcesForPicture: jest.fn()};
<add> let testFunct = LazyLoad.prototype._setSources.bind(fakeInstance);
<add> let img1 = "http://placehold.it/1x1";
<add> let img100 = "http://placehold.it/100x100";
<add> let img200 = "http://placehold.it/200x200";
<add> let img400 = "http://placehold.it/400x400";
<add> let dataSrcPartialAttr = 'original';
<add> let dataSrcSetPartialAttr = 'original-set';
<add> let dataSrcAttr = 'data-' + dataSrcPartialAttr;
<add> let dataSrcSetAttr = 'data-' + dataSrcSetPartialAttr;
<add> let srcAttr = 'src';
<add> let srcSetAttr = 'srcset';
<add> beforeEach(() => {
<add> i = document.createElement('img');
<add> });
<add> test("...with initially empty src and srcset", () => {
<add> fakeInstance._setSourcesForPicture.mockClear();
<add> i.setAttribute(dataSrcAttr, img200);
<add> i.setAttribute(dataSrcSetAttr, img400);
<add> testFunct(i, dataSrcSetPartialAttr, dataSrcPartialAttr);
<add> expect(i.getAttribute(srcAttr)).toBe(img200);
<add> expect(i.getAttribute(srcSetAttr)).toBe(img400);
<add> expect(fakeInstance._setSourcesForPicture).toHaveBeenCalledTimes(1);
<add> });
<add> test("...with initial values in src and srcset", () => {
<add> fakeInstance._setSourcesForPicture.mockClear();
<add> i.setAttribute(srcAttr, img1);
<add> i.setAttribute(srcSetAttr, img1);
<add> i.setAttribute(dataSrcAttr, img200);
<add> i.setAttribute(dataSrcSetAttr, img400);
<add> testFunct(i, dataSrcSetPartialAttr, dataSrcPartialAttr);
<add> expect(i.getAttribute(srcAttr)).toBe(img200);
<add> expect(i.getAttribute(srcSetAttr)).toBe(img400);
<add> expect(fakeInstance._setSourcesForPicture).toHaveBeenCalledTimes(1);
<add> });
<add> test("...with initial values in src and srcset and empty data-*", () => {
<add> fakeInstance._setSourcesForPicture.mockClear();
<add> i.setAttribute(srcAttr, img200);
<add> i.setAttribute(srcSetAttr, img400);
<add> i.setAttribute(dataSrcAttr, "");
<add> i.setAttribute(dataSrcSetAttr, "");
<add> testFunct(i, dataSrcSetPartialAttr, dataSrcPartialAttr);
<add> expect(i.getAttribute(srcAttr)).toBe(img200);
<add> expect(i.getAttribute(srcSetAttr)).toBe(img400);
<add> expect(fakeInstance._setSourcesForPicture).toHaveBeenCalledTimes(1);
<add> });
<add>});
<add>
|
|
Java
|
mit
|
cfc08a98c94e96bb7b137c95b05d962a118d6364
| 0 |
jacob-keller/credentials-plugin,jenkinsci/credentials-plugin,stephenc/credentials-plugin,roccivic/credentials-plugin,roccivic/credentials-plugin,jenkinsci/credentials-plugin,roccivic/credentials-plugin,roccivic/credentials-plugin,jenkinsci/credentials-plugin,jacob-keller/credentials-plugin,jacob-keller/credentials-plugin,stephenc/credentials-plugin,stephenc/credentials-plugin,stephenc/credentials-plugin,MarkEWaite/credentials-plugin,MarkEWaite/credentials-plugin,jacob-keller/credentials-plugin,MarkEWaite/credentials-plugin
|
/*
* The MIT License
*
* Copyright (c) 2011-2012, CloudBees, Inc., Stephen Connolly.
*
* 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.cloudbees.plugins.credentials;
import com.cloudbees.plugins.credentials.matchers.AllOfMatcher;
import com.cloudbees.plugins.credentials.matchers.AnyOfMatcher;
import com.cloudbees.plugins.credentials.matchers.ConstantMatcher;
import com.cloudbees.plugins.credentials.matchers.IdMatcher;
import com.cloudbees.plugins.credentials.matchers.InstanceOfMatcher;
import com.cloudbees.plugins.credentials.matchers.NotMatcher;
import com.cloudbees.plugins.credentials.matchers.ScopeMatcher;
import com.cloudbees.plugins.credentials.matchers.UsernameMatcher;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Some standard matchers and filtering utility methods.
*
* @since 1.5
*/
public class CredentialsMatchers {
/**
* Utility class.
*/
private CredentialsMatchers() {
throw new UnsupportedOperationException("Utility class");
}
/**
* Creates a matcher that always matches.
*
* @return a matcher that always matches.
*/
@NonNull
public static CredentialsMatcher always() {
return new ConstantMatcher(true);
}
/**
* Creates a matcher that never matches.
*
* @return a matcher that never matches.
*/
@NonNull
public static CredentialsMatcher never() {
return new ConstantMatcher(false);
}
/**
* Creates a matcher that inverts the supplied matcher.
*
* @param matcher matcher to invert.
* @return a matcher that is the opposite of the supplied matcher.
*/
@NonNull
public static CredentialsMatcher not(@NonNull CredentialsMatcher matcher) {
return new NotMatcher(matcher);
}
/**
* Creates a matcher that matches credentials of the specified type.
*
* @param clazz the type of credential to match.
* @return a matcher that matches credentials of the specified type.
*/
@NonNull
public static CredentialsMatcher instanceOf(@NonNull Class clazz) {
return new InstanceOfMatcher(clazz);
}
/**
* Creates a matcher that matches {@link com.cloudbees.plugins.credentials.common.IdCredentials} with the
* supplied {@link com.cloudbees.plugins.credentials.common.IdCredentials#getId()}
*
* @param id the {@link com.cloudbees.plugins.credentials.common.IdCredentials#getId()} to match.
* @return a matcher that matches {@link com.cloudbees.plugins.credentials.common.IdCredentials} with the
* supplied {@link com.cloudbees.plugins.credentials.common.IdCredentials#getId()}
*/
@NonNull
public static CredentialsMatcher withId(@NonNull String id) {
return new IdMatcher(id);
}
/**
* Creates a matcher that matches {@link Credentials} with the supplied {@link CredentialsScope}.
*
* @param scope the {@link CredentialsScope} to match.
* @return a matcher that matches {@link Credentials} with the supplied {@link CredentialsScope}.
*/
@NonNull
public static CredentialsMatcher withScope(@NonNull CredentialsScope scope) {
return new ScopeMatcher(scope);
}
/**
* Creates a matcher that matches {@link Credentials} with the supplied {@link CredentialsScope}.
*
* @param scopes the {@link CredentialsScope}s to match.
* @return a matcher that matches {@link Credentials} with the supplied {@link CredentialsScope}s.
*/
@NonNull
public static CredentialsMatcher withScopes(@NonNull CredentialsScope... scopes) {
return new ScopeMatcher(scopes);
}
/**
* Creates a matcher that matches {@link Credentials} with the supplied {@link CredentialsScope}.
*
* @param scopes the {@link CredentialsScope}s to match.
* @return a matcher that matches {@link Credentials} with the supplied {@link CredentialsScope}s.
*/
@NonNull
public static CredentialsMatcher withScopes(@NonNull Collection<CredentialsScope> scopes) {
return new ScopeMatcher(scopes);
}
/**
* Creates a matcher that matches {@link com.cloudbees.plugins.credentials.common.UsernameCredentials} with the
* supplied {@link com.cloudbees.plugins.credentials.common.UsernameCredentials#getUsername()}
*
* @param username the {@link com.cloudbees.plugins.credentials.common.UsernameCredentials#getUsername()} to match.
* @return a matcher that matches {@link com.cloudbees.plugins.credentials.common.UsernameCredentials} with the
* supplied {@link com.cloudbees.plugins.credentials.common.UsernameCredentials#getUsername()}
*/
@NonNull
public static CredentialsMatcher withUsername(@NonNull String username) {
return new UsernameMatcher(username);
}
/**
* Creates a matcher that matches when all of the supplied matchers match.
*
* @param matchers the matchers to match.
* @return a matcher that matches when all of the supplied matchers match.
*/
@NonNull
public static CredentialsMatcher allOf(@NonNull CredentialsMatcher... matchers) {
return new AllOfMatcher(Arrays.asList(matchers));
}
/**
* Creates a matcher that matches when any of the supplied matchers match.
*
* @param matchers the matchers to match.
* @return a matcher that matches when any of the supplied matchers match.
*/
@NonNull
public static CredentialsMatcher anyOf(@NonNull CredentialsMatcher... matchers) {
return new AnyOfMatcher(Arrays.asList(matchers));
}
/**
* Creates a matcher that matches when both of the supplied matchers match.
*
* @param matcher1 the first matcher to match.
* @param matcher2 the second matcher to match.
* @return a matcher that matches when both of the supplied matchers match.
*/
@NonNull
public static CredentialsMatcher both(@NonNull CredentialsMatcher matcher1, @NonNull CredentialsMatcher matcher2) {
return new AllOfMatcher(Arrays.asList(matcher1, matcher2));
}
/**
* Creates a matcher that matches when either of the supplied matchers match.
*
* @param matcher1 the first matcher to match.
* @param matcher2 the second matcher to match.
* @return a matcher that matches when either of the supplied matchers match.
*/
@NonNull
public static CredentialsMatcher either(@NonNull CredentialsMatcher matcher1,
@NonNull CredentialsMatcher matcher2) {
return new AnyOfMatcher(Arrays.asList(matcher1, matcher2));
}
/**
* Creates a matcher that matches when none of the supplied matchers match.
*
* @param matchers the matchers to match.
* @return a matcher that matches when none of the supplied matchers match.
*/
@NonNull
public static CredentialsMatcher noneOf(@NonNull CredentialsMatcher... matchers) {
return not(anyOf(matchers));
}
/**
* Filters credentials using the supplied matcher.
*
* @param credentials the credentials to filter.
* @param matcher the matcher to match on.
* @param <C> the type of credentials.
* @return only those credentials that match the supplied matcher.
*/
@NonNull
public static <C extends Credentials> Collection<C> filter(@NonNull Collection<C> credentials,
@NonNull CredentialsMatcher matcher) {
Collection<C> result = credentials instanceof Set ? new LinkedHashSet<C>() : new ArrayList<C>();
for (C credential : credentials) {
if (credential != null && matcher.matches(credential)) {
result.add(credential);
}
}
return result;
}
/**
* Filters credentials using the supplied matcher.
*
* @param credentials the credentials to filter.
* @param matcher the matcher to match on.
* @param <C> the type of credentials.
* @return only those credentials that match the supplied matcher.
*/
@NonNull
public static <C extends Credentials> Set<C> filter(@NonNull Set<C> credentials,
@NonNull CredentialsMatcher matcher) {
Set<C> result = new LinkedHashSet<C>();
for (C credential : credentials) {
if (credential != null && matcher.matches(credential)) {
result.add(credential);
}
}
return result;
}
/**
* Filters credentials using the supplied matcher.
*
* @param credentials the credentials to filter.
* @param matcher the matcher to match on.
* @param <C> the type of credentials.
* @return only those credentials that match the supplied matcher.
*/
@NonNull
public static <C extends Credentials> List<C> filter(@NonNull List<C> credentials,
@NonNull CredentialsMatcher matcher) {
List<C> result = new ArrayList<C>();
for (C credential : credentials) {
if (credential != null && matcher.matches(credential)) {
result.add(credential);
}
}
return result;
}
/**
* Filters credentials using the supplied matcher.
*
* @param credentials the credentials to filter.
* @param matcher the matcher to match on.
* @param <C> the type of credentials.
* @return only those credentials that match the supplied matcher.
*/
@NonNull
public static <C extends Credentials> Iterable<C> filter(@NonNull Iterable<C> credentials,
@NonNull CredentialsMatcher matcher) {
List<C> result = new ArrayList<C>();
for (C credential : credentials) {
if (credential != null && matcher.matches(credential)) {
result.add(credential);
}
}
return result;
}
/**
* Filters a map keyed by credentials using the supplied matcher.
*
* @param credentialMap the map keyed by credentials to filter.
* @param matcher the matcher to match on.
* @param <C> the type of credentials.
* @param <V> the type of the map values.
* @return only those entries with keys that that match the supplied matcher.
*/
@NonNull
public static <C extends Credentials, V> Map<C, V> filterKeys(@NonNull Map<C, V> credentialMap,
@NonNull CredentialsMatcher matcher) {
Map<C, V> result = new LinkedHashMap<C, V>();
for (Map.Entry<C, V> credential : credentialMap.entrySet()) {
if (credential.getKey() != null && matcher.matches(credential.getKey())) {
result.put(credential.getKey(), credential.getValue());
}
}
return result;
}
/**
* Filters a map based on credential values using the supplied matcher.
*
* @param credentialMap the map with credentials values to filter.
* @param matcher the matcher to match on.
* @param <K> the type of the map keys.
* @param <C> the type of credentials.
* @return only those entries with keys that that match the supplied matcher.
*/
@NonNull
public static <C extends Credentials, K> Map<K, C> filterValues(@NonNull Map<K, C> credentialMap,
@NonNull CredentialsMatcher matcher) {
Map<K, C> result = new LinkedHashMap<K, C>();
for (Map.Entry<K, C> credential : credentialMap.entrySet()) {
if (credential.getValue() != null && matcher.matches(credential.getValue())) {
result.put(credential.getKey(), credential.getValue());
}
}
return result;
}
/**
* Returns the first credential from a collection that matches the supplied matcher or if none match then the
* specified default.
*
* @param credentials the credentials to select from.
* @param matcher the matcher.
* @param defaultIfNone the default value if no match found.
* @param <C> the type of credential.
* @return a matching credential or the supplied default.
*/
@CheckForNull
public static <C extends Credentials> C firstOrDefault(@NonNull Iterable<C> credentials,
@NonNull CredentialsMatcher matcher,
@CheckForNull C defaultIfNone) {
for (C c : credentials) {
if (matcher.matches(c)) {
return c;
}
}
return defaultIfNone;
}
/**
* Returns the first credential from a collection that matches the supplied matcher or {@code null} if none match.
*
* @param credentials the credentials to select from.
* @param matcher the matcher.
* @param <C> the type of credential.
* @return a matching credential or the supplied default.
*/
@CheckForNull
public static <C extends Credentials> C firstOrNull(@NonNull Iterable<C> credentials,
@NonNull CredentialsMatcher matcher) {
return firstOrDefault(credentials, matcher, null);
}
}
|
src/main/java/com/cloudbees/plugins/credentials/CredentialsMatchers.java
|
/*
* The MIT License
*
* Copyright (c) 2011-2012, CloudBees, Inc., Stephen Connolly.
*
* 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.cloudbees.plugins.credentials;
import com.cloudbees.plugins.credentials.matchers.AllOfMatcher;
import com.cloudbees.plugins.credentials.matchers.AnyOfMatcher;
import com.cloudbees.plugins.credentials.matchers.ConstantMatcher;
import com.cloudbees.plugins.credentials.matchers.IdMatcher;
import com.cloudbees.plugins.credentials.matchers.InstanceOfMatcher;
import com.cloudbees.plugins.credentials.matchers.NotMatcher;
import com.cloudbees.plugins.credentials.matchers.ScopeMatcher;
import com.cloudbees.plugins.credentials.matchers.UsernameMatcher;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Some standard matchers and filtering utility methods.
*
* @since 1.5
*/
public class CredentialsMatchers {
/**
* Utility class.
*/
private CredentialsMatchers() {
throw new UnsupportedOperationException("Utility class");
}
/**
* Creates a matcher that always matches.
*
* @return a matcher that always matches.
*/
@NonNull
public static CredentialsMatcher always() {
return new ConstantMatcher(true);
}
/**
* Creates a matcher that never matches.
*
* @return a matcher that never matches.
*/
@NonNull
public static CredentialsMatcher never() {
return new ConstantMatcher(false);
}
/**
* Creates a matcher that inverts the supplied matcher.
*
* @param matcher matcher to invert.
* @return a matcher that is the opposite of the supplied matcher.
*/
@NonNull
public static CredentialsMatcher not(@NonNull CredentialsMatcher matcher) {
return new NotMatcher(matcher);
}
/**
* Creates a matcher that matches credentials of the specified type.
*
* @param clazz the type of credential to match.
* @return a matcher that matches credentials of the specified type.
*/
@NonNull
public static CredentialsMatcher instanceOf(@NonNull Class clazz) {
return new InstanceOfMatcher(clazz);
}
/**
* Creates a matcher that matches {@link com.cloudbees.plugins.credentials.common.IdCredentials} with the
* supplied {@link com.cloudbees.plugins.credentials.common.IdCredentials#getId()}
*
* @param id the {@link com.cloudbees.plugins.credentials.common.IdCredentials#getId()} to match.
* @return a matcher that matches {@link com.cloudbees.plugins.credentials.common.IdCredentials} with the
* supplied {@link com.cloudbees.plugins.credentials.common.IdCredentials#getId()}
*/
@NonNull
public static CredentialsMatcher withId(@NonNull String id) {
return new IdMatcher(id);
}
/**
* Creates a matcher that matches {@link Credentials} with the supplied {@link CredentialsScope}.
*
* @param scope the {@link CredentialsScope} to match.
* @return a matcher that matches {@link Credentials} with the supplied {@link CredentialsScope}.
*/
@NonNull
public static CredentialsMatcher withScope(@NonNull CredentialsScope scope) {
return new ScopeMatcher(scope);
}
/**
* Creates a matcher that matches {@link Credentials} with the supplied {@link CredentialsScope}.
*
* @param scopes the {@link CredentialsScope}s to match.
* @return a matcher that matches {@link Credentials} with the supplied {@link CredentialsScope}s.
*/
@NonNull
public static CredentialsMatcher withScopes(@NonNull CredentialsScope... scopes) {
return new ScopeMatcher(scopes);
}
/**
* Creates a matcher that matches {@link Credentials} with the supplied {@link CredentialsScope}.
*
* @param scopes the {@link CredentialsScope}s to match.
* @return a matcher that matches {@link Credentials} with the supplied {@link CredentialsScope}s.
*/
@NonNull
public static CredentialsMatcher withScopes(@NonNull Collection<CredentialsScope> scopes) {
return new ScopeMatcher(scopes);
}
/**
* Creates a matcher that matches {@link com.cloudbees.plugins.credentials.common.UsernameCredentials} with the
* supplied {@link com.cloudbees.plugins.credentials.common.UsernameCredentials#getUsername()}
*
* @param username the {@link com.cloudbees.plugins.credentials.common.UsernameCredentials#getUsername()} to match.
* @return a matcher that matches {@link com.cloudbees.plugins.credentials.common.UsernameCredentials} with the
* supplied {@link com.cloudbees.plugins.credentials.common.UsernameCredentials#getUsername()}
*/
@NonNull
public static CredentialsMatcher withUsername(@NonNull String username) {
return new UsernameMatcher(username);
}
/**
* Creates a matcher that matches when all of the supplied matchers match.
*
* @param matchers the matchers to match.
* @return a matcher that matches when all of the supplied matchers match.
*/
@NonNull
public static CredentialsMatcher allOf(@NonNull CredentialsMatcher... matchers) {
return new AllOfMatcher(Arrays.asList(matchers));
}
/**
* Creates a matcher that matches when any of the supplied matchers match.
*
* @param matchers the matchers to match.
* @return a matcher that matches when any of the supplied matchers match.
*/
@NonNull
public static CredentialsMatcher anyOf(@NonNull CredentialsMatcher... matchers) {
return new AnyOfMatcher(Arrays.asList(matchers));
}
/**
* Creates a matcher that matches when both of the supplied matchers match.
*
* @param matcher1 the first matcher to match.
* @param matcher2 the second matcher to match.
* @return a matcher that matches when both of the supplied matchers match.
*/
@NonNull
public static CredentialsMatcher both(@NonNull CredentialsMatcher matcher1, @NonNull CredentialsMatcher matcher2) {
return new AllOfMatcher(Arrays.asList(matcher1, matcher2));
}
/**
* Creates a matcher that matches when either of the supplied matchers match.
*
* @param matcher1 the first matcher to match.
* @param matcher2 the second matcher to match.
* @return a matcher that matches when either of the supplied matchers match.
*/
@NonNull
public static CredentialsMatcher either(@NonNull CredentialsMatcher matcher1,
@NonNull CredentialsMatcher matcher2) {
return new AnyOfMatcher(Arrays.asList(matcher1, matcher2));
}
/**
* Creates a matcher that matches when none of the supplied matchers match.
*
* @param matchers the matchers to match.
* @return a matcher that matches when none of the supplied matchers match.
*/
@NonNull
public static CredentialsMatcher noneOf(@NonNull CredentialsMatcher... matchers) {
return not(anyOf(matchers));
}
/**
* Filters credentials using the supplied matcher.
*
* @param credentials the credentials to filter.
* @param matcher the matcher to match on.
* @param <C> the type of credentials.
* @return only those credentials that match the supplied matcher.
*/
@NonNull
public static <C extends Credentials> Collection<C> filter(@NonNull Collection<C> credentials,
@NonNull CredentialsMatcher matcher) {
Collection<C> result = credentials instanceof Set ? new LinkedHashSet<C>() : new ArrayList<C>();
for (C credential : credentials) {
if (credential != null && matcher.matches(credential)) {
result.add(credential);
}
}
return result;
}
/**
* Filters credentials using the supplied matcher.
*
* @param credentials the credentials to filter.
* @param matcher the matcher to match on.
* @param <C> the type of credentials.
* @return only those credentials that match the supplied matcher.
*/
@NonNull
public static <C extends Credentials> Set<C> filter(@NonNull Set<C> credentials,
@NonNull CredentialsMatcher matcher) {
Set<C> result = new LinkedHashSet<C>();
for (C credential : credentials) {
if (credential != null && matcher.matches(credential)) {
result.add(credential);
}
}
return result;
}
/**
* Filters credentials using the supplied matcher.
*
* @param credentials the credentials to filter.
* @param matcher the matcher to match on.
* @param <C> the type of credentials.
* @return only those credentials that match the supplied matcher.
*/
@NonNull
public static <C extends Credentials> List<C> filter(@NonNull List<C> credentials,
@NonNull CredentialsMatcher matcher) {
List<C> result = new ArrayList<C>();
for (C credential : credentials) {
if (credential != null && matcher.matches(credential)) {
result.add(credential);
}
}
return result;
}
/**
* Filters credentials using the supplied matcher.
*
* @param credentials the credentials to filter.
* @param matcher the matcher to match on.
* @param <C> the type of credentials.
* @return only those credentials that match the supplied matcher.
*/
@NonNull
public static <C extends Credentials> Iterable<C> filter(@NonNull Iterable<C> credentials,
@NonNull CredentialsMatcher matcher) {
List<C> result = new ArrayList<C>();
for (C credential : credentials) {
if (credential != null && matcher.matches(credential)) {
result.add(credential);
}
}
return result;
}
/**
* Filters a map keyed by credentials using the supplied matcher.
*
* @param credentialMap the map keyed by credentials to filter.
* @param matcher the matcher to match on.
* @param <C> the type of credentials.
* @param <V> the type of the map values.
* @return only those entries with keys that that match the supplied matcher.
*/
@NonNull
public static <C extends Credentials, V> Map<C, V> filterKeys(@NonNull Map<C, V> credentialMap,
@NonNull CredentialsMatcher matcher) {
Map<C, V> result = new LinkedHashMap<C, V>();
for (Map.Entry<C, V> credential : credentialMap.entrySet()) {
if (credential.getKey() != null && matcher.matches(credential.getKey())) {
result.put(credential.getKey(), credential.getValue());
}
}
return result;
}
/**
* Filters a map based on credential values using the supplied matcher.
*
* @param credentialMap the map with credentials values to filter.
* @param matcher the matcher to match on.
* @param <K> the type of the map keys.
* @param <C> the type of credentials.
* @return only those entries with keys that that match the supplied matcher.
*/
@NonNull
public static <C extends Credentials, K> Map<K, C> filterValues(@NonNull Map<K, C> credentialMap,
@NonNull CredentialsMatcher matcher) {
Map<K, C> result = new LinkedHashMap<K, C>();
for (Map.Entry<K, C> credential : credentialMap.entrySet()) {
if (credential.getValue() != null && matcher.matches(credential.getValue())) {
result.put(credential.getKey(), credential.getValue());
}
}
return result;
}
/**
* Returns the first credential from a collection that matches the supplied matcher or if none match then the
* specified default.
*
* @param credentials the credentials to select from.
* @param matcher the matcher.
* @param defaultIfNone the default value if no match found.
* @param <C> the type of credential.
* @return a matching credential or the supplied default.
*/
@CheckForNull
public static <C extends Credentials> C firstOrDefault(@NonNull Iterable<C> credentials,
@NonNull CredentialsMatcher matcher,
@CheckForNull C defaultIfNone) {
for (C c : credentials) {
if (matcher.matches(c)) {
return c;
}
}
return defaultIfNone;
}
}
|
Another utility method
|
src/main/java/com/cloudbees/plugins/credentials/CredentialsMatchers.java
|
Another utility method
|
<ide><path>rc/main/java/com/cloudbees/plugins/credentials/CredentialsMatchers.java
<ide> }
<ide> return defaultIfNone;
<ide> }
<add>
<add> /**
<add> * Returns the first credential from a collection that matches the supplied matcher or {@code null} if none match.
<add> *
<add> * @param credentials the credentials to select from.
<add> * @param matcher the matcher.
<add> * @param <C> the type of credential.
<add> * @return a matching credential or the supplied default.
<add> */
<add> @CheckForNull
<add> public static <C extends Credentials> C firstOrNull(@NonNull Iterable<C> credentials,
<add> @NonNull CredentialsMatcher matcher) {
<add> return firstOrDefault(credentials, matcher, null);
<add> }
<ide> }
|
|
JavaScript
|
mit
|
21a1a93c3bd4dde2d844f245df5569bd8c2cf0bf
| 0 |
plotly/plotly.js,plotly/plotly.js,plotly/plotly.js,plotly/plotly.js
|
'use strict';
var d3 = require('@plotly/d3');
var isNumeric = require('fast-isnumeric');
var tinycolor = require('tinycolor2');
var Lib = require('../../lib');
var strTranslate = Lib.strTranslate;
var strRotate = Lib.strRotate;
var Events = require('../../lib/events');
var svgTextUtils = require('../../lib/svg_text_utils');
var overrideCursor = require('../../lib/override_cursor');
var Drawing = require('../drawing');
var Color = require('../color');
var dragElement = require('../dragelement');
var Axes = require('../../plots/cartesian/axes');
var Registry = require('../../registry');
var helpers = require('./helpers');
var constants = require('./constants');
var legendSupplyDefaults = require('../legend/defaults');
var legendDraw = require('../legend/draw');
// hover labels for multiple horizontal bars get tilted by some angle,
// then need to be offset differently if they overlap
var YANGLE = constants.YANGLE;
var YA_RADIANS = Math.PI * YANGLE / 180;
// expansion of projected height
var YFACTOR = 1 / Math.sin(YA_RADIANS);
// to make the appropriate post-rotation x offset,
// you need both x and y offsets
var YSHIFTX = Math.cos(YA_RADIANS);
var YSHIFTY = Math.sin(YA_RADIANS);
// size and display constants for hover text
var HOVERARROWSIZE = constants.HOVERARROWSIZE;
var HOVERTEXTPAD = constants.HOVERTEXTPAD;
var multipleHoverPoints = {
box: true,
ohlc: true,
violin: true,
candlestick: true
};
// fx.hover: highlight data on hover
// evt can be a mousemove event, or an object with data about what points
// to hover on
// {xpx,ypx[,hovermode]} - pixel locations from top left
// (with optional overriding hovermode)
// {xval,yval[,hovermode]} - data values
// [{curveNumber,(pointNumber|xval and/or yval)}] -
// array of specific points to highlight
// pointNumber is a single integer if gd.data[curveNumber] is 1D,
// or a two-element array if it's 2D
// xval and yval are data values,
// 1D data may specify either or both,
// 2D data must specify both
// subplot is an id string (default "xy")
// makes use of gl.hovermode, which can be:
// x (find the points with the closest x values, ie a column),
// closest (find the single closest point)
// internally there are two more that occasionally get used:
// y (pick out a row - only used for multiple horizontal bar charts)
// array (used when the user specifies an explicit
// array of points to hover on)
//
// We wrap the hovers in a timer, to limit their frequency.
// The actual rendering is done by private function _hover.
exports.hover = function hover(gd, evt, subplot, noHoverEvent) {
gd = Lib.getGraphDiv(gd);
Lib.throttle(
gd._fullLayout._uid + constants.HOVERID,
constants.HOVERMINTIME,
function() { _hover(gd, evt, subplot, noHoverEvent); }
);
};
/*
* Draw a single hover item or an array of hover item in a pre-existing svg container somewhere
* hoverItem should have keys:
* - x and y (or x0, x1, y0, and y1):
* the pixel position to mark, relative to opts.container
* - xLabel, yLabel, zLabel, text, and name:
* info to go in the label
* - color:
* the background color for the label.
* - idealAlign (optional):
* 'left' or 'right' for which side of the x/y box to try to put this on first
* - borderColor (optional):
* color for the border, defaults to strongest contrast with color
* - fontFamily (optional):
* string, the font for this label, defaults to constants.HOVERFONT
* - fontSize (optional):
* the label font size, defaults to constants.HOVERFONTSIZE
* - fontColor (optional):
* defaults to borderColor
* opts should have keys:
* - bgColor:
* the background color this is against, used if the trace is
* non-opaque, and for the name, which goes outside the box
* - container:
* a <svg> or <g> element to add the hover label to
* - outerContainer:
* normally a parent of `container`, sets the bounding box to use to
* constrain the hover label and determine whether to show it on the left or right
* opts can have optional keys:
* - anchorIndex:
the index of the hover item used as an anchor for positioning.
The other hover items will be pushed up or down to prevent overlap.
*/
exports.loneHover = function loneHover(hoverItems, opts) {
var multiHover = true;
if(!Array.isArray(hoverItems)) {
multiHover = false;
hoverItems = [hoverItems];
}
var pointsData = hoverItems.map(function(hoverItem) {
return {
color: hoverItem.color || Color.defaultLine,
x0: hoverItem.x0 || hoverItem.x || 0,
x1: hoverItem.x1 || hoverItem.x || 0,
y0: hoverItem.y0 || hoverItem.y || 0,
y1: hoverItem.y1 || hoverItem.y || 0,
xLabel: hoverItem.xLabel,
yLabel: hoverItem.yLabel,
zLabel: hoverItem.zLabel,
text: hoverItem.text,
name: hoverItem.name,
idealAlign: hoverItem.idealAlign,
// optional extra bits of styling
borderColor: hoverItem.borderColor,
fontFamily: hoverItem.fontFamily,
fontSize: hoverItem.fontSize,
fontColor: hoverItem.fontColor,
nameLength: hoverItem.nameLength,
textAlign: hoverItem.textAlign,
// filler to make createHoverText happy
trace: hoverItem.trace || {
index: 0,
hoverinfo: ''
},
xa: {_offset: 0},
ya: {_offset: 0},
index: 0,
hovertemplate: hoverItem.hovertemplate || false,
eventData: hoverItem.eventData || false,
hovertemplateLabels: hoverItem.hovertemplateLabels || false,
};
});
var container3 = d3.select(opts.container);
var outerContainer3 = opts.outerContainer ? d3.select(opts.outerContainer) : container3;
var fullOpts = {
hovermode: 'closest',
rotateLabels: false,
bgColor: opts.bgColor || Color.background,
container: container3,
outerContainer: outerContainer3
};
var hoverLabel = createHoverText(pointsData, fullOpts, opts.gd);
// Fix vertical overlap
var tooltipSpacing = 5;
var lastBottomY = 0;
var anchor = 0;
hoverLabel
.sort(function(a, b) {return a.y0 - b.y0;})
.each(function(d, i) {
var topY = d.y0 - d.by / 2;
if((topY - tooltipSpacing) < lastBottomY) {
d.offset = (lastBottomY - topY) + tooltipSpacing;
} else {
d.offset = 0;
}
lastBottomY = topY + d.by + d.offset;
if(i === opts.anchorIndex || 0) anchor = d.offset;
})
.each(function(d) {
d.offset -= anchor;
});
var scaleX = opts.gd._fullLayout._invScaleX;
var scaleY = opts.gd._fullLayout._invScaleY;
alignHoverText(hoverLabel, fullOpts.rotateLabels, scaleX, scaleY);
return multiHover ? hoverLabel : hoverLabel.node();
};
// The actual implementation is here:
function _hover(gd, evt, subplot, noHoverEvent) {
if(!subplot) subplot = 'xy';
// if the user passed in an array of subplots,
// use those instead of finding overlayed plots
var subplots = Array.isArray(subplot) ? subplot : [subplot];
var fullLayout = gd._fullLayout;
var plots = fullLayout._plots || [];
var plotinfo = plots[subplot];
var hasCartesian = fullLayout._has('cartesian');
// list of all overlaid subplots to look at
if(plotinfo) {
var overlayedSubplots = plotinfo.overlays.map(function(pi) {
return pi.id;
});
subplots = subplots.concat(overlayedSubplots);
}
var len = subplots.length;
var xaArray = new Array(len);
var yaArray = new Array(len);
var supportsCompare = false;
for(var i = 0; i < len; i++) {
var spId = subplots[i];
if(plots[spId]) {
// 'cartesian' case
supportsCompare = true;
xaArray[i] = plots[spId].xaxis;
yaArray[i] = plots[spId].yaxis;
} else if(fullLayout[spId] && fullLayout[spId]._subplot) {
// other subplot types
var _subplot = fullLayout[spId]._subplot;
xaArray[i] = _subplot.xaxis;
yaArray[i] = _subplot.yaxis;
} else {
Lib.warn('Unrecognized subplot: ' + spId);
return;
}
}
var hovermode = evt.hovermode || fullLayout.hovermode;
if(hovermode && !supportsCompare) hovermode = 'closest';
if(['x', 'y', 'closest', 'x unified', 'y unified'].indexOf(hovermode) === -1 || !gd.calcdata ||
gd.querySelector('.zoombox') || gd._dragging) {
return dragElement.unhoverRaw(gd, evt);
}
var hoverdistance = fullLayout.hoverdistance;
if(hoverdistance === -1) hoverdistance = Infinity;
var spikedistance = fullLayout.spikedistance;
if(spikedistance === -1) spikedistance = Infinity;
// hoverData: the set of candidate points we've found to highlight
var hoverData = [];
// searchData: the data to search in. Mostly this is just a copy of
// gd.calcdata, filtered to the subplot and overlays we're on
// but if a point array is supplied it will be a mapping
// of indicated curves
var searchData = [];
// [x|y]valArray: the axis values of the hover event
// mapped onto each of the currently selected overlaid subplots
var xvalArray, yvalArray;
var itemnum, curvenum, cd, trace, subplotId, subploti, _mode,
xval, yval, pointData, closedataPreviousLength;
// spikePoints: the set of candidate points we've found to draw spikes to
var spikePoints = {
hLinePoint: null,
vLinePoint: null
};
// does subplot have one (or more) horizontal traces?
// This is used to determine whether we rotate the labels or not
var hasOneHorizontalTrace = false;
// Figure out what we're hovering on:
// mouse location or user-supplied data
if(Array.isArray(evt)) {
// user specified an array of points to highlight
hovermode = 'array';
for(itemnum = 0; itemnum < evt.length; itemnum++) {
cd = gd.calcdata[evt[itemnum].curveNumber || 0];
if(cd) {
trace = cd[0].trace;
if(cd[0].trace.hoverinfo !== 'skip') {
searchData.push(cd);
if(trace.orientation === 'h') {
hasOneHorizontalTrace = true;
}
}
}
}
} else {
for(curvenum = 0; curvenum < gd.calcdata.length; curvenum++) {
cd = gd.calcdata[curvenum];
trace = cd[0].trace;
if(trace.hoverinfo !== 'skip' && helpers.isTraceInSubplots(trace, subplots)) {
searchData.push(cd);
if(trace.orientation === 'h') {
hasOneHorizontalTrace = true;
}
}
}
// [x|y]px: the pixels (from top left) of the mouse location
// on the currently selected plot area
// add pointerX|Y property for drawing the spikes in spikesnap 'cursor' situation
var hasUserCalledHover = !evt.target;
var xpx, ypx;
if(hasUserCalledHover) {
if('xpx' in evt) xpx = evt.xpx;
else xpx = xaArray[0]._length / 2;
if('ypx' in evt) ypx = evt.ypx;
else ypx = yaArray[0]._length / 2;
} else {
// fire the beforehover event and quit if it returns false
// note that we're only calling this on real mouse events, so
// manual calls to fx.hover will always run.
if(Events.triggerHandler(gd, 'plotly_beforehover', evt) === false) {
return;
}
// Discover event target, traversing open shadow roots.
var target = evt.composedPath && evt.composedPath()[0];
if(!target) {
// Fallback for browsers not supporting composedPath
target = evt.target;
}
var dbb = target.getBoundingClientRect();
xpx = evt.clientX - dbb.left;
ypx = evt.clientY - dbb.top;
fullLayout._calcInverseTransform(gd);
var transformedCoords = Lib.apply3DTransform(fullLayout._invTransform)(xpx, ypx);
xpx = transformedCoords[0];
ypx = transformedCoords[1];
// in case hover was called from mouseout into hovertext,
// it's possible you're not actually over the plot anymore
if(xpx < 0 || xpx > xaArray[0]._length || ypx < 0 || ypx > yaArray[0]._length) {
return dragElement.unhoverRaw(gd, evt);
}
}
evt.pointerX = xpx + xaArray[0]._offset;
evt.pointerY = ypx + yaArray[0]._offset;
if('xval' in evt) xvalArray = helpers.flat(subplots, evt.xval);
else xvalArray = helpers.p2c(xaArray, xpx);
if('yval' in evt) yvalArray = helpers.flat(subplots, evt.yval);
else yvalArray = helpers.p2c(yaArray, ypx);
if(!isNumeric(xvalArray[0]) || !isNumeric(yvalArray[0])) {
Lib.warn('Fx.hover failed', evt, gd);
return dragElement.unhoverRaw(gd, evt);
}
}
// the pixel distance to beat as a matching point
// in 'x' or 'y' mode this resets for each trace
var distance = Infinity;
// find the closest point in each trace
// this is minimum dx and/or dy, depending on mode
// and the pixel position for the label (labelXpx, labelYpx)
function findHoverPoints(customXVal, customYVal) {
for(curvenum = 0; curvenum < searchData.length; curvenum++) {
cd = searchData[curvenum];
// filter out invisible or broken data
if(!cd || !cd[0] || !cd[0].trace) continue;
trace = cd[0].trace;
if(trace.visible !== true || trace._length === 0) continue;
// Explicitly bail out for these two. I don't know how to otherwise prevent
// the rest of this function from running and failing
if(['carpet', 'contourcarpet'].indexOf(trace._module.name) !== -1) continue;
if(trace.type === 'splom') {
// splom traces do not generate overlay subplots,
// it is safe to assume here splom traces correspond to the 0th subplot
subploti = 0;
subplotId = subplots[subploti];
} else {
subplotId = helpers.getSubplot(trace);
subploti = subplots.indexOf(subplotId);
}
// within one trace mode can sometimes be overridden
_mode = hovermode;
if(helpers.isUnifiedHover(_mode)) {
_mode = _mode.charAt(0);
}
// container for new point, also used to pass info into module.hoverPoints
pointData = {
// trace properties
cd: cd,
trace: trace,
xa: xaArray[subploti],
ya: yaArray[subploti],
// max distances for hover and spikes - for points that want to show but do not
// want to override other points, set distance/spikeDistance equal to max*Distance
// and it will not get filtered out but it will be guaranteed to have a greater
// distance than any point that calculated a real distance.
maxHoverDistance: hoverdistance,
maxSpikeDistance: spikedistance,
// point properties - override all of these
index: false, // point index in trace - only used by plotly.js hoverdata consumers
distance: Math.min(distance, hoverdistance), // pixel distance or pseudo-distance
// distance/pseudo-distance for spikes. This distance should always be calculated
// as if in "closest" mode, and should only be set if this point should
// generate a spike.
spikeDistance: Infinity,
// in some cases the spikes have different positioning from the hover label
// they don't need x0/x1, just one position
xSpike: undefined,
ySpike: undefined,
// where and how to display the hover label
color: Color.defaultLine, // trace color
name: trace.name,
x0: undefined,
x1: undefined,
y0: undefined,
y1: undefined,
xLabelVal: undefined,
yLabelVal: undefined,
zLabelVal: undefined,
text: undefined
};
// add ref to subplot object (non-cartesian case)
if(fullLayout[subplotId]) {
pointData.subplot = fullLayout[subplotId]._subplot;
}
// add ref to splom scene
if(fullLayout._splomScenes && fullLayout._splomScenes[trace.uid]) {
pointData.scene = fullLayout._splomScenes[trace.uid];
}
closedataPreviousLength = hoverData.length;
// for a highlighting array, figure out what
// we're searching for with this element
if(_mode === 'array') {
var selection = evt[curvenum];
if('pointNumber' in selection) {
pointData.index = selection.pointNumber;
_mode = 'closest';
} else {
_mode = '';
if('xval' in selection) {
xval = selection.xval;
_mode = 'x';
}
if('yval' in selection) {
yval = selection.yval;
_mode = _mode ? 'closest' : 'y';
}
}
} else if(customXVal !== undefined && customYVal !== undefined) {
xval = customXVal;
yval = customYVal;
} else {
xval = xvalArray[subploti];
yval = yvalArray[subploti];
}
// Now if there is range to look in, find the points to hover.
if(hoverdistance !== 0) {
if(trace._module && trace._module.hoverPoints) {
var newPoints = trace._module.hoverPoints(pointData, xval, yval, _mode, {
finiteRange: true,
hoverLayer: fullLayout._hoverlayer
});
if(newPoints) {
var newPoint;
for(var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) {
newPoint = newPoints[newPointNum];
if(isNumeric(newPoint.x0) && isNumeric(newPoint.y0)) {
hoverData.push(cleanPoint(newPoint, hovermode));
}
}
}
} else {
Lib.log('Unrecognized trace type in hover:', trace);
}
}
// in closest mode, remove any existing (farther) points
// and don't look any farther than this latest point (or points, some
// traces like box & violin make multiple hover labels at once)
if(hovermode === 'closest' && hoverData.length > closedataPreviousLength) {
hoverData.splice(0, closedataPreviousLength);
distance = hoverData[0].distance;
}
// Now if there is range to look in, find the points to draw the spikelines
// Do it only if there is no hoverData
if(hasCartesian && (spikedistance !== 0)) {
if(hoverData.length === 0) {
pointData.distance = spikedistance;
pointData.index = false;
var closestPoints = trace._module.hoverPoints(pointData, xval, yval, 'closest', {
hoverLayer: fullLayout._hoverlayer
});
if(closestPoints) {
closestPoints = closestPoints.filter(function(point) {
// some hover points, like scatter fills, do not allow spikes,
// so will generate a hover point but without a valid spikeDistance
return point.spikeDistance <= spikedistance;
});
}
if(closestPoints && closestPoints.length) {
var tmpPoint;
var closestVPoints = closestPoints.filter(function(point) {
return point.xa.showspikes && point.xa.spikesnap !== 'hovered data';
});
if(closestVPoints.length) {
var closestVPt = closestVPoints[0];
if(isNumeric(closestVPt.x0) && isNumeric(closestVPt.y0)) {
tmpPoint = fillSpikePoint(closestVPt);
if(!spikePoints.vLinePoint || (spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance)) {
spikePoints.vLinePoint = tmpPoint;
}
}
}
var closestHPoints = closestPoints.filter(function(point) {
return point.ya.showspikes && point.ya.spikesnap !== 'hovered data';
});
if(closestHPoints.length) {
var closestHPt = closestHPoints[0];
if(isNumeric(closestHPt.x0) && isNumeric(closestHPt.y0)) {
tmpPoint = fillSpikePoint(closestHPt);
if(!spikePoints.hLinePoint || (spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance)) {
spikePoints.hLinePoint = tmpPoint;
}
}
}
}
}
}
}
}
findHoverPoints();
function selectClosestPoint(pointsData, spikedistance) {
var resultPoint = null;
var minDistance = Infinity;
var thisSpikeDistance;
for(var i = 0; i < pointsData.length; i++) {
thisSpikeDistance = pointsData[i].spikeDistance;
if(thisSpikeDistance <= minDistance && thisSpikeDistance <= spikedistance) {
resultPoint = pointsData[i];
minDistance = thisSpikeDistance;
}
}
return resultPoint;
}
function fillSpikePoint(point) {
if(!point) return null;
return {
xa: point.xa,
ya: point.ya,
x: point.xSpike !== undefined ? point.xSpike : (point.x0 + point.x1) / 2,
y: point.ySpike !== undefined ? point.ySpike : (point.y0 + point.y1) / 2,
distance: point.distance,
spikeDistance: point.spikeDistance,
curveNumber: point.trace.index,
color: point.color,
pointNumber: point.index
};
}
var spikelineOpts = {
fullLayout: fullLayout,
container: fullLayout._hoverlayer,
outerContainer: fullLayout._paperdiv,
event: evt
};
var oldspikepoints = gd._spikepoints;
var newspikepoints = {
vLinePoint: spikePoints.vLinePoint,
hLinePoint: spikePoints.hLinePoint
};
gd._spikepoints = newspikepoints;
// Now if it is not restricted by spikedistance option, set the points to draw the spikelines
if(hasCartesian && (spikedistance !== 0)) {
if(hoverData.length !== 0) {
var tmpHPointData = hoverData.filter(function(point) {
return point.ya.showspikes;
});
var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance);
spikePoints.hLinePoint = fillSpikePoint(tmpHPoint);
var tmpVPointData = hoverData.filter(function(point) {
return point.xa.showspikes;
});
var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance);
spikePoints.vLinePoint = fillSpikePoint(tmpVPoint);
}
}
// if hoverData is empty check for the spikes to draw and quit if there are none
if(hoverData.length === 0) {
var result = dragElement.unhoverRaw(gd, evt);
if(hasCartesian && ((spikePoints.hLinePoint !== null) || (spikePoints.vLinePoint !== null))) {
if(spikesChanged(oldspikepoints)) {
createSpikelines(gd, spikePoints, spikelineOpts);
}
}
return result;
}
if(hasCartesian) {
if(spikesChanged(oldspikepoints)) {
createSpikelines(gd, spikePoints, spikelineOpts);
}
}
var sortHoverData = function() {
hoverData.sort(function(d1, d2) { return d1.distance - d2.distance; });
// move period positioned points and box/bar-like traces to the end of the list
hoverData = orderRangePoints(hoverData, hovermode);
};
sortHoverData();
if(
helpers.isXYhover(_mode) &&
hoverData[0].length !== 0 &&
hoverData[0].trace.type !== 'splom' // TODO: add support for splom
) {
// pick winning point
var winningPoint = hoverData[0];
// discard other points
if(multipleHoverPoints[winningPoint.trace.type]) {
hoverData = hoverData.filter(function(d) {
return d.trace.index === winningPoint.trace.index;
});
} else {
hoverData = [winningPoint];
}
var initLen = hoverData.length;
var winX = getCoord('x', winningPoint, fullLayout);
var winY = getCoord('y', winningPoint, fullLayout);
// in compare mode, select every point at position
findHoverPoints(winX, winY);
var finalPoints = [];
var seen = {};
var id = 0;
var insert = function(newHd) {
var key = multipleHoverPoints[newHd.trace.type] ? hoverDataKey(newHd) : newHd.trace.index;
if(!seen[key]) {
id++;
seen[key] = id;
finalPoints.push(newHd);
} else {
var oldId = seen[key] - 1;
var oldHd = finalPoints[oldId];
if(oldId > 0 &&
Math.abs(newHd.distance) <
Math.abs(oldHd.distance)
) {
// replace with closest
finalPoints[oldId] = newHd;
}
}
};
var k;
// insert the winnig point(s) first
for(k = 0; k < initLen; k++) {
insert(hoverData[k]);
}
// override from the end
for(k = hoverData.length - 1; k > initLen - 1; k--) {
insert(hoverData[k]);
}
hoverData = finalPoints;
sortHoverData();
}
// lastly, emit custom hover/unhover events
var oldhoverdata = gd._hoverdata;
var newhoverdata = [];
// pull out just the data that's useful to
// other people and send it to the event
for(itemnum = 0; itemnum < hoverData.length; itemnum++) {
var pt = hoverData[itemnum];
var eventData = helpers.makeEventData(pt, pt.trace, pt.cd);
if(pt.hovertemplate !== false) {
var ht = false;
if(pt.cd[pt.index] && pt.cd[pt.index].ht) {
ht = pt.cd[pt.index].ht;
}
pt.hovertemplate = ht || pt.trace.hovertemplate || false;
}
pt.eventData = [eventData];
newhoverdata.push(eventData);
}
gd._hoverdata = newhoverdata;
var rotateLabels = (
(hovermode === 'y' && (searchData.length > 1 || hoverData.length > 1)) ||
(hovermode === 'closest' && hasOneHorizontalTrace && hoverData.length > 1)
);
var bgColor = Color.combine(
fullLayout.plot_bgcolor || Color.background,
fullLayout.paper_bgcolor
);
var labelOpts = {
hovermode: hovermode,
rotateLabels: rotateLabels,
bgColor: bgColor,
container: fullLayout._hoverlayer,
outerContainer: fullLayout._paperdiv,
commonLabelOpts: fullLayout.hoverlabel,
hoverdistance: fullLayout.hoverdistance
};
var hoverLabels = createHoverText(hoverData, labelOpts, gd);
if(!helpers.isUnifiedHover(hovermode)) {
hoverAvoidOverlaps(hoverLabels, rotateLabels ? 'xa' : 'ya', fullLayout);
alignHoverText(hoverLabels, rotateLabels, fullLayout._invScaleX, fullLayout._invScaleY);
} // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true
// we should improve the "fx" API so other plots can use it without these hack.
if(evt.target && evt.target.tagName) {
var hasClickToShow = Registry.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata);
overrideCursor(d3.select(evt.target), hasClickToShow ? 'pointer' : '');
}
// don't emit events if called manually
if(!evt.target || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return;
if(oldhoverdata) {
gd.emit('plotly_unhover', {
event: evt,
points: oldhoverdata
});
}
gd.emit('plotly_hover', {
event: evt,
points: gd._hoverdata,
xaxes: xaArray,
yaxes: yaArray,
xvals: xvalArray,
yvals: yvalArray
});
}
function hoverDataKey(d) {
return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa, d.ya || ''].join(',');
}
var EXTRA_STRING_REGEX = /<extra>([\s\S]*)<\/extra>/;
function createHoverText(hoverData, opts, gd) {
var fullLayout = gd._fullLayout;
var hovermode = opts.hovermode;
var rotateLabels = opts.rotateLabels;
var bgColor = opts.bgColor;
var container = opts.container;
var outerContainer = opts.outerContainer;
var commonLabelOpts = opts.commonLabelOpts || {};
// opts.fontFamily/Size are used for the common label
// and as defaults for each hover label, though the individual labels
// can override this.
var fontFamily = opts.fontFamily || constants.HOVERFONT;
var fontSize = opts.fontSize || constants.HOVERFONTSIZE;
var c0 = hoverData[0];
var xa = c0.xa;
var ya = c0.ya;
var axLetter = hovermode.charAt(0);
var t0 = c0[axLetter + 'Label'];
var outerContainerBB = outerContainer.node().getBoundingClientRect();
var outerTop = outerContainerBB.top;
var outerWidth = outerContainerBB.width;
var outerHeight = outerContainerBB.height;
// show the common label, if any, on the axis
// never show a common label in array mode,
// even if sometimes there could be one
var showCommonLabel = (
(t0 !== undefined) &&
(c0.distance <= opts.hoverdistance) &&
(hovermode === 'x' || hovermode === 'y')
);
// all hover traces hoverinfo must contain the hovermode
// to have common labels
if(showCommonLabel) {
var allHaveZ = true;
var i, traceHoverinfo;
for(i = 0; i < hoverData.length; i++) {
if(allHaveZ && hoverData[i].zLabel === undefined) allHaveZ = false;
traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo;
if(traceHoverinfo) {
var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split('+');
if(parts.indexOf('all') === -1 &&
parts.indexOf(hovermode) === -1) {
showCommonLabel = false;
break;
}
}
}
// xyz labels put all info in their main label, so have no need of a common label
if(allHaveZ) showCommonLabel = false;
}
var commonLabel = container.selectAll('g.axistext')
.data(showCommonLabel ? [0] : []);
commonLabel.enter().append('g')
.classed('axistext', true);
commonLabel.exit().remove();
commonLabel.each(function() {
var label = d3.select(this);
var lpath = Lib.ensureSingle(label, 'path', '', function(s) {
s.style({'stroke-width': '1px'});
});
var ltext = Lib.ensureSingle(label, 'text', '', function(s) {
// prohibit tex interpretation until we can handle
// tex and regular text together
s.attr('data-notex', 1);
});
var commonBgColor = commonLabelOpts.bgcolor || Color.defaultLine;
var commonStroke = commonLabelOpts.bordercolor || Color.contrast(commonBgColor);
var contrastColor = Color.contrast(commonBgColor);
var commonLabelFont = {
family: commonLabelOpts.font.family || fontFamily,
size: commonLabelOpts.font.size || fontSize,
color: commonLabelOpts.font.color || contrastColor
};
lpath.style({
fill: commonBgColor,
stroke: commonStroke
});
ltext.text(t0)
.call(Drawing.font, commonLabelFont)
.call(svgTextUtils.positionText, 0, 0)
.call(svgTextUtils.convertToTspans, gd);
label.attr('transform', '');
var tbb = ltext.node().getBoundingClientRect();
var lx, ly;
if(hovermode === 'x') {
var topsign = xa.side === 'top' ? '-' : '';
ltext.attr('text-anchor', 'middle')
.call(svgTextUtils.positionText, 0, (xa.side === 'top' ?
(outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) :
(outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD)));
lx = xa._offset + (c0.x0 + c0.x1) / 2;
ly = ya._offset + (xa.side === 'top' ? 0 : ya._length);
var halfWidth = tbb.width / 2 + HOVERTEXTPAD;
if(lx < halfWidth) {
lx = halfWidth;
lpath.attr('d', 'M-' + (halfWidth - HOVERARROWSIZE) + ',0' +
'L-' + (halfWidth - HOVERARROWSIZE * 2) + ',' + topsign + HOVERARROWSIZE +
'H' + (HOVERTEXTPAD + tbb.width / 2) +
'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) +
'H-' + halfWidth +
'V' + topsign + HOVERARROWSIZE +
'Z');
} else if(lx > (fullLayout.width - halfWidth)) {
lx = fullLayout.width - halfWidth;
lpath.attr('d', 'M' + (halfWidth - HOVERARROWSIZE) + ',0' +
'L' + halfWidth + ',' + topsign + HOVERARROWSIZE +
'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) +
'H-' + halfWidth +
'V' + topsign + HOVERARROWSIZE +
'H' + (halfWidth - HOVERARROWSIZE * 2) + 'Z');
} else {
lpath.attr('d', 'M0,0' +
'L' + HOVERARROWSIZE + ',' + topsign + HOVERARROWSIZE +
'H' + (HOVERTEXTPAD + tbb.width / 2) +
'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) +
'H-' + (HOVERTEXTPAD + tbb.width / 2) +
'V' + topsign + HOVERARROWSIZE +
'H-' + HOVERARROWSIZE + 'Z');
}
} else {
var anchor;
var sgn;
var leftsign;
if(ya.side === 'right') {
anchor = 'start';
sgn = 1;
leftsign = '';
lx = xa._offset + xa._length;
} else {
anchor = 'end';
sgn = -1;
leftsign = '-';
lx = xa._offset;
}
ly = ya._offset + (c0.y0 + c0.y1) / 2;
ltext.attr('text-anchor', anchor);
lpath.attr('d', 'M0,0' +
'L' + leftsign + HOVERARROWSIZE + ',' + HOVERARROWSIZE +
'V' + (HOVERTEXTPAD + tbb.height / 2) +
'h' + leftsign + (HOVERTEXTPAD * 2 + tbb.width) +
'V-' + (HOVERTEXTPAD + tbb.height / 2) +
'H' + leftsign + HOVERARROWSIZE + 'V-' + HOVERARROWSIZE + 'Z');
var halfHeight = tbb.height / 2;
var lty = outerTop - tbb.top - halfHeight;
var clipId = 'clip' + fullLayout._uid + 'commonlabel' + ya._id;
var clipPath;
if(lx < (tbb.width + 2 * HOVERTEXTPAD + HOVERARROWSIZE)) {
clipPath = 'M-' + (HOVERARROWSIZE + HOVERTEXTPAD) + '-' + halfHeight +
'h-' + (tbb.width - HOVERTEXTPAD) +
'V' + halfHeight +
'h' + (tbb.width - HOVERTEXTPAD) + 'Z';
var ltx = tbb.width - lx + HOVERTEXTPAD;
svgTextUtils.positionText(ltext, ltx, lty);
// shift each line (except the longest) so that start-of-line
// is always visible
if(anchor === 'end') {
ltext.selectAll('tspan').each(function() {
var s = d3.select(this);
var dummy = Drawing.tester.append('text')
.text(s.text())
.call(Drawing.font, commonLabelFont);
var dummyBB = dummy.node().getBoundingClientRect();
if(Math.round(dummyBB.width) < Math.round(tbb.width)) {
s.attr('x', ltx - dummyBB.width);
}
dummy.remove();
});
}
} else {
svgTextUtils.positionText(ltext, sgn * (HOVERTEXTPAD + HOVERARROWSIZE), lty);
clipPath = null;
}
var textClip = fullLayout._topclips.selectAll('#' + clipId).data(clipPath ? [0] : []);
textClip.enter().append('clipPath').attr('id', clipId).append('path');
textClip.exit().remove();
textClip.select('path').attr('d', clipPath);
Drawing.setClipUrl(ltext, clipPath ? clipId : null, gd);
}
label.attr('transform', strTranslate(lx, ly));
});
// Show a single hover label
if(helpers.isUnifiedHover(hovermode)) {
// Delete leftover hover labels from other hovermodes
container.selectAll('g.hovertext').remove();
// Return early if nothing is hovered on
if(hoverData.length === 0) return;
// mock legend
var mockLayoutIn = {
showlegend: true,
legend: {
title: {text: t0, font: fullLayout.hoverlabel.font},
font: fullLayout.hoverlabel.font,
bgcolor: fullLayout.hoverlabel.bgcolor,
bordercolor: fullLayout.hoverlabel.bordercolor,
borderwidth: 1,
tracegroupgap: 7,
traceorder: fullLayout.legend ? fullLayout.legend.traceorder : undefined,
orientation: 'v'
}
};
var mockLayoutOut = {};
legendSupplyDefaults(mockLayoutIn, mockLayoutOut, gd._fullData);
var mockLegend = mockLayoutOut.legend;
// prepare items for the legend
mockLegend.entries = [];
for(var j = 0; j < hoverData.length; j++) {
var texts = getHoverLabelText(hoverData[j], true, hovermode, fullLayout, t0);
var text = texts[0];
var name = texts[1];
var pt = hoverData[j];
pt.name = name;
if(name !== '') {
pt.text = name + ' : ' + text;
} else {
pt.text = text;
}
// pass through marker's calcdata to style legend items
var cd = pt.cd[pt.index];
if(cd) {
if(cd.mc) pt.mc = cd.mc;
if(cd.mcc) pt.mc = cd.mcc;
if(cd.mlc) pt.mlc = cd.mlc;
if(cd.mlcc) pt.mlc = cd.mlcc;
if(cd.mlw) pt.mlw = cd.mlw;
if(cd.mrc) pt.mrc = cd.mrc;
if(cd.dir) pt.dir = cd.dir;
}
pt._distinct = true;
mockLegend.entries.push([pt]);
}
mockLegend.entries.sort(function(a, b) { return a[0].trace.index - b[0].trace.index;});
mockLegend.layer = container;
// Draw unified hover label
mockLegend._inHover = true;
legendDraw(gd, mockLegend);
// Position the hover
var lyBottom, lyTop;
if(axLetter === 'y') {
lyTop = Math.min.apply(null, hoverData.map(function(c) { return Math.min(c.y0, c.y1);}));
lyBottom = Math.max.apply(null, hoverData.map(function(c) {return Math.max(c.y0, c.y1);}));
} else {
lyTop = lyBottom = Lib.mean(hoverData.map(function(c) {return (c.y0 + c.y1) / 2;}));
}
var lxRight, lxLeft;
if(axLetter === 'x') {
lxRight = Math.max.apply(null, hoverData.map(function(c) {return Math.max(c.x0, c.x1);}));
lxLeft = Math.min.apply(null, hoverData.map(function(c) {return Math.min(c.x0, c.x1);}));
} else {
lxRight = lxLeft = Lib.mean(hoverData.map(function(c) {return (c.x0 + c.x1) / 2;}));
}
var legendContainer = container.select('g.legend');
var tbb = legendContainer.node().getBoundingClientRect();
var tWidth = tbb.width + 2 * HOVERTEXTPAD;
var tHeight = tbb.height + 2 * HOVERTEXTPAD;
var xOffset = xa._offset;
var yOffset = ya._offset;
lyBottom += yOffset;
lxRight += xOffset;
lxLeft += xOffset - tWidth;
lyTop += yOffset - tHeight;
var lx, ly; // top and left positions of the hover box
// horizontal alignment to end up on screen
if(lxRight + tWidth <= outerWidth && lxRight >= 0) {
lx = lxRight;
} else if(lxLeft + tWidth <= outerWidth && lxLeft >= 0) {
lx = lxLeft;
} else if(xOffset + tWidth <= outerWidth) {
lx = xOffset; // subplot left corner
} else {
lx = 0; // paper left corner
}
lx += HOVERTEXTPAD;
// vertical alignement to end up on screen
if(lyBottom + tHeight <= outerHeight && lyBottom >= 0) {
ly = lyBottom;
} else if(lyTop + tHeight <= outerHeight && lyTop >= 0) {
ly = lyTop;
} else if(yOffset + tHeight <= outerHeight) {
ly = yOffset; // subplot top corner
} else {
ly = 0; // paper top corner
}
ly += HOVERTEXTPAD;
legendContainer.attr('transform', strTranslate(lx, ly));
return legendContainer;
}
// show all the individual labels
// first create the objects
var hoverLabels = container.selectAll('g.hovertext')
.data(hoverData, function(d) {
// N.B. when multiple items have the same result key-function value,
// only the first of those items in hoverData gets rendered
return hoverDataKey(d);
});
hoverLabels.enter().append('g')
.classed('hovertext', true)
.each(function() {
var g = d3.select(this);
// trace name label (rect and text.name)
g.append('rect')
.call(Color.fill, Color.addOpacity(bgColor, 0.8));
g.append('text').classed('name', true);
// trace data label (path and text.nums)
g.append('path')
.style('stroke-width', '1px');
g.append('text').classed('nums', true)
.call(Drawing.font, fontFamily, fontSize);
});
hoverLabels.exit().remove();
// then put the text in, position the pointer to the data,
// and figure out sizes
hoverLabels.each(function(d) {
var g = d3.select(this).attr('transform', '');
var dColor = d.color;
if(Array.isArray(dColor)) {
dColor = dColor[d.eventData[0].pointNumber];
}
// combine possible non-opaque trace color with bgColor
var color0 = d.bgcolor || dColor;
// color for 'nums' part of the label
var numsColor = Color.combine(
Color.opacity(color0) ? color0 : Color.defaultLine,
bgColor
);
// color for 'name' part of the label
var nameColor = Color.combine(
Color.opacity(dColor) ? dColor : Color.defaultLine,
bgColor
);
// find a contrasting color for border and text
var contrastColor = d.borderColor || Color.contrast(numsColor);
var texts = getHoverLabelText(d, showCommonLabel, hovermode, fullLayout, t0, g);
var text = texts[0];
var name = texts[1];
// main label
var tx = g.select('text.nums')
.call(Drawing.font,
d.fontFamily || fontFamily,
d.fontSize || fontSize,
d.fontColor || contrastColor)
.text(text)
.attr('data-notex', 1)
.call(svgTextUtils.positionText, 0, 0)
.call(svgTextUtils.convertToTspans, gd);
var tx2 = g.select('text.name');
var tx2width = 0;
var tx2height = 0;
// secondary label for non-empty 'name'
if(name && name !== text) {
tx2.call(Drawing.font,
d.fontFamily || fontFamily,
d.fontSize || fontSize,
nameColor)
.text(name)
.attr('data-notex', 1)
.call(svgTextUtils.positionText, 0, 0)
.call(svgTextUtils.convertToTspans, gd);
var t2bb = tx2.node().getBoundingClientRect();
tx2width = t2bb.width + 2 * HOVERTEXTPAD;
tx2height = t2bb.height + 2 * HOVERTEXTPAD;
} else {
tx2.remove();
g.select('rect').remove();
}
g.select('path').style({
fill: numsColor,
stroke: contrastColor
});
var tbb = tx.node().getBoundingClientRect();
var htx = d.xa._offset + (d.x0 + d.x1) / 2;
var hty = d.ya._offset + (d.y0 + d.y1) / 2;
var dx = Math.abs(d.x1 - d.x0);
var dy = Math.abs(d.y1 - d.y0);
var txTotalWidth = tbb.width + HOVERARROWSIZE + HOVERTEXTPAD + tx2width;
var anchorStartOK, anchorEndOK;
d.ty0 = outerTop - tbb.top;
d.bx = tbb.width + 2 * HOVERTEXTPAD;
d.by = Math.max(tbb.height + 2 * HOVERTEXTPAD, tx2height);
d.anchor = 'start';
d.txwidth = tbb.width;
d.tx2width = tx2width;
d.offset = 0;
if(rotateLabels) {
d.pos = htx;
anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight;
anchorEndOK = hty - dy / 2 - txTotalWidth >= 0;
if((d.idealAlign === 'top' || !anchorStartOK) && anchorEndOK) {
hty -= dy / 2;
d.anchor = 'end';
} else if(anchorStartOK) {
hty += dy / 2;
d.anchor = 'start';
} else d.anchor = 'middle';
} else {
d.pos = hty;
anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth;
anchorEndOK = htx - dx / 2 - txTotalWidth >= 0;
if((d.idealAlign === 'left' || !anchorStartOK) && anchorEndOK) {
htx -= dx / 2;
d.anchor = 'end';
} else if(anchorStartOK) {
htx += dx / 2;
d.anchor = 'start';
} else {
d.anchor = 'middle';
var txHalfWidth = txTotalWidth / 2;
var overflowR = htx + txHalfWidth - outerWidth;
var overflowL = htx - txHalfWidth;
if(overflowR > 0) htx -= overflowR;
if(overflowL < 0) htx += -overflowL;
}
}
tx.attr('text-anchor', d.anchor);
if(tx2width) tx2.attr('text-anchor', d.anchor);
g.attr('transform', strTranslate(htx, hty) +
(rotateLabels ? strRotate(YANGLE) : ''));
});
return hoverLabels;
}
function getHoverLabelText(d, showCommonLabel, hovermode, fullLayout, t0, g) {
var name = '';
var text = '';
// to get custom 'name' labels pass cleanPoint
if(d.nameOverride !== undefined) d.name = d.nameOverride;
if(d.name) {
if(d.trace._meta) {
d.name = Lib.templateString(d.name, d.trace._meta);
}
name = plainText(d.name, d.nameLength);
}
var h0 = hovermode.charAt(0);
var h1 = h0 === 'x' ? 'y' : 'x';
if(d.zLabel !== undefined) {
if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '<br>';
if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '<br>';
if(d.trace.type !== 'choropleth' && d.trace.type !== 'choroplethmapbox') {
text += (text ? 'z: ' : '') + d.zLabel;
}
} else if(showCommonLabel && d[h0 + 'Label'] === t0) {
text = d[h1 + 'Label'] || '';
} else if(d.xLabel === undefined) {
if(d.yLabel !== undefined && d.trace.type !== 'scattercarpet') {
text = d.yLabel;
}
} else if(d.yLabel === undefined) text = d.xLabel;
else text = '(' + d.xLabel + ', ' + d.yLabel + ')';
if((d.text || d.text === 0) && !Array.isArray(d.text)) {
text += (text ? '<br>' : '') + d.text;
}
// used by other modules (initially just ternary) that
// manage their own hoverinfo independent of cleanPoint
// the rest of this will still apply, so such modules
// can still put things in (x|y|z)Label, text, and name
// and hoverinfo will still determine their visibility
if(d.extraText !== undefined) text += (text ? '<br>' : '') + d.extraText;
// if 'text' is empty at this point,
// and hovertemplate is not defined,
// put 'name' in main label and don't show secondary label
if(g && text === '' && !d.hovertemplate) {
// if 'name' is also empty, remove entire label
if(name === '') g.remove();
text = name;
}
// hovertemplate
var hovertemplate = d.hovertemplate || false;
if(hovertemplate) {
var labels = d.hovertemplateLabels || d;
if(d[h0 + 'Label'] !== t0) {
labels[h0 + 'other'] = labels[h0 + 'Val'];
labels[h0 + 'otherLabel'] = labels[h0 + 'Label'];
}
text = Lib.hovertemplateString(
hovertemplate,
labels,
fullLayout._d3locale,
d.eventData[0] || {},
d.trace._meta
);
text = text.replace(EXTRA_STRING_REGEX, function(match, extra) {
// assign name for secondary text label
name = plainText(extra, d.nameLength);
// remove from main text label
return '';
});
}
return [text, name];
}
// Make groups of touching points, and within each group
// move each point so that no labels overlap, but the average
// label position is the same as it was before moving. Incidentally,
// this is equivalent to saying all the labels are on equal linear
// springs about their initial position. Initially, each point is
// its own group, but as we find overlaps we will clump the points.
//
// Also, there are hard constraints at the edges of the graphs,
// that push all groups to the middle so they are visible. I don't
// know what happens if the group spans all the way from one edge to
// the other, though it hardly matters - there's just too much
// information then.
function hoverAvoidOverlaps(hoverLabels, axKey, fullLayout) {
var nummoves = 0;
var axSign = 1;
var nLabels = hoverLabels.size();
// make groups of touching points
var pointgroups = new Array(nLabels);
var k = 0;
hoverLabels.each(function(d) {
var ax = d[axKey];
var axIsX = ax._id.charAt(0) === 'x';
var rng = ax.range;
if(k === 0 && rng && ((rng[0] > rng[1]) !== axIsX)) {
axSign = -1;
}
pointgroups[k++] = [{
datum: d,
traceIndex: d.trace.index,
dp: 0,
pos: d.pos,
posref: d.posref,
size: d.by * (axIsX ? YFACTOR : 1) / 2,
pmin: 0,
pmax: (axIsX ? fullLayout.width : fullLayout.height)
}];
});
pointgroups.sort(function(a, b) {
return (a[0].posref - b[0].posref) ||
// for equal positions, sort trace indices increasing or decreasing
// depending on whether the axis is reversed or not... so stacked
// traces will generally keep their order even if one trace adds
// nothing to the stack.
(axSign * (b[0].traceIndex - a[0].traceIndex));
});
var donepositioning, topOverlap, bottomOverlap, i, j, pti, sumdp;
function constrainGroup(grp) {
var minPt = grp[0];
var maxPt = grp[grp.length - 1];
// overlap with the top - positive vals are overlaps
topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size;
// overlap with the bottom - positive vals are overlaps
bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax;
// check for min overlap first, so that we always
// see the largest labels
// allow for .01px overlap, so we don't get an
// infinite loop from rounding errors
if(topOverlap > 0.01) {
for(j = grp.length - 1; j >= 0; j--) grp[j].dp += topOverlap;
donepositioning = false;
}
if(bottomOverlap < 0.01) return;
if(topOverlap < -0.01) {
// make sure we're not pushing back and forth
for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap;
donepositioning = false;
}
if(!donepositioning) return;
// no room to fix positioning, delete off-screen points
// first see how many points we need to delete
var deleteCount = 0;
for(i = 0; i < grp.length; i++) {
pti = grp[i];
if(pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++;
}
// start by deleting points whose data is off screen
for(i = grp.length - 1; i >= 0; i--) {
if(deleteCount <= 0) break;
pti = grp[i];
// pos has already been constrained to [pmin,pmax]
// so look for points close to that to delete
if(pti.pos > minPt.pmax - 1) {
pti.del = true;
deleteCount--;
}
}
for(i = 0; i < grp.length; i++) {
if(deleteCount <= 0) break;
pti = grp[i];
// pos has already been constrained to [pmin,pmax]
// so look for points close to that to delete
if(pti.pos < minPt.pmin + 1) {
pti.del = true;
deleteCount--;
// shift the whole group minus into this new space
bottomOverlap = pti.size * 2;
for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap;
}
}
// then delete points that go off the bottom
for(i = grp.length - 1; i >= 0; i--) {
if(deleteCount <= 0) break;
pti = grp[i];
if(pti.pos + pti.dp + pti.size > minPt.pmax) {
pti.del = true;
deleteCount--;
}
}
}
// loop through groups, combining them if they overlap,
// until nothing moves
while(!donepositioning && nummoves <= nLabels) {
// to avoid infinite loops, don't move more times
// than there are traces
nummoves++;
// assume nothing will move in this iteration,
// reverse this if it does
donepositioning = true;
i = 0;
while(i < pointgroups.length - 1) {
// the higher (g0) and lower (g1) point group
var g0 = pointgroups[i];
var g1 = pointgroups[i + 1];
// the lowest point in the higher group (p0)
// the highest point in the lower group (p1)
var p0 = g0[g0.length - 1];
var p1 = g1[0];
topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size;
// Only group points that lie on the same axes
if(topOverlap > 0.01 && (p0.pmin === p1.pmin) && (p0.pmax === p1.pmax)) {
// push the new point(s) added to this group out of the way
for(j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap;
// add them to the group
g0.push.apply(g0, g1);
pointgroups.splice(i + 1, 1);
// adjust for minimum average movement
sumdp = 0;
for(j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp;
bottomOverlap = sumdp / g0.length;
for(j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap;
donepositioning = false;
} else i++;
}
// check if we're going off the plot on either side and fix
pointgroups.forEach(constrainGroup);
}
// now put these offsets into hoverData
for(i = pointgroups.length - 1; i >= 0; i--) {
var grp = pointgroups[i];
for(j = grp.length - 1; j >= 0; j--) {
var pt = grp[j];
var hoverPt = pt.datum;
hoverPt.offset = pt.dp;
hoverPt.del = pt.del;
}
}
}
function alignHoverText(hoverLabels, rotateLabels, scaleX, scaleY) {
var pX = function(x) { return x * scaleX; };
var pY = function(y) { return y * scaleY; };
// finally set the text positioning relative to the data and draw the
// box around it
hoverLabels.each(function(d) {
var g = d3.select(this);
if(d.del) return g.remove();
var tx = g.select('text.nums');
var anchor = d.anchor;
var horzSign = anchor === 'end' ? -1 : 1;
var alignShift = {start: 1, end: -1, middle: 0}[anchor];
var txx = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD);
var tx2x = txx + alignShift * (d.txwidth + HOVERTEXTPAD);
var offsetX = 0;
var offsetY = d.offset;
var isMiddle = anchor === 'middle';
if(isMiddle) {
txx -= d.tx2width / 2;
tx2x += d.txwidth / 2 + HOVERTEXTPAD;
}
if(rotateLabels) {
offsetY *= -YSHIFTY;
offsetX = d.offset * YSHIFTX;
}
g.select('path')
.attr('d', isMiddle ?
// middle aligned: rect centered on data
('M-' + pX(d.bx / 2 + d.tx2width / 2) + ',' + pY(offsetY - d.by / 2) +
'h' + pX(d.bx) + 'v' + pY(d.by) + 'h-' + pX(d.bx) + 'Z') :
// left or right aligned: side rect with arrow to data
('M0,0L' + pX(horzSign * HOVERARROWSIZE + offsetX) + ',' + pY(HOVERARROWSIZE + offsetY) +
'v' + pY(d.by / 2 - HOVERARROWSIZE) +
'h' + pX(horzSign * d.bx) +
'v-' + pY(d.by) +
'H' + pX(horzSign * HOVERARROWSIZE + offsetX) +
'V' + pY(offsetY - HOVERARROWSIZE) +
'Z'));
var posX = offsetX + txx;
var posY = offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD;
var textAlign = d.textAlign || 'auto';
if(textAlign !== 'auto') {
if(textAlign === 'left' && anchor !== 'start') {
tx.attr('text-anchor', 'start');
posX = isMiddle ?
-d.bx / 2 - d.tx2width / 2 + HOVERTEXTPAD :
-d.bx - HOVERTEXTPAD;
} else if(textAlign === 'right' && anchor !== 'end') {
tx.attr('text-anchor', 'end');
posX = isMiddle ?
d.bx / 2 - d.tx2width / 2 - HOVERTEXTPAD :
d.bx + HOVERTEXTPAD;
}
}
tx.call(svgTextUtils.positionText, pX(posX), pY(posY));
if(d.tx2width) {
g.select('text.name')
.call(svgTextUtils.positionText,
pX(tx2x + alignShift * HOVERTEXTPAD + offsetX),
pY(offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD));
g.select('rect')
.call(Drawing.setRect,
pX(tx2x + (alignShift - 1) * d.tx2width / 2 + offsetX),
pY(offsetY - d.by / 2 - 1),
pX(d.tx2width), pY(d.by + 2));
}
});
}
function cleanPoint(d, hovermode) {
var index = d.index;
var trace = d.trace || {};
var cd0 = d.cd[0];
var cd = d.cd[index] || {};
function pass(v) {
return v || (isNumeric(v) && v === 0);
}
var getVal = Array.isArray(index) ?
function(calcKey, traceKey) {
var v = Lib.castOption(cd0, index, calcKey);
return pass(v) ? v : Lib.extractOption({}, trace, '', traceKey);
} :
function(calcKey, traceKey) {
return Lib.extractOption(cd, trace, calcKey, traceKey);
};
function fill(key, calcKey, traceKey) {
var val = getVal(calcKey, traceKey);
if(pass(val)) d[key] = val;
}
fill('hoverinfo', 'hi', 'hoverinfo');
fill('bgcolor', 'hbg', 'hoverlabel.bgcolor');
fill('borderColor', 'hbc', 'hoverlabel.bordercolor');
fill('fontFamily', 'htf', 'hoverlabel.font.family');
fill('fontSize', 'hts', 'hoverlabel.font.size');
fill('fontColor', 'htc', 'hoverlabel.font.color');
fill('nameLength', 'hnl', 'hoverlabel.namelength');
fill('textAlign', 'hta', 'hoverlabel.align');
d.posref = (hovermode === 'y' || (hovermode === 'closest' && trace.orientation === 'h')) ?
(d.xa._offset + (d.x0 + d.x1) / 2) :
(d.ya._offset + (d.y0 + d.y1) / 2);
// then constrain all the positions to be on the plot
d.x0 = Lib.constrain(d.x0, 0, d.xa._length);
d.x1 = Lib.constrain(d.x1, 0, d.xa._length);
d.y0 = Lib.constrain(d.y0, 0, d.ya._length);
d.y1 = Lib.constrain(d.y1, 0, d.ya._length);
// and convert the x and y label values into formatted text
if(d.xLabelVal !== undefined) {
d.xLabel = ('xLabel' in d) ? d.xLabel : Axes.hoverLabelText(d.xa, d.xLabelVal, trace.xhoverformat);
d.xVal = d.xa.c2d(d.xLabelVal);
}
if(d.yLabelVal !== undefined) {
d.yLabel = ('yLabel' in d) ? d.yLabel : Axes.hoverLabelText(d.ya, d.yLabelVal, trace.yhoverformat);
d.yVal = d.ya.c2d(d.yLabelVal);
}
// Traces like heatmaps generate the zLabel in their hoverPoints function
if(d.zLabelVal !== undefined && d.zLabel === undefined) {
d.zLabel = String(d.zLabelVal);
}
// for box means and error bars, add the range to the label
if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) {
var xeText = Axes.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text;
if(d.xerrneg !== undefined) {
d.xLabel += ' +' + xeText + ' / -' +
Axes.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text;
} else d.xLabel += ' ± ' + xeText;
// small distance penalty for error bars, so that if there are
// traces with errors and some without, the error bar label will
// hoist up to the point
if(hovermode === 'x') d.distance += 1;
}
if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) {
var yeText = Axes.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text;
if(d.yerrneg !== undefined) {
d.yLabel += ' +' + yeText + ' / -' +
Axes.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text;
} else d.yLabel += ' ± ' + yeText;
if(hovermode === 'y') d.distance += 1;
}
var infomode = d.hoverinfo || d.trace.hoverinfo;
if(infomode && infomode !== 'all') {
infomode = Array.isArray(infomode) ? infomode : infomode.split('+');
if(infomode.indexOf('x') === -1) d.xLabel = undefined;
if(infomode.indexOf('y') === -1) d.yLabel = undefined;
if(infomode.indexOf('z') === -1) d.zLabel = undefined;
if(infomode.indexOf('text') === -1) d.text = undefined;
if(infomode.indexOf('name') === -1) d.name = undefined;
}
return d;
}
function createSpikelines(gd, closestPoints, opts) {
var container = opts.container;
var fullLayout = opts.fullLayout;
var gs = fullLayout._size;
var evt = opts.event;
var showY = !!closestPoints.hLinePoint;
var showX = !!closestPoints.vLinePoint;
var xa, ya;
// Remove old spikeline items
container.selectAll('.spikeline').remove();
if(!(showX || showY)) return;
var contrastColor = Color.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor);
// Horizontal line (to y-axis)
if(showY) {
var hLinePoint = closestPoints.hLinePoint;
var hLinePointX, hLinePointY;
xa = hLinePoint && hLinePoint.xa;
ya = hLinePoint && hLinePoint.ya;
var ySnap = ya.spikesnap;
if(ySnap === 'cursor') {
hLinePointX = evt.pointerX;
hLinePointY = evt.pointerY;
} else {
hLinePointX = xa._offset + hLinePoint.x;
hLinePointY = ya._offset + hLinePoint.y;
}
var dfltHLineColor = tinycolor.readability(hLinePoint.color, contrastColor) < 1.5 ?
Color.contrast(contrastColor) : hLinePoint.color;
var yMode = ya.spikemode;
var yThickness = ya.spikethickness;
var yColor = ya.spikecolor || dfltHLineColor;
var xEdge = Axes.getPxPosition(gd, ya);
var xBase, xEndSpike;
if(yMode.indexOf('toaxis') !== -1 || yMode.indexOf('across') !== -1) {
if(yMode.indexOf('toaxis') !== -1) {
xBase = xEdge;
xEndSpike = hLinePointX;
}
if(yMode.indexOf('across') !== -1) {
var xAcross0 = ya._counterDomainMin;
var xAcross1 = ya._counterDomainMax;
if(ya.anchor === 'free') {
xAcross0 = Math.min(xAcross0, ya.position);
xAcross1 = Math.max(xAcross1, ya.position);
}
xBase = gs.l + xAcross0 * gs.w;
xEndSpike = gs.l + xAcross1 * gs.w;
}
// Foreground horizontal line (to y-axis)
container.insert('line', ':first-child')
.attr({
x1: xBase,
x2: xEndSpike,
y1: hLinePointY,
y2: hLinePointY,
'stroke-width': yThickness,
stroke: yColor,
'stroke-dasharray': Drawing.dashStyle(ya.spikedash, yThickness)
})
.classed('spikeline', true)
.classed('crisp', true);
// Background horizontal Line (to y-axis)
container.insert('line', ':first-child')
.attr({
x1: xBase,
x2: xEndSpike,
y1: hLinePointY,
y2: hLinePointY,
'stroke-width': yThickness + 2,
stroke: contrastColor
})
.classed('spikeline', true)
.classed('crisp', true);
}
// Y axis marker
if(yMode.indexOf('marker') !== -1) {
container.insert('circle', ':first-child')
.attr({
cx: xEdge + (ya.side !== 'right' ? yThickness : -yThickness),
cy: hLinePointY,
r: yThickness,
fill: yColor
})
.classed('spikeline', true);
}
}
if(showX) {
var vLinePoint = closestPoints.vLinePoint;
var vLinePointX, vLinePointY;
xa = vLinePoint && vLinePoint.xa;
ya = vLinePoint && vLinePoint.ya;
var xSnap = xa.spikesnap;
if(xSnap === 'cursor') {
vLinePointX = evt.pointerX;
vLinePointY = evt.pointerY;
} else {
vLinePointX = xa._offset + vLinePoint.x;
vLinePointY = ya._offset + vLinePoint.y;
}
var dfltVLineColor = tinycolor.readability(vLinePoint.color, contrastColor) < 1.5 ?
Color.contrast(contrastColor) : vLinePoint.color;
var xMode = xa.spikemode;
var xThickness = xa.spikethickness;
var xColor = xa.spikecolor || dfltVLineColor;
var yEdge = Axes.getPxPosition(gd, xa);
var yBase, yEndSpike;
if(xMode.indexOf('toaxis') !== -1 || xMode.indexOf('across') !== -1) {
if(xMode.indexOf('toaxis') !== -1) {
yBase = yEdge;
yEndSpike = vLinePointY;
}
if(xMode.indexOf('across') !== -1) {
var yAcross0 = xa._counterDomainMin;
var yAcross1 = xa._counterDomainMax;
if(xa.anchor === 'free') {
yAcross0 = Math.min(yAcross0, xa.position);
yAcross1 = Math.max(yAcross1, xa.position);
}
yBase = gs.t + (1 - yAcross1) * gs.h;
yEndSpike = gs.t + (1 - yAcross0) * gs.h;
}
// Foreground vertical line (to x-axis)
container.insert('line', ':first-child')
.attr({
x1: vLinePointX,
x2: vLinePointX,
y1: yBase,
y2: yEndSpike,
'stroke-width': xThickness,
stroke: xColor,
'stroke-dasharray': Drawing.dashStyle(xa.spikedash, xThickness)
})
.classed('spikeline', true)
.classed('crisp', true);
// Background vertical line (to x-axis)
container.insert('line', ':first-child')
.attr({
x1: vLinePointX,
x2: vLinePointX,
y1: yBase,
y2: yEndSpike,
'stroke-width': xThickness + 2,
stroke: contrastColor
})
.classed('spikeline', true)
.classed('crisp', true);
}
// X axis marker
if(xMode.indexOf('marker') !== -1) {
container.insert('circle', ':first-child')
.attr({
cx: vLinePointX,
cy: yEdge - (xa.side !== 'top' ? xThickness : -xThickness),
r: xThickness,
fill: xColor
})
.classed('spikeline', true);
}
}
}
function hoverChanged(gd, evt, oldhoverdata) {
// don't emit any events if nothing changed
if(!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true;
for(var i = oldhoverdata.length - 1; i >= 0; i--) {
var oldPt = oldhoverdata[i];
var newPt = gd._hoverdata[i];
if(oldPt.curveNumber !== newPt.curveNumber ||
String(oldPt.pointNumber) !== String(newPt.pointNumber) ||
String(oldPt.pointNumbers) !== String(newPt.pointNumbers)
) {
return true;
}
}
return false;
}
function spikesChanged(gd, oldspikepoints) {
// don't relayout the plot because of new spikelines if spikelines points didn't change
if(!oldspikepoints) return true;
if(oldspikepoints.vLinePoint !== gd._spikepoints.vLinePoint ||
oldspikepoints.hLinePoint !== gd._spikepoints.hLinePoint
) return true;
return false;
}
function plainText(s, len) {
return svgTextUtils.plainText(s || '', {
len: len,
allowedTags: ['br', 'sub', 'sup', 'b', 'i', 'em']
});
}
function orderRangePoints(hoverData, hovermode) {
var axLetter = hovermode.charAt(0);
var first = [];
var second = [];
var last = [];
for(var i = 0; i < hoverData.length; i++) {
var d = hoverData[i];
if(
Registry.traceIs(d.trace, 'bar-like') ||
Registry.traceIs(d.trace, 'box-violin')
) {
last.push(d);
} else if(d.trace[axLetter + 'period']) {
second.push(d);
} else {
first.push(d);
}
}
return first.concat(second).concat(last);
}
function getCoord(axLetter, winningPoint, fullLayout) {
var ax = winningPoint[axLetter + 'a'];
var val = winningPoint[axLetter + 'Val'];
if(ax.type === 'category') val = ax._categoriesMap[val];
else if(ax.type === 'date') {
var period = winningPoint[axLetter + 'Period'];
val = ax.d2c(period !== undefined ? period : val);
}
var cd0 = winningPoint.cd[winningPoint.index];
if(cd0 && cd0.t && cd0.t.posLetter === ax._id) {
if(
fullLayout.boxmode === 'group' ||
fullLayout.violinmode === 'group'
) {
val += cd0.t.dPos;
}
}
return val;
}
|
src/components/fx/hover.js
|
'use strict';
var d3 = require('@plotly/d3');
var isNumeric = require('fast-isnumeric');
var tinycolor = require('tinycolor2');
var Lib = require('../../lib');
var strTranslate = Lib.strTranslate;
var strRotate = Lib.strRotate;
var Events = require('../../lib/events');
var svgTextUtils = require('../../lib/svg_text_utils');
var overrideCursor = require('../../lib/override_cursor');
var Drawing = require('../drawing');
var Color = require('../color');
var dragElement = require('../dragelement');
var Axes = require('../../plots/cartesian/axes');
var Registry = require('../../registry');
var helpers = require('./helpers');
var constants = require('./constants');
var legendSupplyDefaults = require('../legend/defaults');
var legendDraw = require('../legend/draw');
// hover labels for multiple horizontal bars get tilted by some angle,
// then need to be offset differently if they overlap
var YANGLE = constants.YANGLE;
var YA_RADIANS = Math.PI * YANGLE / 180;
// expansion of projected height
var YFACTOR = 1 / Math.sin(YA_RADIANS);
// to make the appropriate post-rotation x offset,
// you need both x and y offsets
var YSHIFTX = Math.cos(YA_RADIANS);
var YSHIFTY = Math.sin(YA_RADIANS);
// size and display constants for hover text
var HOVERARROWSIZE = constants.HOVERARROWSIZE;
var HOVERTEXTPAD = constants.HOVERTEXTPAD;
var multipleHoverPoints = {
box: true,
ohlc: true,
violin: true,
candlestick: true
};
// fx.hover: highlight data on hover
// evt can be a mousemove event, or an object with data about what points
// to hover on
// {xpx,ypx[,hovermode]} - pixel locations from top left
// (with optional overriding hovermode)
// {xval,yval[,hovermode]} - data values
// [{curveNumber,(pointNumber|xval and/or yval)}] -
// array of specific points to highlight
// pointNumber is a single integer if gd.data[curveNumber] is 1D,
// or a two-element array if it's 2D
// xval and yval are data values,
// 1D data may specify either or both,
// 2D data must specify both
// subplot is an id string (default "xy")
// makes use of gl.hovermode, which can be:
// x (find the points with the closest x values, ie a column),
// closest (find the single closest point)
// internally there are two more that occasionally get used:
// y (pick out a row - only used for multiple horizontal bar charts)
// array (used when the user specifies an explicit
// array of points to hover on)
//
// We wrap the hovers in a timer, to limit their frequency.
// The actual rendering is done by private function _hover.
exports.hover = function hover(gd, evt, subplot, noHoverEvent) {
gd = Lib.getGraphDiv(gd);
Lib.throttle(
gd._fullLayout._uid + constants.HOVERID,
constants.HOVERMINTIME,
function() { _hover(gd, evt, subplot, noHoverEvent); }
);
};
/*
* Draw a single hover item or an array of hover item in a pre-existing svg container somewhere
* hoverItem should have keys:
* - x and y (or x0, x1, y0, and y1):
* the pixel position to mark, relative to opts.container
* - xLabel, yLabel, zLabel, text, and name:
* info to go in the label
* - color:
* the background color for the label.
* - idealAlign (optional):
* 'left' or 'right' for which side of the x/y box to try to put this on first
* - borderColor (optional):
* color for the border, defaults to strongest contrast with color
* - fontFamily (optional):
* string, the font for this label, defaults to constants.HOVERFONT
* - fontSize (optional):
* the label font size, defaults to constants.HOVERFONTSIZE
* - fontColor (optional):
* defaults to borderColor
* opts should have keys:
* - bgColor:
* the background color this is against, used if the trace is
* non-opaque, and for the name, which goes outside the box
* - container:
* a <svg> or <g> element to add the hover label to
* - outerContainer:
* normally a parent of `container`, sets the bounding box to use to
* constrain the hover label and determine whether to show it on the left or right
* opts can have optional keys:
* - anchorIndex:
the index of the hover item used as an anchor for positioning.
The other hover items will be pushed up or down to prevent overlap.
*/
exports.loneHover = function loneHover(hoverItems, opts) {
var multiHover = true;
if(!Array.isArray(hoverItems)) {
multiHover = false;
hoverItems = [hoverItems];
}
var pointsData = hoverItems.map(function(hoverItem) {
return {
color: hoverItem.color || Color.defaultLine,
x0: hoverItem.x0 || hoverItem.x || 0,
x1: hoverItem.x1 || hoverItem.x || 0,
y0: hoverItem.y0 || hoverItem.y || 0,
y1: hoverItem.y1 || hoverItem.y || 0,
xLabel: hoverItem.xLabel,
yLabel: hoverItem.yLabel,
zLabel: hoverItem.zLabel,
text: hoverItem.text,
name: hoverItem.name,
idealAlign: hoverItem.idealAlign,
// optional extra bits of styling
borderColor: hoverItem.borderColor,
fontFamily: hoverItem.fontFamily,
fontSize: hoverItem.fontSize,
fontColor: hoverItem.fontColor,
nameLength: hoverItem.nameLength,
textAlign: hoverItem.textAlign,
// filler to make createHoverText happy
trace: hoverItem.trace || {
index: 0,
hoverinfo: ''
},
xa: {_offset: 0},
ya: {_offset: 0},
index: 0,
hovertemplate: hoverItem.hovertemplate || false,
eventData: hoverItem.eventData || false,
hovertemplateLabels: hoverItem.hovertemplateLabels || false,
};
});
var container3 = d3.select(opts.container);
var outerContainer3 = opts.outerContainer ? d3.select(opts.outerContainer) : container3;
var fullOpts = {
hovermode: 'closest',
rotateLabels: false,
bgColor: opts.bgColor || Color.background,
container: container3,
outerContainer: outerContainer3
};
var hoverLabel = createHoverText(pointsData, fullOpts, opts.gd);
// Fix vertical overlap
var tooltipSpacing = 5;
var lastBottomY = 0;
var anchor = 0;
hoverLabel
.sort(function(a, b) {return a.y0 - b.y0;})
.each(function(d, i) {
var topY = d.y0 - d.by / 2;
if((topY - tooltipSpacing) < lastBottomY) {
d.offset = (lastBottomY - topY) + tooltipSpacing;
} else {
d.offset = 0;
}
lastBottomY = topY + d.by + d.offset;
if(i === opts.anchorIndex || 0) anchor = d.offset;
})
.each(function(d) {
d.offset -= anchor;
});
var scaleX = opts.gd._fullLayout._invScaleX;
var scaleY = opts.gd._fullLayout._invScaleY;
alignHoverText(hoverLabel, fullOpts.rotateLabels, scaleX, scaleY);
return multiHover ? hoverLabel : hoverLabel.node();
};
// The actual implementation is here:
function _hover(gd, evt, subplot, noHoverEvent) {
if(!subplot) subplot = 'xy';
// if the user passed in an array of subplots,
// use those instead of finding overlayed plots
var subplots = Array.isArray(subplot) ? subplot : [subplot];
var fullLayout = gd._fullLayout;
var plots = fullLayout._plots || [];
var plotinfo = plots[subplot];
var hasCartesian = fullLayout._has('cartesian');
// list of all overlaid subplots to look at
if(plotinfo) {
var overlayedSubplots = plotinfo.overlays.map(function(pi) {
return pi.id;
});
subplots = subplots.concat(overlayedSubplots);
}
var len = subplots.length;
var xaArray = new Array(len);
var yaArray = new Array(len);
var supportsCompare = false;
for(var i = 0; i < len; i++) {
var spId = subplots[i];
if(plots[spId]) {
// 'cartesian' case
supportsCompare = true;
xaArray[i] = plots[spId].xaxis;
yaArray[i] = plots[spId].yaxis;
} else if(fullLayout[spId] && fullLayout[spId]._subplot) {
// other subplot types
var _subplot = fullLayout[spId]._subplot;
xaArray[i] = _subplot.xaxis;
yaArray[i] = _subplot.yaxis;
} else {
Lib.warn('Unrecognized subplot: ' + spId);
return;
}
}
var hovermode = evt.hovermode || fullLayout.hovermode;
if(hovermode && !supportsCompare) hovermode = 'closest';
if(['x', 'y', 'closest', 'x unified', 'y unified'].indexOf(hovermode) === -1 || !gd.calcdata ||
gd.querySelector('.zoombox') || gd._dragging) {
return dragElement.unhoverRaw(gd, evt);
}
var hoverdistance = fullLayout.hoverdistance;
if(hoverdistance === -1) hoverdistance = Infinity;
var spikedistance = fullLayout.spikedistance;
if(spikedistance === -1) spikedistance = Infinity;
// hoverData: the set of candidate points we've found to highlight
var hoverData = [];
// searchData: the data to search in. Mostly this is just a copy of
// gd.calcdata, filtered to the subplot and overlays we're on
// but if a point array is supplied it will be a mapping
// of indicated curves
var searchData = [];
// [x|y]valArray: the axis values of the hover event
// mapped onto each of the currently selected overlaid subplots
var xvalArray, yvalArray;
var itemnum, curvenum, cd, trace, subplotId, subploti, _mode,
xval, yval, pointData, closedataPreviousLength;
// spikePoints: the set of candidate points we've found to draw spikes to
var spikePoints = {
hLinePoint: null,
vLinePoint: null
};
// does subplot have one (or more) horizontal traces?
// This is used to determine whether we rotate the labels or not
var hasOneHorizontalTrace = false;
// Figure out what we're hovering on:
// mouse location or user-supplied data
if(Array.isArray(evt)) {
// user specified an array of points to highlight
hovermode = 'array';
for(itemnum = 0; itemnum < evt.length; itemnum++) {
cd = gd.calcdata[evt[itemnum].curveNumber || 0];
if(cd) {
trace = cd[0].trace;
if(cd[0].trace.hoverinfo !== 'skip') {
searchData.push(cd);
if(trace.orientation === 'h') {
hasOneHorizontalTrace = true;
}
}
}
}
} else {
for(curvenum = 0; curvenum < gd.calcdata.length; curvenum++) {
cd = gd.calcdata[curvenum];
trace = cd[0].trace;
if(trace.hoverinfo !== 'skip' && helpers.isTraceInSubplots(trace, subplots)) {
searchData.push(cd);
if(trace.orientation === 'h') {
hasOneHorizontalTrace = true;
}
}
}
// [x|y]px: the pixels (from top left) of the mouse location
// on the currently selected plot area
// add pointerX|Y property for drawing the spikes in spikesnap 'cursor' situation
var hasUserCalledHover = !evt.target;
var xpx, ypx;
if(hasUserCalledHover) {
if('xpx' in evt) xpx = evt.xpx;
else xpx = xaArray[0]._length / 2;
if('ypx' in evt) ypx = evt.ypx;
else ypx = yaArray[0]._length / 2;
} else {
// fire the beforehover event and quit if it returns false
// note that we're only calling this on real mouse events, so
// manual calls to fx.hover will always run.
if(Events.triggerHandler(gd, 'plotly_beforehover', evt) === false) {
return;
}
// Discover event target, traversing open shadow roots.
var target = evt.composedPath && evt.composedPath()[0];
if(!target) {
// Fallback for browsers not supporting composedPath
target = evt.target;
}
var dbb = target.getBoundingClientRect();
xpx = evt.clientX - dbb.left;
ypx = evt.clientY - dbb.top;
fullLayout._calcInverseTransform(gd);
var transformedCoords = Lib.apply3DTransform(fullLayout._invTransform)(xpx, ypx);
xpx = transformedCoords[0];
ypx = transformedCoords[1];
// in case hover was called from mouseout into hovertext,
// it's possible you're not actually over the plot anymore
if(xpx < 0 || xpx > xaArray[0]._length || ypx < 0 || ypx > yaArray[0]._length) {
return dragElement.unhoverRaw(gd, evt);
}
}
evt.pointerX = xpx + xaArray[0]._offset;
evt.pointerY = ypx + yaArray[0]._offset;
if('xval' in evt) xvalArray = helpers.flat(subplots, evt.xval);
else xvalArray = helpers.p2c(xaArray, xpx);
if('yval' in evt) yvalArray = helpers.flat(subplots, evt.yval);
else yvalArray = helpers.p2c(yaArray, ypx);
if(!isNumeric(xvalArray[0]) || !isNumeric(yvalArray[0])) {
Lib.warn('Fx.hover failed', evt, gd);
return dragElement.unhoverRaw(gd, evt);
}
}
// the pixel distance to beat as a matching point
// in 'x' or 'y' mode this resets for each trace
var distance = Infinity;
// find the closest point in each trace
// this is minimum dx and/or dy, depending on mode
// and the pixel position for the label (labelXpx, labelYpx)
function findHoverPoints(customXVal, customYVal) {
for(curvenum = 0; curvenum < searchData.length; curvenum++) {
cd = searchData[curvenum];
// filter out invisible or broken data
if(!cd || !cd[0] || !cd[0].trace) continue;
trace = cd[0].trace;
if(trace.visible !== true || trace._length === 0) continue;
// Explicitly bail out for these two. I don't know how to otherwise prevent
// the rest of this function from running and failing
if(['carpet', 'contourcarpet'].indexOf(trace._module.name) !== -1) continue;
if(trace.type === 'splom') {
// splom traces do not generate overlay subplots,
// it is safe to assume here splom traces correspond to the 0th subplot
subploti = 0;
subplotId = subplots[subploti];
} else {
subplotId = helpers.getSubplot(trace);
subploti = subplots.indexOf(subplotId);
}
// within one trace mode can sometimes be overridden
_mode = hovermode;
if(helpers.isUnifiedHover(_mode)) {
_mode = _mode.charAt(0);
}
// container for new point, also used to pass info into module.hoverPoints
pointData = {
// trace properties
cd: cd,
trace: trace,
xa: xaArray[subploti],
ya: yaArray[subploti],
// max distances for hover and spikes - for points that want to show but do not
// want to override other points, set distance/spikeDistance equal to max*Distance
// and it will not get filtered out but it will be guaranteed to have a greater
// distance than any point that calculated a real distance.
maxHoverDistance: hoverdistance,
maxSpikeDistance: spikedistance,
// point properties - override all of these
index: false, // point index in trace - only used by plotly.js hoverdata consumers
distance: Math.min(distance, hoverdistance), // pixel distance or pseudo-distance
// distance/pseudo-distance for spikes. This distance should always be calculated
// as if in "closest" mode, and should only be set if this point should
// generate a spike.
spikeDistance: Infinity,
// in some cases the spikes have different positioning from the hover label
// they don't need x0/x1, just one position
xSpike: undefined,
ySpike: undefined,
// where and how to display the hover label
color: Color.defaultLine, // trace color
name: trace.name,
x0: undefined,
x1: undefined,
y0: undefined,
y1: undefined,
xLabelVal: undefined,
yLabelVal: undefined,
zLabelVal: undefined,
text: undefined
};
// add ref to subplot object (non-cartesian case)
if(fullLayout[subplotId]) {
pointData.subplot = fullLayout[subplotId]._subplot;
}
// add ref to splom scene
if(fullLayout._splomScenes && fullLayout._splomScenes[trace.uid]) {
pointData.scene = fullLayout._splomScenes[trace.uid];
}
closedataPreviousLength = hoverData.length;
// for a highlighting array, figure out what
// we're searching for with this element
if(_mode === 'array') {
var selection = evt[curvenum];
if('pointNumber' in selection) {
pointData.index = selection.pointNumber;
_mode = 'closest';
} else {
_mode = '';
if('xval' in selection) {
xval = selection.xval;
_mode = 'x';
}
if('yval' in selection) {
yval = selection.yval;
_mode = _mode ? 'closest' : 'y';
}
}
} else if(customXVal !== undefined && customYVal !== undefined) {
xval = customXVal;
yval = customYVal;
} else {
xval = xvalArray[subploti];
yval = yvalArray[subploti];
}
// Now if there is range to look in, find the points to hover.
if(hoverdistance !== 0) {
if(trace._module && trace._module.hoverPoints) {
var newPoints = trace._module.hoverPoints(pointData, xval, yval, _mode, {
finiteRange: true,
hoverLayer: fullLayout._hoverlayer
});
if(newPoints) {
var newPoint;
for(var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) {
newPoint = newPoints[newPointNum];
if(isNumeric(newPoint.x0) && isNumeric(newPoint.y0)) {
hoverData.push(cleanPoint(newPoint, hovermode));
}
}
}
} else {
Lib.log('Unrecognized trace type in hover:', trace);
}
}
// in closest mode, remove any existing (farther) points
// and don't look any farther than this latest point (or points, some
// traces like box & violin make multiple hover labels at once)
if(hovermode === 'closest' && hoverData.length > closedataPreviousLength) {
hoverData.splice(0, closedataPreviousLength);
distance = hoverData[0].distance;
}
// Now if there is range to look in, find the points to draw the spikelines
// Do it only if there is no hoverData
if(hasCartesian && (spikedistance !== 0)) {
if(hoverData.length === 0) {
pointData.distance = spikedistance;
pointData.index = false;
var closestPoints = trace._module.hoverPoints(pointData, xval, yval, 'closest', {
hoverLayer: fullLayout._hoverlayer
});
if(closestPoints) {
closestPoints = closestPoints.filter(function(point) {
// some hover points, like scatter fills, do not allow spikes,
// so will generate a hover point but without a valid spikeDistance
return point.spikeDistance <= spikedistance;
});
}
if(closestPoints && closestPoints.length) {
var tmpPoint;
var closestVPoints = closestPoints.filter(function(point) {
return point.xa.showspikes && point.xa.spikesnap !== 'hovered data';
});
if(closestVPoints.length) {
var closestVPt = closestVPoints[0];
if(isNumeric(closestVPt.x0) && isNumeric(closestVPt.y0)) {
tmpPoint = fillSpikePoint(closestVPt);
if(!spikePoints.vLinePoint || (spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance)) {
spikePoints.vLinePoint = tmpPoint;
}
}
}
var closestHPoints = closestPoints.filter(function(point) {
return point.ya.showspikes && point.ya.spikesnap !== 'hovered data';
});
if(closestHPoints.length) {
var closestHPt = closestHPoints[0];
if(isNumeric(closestHPt.x0) && isNumeric(closestHPt.y0)) {
tmpPoint = fillSpikePoint(closestHPt);
if(!spikePoints.hLinePoint || (spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance)) {
spikePoints.hLinePoint = tmpPoint;
}
}
}
}
}
}
}
}
findHoverPoints();
function selectClosestPoint(pointsData, spikedistance) {
var resultPoint = null;
var minDistance = Infinity;
var thisSpikeDistance;
for(var i = 0; i < pointsData.length; i++) {
thisSpikeDistance = pointsData[i].spikeDistance;
if(thisSpikeDistance <= minDistance && thisSpikeDistance <= spikedistance) {
resultPoint = pointsData[i];
minDistance = thisSpikeDistance;
}
}
return resultPoint;
}
function fillSpikePoint(point) {
if(!point) return null;
return {
xa: point.xa,
ya: point.ya,
x: point.xSpike !== undefined ? point.xSpike : (point.x0 + point.x1) / 2,
y: point.ySpike !== undefined ? point.ySpike : (point.y0 + point.y1) / 2,
distance: point.distance,
spikeDistance: point.spikeDistance,
curveNumber: point.trace.index,
color: point.color,
pointNumber: point.index
};
}
var spikelineOpts = {
fullLayout: fullLayout,
container: fullLayout._hoverlayer,
outerContainer: fullLayout._paperdiv,
event: evt
};
var oldspikepoints = gd._spikepoints;
var newspikepoints = {
vLinePoint: spikePoints.vLinePoint,
hLinePoint: spikePoints.hLinePoint
};
gd._spikepoints = newspikepoints;
// Now if it is not restricted by spikedistance option, set the points to draw the spikelines
if(hasCartesian && (spikedistance !== 0)) {
if(hoverData.length !== 0) {
var tmpHPointData = hoverData.filter(function(point) {
return point.ya.showspikes;
});
var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance);
spikePoints.hLinePoint = fillSpikePoint(tmpHPoint);
var tmpVPointData = hoverData.filter(function(point) {
return point.xa.showspikes;
});
var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance);
spikePoints.vLinePoint = fillSpikePoint(tmpVPoint);
}
}
// if hoverData is empty check for the spikes to draw and quit if there are none
if(hoverData.length === 0) {
var result = dragElement.unhoverRaw(gd, evt);
if(hasCartesian && ((spikePoints.hLinePoint !== null) || (spikePoints.vLinePoint !== null))) {
if(spikesChanged(oldspikepoints)) {
createSpikelines(gd, spikePoints, spikelineOpts);
}
}
return result;
}
if(hasCartesian) {
if(spikesChanged(oldspikepoints)) {
createSpikelines(gd, spikePoints, spikelineOpts);
}
}
var sortHoverData = function() {
hoverData.sort(function(d1, d2) { return d1.distance - d2.distance; });
// move period positioned points and box/bar-like traces to the end of the list
hoverData = orderRangePoints(hoverData, hovermode);
};
sortHoverData();
if(
helpers.isXYhover(_mode) &&
hoverData[0].length !== 0 &&
hoverData[0].trace.type !== 'splom' // TODO: add support for splom
) {
// pick winning point
var winningPoint = hoverData[0];
// discard other points
if(multipleHoverPoints[winningPoint.trace.type]) {
hoverData = hoverData.filter(function(d) {
return d.trace.index === winningPoint.trace.index;
});
} else {
hoverData = [winningPoint];
}
var initLen = hoverData.length;
var winX = getCoord('x', winningPoint, fullLayout);
var winY = getCoord('y', winningPoint, fullLayout);
// in compare mode, select every point at position
findHoverPoints(winX, winY);
var finalPoints = [];
var seen = {};
var id = 0;
var insert = function(newHd) {
var key = multipleHoverPoints[newHd.trace.type] ? hoverDataKey(newHd) : newHd.trace.index;
if(!seen[key]) {
id++;
seen[key] = id;
finalPoints.push(newHd);
} else {
var oldId = seen[key] - 1;
var oldHd = finalPoints[oldId];
if(oldId > 0 &&
Math.abs(newHd.distance) <
Math.abs(oldHd.distance)
) {
// replace with closest
finalPoints[oldId] = newHd;
}
}
};
var k;
// insert the winnig point(s) first
for(k = 0; k < initLen; k++) {
insert(hoverData[k]);
}
// override from the end
for(k = hoverData.length - 1; k > initLen - 1; k--) {
insert(hoverData[k]);
}
hoverData = finalPoints;
sortHoverData();
}
// lastly, emit custom hover/unhover events
var oldhoverdata = gd._hoverdata;
var newhoverdata = [];
// pull out just the data that's useful to
// other people and send it to the event
for(itemnum = 0; itemnum < hoverData.length; itemnum++) {
var pt = hoverData[itemnum];
var eventData = helpers.makeEventData(pt, pt.trace, pt.cd);
if(pt.hovertemplate !== false) {
var ht = false;
if(pt.cd[pt.index] && pt.cd[pt.index].ht) {
ht = pt.cd[pt.index].ht;
}
pt.hovertemplate = ht || pt.trace.hovertemplate || false;
}
pt.eventData = [eventData];
newhoverdata.push(eventData);
}
gd._hoverdata = newhoverdata;
var rotateLabels = (
(hovermode === 'y' && (searchData.length > 1 || hoverData.length > 1)) ||
(hovermode === 'closest' && hasOneHorizontalTrace && hoverData.length > 1)
);
var bgColor = Color.combine(
fullLayout.plot_bgcolor || Color.background,
fullLayout.paper_bgcolor
);
var labelOpts = {
hovermode: hovermode,
rotateLabels: rotateLabels,
bgColor: bgColor,
container: fullLayout._hoverlayer,
outerContainer: fullLayout._paperdiv,
commonLabelOpts: fullLayout.hoverlabel,
hoverdistance: fullLayout.hoverdistance
};
var hoverLabels = createHoverText(hoverData, labelOpts, gd);
if(!helpers.isUnifiedHover(hovermode)) {
hoverAvoidOverlaps(hoverLabels, rotateLabels ? 'xa' : 'ya', fullLayout);
alignHoverText(hoverLabels, rotateLabels, fullLayout._invScaleX, fullLayout._invScaleY);
} // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true
// we should improve the "fx" API so other plots can use it without these hack.
if(evt.target && evt.target.tagName) {
var hasClickToShow = Registry.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata);
overrideCursor(d3.select(evt.target), hasClickToShow ? 'pointer' : '');
}
// don't emit events if called manually
if(!evt.target || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return;
if(oldhoverdata) {
gd.emit('plotly_unhover', {
event: evt,
points: oldhoverdata
});
}
gd.emit('plotly_hover', {
event: evt,
points: gd._hoverdata,
xaxes: xaArray,
yaxes: yaArray,
xvals: xvalArray,
yvals: yvalArray
});
}
function hoverDataKey(d) {
return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa, d.ya || ''].join(',');
}
var EXTRA_STRING_REGEX = /<extra>([\s\S]*)<\/extra>/;
function createHoverText(hoverData, opts, gd) {
var fullLayout = gd._fullLayout;
var hovermode = opts.hovermode;
var rotateLabels = opts.rotateLabels;
var bgColor = opts.bgColor;
var container = opts.container;
var outerContainer = opts.outerContainer;
var commonLabelOpts = opts.commonLabelOpts || {};
// opts.fontFamily/Size are used for the common label
// and as defaults for each hover label, though the individual labels
// can override this.
var fontFamily = opts.fontFamily || constants.HOVERFONT;
var fontSize = opts.fontSize || constants.HOVERFONTSIZE;
var c0 = hoverData[0];
var xa = c0.xa;
var ya = c0.ya;
var axLetter = hovermode.charAt(0);
var t0 = c0[axLetter + 'Label'];
var outerContainerBB = outerContainer.node().getBoundingClientRect();
var outerTop = outerContainerBB.top;
var outerWidth = outerContainerBB.width;
var outerHeight = outerContainerBB.height;
// show the common label, if any, on the axis
// never show a common label in array mode,
// even if sometimes there could be one
var showCommonLabel = (
(t0 !== undefined) &&
(c0.distance <= opts.hoverdistance) &&
(hovermode === 'x' || hovermode === 'y')
);
// all hover traces hoverinfo must contain the hovermode
// to have common labels
if(showCommonLabel) {
var allHaveZ = true;
var i, traceHoverinfo;
for(i = 0; i < hoverData.length; i++) {
if(allHaveZ && hoverData[i].zLabel === undefined) allHaveZ = false;
traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo;
if(traceHoverinfo) {
var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split('+');
if(parts.indexOf('all') === -1 &&
parts.indexOf(hovermode) === -1) {
showCommonLabel = false;
break;
}
}
}
// xyz labels put all info in their main label, so have no need of a common label
if(allHaveZ) showCommonLabel = false;
}
var commonLabel = container.selectAll('g.axistext')
.data(showCommonLabel ? [0] : []);
commonLabel.enter().append('g')
.classed('axistext', true);
commonLabel.exit().remove();
commonLabel.each(function() {
var label = d3.select(this);
var lpath = Lib.ensureSingle(label, 'path', '', function(s) {
s.style({'stroke-width': '1px'});
});
var ltext = Lib.ensureSingle(label, 'text', '', function(s) {
// prohibit tex interpretation until we can handle
// tex and regular text together
s.attr('data-notex', 1);
});
var commonBgColor = commonLabelOpts.bgcolor || Color.defaultLine;
var commonStroke = commonLabelOpts.bordercolor || Color.contrast(commonBgColor);
var contrastColor = Color.contrast(commonBgColor);
var commonLabelFont = {
family: commonLabelOpts.font.family || fontFamily,
size: commonLabelOpts.font.size || fontSize,
color: commonLabelOpts.font.color || contrastColor
};
lpath.style({
fill: commonBgColor,
stroke: commonStroke
});
ltext.text(t0)
.call(Drawing.font, commonLabelFont)
.call(svgTextUtils.positionText, 0, 0)
.call(svgTextUtils.convertToTspans, gd);
label.attr('transform', '');
var tbb = ltext.node().getBoundingClientRect();
var lx, ly;
if(hovermode === 'x') {
var topsign = xa.side === 'top' ? '-' : '';
ltext.attr('text-anchor', 'middle')
.call(svgTextUtils.positionText, 0, (xa.side === 'top' ?
(outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) :
(outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD)));
lx = xa._offset + (c0.x0 + c0.x1) / 2;
ly = ya._offset + (xa.side === 'top' ? 0 : ya._length);
var halfWidth = tbb.width / 2 + HOVERTEXTPAD;
if(lx < halfWidth) {
lx = halfWidth;
lpath.attr('d', 'M-' + (halfWidth - HOVERARROWSIZE) + ',0' +
'L-' + (halfWidth - HOVERARROWSIZE * 2) + ',' + topsign + HOVERARROWSIZE +
'H' + (HOVERTEXTPAD + tbb.width / 2) +
'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) +
'H-' + halfWidth +
'V' + topsign + HOVERARROWSIZE +
'Z');
} else if(lx > (fullLayout.width - halfWidth)) {
lx = fullLayout.width - halfWidth;
lpath.attr('d', 'M' + (halfWidth - HOVERARROWSIZE) + ',0' +
'L' + halfWidth + ',' + topsign + HOVERARROWSIZE +
'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) +
'H-' + halfWidth +
'V' + topsign + HOVERARROWSIZE +
'H' + (halfWidth - HOVERARROWSIZE * 2) + 'Z');
} else {
lpath.attr('d', 'M0,0' +
'L' + HOVERARROWSIZE + ',' + topsign + HOVERARROWSIZE +
'H' + (HOVERTEXTPAD + tbb.width / 2) +
'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) +
'H-' + (HOVERTEXTPAD + tbb.width / 2) +
'V' + topsign + HOVERARROWSIZE +
'H-' + HOVERARROWSIZE + 'Z');
}
} else {
var anchor;
var sgn;
var leftsign;
if(ya.side === 'right') {
anchor = 'start';
sgn = 1;
leftsign = '';
lx = xa._offset + xa._length;
} else {
anchor = 'end';
sgn = -1;
leftsign = '-';
lx = xa._offset;
}
ly = ya._offset + (c0.y0 + c0.y1) / 2;
ltext.attr('text-anchor', anchor);
lpath.attr('d', 'M0,0' +
'L' + leftsign + HOVERARROWSIZE + ',' + HOVERARROWSIZE +
'V' + (HOVERTEXTPAD + tbb.height / 2) +
'h' + leftsign + (HOVERTEXTPAD * 2 + tbb.width) +
'V-' + (HOVERTEXTPAD + tbb.height / 2) +
'H' + leftsign + HOVERARROWSIZE + 'V-' + HOVERARROWSIZE + 'Z');
var halfHeight = tbb.height / 2;
var lty = outerTop - tbb.top - halfHeight;
var clipId = 'clip' + fullLayout._uid + 'commonlabel' + ya._id;
var clipPath;
if(lx < (tbb.width + 2 * HOVERTEXTPAD + HOVERARROWSIZE)) {
clipPath = 'M-' + (HOVERARROWSIZE + HOVERTEXTPAD) + '-' + halfHeight +
'h-' + (tbb.width - HOVERTEXTPAD) +
'V' + halfHeight +
'h' + (tbb.width - HOVERTEXTPAD) + 'Z';
var ltx = tbb.width - lx + HOVERTEXTPAD;
svgTextUtils.positionText(ltext, ltx, lty);
// shift each line (except the longest) so that start-of-line
// is always visible
if(anchor === 'end') {
ltext.selectAll('tspan').each(function() {
var s = d3.select(this);
var dummy = Drawing.tester.append('text')
.text(s.text())
.call(Drawing.font, commonLabelFont);
var dummyBB = dummy.node().getBoundingClientRect();
if(Math.round(dummyBB.width) < Math.round(tbb.width)) {
s.attr('x', ltx - dummyBB.width);
}
dummy.remove();
});
}
} else {
svgTextUtils.positionText(ltext, sgn * (HOVERTEXTPAD + HOVERARROWSIZE), lty);
clipPath = null;
}
var textClip = fullLayout._topclips.selectAll('#' + clipId).data(clipPath ? [0] : []);
textClip.enter().append('clipPath').attr('id', clipId).append('path');
textClip.exit().remove();
textClip.select('path').attr('d', clipPath);
Drawing.setClipUrl(ltext, clipPath ? clipId : null, gd);
}
label.attr('transform', strTranslate(lx, ly));
});
// Show a single hover label
if(helpers.isUnifiedHover(hovermode)) {
// Delete leftover hover labels from other hovermodes
container.selectAll('g.hovertext').remove();
// Return early if nothing is hovered on
if(hoverData.length === 0) return;
// mock legend
var mockLayoutIn = {
showlegend: true,
legend: {
title: {text: t0, font: fullLayout.hoverlabel.font},
font: fullLayout.hoverlabel.font,
bgcolor: fullLayout.hoverlabel.bgcolor,
bordercolor: fullLayout.hoverlabel.bordercolor,
borderwidth: 1,
tracegroupgap: 7,
traceorder: fullLayout.legend ? fullLayout.legend.traceorder : undefined,
orientation: 'v'
}
};
var mockLayoutOut = {};
legendSupplyDefaults(mockLayoutIn, mockLayoutOut, gd._fullData);
var mockLegend = mockLayoutOut.legend;
// prepare items for the legend
mockLegend.entries = [];
for(var j = 0; j < hoverData.length; j++) {
var texts = getHoverLabelText(hoverData[j], true, hovermode, fullLayout, t0);
var text = texts[0];
var name = texts[1];
var pt = hoverData[j];
pt.name = name;
if(name !== '') {
pt.text = name + ' : ' + text;
} else {
pt.text = text;
}
// pass through marker's calcdata to style legend items
var cd = pt.cd[pt.index];
if(cd) {
if(cd.mc) pt.mc = cd.mc;
if(cd.mcc) pt.mc = cd.mcc;
if(cd.mlc) pt.mlc = cd.mlc;
if(cd.mlcc) pt.mlc = cd.mlcc;
if(cd.mlw) pt.mlw = cd.mlw;
if(cd.mrc) pt.mrc = cd.mrc;
if(cd.dir) pt.dir = cd.dir;
}
pt._distinct = true;
mockLegend.entries.push([pt]);
}
mockLegend.entries.sort(function(a, b) { return a[0].trace.index - b[0].trace.index;});
mockLegend.layer = container;
// Draw unified hover label
mockLegend._inHover = true;
legendDraw(gd, mockLegend);
// Position the hover
var lyBottom, lyTop;
if(axLetter === 'y') {
lyTop = Math.min.apply(null, hoverData.map(function(c) { return Math.min(c.y0, c.y1);}));
lyBottom = Math.max.apply(null, hoverData.map(function(c) {return Math.max(c.y0, c.y1);}));
} else {
lyTop = lyBottom = Lib.mean(hoverData.map(function(c) {return (c.y0 + c.y1) / 2;}));
}
var lxRight, lxLeft;
if(axLetter === 'x') {
lxRight = Math.max.apply(null, hoverData.map(function(c) {return Math.max(c.x0, c.x1);}));
lxLeft = Math.min.apply(null, hoverData.map(function(c) {return Math.min(c.x0, c.x1);}));
} else {
lxRight = lxLeft = Lib.mean(hoverData.map(function(c) {return (c.x0 + c.x1) / 2;}));
}
var legendContainer = container.select('g.legend');
var tbb = legendContainer.node().getBoundingClientRect();
var tWidth = tbb.width;
var tHeight = tbb.height;
var xOffset = xa._offset;
var yOffset = ya._offset;
lyBottom += yOffset + HOVERTEXTPAD;
lxRight += xOffset + HOVERTEXTPAD;
lxLeft += xOffset - tWidth - HOVERTEXTPAD;
lyTop += yOffset - tHeight - HOVERTEXTPAD;
var lx, ly;
// horizontal alignment to end up on screen
if(lxRight + tWidth + HOVERTEXTPAD <= outerWidth && lxRight - HOVERTEXTPAD >= 0) {
lx = lxRight;
} else if(lxLeft + HOVERTEXTPAD <= outerWidth && lxLeft - HOVERTEXTPAD >= 0) {
lx = lxLeft;
} else {
lx = xOffset;
}
// vertical alignement to end up on screen
if(lyBottom + tHeight + HOVERTEXTPAD <= outerHeight && lyBottom - HOVERTEXTPAD >= 0) {
ly = lyBottom;
} else if(lyTop + HOVERTEXTPAD <= outerHeight && lyTop - HOVERTEXTPAD >= 0) {
ly = lyTop;
} else {
ly = yOffset;
}
legendContainer.attr('transform', strTranslate(lx, ly));
return legendContainer;
}
// show all the individual labels
// first create the objects
var hoverLabels = container.selectAll('g.hovertext')
.data(hoverData, function(d) {
// N.B. when multiple items have the same result key-function value,
// only the first of those items in hoverData gets rendered
return hoverDataKey(d);
});
hoverLabels.enter().append('g')
.classed('hovertext', true)
.each(function() {
var g = d3.select(this);
// trace name label (rect and text.name)
g.append('rect')
.call(Color.fill, Color.addOpacity(bgColor, 0.8));
g.append('text').classed('name', true);
// trace data label (path and text.nums)
g.append('path')
.style('stroke-width', '1px');
g.append('text').classed('nums', true)
.call(Drawing.font, fontFamily, fontSize);
});
hoverLabels.exit().remove();
// then put the text in, position the pointer to the data,
// and figure out sizes
hoverLabels.each(function(d) {
var g = d3.select(this).attr('transform', '');
var dColor = d.color;
if(Array.isArray(dColor)) {
dColor = dColor[d.eventData[0].pointNumber];
}
// combine possible non-opaque trace color with bgColor
var color0 = d.bgcolor || dColor;
// color for 'nums' part of the label
var numsColor = Color.combine(
Color.opacity(color0) ? color0 : Color.defaultLine,
bgColor
);
// color for 'name' part of the label
var nameColor = Color.combine(
Color.opacity(dColor) ? dColor : Color.defaultLine,
bgColor
);
// find a contrasting color for border and text
var contrastColor = d.borderColor || Color.contrast(numsColor);
var texts = getHoverLabelText(d, showCommonLabel, hovermode, fullLayout, t0, g);
var text = texts[0];
var name = texts[1];
// main label
var tx = g.select('text.nums')
.call(Drawing.font,
d.fontFamily || fontFamily,
d.fontSize || fontSize,
d.fontColor || contrastColor)
.text(text)
.attr('data-notex', 1)
.call(svgTextUtils.positionText, 0, 0)
.call(svgTextUtils.convertToTspans, gd);
var tx2 = g.select('text.name');
var tx2width = 0;
var tx2height = 0;
// secondary label for non-empty 'name'
if(name && name !== text) {
tx2.call(Drawing.font,
d.fontFamily || fontFamily,
d.fontSize || fontSize,
nameColor)
.text(name)
.attr('data-notex', 1)
.call(svgTextUtils.positionText, 0, 0)
.call(svgTextUtils.convertToTspans, gd);
var t2bb = tx2.node().getBoundingClientRect();
tx2width = t2bb.width + 2 * HOVERTEXTPAD;
tx2height = t2bb.height + 2 * HOVERTEXTPAD;
} else {
tx2.remove();
g.select('rect').remove();
}
g.select('path').style({
fill: numsColor,
stroke: contrastColor
});
var tbb = tx.node().getBoundingClientRect();
var htx = d.xa._offset + (d.x0 + d.x1) / 2;
var hty = d.ya._offset + (d.y0 + d.y1) / 2;
var dx = Math.abs(d.x1 - d.x0);
var dy = Math.abs(d.y1 - d.y0);
var txTotalWidth = tbb.width + HOVERARROWSIZE + HOVERTEXTPAD + tx2width;
var anchorStartOK, anchorEndOK;
d.ty0 = outerTop - tbb.top;
d.bx = tbb.width + 2 * HOVERTEXTPAD;
d.by = Math.max(tbb.height + 2 * HOVERTEXTPAD, tx2height);
d.anchor = 'start';
d.txwidth = tbb.width;
d.tx2width = tx2width;
d.offset = 0;
if(rotateLabels) {
d.pos = htx;
anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight;
anchorEndOK = hty - dy / 2 - txTotalWidth >= 0;
if((d.idealAlign === 'top' || !anchorStartOK) && anchorEndOK) {
hty -= dy / 2;
d.anchor = 'end';
} else if(anchorStartOK) {
hty += dy / 2;
d.anchor = 'start';
} else d.anchor = 'middle';
} else {
d.pos = hty;
anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth;
anchorEndOK = htx - dx / 2 - txTotalWidth >= 0;
if((d.idealAlign === 'left' || !anchorStartOK) && anchorEndOK) {
htx -= dx / 2;
d.anchor = 'end';
} else if(anchorStartOK) {
htx += dx / 2;
d.anchor = 'start';
} else {
d.anchor = 'middle';
var txHalfWidth = txTotalWidth / 2;
var overflowR = htx + txHalfWidth - outerWidth;
var overflowL = htx - txHalfWidth;
if(overflowR > 0) htx -= overflowR;
if(overflowL < 0) htx += -overflowL;
}
}
tx.attr('text-anchor', d.anchor);
if(tx2width) tx2.attr('text-anchor', d.anchor);
g.attr('transform', strTranslate(htx, hty) +
(rotateLabels ? strRotate(YANGLE) : ''));
});
return hoverLabels;
}
function getHoverLabelText(d, showCommonLabel, hovermode, fullLayout, t0, g) {
var name = '';
var text = '';
// to get custom 'name' labels pass cleanPoint
if(d.nameOverride !== undefined) d.name = d.nameOverride;
if(d.name) {
if(d.trace._meta) {
d.name = Lib.templateString(d.name, d.trace._meta);
}
name = plainText(d.name, d.nameLength);
}
var h0 = hovermode.charAt(0);
var h1 = h0 === 'x' ? 'y' : 'x';
if(d.zLabel !== undefined) {
if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '<br>';
if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '<br>';
if(d.trace.type !== 'choropleth' && d.trace.type !== 'choroplethmapbox') {
text += (text ? 'z: ' : '') + d.zLabel;
}
} else if(showCommonLabel && d[h0 + 'Label'] === t0) {
text = d[h1 + 'Label'] || '';
} else if(d.xLabel === undefined) {
if(d.yLabel !== undefined && d.trace.type !== 'scattercarpet') {
text = d.yLabel;
}
} else if(d.yLabel === undefined) text = d.xLabel;
else text = '(' + d.xLabel + ', ' + d.yLabel + ')';
if((d.text || d.text === 0) && !Array.isArray(d.text)) {
text += (text ? '<br>' : '') + d.text;
}
// used by other modules (initially just ternary) that
// manage their own hoverinfo independent of cleanPoint
// the rest of this will still apply, so such modules
// can still put things in (x|y|z)Label, text, and name
// and hoverinfo will still determine their visibility
if(d.extraText !== undefined) text += (text ? '<br>' : '') + d.extraText;
// if 'text' is empty at this point,
// and hovertemplate is not defined,
// put 'name' in main label and don't show secondary label
if(g && text === '' && !d.hovertemplate) {
// if 'name' is also empty, remove entire label
if(name === '') g.remove();
text = name;
}
// hovertemplate
var hovertemplate = d.hovertemplate || false;
if(hovertemplate) {
var labels = d.hovertemplateLabels || d;
if(d[h0 + 'Label'] !== t0) {
labels[h0 + 'other'] = labels[h0 + 'Val'];
labels[h0 + 'otherLabel'] = labels[h0 + 'Label'];
}
text = Lib.hovertemplateString(
hovertemplate,
labels,
fullLayout._d3locale,
d.eventData[0] || {},
d.trace._meta
);
text = text.replace(EXTRA_STRING_REGEX, function(match, extra) {
// assign name for secondary text label
name = plainText(extra, d.nameLength);
// remove from main text label
return '';
});
}
return [text, name];
}
// Make groups of touching points, and within each group
// move each point so that no labels overlap, but the average
// label position is the same as it was before moving. Incidentally,
// this is equivalent to saying all the labels are on equal linear
// springs about their initial position. Initially, each point is
// its own group, but as we find overlaps we will clump the points.
//
// Also, there are hard constraints at the edges of the graphs,
// that push all groups to the middle so they are visible. I don't
// know what happens if the group spans all the way from one edge to
// the other, though it hardly matters - there's just too much
// information then.
function hoverAvoidOverlaps(hoverLabels, axKey, fullLayout) {
var nummoves = 0;
var axSign = 1;
var nLabels = hoverLabels.size();
// make groups of touching points
var pointgroups = new Array(nLabels);
var k = 0;
hoverLabels.each(function(d) {
var ax = d[axKey];
var axIsX = ax._id.charAt(0) === 'x';
var rng = ax.range;
if(k === 0 && rng && ((rng[0] > rng[1]) !== axIsX)) {
axSign = -1;
}
pointgroups[k++] = [{
datum: d,
traceIndex: d.trace.index,
dp: 0,
pos: d.pos,
posref: d.posref,
size: d.by * (axIsX ? YFACTOR : 1) / 2,
pmin: 0,
pmax: (axIsX ? fullLayout.width : fullLayout.height)
}];
});
pointgroups.sort(function(a, b) {
return (a[0].posref - b[0].posref) ||
// for equal positions, sort trace indices increasing or decreasing
// depending on whether the axis is reversed or not... so stacked
// traces will generally keep their order even if one trace adds
// nothing to the stack.
(axSign * (b[0].traceIndex - a[0].traceIndex));
});
var donepositioning, topOverlap, bottomOverlap, i, j, pti, sumdp;
function constrainGroup(grp) {
var minPt = grp[0];
var maxPt = grp[grp.length - 1];
// overlap with the top - positive vals are overlaps
topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size;
// overlap with the bottom - positive vals are overlaps
bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax;
// check for min overlap first, so that we always
// see the largest labels
// allow for .01px overlap, so we don't get an
// infinite loop from rounding errors
if(topOverlap > 0.01) {
for(j = grp.length - 1; j >= 0; j--) grp[j].dp += topOverlap;
donepositioning = false;
}
if(bottomOverlap < 0.01) return;
if(topOverlap < -0.01) {
// make sure we're not pushing back and forth
for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap;
donepositioning = false;
}
if(!donepositioning) return;
// no room to fix positioning, delete off-screen points
// first see how many points we need to delete
var deleteCount = 0;
for(i = 0; i < grp.length; i++) {
pti = grp[i];
if(pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++;
}
// start by deleting points whose data is off screen
for(i = grp.length - 1; i >= 0; i--) {
if(deleteCount <= 0) break;
pti = grp[i];
// pos has already been constrained to [pmin,pmax]
// so look for points close to that to delete
if(pti.pos > minPt.pmax - 1) {
pti.del = true;
deleteCount--;
}
}
for(i = 0; i < grp.length; i++) {
if(deleteCount <= 0) break;
pti = grp[i];
// pos has already been constrained to [pmin,pmax]
// so look for points close to that to delete
if(pti.pos < minPt.pmin + 1) {
pti.del = true;
deleteCount--;
// shift the whole group minus into this new space
bottomOverlap = pti.size * 2;
for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap;
}
}
// then delete points that go off the bottom
for(i = grp.length - 1; i >= 0; i--) {
if(deleteCount <= 0) break;
pti = grp[i];
if(pti.pos + pti.dp + pti.size > minPt.pmax) {
pti.del = true;
deleteCount--;
}
}
}
// loop through groups, combining them if they overlap,
// until nothing moves
while(!donepositioning && nummoves <= nLabels) {
// to avoid infinite loops, don't move more times
// than there are traces
nummoves++;
// assume nothing will move in this iteration,
// reverse this if it does
donepositioning = true;
i = 0;
while(i < pointgroups.length - 1) {
// the higher (g0) and lower (g1) point group
var g0 = pointgroups[i];
var g1 = pointgroups[i + 1];
// the lowest point in the higher group (p0)
// the highest point in the lower group (p1)
var p0 = g0[g0.length - 1];
var p1 = g1[0];
topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size;
// Only group points that lie on the same axes
if(topOverlap > 0.01 && (p0.pmin === p1.pmin) && (p0.pmax === p1.pmax)) {
// push the new point(s) added to this group out of the way
for(j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap;
// add them to the group
g0.push.apply(g0, g1);
pointgroups.splice(i + 1, 1);
// adjust for minimum average movement
sumdp = 0;
for(j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp;
bottomOverlap = sumdp / g0.length;
for(j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap;
donepositioning = false;
} else i++;
}
// check if we're going off the plot on either side and fix
pointgroups.forEach(constrainGroup);
}
// now put these offsets into hoverData
for(i = pointgroups.length - 1; i >= 0; i--) {
var grp = pointgroups[i];
for(j = grp.length - 1; j >= 0; j--) {
var pt = grp[j];
var hoverPt = pt.datum;
hoverPt.offset = pt.dp;
hoverPt.del = pt.del;
}
}
}
function alignHoverText(hoverLabels, rotateLabels, scaleX, scaleY) {
var pX = function(x) { return x * scaleX; };
var pY = function(y) { return y * scaleY; };
// finally set the text positioning relative to the data and draw the
// box around it
hoverLabels.each(function(d) {
var g = d3.select(this);
if(d.del) return g.remove();
var tx = g.select('text.nums');
var anchor = d.anchor;
var horzSign = anchor === 'end' ? -1 : 1;
var alignShift = {start: 1, end: -1, middle: 0}[anchor];
var txx = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD);
var tx2x = txx + alignShift * (d.txwidth + HOVERTEXTPAD);
var offsetX = 0;
var offsetY = d.offset;
var isMiddle = anchor === 'middle';
if(isMiddle) {
txx -= d.tx2width / 2;
tx2x += d.txwidth / 2 + HOVERTEXTPAD;
}
if(rotateLabels) {
offsetY *= -YSHIFTY;
offsetX = d.offset * YSHIFTX;
}
g.select('path')
.attr('d', isMiddle ?
// middle aligned: rect centered on data
('M-' + pX(d.bx / 2 + d.tx2width / 2) + ',' + pY(offsetY - d.by / 2) +
'h' + pX(d.bx) + 'v' + pY(d.by) + 'h-' + pX(d.bx) + 'Z') :
// left or right aligned: side rect with arrow to data
('M0,0L' + pX(horzSign * HOVERARROWSIZE + offsetX) + ',' + pY(HOVERARROWSIZE + offsetY) +
'v' + pY(d.by / 2 - HOVERARROWSIZE) +
'h' + pX(horzSign * d.bx) +
'v-' + pY(d.by) +
'H' + pX(horzSign * HOVERARROWSIZE + offsetX) +
'V' + pY(offsetY - HOVERARROWSIZE) +
'Z'));
var posX = offsetX + txx;
var posY = offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD;
var textAlign = d.textAlign || 'auto';
if(textAlign !== 'auto') {
if(textAlign === 'left' && anchor !== 'start') {
tx.attr('text-anchor', 'start');
posX = isMiddle ?
-d.bx / 2 - d.tx2width / 2 + HOVERTEXTPAD :
-d.bx - HOVERTEXTPAD;
} else if(textAlign === 'right' && anchor !== 'end') {
tx.attr('text-anchor', 'end');
posX = isMiddle ?
d.bx / 2 - d.tx2width / 2 - HOVERTEXTPAD :
d.bx + HOVERTEXTPAD;
}
}
tx.call(svgTextUtils.positionText, pX(posX), pY(posY));
if(d.tx2width) {
g.select('text.name')
.call(svgTextUtils.positionText,
pX(tx2x + alignShift * HOVERTEXTPAD + offsetX),
pY(offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD));
g.select('rect')
.call(Drawing.setRect,
pX(tx2x + (alignShift - 1) * d.tx2width / 2 + offsetX),
pY(offsetY - d.by / 2 - 1),
pX(d.tx2width), pY(d.by + 2));
}
});
}
function cleanPoint(d, hovermode) {
var index = d.index;
var trace = d.trace || {};
var cd0 = d.cd[0];
var cd = d.cd[index] || {};
function pass(v) {
return v || (isNumeric(v) && v === 0);
}
var getVal = Array.isArray(index) ?
function(calcKey, traceKey) {
var v = Lib.castOption(cd0, index, calcKey);
return pass(v) ? v : Lib.extractOption({}, trace, '', traceKey);
} :
function(calcKey, traceKey) {
return Lib.extractOption(cd, trace, calcKey, traceKey);
};
function fill(key, calcKey, traceKey) {
var val = getVal(calcKey, traceKey);
if(pass(val)) d[key] = val;
}
fill('hoverinfo', 'hi', 'hoverinfo');
fill('bgcolor', 'hbg', 'hoverlabel.bgcolor');
fill('borderColor', 'hbc', 'hoverlabel.bordercolor');
fill('fontFamily', 'htf', 'hoverlabel.font.family');
fill('fontSize', 'hts', 'hoverlabel.font.size');
fill('fontColor', 'htc', 'hoverlabel.font.color');
fill('nameLength', 'hnl', 'hoverlabel.namelength');
fill('textAlign', 'hta', 'hoverlabel.align');
d.posref = (hovermode === 'y' || (hovermode === 'closest' && trace.orientation === 'h')) ?
(d.xa._offset + (d.x0 + d.x1) / 2) :
(d.ya._offset + (d.y0 + d.y1) / 2);
// then constrain all the positions to be on the plot
d.x0 = Lib.constrain(d.x0, 0, d.xa._length);
d.x1 = Lib.constrain(d.x1, 0, d.xa._length);
d.y0 = Lib.constrain(d.y0, 0, d.ya._length);
d.y1 = Lib.constrain(d.y1, 0, d.ya._length);
// and convert the x and y label values into formatted text
if(d.xLabelVal !== undefined) {
d.xLabel = ('xLabel' in d) ? d.xLabel : Axes.hoverLabelText(d.xa, d.xLabelVal, trace.xhoverformat);
d.xVal = d.xa.c2d(d.xLabelVal);
}
if(d.yLabelVal !== undefined) {
d.yLabel = ('yLabel' in d) ? d.yLabel : Axes.hoverLabelText(d.ya, d.yLabelVal, trace.yhoverformat);
d.yVal = d.ya.c2d(d.yLabelVal);
}
// Traces like heatmaps generate the zLabel in their hoverPoints function
if(d.zLabelVal !== undefined && d.zLabel === undefined) {
d.zLabel = String(d.zLabelVal);
}
// for box means and error bars, add the range to the label
if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) {
var xeText = Axes.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text;
if(d.xerrneg !== undefined) {
d.xLabel += ' +' + xeText + ' / -' +
Axes.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text;
} else d.xLabel += ' ± ' + xeText;
// small distance penalty for error bars, so that if there are
// traces with errors and some without, the error bar label will
// hoist up to the point
if(hovermode === 'x') d.distance += 1;
}
if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) {
var yeText = Axes.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text;
if(d.yerrneg !== undefined) {
d.yLabel += ' +' + yeText + ' / -' +
Axes.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text;
} else d.yLabel += ' ± ' + yeText;
if(hovermode === 'y') d.distance += 1;
}
var infomode = d.hoverinfo || d.trace.hoverinfo;
if(infomode && infomode !== 'all') {
infomode = Array.isArray(infomode) ? infomode : infomode.split('+');
if(infomode.indexOf('x') === -1) d.xLabel = undefined;
if(infomode.indexOf('y') === -1) d.yLabel = undefined;
if(infomode.indexOf('z') === -1) d.zLabel = undefined;
if(infomode.indexOf('text') === -1) d.text = undefined;
if(infomode.indexOf('name') === -1) d.name = undefined;
}
return d;
}
function createSpikelines(gd, closestPoints, opts) {
var container = opts.container;
var fullLayout = opts.fullLayout;
var gs = fullLayout._size;
var evt = opts.event;
var showY = !!closestPoints.hLinePoint;
var showX = !!closestPoints.vLinePoint;
var xa, ya;
// Remove old spikeline items
container.selectAll('.spikeline').remove();
if(!(showX || showY)) return;
var contrastColor = Color.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor);
// Horizontal line (to y-axis)
if(showY) {
var hLinePoint = closestPoints.hLinePoint;
var hLinePointX, hLinePointY;
xa = hLinePoint && hLinePoint.xa;
ya = hLinePoint && hLinePoint.ya;
var ySnap = ya.spikesnap;
if(ySnap === 'cursor') {
hLinePointX = evt.pointerX;
hLinePointY = evt.pointerY;
} else {
hLinePointX = xa._offset + hLinePoint.x;
hLinePointY = ya._offset + hLinePoint.y;
}
var dfltHLineColor = tinycolor.readability(hLinePoint.color, contrastColor) < 1.5 ?
Color.contrast(contrastColor) : hLinePoint.color;
var yMode = ya.spikemode;
var yThickness = ya.spikethickness;
var yColor = ya.spikecolor || dfltHLineColor;
var xEdge = Axes.getPxPosition(gd, ya);
var xBase, xEndSpike;
if(yMode.indexOf('toaxis') !== -1 || yMode.indexOf('across') !== -1) {
if(yMode.indexOf('toaxis') !== -1) {
xBase = xEdge;
xEndSpike = hLinePointX;
}
if(yMode.indexOf('across') !== -1) {
var xAcross0 = ya._counterDomainMin;
var xAcross1 = ya._counterDomainMax;
if(ya.anchor === 'free') {
xAcross0 = Math.min(xAcross0, ya.position);
xAcross1 = Math.max(xAcross1, ya.position);
}
xBase = gs.l + xAcross0 * gs.w;
xEndSpike = gs.l + xAcross1 * gs.w;
}
// Foreground horizontal line (to y-axis)
container.insert('line', ':first-child')
.attr({
x1: xBase,
x2: xEndSpike,
y1: hLinePointY,
y2: hLinePointY,
'stroke-width': yThickness,
stroke: yColor,
'stroke-dasharray': Drawing.dashStyle(ya.spikedash, yThickness)
})
.classed('spikeline', true)
.classed('crisp', true);
// Background horizontal Line (to y-axis)
container.insert('line', ':first-child')
.attr({
x1: xBase,
x2: xEndSpike,
y1: hLinePointY,
y2: hLinePointY,
'stroke-width': yThickness + 2,
stroke: contrastColor
})
.classed('spikeline', true)
.classed('crisp', true);
}
// Y axis marker
if(yMode.indexOf('marker') !== -1) {
container.insert('circle', ':first-child')
.attr({
cx: xEdge + (ya.side !== 'right' ? yThickness : -yThickness),
cy: hLinePointY,
r: yThickness,
fill: yColor
})
.classed('spikeline', true);
}
}
if(showX) {
var vLinePoint = closestPoints.vLinePoint;
var vLinePointX, vLinePointY;
xa = vLinePoint && vLinePoint.xa;
ya = vLinePoint && vLinePoint.ya;
var xSnap = xa.spikesnap;
if(xSnap === 'cursor') {
vLinePointX = evt.pointerX;
vLinePointY = evt.pointerY;
} else {
vLinePointX = xa._offset + vLinePoint.x;
vLinePointY = ya._offset + vLinePoint.y;
}
var dfltVLineColor = tinycolor.readability(vLinePoint.color, contrastColor) < 1.5 ?
Color.contrast(contrastColor) : vLinePoint.color;
var xMode = xa.spikemode;
var xThickness = xa.spikethickness;
var xColor = xa.spikecolor || dfltVLineColor;
var yEdge = Axes.getPxPosition(gd, xa);
var yBase, yEndSpike;
if(xMode.indexOf('toaxis') !== -1 || xMode.indexOf('across') !== -1) {
if(xMode.indexOf('toaxis') !== -1) {
yBase = yEdge;
yEndSpike = vLinePointY;
}
if(xMode.indexOf('across') !== -1) {
var yAcross0 = xa._counterDomainMin;
var yAcross1 = xa._counterDomainMax;
if(xa.anchor === 'free') {
yAcross0 = Math.min(yAcross0, xa.position);
yAcross1 = Math.max(yAcross1, xa.position);
}
yBase = gs.t + (1 - yAcross1) * gs.h;
yEndSpike = gs.t + (1 - yAcross0) * gs.h;
}
// Foreground vertical line (to x-axis)
container.insert('line', ':first-child')
.attr({
x1: vLinePointX,
x2: vLinePointX,
y1: yBase,
y2: yEndSpike,
'stroke-width': xThickness,
stroke: xColor,
'stroke-dasharray': Drawing.dashStyle(xa.spikedash, xThickness)
})
.classed('spikeline', true)
.classed('crisp', true);
// Background vertical line (to x-axis)
container.insert('line', ':first-child')
.attr({
x1: vLinePointX,
x2: vLinePointX,
y1: yBase,
y2: yEndSpike,
'stroke-width': xThickness + 2,
stroke: contrastColor
})
.classed('spikeline', true)
.classed('crisp', true);
}
// X axis marker
if(xMode.indexOf('marker') !== -1) {
container.insert('circle', ':first-child')
.attr({
cx: vLinePointX,
cy: yEdge - (xa.side !== 'top' ? xThickness : -xThickness),
r: xThickness,
fill: xColor
})
.classed('spikeline', true);
}
}
}
function hoverChanged(gd, evt, oldhoverdata) {
// don't emit any events if nothing changed
if(!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true;
for(var i = oldhoverdata.length - 1; i >= 0; i--) {
var oldPt = oldhoverdata[i];
var newPt = gd._hoverdata[i];
if(oldPt.curveNumber !== newPt.curveNumber ||
String(oldPt.pointNumber) !== String(newPt.pointNumber) ||
String(oldPt.pointNumbers) !== String(newPt.pointNumbers)
) {
return true;
}
}
return false;
}
function spikesChanged(gd, oldspikepoints) {
// don't relayout the plot because of new spikelines if spikelines points didn't change
if(!oldspikepoints) return true;
if(oldspikepoints.vLinePoint !== gd._spikepoints.vLinePoint ||
oldspikepoints.hLinePoint !== gd._spikepoints.hLinePoint
) return true;
return false;
}
function plainText(s, len) {
return svgTextUtils.plainText(s || '', {
len: len,
allowedTags: ['br', 'sub', 'sup', 'b', 'i', 'em']
});
}
function orderRangePoints(hoverData, hovermode) {
var axLetter = hovermode.charAt(0);
var first = [];
var second = [];
var last = [];
for(var i = 0; i < hoverData.length; i++) {
var d = hoverData[i];
if(
Registry.traceIs(d.trace, 'bar-like') ||
Registry.traceIs(d.trace, 'box-violin')
) {
last.push(d);
} else if(d.trace[axLetter + 'period']) {
second.push(d);
} else {
first.push(d);
}
}
return first.concat(second).concat(last);
}
function getCoord(axLetter, winningPoint, fullLayout) {
var ax = winningPoint[axLetter + 'a'];
var val = winningPoint[axLetter + 'Val'];
if(ax.type === 'category') val = ax._categoriesMap[val];
else if(ax.type === 'date') {
var period = winningPoint[axLetter + 'Period'];
val = ax.d2c(period !== undefined ? period : val);
}
var cd0 = winningPoint.cd[winningPoint.index];
if(cd0 && cd0.t && cd0.t.posLetter === ax._id) {
if(
fullLayout.boxmode === 'group' ||
fullLayout.violinmode === 'group'
) {
val += cd0.t.dPos;
}
}
return val;
}
|
simplify logic and handle the case of not fitting inside the subplot
|
src/components/fx/hover.js
|
simplify logic and handle the case of not fitting inside the subplot
|
<ide><path>rc/components/fx/hover.js
<ide>
<ide> var legendContainer = container.select('g.legend');
<ide> var tbb = legendContainer.node().getBoundingClientRect();
<del> var tWidth = tbb.width;
<del> var tHeight = tbb.height;
<add> var tWidth = tbb.width + 2 * HOVERTEXTPAD;
<add> var tHeight = tbb.height + 2 * HOVERTEXTPAD;
<ide>
<ide> var xOffset = xa._offset;
<ide> var yOffset = ya._offset;
<del> lyBottom += yOffset + HOVERTEXTPAD;
<del> lxRight += xOffset + HOVERTEXTPAD;
<del> lxLeft += xOffset - tWidth - HOVERTEXTPAD;
<del> lyTop += yOffset - tHeight - HOVERTEXTPAD;
<del>
<del> var lx, ly;
<add> lyBottom += yOffset;
<add> lxRight += xOffset;
<add> lxLeft += xOffset - tWidth;
<add> lyTop += yOffset - tHeight;
<add>
<add> var lx, ly; // top and left positions of the hover box
<ide>
<ide> // horizontal alignment to end up on screen
<del> if(lxRight + tWidth + HOVERTEXTPAD <= outerWidth && lxRight - HOVERTEXTPAD >= 0) {
<add> if(lxRight + tWidth <= outerWidth && lxRight >= 0) {
<ide> lx = lxRight;
<del> } else if(lxLeft + HOVERTEXTPAD <= outerWidth && lxLeft - HOVERTEXTPAD >= 0) {
<add> } else if(lxLeft + tWidth <= outerWidth && lxLeft >= 0) {
<ide> lx = lxLeft;
<add> } else if(xOffset + tWidth <= outerWidth) {
<add> lx = xOffset; // subplot left corner
<ide> } else {
<del> lx = xOffset;
<del> }
<add> lx = 0; // paper left corner
<add> }
<add> lx += HOVERTEXTPAD;
<ide>
<ide> // vertical alignement to end up on screen
<del> if(lyBottom + tHeight + HOVERTEXTPAD <= outerHeight && lyBottom - HOVERTEXTPAD >= 0) {
<add> if(lyBottom + tHeight <= outerHeight && lyBottom >= 0) {
<ide> ly = lyBottom;
<del> } else if(lyTop + HOVERTEXTPAD <= outerHeight && lyTop - HOVERTEXTPAD >= 0) {
<add> } else if(lyTop + tHeight <= outerHeight && lyTop >= 0) {
<ide> ly = lyTop;
<add> } else if(yOffset + tHeight <= outerHeight) {
<add> ly = yOffset; // subplot top corner
<ide> } else {
<del> ly = yOffset;
<del> }
<add> ly = 0; // paper top corner
<add> }
<add> ly += HOVERTEXTPAD;
<ide>
<ide> legendContainer.attr('transform', strTranslate(lx, ly));
<ide> return legendContainer;
|
|
JavaScript
|
agpl-3.0
|
0991572f5445935628c3f2f137ace5c29d02a3cd
| 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
|
611c3304-2e63-11e5-9284-b827eb9e62be
|
helloWorld.js
|
6116bf6e-2e63-11e5-9284-b827eb9e62be
|
611c3304-2e63-11e5-9284-b827eb9e62be
|
helloWorld.js
|
611c3304-2e63-11e5-9284-b827eb9e62be
|
<ide><path>elloWorld.js
<del>6116bf6e-2e63-11e5-9284-b827eb9e62be
<add>611c3304-2e63-11e5-9284-b827eb9e62be
|
|
Java
|
apache-2.0
|
ae6416abdbb2fc48ef605f87d6fc4e8aea594747
| 0 |
OSBI/oodt,Cyan3/oodt,apache/oodt,Cyan3/oodt,OSBI/oodt,OSBI/oodt,IMS94/oodt,OSBI/oodt,IMS94/oodt,apache/oodt,apache/oodt,LeStarch/oodt,IMS94/oodt,Cyan3/oodt,LeStarch/oodt,IMS94/oodt,LeStarch/oodt,LeStarch/oodt,Cyan3/oodt,apache/oodt,IMS94/oodt,OSBI/oodt,apache/oodt,OSBI/oodt,LeStarch/oodt,apache/oodt,IMS94/oodt,Cyan3/oodt,LeStarch/oodt,Cyan3/oodt,OSBI/oodt,OSBI/oodt,apache/oodt,Cyan3/oodt,IMS94/oodt,LeStarch/oodt,Cyan3/oodt,OSBI/oodt,Cyan3/oodt,apache/oodt,LeStarch/oodt,LeStarch/oodt,IMS94/oodt
|
/*
* 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.oodt.cas.filemgr.system;
//APACHE imports
import org.apache.xmlrpc.CommonsXmlRpcTransport;
import org.apache.xmlrpc.XmlRpcClient;
import org.apache.xmlrpc.XmlRpcClientException;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.XmlRpcTransport;
import org.apache.xmlrpc.XmlRpcTransportFactory;
//JDK imports
import java.net.URL;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.File;
//OODT imports
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodRetryHandler;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.oodt.cas.metadata.Metadata;
import org.apache.oodt.cas.cli.CmdLineUtility;
import org.apache.oodt.cas.filemgr.structs.exceptions.CatalogException;
import org.apache.oodt.cas.filemgr.structs.exceptions.RepositoryManagerException;
import org.apache.oodt.cas.filemgr.structs.exceptions.ValidationLayerException;
import org.apache.oodt.cas.filemgr.structs.Element;
import org.apache.oodt.cas.filemgr.structs.FileTransferStatus;
import org.apache.oodt.cas.filemgr.structs.ProductPage;
import org.apache.oodt.cas.filemgr.structs.ProductType;
import org.apache.oodt.cas.filemgr.structs.Product;
import org.apache.oodt.cas.filemgr.structs.Query;
import org.apache.oodt.cas.filemgr.structs.Reference;
import org.apache.oodt.cas.filemgr.util.GenericFileManagerObjectFactory;
import org.apache.oodt.cas.filemgr.util.XmlRpcStructFactory;
import org.apache.oodt.cas.filemgr.versioning.Versioner;
import org.apache.oodt.cas.filemgr.structs.exceptions.VersioningException;
import org.apache.oodt.cas.filemgr.datatransfer.DataTransfer;
import org.apache.oodt.cas.filemgr.structs.exceptions.DataTransferException;
import org.apache.oodt.cas.filemgr.structs.exceptions.ConnectionException;
import org.apache.oodt.cas.filemgr.structs.query.ComplexQuery;
import org.apache.oodt.cas.filemgr.structs.query.QueryResult;
/**
* @author mattmann (Chris Mattmann)
* @author bfoster (Brian Foster)
* @version $Revision$
*
* <p>
* The XML RPC based file manager client.
* </p>
*
*/
public class XmlRpcFileManagerClient {
/* our xml rpc client */
private XmlRpcClient client = null;
/* our log stream */
private static Logger LOG = Logger.getLogger(XmlRpcFileManagerClient.class
.getName());
/* file manager url */
private URL fileManagerUrl = null;
/* data transferer needed if client is request to move files itself */
private DataTransfer dataTransfer = null;
public XmlRpcFileManagerClient(final URL url) throws ConnectionException {
this(url, true);
}
/**
* <p>
* Constructs a new XmlRpcFileManagerClient with the given <code>url</code>.
* </p>
*
* @param url
* The url pointer to the xml rpc file manager service.
* @param testConnection
* Whether or not to check if server at given url is alive.
*/
public XmlRpcFileManagerClient(final URL url, boolean testConnection)
throws ConnectionException {
// set up the configuration, if there is any
if (System.getProperty("org.apache.oodt.cas.filemgr.properties") != null) {
String configFile = System
.getProperty("org.apache.oodt.cas.filemgr.properties");
LOG.log(Level.INFO,
"Loading File Manager Configuration Properties from: ["
+ configFile + "]");
try {
System.getProperties().load(
new FileInputStream(new File(configFile)));
} catch (Exception e) {
LOG.log(Level.INFO,
"Error loading configuration properties from: ["
+ configFile + "]");
}
}
XmlRpcTransportFactory transportFactory = new XmlRpcTransportFactory() {
public XmlRpcTransport createTransport()
throws XmlRpcClientException {
HttpClient client = new HttpClient();
client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new HttpMethodRetryHandler() {
public boolean retryMethod(HttpMethod method,
IOException e, int count) {
if (count < Integer
.getInteger(
"org.apache.oodt.cas.filemgr.system.xmlrpc.connection.retries",
3).intValue()) {
try {
Thread
.sleep(Integer
.getInteger(
"org.apache.oodt.cas.filemgr.system.xmlrpc.connection.retry.interval.seconds",
0).intValue() * 1000);
return true;
} catch (Exception e1) {
}
}
return false;
}
});
CommonsXmlRpcTransport transport = new CommonsXmlRpcTransport(
url, client);
transport
.setConnectionTimeout(Integer
.getInteger(
"org.apache.oodt.cas.filemgr.system.xmlrpc.connectionTimeout.minutes",
20).intValue() * 60 * 1000);
transport
.setTimeout(Integer
.getInteger(
"org.apache.oodt.cas.filemgr.system.xmlrpc.requestTimeout.minutes",
60).intValue() * 60 * 1000);
return transport;
}
public void setProperty(String arg0, Object arg1) {
}
};
client = new XmlRpcClient(url, transportFactory);
fileManagerUrl = url;
if (testConnection && !isAlive()) {
throw new ConnectionException("Exception connecting to filemgr: ["
+ this.fileManagerUrl + "]");
}
}
public boolean refreshConfigAndPolicy() {
boolean success = false;
Vector<Object> argList = new Vector<Object>();
try {
success = ((Boolean) client.execute("filemgr.refreshConfigAndPolicy",
argList)).booleanValue();
} catch (XmlRpcException e) {
LOG.log(Level.WARNING, "XmlRpcException when connecting to filemgr: ["
+ this.fileManagerUrl + "]");
success = false;
} catch (IOException e) {
LOG.log(Level.WARNING, "IOException when connecting to filemgr: ["
+ this.fileManagerUrl + "]");
success = false;
}
return success;
}
public boolean isAlive() {
boolean connected = false;
Vector<Object> argList = new Vector<Object>();
try {
connected = ((Boolean) client.execute("filemgr.isAlive", argList))
.booleanValue();
} catch (XmlRpcException e) {
LOG.log(Level.WARNING,
"XmlRpcException when connecting to filemgr: ["
+ this.fileManagerUrl + "]");
connected = false;
} catch (IOException e) {
LOG.log(Level.WARNING, "IOException when connecting to filemgr: ["
+ this.fileManagerUrl + "]");
connected = false;
}
return connected;
}
public boolean transferringProduct(Product product)
throws DataTransferException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
argList.add(productHash);
boolean success = false;
try {
success = ((Boolean) client.execute("filemgr.transferringProduct",
argList)).booleanValue();
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
return success;
}
public boolean removeProductTransferStatus(Product product)
throws DataTransferException {
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
Vector<Object> argList = new Vector<Object>();
argList.add(productHash);
boolean success = false;
try {
success = ((Boolean) client.execute(
"filemgr.removeProductTransferStatus", argList))
.booleanValue();
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
return success;
}
public boolean isTransferComplete(Product product)
throws DataTransferException {
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
Vector<Object> argList = new Vector<Object>();
argList.add(productHash);
boolean success = false;
try {
success = ((Boolean) client.execute("filemgr.isTransferComplete",
argList)).booleanValue();
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
return success;
}
public boolean moveProduct(Product product, String newPath)
throws DataTransferException {
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
Vector<Object> argList = new Vector<Object>();
argList.add(productHash);
argList.add(newPath);
boolean success = false;
try {
success = ((Boolean) client.execute("filemgr.moveProduct", argList))
.booleanValue();
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
return success;
}
public boolean modifyProduct(Product product) throws CatalogException {
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
Vector<Object> argList = new Vector<Object>();
argList.add(productHash);
boolean success = false;
try {
success = ((Boolean) client.execute("filemgr.modifyProduct",
argList)).booleanValue();
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
return success;
}
public boolean removeProduct(Product product) throws CatalogException {
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
Vector<Object> argList = new Vector<Object>();
argList.add(productHash);
boolean success = false;
try {
success = ((Boolean) client.execute("filemgr.removeProduct",
argList)).booleanValue();
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
return success;
}
public FileTransferStatus getCurrentFileTransfer()
throws DataTransferException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> statusHash = null;
FileTransferStatus status = null;
try {
statusHash = (Hashtable<String, Object>) client.execute(
"filemgr.getCurrentFileTransfer", argList);
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
if (statusHash != null) {
status = XmlRpcStructFactory
.getFileTransferStatusFromXmlRpc(statusHash);
}
return status;
}
public List<FileTransferStatus> getCurrentFileTransfers()
throws DataTransferException {
Vector<Object> argList = new Vector<Object>();
Vector<Hashtable<String, Object>> statusVector = null;
List<FileTransferStatus> statuses = null;
try {
statusVector = (Vector<Hashtable<String, Object>>) client.execute(
"filemgr.getCurrentFileTransfers", argList);
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
if (statusVector != null) {
statuses = XmlRpcStructFactory
.getFileTransferStatusesFromXmlRpc(statusVector);
}
return statuses;
}
public double getProductPctTransferred(Product product)
throws DataTransferException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
argList.add(productHash);
Double pct = null;
try {
pct = (Double) client.execute("filemgr.getProductPctTransferred",
argList);
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
if (pct != null) {
return pct.doubleValue();
}
return -1.0;
}
public double getRefPctTransferred(Reference reference)
throws DataTransferException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> refHash = XmlRpcStructFactory
.getXmlRpcReference(reference);
argList.add(refHash);
Double pct = null;
try {
pct = (Double) client.execute("filemgr.getRefPctTransferred",
argList);
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
if (pct != null) {
return pct.doubleValue();
}
return -1.0;
}
public ProductPage pagedQuery(Query query, ProductType type, int pageNum)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> queryHash = XmlRpcStructFactory
.getXmlRpcQuery(query);
Hashtable<String, Object> typeHash = XmlRpcStructFactory
.getXmlRpcProductType(type);
argList.add(queryHash);
argList.add(typeHash);
argList.add(new Integer(pageNum));
Hashtable<String, Object> pageHash = null;
try {
pageHash = (Hashtable<String, Object>) client.execute(
"filemgr.pagedQuery", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
return XmlRpcStructFactory.getProductPageFromXmlRpc(pageHash);
}
public ProductPage getFirstPage(ProductType type) throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(XmlRpcStructFactory.getXmlRpcProductType(type));
ProductPage page = null;
Hashtable<String, Object> pageHash = null;
try {
pageHash = (Hashtable<String, Object>) client.execute(
"filemgr.getFirstPage", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
if (pageHash != null) {
page = XmlRpcStructFactory.getProductPageFromXmlRpc(pageHash);
}
return page;
}
public ProductPage getLastPage(ProductType type) throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(XmlRpcStructFactory.getXmlRpcProductType(type));
ProductPage page = null;
Hashtable<String, Object> pageHash = null;
try {
pageHash = (Hashtable<String, Object>) client.execute(
"filemgr.getLastPage", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
if (pageHash != null) {
page = XmlRpcStructFactory.getProductPageFromXmlRpc(pageHash);
}
return page;
}
public ProductPage getNextPage(ProductType type, ProductPage currPage)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(XmlRpcStructFactory.getXmlRpcProductType(type));
argList.add(XmlRpcStructFactory.getXmlRpcProductPage(currPage));
ProductPage page = null;
Hashtable<String, Object> pageHash = null;
try {
pageHash = (Hashtable<String, Object>) client.execute(
"filemgr.getNextPage", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
if (pageHash != null) {
page = XmlRpcStructFactory.getProductPageFromXmlRpc(pageHash);
}
return page;
}
public ProductPage getPrevPage(ProductType type, ProductPage currPage)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(XmlRpcStructFactory.getXmlRpcProductType(type));
argList.add(XmlRpcStructFactory.getXmlRpcProductPage(currPage));
ProductPage page = null;
Hashtable<String, Object> pageHash = null;
try {
pageHash = (Hashtable<String, Object>) client.execute(
"filemgr.getPrevPage", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
if (pageHash != null) {
page = XmlRpcStructFactory.getProductPageFromXmlRpc(pageHash);
}
return page;
}
public String addProductType(ProductType type)
throws RepositoryManagerException {
String productTypeId = null;
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> typeHash = XmlRpcStructFactory
.getXmlRpcProductType(type);
argList.add(typeHash);
try {
productTypeId = (String) client.execute("filemgr.addProductType",
argList);
} catch (XmlRpcException e) {
throw new RepositoryManagerException(e.getMessage());
} catch (IOException e) {
throw new RepositoryManagerException(e.getMessage());
}
return productTypeId;
}
public boolean hasProduct(String productName) throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(productName);
boolean hasProduct = false;
try {
hasProduct = ((Boolean) client.execute("filemgr.hasProduct",
argList)).booleanValue();
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
return hasProduct;
}
public int getNumProducts(ProductType type) throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(XmlRpcStructFactory.getXmlRpcProductType(type));
Integer numProducts = new Integer(-1);
try {
numProducts = (Integer) client.execute("filemgr.getNumProducts",
argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
return numProducts.intValue();
}
public List<Product> getTopNProducts(int n) throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(new Integer(n));
Vector<Hashtable<String, Object>> topNProducts = null;
try {
topNProducts = (Vector<Hashtable<String, Object>>) client.execute(
"filemgr.getTopNProducts", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
List<Product> topNProductList = XmlRpcStructFactory
.getProductListFromXmlRpc(topNProducts);
return topNProductList;
}
public List<Product> getTopNProducts(int n, ProductType type)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(new Integer(n));
Hashtable<String, Object> productTypeHash = XmlRpcStructFactory
.getXmlRpcProductType(type);
argList.add(productTypeHash);
Vector<Hashtable<String, Object>> topNProducts = null;
try {
topNProducts = (Vector<Hashtable<String, Object>>) client.execute(
"filemgr.getTopNProducts", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
List<Product> topNProductList = XmlRpcStructFactory
.getProductListFromXmlRpc(topNProducts);
return topNProductList;
}
public void setProductTransferStatus(Product product)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
argList.add(productHash);
try {
client.execute("filemgr.setProductTransferStatus", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
}
public void addProductReferences(Product product) throws CatalogException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
argList.add(productHash);
try {
client.execute("filemgr.addProductReferences", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
}
public void addMetadata(Product product, Metadata metadata)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(XmlRpcStructFactory.getXmlRpcProduct(product));
argList.add(metadata.getHashtable());
try {
client.execute("filemgr.addMetadata", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
}
public boolean updateMetadata(Product product, Metadata met)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(XmlRpcStructFactory.getXmlRpcProduct(product));
argList.add(met.getHashtable());
boolean result = false;
try {
result = (Boolean) client.execute("filemgr.updateMetadata", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
return result;
}
public String catalogProduct(Product product) throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(XmlRpcStructFactory.getXmlRpcProduct(product));
String productId = null;
try {
productId = (String) client.execute("filemgr.catalogProduct",
argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
return productId;
}
public Metadata getMetadata(Product product) throws CatalogException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
argList.add(productHash);
Hashtable<String, Object> metadata = null;
try {
metadata = (Hashtable<String, Object>) client.execute(
"filemgr.getMetadata", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
Metadata m = new Metadata();
m.addMetadata(metadata);
return m;
}
public Metadata getReducedMetadata(Product product, List elements)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
argList.add(productHash);
argList.add(new Vector(elements));
Hashtable<String, Object> metadata = null;
try {
metadata = (Hashtable<String, Object>) client.execute(
"filemgr.getReducedMetadata", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
Metadata m = new Metadata();
m.addMetadata(metadata);
return m;
}
public boolean removeFile(String filePath) throws DataTransferException {
Vector<Object> argList = new Vector<Object>();
argList.add(filePath);
boolean success = false;
try {
success = ((Boolean) client.execute("filemgr.removeFile", argList))
.booleanValue();
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
return success;
}
public byte[] retrieveFile(String filePath, int offset, int numBytes)
throws DataTransferException {
Vector<Object> argList = new Vector<Object>();
argList.add(filePath);
argList.add(new Integer(offset));
argList.add(new Integer(numBytes));
try {
return (byte[]) client.execute("filemgr.retrieveFile", argList);
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
}
public void transferFile(String filePath, byte[] fileData, int offset,
int numBytes) throws DataTransferException {
Vector<Object> argList = new Vector<Object>();
argList.add(filePath);
argList.add(fileData);
argList.add(new Integer(offset));
argList.add(new Integer(numBytes));
try {
client.execute("filemgr.transferFile", argList);
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
}
public List<Product> getProductsByProductType(ProductType type)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productTypeHash = XmlRpcStructFactory
.getXmlRpcProductType(type);
argList.add(productTypeHash);
Vector<Hashtable<String, Object>> productVector = null;
try {
productVector = (Vector<Hashtable<String, Object>>) client.execute(
"filemgr.getProductsByProductType", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
if (productVector == null) {
return null;
} else {
return XmlRpcStructFactory.getProductListFromXmlRpc(productVector);
}
}
public List<Element> getElementsByProductType(ProductType type)
throws ValidationLayerException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productTypeHash = XmlRpcStructFactory
.getXmlRpcProductType(type);
argList.add(productTypeHash);
Vector<Hashtable<String, Object>> elementVector = null;
try {
elementVector = (Vector<Hashtable<String, Object>>) client.execute(
"filemgr.getElementsByProductType", argList);
} catch (XmlRpcException e) {
throw new ValidationLayerException(e.getMessage());
} catch (IOException e) {
throw new ValidationLayerException(e.getMessage());
}
if (elementVector == null) {
return null;
} else {
return XmlRpcStructFactory.getElementListFromXmlRpc(elementVector);
}
}
public Element getElementById(String elementId)
throws ValidationLayerException {
Vector<Object> argList = new Vector<Object>();
argList.add(elementId);
Hashtable<String, Object> elementHash = null;
try {
elementHash = (Hashtable<String, Object>) client.execute(
"filemgr.getElementById", argList);
} catch (XmlRpcException e) {
throw new ValidationLayerException(e.getMessage());
} catch (IOException e) {
throw new ValidationLayerException(e.getMessage());
}
if (elementHash == null) {
return null;
} else {
return XmlRpcStructFactory.getElementFromXmlRpc(elementHash);
}
}
public Element getElementByName(String elementName)
throws ValidationLayerException {
Vector<Object> argList = new Vector<Object>();
argList.add(elementName);
Hashtable<String, Object> elementHash = null;
try {
elementHash = (Hashtable<String, Object>) client.execute(
"filemgr.getElementByName", argList);
} catch (XmlRpcException e) {
throw new ValidationLayerException(e.getMessage());
} catch (IOException e) {
throw new ValidationLayerException(e.getMessage());
}
if (elementHash == null) {
return null;
} else {
return XmlRpcStructFactory.getElementFromXmlRpc(elementHash);
}
}
public Element getElementByName(String elementName, ProductType type)
throws ValidationLayerException {
Vector<Object> argList = new Vector<Object>();
argList.add(elementName);
argList.add(XmlRpcStructFactory.getXmlRpcProductType(type));
Hashtable<String, Object> elementHash = null;
try {
elementHash = (Hashtable<String, Object>) client.execute(
"filemgr.getElementByName", argList);
} catch (XmlRpcException e) {
throw new ValidationLayerException(e.getMessage());
} catch (IOException e) {
throw new ValidationLayerException(e.getMessage());
}
if (elementHash == null) {
return null;
} else {
return XmlRpcStructFactory.getElementFromXmlRpc(elementHash);
}
}
public List<QueryResult> complexQuery(ComplexQuery complexQuery)
throws CatalogException {
try {
Hashtable<String, Object> complexQueryHash = XmlRpcStructFactory
.getXmlRpcComplexQuery(complexQuery);
Vector<Object> argList = new Vector<Object>();
argList.add(complexQueryHash);
Vector<Hashtable<String, Object>> queryResultHashVector = (Vector<Hashtable<String, Object>>) client
.execute("filemgr.complexQuery", argList);
return XmlRpcStructFactory
.getQueryResultsFromXmlRpc(queryResultHashVector);
} catch (Exception e) {
e.printStackTrace();
throw new CatalogException(e.getMessage());
}
}
public List<Product> query(Query query, ProductType type)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> queryHash = XmlRpcStructFactory
.getXmlRpcQuery(query);
Hashtable<String, Object> typeHash = XmlRpcStructFactory
.getXmlRpcProductType(type);
argList.add(queryHash);
argList.add(typeHash);
Vector<Hashtable<String, Object>> productVector = null;
try {
productVector = (Vector<Hashtable<String, Object>>) client.execute(
"filemgr.query", argList);
} catch (XmlRpcException e) {
e.printStackTrace();
throw new CatalogException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new CatalogException(e.getMessage());
}
if (productVector == null) {
return null;
} else {
return XmlRpcStructFactory.getProductListFromXmlRpc(productVector);
}
}
public ProductType getProductTypeByName(String productTypeName)
throws RepositoryManagerException {
Hashtable<String, Object> productTypeHash = new Hashtable<String, Object>();
Vector<Object> argList = new Vector<Object>();
argList.add(productTypeName);
try {
productTypeHash = (Hashtable<String, Object>) client.execute(
"filemgr.getProductTypeByName", argList);
} catch (XmlRpcException e) {
throw new RepositoryManagerException(e.getMessage());
} catch (IOException e) {
throw new RepositoryManagerException(e.getMessage());
}
if (productTypeHash == null) {
return null;
} else
return XmlRpcStructFactory
.getProductTypeFromXmlRpc(productTypeHash);
}
public ProductType getProductTypeById(String productTypeId)
throws RepositoryManagerException {
Hashtable<String, Object> productTypeHash = new Hashtable<String, Object>();
Vector<Object> argList = new Vector<Object>();
argList.add(productTypeId);
try {
productTypeHash = (Hashtable<String, Object>) client.execute(
"filemgr.getProductTypeById", argList);
} catch (XmlRpcException e) {
throw new RepositoryManagerException(e.getMessage());
} catch (IOException e) {
throw new RepositoryManagerException(e.getMessage());
}
if (productTypeHash == null) {
return null;
} else
return XmlRpcStructFactory
.getProductTypeFromXmlRpc(productTypeHash);
}
public List<ProductType> getProductTypes()
throws RepositoryManagerException {
Vector<Object> argList = new Vector<Object>();
Vector<Hashtable<String, Object>> productTypeVector = null;
try {
productTypeVector = (Vector<Hashtable<String, Object>>) client
.execute("filemgr.getProductTypes", argList);
} catch (XmlRpcException e) {
throw new RepositoryManagerException(e.getMessage());
} catch (IOException e) {
throw new RepositoryManagerException(e.getMessage());
}
if (productTypeVector == null) {
return null;
} else {
return XmlRpcStructFactory
.getProductTypeListFromXmlRpc(productTypeVector);
}
}
public List<Reference> getProductReferences(Product product)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
Vector<Hashtable<String, Object>> productReferenceVector = null;
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
argList.add(productHash);
try {
productReferenceVector = (Vector<Hashtable<String, Object>>) client
.execute("filemgr.getProductReferences", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
if (productReferenceVector == null) {
return null;
} else {
return XmlRpcStructFactory
.getReferencesFromXmlRpc(productReferenceVector);
}
}
public Product getProductById(String productId) throws CatalogException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productHash = null;
argList.add(productId);
try {
productHash = (Hashtable<String, Object>) client.execute(
"filemgr.getProductById", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
if (productHash == null) {
return null;
} else {
return XmlRpcStructFactory.getProductFromXmlRpc(productHash);
}
}
public Product getProductByName(String productName) throws CatalogException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productHash = null;
argList.add(productName);
try {
productHash = (Hashtable<String, Object>) client.execute(
"filemgr.getProductByName", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
if (productHash == null) {
return null;
} else {
return XmlRpcStructFactory.getProductFromXmlRpc(productHash);
}
}
public String ingestProduct(Product product, Metadata metadata,
boolean clientTransfer) throws Exception {
try {
// ingest product
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
argList.add(productHash);
argList.add(metadata.getHashtable());
argList.add(Boolean.valueOf(clientTransfer));
String productId = (String) client.execute("filemgr.ingestProduct",
argList);
if (clientTransfer) {
LOG.log(Level.FINEST,
"File Manager Client: clientTransfer enabled: "
+ "transfering product ["
+ product.getProductName() + "]");
// we need to transfer the product ourselves
// make sure we have the product ID
if (productId == null) {
throw new Exception("Request to ingest product: "
+ product.getProductName()
+ " but no product ID returned from File "
+ "Manager ingest");
}
if (dataTransfer == null) {
throw new Exception("Request to ingest product: ["
+ product.getProductName()
+ "] using client transfer, but no "
+ "dataTransferer specified!");
}
product.setProductId(productId);
if (!Boolean.getBoolean("org.apache.oodt.cas.filemgr.serverside.versioning")) {
// version the product
Versioner versioner = GenericFileManagerObjectFactory
.getVersionerFromClassName(product.getProductType()
.getVersioner());
versioner.createDataStoreReferences(product, metadata);
// add the newly versioned references to the data store
try {
addProductReferences(product);
} catch (CatalogException e) {
LOG
.log(
Level.SEVERE,
"ingestProduct: RepositoryManagerException "
+ "when adding Product References for Product : "
+ product.getProductName()
+ " to RepositoryManager: Message: "
+ e.getMessage());
throw e;
}
} else {
product.setProductReferences(getProductReferences(product));
}
// now transfer the product
try {
dataTransfer.transferProduct(product);
// now update the product's transfer status in the data
// store
product.setTransferStatus(Product.STATUS_RECEIVED);
try {
setProductTransferStatus(product);
} catch (CatalogException e) {
LOG
.log(
Level.SEVERE,
"ingestProduct: RepositoryManagerException "
+ "when updating product transfer status for Product: "
+ product.getProductName()
+ " Message: " + e.getMessage());
throw e;
}
} catch (Exception e) {
LOG.log(Level.SEVERE,
"ingestProduct: DataTransferException when transfering Product: "
+ product.getProductName() + ": Message: "
+ e.getMessage());
throw new DataTransferException(e);
}
}
return productId;
// error versioning file
} catch (VersioningException e) {
e.printStackTrace();
LOG.log(Level.SEVERE,
"ingestProduct: VersioningException when versioning Product: "
+ product.getProductName() + " with Versioner "
+ product.getProductType().getVersioner()
+ ": Message: " + e.getMessage());
throw new VersioningException(e);
} catch (Exception e) {
e.printStackTrace();
LOG.log(Level.SEVERE, "Failed to ingest product [" + product
+ "] : " + e.getMessage() + " -- rolling back ingest");
try {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
argList.add(productHash);
client.execute("filemgr.removeProduct", argList);
} catch (Exception e1) {
LOG.log(Level.SEVERE, "Failed to rollback ingest of product ["
+ product + "] : " + e.getMessage());
}
throw new Exception("Failed to ingest product [" + product + "] : "
+ e.getMessage());
}
}
public Metadata getCatalogValues(Metadata metadata, ProductType productType)
throws XmlRpcException, IOException {
Vector<Object> args = new Vector<Object>();
args.add(metadata.getHashtable());
args.add(XmlRpcStructFactory.getXmlRpcProductType(productType));
Metadata m = new Metadata();
m.addMetadata((Hashtable<String, Object>) this.client.execute(
"filemgr.getCatalogValues", args));
return m;
}
public Metadata getOrigValues(Metadata metadata, ProductType productType)
throws XmlRpcException, IOException {
Vector<Object> args = new Vector<Object>();
args.add(metadata.getHashtable());
args.add(XmlRpcStructFactory.getXmlRpcProductType(productType));
Metadata m = new Metadata();
m.addMetadata((Hashtable<String, Object>) this.client.execute(
"filemgr.getOrigValues", args));
return m;
}
public Query getCatalogQuery(Query query, ProductType productType)
throws XmlRpcException, IOException {
Vector<Object> args = new Vector<Object>();
args.add(XmlRpcStructFactory.getXmlRpcQuery(query));
args.add(XmlRpcStructFactory.getXmlRpcProductType(productType));
return XmlRpcStructFactory
.getQueryFromXmlRpc((Hashtable<String, Object>) this.client
.execute("filemgr.getCatalogQuery", args));
}
public static void main(String[] args) {
CmdLineUtility cmdLineUtility = new CmdLineUtility();
cmdLineUtility.run(args);
}
/**
* @return Returns the fileManagerUrl.
*/
public URL getFileManagerUrl() {
return fileManagerUrl;
}
/**
* @param fileManagerUrl
* The fileManagerUrl to set.
*/
public void setFileManagerUrl(URL fileManagerUrl) {
this.fileManagerUrl = fileManagerUrl;
// reset the client
this.client = new XmlRpcClient(fileManagerUrl);
}
/**
* @return Returns the dataTransfer.
*/
public DataTransfer getDataTransfer() {
return dataTransfer;
}
/**
* @param dataTransfer
* The dataTransfer to set.
*/
public void setDataTransfer(DataTransfer dataTransfer) {
this.dataTransfer = dataTransfer;
this.dataTransfer.setFileManagerUrl(this.fileManagerUrl);
}
}
|
filemgr/src/main/java/org/apache/oodt/cas/filemgr/system/XmlRpcFileManagerClient.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.oodt.cas.filemgr.system;
//APACHE imports
import org.apache.xmlrpc.CommonsXmlRpcTransport;
import org.apache.xmlrpc.XmlRpcClient;
import org.apache.xmlrpc.XmlRpcClientException;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.XmlRpcTransport;
import org.apache.xmlrpc.XmlRpcTransportFactory;
//JDK imports
import java.net.URL;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.File;
//OODT imports
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodRetryHandler;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.oodt.cas.metadata.Metadata;
import org.apache.oodt.cas.cli.CmdLineUtility;
import org.apache.oodt.cas.filemgr.structs.exceptions.CatalogException;
import org.apache.oodt.cas.filemgr.structs.exceptions.RepositoryManagerException;
import org.apache.oodt.cas.filemgr.structs.exceptions.ValidationLayerException;
import org.apache.oodt.cas.filemgr.structs.Element;
import org.apache.oodt.cas.filemgr.structs.FileTransferStatus;
import org.apache.oodt.cas.filemgr.structs.ProductPage;
import org.apache.oodt.cas.filemgr.structs.ProductType;
import org.apache.oodt.cas.filemgr.structs.Product;
import org.apache.oodt.cas.filemgr.structs.Query;
import org.apache.oodt.cas.filemgr.structs.Reference;
import org.apache.oodt.cas.filemgr.util.GenericFileManagerObjectFactory;
import org.apache.oodt.cas.filemgr.util.XmlRpcStructFactory;
import org.apache.oodt.cas.filemgr.versioning.Versioner;
import org.apache.oodt.cas.filemgr.structs.exceptions.VersioningException;
import org.apache.oodt.cas.filemgr.datatransfer.DataTransfer;
import org.apache.oodt.cas.filemgr.structs.exceptions.DataTransferException;
import org.apache.oodt.cas.filemgr.structs.exceptions.ConnectionException;
import org.apache.oodt.cas.filemgr.structs.query.ComplexQuery;
import org.apache.oodt.cas.filemgr.structs.query.QueryResult;
/**
* @author mattmann (Chris Mattmann)
* @author bfoster (Brian Foster)
* @version $Revision$
*
* <p>
* The XML RPC based file manager client.
* </p>
*
*/
public class XmlRpcFileManagerClient {
/* our xml rpc client */
private XmlRpcClient client = null;
/* our log stream */
private static Logger LOG = Logger.getLogger(XmlRpcFileManagerClient.class
.getName());
/* file manager url */
private URL fileManagerUrl = null;
/* data transferer needed if client is request to move files itself */
private DataTransfer dataTransfer = null;
public XmlRpcFileManagerClient(final URL url) throws ConnectionException {
this(url, true);
}
/**
* <p>
* Constructs a new XmlRpcFileManagerClient with the given <code>url</code>.
* </p>
*
* @param url
* The url pointer to the xml rpc file manager service.
* @param testConnection
* Whether or not to check if server at given url is alive.
*/
public XmlRpcFileManagerClient(final URL url, boolean testConnection)
throws ConnectionException {
// set up the configuration, if there is any
if (System.getProperty("org.apache.oodt.cas.filemgr.properties") != null) {
String configFile = System
.getProperty("org.apache.oodt.cas.filemgr.properties");
LOG.log(Level.INFO,
"Loading File Manager Configuration Properties from: ["
+ configFile + "]");
try {
System.getProperties().load(
new FileInputStream(new File(configFile)));
} catch (Exception e) {
LOG.log(Level.INFO,
"Error loading configuration properties from: ["
+ configFile + "]");
}
}
XmlRpcTransportFactory transportFactory = new XmlRpcTransportFactory() {
public XmlRpcTransport createTransport()
throws XmlRpcClientException {
HttpClient client = new HttpClient();
client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new HttpMethodRetryHandler() {
public boolean retryMethod(HttpMethod method,
IOException e, int count) {
if (count < Integer
.getInteger(
"org.apache.oodt.cas.filemgr.system.xmlrpc.connection.retries",
3).intValue()) {
try {
Thread
.sleep(Integer
.getInteger(
"org.apache.oodt.cas.filemgr.system.xmlrpc.connection.retry.interval.seconds",
0).intValue() * 1000);
return true;
} catch (Exception e1) {
}
}
return false;
}
});
CommonsXmlRpcTransport transport = new CommonsXmlRpcTransport(
url, client);
transport
.setConnectionTimeout(Integer
.getInteger(
"org.apache.oodt.cas.filemgr.system.xmlrpc.connectionTimeout.minutes",
20).intValue() * 60 * 1000);
transport
.setTimeout(Integer
.getInteger(
"org.apache.oodt.cas.filemgr.system.xmlrpc.requestTimeout.minutes",
60).intValue() * 60 * 1000);
return transport;
}
public void setProperty(String arg0, Object arg1) {
}
};
client = new XmlRpcClient(url, transportFactory);
fileManagerUrl = url;
if (testConnection && !isAlive()) {
throw new ConnectionException("Exception connecting to filemgr: ["
+ this.fileManagerUrl + "]");
}
}
public boolean refreshConfigAndPolicy() {
boolean success = false;
Vector<Object> argList = new Vector<Object>();
try {
success = ((Boolean) client.execute("filemgr.refreshConfigAndPolicy",
argList)).booleanValue();
} catch (XmlRpcException e) {
LOG.log(Level.WARNING, "XmlRpcException when connecting to filemgr: ["
+ this.fileManagerUrl + "]");
success = false;
} catch (IOException e) {
LOG.log(Level.WARNING, "IOException when connecting to filemgr: ["
+ this.fileManagerUrl + "]");
success = false;
}
return success;
}
public boolean isAlive() {
boolean connected = false;
Vector<Object> argList = new Vector<Object>();
try {
connected = ((Boolean) client.execute("filemgr.isAlive", argList))
.booleanValue();
} catch (XmlRpcException e) {
LOG.log(Level.WARNING,
"XmlRpcException when connecting to filemgr: ["
+ this.fileManagerUrl + "]");
connected = false;
} catch (IOException e) {
LOG.log(Level.WARNING, "IOException when connecting to filemgr: ["
+ this.fileManagerUrl + "]");
connected = false;
}
return connected;
}
public boolean transferringProduct(Product product)
throws DataTransferException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
argList.add(productHash);
boolean success = false;
try {
success = ((Boolean) client.execute("filemgr.transferringProduct",
argList)).booleanValue();
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
return success;
}
public boolean removeProductTransferStatus(Product product)
throws DataTransferException {
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
Vector<Object> argList = new Vector<Object>();
argList.add(productHash);
boolean success = false;
try {
success = ((Boolean) client.execute(
"filemgr.removeProductTransferStatus", argList))
.booleanValue();
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
return success;
}
public boolean isTransferComplete(Product product)
throws DataTransferException {
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
Vector<Object> argList = new Vector<Object>();
argList.add(productHash);
boolean success = false;
try {
success = ((Boolean) client.execute("filemgr.isTransferComplete",
argList)).booleanValue();
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
return success;
}
public boolean moveProduct(Product product, String newPath)
throws DataTransferException {
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
Vector<Object> argList = new Vector<Object>();
argList.add(productHash);
argList.add(newPath);
boolean success = false;
try {
success = ((Boolean) client.execute("filemgr.moveProduct", argList))
.booleanValue();
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
return success;
}
public boolean modifyProduct(Product product) throws CatalogException {
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
Vector<Object> argList = new Vector<Object>();
argList.add(productHash);
boolean success = false;
try {
success = ((Boolean) client.execute("filemgr.modifyProduct",
argList)).booleanValue();
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
return success;
}
public boolean removeProduct(Product product) throws CatalogException {
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
Vector<Object> argList = new Vector<Object>();
argList.add(productHash);
boolean success = false;
try {
success = ((Boolean) client.execute("filemgr.removeProduct",
argList)).booleanValue();
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
return success;
}
public FileTransferStatus getCurrentFileTransfer()
throws DataTransferException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> statusHash = null;
FileTransferStatus status = null;
try {
statusHash = (Hashtable<String, Object>) client.execute(
"filemgr.getCurrentFileTransfer", argList);
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
if (statusHash != null) {
status = XmlRpcStructFactory
.getFileTransferStatusFromXmlRpc(statusHash);
}
return status;
}
public List<FileTransferStatus> getCurrentFileTransfers()
throws DataTransferException {
Vector<Object> argList = new Vector<Object>();
Vector<Hashtable<String, Object>> statusVector = null;
List<FileTransferStatus> statuses = null;
try {
statusVector = (Vector<Hashtable<String, Object>>) client.execute(
"filemgr.getCurrentFileTransfers", argList);
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
if (statusVector != null) {
statuses = XmlRpcStructFactory
.getFileTransferStatusesFromXmlRpc(statusVector);
}
return statuses;
}
public double getProductPctTransferred(Product product)
throws DataTransferException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
argList.add(productHash);
Double pct = null;
try {
pct = (Double) client.execute("filemgr.getProductPctTransferred",
argList);
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
if (pct != null) {
return pct.doubleValue();
}
return -1.0;
}
public double getRefPctTransferred(Reference reference)
throws DataTransferException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> refHash = XmlRpcStructFactory
.getXmlRpcReference(reference);
argList.add(refHash);
Double pct = null;
try {
pct = (Double) client.execute("filemgr.getRefPctTransferred",
argList);
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
if (pct != null) {
return pct.doubleValue();
}
return -1.0;
}
public ProductPage pagedQuery(Query query, ProductType type, int pageNum)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> queryHash = XmlRpcStructFactory
.getXmlRpcQuery(query);
Hashtable<String, Object> typeHash = XmlRpcStructFactory
.getXmlRpcProductType(type);
argList.add(queryHash);
argList.add(typeHash);
argList.add(new Integer(pageNum));
Hashtable<String, Object> pageHash = null;
try {
pageHash = (Hashtable<String, Object>) client.execute(
"filemgr.pagedQuery", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
return XmlRpcStructFactory.getProductPageFromXmlRpc(pageHash);
}
public ProductPage getFirstPage(ProductType type) throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(XmlRpcStructFactory.getXmlRpcProductType(type));
ProductPage page = null;
Hashtable<String, Object> pageHash = null;
try {
pageHash = (Hashtable<String, Object>) client.execute(
"filemgr.getFirstPage", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
if (pageHash != null) {
page = XmlRpcStructFactory.getProductPageFromXmlRpc(pageHash);
}
return page;
}
public ProductPage getLastPage(ProductType type) throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(XmlRpcStructFactory.getXmlRpcProductType(type));
ProductPage page = null;
Hashtable<String, Object> pageHash = null;
try {
pageHash = (Hashtable<String, Object>) client.execute(
"filemgr.getLastPage", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
if (pageHash != null) {
page = XmlRpcStructFactory.getProductPageFromXmlRpc(pageHash);
}
return page;
}
public ProductPage getNextPage(ProductType type, ProductPage currPage)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(XmlRpcStructFactory.getXmlRpcProductType(type));
argList.add(XmlRpcStructFactory.getXmlRpcProductPage(currPage));
ProductPage page = null;
Hashtable<String, Object> pageHash = null;
try {
pageHash = (Hashtable<String, Object>) client.execute(
"filemgr.getNextPage", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
if (pageHash != null) {
page = XmlRpcStructFactory.getProductPageFromXmlRpc(pageHash);
}
return page;
}
public ProductPage getPrevPage(ProductType type, ProductPage currPage)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(XmlRpcStructFactory.getXmlRpcProductType(type));
argList.add(XmlRpcStructFactory.getXmlRpcProductPage(currPage));
ProductPage page = null;
Hashtable<String, Object> pageHash = null;
try {
pageHash = (Hashtable<String, Object>) client.execute(
"filemgr.getPrevPage", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
if (pageHash != null) {
page = XmlRpcStructFactory.getProductPageFromXmlRpc(pageHash);
}
return page;
}
public String addProductType(ProductType type)
throws RepositoryManagerException {
String productTypeId = null;
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> typeHash = XmlRpcStructFactory
.getXmlRpcProductType(type);
argList.add(typeHash);
try {
productTypeId = (String) client.execute("filemgr.addProductType",
argList);
} catch (XmlRpcException e) {
throw new RepositoryManagerException(e.getMessage());
} catch (IOException e) {
throw new RepositoryManagerException(e.getMessage());
}
return productTypeId;
}
public boolean hasProduct(String productName) throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(productName);
boolean hasProduct = false;
try {
hasProduct = ((Boolean) client.execute("filemgr.hasProduct",
argList)).booleanValue();
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
return hasProduct;
}
public int getNumProducts(ProductType type) throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(XmlRpcStructFactory.getXmlRpcProductType(type));
Integer numProducts = new Integer(-1);
try {
numProducts = (Integer) client.execute("filemgr.getNumProducts",
argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
return numProducts.intValue();
}
public List<Product> getTopNProducts(int n) throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(new Integer(n));
Vector<Hashtable<String, Object>> topNProducts = null;
try {
topNProducts = (Vector<Hashtable<String, Object>>) client.execute(
"filemgr.getTopNProducts", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
List<Product> topNProductList = XmlRpcStructFactory
.getProductListFromXmlRpc(topNProducts);
return topNProductList;
}
public List<Product> getTopNProducts(int n, ProductType type)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(new Integer(n));
Hashtable<String, Object> productTypeHash = XmlRpcStructFactory
.getXmlRpcProductType(type);
argList.add(productTypeHash);
Vector<Hashtable<String, Object>> topNProducts = null;
try {
topNProducts = (Vector<Hashtable<String, Object>>) client.execute(
"filemgr.getTopNProducts", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
List<Product> topNProductList = XmlRpcStructFactory
.getProductListFromXmlRpc(topNProducts);
return topNProductList;
}
public void setProductTransferStatus(Product product)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
argList.add(productHash);
try {
client.execute("filemgr.setProductTransferStatus", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
}
public void addProductReferences(Product product) throws CatalogException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
argList.add(productHash);
try {
client.execute("filemgr.addProductReferences", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
}
public void addMetadata(Product product, Metadata metadata)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(XmlRpcStructFactory.getXmlRpcProduct(product));
argList.add(metadata.getHashtable());
try {
client.execute("filemgr.addMetadata", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
}
public boolean updateMetadata(Product product, Metadata met)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(XmlRpcStructFactory.getXmlRpcProduct(product));
argList.add(met.getHashtable());
boolean result = false;
try {
result = (Boolean) client.execute("filemgr.updateMetadata", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
return result;
}
public String catalogProduct(Product product) throws CatalogException {
Vector<Object> argList = new Vector<Object>();
argList.add(XmlRpcStructFactory.getXmlRpcProduct(product));
String productId = null;
try {
productId = (String) client.execute("filemgr.catalogProduct",
argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
return productId;
}
public Metadata getMetadata(Product product) throws CatalogException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
argList.add(productHash);
Hashtable<String, Object> metadata = null;
try {
metadata = (Hashtable<String, Object>) client.execute(
"filemgr.getMetadata", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
Metadata m = new Metadata();
m.addMetadata(metadata);
return m;
}
public Metadata getReducedMetadata(Product product, List elements)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
argList.add(productHash);
argList.add(new Vector(elements));
Hashtable<String, Object> metadata = null;
try {
metadata = (Hashtable<String, Object>) client.execute(
"filemgr.getReducedMetadata", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
Metadata m = new Metadata();
m.addMetadata(metadata);
return m;
}
public boolean removeFile(String filePath) throws DataTransferException {
Vector<Object> argList = new Vector<Object>();
argList.add(filePath);
boolean success = false;
try {
success = ((Boolean) client.execute("filemgr.removeFile", argList))
.booleanValue();
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
return success;
}
public byte[] retrieveFile(String filePath, int offset, int numBytes)
throws DataTransferException {
Vector<Object> argList = new Vector<Object>();
argList.add(filePath);
argList.add(new Integer(offset));
argList.add(new Integer(numBytes));
try {
return (byte[]) client.execute("filemgr.retrieveFile", argList);
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
}
public void transferFile(String filePath, byte[] fileData, int offset,
int numBytes) throws DataTransferException {
Vector<Object> argList = new Vector<Object>();
argList.add(filePath);
argList.add(fileData);
argList.add(new Integer(offset));
argList.add(new Integer(numBytes));
try {
client.execute("filemgr.transferFile", argList);
} catch (XmlRpcException e) {
throw new DataTransferException(e.getMessage());
} catch (IOException e) {
throw new DataTransferException(e.getMessage());
}
}
public List<Product> getProductsByProductType(ProductType type)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productTypeHash = XmlRpcStructFactory
.getXmlRpcProductType(type);
argList.add(productTypeHash);
Vector<Hashtable<String, Object>> productVector = null;
try {
productVector = (Vector<Hashtable<String, Object>>) client.execute(
"filemgr.getProductsByProductType", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
if (productVector == null) {
return null;
} else {
return XmlRpcStructFactory.getProductListFromXmlRpc(productVector);
}
}
public List<Element> getElementsByProductType(ProductType type)
throws ValidationLayerException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productTypeHash = XmlRpcStructFactory
.getXmlRpcProductType(type);
argList.add(productTypeHash);
Vector<Hashtable<String, Object>> elementVector = null;
try {
elementVector = (Vector<Hashtable<String, Object>>) client.execute(
"filemgr.getElementsByProductType", argList);
} catch (XmlRpcException e) {
throw new ValidationLayerException(e.getMessage());
} catch (IOException e) {
throw new ValidationLayerException(e.getMessage());
}
if (elementVector == null) {
return null;
} else {
return XmlRpcStructFactory.getElementListFromXmlRpc(elementVector);
}
}
public Element getElementById(String elementId)
throws ValidationLayerException {
Vector<Object> argList = new Vector<Object>();
argList.add(elementId);
Hashtable<String, Object> elementHash = null;
try {
elementHash = (Hashtable<String, Object>) client.execute(
"filemgr.getElementById", argList);
} catch (XmlRpcException e) {
throw new ValidationLayerException(e.getMessage());
} catch (IOException e) {
throw new ValidationLayerException(e.getMessage());
}
if (elementHash == null) {
return null;
} else {
return XmlRpcStructFactory.getElementFromXmlRpc(elementHash);
}
}
public Element getElementByName(String elementName)
throws ValidationLayerException {
Vector<Object> argList = new Vector<Object>();
argList.add(elementName);
Hashtable<String, Object> elementHash = null;
try {
elementHash = (Hashtable<String, Object>) client.execute(
"filemgr.getElementByName", argList);
} catch (XmlRpcException e) {
throw new ValidationLayerException(e.getMessage());
} catch (IOException e) {
throw new ValidationLayerException(e.getMessage());
}
if (elementHash == null) {
return null;
} else {
return XmlRpcStructFactory.getElementFromXmlRpc(elementHash);
}
}
public Element getElementByName(String elementName, ProductType type)
throws ValidationLayerException {
Vector<Object> argList = new Vector<Object>();
argList.add(elementName);
argList.add(XmlRpcStructFactory.getXmlRpcProductType(type));
Hashtable<String, Object> elementHash = null;
try {
elementHash = (Hashtable<String, Object>) client.execute(
"filemgr.getElementByName", argList);
} catch (XmlRpcException e) {
throw new ValidationLayerException(e.getMessage());
} catch (IOException e) {
throw new ValidationLayerException(e.getMessage());
}
if (elementHash == null) {
return null;
} else {
return XmlRpcStructFactory.getElementFromXmlRpc(elementHash);
}
}
public List<QueryResult> complexQuery(ComplexQuery complexQuery)
throws CatalogException {
try {
Hashtable<String, Object> complexQueryHash = XmlRpcStructFactory
.getXmlRpcComplexQuery(complexQuery);
Vector<Object> argList = new Vector<Object>();
argList.add(complexQueryHash);
Vector<Hashtable<String, Object>> queryResultHashVector = (Vector<Hashtable<String, Object>>) client
.execute("filemgr.complexQuery", argList);
return XmlRpcStructFactory
.getQueryResultsFromXmlRpc(queryResultHashVector);
} catch (Exception e) {
e.printStackTrace();
throw new CatalogException(e.getMessage());
}
}
public List<Product> query(Query query, ProductType type)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> queryHash = XmlRpcStructFactory
.getXmlRpcQuery(query);
Hashtable<String, Object> typeHash = XmlRpcStructFactory
.getXmlRpcProductType(type);
argList.add(queryHash);
argList.add(typeHash);
Vector<Hashtable<String, Object>> productVector = null;
try {
productVector = (Vector<Hashtable<String, Object>>) client.execute(
"filemgr.query", argList);
} catch (XmlRpcException e) {
e.printStackTrace();
throw new CatalogException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new CatalogException(e.getMessage());
}
if (productVector == null) {
return null;
} else {
return XmlRpcStructFactory.getProductListFromXmlRpc(productVector);
}
}
public ProductType getProductTypeByName(String productTypeName)
throws RepositoryManagerException {
Hashtable<String, Object> productTypeHash = new Hashtable<String, Object>();
Vector<Object> argList = new Vector<Object>();
argList.add(productTypeName);
try {
productTypeHash = (Hashtable<String, Object>) client.execute(
"filemgr.getProductTypeByName", argList);
} catch (XmlRpcException e) {
throw new RepositoryManagerException(e.getMessage());
} catch (IOException e) {
throw new RepositoryManagerException(e.getMessage());
}
if (productTypeHash == null) {
return null;
} else
return XmlRpcStructFactory
.getProductTypeFromXmlRpc(productTypeHash);
}
public ProductType getProductTypeById(String productTypeId)
throws RepositoryManagerException {
Hashtable<String, Object> productTypeHash = new Hashtable<String, Object>();
Vector<Object> argList = new Vector<Object>();
argList.add(productTypeId);
try {
productTypeHash = (Hashtable<String, Object>) client.execute(
"filemgr.getProductTypeById", argList);
} catch (XmlRpcException e) {
throw new RepositoryManagerException(e.getMessage());
} catch (IOException e) {
throw new RepositoryManagerException(e.getMessage());
}
if (productTypeHash == null) {
return null;
} else
return XmlRpcStructFactory
.getProductTypeFromXmlRpc(productTypeHash);
}
public List<ProductType> getProductTypes()
throws RepositoryManagerException {
Vector<Object> argList = new Vector<Object>();
Vector<Hashtable<String, Object>> productTypeVector = null;
try {
productTypeVector = (Vector<Hashtable<String, Object>>) client
.execute("filemgr.getProductTypes", argList);
} catch (XmlRpcException e) {
throw new RepositoryManagerException(e.getMessage());
} catch (IOException e) {
throw new RepositoryManagerException(e.getMessage());
}
if (productTypeVector == null) {
return null;
} else {
return XmlRpcStructFactory
.getProductTypeListFromXmlRpc(productTypeVector);
}
}
public List<Reference> getProductReferences(Product product)
throws CatalogException {
Vector<Object> argList = new Vector<Object>();
Vector<Hashtable<String, Object>> productReferenceVector = null;
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
argList.add(productHash);
try {
productReferenceVector = (Vector<Hashtable<String, Object>>) client
.execute("filemgr.getProductReferences", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
if (productReferenceVector == null) {
return null;
} else {
return XmlRpcStructFactory
.getReferencesFromXmlRpc(productReferenceVector);
}
}
public Product getProductById(String productId) throws CatalogException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productHash = null;
argList.add(productId);
try {
productHash = (Hashtable<String, Object>) client.execute(
"filemgr.getProductById", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
if (productHash == null) {
return null;
} else {
return XmlRpcStructFactory.getProductFromXmlRpc(productHash);
}
}
public Product getProductByName(String productName) throws CatalogException {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productHash = null;
argList.add(productName);
try {
productHash = (Hashtable<String, Object>) client.execute(
"filemgr.getProductByName", argList);
} catch (XmlRpcException e) {
throw new CatalogException(e.getMessage());
} catch (IOException e) {
throw new CatalogException(e.getMessage());
}
if (productHash == null) {
return null;
} else {
return XmlRpcStructFactory.getProductFromXmlRpc(productHash);
}
}
public String ingestProduct(Product product, Metadata metadata,
boolean clientTransfer) throws Exception {
try {
// ingest product
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
argList.add(productHash);
argList.add(metadata.getHashtable());
argList.add(Boolean.valueOf(clientTransfer));
String productId = (String) client.execute("filemgr.ingestProduct",
argList);
if (clientTransfer) {
LOG.log(Level.FINEST,
"File Manager Client: clientTransfer enabled: "
+ "transfering product ["
+ product.getProductName() + "]");
// we need to transfer the product ourselves
// make sure we have the product ID
if (productId == null) {
throw new Exception("Request to ingest product: "
+ product.getProductName()
+ " but no product ID returned from File "
+ "Manager ingest");
}
if (dataTransfer == null) {
throw new Exception("Request to ingest product: ["
+ product.getProductName()
+ "] using client transfer, but no "
+ "dataTransferer specified!");
}
product.setProductId(productId);
if (!Boolean.getBoolean("org.apache.oodt.cas.filemgr.serverside.versioning")) {
// version the product
Versioner versioner = GenericFileManagerObjectFactory
.getVersionerFromClassName(product.getProductType()
.getVersioner());
versioner.createDataStoreReferences(product, metadata);
// add the newly versioned references to the data store
try {
addProductReferences(product);
} catch (CatalogException e) {
LOG
.log(
Level.SEVERE,
"ingestProduct: RepositoryManagerException "
+ "when adding Product References for Product : "
+ product.getProductName()
+ " to RepositoryManager: Message: "
+ e.getMessage());
throw e;
}
}
// now transfer the product
try {
dataTransfer.transferProduct(product);
// now update the product's transfer status in the data
// store
product.setTransferStatus(Product.STATUS_RECEIVED);
try {
setProductTransferStatus(product);
} catch (CatalogException e) {
LOG
.log(
Level.SEVERE,
"ingestProduct: RepositoryManagerException "
+ "when updating product transfer status for Product: "
+ product.getProductName()
+ " Message: " + e.getMessage());
throw e;
}
} catch (Exception e) {
LOG.log(Level.SEVERE,
"ingestProduct: DataTransferException when transfering Product: "
+ product.getProductName() + ": Message: "
+ e.getMessage());
throw new DataTransferException(e);
}
}
return productId;
// error versioning file
} catch (VersioningException e) {
e.printStackTrace();
LOG.log(Level.SEVERE,
"ingestProduct: VersioningException when versioning Product: "
+ product.getProductName() + " with Versioner "
+ product.getProductType().getVersioner()
+ ": Message: " + e.getMessage());
throw new VersioningException(e);
} catch (Exception e) {
e.printStackTrace();
LOG.log(Level.SEVERE, "Failed to ingest product [" + product
+ "] : " + e.getMessage() + " -- rolling back ingest");
try {
Vector<Object> argList = new Vector<Object>();
Hashtable<String, Object> productHash = XmlRpcStructFactory
.getXmlRpcProduct(product);
argList.add(productHash);
client.execute("filemgr.removeProduct", argList);
} catch (Exception e1) {
LOG.log(Level.SEVERE, "Failed to rollback ingest of product ["
+ product + "] : " + e.getMessage());
}
throw new Exception("Failed to ingest product [" + product + "] : "
+ e.getMessage());
}
}
public Metadata getCatalogValues(Metadata metadata, ProductType productType)
throws XmlRpcException, IOException {
Vector<Object> args = new Vector<Object>();
args.add(metadata.getHashtable());
args.add(XmlRpcStructFactory.getXmlRpcProductType(productType));
Metadata m = new Metadata();
m.addMetadata((Hashtable<String, Object>) this.client.execute(
"filemgr.getCatalogValues", args));
return m;
}
public Metadata getOrigValues(Metadata metadata, ProductType productType)
throws XmlRpcException, IOException {
Vector<Object> args = new Vector<Object>();
args.add(metadata.getHashtable());
args.add(XmlRpcStructFactory.getXmlRpcProductType(productType));
Metadata m = new Metadata();
m.addMetadata((Hashtable<String, Object>) this.client.execute(
"filemgr.getOrigValues", args));
return m;
}
public Query getCatalogQuery(Query query, ProductType productType)
throws XmlRpcException, IOException {
Vector<Object> args = new Vector<Object>();
args.add(XmlRpcStructFactory.getXmlRpcQuery(query));
args.add(XmlRpcStructFactory.getXmlRpcProductType(productType));
return XmlRpcStructFactory
.getQueryFromXmlRpc((Hashtable<String, Object>) this.client
.execute("filemgr.getCatalogQuery", args));
}
public static void main(String[] args) {
CmdLineUtility cmdLineUtility = new CmdLineUtility();
cmdLineUtility.run(args);
}
/**
* @return Returns the fileManagerUrl.
*/
public URL getFileManagerUrl() {
return fileManagerUrl;
}
/**
* @param fileManagerUrl
* The fileManagerUrl to set.
*/
public void setFileManagerUrl(URL fileManagerUrl) {
this.fileManagerUrl = fileManagerUrl;
// reset the client
this.client = new XmlRpcClient(fileManagerUrl);
}
/**
* @return Returns the dataTransfer.
*/
public DataTransfer getDataTransfer() {
return dataTransfer;
}
/**
* @param dataTransfer
* The dataTransfer to set.
*/
public void setDataTransfer(DataTransfer dataTransfer) {
this.dataTransfer = dataTransfer;
this.dataTransfer.setFileManagerUrl(this.fileManagerUrl);
}
}
|
Sync reference is using server side versioning
OODT-681
git-svn-id: cd5c091416a298f3e35c4136755389c696553b5d@1592165 13f79535-47bb-0310-9956-ffa450edef68
|
filemgr/src/main/java/org/apache/oodt/cas/filemgr/system/XmlRpcFileManagerClient.java
|
Sync reference is using server side versioning
|
<ide><path>ilemgr/src/main/java/org/apache/oodt/cas/filemgr/system/XmlRpcFileManagerClient.java
<ide> + e.getMessage());
<ide> throw e;
<ide> }
<add> } else {
<add> product.setProductReferences(getProductReferences(product));
<ide> }
<ide>
<ide> // now transfer the product
|
|
Java
|
apache-2.0
|
90cae9fac3a92c8756f679dd80833be3a4dd9b9c
| 0 |
0xERR0R/jmstool,0xERR0R/jmstool,0xERR0R/jmstool,0xERR0R/jmstool
|
package jmstool.jms;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import com.machinezoo.noexception.Exceptions;
import jmstool.model.SimpleMessage;
import jmstool.storage.LocalMessageStorage;
/**
* Message listener for single JMS queue. Each new message will be added to
* {@link LocalMessageStorage}
*
*/
public class JmsMessageListener implements MessageListener {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public static final String JMS_IBM_CHARACTER_SET = "JMS_IBM_Character_Set";
private final LocalMessageStorage storage;
private final String queue;
private final List<String> propertiesToExtract;
private final String encoding;
private final MessageConverter messageConverter = new SimpleMessageConverter();
public JmsMessageListener(String queue, LocalMessageStorage storage, List<String> propertiesToExtract,
String encoding) {
super();
this.queue = queue;
this.storage = storage;
this.propertiesToExtract = propertiesToExtract;
this.encoding = encoding;
}
@Override
public void onMessage(Message msg) {
logger.debug("received new message from queue '{}'", queue);
String text = Exceptions.sneak().get(() -> extractTextFromMessage(msg));
SimpleMessage message = new SimpleMessage(text, queue, getMessageProperties(msg));
storage.addMessage(message);
}
private String extractTextFromMessage(Message msg) throws JMSException {
String text = null;
if (msg instanceof TextMessage) {
text = (String) messageConverter.fromMessage(msg);
} else if (msg instanceof BytesMessage) {
BytesMessage bytesMessage = (BytesMessage) msg;
byte[] bytes = (byte[]) messageConverter.fromMessage(bytesMessage);
text = new String(bytes, Charset.forName(encodingFromMessageOrDefault(bytesMessage)));
} else {
text = String.format("Unsupported message type: '%s'", msg.getClass().getName());
logger.warn(text);
}
return text;
}
/**
* @see com.ibm.msg.client.jms.JmsConstants.JMS_IBM_CHARACTER_SET
*/
private String encodingFromMessageOrDefault(BytesMessage bytesMessage) {
String charset = Exceptions.log(logger)
.get(Exceptions.sneak().supplier(() -> bytesMessage.getStringProperty(JMS_IBM_CHARACTER_SET)))
.orElse(encoding);
return charset;
}
public Map<String, String> getMessageProperties(Message msg) {
Map<String, String> msgProps = new HashMap<>();
@SuppressWarnings("unchecked")
Enumeration<String> propertyNames = Exceptions.sneak().get(() -> msg.getPropertyNames());
Collections.list(propertyNames).stream().filter(p -> propertiesToExtract.contains(p))
.forEach(p -> msgProps.put(p, Exceptions.sneak().get(() -> msg.getStringProperty(p))));
return msgProps;
}
}
|
backend/src/main/java/jmstool/jms/JmsMessageListener.java
|
package jmstool.jms;
import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.machinezoo.noexception.Exceptions;
import jmstool.model.SimpleMessage;
import jmstool.storage.LocalMessageStorage;
/**
* Message listener for single JMS queue. Each new message will be added to
* {@link LocalMessageStorage}
*
*/
public class JmsMessageListener implements MessageListener {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public static final String JMS_IBM_CHARACTER_SET = "JMS_IBM_Character_Set";
private final LocalMessageStorage storage;
private final String queue;
private final List<String> propertiesToExtract;
private final String encoding;
public JmsMessageListener(String queue, LocalMessageStorage storage, List<String> propertiesToExtract,
String encoding) {
super();
this.queue = queue;
this.storage = storage;
this.propertiesToExtract = propertiesToExtract;
this.encoding = encoding;
}
@Override
public void onMessage(Message msg) {
logger.debug("received new message from queue '{}'", queue);
String text = Exceptions.sneak().get(() -> extractTextFromMessage(msg));
SimpleMessage message = new SimpleMessage(text, queue, getMessageProperties(msg));
storage.addMessage(message);
}
private String extractTextFromMessage(Message msg) throws JMSException {
String text = null;
if (msg instanceof TextMessage) {
TextMessage textMessage = (TextMessage) msg;
text = Exceptions.sneak().get(() -> textMessage.getText());
} else if (msg instanceof BytesMessage) {
BytesMessage bytesMessage = (BytesMessage) msg;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int n = 0;
byte[] buf = new byte[(int) (bytesMessage.getBodyLength() > Integer.MAX_VALUE ? 1024
: bytesMessage.getBodyLength())];
while ((n = bytesMessage.readBytes(buf)) >= 0) {
out.write(buf, 0, n);
}
byte[] bytes = out.toByteArray();
text = new String(bytes, Charset.forName(encodingFromMessageOrDefault(bytesMessage)));
} else {
text = String.format("Unsupported message type: '%s'", msg.getClass().getName());
logger.warn(text);
}
return text;
}
/**
* @see com.ibm.msg.client.jms.JmsConstants.JMS_IBM_CHARACTER_SET
*/
private String encodingFromMessageOrDefault(BytesMessage bytesMessage) {
String charset = Exceptions.log(logger)
.get(Exceptions.sneak().supplier(() -> bytesMessage.getStringProperty(JMS_IBM_CHARACTER_SET)))
.orElse(encoding);
return charset;
}
public Map<String, String> getMessageProperties(Message msg) {
Map<String, String> msgProps = new HashMap<>();
@SuppressWarnings("unchecked")
Enumeration<String> propertyNames = Exceptions.sneak().get(() -> msg.getPropertyNames());
Collections.list(propertyNames).stream().filter(p -> propertiesToExtract.contains(p))
.forEach(p -> msgProps.put(p, Exceptions.sneak().get(() -> msg.getStringProperty(p))));
return msgProps;
}
}
|
Using MessageConverter to extract message content
|
backend/src/main/java/jmstool/jms/JmsMessageListener.java
|
Using MessageConverter to extract message content
|
<ide><path>ackend/src/main/java/jmstool/jms/JmsMessageListener.java
<ide> package jmstool.jms;
<ide>
<del>import java.io.ByteArrayOutputStream;
<ide> import java.nio.charset.Charset;
<ide> import java.util.Collections;
<ide> import java.util.Enumeration;
<ide>
<ide> import org.slf4j.Logger;
<ide> import org.slf4j.LoggerFactory;
<add>import org.springframework.jms.support.converter.MessageConverter;
<add>import org.springframework.jms.support.converter.SimpleMessageConverter;
<ide>
<ide> import com.machinezoo.noexception.Exceptions;
<ide>
<ide>
<ide> private final String encoding;
<ide>
<add> private final MessageConverter messageConverter = new SimpleMessageConverter();
<add>
<ide> public JmsMessageListener(String queue, LocalMessageStorage storage, List<String> propertiesToExtract,
<ide> String encoding) {
<ide> super();
<ide> String text = null;
<ide>
<ide> if (msg instanceof TextMessage) {
<del> TextMessage textMessage = (TextMessage) msg;
<del> text = Exceptions.sneak().get(() -> textMessage.getText());
<add> text = (String) messageConverter.fromMessage(msg);
<ide> } else if (msg instanceof BytesMessage) {
<ide> BytesMessage bytesMessage = (BytesMessage) msg;
<del> ByteArrayOutputStream out = new ByteArrayOutputStream();
<del> int n = 0;
<del> byte[] buf = new byte[(int) (bytesMessage.getBodyLength() > Integer.MAX_VALUE ? 1024
<del> : bytesMessage.getBodyLength())];
<del> while ((n = bytesMessage.readBytes(buf)) >= 0) {
<del> out.write(buf, 0, n);
<del> }
<del> byte[] bytes = out.toByteArray();
<del>
<add> byte[] bytes = (byte[]) messageConverter.fromMessage(bytesMessage);
<ide> text = new String(bytes, Charset.forName(encodingFromMessageOrDefault(bytesMessage)));
<ide> } else {
<ide> text = String.format("Unsupported message type: '%s'", msg.getClass().getName());
|
|
Java
|
mit
|
1a5dbed7349cccc85266dc9af31a9c340fbef2e6
| 0 |
mySingleLive/forest
|
package com.dtflys.test.http;
import com.dtflys.forest.backend.HttpBackend;
import com.dtflys.forest.config.ForestConfiguration;
import com.dtflys.test.mock.PostMockServer;
import com.dtflys.test.http.client.PostClient;
import com.dtflys.test.http.model.UserParam;
import com.dtflys.test.mock.PutMockServer;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* @author gongjun[[email protected]]
* @since 2017-05-11 16:55
*/
public class TestPostClient extends BaseClientTest {
private final static Logger log = LoggerFactory.getLogger(TestPostClient.class);
@Rule
public PostMockServer server = new PostMockServer(this);
private static ForestConfiguration configuration;
private static PostClient postClient;
@BeforeClass
public static void prepareClient() {
configuration = ForestConfiguration.configuration();
}
public TestPostClient(HttpBackend backend) {
super(backend, configuration);
postClient = configuration.createInstance(PostClient.class);
}
@Before
public void prepareMockServer() {
server.initServer();
}
@Test
public void testSimplePost() {
String result = postClient.simplePost();
log.info("response: " + result);
assertNotNull(result);
assertEquals(PostMockServer.EXPECTED, result);
}
@Test
public void testTextParamPost() {
String result = postClient.textParamPost("foo", "123456");
log.info("response: " + result);
assertNotNull(result);
assertEquals(PostMockServer.EXPECTED, result);
}
@Test
public void testVarParamPost() {
String result = postClient.varParamPost("foo", "123456");
log.info("response: " + result);
assertNotNull(result);
assertEquals(PostMockServer.EXPECTED, result);
}
@Test
public void testModelParamPost() {
UserParam userParam = new UserParam();
userParam.setUsername("foo");
userParam.setPassword("123456");
String result = postClient.modelParamPost(userParam);
log.info("response: " + result);
assertNotNull(result);
assertEquals(PostMockServer.EXPECTED, result);
}
@Test
public void testAnnParamPost() {
String result = postClient.annParamPost("foo", "123456");
log.info("response: " + result);
assertNotNull(result);
assertEquals(PutMockServer.EXPECTED, result);
}
/*
@Test
public void testModelParamNumPost() {
UserParam userParam = new UserParam();
userParam.setUsername("foo");
userParam.setPassword("123456");
String result = postClient.modelParamNumPost(userParam);
log.info("response: " + result);
assertNotNull(result);
assertEquals(PostMockServer.EXPECTED, result);
}
*/
}
|
forest-core/src/test/java/com/dtflys/test/http/TestPostClient.java
|
package com.dtflys.test.http;
import com.dtflys.forest.backend.HttpBackend;
import com.dtflys.forest.config.ForestConfiguration;
import com.dtflys.test.mock.PostMockServer;
import com.dtflys.forest.backend.HttpBackend;
import com.dtflys.forest.backend.okhttp3.OkHttp3Backend;
import com.dtflys.forest.config.ForestConfiguration;
import com.dtflys.test.http.client.PostClient;
import com.dtflys.test.http.model.UserParam;
import com.dtflys.test.mock.PostMockServer;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* @author gongjun[[email protected]]
* @since 2017-05-11 16:55
*/
public class TestPostClient extends BaseClientTest {
private final static Logger log = LoggerFactory.getLogger(TestPostClient.class);
@Rule
public PostMockServer server = new PostMockServer(this);
private static ForestConfiguration configuration;
private static PostClient postClient;
@BeforeClass
public static void prepareClient() {
configuration = ForestConfiguration.configuration();
}
public TestPostClient(HttpBackend backend) {
super(backend, configuration);
postClient = configuration.createInstance(PostClient.class);
}
@Before
public void prepareMockServer() {
server.initServer();
}
@Test
public void testSimplePost() {
String result = postClient.simplePost();
log.info("response: " + result);
assertNotNull(result);
assertEquals(PostMockServer.EXPECTED, result);
}
@Test
public void testTextParamPost() {
String result = postClient.textParamPost("foo", "123456");
log.info("response: " + result);
assertNotNull(result);
assertEquals(PostMockServer.EXPECTED, result);
}
@Test
public void testAnnParamPost() {
String result = postClient.textParamPost("foo", "123456");
log.info("response: " + result);
assertNotNull(result);
assertEquals(PostMockServer.EXPECTED, result);
}
@Test
public void testVarParamPost() {
String result = postClient.varParamPost("foo", "123456");
log.info("response: " + result);
assertNotNull(result);
assertEquals(PostMockServer.EXPECTED, result);
}
@Test
public void testModelParamPost() {
UserParam userParam = new UserParam();
userParam.setUsername("foo");
userParam.setPassword("123456");
String result = postClient.modelParamPost(userParam);
log.info("response: " + result);
assertNotNull(result);
assertEquals(PostMockServer.EXPECTED, result);
}
/*
@Test
public void testModelParamNumPost() {
UserParam userParam = new UserParam();
userParam.setUsername("foo");
userParam.setPassword("123456");
String result = postClient.modelParamNumPost(userParam);
log.info("response: " + result);
assertNotNull(result);
assertEquals(PostMockServer.EXPECTED, result);
}
*/
}
|
fix: 请求体测试
|
forest-core/src/test/java/com/dtflys/test/http/TestPostClient.java
|
fix: 请求体测试
|
<ide><path>orest-core/src/test/java/com/dtflys/test/http/TestPostClient.java
<ide> import com.dtflys.forest.backend.HttpBackend;
<ide> import com.dtflys.forest.config.ForestConfiguration;
<ide> import com.dtflys.test.mock.PostMockServer;
<del>import com.dtflys.forest.backend.HttpBackend;
<del>import com.dtflys.forest.backend.okhttp3.OkHttp3Backend;
<del>import com.dtflys.forest.config.ForestConfiguration;
<ide> import com.dtflys.test.http.client.PostClient;
<ide> import com.dtflys.test.http.model.UserParam;
<del>import com.dtflys.test.mock.PostMockServer;
<add>import com.dtflys.test.mock.PutMockServer;
<ide> import org.junit.Before;
<ide> import org.junit.BeforeClass;
<ide> import org.junit.Rule;
<ide> }
<ide>
<ide> @Test
<del> public void testAnnParamPost() {
<del> String result = postClient.textParamPost("foo", "123456");
<del> log.info("response: " + result);
<del> assertNotNull(result);
<del> assertEquals(PostMockServer.EXPECTED, result);
<del> }
<del>
<del> @Test
<ide> public void testVarParamPost() {
<ide> String result = postClient.varParamPost("foo", "123456");
<ide> log.info("response: " + result);
<ide> assertEquals(PostMockServer.EXPECTED, result);
<ide> }
<ide>
<add> @Test
<add> public void testAnnParamPost() {
<add> String result = postClient.annParamPost("foo", "123456");
<add> log.info("response: " + result);
<add> assertNotNull(result);
<add> assertEquals(PutMockServer.EXPECTED, result);
<add> }
<add>
<ide>
<ide> /*
<ide> @Test
|
|
JavaScript
|
bsd-2-clause
|
26cce79170d3850dacb9bb1d71cecb0c182a3312
| 0 |
Trufi/Leaflet,stefanocudini/Leaflet,codeator/Leaflet,msiadak/Leaflet,stefanocudini/Leaflet,Leaflet/Leaflet,CapeSepias/Leaflet,frogcat/Leaflet,frogcat/Leaflet,davojta/Leaflet,msiadak/Leaflet,iZucken/Leaflet,codeator/Leaflet,Neorth/Leaflet,rlugojr/Leaflet,Ubisense/Leaflet,jasonoverland/Leaflet,CapeSepias/Leaflet,Leaflet/Leaflet,Ubisense/Leaflet,davojta/Leaflet,geoloep/Leaflet,iZucken/Leaflet,scaddenp/Leaflet,iZucken/Leaflet,msiadak/Leaflet,Trufi/Leaflet,Trufi/Leaflet,AP-whitehat/Leaflet,davojta/Leaflet,rlugojr/Leaflet,codeator/Leaflet,stefanocudini/Leaflet,Neorth/Leaflet,jasonoverland/Leaflet,AP-whitehat/Leaflet,scaddenp/Leaflet,Neorth/Leaflet,CapeSepias/Leaflet,geoloep/Leaflet,rlugojr/Leaflet,geoloep/Leaflet,Leaflet/Leaflet,frogcat/Leaflet,jasonoverland/Leaflet,scaddenp/Leaflet,AP-whitehat/Leaflet,Ubisense/Leaflet
|
/*
* @namespace CRS
* @crs L.CRS.EPSG4326
*
* A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
*
* Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),
* which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`
* with this CRS, ensure that there are two 256x256 pixel tiles covering the
* whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),
* or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.
*/
L.CRS.EPSG4326 = L.extend({}, L.CRS.Earth, {
code: 'EPSG:4326',
projection: L.Projection.LonLat,
transformation: new L.Transformation(1 / 180, 1, -1 / 180, 0.5)
});
|
src/geo/crs/CRS.EPSG4326.js
|
/*
* @namespace CRS
* @crs L.CRS.EPSG4326
*
* A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
*/
L.CRS.EPSG4326 = L.extend({}, L.CRS.Earth, {
code: 'EPSG:4326',
projection: L.Projection.LonLat,
transformation: new L.Transformation(1 / 180, 1, -1 / 180, 0.5)
});
|
Mention TMS tile scheme for EPSG:4326 proj, fixes #5072
|
src/geo/crs/CRS.EPSG4326.js
|
Mention TMS tile scheme for EPSG:4326 proj, fixes #5072
|
<ide><path>rc/geo/crs/CRS.EPSG4326.js
<ide> * @crs L.CRS.EPSG4326
<ide> *
<ide> * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
<add> *
<add> * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),
<add> * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`
<add> * with this CRS, ensure that there are two 256x256 pixel tiles covering the
<add> * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),
<add> * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.
<ide> */
<ide>
<ide> L.CRS.EPSG4326 = L.extend({}, L.CRS.Earth, {
|
|
JavaScript
|
mit
|
934d316dd604ea72161ed5d9342ea0b228fe7ba3
| 0 |
djmiley/d3fc-showcase,jleft/BitFlux,jdhodges/d3fc-showcase,rjmcneill/d3fc-showcase,djmiley/d3fc-showcase,rjmcneill/d3fc-showcase,ScottLogic/d3fc-showcase,jleft/d3fc-showcase,ScottLogic/BitFlux,ScottLogic/d3fc-showcase,jleft/BitFlux,jdhodges/d3fc-showcase,jleft/d3fc-showcase,rjmcneill/d3fc-showcase,jdhodges/d3fc-showcase,djmiley/d3fc-showcase,ScottLogic/BitFlux,ScottLogic/d3fc-showcase,jleft/d3fc-showcase
|
import d3 from 'd3';
import fc from 'd3fc';
export default function() {
var historicFeed = fc.data.feed.quandl()
.database('WIKI')
.columnNameMap(mapColumnNames),
granularity,
candles;
// More options are allowed through the API; for now, only support daily and weekly
var allowedPeriods = d3.map();
allowedPeriods.set(60 * 60 * 24, 'daily');
allowedPeriods.set(60 * 60 * 24 * 7, 'weekly');
// Map fields for WIKI database, to use all adjusted values
var columnNameMap = d3.map();
columnNameMap.set('Open', 'unadjustedOpen');
columnNameMap.set('High', 'unadjustedHigh');
columnNameMap.set('Low', 'unadjustedLow');
columnNameMap.set('Close', 'unadjustedClose');
columnNameMap.set('Volume', 'unadjustedVolume');
columnNameMap.set('Adj. Open', 'open');
columnNameMap.set('Adj. High', 'high');
columnNameMap.set('Adj. Low', 'low');
columnNameMap.set('Adj. Close', 'close');
columnNameMap.set('Adj. Volume', 'volume');
function mapColumnNames(colName) {
var mappedName = columnNameMap.get(colName);
if (!mappedName) {
mappedName = colName[0].toLowerCase() + colName.substr(1);
}
return mappedName;
}
function normaliseDataDateToStartOfDay(data) {
return data.map(function(datum) {
datum.date.setHours(0, 0, 0, 0);
return datum;
});
}
function quandlAdaptor(cb) {
var startDate = d3.time.second.offset(historicFeed.end(), -candles * granularity);
historicFeed.start(startDate)
.collapse(allowedPeriods.get(granularity));
historicFeed(function(err, data) {
var normalisedData = normaliseDataDateToStartOfDay(data);
cb(err, normalisedData);
});
}
quandlAdaptor.candles = function(x) {
if (!arguments.length) {
return candles;
}
candles = x;
return quandlAdaptor;
};
quandlAdaptor.granularity = function(x) {
if (!arguments.length) {
return granularity;
}
if (!allowedPeriods.has(x)) {
throw new Error('Granularity of ' + x + ' is not supported.');
}
granularity = x;
return quandlAdaptor;
};
fc.util.rebind(quandlAdaptor, historicFeed, {
end: 'end',
product: 'dataset',
apiKey: 'apiKey'
});
return quandlAdaptor;
}
|
src/assets/js/data/quandl/historic/feedAdaptor.js
|
import d3 from 'd3';
import fc from 'd3fc';
export default function() {
var historicFeed = fc.data.feed.quandl()
.database('WIKI')
.columnNameMap(mapColumnNames),
granularity,
candles;
// More options are allowed through the API; for now, only support daily and weekly
var allowedPeriods = d3.map();
allowedPeriods.set(60 * 60 * 24, 'daily');
allowedPeriods.set(60 * 60 * 24 * 7, 'weekly');
// Map fields for WIKI database, to use all adjusted values
var columnNameMap = d3.map();
columnNameMap.set('Open', 'unadjustedOpen');
columnNameMap.set('High', 'unadjustedHigh');
columnNameMap.set('Low', 'unadjustedLow');
columnNameMap.set('Close', 'unadjustedClose');
columnNameMap.set('Volume', 'unadjustedVolume');
columnNameMap.set('Adj. Open', 'open');
columnNameMap.set('Adj. High', 'high');
columnNameMap.set('Adj. Low', 'low');
columnNameMap.set('Adj. Close', 'close');
columnNameMap.set('Adj. Volume', 'volume');
function mapColumnNames(colName) {
var mappedName = columnNameMap.get(colName);
if (!mappedName) {
mappedName = colName[0].toLowerCase() + colName.substr(1);
}
return mappedName;
}
function quandlAdaptor(cb) {
var startDate = d3.time.second.offset(historicFeed.end(), -candles * granularity);
historicFeed.start(startDate)
.collapse(allowedPeriods.get(granularity));
historicFeed(cb);
}
quandlAdaptor.candles = function(x) {
if (!arguments.length) {
return candles;
}
candles = x;
return quandlAdaptor;
};
quandlAdaptor.granularity = function(x) {
if (!arguments.length) {
return granularity;
}
if (!allowedPeriods.has(x)) {
throw new Error('Granularity of ' + x + ' is not supported.');
}
granularity = x;
return quandlAdaptor;
};
fc.util.rebind(quandlAdaptor, historicFeed, {
end: 'end',
product: 'dataset',
apiKey: 'apiKey'
});
return quandlAdaptor;
}
|
Normalise Quandl dates to midnight
|
src/assets/js/data/quandl/historic/feedAdaptor.js
|
Normalise Quandl dates to midnight
|
<ide><path>rc/assets/js/data/quandl/historic/feedAdaptor.js
<ide> return mappedName;
<ide> }
<ide>
<add> function normaliseDataDateToStartOfDay(data) {
<add> return data.map(function(datum) {
<add> datum.date.setHours(0, 0, 0, 0);
<add> return datum;
<add> });
<add> }
<add>
<ide> function quandlAdaptor(cb) {
<ide> var startDate = d3.time.second.offset(historicFeed.end(), -candles * granularity);
<ide> historicFeed.start(startDate)
<ide> .collapse(allowedPeriods.get(granularity));
<del> historicFeed(cb);
<add> historicFeed(function(err, data) {
<add> var normalisedData = normaliseDataDateToStartOfDay(data);
<add> cb(err, normalisedData);
<add> });
<ide> }
<ide>
<ide> quandlAdaptor.candles = function(x) {
|
|
Java
|
apache-2.0
|
4473671dd688ca25e7fc0ca1045d4c88d120ae0c
| 0 |
mbrinkmeier/ScrumProjekt
|
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Holz here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Holz extends ZerstoerbareBloecke
{
public Holz() {
this.getImage().scale(10, 10);
}
/**
* Act - do whatever the Holz wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
// Add your action code here.
}
}
|
Holz.java
|
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Holz here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Holz extends ZerstoerbareBloecke
{
/**
* Act - do whatever the Holz wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
// Add your action code here.
}
}
|
Holz auf 10x10
|
Holz.java
|
Holz auf 10x10
|
<ide><path>olz.java
<ide> */
<ide> public class Holz extends ZerstoerbareBloecke
<ide> {
<add> public Holz() {
<add> this.getImage().scale(10, 10);
<add> }
<ide> /**
<ide> * Act - do whatever the Holz wants to do. This method is called whenever
<ide> * the 'Act' or 'Run' button gets pressed in the environment.
|
|
Java
|
mit
|
f20efd3aa0bb44bb9736d2b3fc6f062f653c7432
| 0 |
CS2103JAN2017-T16-B4/main,CS2103JAN2017-T16-B4/main
|
package guitests;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class ClearCommandTest extends TaskManagerGuiTest {
// @@author A0139448U
@Test
public void clear() {
// verify a non-empty list can be cleared
assertTrue(taskListPanel.isListMatching(td.getTypicalTasks()));
assertClearCommandSuccess();
// verify other commands can work after a clear command
commandBox.runCommand("add Act like a craven");
assertTrue(taskListPanel.isListMatching(td.cower));
commandBox.runCommand("delete 1");
assertListSize(0);
// verify clear command works when the list is empty
assertClearCommandSuccess();
}
private void assertClearCommandSuccess() {
commandBox.runCommand("reset");
assertListSize(0);
assertResultMessage("Task Manager has been reset!");
}
}
|
src/test/java/guitests/ClearCommandTest.java
|
package guitests;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class ClearCommandTest extends TaskManagerGuiTest {
@Test
public void clear() {
// verify a non-empty list can be cleared
assertTrue(taskListPanel.isListMatching(td.getTypicalTasks()));
assertClearCommandSuccess();
// verify other commands can work after a clear command
commandBox.runCommand("add Act like a craven"); // td.cower.getAddCommand()
assertTrue(taskListPanel.isListMatching(td.cower));
commandBox.runCommand("delete 1");
assertListSize(0);
// verify clear command works when the list is empty
assertClearCommandSuccess();
}
private void assertClearCommandSuccess() {
commandBox.runCommand("reset");
assertListSize(0);
assertResultMessage("Task Manager has been reset!");
}
}
|
nothing i think
|
src/test/java/guitests/ClearCommandTest.java
|
nothing i think
|
<ide><path>rc/test/java/guitests/ClearCommandTest.java
<ide>
<ide> public class ClearCommandTest extends TaskManagerGuiTest {
<ide>
<add> // @@author A0139448U
<ide> @Test
<ide> public void clear() {
<ide>
<ide> assertClearCommandSuccess();
<ide>
<ide> // verify other commands can work after a clear command
<del> commandBox.runCommand("add Act like a craven"); // td.cower.getAddCommand()
<add> commandBox.runCommand("add Act like a craven");
<ide> assertTrue(taskListPanel.isListMatching(td.cower));
<ide> commandBox.runCommand("delete 1");
<ide> assertListSize(0);
|
|
Java
|
apache-2.0
|
7d0f48289ba60938cdbf9bbaa1ceb58f44052c84
| 0 |
spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework
|
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.web.context.request.async;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.core.task.SyncTaskExecutor;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.async.DeferredResult.DeferredResultHandler;
/**
* The central class for managing asynchronous request processing, mainly intended
* as an SPI and not typically used directly by application classes.
*
* <p>An async scenario starts with request processing as usual in a thread (T1).
* Concurrent request handling can be initiated by calling
* {@link #startCallableProcessing(Callable, Object...) startCallableProcessing} or
* {@link #startDeferredResultProcessing(DeferredResult, Object...) startDeferredResultProcessing},
* both of which produce a result in a separate thread (T2). The result is saved
* and the request dispatched to the container, to resume processing with the saved
* result in a third thread (T3). Within the dispatched thread (T3), the saved
* result can be accessed via {@link #getConcurrentResult()} or its presence
* detected via {@link #hasConcurrentResult()}.
*
* @author Rossen Stoyanchev
* @author Juergen Hoeller
* @since 3.2
* @see org.springframework.web.context.request.AsyncWebRequestInterceptor
* @see org.springframework.web.servlet.AsyncHandlerInterceptor
* @see org.springframework.web.filter.OncePerRequestFilter#shouldNotFilterAsyncDispatch
* @see org.springframework.web.filter.OncePerRequestFilter#isAsyncDispatch
*/
public final class WebAsyncManager {
private static final Object RESULT_NONE = new Object();
private static final AsyncTaskExecutor DEFAULT_TASK_EXECUTOR =
new SimpleAsyncTaskExecutor(WebAsyncManager.class.getSimpleName());
private static final Log logger = LogFactory.getLog(WebAsyncManager.class);
private static final CallableProcessingInterceptor timeoutCallableInterceptor =
new TimeoutCallableProcessingInterceptor();
private static final DeferredResultProcessingInterceptor timeoutDeferredResultInterceptor =
new TimeoutDeferredResultProcessingInterceptor();
private static Boolean taskExecutorWarning = true;
private AsyncWebRequest asyncWebRequest;
private AsyncTaskExecutor taskExecutor = DEFAULT_TASK_EXECUTOR;
private volatile Object concurrentResult = RESULT_NONE;
private volatile Object[] concurrentResultContext;
/*
* Whether the concurrentResult is an error. If such errors remain unhandled, some
* Servlet containers will call AsyncListener#onError at the end, after the ASYNC
* and/or the ERROR dispatch (Boot's case), and we need to ignore those.
*/
private volatile boolean errorHandlingInProgress;
private final Map<Object, CallableProcessingInterceptor> callableInterceptors = new LinkedHashMap<>();
private final Map<Object, DeferredResultProcessingInterceptor> deferredResultInterceptors = new LinkedHashMap<>();
/**
* Package-private constructor.
* @see WebAsyncUtils#getAsyncManager(javax.servlet.ServletRequest)
* @see WebAsyncUtils#getAsyncManager(org.springframework.web.context.request.WebRequest)
*/
WebAsyncManager() {
}
/**
* Configure the {@link AsyncWebRequest} to use. This property may be set
* more than once during a single request to accurately reflect the current
* state of the request (e.g. following a forward, request/response
* wrapping, etc). However, it should not be set while concurrent handling
* is in progress, i.e. while {@link #isConcurrentHandlingStarted()} is
* {@code true}.
* @param asyncWebRequest the web request to use
*/
public void setAsyncWebRequest(AsyncWebRequest asyncWebRequest) {
Assert.notNull(asyncWebRequest, "AsyncWebRequest must not be null");
this.asyncWebRequest = asyncWebRequest;
this.asyncWebRequest.addCompletionHandler(() -> asyncWebRequest.removeAttribute(
WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST));
}
/**
* Configure an AsyncTaskExecutor for use with concurrent processing via
* {@link #startCallableProcessing(Callable, Object...)}.
* <p>By default a {@link SimpleAsyncTaskExecutor} instance is used.
*/
public void setTaskExecutor(AsyncTaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
/**
* Whether the selected handler for the current request chose to handle the
* request asynchronously. A return value of "true" indicates concurrent
* handling is under way and the response will remain open. A return value
* of "false" means concurrent handling was either not started or possibly
* that it has completed and the request was dispatched for further
* processing of the concurrent result.
*/
public boolean isConcurrentHandlingStarted() {
return (this.asyncWebRequest != null && this.asyncWebRequest.isAsyncStarted());
}
/**
* Whether a result value exists as a result of concurrent handling.
*/
public boolean hasConcurrentResult() {
return (this.concurrentResult != RESULT_NONE);
}
/**
* Provides access to the result from concurrent handling.
* @return an Object, possibly an {@code Exception} or {@code Throwable} if
* concurrent handling raised one.
* @see #clearConcurrentResult()
*/
public Object getConcurrentResult() {
return this.concurrentResult;
}
/**
* Provides access to additional processing context saved at the start of
* concurrent handling.
* @see #clearConcurrentResult()
*/
public Object[] getConcurrentResultContext() {
return this.concurrentResultContext;
}
/**
* Get the {@link CallableProcessingInterceptor} registered under the given key.
* @param key the key
* @return the interceptor registered under that key, or {@code null} if none
*/
@Nullable
public CallableProcessingInterceptor getCallableInterceptor(Object key) {
return this.callableInterceptors.get(key);
}
/**
* Get the {@link DeferredResultProcessingInterceptor} registered under the given key.
* @param key the key
* @return the interceptor registered under that key, or {@code null} if none
*/
@Nullable
public DeferredResultProcessingInterceptor getDeferredResultInterceptor(Object key) {
return this.deferredResultInterceptors.get(key);
}
/**
* Register a {@link CallableProcessingInterceptor} under the given key.
* @param key the key
* @param interceptor the interceptor to register
*/
public void registerCallableInterceptor(Object key, CallableProcessingInterceptor interceptor) {
Assert.notNull(key, "Key is required");
Assert.notNull(interceptor, "CallableProcessingInterceptor is required");
this.callableInterceptors.put(key, interceptor);
}
/**
* Register a {@link CallableProcessingInterceptor} without a key.
* The key is derived from the class name and hashcode.
* @param interceptors one or more interceptors to register
*/
public void registerCallableInterceptors(CallableProcessingInterceptor... interceptors) {
Assert.notNull(interceptors, "A CallableProcessingInterceptor is required");
for (CallableProcessingInterceptor interceptor : interceptors) {
String key = interceptor.getClass().getName() + ":" + interceptor.hashCode();
this.callableInterceptors.put(key, interceptor);
}
}
/**
* Register a {@link DeferredResultProcessingInterceptor} under the given key.
* @param key the key
* @param interceptor the interceptor to register
*/
public void registerDeferredResultInterceptor(Object key, DeferredResultProcessingInterceptor interceptor) {
Assert.notNull(key, "Key is required");
Assert.notNull(interceptor, "DeferredResultProcessingInterceptor is required");
this.deferredResultInterceptors.put(key, interceptor);
}
/**
* Register one or more {@link DeferredResultProcessingInterceptor DeferredResultProcessingInterceptors} without a specified key.
* The default key is derived from the interceptor class name and hash code.
* @param interceptors one or more interceptors to register
*/
public void registerDeferredResultInterceptors(DeferredResultProcessingInterceptor... interceptors) {
Assert.notNull(interceptors, "A DeferredResultProcessingInterceptor is required");
for (DeferredResultProcessingInterceptor interceptor : interceptors) {
String key = interceptor.getClass().getName() + ":" + interceptor.hashCode();
this.deferredResultInterceptors.put(key, interceptor);
}
}
/**
* Clear {@linkplain #getConcurrentResult() concurrentResult} and
* {@linkplain #getConcurrentResultContext() concurrentResultContext}.
*/
public void clearConcurrentResult() {
synchronized (WebAsyncManager.this) {
this.concurrentResult = RESULT_NONE;
this.concurrentResultContext = null;
}
}
/**
* Start concurrent request processing and execute the given task with an
* {@link #setTaskExecutor(AsyncTaskExecutor) AsyncTaskExecutor}. The result
* from the task execution is saved and the request dispatched in order to
* resume processing of that result. If the task raises an Exception then
* the saved result will be the raised Exception.
* @param callable a unit of work to be executed asynchronously
* @param processingContext additional context to save that can be accessed
* via {@link #getConcurrentResultContext()}
* @throws Exception if concurrent processing failed to start
* @see #getConcurrentResult()
* @see #getConcurrentResultContext()
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public void startCallableProcessing(Callable<?> callable, Object... processingContext) throws Exception {
Assert.notNull(callable, "Callable must not be null");
startCallableProcessing(new WebAsyncTask(callable), processingContext);
}
/**
* Use the given {@link WebAsyncTask} to configure the task executor as well as
* the timeout value of the {@code AsyncWebRequest} before delegating to
* {@link #startCallableProcessing(Callable, Object...)}.
* @param webAsyncTask a WebAsyncTask containing the target {@code Callable}
* @param processingContext additional context to save that can be accessed
* via {@link #getConcurrentResultContext()}
* @throws Exception if concurrent processing failed to start
*/
public void startCallableProcessing(final WebAsyncTask<?> webAsyncTask, Object... processingContext)
throws Exception {
Assert.notNull(webAsyncTask, "WebAsyncTask must not be null");
Assert.state(this.asyncWebRequest != null, "AsyncWebRequest must not be null");
Long timeout = webAsyncTask.getTimeout();
if (timeout != null) {
this.asyncWebRequest.setTimeout(timeout);
}
AsyncTaskExecutor executor = webAsyncTask.getExecutor();
if (executor != null) {
this.taskExecutor = executor;
}
else {
logExecutorWarning();
}
List<CallableProcessingInterceptor> interceptors = new ArrayList<>();
interceptors.add(webAsyncTask.getInterceptor());
interceptors.addAll(this.callableInterceptors.values());
interceptors.add(timeoutCallableInterceptor);
final Callable<?> callable = webAsyncTask.getCallable();
final CallableInterceptorChain interceptorChain = new CallableInterceptorChain(interceptors);
this.asyncWebRequest.addTimeoutHandler(() -> {
if (logger.isDebugEnabled()) {
logger.debug("Async request timeout for " + formatRequestUri());
}
Object result = interceptorChain.triggerAfterTimeout(this.asyncWebRequest, callable);
if (result != CallableProcessingInterceptor.RESULT_NONE) {
setConcurrentResultAndDispatch(result);
}
});
this.asyncWebRequest.addErrorHandler(ex -> {
if (!this.errorHandlingInProgress) {
if (logger.isDebugEnabled()) {
logger.debug("Async request error for " + formatRequestUri() + ": " + ex);
}
Object result = interceptorChain.triggerAfterError(this.asyncWebRequest, callable, ex);
result = (result != CallableProcessingInterceptor.RESULT_NONE ? result : ex);
setConcurrentResultAndDispatch(result);
}
});
this.asyncWebRequest.addCompletionHandler(() ->
interceptorChain.triggerAfterCompletion(this.asyncWebRequest, callable));
interceptorChain.applyBeforeConcurrentHandling(this.asyncWebRequest, callable);
startAsyncProcessing(processingContext);
try {
Future<?> future = this.taskExecutor.submit(() -> {
Object result = null;
try {
interceptorChain.applyPreProcess(this.asyncWebRequest, callable);
result = callable.call();
}
catch (Throwable ex) {
result = ex;
}
finally {
result = interceptorChain.applyPostProcess(this.asyncWebRequest, callable, result);
}
setConcurrentResultAndDispatch(result);
});
interceptorChain.setTaskFuture(future);
}
catch (RejectedExecutionException ex) {
Object result = interceptorChain.applyPostProcess(this.asyncWebRequest, callable, ex);
setConcurrentResultAndDispatch(result);
throw ex;
}
}
private void logExecutorWarning() {
if (taskExecutorWarning && logger.isWarnEnabled()) {
synchronized (DEFAULT_TASK_EXECUTOR) {
AsyncTaskExecutor executor = this.taskExecutor;
if (taskExecutorWarning &&
(executor instanceof SimpleAsyncTaskExecutor || executor instanceof SyncTaskExecutor)) {
String executorTypeName = executor.getClass().getSimpleName();
logger.warn("\n!!!\n" +
"An Executor is required to handle java.util.concurrent.Callable return values.\n" +
"Please, configure a TaskExecutor in the MVC config under \"async support\".\n" +
"The " + executorTypeName + " currently in use is not suitable under load.\n" +
"-------------------------------\n" +
"Request URI: '" + formatRequestUri() + "'\n" +
"!!!");
taskExecutorWarning = false;
}
}
}
}
private String formatRequestUri() {
HttpServletRequest request = this.asyncWebRequest.getNativeRequest(HttpServletRequest.class);
return request != null ? request.getRequestURI() : "servlet container";
}
private void setConcurrentResultAndDispatch(Object result) {
synchronized (WebAsyncManager.this) {
if (this.concurrentResult != RESULT_NONE) {
return;
}
this.concurrentResult = result;
this.errorHandlingInProgress = (result instanceof Throwable);
}
if (this.asyncWebRequest.isAsyncComplete()) {
if (logger.isDebugEnabled()) {
logger.debug("Async result set but request already complete: " + formatRequestUri());
}
return;
}
if (logger.isDebugEnabled()) {
boolean isError = result instanceof Throwable;
logger.debug("Async " + (isError ? "error" : "result set") + ", dispatch to " + formatRequestUri());
}
this.asyncWebRequest.dispatch();
}
/**
* Start concurrent request processing and initialize the given
* {@link DeferredResult} with a {@link DeferredResultHandler} that saves
* the result and dispatches the request to resume processing of that
* result. The {@code AsyncWebRequest} is also updated with a completion
* handler that expires the {@code DeferredResult} and a timeout handler
* assuming the {@code DeferredResult} has a default timeout result.
* @param deferredResult the DeferredResult instance to initialize
* @param processingContext additional context to save that can be accessed
* via {@link #getConcurrentResultContext()}
* @throws Exception if concurrent processing failed to start
* @see #getConcurrentResult()
* @see #getConcurrentResultContext()
*/
public void startDeferredResultProcessing(
final DeferredResult<?> deferredResult, Object... processingContext) throws Exception {
Assert.notNull(deferredResult, "DeferredResult must not be null");
Assert.state(this.asyncWebRequest != null, "AsyncWebRequest must not be null");
Long timeout = deferredResult.getTimeoutValue();
if (timeout != null) {
this.asyncWebRequest.setTimeout(timeout);
}
List<DeferredResultProcessingInterceptor> interceptors = new ArrayList<>();
interceptors.add(deferredResult.getInterceptor());
interceptors.addAll(this.deferredResultInterceptors.values());
interceptors.add(timeoutDeferredResultInterceptor);
final DeferredResultInterceptorChain interceptorChain = new DeferredResultInterceptorChain(interceptors);
this.asyncWebRequest.addTimeoutHandler(() -> {
try {
interceptorChain.triggerAfterTimeout(this.asyncWebRequest, deferredResult);
}
catch (Throwable ex) {
setConcurrentResultAndDispatch(ex);
}
});
this.asyncWebRequest.addErrorHandler(ex -> {
if (!this.errorHandlingInProgress) {
try {
if (!interceptorChain.triggerAfterError(this.asyncWebRequest, deferredResult, ex)) {
return;
}
deferredResult.setErrorResult(ex);
}
catch (Throwable interceptorEx) {
setConcurrentResultAndDispatch(interceptorEx);
}
}
});
this.asyncWebRequest.addCompletionHandler(()
-> interceptorChain.triggerAfterCompletion(this.asyncWebRequest, deferredResult));
interceptorChain.applyBeforeConcurrentHandling(this.asyncWebRequest, deferredResult);
startAsyncProcessing(processingContext);
try {
interceptorChain.applyPreProcess(this.asyncWebRequest, deferredResult);
deferredResult.setResultHandler(result -> {
result = interceptorChain.applyPostProcess(this.asyncWebRequest, deferredResult, result);
setConcurrentResultAndDispatch(result);
});
}
catch (Throwable ex) {
setConcurrentResultAndDispatch(ex);
}
}
private void startAsyncProcessing(Object[] processingContext) {
synchronized (WebAsyncManager.this) {
this.concurrentResult = RESULT_NONE;
this.concurrentResultContext = processingContext;
this.errorHandlingInProgress = false;
}
this.asyncWebRequest.startAsync();
if (logger.isDebugEnabled()) {
logger.debug("Started async request");
}
}
}
|
spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncManager.java
|
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.web.context.request.async;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.core.task.SyncTaskExecutor;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.async.DeferredResult.DeferredResultHandler;
/**
* The central class for managing asynchronous request processing, mainly intended
* as an SPI and not typically used directly by application classes.
*
* <p>An async scenario starts with request processing as usual in a thread (T1).
* Concurrent request handling can be initiated by calling
* {@link #startCallableProcessing(Callable, Object...) startCallableProcessing} or
* {@link #startDeferredResultProcessing(DeferredResult, Object...) startDeferredResultProcessing},
* both of which produce a result in a separate thread (T2). The result is saved
* and the request dispatched to the container, to resume processing with the saved
* result in a third thread (T3). Within the dispatched thread (T3), the saved
* result can be accessed via {@link #getConcurrentResult()} or its presence
* detected via {@link #hasConcurrentResult()}.
*
* @author Rossen Stoyanchev
* @author Juergen Hoeller
* @since 3.2
* @see org.springframework.web.context.request.AsyncWebRequestInterceptor
* @see org.springframework.web.servlet.AsyncHandlerInterceptor
* @see org.springframework.web.filter.OncePerRequestFilter#shouldNotFilterAsyncDispatch
* @see org.springframework.web.filter.OncePerRequestFilter#isAsyncDispatch
*/
public final class WebAsyncManager {
private static final Object RESULT_NONE = new Object();
private static final AsyncTaskExecutor DEFAULT_TASK_EXECUTOR =
new SimpleAsyncTaskExecutor(WebAsyncManager.class.getSimpleName());
private static final Log logger = LogFactory.getLog(WebAsyncManager.class);
private static final CallableProcessingInterceptor timeoutCallableInterceptor =
new TimeoutCallableProcessingInterceptor();
private static final DeferredResultProcessingInterceptor timeoutDeferredResultInterceptor =
new TimeoutDeferredResultProcessingInterceptor();
private static Boolean taskExecutorWarning = true;
private AsyncWebRequest asyncWebRequest;
private AsyncTaskExecutor taskExecutor = DEFAULT_TASK_EXECUTOR;
private volatile Object concurrentResult = RESULT_NONE;
private volatile Object[] concurrentResultContext;
private final Map<Object, CallableProcessingInterceptor> callableInterceptors = new LinkedHashMap<>();
private final Map<Object, DeferredResultProcessingInterceptor> deferredResultInterceptors = new LinkedHashMap<>();
/**
* Package-private constructor.
* @see WebAsyncUtils#getAsyncManager(javax.servlet.ServletRequest)
* @see WebAsyncUtils#getAsyncManager(org.springframework.web.context.request.WebRequest)
*/
WebAsyncManager() {
}
/**
* Configure the {@link AsyncWebRequest} to use. This property may be set
* more than once during a single request to accurately reflect the current
* state of the request (e.g. following a forward, request/response
* wrapping, etc). However, it should not be set while concurrent handling
* is in progress, i.e. while {@link #isConcurrentHandlingStarted()} is
* {@code true}.
* @param asyncWebRequest the web request to use
*/
public void setAsyncWebRequest(AsyncWebRequest asyncWebRequest) {
Assert.notNull(asyncWebRequest, "AsyncWebRequest must not be null");
this.asyncWebRequest = asyncWebRequest;
this.asyncWebRequest.addCompletionHandler(() -> asyncWebRequest.removeAttribute(
WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST));
}
/**
* Configure an AsyncTaskExecutor for use with concurrent processing via
* {@link #startCallableProcessing(Callable, Object...)}.
* <p>By default a {@link SimpleAsyncTaskExecutor} instance is used.
*/
public void setTaskExecutor(AsyncTaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
/**
* Whether the selected handler for the current request chose to handle the
* request asynchronously. A return value of "true" indicates concurrent
* handling is under way and the response will remain open. A return value
* of "false" means concurrent handling was either not started or possibly
* that it has completed and the request was dispatched for further
* processing of the concurrent result.
*/
public boolean isConcurrentHandlingStarted() {
return (this.asyncWebRequest != null && this.asyncWebRequest.isAsyncStarted());
}
/**
* Whether a result value exists as a result of concurrent handling.
*/
public boolean hasConcurrentResult() {
return (this.concurrentResult != RESULT_NONE);
}
/**
* Provides access to the result from concurrent handling.
* @return an Object, possibly an {@code Exception} or {@code Throwable} if
* concurrent handling raised one.
* @see #clearConcurrentResult()
*/
public Object getConcurrentResult() {
return this.concurrentResult;
}
/**
* Provides access to additional processing context saved at the start of
* concurrent handling.
* @see #clearConcurrentResult()
*/
public Object[] getConcurrentResultContext() {
return this.concurrentResultContext;
}
/**
* Get the {@link CallableProcessingInterceptor} registered under the given key.
* @param key the key
* @return the interceptor registered under that key, or {@code null} if none
*/
@Nullable
public CallableProcessingInterceptor getCallableInterceptor(Object key) {
return this.callableInterceptors.get(key);
}
/**
* Get the {@link DeferredResultProcessingInterceptor} registered under the given key.
* @param key the key
* @return the interceptor registered under that key, or {@code null} if none
*/
@Nullable
public DeferredResultProcessingInterceptor getDeferredResultInterceptor(Object key) {
return this.deferredResultInterceptors.get(key);
}
/**
* Register a {@link CallableProcessingInterceptor} under the given key.
* @param key the key
* @param interceptor the interceptor to register
*/
public void registerCallableInterceptor(Object key, CallableProcessingInterceptor interceptor) {
Assert.notNull(key, "Key is required");
Assert.notNull(interceptor, "CallableProcessingInterceptor is required");
this.callableInterceptors.put(key, interceptor);
}
/**
* Register a {@link CallableProcessingInterceptor} without a key.
* The key is derived from the class name and hashcode.
* @param interceptors one or more interceptors to register
*/
public void registerCallableInterceptors(CallableProcessingInterceptor... interceptors) {
Assert.notNull(interceptors, "A CallableProcessingInterceptor is required");
for (CallableProcessingInterceptor interceptor : interceptors) {
String key = interceptor.getClass().getName() + ":" + interceptor.hashCode();
this.callableInterceptors.put(key, interceptor);
}
}
/**
* Register a {@link DeferredResultProcessingInterceptor} under the given key.
* @param key the key
* @param interceptor the interceptor to register
*/
public void registerDeferredResultInterceptor(Object key, DeferredResultProcessingInterceptor interceptor) {
Assert.notNull(key, "Key is required");
Assert.notNull(interceptor, "DeferredResultProcessingInterceptor is required");
this.deferredResultInterceptors.put(key, interceptor);
}
/**
* Register one or more {@link DeferredResultProcessingInterceptor DeferredResultProcessingInterceptors} without a specified key.
* The default key is derived from the interceptor class name and hash code.
* @param interceptors one or more interceptors to register
*/
public void registerDeferredResultInterceptors(DeferredResultProcessingInterceptor... interceptors) {
Assert.notNull(interceptors, "A DeferredResultProcessingInterceptor is required");
for (DeferredResultProcessingInterceptor interceptor : interceptors) {
String key = interceptor.getClass().getName() + ":" + interceptor.hashCode();
this.deferredResultInterceptors.put(key, interceptor);
}
}
/**
* Clear {@linkplain #getConcurrentResult() concurrentResult} and
* {@linkplain #getConcurrentResultContext() concurrentResultContext}.
*/
public void clearConcurrentResult() {
synchronized (WebAsyncManager.this) {
this.concurrentResult = RESULT_NONE;
this.concurrentResultContext = null;
}
}
/**
* Start concurrent request processing and execute the given task with an
* {@link #setTaskExecutor(AsyncTaskExecutor) AsyncTaskExecutor}. The result
* from the task execution is saved and the request dispatched in order to
* resume processing of that result. If the task raises an Exception then
* the saved result will be the raised Exception.
* @param callable a unit of work to be executed asynchronously
* @param processingContext additional context to save that can be accessed
* via {@link #getConcurrentResultContext()}
* @throws Exception if concurrent processing failed to start
* @see #getConcurrentResult()
* @see #getConcurrentResultContext()
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public void startCallableProcessing(Callable<?> callable, Object... processingContext) throws Exception {
Assert.notNull(callable, "Callable must not be null");
startCallableProcessing(new WebAsyncTask(callable), processingContext);
}
/**
* Use the given {@link WebAsyncTask} to configure the task executor as well as
* the timeout value of the {@code AsyncWebRequest} before delegating to
* {@link #startCallableProcessing(Callable, Object...)}.
* @param webAsyncTask a WebAsyncTask containing the target {@code Callable}
* @param processingContext additional context to save that can be accessed
* via {@link #getConcurrentResultContext()}
* @throws Exception if concurrent processing failed to start
*/
public void startCallableProcessing(final WebAsyncTask<?> webAsyncTask, Object... processingContext)
throws Exception {
Assert.notNull(webAsyncTask, "WebAsyncTask must not be null");
Assert.state(this.asyncWebRequest != null, "AsyncWebRequest must not be null");
Long timeout = webAsyncTask.getTimeout();
if (timeout != null) {
this.asyncWebRequest.setTimeout(timeout);
}
AsyncTaskExecutor executor = webAsyncTask.getExecutor();
if (executor != null) {
this.taskExecutor = executor;
}
else {
logExecutorWarning();
}
List<CallableProcessingInterceptor> interceptors = new ArrayList<>();
interceptors.add(webAsyncTask.getInterceptor());
interceptors.addAll(this.callableInterceptors.values());
interceptors.add(timeoutCallableInterceptor);
final Callable<?> callable = webAsyncTask.getCallable();
final CallableInterceptorChain interceptorChain = new CallableInterceptorChain(interceptors);
this.asyncWebRequest.addTimeoutHandler(() -> {
if (logger.isDebugEnabled()) {
logger.debug("Async request timeout for " + formatRequestUri());
}
Object result = interceptorChain.triggerAfterTimeout(this.asyncWebRequest, callable);
if (result != CallableProcessingInterceptor.RESULT_NONE) {
setConcurrentResultAndDispatch(result);
}
});
this.asyncWebRequest.addErrorHandler(ex -> {
if (logger.isDebugEnabled()) {
logger.debug("Async request error for " + formatRequestUri() + ": " + ex);
}
Object result = interceptorChain.triggerAfterError(this.asyncWebRequest, callable, ex);
result = (result != CallableProcessingInterceptor.RESULT_NONE ? result : ex);
setConcurrentResultAndDispatch(result);
});
this.asyncWebRequest.addCompletionHandler(() ->
interceptorChain.triggerAfterCompletion(this.asyncWebRequest, callable));
interceptorChain.applyBeforeConcurrentHandling(this.asyncWebRequest, callable);
startAsyncProcessing(processingContext);
try {
Future<?> future = this.taskExecutor.submit(() -> {
Object result = null;
try {
interceptorChain.applyPreProcess(this.asyncWebRequest, callable);
result = callable.call();
}
catch (Throwable ex) {
result = ex;
}
finally {
result = interceptorChain.applyPostProcess(this.asyncWebRequest, callable, result);
}
setConcurrentResultAndDispatch(result);
});
interceptorChain.setTaskFuture(future);
}
catch (RejectedExecutionException ex) {
Object result = interceptorChain.applyPostProcess(this.asyncWebRequest, callable, ex);
setConcurrentResultAndDispatch(result);
throw ex;
}
}
private void logExecutorWarning() {
if (taskExecutorWarning && logger.isWarnEnabled()) {
synchronized (DEFAULT_TASK_EXECUTOR) {
AsyncTaskExecutor executor = this.taskExecutor;
if (taskExecutorWarning &&
(executor instanceof SimpleAsyncTaskExecutor || executor instanceof SyncTaskExecutor)) {
String executorTypeName = executor.getClass().getSimpleName();
logger.warn("\n!!!\n" +
"An Executor is required to handle java.util.concurrent.Callable return values.\n" +
"Please, configure a TaskExecutor in the MVC config under \"async support\".\n" +
"The " + executorTypeName + " currently in use is not suitable under load.\n" +
"-------------------------------\n" +
"Request URI: '" + formatRequestUri() + "'\n" +
"!!!");
taskExecutorWarning = false;
}
}
}
}
private String formatRequestUri() {
HttpServletRequest request = this.asyncWebRequest.getNativeRequest(HttpServletRequest.class);
return request != null ? request.getRequestURI() : "servlet container";
}
private void setConcurrentResultAndDispatch(Object result) {
synchronized (WebAsyncManager.this) {
if (this.concurrentResult != RESULT_NONE) {
return;
}
this.concurrentResult = result;
}
if (this.asyncWebRequest.isAsyncComplete()) {
if (logger.isDebugEnabled()) {
logger.debug("Async result set but request already complete: " + formatRequestUri());
}
return;
}
if (logger.isDebugEnabled()) {
boolean isError = result instanceof Throwable;
logger.debug("Async " + (isError ? "error" : "result set") + ", dispatch to " + formatRequestUri());
}
this.asyncWebRequest.dispatch();
}
/**
* Start concurrent request processing and initialize the given
* {@link DeferredResult} with a {@link DeferredResultHandler} that saves
* the result and dispatches the request to resume processing of that
* result. The {@code AsyncWebRequest} is also updated with a completion
* handler that expires the {@code DeferredResult} and a timeout handler
* assuming the {@code DeferredResult} has a default timeout result.
* @param deferredResult the DeferredResult instance to initialize
* @param processingContext additional context to save that can be accessed
* via {@link #getConcurrentResultContext()}
* @throws Exception if concurrent processing failed to start
* @see #getConcurrentResult()
* @see #getConcurrentResultContext()
*/
public void startDeferredResultProcessing(
final DeferredResult<?> deferredResult, Object... processingContext) throws Exception {
Assert.notNull(deferredResult, "DeferredResult must not be null");
Assert.state(this.asyncWebRequest != null, "AsyncWebRequest must not be null");
Long timeout = deferredResult.getTimeoutValue();
if (timeout != null) {
this.asyncWebRequest.setTimeout(timeout);
}
List<DeferredResultProcessingInterceptor> interceptors = new ArrayList<>();
interceptors.add(deferredResult.getInterceptor());
interceptors.addAll(this.deferredResultInterceptors.values());
interceptors.add(timeoutDeferredResultInterceptor);
final DeferredResultInterceptorChain interceptorChain = new DeferredResultInterceptorChain(interceptors);
this.asyncWebRequest.addTimeoutHandler(() -> {
try {
interceptorChain.triggerAfterTimeout(this.asyncWebRequest, deferredResult);
}
catch (Throwable ex) {
setConcurrentResultAndDispatch(ex);
}
});
this.asyncWebRequest.addErrorHandler(ex -> {
try {
if (!interceptorChain.triggerAfterError(this.asyncWebRequest, deferredResult, ex)) {
return;
}
deferredResult.setErrorResult(ex);
}
catch (Throwable interceptorEx) {
setConcurrentResultAndDispatch(interceptorEx);
}
});
this.asyncWebRequest.addCompletionHandler(()
-> interceptorChain.triggerAfterCompletion(this.asyncWebRequest, deferredResult));
interceptorChain.applyBeforeConcurrentHandling(this.asyncWebRequest, deferredResult);
startAsyncProcessing(processingContext);
try {
interceptorChain.applyPreProcess(this.asyncWebRequest, deferredResult);
deferredResult.setResultHandler(result -> {
result = interceptorChain.applyPostProcess(this.asyncWebRequest, deferredResult, result);
setConcurrentResultAndDispatch(result);
});
}
catch (Throwable ex) {
setConcurrentResultAndDispatch(ex);
}
}
private void startAsyncProcessing(Object[] processingContext) {
synchronized (WebAsyncManager.this) {
this.concurrentResult = RESULT_NONE;
this.concurrentResultContext = processingContext;
}
this.asyncWebRequest.startAsync();
if (logger.isDebugEnabled()) {
logger.debug("Started async request");
}
}
}
|
Improve error handling in WebAsyncManager
See gh-24835
|
spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncManager.java
|
Improve error handling in WebAsyncManager
|
<ide><path>pring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncManager.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> private volatile Object[] concurrentResultContext;
<ide>
<add> /*
<add> * Whether the concurrentResult is an error. If such errors remain unhandled, some
<add> * Servlet containers will call AsyncListener#onError at the end, after the ASYNC
<add> * and/or the ERROR dispatch (Boot's case), and we need to ignore those.
<add> */
<add> private volatile boolean errorHandlingInProgress;
<add>
<ide> private final Map<Object, CallableProcessingInterceptor> callableInterceptors = new LinkedHashMap<>();
<ide>
<ide> private final Map<Object, DeferredResultProcessingInterceptor> deferredResultInterceptors = new LinkedHashMap<>();
<ide> });
<ide>
<ide> this.asyncWebRequest.addErrorHandler(ex -> {
<del> if (logger.isDebugEnabled()) {
<del> logger.debug("Async request error for " + formatRequestUri() + ": " + ex);
<del> }
<del> Object result = interceptorChain.triggerAfterError(this.asyncWebRequest, callable, ex);
<del> result = (result != CallableProcessingInterceptor.RESULT_NONE ? result : ex);
<del> setConcurrentResultAndDispatch(result);
<add> if (!this.errorHandlingInProgress) {
<add> if (logger.isDebugEnabled()) {
<add> logger.debug("Async request error for " + formatRequestUri() + ": " + ex);
<add> }
<add> Object result = interceptorChain.triggerAfterError(this.asyncWebRequest, callable, ex);
<add> result = (result != CallableProcessingInterceptor.RESULT_NONE ? result : ex);
<add> setConcurrentResultAndDispatch(result);
<add> }
<ide> });
<ide>
<ide> this.asyncWebRequest.addCompletionHandler(() ->
<ide> return;
<ide> }
<ide> this.concurrentResult = result;
<add> this.errorHandlingInProgress = (result instanceof Throwable);
<ide> }
<ide>
<ide> if (this.asyncWebRequest.isAsyncComplete()) {
<ide> });
<ide>
<ide> this.asyncWebRequest.addErrorHandler(ex -> {
<del> try {
<del> if (!interceptorChain.triggerAfterError(this.asyncWebRequest, deferredResult, ex)) {
<del> return;
<del> }
<del> deferredResult.setErrorResult(ex);
<del> }
<del> catch (Throwable interceptorEx) {
<del> setConcurrentResultAndDispatch(interceptorEx);
<add> if (!this.errorHandlingInProgress) {
<add> try {
<add> if (!interceptorChain.triggerAfterError(this.asyncWebRequest, deferredResult, ex)) {
<add> return;
<add> }
<add> deferredResult.setErrorResult(ex);
<add> }
<add> catch (Throwable interceptorEx) {
<add> setConcurrentResultAndDispatch(interceptorEx);
<add> }
<ide> }
<ide> });
<ide>
<ide> synchronized (WebAsyncManager.this) {
<ide> this.concurrentResult = RESULT_NONE;
<ide> this.concurrentResultContext = processingContext;
<add> this.errorHandlingInProgress = false;
<ide> }
<ide> this.asyncWebRequest.startAsync();
<ide>
|
|
Java
|
apache-2.0
|
828142771db527f7f679d53fc516987a5982bd8b
| 0 |
wyona/yanel,wyona/yanel,wyona/yanel,wyona/yanel,wyona/yanel,wyona/yanel
|
/*
* Copyright 2016 Wyona
*/
package bar.foo.yanel.impl.resources;
import org.wyona.yanel.impl.resources.BasicXMLResource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
/**
* A simple Resource which extends BasicXMLResource
*/
public class FromScratchResource extends BasicXMLResource {
private static Logger log = LogManager.getLogger(FromScratchResource.class);
/**
* This method overrides the method to create the InputStream called by BasicXMLResource
* Since you extend the BasicXMLResource this has to contain well-formed xml.
* Should return a InputStream which contains XML.
* Use StringBuilder, dom, jdom, org.apache.commons.io.IOUtils and so on to generate the XML.
*
* @see org.wyona.yanel.impl.resources.BasicXMLResource#getContentXML(String)
*/
@Override
protected InputStream getContentXML(String viewId) throws Exception {
if (log.isDebugEnabled()) {
log.debug("requested viewId: " + viewId);
}
StringBuilder sb = new StringBuilder("<?xml version=\"1.0\"?>");
sb.append("<root/>");
return new ByteArrayInputStream(sb.toString().getBytes());
}
}
|
src/build/targets/create-new-resource-type/from-scratch-resource-template/src/java/bar/foo/yanel/impl/resources/FromScratchResource-xml.java
|
/*
* Copyright 2015 Wyona
*/
package bar.foo.yanel.impl.resources;
import org.wyona.yanel.impl.resources.BasicXMLResource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
/**
* A simple Resource which extends BasicXMLResource
*/
public class FromScratchResource extends BasicXMLResource {
private static Logger log = LogManager.getLogger(FromScratchResource.class);
/**
* This method overrides the method to create the InputStream called by BasicXMLResource
* Since you extend the BasicXMLResource this has to contain well-formed xml.
* Should return a InputStream which contains XML.
* Use StringBuilder, dom, jdom, org.apache.commons.io.IOUtils and so on to generate the XML.
*
* @see org.wyona.yanel.impl.resources.BasicXMLResource#getContentXML(String)
*/
@Override
protected InputStream getContentXML(String viewId) throws Exception {
if (log.isDebugEnabled()) {
log.debug("requested viewId: " + viewId);
}
StringBuilder sb = new StringBuilder("<?xml version=\"1.0\"?>");
sb.append("<root/>");
return new ByteArrayInputStream(sb.toString().getBytes());
}
}
|
copyright updated
|
src/build/targets/create-new-resource-type/from-scratch-resource-template/src/java/bar/foo/yanel/impl/resources/FromScratchResource-xml.java
|
copyright updated
|
<ide><path>rc/build/targets/create-new-resource-type/from-scratch-resource-template/src/java/bar/foo/yanel/impl/resources/FromScratchResource-xml.java
<ide> /*
<del> * Copyright 2015 Wyona
<add> * Copyright 2016 Wyona
<ide> */
<ide> package bar.foo.yanel.impl.resources;
<ide>
|
|
JavaScript
|
bsd-3-clause
|
b012211c90c2164658191332f5969531d5697145
| 0 |
aina1205/nmtrypi-seek,BioVeL/seek,HITS-SDBV/nmtrypi-seek,kjgarza/frame_experiment,HITS-SDBV/seek,SynthSys/seek,SynthSys/seek,kjgarza/frame_experiment,aina1205/nmtrypi-seek,HITS-SDBV/seek,Virtual-Liver-Network/seek,aina1205/SysMO-DB-seek,BioVeL/seek,Virtual-Liver-Network/seek,stuzart/seek,aina1205/nmtrypi-seek,HITS-SDBV/seek,kjgarza/frame_experiment,aina1205/nmtrypi-seek,BioVeL/seek,stuzart/seek,HITS-SDBV/seek,SynthSys/seek,stuzart/seek,BioVeL/seek,Virtual-Liver-Network/seek,kjgarza/frame_experiment,SynthSys/seek,HITS-SDBV/nmtrypi-seek,Virtual-Liver-Network/seek,HITS-SDBV/nmtrypi-seek,HITS-SDBV/nmtrypi-seek,aina1205/SysMO-DB-seek,aina1205/SysMO-DB-seek
|
function animateNode(node){
var nodes = cy.$('node');
var edges = cy.$('edge');
//first normalizing all nodes and fading all nodes and edges
normalizingNodes(nodes);
fadingNodes(nodes);
fadingEdges(edges);
//then appearing the chosen node and the connected nodes and edges
appearingNodes(node);
edges.each(function(i, edge){
var source = edge.source();
var target =edge.target();
if (source.id() == node.id()){
appearingEdges(edge);
appearingNodes(target);
}
if (target.id() == node.id()){
appearingEdges(edge);
appearingNodes(source);
}
});
//then animate the chosen node
node.animate({
css: { 'width':250, 'height':50 }
}, {
duration: 300
})
// set font style here for better animation (instead of in animate function).
node.css('font-size', 14);
node.css('font-weight', 'bolder');
if (node.data().name != 'Hidden item')
node.css('color', '#0000e5');
node.select();
}
function displayNodeInfo(node){
var html = "<h3>Chosen item</h3>"
html += "<ul class='items'>";
var item_data = node.data();
html += itemInfo(item_data);
html += '</ul>';
html += '<br/>';
html += "<h3>Connected items</h3>";
html += "<ul class='items'>";
var connected_nodes = connectedNodes(node);
for(var i=0;i<connected_nodes.length;i++){
var item_data = connected_nodes[i].data();
html += itemInfo(item_data);
}
html += '</ul>';
var node_info = $('node_info');
$('node_info').innerHTML = html;
//can not use Effect.Appear here, it does not activate clientHeight
node_info.style['display'] = 'block';
alignCenterVertical(node_info, node_info.clientHeight);
}
function itemInfo(item_data){
html = '<li>';
if (item_data.name == 'Hidden item'){
html += item_data.hidden_item_info;
}else{
html += item_data.link;
}
html += '</li>';
return html;
}
function connectedNodes(node){
var edges = cy.$('edge');
var connected_nodes = [];
edges.each(function(i, edge){
var source = edge.source();
var target =edge.target();
if (source.id() == node.id()){
connected_nodes.push(target);
}
if (target.id() == node.id()){
connected_nodes.push(source);
}
});
return connected_nodes;
}
function processPanzoom() {
//display panzoom
$j('#cy').cytoscapePanzoom({
panSpeed: 1
});
//set again the graph height if panzoom height is bigger
var panzoom_height = 220;
var graph_height = cy.container().style.height.split('px')[0];
cy.container().style.height = Math.max(graph_height, panzoom_height) +'px';
alignCenterVertical($j('.ui-cytoscape-panzoom')[0], panzoom_height);
//reset on panzoom also reset all nodes and edges css
$j('.ui-cytoscape-panzoom-reset').click(function () {
var nodes = cy.$('node')
normalizingNodes(nodes);
appearingNodes(nodes);
appearingEdges(cy.$('edge'));
Effect.Fade('node_info', { duration: 0.25 });
});
}
function alignCenterVertical(element, element_height){
var graph_height = cy.container().style.height.split('px')[0];
var distance_from_top = (graph_height - element_height)/2;
if (distance_from_top > 0){
element.style['top']=distance_from_top+'px';
}else{
element.style['top']='0px';
}
}
function appearingNodes(nodes){
nodes.css('opacity', 1);
}
function appearingEdges(edges){
edges.css('opacity', 1);
}
function fadingNodes(nodes){
nodes.css('opacity', 0.3);
}
function fadingEdges(edges){
edges.css('opacity', 0.2);
}
function normalizingNodes(nodes){
nodes.css('width',default_node_width);
nodes.css('height',default_node_height);
nodes.css('font-size',default_font_size);
nodes.css('font-weight', 'normal');
nodes.css('color',default_color);
nodes.unselect();
}
function resizeGraph(){
cy.fit(50);
if (cy.zoom() > 1){
cy.reset();
cy.center();
}
}
function labelPosition(node){
var label_pos = new Object();
var graph_pos = $j('#cy')[0].getBoundingClientRect();
var node_posX = node.renderedPosition().x + graph_pos.left;
var node_posY = node.renderedPosition().y + graph_pos.top;
var font_size = node.renderedCss()['font-size'];
var label = node.data().name;
var ruler = $j('#ruler')[0];
ruler.style.fontSize = font_size;
ruler.style.fontWeight = 'bolder';
ruler.innerHTML = label;
var zoom_level = cy.zoom();
var label_width = ruler.offsetWidth + 2*zoom_level;
var label_height = ruler.offsetHeight;
label_pos.minX = node_posX - label_width/2;
label_pos.maxX = node_posX + label_width/2;
label_pos.minY = node_posY - label_height/2;
label_pos.maxY = node_posY + label_height/2;
return label_pos;
}
function mouseOnLabel(node, mouse_event){
var label_pos = labelPosition(node);
var mouse_posX = mouse_event.clientX;
var mouse_posY = mouse_event.clientY;
var mouse_on_label = mouse_posX > label_pos.minX && mouse_posX < label_pos.maxX && mouse_posY > label_pos.minY && mouse_posY < label_pos.maxY;
return mouse_on_label;
}
function clickLabelLink(node, mouse_event){
if (mouseOnLabel(node, mouse_event)){
var link = document.createElement('a');
link.href = node.data().link.split('"')[1];
clickLink(link);
}
}
// This jquery function is to overide the cytoscape BreadthFirstLayout
(function($$){
var defaults = {
fit: true, // whether to fit the viewport to the graph
ready: undefined, // callback on layoutready
stop: undefined, // callback on layoutstop
directed: true, // whether the tree is directed downwards (or edges can point in any direction if false)
padding: 30, // padding on fit
circle: false, // put depths in concentric circles if true, put depths top down if false
roots: undefined // the roots of the trees
};
function BreadthFirstLayout( options ){
this.options = $$.util.extend({}, defaults, options);
}
BreadthFirstLayout.prototype.run = function(){
var params = this.options;
var options = params;
var cy = params.cy;
var nodes = cy.nodes();
var edges = cy.edges();
var container = cy.container();
//var width = container.clientWidth;
//var height = container.clientHeight;
var roots;
if( $$.is.elementOrCollection(options.roots) ){
roots = options.roots;
} else if( $$.is.array(options.roots) ){
var rootsArray = [];
for( var i = 0; i < options.roots.length; i++ ){
var id = options.roots[i];
var ele = cy.getElementById( id );
roots.push( ele );
}
roots = new $$.Collection( cy, rootsArray );
} else {
roots = nodes.roots();
}
var depths = [];
var foundByBfs = {};
var id2depth = {};
// find the depths of the nodes
roots.bfs(function(i, depth){
var ele = this[0];
if( !depths[depth] ){
depths[depth] = [];
}
depths[depth].push( ele );
foundByBfs[ ele.id() ] = true;
id2depth[ ele.id() ] = depth;
}, options.directed);
// check for nodes not found by bfs
var orphanNodes = [];
for( var i = 0; i < nodes.length; i++ ){
var ele = nodes[i];
if( foundByBfs[ ele.id() ] ){
continue;
} else {
orphanNodes.push( ele );
}
}
// assign orphan nodes a depth from their neighborhood
var maxChecks = orphanNodes.length * 3;
var checks = 0;
while( orphanNodes.length !== 0 && checks < maxChecks ){
var node = orphanNodes.shift();
var neighbors = node.neighborhood().nodes();
var assignedDepth = false;
for( var i = 0; i < neighbors.length; i++ ){
var depth = id2depth[ neighbors[i].id() ];
if( depth !== undefined ){
depths[depth].push( node );
assignedDepth = true;
break;
}
}
if( !assignedDepth ){
orphanNodes.push( node );
}
checks++;
}
// assign orphan nodes that are still left to the depth of their subgraph
while( orphanNodes.length !== 0 ){
var node = orphanNodes.shift();
var subgraph = node.bfs();
var assignedDepth = false;
for( var i = 0; i < subgraph.length; i++ ){
var depth = id2depth[ subgraph[i].id() ];
if( depth !== undefined ){
depths[depth].push( node );
assignedDepth = true;
break;
}
}
if( !assignedDepth ){ // worst case if the graph really isn't tree friendly, then just dump it in 0
if( depths.length === 0 ){
depths.push([]);
}
depths[0].push( node );
}
}
// assign the nodes a depth and index
function assignDepthsToEles(){
for( var i = 0; i < depths.length; i++ ){
var eles = depths[i];
for( var j = 0; j < eles.length; j++ ){
var ele = eles[j];
ele._private.scratch.BreadthFirstLayout = {
depth: i,
index: j
};
}
}
}
assignDepthsToEles();
// find min distance we need to leave between nodes
var minDistance = 0;
for( var i = 0; i < nodes.length; i++ ){
var w = nodes[i].outerWidth();
var h = nodes[i].outerHeight();
minDistance = Math.max(minDistance, w, h);
}
minDistance *= 1.75; // just to have some nice spacing
// get the weighted percent for an element based on its connectivity to other levels
var cachedWeightedPercent = {};
function getWeightedPercent( ele ){
if( cachedWeightedPercent[ ele.id() ] ){
return cachedWeightedPercent[ ele.id() ];
}
var eleDepth = ele._private.scratch.BreadthFirstLayout.depth;
var neighbors = ele.neighborhood().nodes();
var percent = 0;
var samples = 0;
for( var i = 0; i < neighbors.length; i++ ){
var neighbor = neighbors[i];
var nEdges = neighbor.edgesWith( ele );
var index = neighbor._private.scratch.BreadthFirstLayout.index;
var depth = neighbor._private.scratch.BreadthFirstLayout.depth;
var nDepth = depths[depth].length;
if( eleDepth > depth || eleDepth === 0 ){ // only get influenced by elements above
percent += index / nDepth;
samples++;
}
}
samples = Math.max(1, samples);
percent = percent / samples;
if( samples === 0 ){ // so lone nodes have a "don't care" state in sorting
percent = undefined;
}
cachedWeightedPercent[ ele.id() ] = percent;
return percent;
}
// rearrange the indices in each depth level based on connectivity
for( var times = 0; times < 3; times++ ){ // do it a few times b/c the depths are dynamic and we want a more stable result
for( var i = 0; i < depths.length; i++ ){
var depth = i;
var newDepths = [];
depths[i] = depths[i].sort(function(a, b){
var apct = getWeightedPercent( a );
var bpct = getWeightedPercent( b );
return apct - bpct;
});
}
assignDepthsToEles(); // and update
}
var center = {
x: width/2,
y: height/2
};
nodes.positions(function(){
var ele = this[0];
var info = ele._private.scratch.BreadthFirstLayout;
var depth = info.depth;
var index = info.index;
var width = container.clientWidth;
//calculate the height dynamically
var height = graphHeight();
container.style.height = height+'px';
function graphHeight(){
var max_index = 0;
for (var i=0;i<depths.length;i++){
max_index = Math.max(depths[i].length, max_index);
}
return (2*max_index + 1)*nodes[0].outerHeight();
}
var distanceX = Math.max(width / (depths.length + 1), minDistance );
var distanceY = height / (depths[depth].length + 1);
var radiusStepSize = Math.min( width / 2 / depths.length, height / 2 / depths.length );
radiusStepSize = Math.max( radiusStepSize, minDistance );
if( options.circle ){
var radius = radiusStepSize * depth + radiusStepSize - (depths.length > 0 && depths[0].length <= 3 ? radiusStepSize/2 : 0);
var theta = 2 * Math.PI / depths[depth].length * index;
if( depth === 0 && depths[0].length === 1 ){
radius = 1;
}
return {
x: center.x + radius * Math.cos(theta),
y: center.y + radius * Math.sin(theta)
};
} else {
return {
y: (index + 1) * distanceY,
x: (depth + 1) * distanceX
};
}
});
if( params.fit ){
cy.fit( options.padding );
}
cy.one("layoutready", params.ready);
cy.trigger("layoutready");
cy.one("layoutstop", params.stop);
cy.trigger("layoutstop");
};
BreadthFirstLayout.prototype.stop = function(){
// not a continuous layout
};
$$("layout", "breadthfirst", BreadthFirstLayout);
})( cytoscape );
|
app/assets/javascripts/isa_graph.js
|
function animateNode(node){
var nodes = cy.$('node');
var edges = cy.$('edge');
//first normalizing all nodes and fading all nodes and edges
normalizingNodes(nodes);
fadingNodes(nodes);
fadingEdges(edges);
//then appearing the chosen node and the connected nodes and edges
appearingNodes(node);
edges.each(function(i, edge){
var source = edge.source();
var target =edge.target();
if (source.id() == node.id()){
appearingEdges(edge);
appearingNodes(target);
}
if (target.id() == node.id()){
appearingEdges(edge);
appearingNodes(source);
}
});
//then animate the chosen node
node.animate({
css: { 'width':250, 'height':50 }
}, {
duration: 300
})
// set font style here for better animation (instead of in animate function).
node.css('font-size', 14);
node.css('font-weight', 'bolder');
if (node.data().name != 'Hidden item')
node.css('color', '#0000e5');
node.select();
}
function displayNodeInfo(node){
var html = "<h3>Chosen item</h3>"
html += "<ul class='items'>";
var item_data = node.data();
html += itemInfo(item_data);
html += '</ul>';
html += '<br/>';
html += "<h3>Connected items</h3>";
html += "<ul class='items'>";
var connected_nodes = connectedNodes(node);
for(var i=0;i<connected_nodes.length;i++){
var item_data = connected_nodes[i].data();
html += itemInfo(item_data);
}
html += '</ul>';
var node_info = $('node_info');
$('node_info').innerHTML = html;
//can not use Effect.Appear here, it does not activate clientHeight
node_info.style['display'] = 'block';
alignCenterVertical(node_info, node_info.clientHeight);
}
function itemInfo(item_data){
html = '<li>';
if (item_data.name == 'Hidden item'){
html += item_data.hidden_item_info;
}else{
html += item_data.link;
}
html += '</li>';
return html;
}
function connectedNodes(node){
var edges = cy.$('edge');
var connected_nodes = [];
edges.each(function(i, edge){
var source = edge.source();
var target =edge.target();
if (source.id() == node.id()){
connected_nodes.push(target);
}
if (target.id() == node.id()){
connected_nodes.push(source);
}
});
return connected_nodes;
}
function processPanzoom() {
//display panzoom
$j('#cy').cytoscapePanzoom({
panSpeed: 1
});
//set again the graph height if panzoom height is bigger
var panzoom_height = 220;
var graph_height = cy.container().style.height.split('px')[0];
cy.container().style.height = Math.max(graph_height, panzoom_height) +'px';
alignCenterVertical($j('.ui-cytoscape-panzoom')[0], panzoom_height);
//reset on panzoom also reset all nodes and edges css
$j('.ui-cytoscape-panzoom-reset').click(function () {
var nodes = cy.$('node')
normalizingNodes(nodes);
appearingNodes(nodes);
appearingEdges(cy.$('edge'));
Effect.Fade('node_info', { duration: 0.25 });
});
}
function alignCenterVertical(element, element_height){
var graph_height = cy.container().style.height.split('px')[0];
var distance_from_top = (graph_height - element_height)/2;
if (distance_from_top > 0){
element.style['top']=distance_from_top+'px';
}else{
element.style['top']='0px';
}
}
function appearingNodes(nodes){
nodes.css('opacity', 1);
}
function appearingEdges(edges){
edges.css('opacity', 1);
}
function fadingNodes(nodes){
nodes.css('opacity', 0.3);
}
function fadingEdges(edges){
edges.css('opacity', 0.2);
}
function normalizingNodes(nodes){
nodes.css('width',default_node_width);
nodes.css('height',default_node_height);
nodes.css('font-size',default_font_size);
nodes.css('font-weight', 'normal');
nodes.css('color',default_color);
nodes.unselect();
}
function resizeGraph(){
cy.fit(50);
if (cy.zoom() > 1){
cy.reset();
cy.center();
}
}
function labelPosition(node){
var label_pos = new Object();
var graph_pos = $j('#cy')[0].getBoundingClientRect();
var node_posX = node.renderedPosition().x + graph_pos.left;
var node_posY = node.renderedPosition().y + graph_pos.top;
var font_size = node.renderedCss()['font-size'];
var label = node.data().name;
var ruler = $j('#ruler')[0];
ruler.style.fontSize = font_size;
ruler.style.fontWeight = 'bolder';
ruler.innerHTML = label;
var zoom_level = cy.zoom();
var label_width = ruler.offsetWidth + 2*zoom_level;
var label_height = ruler.offsetHeight;
label_pos.minX = node_posX - label_width/2;
label_pos.maxX = node_posX + label_width/2;
label_pos.minY = node_posY - label_height/2;
label_pos.maxY = node_posY + label_height/2;
return label_pos;
}
function mouseOnLabel(node, mouse_event){
var label_pos = labelPosition(node);
var mouse_posX = mouse_event.clientX;
var mouse_posY = mouse_event.clientY;
var mouse_on_label = mouse_posX > label_pos.minX && mouse_posX < label_pos.maxX && mouse_posY > label_pos.minY && mouse_posY < label_pos.maxY;
return mouse_on_label;
}
function clickLabelLink(node, mouse_event){
if (mouseOnLabel(node, mouse_event)){
var link = document.createElement('a');
link.href = node.data().link.split('"')[1];
clickLink(link);
}
}
|
override breadthfirst layout
|
app/assets/javascripts/isa_graph.js
|
override breadthfirst layout
|
<ide><path>pp/assets/javascripts/isa_graph.js
<ide> clickLink(link);
<ide> }
<ide> }
<add>
<add>// This jquery function is to overide the cytoscape BreadthFirstLayout
<add>(function($$){
<add> var defaults = {
<add> fit: true, // whether to fit the viewport to the graph
<add> ready: undefined, // callback on layoutready
<add> stop: undefined, // callback on layoutstop
<add> directed: true, // whether the tree is directed downwards (or edges can point in any direction if false)
<add> padding: 30, // padding on fit
<add> circle: false, // put depths in concentric circles if true, put depths top down if false
<add> roots: undefined // the roots of the trees
<add> };
<add>
<add> function BreadthFirstLayout( options ){
<add> this.options = $$.util.extend({}, defaults, options);
<add> }
<add>
<add> BreadthFirstLayout.prototype.run = function(){
<add> var params = this.options;
<add> var options = params;
<add>
<add> var cy = params.cy;
<add> var nodes = cy.nodes();
<add> var edges = cy.edges();
<add> var container = cy.container();
<add>
<add> //var width = container.clientWidth;
<add> //var height = container.clientHeight;
<add>
<add> var roots;
<add> if( $$.is.elementOrCollection(options.roots) ){
<add> roots = options.roots;
<add> } else if( $$.is.array(options.roots) ){
<add> var rootsArray = [];
<add>
<add> for( var i = 0; i < options.roots.length; i++ ){
<add> var id = options.roots[i];
<add> var ele = cy.getElementById( id );
<add> roots.push( ele );
<add> }
<add>
<add> roots = new $$.Collection( cy, rootsArray );
<add> } else {
<add> roots = nodes.roots();
<add> }
<add>
<add>
<add> var depths = [];
<add> var foundByBfs = {};
<add> var id2depth = {};
<add>
<add> // find the depths of the nodes
<add> roots.bfs(function(i, depth){
<add> var ele = this[0];
<add>
<add> if( !depths[depth] ){
<add> depths[depth] = [];
<add> }
<add>
<add> depths[depth].push( ele );
<add> foundByBfs[ ele.id() ] = true;
<add> id2depth[ ele.id() ] = depth;
<add> }, options.directed);
<add>
<add> // check for nodes not found by bfs
<add> var orphanNodes = [];
<add> for( var i = 0; i < nodes.length; i++ ){
<add> var ele = nodes[i];
<add>
<add> if( foundByBfs[ ele.id() ] ){
<add> continue;
<add> } else {
<add> orphanNodes.push( ele );
<add> }
<add> }
<add>
<add> // assign orphan nodes a depth from their neighborhood
<add> var maxChecks = orphanNodes.length * 3;
<add> var checks = 0;
<add> while( orphanNodes.length !== 0 && checks < maxChecks ){
<add> var node = orphanNodes.shift();
<add> var neighbors = node.neighborhood().nodes();
<add> var assignedDepth = false;
<add>
<add> for( var i = 0; i < neighbors.length; i++ ){
<add> var depth = id2depth[ neighbors[i].id() ];
<add>
<add> if( depth !== undefined ){
<add> depths[depth].push( node );
<add> assignedDepth = true;
<add> break;
<add> }
<add> }
<add>
<add> if( !assignedDepth ){
<add> orphanNodes.push( node );
<add> }
<add>
<add> checks++;
<add> }
<add>
<add> // assign orphan nodes that are still left to the depth of their subgraph
<add> while( orphanNodes.length !== 0 ){
<add> var node = orphanNodes.shift();
<add> var subgraph = node.bfs();
<add> var assignedDepth = false;
<add>
<add> for( var i = 0; i < subgraph.length; i++ ){
<add> var depth = id2depth[ subgraph[i].id() ];
<add>
<add> if( depth !== undefined ){
<add> depths[depth].push( node );
<add> assignedDepth = true;
<add> break;
<add> }
<add> }
<add>
<add> if( !assignedDepth ){ // worst case if the graph really isn't tree friendly, then just dump it in 0
<add> if( depths.length === 0 ){
<add> depths.push([]);
<add> }
<add>
<add> depths[0].push( node );
<add> }
<add> }
<add>
<add> // assign the nodes a depth and index
<add> function assignDepthsToEles(){
<add> for( var i = 0; i < depths.length; i++ ){
<add> var eles = depths[i];
<add>
<add> for( var j = 0; j < eles.length; j++ ){
<add> var ele = eles[j];
<add>
<add> ele._private.scratch.BreadthFirstLayout = {
<add> depth: i,
<add> index: j
<add> };
<add> }
<add> }
<add> }
<add> assignDepthsToEles();
<add>
<add> // find min distance we need to leave between nodes
<add> var minDistance = 0;
<add> for( var i = 0; i < nodes.length; i++ ){
<add> var w = nodes[i].outerWidth();
<add> var h = nodes[i].outerHeight();
<add>
<add> minDistance = Math.max(minDistance, w, h);
<add> }
<add> minDistance *= 1.75; // just to have some nice spacing
<add>
<add> // get the weighted percent for an element based on its connectivity to other levels
<add> var cachedWeightedPercent = {};
<add> function getWeightedPercent( ele ){
<add> if( cachedWeightedPercent[ ele.id() ] ){
<add> return cachedWeightedPercent[ ele.id() ];
<add> }
<add>
<add> var eleDepth = ele._private.scratch.BreadthFirstLayout.depth;
<add> var neighbors = ele.neighborhood().nodes();
<add> var percent = 0;
<add> var samples = 0;
<add>
<add> for( var i = 0; i < neighbors.length; i++ ){
<add> var neighbor = neighbors[i];
<add> var nEdges = neighbor.edgesWith( ele );
<add> var index = neighbor._private.scratch.BreadthFirstLayout.index;
<add> var depth = neighbor._private.scratch.BreadthFirstLayout.depth;
<add> var nDepth = depths[depth].length;
<add>
<add> if( eleDepth > depth || eleDepth === 0 ){ // only get influenced by elements above
<add> percent += index / nDepth;
<add> samples++;
<add> }
<add> }
<add>
<add> samples = Math.max(1, samples);
<add> percent = percent / samples;
<add>
<add> if( samples === 0 ){ // so lone nodes have a "don't care" state in sorting
<add> percent = undefined;
<add> }
<add>
<add> cachedWeightedPercent[ ele.id() ] = percent;
<add> return percent;
<add> }
<add>
<add> // rearrange the indices in each depth level based on connectivity
<add> for( var times = 0; times < 3; times++ ){ // do it a few times b/c the depths are dynamic and we want a more stable result
<add>
<add> for( var i = 0; i < depths.length; i++ ){
<add> var depth = i;
<add> var newDepths = [];
<add>
<add> depths[i] = depths[i].sort(function(a, b){
<add> var apct = getWeightedPercent( a );
<add> var bpct = getWeightedPercent( b );
<add>
<add>
<add> return apct - bpct;
<add> });
<add> }
<add> assignDepthsToEles(); // and update
<add>
<add> }
<add>
<add> var center = {
<add> x: width/2,
<add> y: height/2
<add> };
<add> nodes.positions(function(){
<add> var ele = this[0];
<add> var info = ele._private.scratch.BreadthFirstLayout;
<add> var depth = info.depth;
<add> var index = info.index;
<add>
<add> var width = container.clientWidth;
<add> //calculate the height dynamically
<add> var height = graphHeight();
<add> container.style.height = height+'px';
<add>
<add> function graphHeight(){
<add> var max_index = 0;
<add> for (var i=0;i<depths.length;i++){
<add> max_index = Math.max(depths[i].length, max_index);
<add> }
<add> return (2*max_index + 1)*nodes[0].outerHeight();
<add> }
<add>
<add> var distanceX = Math.max(width / (depths.length + 1), minDistance );
<add> var distanceY = height / (depths[depth].length + 1);
<add> var radiusStepSize = Math.min( width / 2 / depths.length, height / 2 / depths.length );
<add> radiusStepSize = Math.max( radiusStepSize, minDistance );
<add>
<add> if( options.circle ){
<add> var radius = radiusStepSize * depth + radiusStepSize - (depths.length > 0 && depths[0].length <= 3 ? radiusStepSize/2 : 0);
<add> var theta = 2 * Math.PI / depths[depth].length * index;
<add>
<add> if( depth === 0 && depths[0].length === 1 ){
<add> radius = 1;
<add> }
<add>
<add> return {
<add> x: center.x + radius * Math.cos(theta),
<add> y: center.y + radius * Math.sin(theta)
<add> };
<add>
<add> } else {
<add> return {
<add> y: (index + 1) * distanceY,
<add> x: (depth + 1) * distanceX
<add> };
<add> }
<add>
<add> });
<add>
<add> if( params.fit ){
<add> cy.fit( options.padding );
<add> }
<add>
<add> cy.one("layoutready", params.ready);
<add> cy.trigger("layoutready");
<add>
<add> cy.one("layoutstop", params.stop);
<add> cy.trigger("layoutstop");
<add> };
<add>
<add> BreadthFirstLayout.prototype.stop = function(){
<add> // not a continuous layout
<add> };
<add>
<add> $$("layout", "breadthfirst", BreadthFirstLayout);
<add>
<add>})( cytoscape );
|
|
Java
|
apache-2.0
|
c7e0f11ce1562e1151348444c5b505605b66c1ca
| 0 |
JetBrains/teamcity-deployer-plugin,JetBrains/teamcity-deployer-plugin
|
/*
* Copyright 2000-2021 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 jetbrains.buildServer.deployer.agent.ssh;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import jetbrains.buildServer.agent.BuildProgressLogger;
import jetbrains.buildServer.messages.BuildMessage1;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.ByteArrayInputStream;
public class SSHExecProcessAdapterTest {
private static final String DEFAULT_COMMAND = "echo hello";
private Mockery myContext;
private SSHSessionProvider mySessionProvider;
private Session mySession;
private ChannelExec myChannel;
private SSHExecProcessAdapter myAdapter;
private BuildProgressLogger myLogger;
@BeforeMethod
public void setup() {
myContext = new Mockery();
myContext.setImposteriser(ClassImposteriser.INSTANCE);
mySessionProvider = myContext.mock(SSHSessionProvider.class);
mySession = myContext.mock(Session.class);
myChannel = myContext.mock(ChannelExec.class);
myLogger = myContext.mock(BuildProgressLogger.class);
myAdapter = newAdapter(myLogger);
commonExpectations();
}
@Test
public void stdoutAndStderrShouldBeLogged() throws Exception {
myContext.checking(new Expectations() {{
allowing(myChannel).connect(with(any(Integer.class)));
oneOf(myChannel).getInputStream();
will(returnValue(new ByteArrayInputStream("standard output\n".getBytes())));
oneOf(myChannel).getErrStream();
will(returnValue(new ByteArrayInputStream("standard error\n".getBytes())));
oneOf(myChannel).isConnected();
will(returnValue(true));
oneOf(myChannel).isEOF();
will(returnValue(false));
oneOf(myLogger).message("Executing commands:\n" + DEFAULT_COMMAND + "\non host []");
oneOf(myLogger).message("standard output");
oneOf(myLogger).message("standard error");
oneOf(myLogger).message("SSH exit-code [0]");
}});
myAdapter.runProcess();
myContext.assertIsSatisfied();
}
@Test
public void stderrShouldBeLoggedIfStdOutIsEmpty() throws Exception {
myContext.checking(new Expectations() {{
allowing(myChannel).connect(with(any(Integer.class)));
oneOf(myChannel).getInputStream();
will(returnValue(new ByteArrayInputStream(new byte[]{11}) {
@Override
public synchronized int read(byte[] b, int off, int len) {
return -1;
}
}));
oneOf(myChannel).getErrStream();
will(returnValue(new ByteArrayInputStream("standard error\n".getBytes())));
oneOf(myChannel).isConnected();
will(returnValue(true));
oneOf(myChannel).isEOF();
will(returnValue(false));
oneOf(myLogger).message("Executing commands:\n" + DEFAULT_COMMAND + "\non host []");
oneOf(myLogger).message("standard error");
oneOf(myLogger).message("SSH exit-code [0]");
}});
myAdapter.runProcess();
myContext.assertIsSatisfied();
}
private void commonExpectations() {
myContext.checking(new Expectations() {{
try {
allowing(mySessionProvider).getSession();
will(returnValue(mySession));
allowing(mySession).getHost();
allowing(mySession).openChannel("exec");
will(returnValue(myChannel));
allowing(mySession).disconnect();
allowing(myChannel).setCommand(DEFAULT_COMMAND);
allowing(myChannel).connect();
allowing(myChannel).isClosed();
will(returnValue(true));
allowing(myChannel).disconnect();
allowing(myChannel).getExitStatus();
allowing(myLogger).logMessage(with(any(BuildMessage1.class)));
} catch (JSchException e) {
Assert.fail("Unexpected exception in jmock expectations list.", e);
}
}});
}
private SSHExecProcessAdapter newAdapter(BuildProgressLogger logger) {
SSHProcessAdapterOptions options = new SSHProcessAdapterOptions(true, false);
return new SSHExecProcessAdapter(mySessionProvider, DEFAULT_COMMAND, "", logger, options);
}
}
|
deploy-runner-agent/src/test/java/jetbrains/buildServer/deployer/agent/ssh/SSHExecProcessAdapterTest.java
|
/*
* Copyright 2000-2021 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 jetbrains.buildServer.deployer.agent.ssh;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import jetbrains.buildServer.agent.BuildProgressLogger;
import jetbrains.buildServer.messages.BuildMessage1;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.ByteArrayInputStream;
public class SSHExecProcessAdapterTest {
private static final String DEFAULT_COMMAND = "echo hello";
private Mockery myContext;
private SSHSessionProvider mySessionProvider;
private Session mySession;
private ChannelExec myChannel;
private SSHExecProcessAdapter myAdapter;
private BuildProgressLogger myLogger;
@BeforeMethod
public void setup() {
myContext = new Mockery();
myContext.setImposteriser(ClassImposteriser.INSTANCE);
mySessionProvider = myContext.mock(SSHSessionProvider.class);
mySession = myContext.mock(Session.class);
myChannel = myContext.mock(ChannelExec.class);
myLogger = myContext.mock(BuildProgressLogger.class);
myAdapter = newAdapter(myLogger);
commonExpectations();
}
@Test
public void stdoutAndStderrShouldBeLogged() throws Exception {
myContext.checking(new Expectations() {{
allowing(myChannel).connect(with(any(Integer.class)));
oneOf(myChannel).getInputStream();
will(returnValue(new ByteArrayInputStream("standard output\n".getBytes())));
oneOf(myChannel).getErrStream();
will(returnValue(new ByteArrayInputStream("standard error\n".getBytes())));
oneOf(myChannel).isConnected();
will(returnValue(true));
oneOf(myChannel).isEOF();
will(returnValue(false));
oneOf(myLogger).message("Executing commands:\n" + DEFAULT_COMMAND + "\non host []");
oneOf(myLogger).message("standard output");
oneOf(myLogger).message("standard error");
oneOf(myLogger).message("SSH exit-code [0]");
}});
myAdapter.runProcess();
myContext.assertIsSatisfied();
}
@Test
public void stderrShouldBeLoggedIfStdOutIsEmpty() throws Exception {
myContext.checking(new Expectations() {{
allowing(myChannel).connect(with(any(Integer.class)));
oneOf(myChannel).getInputStream();
will(returnValue(new ByteArrayInputStream(new byte[]{11}) {
@Override
public synchronized int read(byte[] b, int off, int len) {
return -1;
}
}));
oneOf(myChannel).getErrStream();
will(returnValue(new ByteArrayInputStream("standard error\n".getBytes())));
oneOf(myChannel).isConnected();
will(returnValue(true));
oneOf(myChannel).isEOF();
will(returnValue(false));
oneOf(myLogger).message("Executing commands:\n" + DEFAULT_COMMAND + "\non host []");
oneOf(myLogger).message("standard error");
oneOf(myLogger).message("SSH exit-code [0]");
}});
myAdapter.runProcess();
myContext.assertIsSatisfied();
}
private void commonExpectations() {
myContext.checking(new Expectations() {{
try {
allowing(mySessionProvider).getSession();
will(returnValue(mySession));
allowing(mySession).getHost();
allowing(mySession).openChannel("exec");
will(returnValue(myChannel));
allowing(mySession).disconnect();
allowing(myChannel).setCommand(DEFAULT_COMMAND);
allowing(myChannel).connect();
allowing(myChannel).isClosed();
will(returnValue(true));
allowing(myChannel).disconnect();
allowing(myChannel).getExitStatus();
allowing(myLogger).logMessage(with(any(BuildMessage1.class)));
} catch (JSchException e) {
Assert.fail("Unexpected exception in jmock expectations list.", e);
}
}});
}
private SSHExecProcessAdapter newAdapter(BuildProgressLogger logger) {
SSHProcessAdapterOptions options = new SSHProcessAdapterOptions(true, false);
return new SSHExecProcessAdapter(mySessionProvider, DEFAULT_COMMAND, null, logger, options);
}
}
|
fix NPE in test
|
deploy-runner-agent/src/test/java/jetbrains/buildServer/deployer/agent/ssh/SSHExecProcessAdapterTest.java
|
fix NPE in test
|
<ide><path>eploy-runner-agent/src/test/java/jetbrains/buildServer/deployer/agent/ssh/SSHExecProcessAdapterTest.java
<ide>
<ide> private SSHExecProcessAdapter newAdapter(BuildProgressLogger logger) {
<ide> SSHProcessAdapterOptions options = new SSHProcessAdapterOptions(true, false);
<del> return new SSHExecProcessAdapter(mySessionProvider, DEFAULT_COMMAND, null, logger, options);
<add> return new SSHExecProcessAdapter(mySessionProvider, DEFAULT_COMMAND, "", logger, options);
<ide> }
<ide> }
|
|
JavaScript
|
mit
|
27c73b1d206a0d8672434fb58b1089f33bb6b2b2
| 0 |
kingstarking/jpg-glitch,kingstarking/jpg-glitch,snorpey/jpg-glitch,snorpey/jpg-glitch
|
/*global define*/
define(
function()
{
var signals;
var export_button;
var png_link;
var default_file_name;
var file_name;
var download_file_name;
var file_suffix = '.png';
var file_suffix_regex = /(\.)(jpg|jpeg|png|gif|bmp)/ig;
function init( shared )
{
signals = shared.signals;
export_button = document.getElementById( 'export-button' );
png_link = document.getElementById( 'png-button' );
default_file_name = png_link.getAttribute( 'download' ).replace( file_suffix_regex, '' );
file_name = default_file_name;
download_file_name = default_file_name;
export_button.addEventListener( 'click', exportButtonClicked, false );
png_link.addEventListener( 'click', hidePNGLink, false );
signals['load-file'].add( updateFileName );
signals['control-updated'].add( updateDownloadFileName );
}
function exportButtonClicked( event )
{
event.preventDefault();
signals['image-data-url-requested'].dispatch( updatePNGLinkAddress );
}
function updateFileName( file )
{
if (
file &&
typeof file.name === 'string'
)
{
file_name = file.name.replace( file_suffix_regex, '' );
}
}
function updateDownloadFileName( options )
{
download_file_name = file_name + '-glitched-' + objToString( options ) + file_suffix;
}
function updatePNGLinkAddress( data_url )
{
png_link.href = data_url;
png_link.setAttribute( 'download', download_file_name );
png_link.classList.add( 'is-active' );
}
function hidePNGLink()
{
png_link.classList.remove( 'is-active' );
}
function objToString( obj )
{
var result = [ ];
for ( var key in obj )
{
result.push( key[0] + '' + obj[key] );
}
return result.join( '-' );
}
return { init: init };
}
);
|
scripts/src/export-button.js
|
/*global define*/
define(
function()
{
var signals;
var export_button;
var png_link;
var default_file_name;
var file_name;
var download_file_name;
var file_suffix = '.png';
var file_suffix_regex = /(\.)(jpg|jpeg|png|gif|bmp)/ig;
function init( shared )
{
signals = shared.signals;
export_button = document.getElementById( 'export-button' );
png_link = document.getElementById( 'png-button' );
default_file_name = png_link.getAttribute( 'download' ).replace( file_suffix_regex, '' );
file_name = default_file_name;
download_file_name = default_file_name;
export_button.addEventListener( 'click', exportButtonClicked, false );
png_link.addEventListener( 'click', hidePNGLink, false );
signals['load-file'].add( updateFileName );
signals['control-updated'].add( updateDownloadFileName );
}
function exportButtonClicked( event )
{
event.preventDefault();
signals['image-data-url-requested'].dispatch( updatePNGLinkAddress );
}
function updateFileName( file )
{
if (
file &&
typeof file.name === 'string'
)
{
file_name = file.name.replace( file_suffix_regex, '' );
}
}
function updateDownloadFileName( options )
{
download_file_name = file_name + '-' + objToString( options ) + file_suffix;
}
function updatePNGLinkAddress( data_url )
{
png_link.href = data_url;
png_link.setAttribute( 'download', download_file_name );
png_link.classList.add( 'is-active' );
}
function hidePNGLink()
{
png_link.classList.remove( 'is-active' );
}
function objToString( obj )
{
var result = [ ];
for ( var key in obj )
{
result.push( key[0] + '' + obj[key] );
}
return result.join( '-' );
}
return { init: init };
}
);
|
add 'glitched' to downloaded file name
|
scripts/src/export-button.js
|
add 'glitched' to downloaded file name
|
<ide><path>cripts/src/export-button.js
<ide>
<ide> function updateDownloadFileName( options )
<ide> {
<del> download_file_name = file_name + '-' + objToString( options ) + file_suffix;
<add> download_file_name = file_name + '-glitched-' + objToString( options ) + file_suffix;
<ide> }
<ide>
<ide> function updatePNGLinkAddress( data_url )
|
|
Java
|
mit
|
a2b5d9fa3c8804a9342b6acf4705fc445c966cc1
| 0 |
joker1/redline,craigwblake/redline,craigwblake/redline,joker1/redline,craigwblake/redline,craigwblake/redline,craigwblake/redline,joker1/redline,joker1/redline
|
package org.freecompany.redline.payload;
import org.freecompany.redline.ChannelWrapper.*;
import org.freecompany.redline.*;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.logging.Logger;
import static java.util.Collections.unmodifiableSet;
import static java.util.Arrays.asList;
import static java.util.logging.Level.FINE;
import static java.util.logging.Logger.getLogger;
import static org.freecompany.redline.payload.CpioHeader.*;
/**
* NOT THREADSAFE
*/
public class Contents {
private Logger logger = getLogger( Contents.class.getName());
private int inode = 1;
/**
* The RPM format requires that files in the archive and file lists to be naturally
* ordered.
*/
protected final TreeSet< CpioHeader> headers = new TreeSet< CpioHeader>( new Comparator< CpioHeader>() {
public int compare( final CpioHeader one, final CpioHeader two) {
return one.getName().compareTo( two.getName());
}
public boolean equals( final CpioHeader one, final CpioHeader two) {
return one.getName().equals( two.getName());
}
});
protected final HashSet< String> files = new HashSet< String>();
protected final HashMap< CpioHeader, Object> sources = new HashMap< CpioHeader, Object>();
public void addLink( final String path, final String target) {
addLink( path, target, -1);
}
public void addLink( final String path, final String target, int permissions) {
if ( files.contains( path)) return;
files.add( path);
logger.log( FINE, "Adding link ''{0}''.", path);
CpioHeader header = new CpioHeader( path);
header.setType( SYMLINK);
header.setFileSize( target.length());
header.setMtime( System.currentTimeMillis());
if ( permissions != -1) header.setPermissions( permissions);
headers.add( header);
sources.put( header, target);
}
public void addDirectory( final String path) {
addDirectory( path, -1);
}
public void addDirectory( final String path, int permissions) {
if ( files.contains( path)) return;
files.add( path);
logger.log( FINE, "Adding directory ''{0}''.", path);
CpioHeader header = new CpioHeader( path);
header.setType( DIR);
header.setInode( inode++);
header.setMtime( System.currentTimeMillis());
if ( permissions != -1) header.setPermissions( permissions);
headers.add( header);
sources.put( header, null);
}
public void addFile( final String path, final File source) throws FileNotFoundException {
addFile( path, source, -1);
}
public void addFile( final String path, final File source, int permissions) throws FileNotFoundException {
if ( files.contains( path)) return;
files.add( path);
logger.log( FINE, "Adding file ''{0}''.", path);
CpioHeader header = new CpioHeader( path, source);
header.setType( FILE);
header.setInode( inode++);
if ( permissions != -1) header.setPermissions( permissions);
headers.add( header);
sources.put( header, source);
}
public int size() { return headers.size(); }
public Iterable< CpioHeader> headers() { return headers; }
public Object getSource( CpioHeader header) { return sources.get( header); }
public int getTotalSize() {
int total = 0;
for ( Object object : sources.values()) if ( object instanceof File) total += (( File) object).length();
return total;
}
public String[] getDirNames() {
final Set< String> set = new LinkedHashSet< String>();
for ( CpioHeader header : headers) {
String parent = new File( header.getName().toString()).getParent();
if ( !parent.endsWith( "/")) parent += "/";
set.add( parent);
}
return set.toArray( new String[ set.size()]);
}
// TODO: Fix this (as part of general refactoring) to be much better.
public int[] getDirIndexes() {
final List< String> dirs = asList( getDirNames());
int[] array = new int[ headers.size()];
int x = 0;
for ( CpioHeader header : headers) {
String parent = new File( header.getName().toString()).getParent();
if ( !parent.endsWith( "/")) parent += "/";
array[ x] = dirs.indexOf( parent);
++x;
}
return array;
}
public String[] getBaseNames() {
String[] array = new String[ headers.size()];
int x = 0;
for ( CpioHeader header : headers) {
array[ x] = new File( header.getName().toString()).getName();
++x;
}
return array;
}
public int[] getSizes() {
int[] array = new int[ headers.size()];
int x = 0;
for ( CpioHeader header : headers) {
Object object = sources.get( header);
if ( object instanceof File) array[ x] = ( int) (( File) object).length();
++x;
}
return array;
}
public short[] getModes() {
short[] array = new short[ headers.size()];
int x = 0;
for ( CpioHeader header : headers) {
array[ x] = ( short) header.getMode();
++x;
}
return array;
}
public short[] getRdevs() {
short[] array = new short[ headers.size()];
int x = 0;
for ( CpioHeader header : headers) {
array[ x] = ( short) (( header.getRdevMajor() << 8) + header.getRdevMinor());
++x;
}
return array;
}
public int[] getMtimes() {
int[] array = new int[ headers.size()];
int x = 0;
for ( CpioHeader header : headers) {
array[ x] = ( int) header.getMtime();
++x;
}
return array;
}
public String[] getMD5s() throws FileNotFoundException, NoSuchAlgorithmException, IOException {
final ByteBuffer buffer = ByteBuffer.allocate( 4096);
String[] array = new String[ headers.size()];
int x = 0;
for ( CpioHeader header : headers) {
Object object = sources.get( header);
if ( object instanceof File) {
final ReadableChannelWrapper input = new ReadableChannelWrapper( new FileInputStream(( File) object).getChannel());
final Key< byte[]> key = input.start( "MD5");
while ( input.read( buffer) != -1) buffer.rewind();
array[ x] = new String( Util.hex( input.finish( key)));
input.close();
} else array[ x] = "";
++x;
}
return array;
}
public String[] getLinkTos() {
String[] array = new String[ headers.size()];
int x = 0;
for ( CpioHeader header : headers) {
Object object = sources.get( header);
if ( object instanceof String) array[ x] = String.valueOf( object);
else array[ x] = "";
++x;
}
return array;
}
public int[] getFlags() {
return new int[ headers.size()];
}
public String[] getUsers() {
String[] array = new String[ headers.size()];
for ( int x = 0; x < array.length; x++) array[ x] = "root";
return array;
}
public String[] getGroups() {
String[] array = new String[ headers.size()];
for ( int x = 0; x < array.length; x++) array[ x] = "root";
return array;
}
public int[] getColors() {
return new int[ headers.size()];
}
public int[] getVerifyFlags() {
int[] array = new int[ headers.size()];
Arrays.fill( array, -1);
return array;
}
public int[] getClasses() {
int[] array = new int[ headers.size()];
Arrays.fill( array, 1);
return array;
}
public int[] getDevices() {
int[] array = new int[ headers.size()];
int x = 0;
for ( CpioHeader header : headers) {
array[ x] = ( header.getDevMajor() << 8) + header.getDevMinor();
++x;
}
return array;
}
public int[] getInodes() {
int[] array = new int[ headers.size()];
int x = 0;
for ( CpioHeader header : headers) {
array[ x] = ( int) header.getInode();
++x;
}
return array;
}
public String[] getLangs() {
String[] array = new String[ headers.size()];
for ( int x = 0; x < array.length; x++) array[ x] = "";
return array;
}
public int[] getDependsX() {
return new int[ headers.size()];
}
public int[] getDependsN() {
return new int[ headers.size()];
}
public String[] getContexts() {
String[] array = new String[ headers.size()];
for ( int x = 0; x < array.length; x++) array[ x] = "<<none>>";
return array;
}
}
|
source/main/org/freecompany/redline/payload/Contents.java
|
package org.freecompany.redline.payload;
import org.freecompany.redline.ChannelWrapper.*;
import org.freecompany.redline.*;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.logging.Logger;
import static java.util.Collections.unmodifiableSet;
import static java.util.Arrays.asList;
import static java.util.logging.Level.INFO;
import static java.util.logging.Logger.getLogger;
import static org.freecompany.redline.payload.CpioHeader.*;
/**
* NOT THREADSAFE
*/
public class Contents {
private Logger logger = getLogger( Contents.class.getName());
private int inode = 1;
/**
* The RPM format requires that files in the archive and file lists to be naturally
* ordered.
*/
protected final TreeSet< CpioHeader> headers = new TreeSet< CpioHeader>( new Comparator< CpioHeader>() {
public int compare( final CpioHeader one, final CpioHeader two) {
return one.getName().compareTo( two.getName());
}
public boolean equals( final CpioHeader one, final CpioHeader two) {
return one.getName().equals( two.getName());
}
});
protected final HashSet< String> files = new HashSet< String>();
protected final HashMap< CpioHeader, Object> sources = new HashMap< CpioHeader, Object>();
public void addLink( final String path, final String target) {
addLink( path, target, -1);
}
public void addLink( final String path, final String target, int permissions) {
if ( files.contains( path)) return;
files.add( path);
logger.log( INFO, "Adding link ''{0}''.", path);
CpioHeader header = new CpioHeader( path);
header.setType( SYMLINK);
header.setFileSize( target.length());
header.setMtime( System.currentTimeMillis());
if ( permissions != -1) header.setPermissions( permissions);
headers.add( header);
sources.put( header, target);
}
public void addDirectory( final String path) {
addDirectory( path, -1);
}
public void addDirectory( final String path, int permissions) {
if ( files.contains( path)) return;
files.add( path);
logger.log( INFO, "Adding directory ''{0}''.", path);
CpioHeader header = new CpioHeader( path);
header.setType( DIR);
header.setInode( inode++);
header.setMtime( System.currentTimeMillis());
if ( permissions != -1) header.setPermissions( permissions);
headers.add( header);
sources.put( header, null);
}
public void addFile( final String path, final File source) throws FileNotFoundException {
addFile( path, source, -1);
}
public void addFile( final String path, final File source, int permissions) throws FileNotFoundException {
if ( files.contains( path)) return;
files.add( path);
logger.log( INFO, "Adding file ''{0}''.", path);
CpioHeader header = new CpioHeader( path, source);
header.setType( FILE);
header.setInode( inode++);
if ( permissions != -1) header.setPermissions( permissions);
headers.add( header);
sources.put( header, source);
}
public int size() { return headers.size(); }
public Iterable< CpioHeader> headers() { return headers; }
public Object getSource( CpioHeader header) { return sources.get( header); }
public int getTotalSize() {
int total = 0;
for ( Object object : sources.values()) if ( object instanceof File) total += (( File) object).length();
return total;
}
public String[] getDirNames() {
final Set< String> set = new LinkedHashSet< String>();
for ( CpioHeader header : headers) {
String parent = new File( header.getName().toString()).getParent();
if ( !parent.endsWith( "/")) parent += "/";
set.add( parent);
}
return set.toArray( new String[ set.size()]);
}
// TODO: Fix this (as part of general refactoring) to be much better.
public int[] getDirIndexes() {
final List< String> dirs = asList( getDirNames());
int[] array = new int[ headers.size()];
int x = 0;
for ( CpioHeader header : headers) {
String parent = new File( header.getName().toString()).getParent();
if ( !parent.endsWith( "/")) parent += "/";
array[ x] = dirs.indexOf( parent);
++x;
}
return array;
}
public String[] getBaseNames() {
String[] array = new String[ headers.size()];
int x = 0;
for ( CpioHeader header : headers) {
array[ x] = new File( header.getName().toString()).getName();
++x;
}
return array;
}
public int[] getSizes() {
int[] array = new int[ headers.size()];
int x = 0;
for ( CpioHeader header : headers) {
Object object = sources.get( header);
if ( object instanceof File) array[ x] = ( int) (( File) object).length();
++x;
}
return array;
}
public short[] getModes() {
short[] array = new short[ headers.size()];
int x = 0;
for ( CpioHeader header : headers) {
array[ x] = ( short) header.getMode();
++x;
}
return array;
}
public short[] getRdevs() {
short[] array = new short[ headers.size()];
int x = 0;
for ( CpioHeader header : headers) {
array[ x] = ( short) (( header.getRdevMajor() << 8) + header.getRdevMinor());
++x;
}
return array;
}
public int[] getMtimes() {
int[] array = new int[ headers.size()];
int x = 0;
for ( CpioHeader header : headers) {
array[ x] = ( int) header.getMtime();
++x;
}
return array;
}
public String[] getMD5s() throws FileNotFoundException, NoSuchAlgorithmException, IOException {
final ByteBuffer buffer = ByteBuffer.allocate( 4096);
String[] array = new String[ headers.size()];
int x = 0;
for ( CpioHeader header : headers) {
Object object = sources.get( header);
if ( object instanceof File) {
final ReadableChannelWrapper input = new ReadableChannelWrapper( new FileInputStream(( File) object).getChannel());
final Key< byte[]> key = input.start( "MD5");
while ( input.read( buffer) != -1) buffer.rewind();
array[ x] = new String( Util.hex( input.finish( key)));
input.close();
} else array[ x] = "";
++x;
}
return array;
}
public String[] getLinkTos() {
String[] array = new String[ headers.size()];
int x = 0;
for ( CpioHeader header : headers) {
Object object = sources.get( header);
if ( object instanceof String) array[ x] = String.valueOf( object);
else array[ x] = "";
++x;
}
return array;
}
public int[] getFlags() {
return new int[ headers.size()];
}
public String[] getUsers() {
String[] array = new String[ headers.size()];
for ( int x = 0; x < array.length; x++) array[ x] = "root";
return array;
}
public String[] getGroups() {
String[] array = new String[ headers.size()];
for ( int x = 0; x < array.length; x++) array[ x] = "root";
return array;
}
public int[] getColors() {
return new int[ headers.size()];
}
public int[] getVerifyFlags() {
int[] array = new int[ headers.size()];
Arrays.fill( array, -1);
return array;
}
public int[] getClasses() {
int[] array = new int[ headers.size()];
Arrays.fill( array, 1);
return array;
}
public int[] getDevices() {
int[] array = new int[ headers.size()];
int x = 0;
for ( CpioHeader header : headers) {
array[ x] = ( header.getDevMajor() << 8) + header.getDevMinor();
++x;
}
return array;
}
public int[] getInodes() {
int[] array = new int[ headers.size()];
int x = 0;
for ( CpioHeader header : headers) {
array[ x] = ( int) header.getInode();
++x;
}
return array;
}
public String[] getLangs() {
String[] array = new String[ headers.size()];
for ( int x = 0; x < array.length; x++) array[ x] = "";
return array;
}
public int[] getDependsX() {
return new int[ headers.size()];
}
public int[] getDependsN() {
return new int[ headers.size()];
}
public String[] getContexts() {
String[] array = new String[ headers.size()];
for ( int x = 0; x < array.length; x++) array[ x] = "<<none>>";
return array;
}
}
|
Removed logging.
git-svn-id: 5623ba1b889e76e0f61c52c0bc2fcdebc37281a4@112 da7a95ae-83ad-11de-b471-8552911d2254
|
source/main/org/freecompany/redline/payload/Contents.java
|
Removed logging.
|
<ide><path>ource/main/org/freecompany/redline/payload/Contents.java
<ide>
<ide> import static java.util.Collections.unmodifiableSet;
<ide> import static java.util.Arrays.asList;
<del>import static java.util.logging.Level.INFO;
<add>import static java.util.logging.Level.FINE;
<ide> import static java.util.logging.Logger.getLogger;
<ide> import static org.freecompany.redline.payload.CpioHeader.*;
<ide>
<ide> public void addLink( final String path, final String target, int permissions) {
<ide> if ( files.contains( path)) return;
<ide> files.add( path);
<del> logger.log( INFO, "Adding link ''{0}''.", path);
<add> logger.log( FINE, "Adding link ''{0}''.", path);
<ide> CpioHeader header = new CpioHeader( path);
<ide> header.setType( SYMLINK);
<ide> header.setFileSize( target.length());
<ide> public void addDirectory( final String path, int permissions) {
<ide> if ( files.contains( path)) return;
<ide> files.add( path);
<del> logger.log( INFO, "Adding directory ''{0}''.", path);
<add> logger.log( FINE, "Adding directory ''{0}''.", path);
<ide> CpioHeader header = new CpioHeader( path);
<ide> header.setType( DIR);
<ide> header.setInode( inode++);
<ide> public void addFile( final String path, final File source, int permissions) throws FileNotFoundException {
<ide> if ( files.contains( path)) return;
<ide> files.add( path);
<del> logger.log( INFO, "Adding file ''{0}''.", path);
<add> logger.log( FINE, "Adding file ''{0}''.", path);
<ide> CpioHeader header = new CpioHeader( path, source);
<ide> header.setType( FILE);
<ide> header.setInode( inode++);
|
|
Java
|
agpl-3.0
|
d09f9d978c115b228d76c14b5b5901003228d7ea
| 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
|
1081d730-2e60-11e5-9284-b827eb9e62be
|
hello.java
|
107c6020-2e60-11e5-9284-b827eb9e62be
|
1081d730-2e60-11e5-9284-b827eb9e62be
|
hello.java
|
1081d730-2e60-11e5-9284-b827eb9e62be
|
<ide><path>ello.java
<del>107c6020-2e60-11e5-9284-b827eb9e62be
<add>1081d730-2e60-11e5-9284-b827eb9e62be
|
|
Java
|
apache-2.0
|
bb672bbf4257347801ac425232ca2fb2c3f04d3d
| 0 |
GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit
|
// Copyright (C) 2020 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.acceptance.rest.change;
import static com.google.common.truth.Truth.assertThat;
import static com.google.gerrit.extensions.restapi.testing.AttentionSetUpdateSubject.assertThat;
import static com.google.gerrit.testing.GerritJUnit.assertThrows;
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.truth.Correspondence;
import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.NoHttpd;
import com.google.gerrit.acceptance.PushOneCommit;
import com.google.gerrit.acceptance.TestAccount;
import com.google.gerrit.acceptance.UseClockStep;
import com.google.gerrit.acceptance.config.GerritConfig;
import com.google.gerrit.acceptance.testsuite.account.AccountOperations;
import com.google.gerrit.acceptance.testsuite.change.ChangeOperations;
import com.google.gerrit.acceptance.testsuite.request.RequestScopeOperations;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.entities.Account;
import com.google.gerrit.entities.AttentionSetUpdate;
import com.google.gerrit.entities.Change;
import com.google.gerrit.entities.Patch;
import com.google.gerrit.extensions.api.changes.AddReviewerInput;
import com.google.gerrit.extensions.api.changes.AttentionSetInput;
import com.google.gerrit.extensions.api.changes.DeleteReviewerInput;
import com.google.gerrit.extensions.api.changes.HashtagsInput;
import com.google.gerrit.extensions.api.changes.ReviewInput;
import com.google.gerrit.extensions.client.GeneralPreferencesInfo;
import com.google.gerrit.extensions.client.GeneralPreferencesInfo.EmailStrategy;
import com.google.gerrit.extensions.client.ReviewerState;
import com.google.gerrit.extensions.client.Side;
import com.google.gerrit.extensions.restapi.BadRequestException;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gerrit.server.query.change.InternalChangeQuery;
import com.google.gerrit.server.util.time.TimeUtil;
import com.google.gerrit.testing.FakeEmailSender;
import com.google.gerrit.testing.TestCommentHelper;
import com.google.gerrit.truth.NullAwareCorrespondence;
import com.google.inject.Inject;
import com.google.inject.Provider;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.LongSupplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
@NoHttpd
@UseClockStep(clockStepUnit = TimeUnit.MINUTES)
public class AttentionSetIT extends AbstractDaemonTest {
@Inject private ChangeOperations changeOperations;
@Inject private AccountOperations accountOperations;
@Inject private RequestScopeOperations requestScopeOperations;
@Inject private FakeEmailSender email;
@Inject private TestCommentHelper testCommentHelper;
@Inject private Provider<InternalChangeQuery> changeQueryProvider;
/** Simulates a fake clock. Uses second granularity. */
private static class FakeClock implements LongSupplier {
Instant now = Instant.now();
@Override
public long getAsLong() {
return TimeUnit.SECONDS.toMillis(now.getEpochSecond());
}
Instant now() {
return Instant.ofEpochSecond(now.getEpochSecond());
}
void advance(Duration duration) {
now = now.plus(duration);
}
}
private FakeClock fakeClock = new FakeClock();
@Before
public void setUp() {
TimeUtil.setCurrentMillisSupplier(fakeClock);
}
@Test
public void emptyAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
assertThat(r.getChange().attentionSet()).isEmpty();
}
@Test
public void addUser() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
int accountId =
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "first"))._accountId;
assertThat(accountId).isEqualTo(user.id().get());
AttentionSetUpdate expectedAttentionSetUpdate =
AttentionSetUpdate.createFromRead(
fakeClock.now(), user.id(), AttentionSetUpdate.Operation.ADD, "first");
assertThat(r.getChange().attentionSet()).containsExactly(expectedAttentionSetUpdate);
// Second add is ignored.
accountId =
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "second"))._accountId;
assertThat(accountId).isEqualTo(user.id().get());
assertThat(r.getChange().attentionSet()).containsExactly(expectedAttentionSetUpdate);
// Only one email since the second add was ignored.
String emailBody = Iterables.getOnlyElement(email.getMessages()).body();
assertThat(emailBody)
.contains(
user.fullName()
+ " added themselves to the attention set of this change.\n The reason is: first.");
}
@Test
public void addMultipleUsers() throws Exception {
PushOneCommit.Result r = createChange();
Instant timestamp1 = fakeClock.now();
int accountId1 =
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "user"))._accountId;
assertThat(accountId1).isEqualTo(user.id().get());
fakeClock.advance(Duration.ofSeconds(42));
Instant timestamp2 = fakeClock.now();
int accountId2 =
change(r)
.addToAttentionSet(new AttentionSetInput(admin.id().toString(), "admin"))
._accountId;
assertThat(accountId2).isEqualTo(admin.id().get());
AttentionSetUpdate expectedAttentionSetUpdate1 =
AttentionSetUpdate.createFromRead(
timestamp1, user.id(), AttentionSetUpdate.Operation.ADD, "user");
AttentionSetUpdate expectedAttentionSetUpdate2 =
AttentionSetUpdate.createFromRead(
timestamp2, admin.id(), AttentionSetUpdate.Operation.ADD, "admin");
assertThat(r.getChange().attentionSet())
.containsExactly(expectedAttentionSetUpdate1, expectedAttentionSetUpdate2);
}
@Test
public void removeUser() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "added"));
requestScopeOperations.setApiUser(user.id());
fakeClock.advance(Duration.ofSeconds(42));
change(r).attention(user.id().toString()).remove(new AttentionSetInput("removed"));
AttentionSetUpdate expectedAttentionSetUpdate =
AttentionSetUpdate.createFromRead(
fakeClock.now(), user.id(), AttentionSetUpdate.Operation.REMOVE, "removed");
assertThat(r.getChange().attentionSet()).containsExactly(expectedAttentionSetUpdate);
// Second removal is ignored.
fakeClock.advance(Duration.ofSeconds(42));
change(r).attention(user.id().toString()).remove(new AttentionSetInput("removed again"));
assertThat(r.getChange().attentionSet()).containsExactly(expectedAttentionSetUpdate);
// Only one email since the second remove was ignored.
String emailBody = Iterables.getOnlyElement(email.getMessages()).body();
assertThat(emailBody)
.contains(
user.fullName()
+ " removed themselves from the attention set of this change.\n"
+ " The reason is: removed.");
}
@Test
public void removeUserWithInvalidUserInput() throws Exception {
PushOneCommit.Result r = createChange();
BadRequestException exception =
assertThrows(
BadRequestException.class,
() ->
change(r)
.attention(user.id().toString())
.remove(new AttentionSetInput("invalid user", "reason")));
assertThat(exception.getMessage())
.isEqualTo("The user specified in the input body couldn't be found.");
exception =
assertThrows(
BadRequestException.class,
() ->
change(r)
.attention(user.id().toString())
.remove(new AttentionSetInput(admin.email(), "reason")));
assertThat(exception.getMessage())
.isEqualTo(
"The field \"user\" must be empty, or must match the user specified in the URL.");
}
@Test
public void removeUnrelatedUser() throws Exception {
PushOneCommit.Result r = createChange();
change(r).attention(user.id().toString()).remove(new AttentionSetInput("foo"));
assertThat(r.getChange().attentionSet()).isEmpty();
}
@Test
public void abandonRemovesUsers() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "user"));
change(r).addToAttentionSet(new AttentionSetInput(admin.email(), "admin"));
change(r).abandon();
AttentionSetUpdate userUpdate =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(userUpdate).hasAccountIdThat().isEqualTo(user.id());
assertThat(userUpdate).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(userUpdate).hasReasonThat().isEqualTo("Change was abandoned");
AttentionSetUpdate adminUpdate =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, admin));
assertThat(adminUpdate).hasAccountIdThat().isEqualTo(admin.id());
assertThat(adminUpdate).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(adminUpdate).hasReasonThat().isEqualTo("Change was abandoned");
}
@Test
public void workInProgressRemovesUsers() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "reason"));
change(r).setWorkInProgress();
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("Change was marked work in progress");
}
@Test
public void submitRemovesUsersForAllSubmittedChanges() throws Exception {
PushOneCommit.Result r1 = createChange("refs/heads/master", "file1", "content");
change(r1)
.current()
.review(ReviewInput.approve().addUserToAttentionSet(user.email(), "reason"));
PushOneCommit.Result r2 = createChange("refs/heads/master", "file2", "content");
change(r2)
.current()
.review(ReviewInput.approve().addUserToAttentionSet(user.email(), "reason"));
change(r2).current().submit();
// Attention set updates that relate to the admin (the person who replied) are filtered out.
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r1, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("Change was submitted");
// Attention set updates that relate to the admin (the person who replied) are filtered out.
attentionSet = Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r2, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("Change was submitted");
}
@Test
public void robotSubmitsRemovesUsers() throws Exception {
PushOneCommit.Result r1 = createChange("refs/heads/master", "file1", "content");
change(r1)
.current()
.review(ReviewInput.approve().addUserToAttentionSet(user.email(), "reason"));
TestAccount robot =
accountCreator.create(
"robot2", "[email protected]", "Ro Bot", "Ro", "Service Users", "Administrators");
requestScopeOperations.setApiUser(robot.id());
change(r1).current().submit();
// Attention set updates that relate to the admin (the person who replied) are filtered out.
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r1, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("Change was submitted");
}
@Test
public void addedReviewersAreAddedToAttentionSetOnMergedChanges() throws Exception {
PushOneCommit.Result r = createChange();
change(r).current().review(ReviewInput.approve());
change(r).current().submit();
change(r).addReviewer(user.email());
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer was added");
}
@Test
public void reviewersAddedAndRemovedFromAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addReviewer(user.id().toString());
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer was added");
change(r).reviewer(user.email()).remove();
attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer/Cc was removed");
}
@Test
public void removedCcRemovedFromAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
// Add cc
AddReviewerInput input = new AddReviewerInput();
input.reviewer = user.email();
input.state = ReviewerState.CC;
change(r).addReviewer(input);
// Add them to the attention set
AttentionSetInput attentionSetInput = new AttentionSetInput();
attentionSetInput.user = user.email();
attentionSetInput.reason = "reason";
change(r).addToAttentionSet(attentionSetInput);
// Remove them from cc
change(r).reviewer(user.email()).remove();
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer/Cc was removed");
}
@Test
public void reviewersAddedAndRemovedByEmailFromAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addReviewer(user.email());
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer was added");
change(r).reviewer(user.email()).remove();
attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer/Cc was removed");
}
@Test
public void reviewersInWorkProgressNotAddedToAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).setWorkInProgress();
change(r).addReviewer(user.email());
assertThat(r.getChange().attentionSet()).isEmpty();
}
@Test
public void addingReviewerWhileMarkingWorkInProgressDoesntAddToAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
ReviewInput reviewInput = ReviewInput.create().setWorkInProgress(true);
AddReviewerInput addReviewerInput = new AddReviewerInput();
addReviewerInput.state = ReviewerState.REVIEWER;
addReviewerInput.reviewer = user.email();
reviewInput.reviewers = ImmutableList.of(addReviewerInput);
change(r).current().review(reviewInput);
assertThat(getAttentionSetUpdatesForUser(r, user)).isEmpty();
}
@Test
public void reviewersAddedAsReviewersAgainAreNotAddedToAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addReviewer(user.id().toString());
change(r)
.attention(user.id().toString())
.remove(new AttentionSetInput("removed and not re-added when re-adding as reviewer"));
change(r).addReviewer(user.id().toString());
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet)
.hasReasonThat()
.isEqualTo("removed and not re-added when re-adding as reviewer");
}
@Test
public void ccsAreIgnored() throws Exception {
PushOneCommit.Result r = createChange();
AddReviewerInput addReviewerInput = new AddReviewerInput();
addReviewerInput.state = ReviewerState.CC;
addReviewerInput.reviewer = user.email();
change(r).addReviewer(addReviewerInput);
assertThat(r.getChange().attentionSet()).isEmpty();
}
@Test
public void ccsConsideredSameAsRemovedForExistingReviewers() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addReviewer(user.email());
AddReviewerInput addReviewerInput = new AddReviewerInput();
addReviewerInput.state = ReviewerState.CC;
addReviewerInput.reviewer = user.email();
change(r).addReviewer(addReviewerInput);
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer/Cc was removed");
}
@Test
public void robotReadyForReviewAddsAllReviewersToAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).setWorkInProgress();
change(r).addReviewer(user.email());
TestAccount robot =
accountCreator.create(
"robot1", "[email protected]", "Ro Bot", "Ro", "Service Users", "Administrators");
requestScopeOperations.setApiUser(robot.id());
change(r).setReadyForReview();
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Change was marked ready for review");
}
@Test
public void readyForReviewAddsAllReviewersToAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).setWorkInProgress();
change(r).addReviewer(user.email());
change(r).setReadyForReview();
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Change was marked ready for review");
}
@Test
public void readyForReviewWhileRemovingReviewerRemovesThemToAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).setWorkInProgress();
change(r).addReviewer(user.email());
ReviewInput reviewInput = ReviewInput.create().setReady(true);
AddReviewerInput addReviewerInput = new AddReviewerInput();
addReviewerInput.state = ReviewerState.CC;
addReviewerInput.reviewer = user.email();
reviewInput.reviewers = ImmutableList.of(addReviewerInput);
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "reason"));
change(r).current().review(reviewInput);
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer/Cc was removed");
}
@Test
public void readyForReviewWhileAddingReviewerAddsThemToAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).setWorkInProgress();
ReviewInput reviewInput = ReviewInput.create().setReady(true).reviewer(user.email());
change(r).current().review(reviewInput);
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer was added");
}
@Test
public void reviewersAreNotAddedForNoReasonBecauseOfAnUpdate() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "user"));
change(r).attention(user.id().toString()).remove(new AttentionSetInput("removed"));
HashtagsInput hashtagsInput = new HashtagsInput();
hashtagsInput.add = ImmutableSet.of("tag");
change(r).setHashtags(hashtagsInput);
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("removed");
}
@Test
public void reviewAddsManuallyAddedUserToAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
ReviewInput reviewInput = ReviewInput.create().addUserToAttentionSet(user.email(), "reason");
change(r).current().review(reviewInput);
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("reason");
// No emails for adding to attention set were sent.
email.getMessages().isEmpty();
}
@Test
public void reviewRemovesManuallyRemovedUserFromAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "reason"));
requestScopeOperations.setApiUser(user.id());
ReviewInput reviewInput =
ReviewInput.create().removeUserFromAttentionSet(user.email(), "reason");
change(r).current().review(reviewInput);
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("reason");
// No emails for removing from attention set were sent.
email.getMessages().isEmpty();
}
@Test
public void reviewWithManualAdditionToAttentionSetFailsWithoutReason() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "reason"));
ReviewInput reviewInput = ReviewInput.create().addUserToAttentionSet(user.email(), "");
BadRequestException exception =
assertThrows(BadRequestException.class, () -> change(r).current().review(reviewInput));
assertThat(exception.getMessage()).isEqualTo("missing field: reason");
}
@Test
public void reviewWithManualAdditionToAttentionSetFailsWithoutUser() throws Exception {
PushOneCommit.Result r = createChange();
ReviewInput reviewInput = ReviewInput.create().addUserToAttentionSet("", "reason");
BadRequestException exception =
assertThrows(BadRequestException.class, () -> change(r).current().review(reviewInput));
assertThat(exception.getMessage()).isEqualTo("missing field: user");
}
@Test
public void reviewAddReviewerWhileRemovingFromAttentionSetJustRemovesUser() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "addition"));
ReviewInput reviewInput =
ReviewInput.create()
.reviewer(user.email())
.removeUserFromAttentionSet(user.email(), "reason");
change(r).current().review(reviewInput);
// Attention set updates that relate to the admin (the person who replied) are filtered out.
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("reason");
}
@Test
public void cantAddAndRemoveSameUser() throws Exception {
PushOneCommit.Result r = createChange();
ReviewInput reviewInput =
ReviewInput.create()
.removeUserFromAttentionSet(user.email(), "reason")
.addUserToAttentionSet(user.username(), "reason");
BadRequestException exception =
assertThrows(BadRequestException.class, () -> change(r).current().review(reviewInput));
assertThat(exception.getMessage())
.isEqualTo(
"user can not be added/removed twice, and can not be added and removed at the same"
+ " time");
}
@Test
public void cantRemoveSameUserTwice() throws Exception {
PushOneCommit.Result r = createChange();
ReviewInput reviewInput =
ReviewInput.create()
.removeUserFromAttentionSet(user.email(), "reason1")
.removeUserFromAttentionSet(user.username(), "reason2");
BadRequestException exception =
assertThrows(BadRequestException.class, () -> change(r).current().review(reviewInput));
assertThat(exception.getMessage())
.isEqualTo(
"user can not be added/removed twice, and can not be added and removed at the same"
+ " time");
}
@Test
public void reviewDoesNotAddReviewerWithoutAutomaticRules() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
ReviewInput reviewInput = ReviewInput.recommend().blockAutomaticAttentionSetRules();
change(r).current().review(reviewInput);
assertThat(getAttentionSetUpdatesForUser(r, user)).isEmpty();
}
@Test
public void reviewDoesNotAddReviewer() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
ReviewInput reviewInput = ReviewInput.recommend();
change(r).current().review(reviewInput);
assertThat(getAttentionSetUpdatesForUser(r, user)).isEmpty();
}
@Test
public void cantAddSameUserTwice() throws Exception {
PushOneCommit.Result r = createChange();
ReviewInput reviewInput =
ReviewInput.create()
.addUserToAttentionSet(user.email(), "reason1")
.addUserToAttentionSet(user.username(), "reason2");
BadRequestException exception =
assertThrows(BadRequestException.class, () -> change(r).current().review(reviewInput));
assertThat(exception.getMessage())
.isEqualTo(
"user can not be added/removed twice, and can not be added and removed at the same"
+ " time");
}
@Test
public void reviewRemoveFromAttentionSetWhileMarkingReadyForReviewJustRemovesUser()
throws Exception {
PushOneCommit.Result r = createChange();
change(r).setWorkInProgress();
change(r).addReviewer(user.email());
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "reason"));
ReviewInput reviewInput =
ReviewInput.create().setReady(true).removeUserFromAttentionSet(user.email(), "reason");
change(r).current().review(reviewInput);
// Attention set updates that relate to the admin (the person who replied) are filtered out.
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("reason");
}
@Test
public void reviewAddToAttentionSetWhileMarkingWorkInProgressJustAddsUser() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addReviewer(user.email());
ReviewInput reviewInput =
ReviewInput.create().setWorkInProgress(true).addUserToAttentionSet(user.email(), "reason");
change(r).attention(user.email()).remove(new AttentionSetInput("removal"));
change(r).current().review(reviewInput);
// Attention set updates that relate to the admin (the person who replied) are filtered out.
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("reason");
}
@Test
public void reviewRemovesUserFromAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(admin.email(), "reason"));
ReviewInput reviewInput = new ReviewInput();
change(r).current().review(reviewInput);
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(admin.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("removed on reply");
}
@Test
public void reviewAddUserToAttentionSetWhileReplyingJustAddsUser() throws Exception {
PushOneCommit.Result r = createChange();
ReviewInput reviewInput = ReviewInput.create().addUserToAttentionSet(admin.email(), "reason");
change(r).current().review(reviewInput);
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(admin.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("reason");
}
@Test
public void reviewWhileAddingThemselvesAsReviewerStillRemovesThem() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "reason"));
ReviewInput reviewInput = ReviewInput.create().reviewer(user.email());
change(r).current().review(reviewInput);
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("removed on reply");
}
@Test
public void reviewWhileAddingThemselvesAsReviewerDoesNotAddThem() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
ReviewInput reviewInput = ReviewInput.create().reviewer(user.email());
change(r).current().review(reviewInput);
assertThat(getAttentionSetUpdatesForUser(r, user)).isEmpty();
}
@Test
public void repliesAddsOwner() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
ReviewInput reviewInput = new ReviewInput();
change(r).current().review(reviewInput);
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, admin));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(admin.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Someone else replied on the change");
}
@Test
public void repliesDoNotAddOwnerWhenChangeIsClosed() throws Exception {
PushOneCommit.Result r = createChange();
change(r).abandon();
requestScopeOperations.setApiUser(user.id());
ReviewInput reviewInput = new ReviewInput();
change(r).current().review(reviewInput);
assertThat(getAttentionSetUpdatesForUser(r, admin)).isEmpty();
}
@Test
public void repliesDoNotAddOwnerWhenChangeIsWorkInProgress() throws Exception {
PushOneCommit.Result r = createChange();
change(r).setWorkInProgress();
requestScopeOperations.setApiUser(user.id());
ReviewInput reviewInput = new ReviewInput();
change(r).current().review(reviewInput);
assertThat(getAttentionSetUpdatesForUser(r, admin)).isEmpty();
}
@Test
public void repliesDoNotAddOwnerWhenChangeIsBecomingWorkInProgress() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(accountCreator.admin2().id());
ReviewInput reviewInput = ReviewInput.create().setWorkInProgress(true);
change(r).current().review(reviewInput);
assertThat(getAttentionSetUpdatesForUser(r, admin)).isEmpty();
}
@Test
public void repliesAddOwnerWhenChangeIsBecomingReadyForReview() throws Exception {
PushOneCommit.Result r = createChange();
change(r).setWorkInProgress();
requestScopeOperations.setApiUser(accountCreator.admin2().id());
ReviewInput reviewInput = ReviewInput.create().setReady(true);
change(r).current().review(reviewInput);
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, admin));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(admin.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Someone else replied on the change");
}
@Test
public void repliesAddsOwnerAndUploader() throws Exception {
// Create change with owner: admin
PushOneCommit.Result r = createChange();
r = amendChangeWithUploader(r, project, user);
TestAccount user2 = accountCreator.user2();
requestScopeOperations.setApiUser(user2.id());
change(r).attention(user.email()).remove(new AttentionSetInput("reason"));
ReviewInput reviewInput = new ReviewInput();
change(r).current().review(reviewInput);
reviewInput = new ReviewInput();
change(r).current().review(reviewInput);
// Uploader added
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Someone else replied on the change");
// Owner added
attentionSet = Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, admin));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(admin.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Someone else replied on the change");
}
@Test
public void reviewIgnoresRobotCommentsForAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
testCommentHelper.addRobotComment(
r.getChangeId(),
TestCommentHelper.createRobotCommentInputWithMandatoryFields(Patch.COMMIT_MSG));
requestScopeOperations.setApiUser(admin.id());
change(r)
.current()
.review(
reviewInReplyToComment(
Iterables.getOnlyElement(
gApi.changes().id(r.getChangeId()).current().robotCommentsAsList())
.id));
assertThat(getAttentionSetUpdatesForUser(r, user)).isEmpty();
}
@Test
public void reviewAddsAllUsersInCommentThread() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
change(r).current().review(reviewWithComment());
TestAccount user2 = accountCreator.user2();
requestScopeOperations.setApiUser(user2.id());
change(r)
.current()
.review(
reviewInReplyToComment(
Iterables.getOnlyElement(
gApi.changes().id(r.getChangeId()).current().commentsAsList())
.id));
change(r).attention(user.email()).remove(new AttentionSetInput("removal"));
requestScopeOperations.setApiUser(admin.id());
change(r)
.current()
.review(
reviewInReplyToComment(
gApi.changes().id(r.getChangeId()).current().commentsAsList().get(1).id));
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet)
.hasReasonThat()
.isEqualTo("Someone else replied on a comment you posted");
attentionSet = Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user2));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user2.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet)
.hasReasonThat()
.isEqualTo("Someone else replied on a comment you posted");
}
@Test
public void reviewAddsAllUsersInCommentThreadWhenOriginalCommentIsARobotComment()
throws Exception {
PushOneCommit.Result result = createChange();
testCommentHelper.addRobotComment(
result.getChangeId(),
TestCommentHelper.createRobotCommentInputWithMandatoryFields(Patch.COMMIT_MSG));
requestScopeOperations.setApiUser(user.id());
// Reply to the robot comment.
change(result)
.current()
.review(
reviewInReplyToComment(
Iterables.getOnlyElement(
gApi.changes().id(result.getChangeId()).current().robotCommentsAsList())
.id));
requestScopeOperations.setApiUser(admin.id());
// Reply to the human comment. which was a reply to the robot comment.
change(result)
.current()
.review(
reviewInReplyToComment(
Iterables.getOnlyElement(
gApi.changes().id(result.getChangeId()).current().commentsAsList())
.id));
// The user which replied to the robot comment was added to the attention set.
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(result, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet)
.hasReasonThat()
.isEqualTo("Someone else replied on a comment you posted");
}
@Test
public void reviewAddsAllUsersInCommentThreadEvenOfDifferentChildBranch() throws Exception {
Account.Id changeOwner = accountOperations.newAccount().create();
Change.Id changeId = changeOperations.newChange().owner(changeOwner).create();
Account.Id user1 = accountOperations.newAccount().create();
Account.Id user2 = accountOperations.newAccount().create();
Account.Id user3 = accountOperations.newAccount().create();
Account.Id user4 = accountOperations.newAccount().create();
// Add users as reviewers.
gApi.changes().id(changeId.get()).addReviewer(user1.toString());
gApi.changes().id(changeId.get()).addReviewer(user2.toString());
gApi.changes().id(changeId.get()).addReviewer(user3.toString());
gApi.changes().id(changeId.get()).addReviewer(user4.toString());
// Add a comment thread with branches. Such threads occur if people reply in parallel without
// having seen/loaded the reply of another person.
String root =
changeOperations.change(changeId).currentPatchset().newComment().author(user1).create();
String sibling1 =
changeOperations
.change(changeId)
.currentPatchset()
.newComment()
.author(user2)
.parentUuid(root)
.create();
String sibling2 =
changeOperations
.change(changeId)
.currentPatchset()
.newComment()
.author(user3)
.parentUuid(root)
.create();
changeOperations
.change(changeId)
.currentPatchset()
.newComment()
.author(user4)
.parentUuid(sibling2)
.create();
// Clear the attention set. Necessary as we used Gerrit APIs above which affect the attention
// set.
AttentionSetInput clearAttention = new AttentionSetInput("clear attention set");
gApi.changes().id(changeId.get()).attention(user1.toString()).remove(clearAttention);
gApi.changes().id(changeId.get()).attention(user2.toString()).remove(clearAttention);
gApi.changes().id(changeId.get()).attention(user3.toString()).remove(clearAttention);
gApi.changes().id(changeId.get()).attention(user4.toString()).remove(clearAttention);
requestScopeOperations.setApiUser(changeOwner);
// Simulate that this reply is a child of sibling1 and thus parallel to sibling2 and its child.
gApi.changes().id(changeId.get()).current().review(reviewInReplyToComment(sibling1));
List<AttentionSetUpdate> attentionSetUpdates = getAttentionSetUpdates(changeId);
assertThat(attentionSetUpdates)
.comparingElementsUsing(hasAccount())
.containsExactly(user1, user2, user3, user4);
}
@Test
public void reviewAddsAllUsersInCommentThreadWhenPostedAsDraft() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
change(r).current().review(reviewWithComment());
requestScopeOperations.setApiUser(admin.id());
testCommentHelper.addDraft(
r.getChangeId(),
testCommentHelper.newDraft(
"message",
Iterables.getOnlyElement(gApi.changes().id(r.getChangeId()).current().commentsAsList())
.id));
ReviewInput reviewInput = new ReviewInput();
reviewInput.drafts = ReviewInput.DraftHandling.PUBLISH;
change(r).current().review(reviewInput);
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet)
.hasReasonThat()
.isEqualTo("Someone else replied on a comment you posted");
}
@Test
public void reviewDoesNotAddUsersInACommentThreadThatAreNotActiveInTheChange() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
change(r).current().review(reviewWithComment());
change(r).reviewer(user.id().toString()).remove(new DeleteReviewerInput());
requestScopeOperations.setApiUser(admin.id());
change(r)
.current()
.review(
reviewInReplyToComment(
Iterables.getOnlyElement(
gApi.changes().id(r.getChangeId()).current().commentsAsList())
.id));
// The user was to be added, but was not added since that user is no longer a
// reviewer/cc/owner/uploader.
assertThat(getAttentionSetUpdatesForUser(r, user)).isEmpty();
}
@Test
public void ownerRepliesWhileRemovingReviewerRemovesFromAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addReviewer(user.email());
ReviewInput reviewInput = ReviewInput.create().reviewer(user.email(), ReviewerState.CC, false);
change(r).current().review(reviewInput);
// cc removed
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer/Cc was removed");
}
@Test
public void uploaderRepliesAddsOwner() throws Exception {
PushOneCommit.Result r = createChange();
r = amendChangeWithUploader(r, project, user);
// Add reviewer and cc
TestAccount reviewer = accountCreator.user2();
TestAccount cc = accountCreator.admin2();
ReviewInput reviewInput = new ReviewInput().blockAutomaticAttentionSetRules();
reviewInput = reviewInput.reviewer(reviewer.email());
reviewInput.reviewer(cc.email(), ReviewerState.CC, false);
change(r).current().review(reviewInput);
requestScopeOperations.setApiUser(user.id());
change(r).current().review(new ReviewInput());
// Reviewer and CC not added since the uploader didn't reply to their comments
assertThat(getAttentionSetUpdatesForUser(r, cc)).isEmpty();
assertThat(getAttentionSetUpdatesForUser(r, reviewer)).isEmpty();
// Owner added
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, admin));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(admin.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Someone else replied on the change");
}
@Test
public void repliesWhileAddingAsReviewerStillRemovesUser() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "remove"));
requestScopeOperations.setApiUser(user.id());
ReviewInput reviewInput = ReviewInput.recommend();
change(r).current().review(reviewInput);
// reviewer removed
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("removed on reply");
}
@Test
public void attentionSetUnchangedWithIgnoreAutomaticAttentionSetRules() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(admin.email(), "reason"));
change(r)
.current()
.review(
ReviewInput.create()
.reviewer(admin.email(), ReviewerState.CC, false)
.blockAutomaticAttentionSetRules());
// admin is still in the attention set, although replies remove from attention set, and removing
// from reviewer also should remove from attention set.
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(admin.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("reason");
}
@Test
public void ownerNotAddedAsReviewerToAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).current().review(ReviewInput.approve());
assertThat(getAttentionSetUpdatesForUser(r, admin)).isEmpty();
}
@Test
public void ownerNotAddedAsReviewerToAttentionSetWithoutAutomaticRules() throws Exception {
PushOneCommit.Result r = createChange();
change(r).current().review(ReviewInput.approve().blockAutomaticAttentionSetRules());
assertThat(getAttentionSetUpdatesForUser(r, admin)).isEmpty();
}
@Test
public void uploaderNotAddedAsReviewerToAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
amendChangeWithUploader(r, project, user);
requestScopeOperations.setApiUser(user.id());
change(r).current().review(ReviewInput.recommend());
assertThat(getAttentionSetUpdatesForUser(r, user)).isEmpty();
}
@Test
public void uploaderNotAddedAsReviewerToAttentionSetWithoutAutomaticRules() throws Exception {
PushOneCommit.Result r = createChange();
amendChangeWithUploader(r, project, user);
requestScopeOperations.setApiUser(user.id());
change(r).current().review(ReviewInput.recommend().blockAutomaticAttentionSetRules());
assertThat(getAttentionSetUpdatesForUser(r, user)).isEmpty();
}
@Test
public void attentionSetStillChangesWithIgnoreAutomaticAttentionSetRulesWithInputList()
throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(admin.email(), "reason"));
change(r)
.current()
.review(
ReviewInput.create()
.removeUserFromAttentionSet(admin.email(), "removed")
.blockAutomaticAttentionSetRules());
// Admin is still removed although we block default attention set rules, since we remove
// the admin manually.
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(admin.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("removed");
}
@Test
public void robotsNotAddedToAttentionSet() throws Exception {
TestAccount robot =
accountCreator.create("robot1", "[email protected]", "Ro Bot", "Ro", "Service Users");
PushOneCommit.Result r = createChange();
// Throw an error when adding a robot explicitly.
BadRequestException exception =
assertThrows(
BadRequestException.class,
() -> change(r).addToAttentionSet(new AttentionSetInput(robot.email(), "reason")));
assertThat(exception.getMessage())
.isEqualTo(
"[email protected] is a robot, and robots can't be added to the attention set.");
// Robots are not added implicitly.
change(r).addReviewer(robot.email());
assertThat(r.getChange().attentionSet()).isEmpty();
}
@Test
public void robotAddingAReviewerChangeAttentionSet() throws Exception {
TestAccount robot =
accountCreator.create("robot2", "[email protected]", "Ro Bot", "Ro", "Service Users");
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(robot.id());
change(r).addReviewer(user.id().toString());
// Bots can still change the attention set, just not when replying.
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer was added");
}
@Test
public void robotReviewDoesNotChangeAttentionSet() throws Exception {
TestAccount robot =
accountCreator.create("robot2", "[email protected]", "Ro Bot", "Ro", "Service Users");
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(robot.id());
change(r).current().review(ReviewInput.recommend());
assertThat(r.getChange().attentionSet()).isEmpty();
}
@Test
public void robotReviewWithNegativeLabelAddsOwner() throws Exception {
TestAccount robot =
accountCreator.create("robot2", "[email protected]", "Ro Bot", "Ro", "Service Users");
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(robot.id());
change(r).current().review(ReviewInput.dislike());
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, admin));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(admin.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("A robot voted negatively on a label");
}
@Test
public void robotCommentDoesNotAddOwnerOnClosedChanges() throws Exception {
TestAccount robot =
accountCreator.create("robot2", "[email protected]", "Ro Bot", "Ro", "Service Users");
PushOneCommit.Result r = createChange();
gApi.changes().id(r.getChangeId()).abandon();
requestScopeOperations.setApiUser(robot.id());
ReviewInput reviewInput = new ReviewInput();
ReviewInput.RobotCommentInput robotCommentInput =
TestCommentHelper.createRobotCommentInputWithMandatoryFields("a.txt");
reviewInput.robotComments = ImmutableMap.of("a.txt", ImmutableList.of(robotCommentInput));
change(r).current().review(reviewInput);
assertThat(r.getChange().attentionSet()).isEmpty();
}
@Test
public void robotCanChangeAttentionSetExplicitly() throws Exception {
TestAccount robot =
accountCreator.create("robot2", "[email protected]", "Ro Bot", "Ro", "Service Users");
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(robot.id());
change(r).current().review(new ReviewInput().addUserToAttentionSet(admin.email(), "reason"));
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, admin));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(admin.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("reason");
}
@Test
public void addUsersToAttentionSetInPrivateChanges() throws Exception {
PushOneCommit.Result r = createChange();
change(r).setPrivate(true);
change(r).current().review(new ReviewInput().addUserToAttentionSet(user.email(), "reason"));
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("reason");
}
@Test
public void addUsersAsReviewerAndAttentionSetInPrivateChanges() throws Exception {
PushOneCommit.Result r = createChange();
change(r).setPrivate(true);
change(r).current().review(new ReviewInput().reviewer(user.email()));
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer was added");
}
@Test
public void attentionSetEmailFooter() throws Exception {
PushOneCommit.Result r = createChange();
// Add user to attention set. They receive an email with the attention footer.
change(r).addReviewer(user.id().toString());
assertThat(Iterables.getOnlyElement(sender.getMessages()).body())
.contains("Gerrit-Attention: " + user.fullName());
sender.clear();
// Irrelevant reply, User is still in the attention set.
change(r).current().review(ReviewInput.approve());
assertThat(Iterables.getOnlyElement(sender.getMessages()).body())
.contains("Gerrit-Attention: " + user.fullName());
sender.clear();
// Abandon the change which removes user from attention set; there is an email but without the
// attention footer.
change(r).abandon();
assertThat(Iterables.getOnlyElement(sender.getMessages()).body())
.doesNotContain("Gerrit-Attention: " + user.fullName());
sender.clear();
}
@Test
@GerritConfig(name = "change.enableAttentionSet", value = "true")
public void attentionSetEmailHeader() throws Exception {
PushOneCommit.Result r = createChange();
TestAccount user2 = accountCreator.user2();
// The pattern ensures the header mentions the attention set requirements in any order.
Pattern attentionSetHeaderPattern =
Pattern.compile(
String.format(
"Attention is currently required from: (%s|%s), (%s|%s).",
user2.fullName(), user.fullName(), user.fullName(), user2.fullName()));
// Add user and user2 to the attention set.
change(r)
.current()
.review(
ReviewInput.create().reviewer(user.email()).reviewer(accountCreator.user2().email()));
assertThat(Iterables.getOnlyElement(sender.getMessages()).body())
.containsMatch(attentionSetHeaderPattern);
assertThat(Iterables.getOnlyElement(sender.getMessages()).htmlBody())
.containsMatch(attentionSetHeaderPattern);
sender.clear();
// Irrelevant reply, User and User2 are still in the attention set.
change(r).current().review(ReviewInput.approve());
assertThat(Iterables.getOnlyElement(sender.getMessages()).body())
.containsMatch(attentionSetHeaderPattern);
assertThat(Iterables.getOnlyElement(sender.getMessages()).htmlBody())
.containsMatch(attentionSetHeaderPattern);
sender.clear();
// Abandon the change which removes user from attention set; there is an email but without the
// attention footer.
change(r).abandon();
assertThat(Iterables.getOnlyElement(sender.getMessages()).body())
.doesNotContain("Attention is currently required");
assertThat(Iterables.getOnlyElement(sender.getMessages()).htmlBody())
.doesNotContain("Attention is currently required");
sender.clear();
}
@Test
@GerritConfig(name = "change.enableAttentionSet", value = "false")
public void noReferenceToAttentionSetInEmailsWhenDisabled() throws Exception {
PushOneCommit.Result r = createChange();
// Add user and to the attention set.
change(r).addReviewer(user.id().toString());
// Attention set is not referenced.
assertThat(Iterables.getOnlyElement(sender.getMessages()).body())
.doesNotContain("Attention is currently required");
assertThat(Iterables.getOnlyElement(sender.getMessages()).htmlBody())
.doesNotContain("Attention is currently required");
sender.clear();
}
@Test
public void attentionSetWithEmailFilter() throws Exception {
PushOneCommit.Result r = createChange();
// Add preference for the user such that they only receive an email on changes that require
// their attention.
requestScopeOperations.setApiUser(user.id());
GeneralPreferencesInfo prefs = gApi.accounts().self().getPreferences();
prefs.emailStrategy = EmailStrategy.ATTENTION_SET_ONLY;
gApi.accounts().self().setPreferences(prefs);
requestScopeOperations.setApiUser(admin.id());
// Add user to attention set. They receive an email since they are in the attention set.
change(r).addReviewer(user.id().toString());
assertThat(sender.getMessages()).isNotEmpty();
sender.clear();
// Irrelevant reply, User is still in the attention set, thus got another email.
change(r).current().review(ReviewInput.approve());
assertThat(sender.getMessages()).isNotEmpty();
sender.clear();
// Abandon the change which removes user from attention set; the user doesn't receive an email
// since they are not in the attention set.
change(r).abandon();
assertThat(sender.getMessages()).isEmpty();
}
@Test
public void attentionSetWithEmailFilterFiltersNewPatchsets() throws Exception {
PushOneCommit.Result r = createChange();
// Add preference for the user such that they only receive an email on changes that require
// their attention.
requestScopeOperations.setApiUser(user.id());
GeneralPreferencesInfo prefs = gApi.accounts().self().getPreferences();
prefs.emailStrategy = EmailStrategy.ATTENTION_SET_ONLY;
gApi.accounts().self().setPreferences(prefs);
requestScopeOperations.setApiUser(admin.id());
// Add user to reviewers but not to the attention set
change(r)
.current()
.review(
ReviewInput.create()
.reviewer(user.email())
.removeUserFromAttentionSet(user.email(), "reason"));
sender.clear();
// amending a change doesn't send an email when user is not in the attention set.
amendChange(r.getChangeId());
assertThat(sender.getMessages()).isEmpty();
}
@Test
public void attentionSetWithEmailFilterImpactingOnlyChangeEmails() throws Exception {
// Add preference for the user such that they only receive an email on changes that require
// their attention.
requestScopeOperations.setApiUser(user.id());
GeneralPreferencesInfo prefs = gApi.accounts().self().getPreferences();
prefs.emailStrategy = EmailStrategy.ATTENTION_SET_ONLY;
gApi.accounts().self().setPreferences(prefs);
requestScopeOperations.setApiUser(admin.id());
// Ensure emails that don't relate to changes are still sent.
gApi.accounts().id(user.id().get()).generateHttpPassword();
assertThat(sender.getMessages()).isNotEmpty();
}
private List<AttentionSetUpdate> getAttentionSetUpdatesForUser(
PushOneCommit.Result r, TestAccount account) {
return getAttentionSetUpdates(r.getChange().getId()).stream()
.filter(a -> a.account().equals(account.id()))
.collect(Collectors.toList());
}
private List<AttentionSetUpdate> getAttentionSetUpdates(Change.Id changeId) {
List<ChangeData> changeData = changeQueryProvider.get().byLegacyChangeId(changeId);
if (changeData.size() != 1) {
throw new IllegalStateException(
String.format("Not exactly one change found for ID %s.", changeId));
}
return new ArrayList<>(Iterables.getOnlyElement(changeData).attentionSet());
}
private ReviewInput reviewWithComment() {
return reviewInReplyToComment(null);
}
private ReviewInput reviewInReplyToComment(@Nullable String id) {
ReviewInput.CommentInput comment = new ReviewInput.CommentInput();
comment.side = Side.REVISION;
comment.path = Patch.COMMIT_MSG;
comment.message = "comment";
comment.updated = TimeUtil.nowTs();
comment.inReplyTo = id;
ReviewInput reviewInput = new ReviewInput();
reviewInput.comments = ImmutableMap.of(Patch.COMMIT_MSG, ImmutableList.of(comment));
return reviewInput;
}
private Correspondence<AttentionSetUpdate, Account.Id> hasAccount() {
return NullAwareCorrespondence.transforming(AttentionSetUpdate::account, "hasAccount");
}
}
|
javatests/com/google/gerrit/acceptance/rest/change/AttentionSetIT.java
|
// Copyright (C) 2020 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.acceptance.rest.change;
import static com.google.common.truth.Truth.assertThat;
import static com.google.gerrit.extensions.restapi.testing.AttentionSetUpdateSubject.assertThat;
import static com.google.gerrit.testing.GerritJUnit.assertThrows;
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.truth.Correspondence;
import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.NoHttpd;
import com.google.gerrit.acceptance.PushOneCommit;
import com.google.gerrit.acceptance.TestAccount;
import com.google.gerrit.acceptance.UseClockStep;
import com.google.gerrit.acceptance.config.GerritConfig;
import com.google.gerrit.acceptance.testsuite.account.AccountOperations;
import com.google.gerrit.acceptance.testsuite.change.ChangeOperations;
import com.google.gerrit.acceptance.testsuite.request.RequestScopeOperations;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.entities.Account;
import com.google.gerrit.entities.AttentionSetUpdate;
import com.google.gerrit.entities.Change;
import com.google.gerrit.entities.Patch;
import com.google.gerrit.extensions.api.changes.AddReviewerInput;
import com.google.gerrit.extensions.api.changes.AttentionSetInput;
import com.google.gerrit.extensions.api.changes.DeleteReviewerInput;
import com.google.gerrit.extensions.api.changes.HashtagsInput;
import com.google.gerrit.extensions.api.changes.ReviewInput;
import com.google.gerrit.extensions.client.GeneralPreferencesInfo;
import com.google.gerrit.extensions.client.GeneralPreferencesInfo.EmailStrategy;
import com.google.gerrit.extensions.client.ReviewerState;
import com.google.gerrit.extensions.client.Side;
import com.google.gerrit.extensions.restapi.BadRequestException;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gerrit.server.query.change.InternalChangeQuery;
import com.google.gerrit.server.util.time.TimeUtil;
import com.google.gerrit.testing.FakeEmailSender;
import com.google.gerrit.testing.TestCommentHelper;
import com.google.gerrit.truth.NullAwareCorrespondence;
import com.google.inject.Inject;
import com.google.inject.Provider;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.LongSupplier;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
@NoHttpd
@UseClockStep(clockStepUnit = TimeUnit.MINUTES)
public class AttentionSetIT extends AbstractDaemonTest {
@Inject private ChangeOperations changeOperations;
@Inject private AccountOperations accountOperations;
@Inject private RequestScopeOperations requestScopeOperations;
@Inject private FakeEmailSender email;
@Inject private TestCommentHelper testCommentHelper;
@Inject private Provider<InternalChangeQuery> changeQueryProvider;
/** Simulates a fake clock. Uses second granularity. */
private static class FakeClock implements LongSupplier {
Instant now = Instant.now();
@Override
public long getAsLong() {
return TimeUnit.SECONDS.toMillis(now.getEpochSecond());
}
Instant now() {
return Instant.ofEpochSecond(now.getEpochSecond());
}
void advance(Duration duration) {
now = now.plus(duration);
}
}
private FakeClock fakeClock = new FakeClock();
@Before
public void setUp() {
TimeUtil.setCurrentMillisSupplier(fakeClock);
}
@Test
public void emptyAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
assertThat(r.getChange().attentionSet()).isEmpty();
}
@Test
public void addUser() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
int accountId =
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "first"))._accountId;
assertThat(accountId).isEqualTo(user.id().get());
AttentionSetUpdate expectedAttentionSetUpdate =
AttentionSetUpdate.createFromRead(
fakeClock.now(), user.id(), AttentionSetUpdate.Operation.ADD, "first");
assertThat(r.getChange().attentionSet()).containsExactly(expectedAttentionSetUpdate);
// Second add is ignored.
accountId =
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "second"))._accountId;
assertThat(accountId).isEqualTo(user.id().get());
assertThat(r.getChange().attentionSet()).containsExactly(expectedAttentionSetUpdate);
// Only one email since the second add was ignored.
String emailBody = Iterables.getOnlyElement(email.getMessages()).body();
assertThat(emailBody)
.contains(
user.fullName()
+ " added themselves to the attention set of this change.\n The reason is: first.");
}
@Test
public void addMultipleUsers() throws Exception {
PushOneCommit.Result r = createChange();
Instant timestamp1 = fakeClock.now();
int accountId1 =
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "user"))._accountId;
assertThat(accountId1).isEqualTo(user.id().get());
fakeClock.advance(Duration.ofSeconds(42));
Instant timestamp2 = fakeClock.now();
int accountId2 =
change(r)
.addToAttentionSet(new AttentionSetInput(admin.id().toString(), "admin"))
._accountId;
assertThat(accountId2).isEqualTo(admin.id().get());
AttentionSetUpdate expectedAttentionSetUpdate1 =
AttentionSetUpdate.createFromRead(
timestamp1, user.id(), AttentionSetUpdate.Operation.ADD, "user");
AttentionSetUpdate expectedAttentionSetUpdate2 =
AttentionSetUpdate.createFromRead(
timestamp2, admin.id(), AttentionSetUpdate.Operation.ADD, "admin");
assertThat(r.getChange().attentionSet())
.containsExactly(expectedAttentionSetUpdate1, expectedAttentionSetUpdate2);
}
@Test
public void removeUser() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "added"));
requestScopeOperations.setApiUser(user.id());
fakeClock.advance(Duration.ofSeconds(42));
change(r).attention(user.id().toString()).remove(new AttentionSetInput("removed"));
AttentionSetUpdate expectedAttentionSetUpdate =
AttentionSetUpdate.createFromRead(
fakeClock.now(), user.id(), AttentionSetUpdate.Operation.REMOVE, "removed");
assertThat(r.getChange().attentionSet()).containsExactly(expectedAttentionSetUpdate);
// Second removal is ignored.
fakeClock.advance(Duration.ofSeconds(42));
change(r).attention(user.id().toString()).remove(new AttentionSetInput("removed again"));
assertThat(r.getChange().attentionSet()).containsExactly(expectedAttentionSetUpdate);
// Only one email since the second remove was ignored.
String emailBody = Iterables.getOnlyElement(email.getMessages()).body();
assertThat(emailBody)
.contains(
user.fullName()
+ " removed themselves from the attention set of this change.\n"
+ " The reason is: removed.");
}
@Test
public void removeUserWithInvalidUserInput() throws Exception {
PushOneCommit.Result r = createChange();
BadRequestException exception =
assertThrows(
BadRequestException.class,
() ->
change(r)
.attention(user.id().toString())
.remove(new AttentionSetInput("invalid user", "reason")));
assertThat(exception.getMessage())
.isEqualTo("The user specified in the input body couldn't be found.");
exception =
assertThrows(
BadRequestException.class,
() ->
change(r)
.attention(user.id().toString())
.remove(new AttentionSetInput(admin.email(), "reason")));
assertThat(exception.getMessage())
.isEqualTo(
"The field \"user\" must be empty, or must match the user specified in the URL.");
}
@Test
public void removeUnrelatedUser() throws Exception {
PushOneCommit.Result r = createChange();
change(r).attention(user.id().toString()).remove(new AttentionSetInput("foo"));
assertThat(r.getChange().attentionSet()).isEmpty();
}
@Test
public void abandonRemovesUsers() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "user"));
change(r).addToAttentionSet(new AttentionSetInput(admin.email(), "admin"));
change(r).abandon();
AttentionSetUpdate userUpdate =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(userUpdate).hasAccountIdThat().isEqualTo(user.id());
assertThat(userUpdate).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(userUpdate).hasReasonThat().isEqualTo("Change was abandoned");
AttentionSetUpdate adminUpdate =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, admin));
assertThat(adminUpdate).hasAccountIdThat().isEqualTo(admin.id());
assertThat(adminUpdate).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(adminUpdate).hasReasonThat().isEqualTo("Change was abandoned");
}
@Test
public void workInProgressRemovesUsers() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "reason"));
change(r).setWorkInProgress();
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("Change was marked work in progress");
}
@Test
public void submitRemovesUsersForAllSubmittedChanges() throws Exception {
PushOneCommit.Result r1 = createChange("refs/heads/master", "file1", "content");
change(r1)
.current()
.review(ReviewInput.approve().addUserToAttentionSet(user.email(), "reason"));
PushOneCommit.Result r2 = createChange("refs/heads/master", "file2", "content");
change(r2)
.current()
.review(ReviewInput.approve().addUserToAttentionSet(user.email(), "reason"));
change(r2).current().submit();
// Attention set updates that relate to the admin (the person who replied) are filtered out.
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r1, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("Change was submitted");
// Attention set updates that relate to the admin (the person who replied) are filtered out.
attentionSet = Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r2, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("Change was submitted");
}
@Test
public void robotSubmitsRemovesUsers() throws Exception {
PushOneCommit.Result r1 = createChange("refs/heads/master", "file1", "content");
change(r1)
.current()
.review(ReviewInput.approve().addUserToAttentionSet(user.email(), "reason"));
TestAccount robot =
accountCreator.create(
"robot2", "[email protected]", "Ro Bot", "Ro", "Service Users", "Administrators");
requestScopeOperations.setApiUser(robot.id());
change(r1).current().submit();
// Attention set updates that relate to the admin (the person who replied) are filtered out.
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r1, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("Change was submitted");
}
@Test
public void addedReviewersAreAddedToAttentionSetOnMergedChanges() throws Exception {
PushOneCommit.Result r = createChange();
change(r).current().review(ReviewInput.approve());
change(r).current().submit();
change(r).addReviewer(user.email());
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer was added");
}
@Test
public void reviewersAddedAndRemovedFromAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addReviewer(user.id().toString());
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer was added");
change(r).reviewer(user.email()).remove();
attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer/Cc was removed");
}
@Test
public void removedCcRemovedFromAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
// Add cc
AddReviewerInput input = new AddReviewerInput();
input.reviewer = user.email();
input.state = ReviewerState.CC;
change(r).addReviewer(input);
// Add them to the attention set
AttentionSetInput attentionSetInput = new AttentionSetInput();
attentionSetInput.user = user.email();
attentionSetInput.reason = "reason";
change(r).addToAttentionSet(attentionSetInput);
// Remove them from cc
change(r).reviewer(user.email()).remove();
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer/Cc was removed");
}
@Test
public void reviewersAddedAndRemovedByEmailFromAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addReviewer(user.email());
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer was added");
change(r).reviewer(user.email()).remove();
attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer/Cc was removed");
}
@Test
public void reviewersInWorkProgressNotAddedToAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).setWorkInProgress();
change(r).addReviewer(user.email());
assertThat(r.getChange().attentionSet()).isEmpty();
}
@Test
public void addingReviewerWhileMarkingWorkInProgressDoesntAddToAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
ReviewInput reviewInput = ReviewInput.create().setWorkInProgress(true);
AddReviewerInput addReviewerInput = new AddReviewerInput();
addReviewerInput.state = ReviewerState.REVIEWER;
addReviewerInput.reviewer = user.email();
reviewInput.reviewers = ImmutableList.of(addReviewerInput);
change(r).current().review(reviewInput);
assertThat(getAttentionSetUpdatesForUser(r, user)).isEmpty();
}
@Test
public void reviewersAddedAsReviewersAgainAreNotAddedToAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addReviewer(user.id().toString());
change(r)
.attention(user.id().toString())
.remove(new AttentionSetInput("removed and not re-added when re-adding as reviewer"));
change(r).addReviewer(user.id().toString());
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet)
.hasReasonThat()
.isEqualTo("removed and not re-added when re-adding as reviewer");
}
@Test
public void ccsAreIgnored() throws Exception {
PushOneCommit.Result r = createChange();
AddReviewerInput addReviewerInput = new AddReviewerInput();
addReviewerInput.state = ReviewerState.CC;
addReviewerInput.reviewer = user.email();
change(r).addReviewer(addReviewerInput);
assertThat(r.getChange().attentionSet()).isEmpty();
}
@Test
public void ccsConsideredSameAsRemovedForExistingReviewers() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addReviewer(user.email());
AddReviewerInput addReviewerInput = new AddReviewerInput();
addReviewerInput.state = ReviewerState.CC;
addReviewerInput.reviewer = user.email();
change(r).addReviewer(addReviewerInput);
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer/Cc was removed");
}
@Test
public void robotReadyForReviewAddsAllReviewersToAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).setWorkInProgress();
change(r).addReviewer(user.email());
TestAccount robot =
accountCreator.create(
"robot1", "[email protected]", "Ro Bot", "Ro", "Service Users", "Administrators");
requestScopeOperations.setApiUser(robot.id());
change(r).setReadyForReview();
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Change was marked ready for review");
}
@Test
public void readyForReviewAddsAllReviewersToAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).setWorkInProgress();
change(r).addReviewer(user.email());
change(r).setReadyForReview();
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Change was marked ready for review");
}
@Test
public void readyForReviewWhileRemovingReviewerRemovesThemToAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).setWorkInProgress();
change(r).addReviewer(user.email());
ReviewInput reviewInput = ReviewInput.create().setReady(true);
AddReviewerInput addReviewerInput = new AddReviewerInput();
addReviewerInput.state = ReviewerState.CC;
addReviewerInput.reviewer = user.email();
reviewInput.reviewers = ImmutableList.of(addReviewerInput);
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "reason"));
change(r).current().review(reviewInput);
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer/Cc was removed");
}
@Test
public void readyForReviewWhileAddingReviewerAddsThemToAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).setWorkInProgress();
ReviewInput reviewInput = ReviewInput.create().setReady(true).reviewer(user.email());
change(r).current().review(reviewInput);
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer was added");
}
@Test
public void reviewersAreNotAddedForNoReasonBecauseOfAnUpdate() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "user"));
change(r).attention(user.id().toString()).remove(new AttentionSetInput("removed"));
HashtagsInput hashtagsInput = new HashtagsInput();
hashtagsInput.add = ImmutableSet.of("tag");
change(r).setHashtags(hashtagsInput);
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("removed");
}
@Test
public void reviewAddsManuallyAddedUserToAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
ReviewInput reviewInput = ReviewInput.create().addUserToAttentionSet(user.email(), "reason");
change(r).current().review(reviewInput);
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("reason");
// No emails for adding to attention set were sent.
email.getMessages().isEmpty();
}
@Test
public void reviewRemovesManuallyRemovedUserFromAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "reason"));
requestScopeOperations.setApiUser(user.id());
ReviewInput reviewInput =
ReviewInput.create().removeUserFromAttentionSet(user.email(), "reason");
change(r).current().review(reviewInput);
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("reason");
// No emails for removing from attention set were sent.
email.getMessages().isEmpty();
}
@Test
public void reviewWithManualAdditionToAttentionSetFailsWithoutReason() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "reason"));
ReviewInput reviewInput = ReviewInput.create().addUserToAttentionSet(user.email(), "");
BadRequestException exception =
assertThrows(BadRequestException.class, () -> change(r).current().review(reviewInput));
assertThat(exception.getMessage()).isEqualTo("missing field: reason");
}
@Test
public void reviewWithManualAdditionToAttentionSetFailsWithoutUser() throws Exception {
PushOneCommit.Result r = createChange();
ReviewInput reviewInput = ReviewInput.create().addUserToAttentionSet("", "reason");
BadRequestException exception =
assertThrows(BadRequestException.class, () -> change(r).current().review(reviewInput));
assertThat(exception.getMessage()).isEqualTo("missing field: user");
}
@Test
public void reviewAddReviewerWhileRemovingFromAttentionSetJustRemovesUser() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "addition"));
ReviewInput reviewInput =
ReviewInput.create()
.reviewer(user.email())
.removeUserFromAttentionSet(user.email(), "reason");
change(r).current().review(reviewInput);
// Attention set updates that relate to the admin (the person who replied) are filtered out.
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("reason");
}
@Test
public void cantAddAndRemoveSameUser() throws Exception {
PushOneCommit.Result r = createChange();
ReviewInput reviewInput =
ReviewInput.create()
.removeUserFromAttentionSet(user.email(), "reason")
.addUserToAttentionSet(user.username(), "reason");
BadRequestException exception =
assertThrows(BadRequestException.class, () -> change(r).current().review(reviewInput));
assertThat(exception.getMessage())
.isEqualTo(
"user can not be added/removed twice, and can not be added and removed at the same"
+ " time");
}
@Test
public void cantRemoveSameUserTwice() throws Exception {
PushOneCommit.Result r = createChange();
ReviewInput reviewInput =
ReviewInput.create()
.removeUserFromAttentionSet(user.email(), "reason1")
.removeUserFromAttentionSet(user.username(), "reason2");
BadRequestException exception =
assertThrows(BadRequestException.class, () -> change(r).current().review(reviewInput));
assertThat(exception.getMessage())
.isEqualTo(
"user can not be added/removed twice, and can not be added and removed at the same"
+ " time");
}
@Test
public void reviewDoesNotAddReviewerWithoutAutomaticRules() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
ReviewInput reviewInput = ReviewInput.recommend().blockAutomaticAttentionSetRules();
change(r).current().review(reviewInput);
assertThat(getAttentionSetUpdatesForUser(r, user)).isEmpty();
}
@Test
public void reviewDoesNotAddReviewer() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
ReviewInput reviewInput = ReviewInput.recommend();
change(r).current().review(reviewInput);
assertThat(getAttentionSetUpdatesForUser(r, user)).isEmpty();
}
@Test
public void cantAddSameUserTwice() throws Exception {
PushOneCommit.Result r = createChange();
ReviewInput reviewInput =
ReviewInput.create()
.addUserToAttentionSet(user.email(), "reason1")
.addUserToAttentionSet(user.username(), "reason2");
BadRequestException exception =
assertThrows(BadRequestException.class, () -> change(r).current().review(reviewInput));
assertThat(exception.getMessage())
.isEqualTo(
"user can not be added/removed twice, and can not be added and removed at the same"
+ " time");
}
@Test
public void reviewRemoveFromAttentionSetWhileMarkingReadyForReviewJustRemovesUser()
throws Exception {
PushOneCommit.Result r = createChange();
change(r).setWorkInProgress();
change(r).addReviewer(user.email());
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "reason"));
ReviewInput reviewInput =
ReviewInput.create().setReady(true).removeUserFromAttentionSet(user.email(), "reason");
change(r).current().review(reviewInput);
// Attention set updates that relate to the admin (the person who replied) are filtered out.
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("reason");
}
@Test
public void reviewAddToAttentionSetWhileMarkingWorkInProgressJustAddsUser() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addReviewer(user.email());
ReviewInput reviewInput =
ReviewInput.create().setWorkInProgress(true).addUserToAttentionSet(user.email(), "reason");
change(r).attention(user.email()).remove(new AttentionSetInput("removal"));
change(r).current().review(reviewInput);
// Attention set updates that relate to the admin (the person who replied) are filtered out.
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("reason");
}
@Test
public void reviewRemovesUserFromAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(admin.email(), "reason"));
ReviewInput reviewInput = new ReviewInput();
change(r).current().review(reviewInput);
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(admin.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("removed on reply");
}
@Test
public void reviewAddUserToAttentionSetWhileReplyingJustAddsUser() throws Exception {
PushOneCommit.Result r = createChange();
ReviewInput reviewInput = ReviewInput.create().addUserToAttentionSet(admin.email(), "reason");
change(r).current().review(reviewInput);
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(admin.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("reason");
}
@Test
public void reviewWhileAddingThemselvesAsReviewerStillRemovesThem() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "reason"));
ReviewInput reviewInput = ReviewInput.create().reviewer(user.email());
change(r).current().review(reviewInput);
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("removed on reply");
}
@Test
public void reviewWhileAddingThemselvesAsReviewerDoesNotAddThem() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
ReviewInput reviewInput = ReviewInput.create().reviewer(user.email());
change(r).current().review(reviewInput);
assertThat(getAttentionSetUpdatesForUser(r, user)).isEmpty();
}
@Test
public void repliesAddsOwner() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
ReviewInput reviewInput = new ReviewInput();
change(r).current().review(reviewInput);
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, admin));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(admin.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Someone else replied on the change");
}
@Test
public void repliesDoNotAddOwnerWhenChangeIsClosed() throws Exception {
PushOneCommit.Result r = createChange();
change(r).abandon();
requestScopeOperations.setApiUser(user.id());
ReviewInput reviewInput = new ReviewInput();
change(r).current().review(reviewInput);
assertThat(getAttentionSetUpdatesForUser(r, admin)).isEmpty();
}
@Test
public void repliesDoNotAddOwnerWhenChangeIsWorkInProgress() throws Exception {
PushOneCommit.Result r = createChange();
change(r).setWorkInProgress();
requestScopeOperations.setApiUser(user.id());
ReviewInput reviewInput = new ReviewInput();
change(r).current().review(reviewInput);
assertThat(getAttentionSetUpdatesForUser(r, admin)).isEmpty();
}
@Test
public void repliesDoNotAddOwnerWhenChangeIsBecomingWorkInProgress() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(accountCreator.admin2().id());
ReviewInput reviewInput = ReviewInput.create().setWorkInProgress(true);
change(r).current().review(reviewInput);
assertThat(getAttentionSetUpdatesForUser(r, admin)).isEmpty();
}
@Test
public void repliesAddOwnerWhenChangeIsBecomingReadyForReview() throws Exception {
PushOneCommit.Result r = createChange();
change(r).setWorkInProgress();
requestScopeOperations.setApiUser(accountCreator.admin2().id());
ReviewInput reviewInput = ReviewInput.create().setReady(true);
change(r).current().review(reviewInput);
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, admin));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(admin.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Someone else replied on the change");
}
@Test
public void repliesAddsOwnerAndUploader() throws Exception {
// Create change with owner: admin
PushOneCommit.Result r = createChange();
r = amendChangeWithUploader(r, project, user);
TestAccount user2 = accountCreator.user2();
requestScopeOperations.setApiUser(user2.id());
change(r).attention(user.email()).remove(new AttentionSetInput("reason"));
ReviewInput reviewInput = new ReviewInput();
change(r).current().review(reviewInput);
reviewInput = new ReviewInput();
change(r).current().review(reviewInput);
// Uploader added
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Someone else replied on the change");
// Owner added
attentionSet = Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, admin));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(admin.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Someone else replied on the change");
}
@Test
public void reviewIgnoresRobotCommentsForAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
testCommentHelper.addRobotComment(
r.getChangeId(),
TestCommentHelper.createRobotCommentInputWithMandatoryFields(Patch.COMMIT_MSG));
requestScopeOperations.setApiUser(admin.id());
change(r)
.current()
.review(
reviewInReplyToComment(
Iterables.getOnlyElement(
gApi.changes().id(r.getChangeId()).current().robotCommentsAsList())
.id));
assertThat(getAttentionSetUpdatesForUser(r, user)).isEmpty();
}
@Test
public void reviewAddsAllUsersInCommentThread() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
change(r).current().review(reviewWithComment());
TestAccount user2 = accountCreator.user2();
requestScopeOperations.setApiUser(user2.id());
change(r)
.current()
.review(
reviewInReplyToComment(
Iterables.getOnlyElement(
gApi.changes().id(r.getChangeId()).current().commentsAsList())
.id));
change(r).attention(user.email()).remove(new AttentionSetInput("removal"));
requestScopeOperations.setApiUser(admin.id());
change(r)
.current()
.review(
reviewInReplyToComment(
gApi.changes().id(r.getChangeId()).current().commentsAsList().get(1).id));
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet)
.hasReasonThat()
.isEqualTo("Someone else replied on a comment you posted");
attentionSet = Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user2));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user2.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet)
.hasReasonThat()
.isEqualTo("Someone else replied on a comment you posted");
}
@Test
public void reviewAddsAllUsersInCommentThreadWhenOriginalCommentIsARobotComment()
throws Exception {
PushOneCommit.Result result = createChange();
testCommentHelper.addRobotComment(
result.getChangeId(),
TestCommentHelper.createRobotCommentInputWithMandatoryFields(Patch.COMMIT_MSG));
requestScopeOperations.setApiUser(user.id());
// Reply to the robot comment.
change(result)
.current()
.review(
reviewInReplyToComment(
Iterables.getOnlyElement(
gApi.changes().id(result.getChangeId()).current().robotCommentsAsList())
.id));
requestScopeOperations.setApiUser(admin.id());
// Reply to the human comment. which was a reply to the robot comment.
change(result)
.current()
.review(
reviewInReplyToComment(
Iterables.getOnlyElement(
gApi.changes().id(result.getChangeId()).current().commentsAsList())
.id));
// The user which replied to the robot comment was added to the attention set.
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(result, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet)
.hasReasonThat()
.isEqualTo("Someone else replied on a comment you posted");
}
@Test
public void reviewAddsAllUsersInCommentThreadEvenOfDifferentChildBranch() throws Exception {
Account.Id changeOwner = accountOperations.newAccount().create();
Change.Id changeId = changeOperations.newChange().owner(changeOwner).create();
Account.Id user1 = accountOperations.newAccount().create();
Account.Id user2 = accountOperations.newAccount().create();
Account.Id user3 = accountOperations.newAccount().create();
Account.Id user4 = accountOperations.newAccount().create();
// Add users as reviewers.
gApi.changes().id(changeId.get()).addReviewer(user1.toString());
gApi.changes().id(changeId.get()).addReviewer(user2.toString());
gApi.changes().id(changeId.get()).addReviewer(user3.toString());
gApi.changes().id(changeId.get()).addReviewer(user4.toString());
// Add a comment thread with branches. Such threads occur if people reply in parallel without
// having seen/loaded the reply of another person.
String root =
changeOperations.change(changeId).currentPatchset().newComment().author(user1).create();
String sibling1 =
changeOperations
.change(changeId)
.currentPatchset()
.newComment()
.author(user2)
.parentUuid(root)
.create();
String sibling2 =
changeOperations
.change(changeId)
.currentPatchset()
.newComment()
.author(user3)
.parentUuid(root)
.create();
changeOperations
.change(changeId)
.currentPatchset()
.newComment()
.author(user4)
.parentUuid(sibling2)
.create();
// Clear the attention set. Necessary as we used Gerrit APIs above which affect the attention
// set.
AttentionSetInput clearAttention = new AttentionSetInput("clear attention set");
gApi.changes().id(changeId.get()).attention(user1.toString()).remove(clearAttention);
gApi.changes().id(changeId.get()).attention(user2.toString()).remove(clearAttention);
gApi.changes().id(changeId.get()).attention(user3.toString()).remove(clearAttention);
gApi.changes().id(changeId.get()).attention(user4.toString()).remove(clearAttention);
requestScopeOperations.setApiUser(changeOwner);
// Simulate that this reply is a child of sibling1 and thus parallel to sibling2 and its child.
gApi.changes().id(changeId.get()).current().review(reviewInReplyToComment(sibling1));
List<AttentionSetUpdate> attentionSetUpdates = getAttentionSetUpdates(changeId);
assertThat(attentionSetUpdates)
.comparingElementsUsing(hasAccount())
.containsExactly(user1, user2, user3, user4);
}
@Test
public void reviewAddsAllUsersInCommentThreadWhenPostedAsDraft() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
change(r).current().review(reviewWithComment());
requestScopeOperations.setApiUser(admin.id());
testCommentHelper.addDraft(
r.getChangeId(),
testCommentHelper.newDraft(
"message",
Iterables.getOnlyElement(gApi.changes().id(r.getChangeId()).current().commentsAsList())
.id));
ReviewInput reviewInput = new ReviewInput();
reviewInput.drafts = ReviewInput.DraftHandling.PUBLISH;
change(r).current().review(reviewInput);
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet)
.hasReasonThat()
.isEqualTo("Someone else replied on a comment you posted");
}
@Test
public void reviewDoesNotAddUsersInACommentThreadThatAreNotActiveInTheChange() throws Exception {
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(user.id());
change(r).current().review(reviewWithComment());
change(r).reviewer(user.id().toString()).remove(new DeleteReviewerInput());
requestScopeOperations.setApiUser(admin.id());
change(r)
.current()
.review(
reviewInReplyToComment(
Iterables.getOnlyElement(
gApi.changes().id(r.getChangeId()).current().commentsAsList())
.id));
// The user was to be added, but was not added since that user is no longer a
// reviewer/cc/owner/uploader.
assertThat(getAttentionSetUpdatesForUser(r, user)).isEmpty();
}
@Test
public void ownerRepliesWhileRemovingReviewerRemovesFromAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addReviewer(user.email());
ReviewInput reviewInput = ReviewInput.create().reviewer(user.email(), ReviewerState.CC, false);
change(r).current().review(reviewInput);
// cc removed
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer/Cc was removed");
}
@Test
public void uploaderRepliesAddsOwner() throws Exception {
PushOneCommit.Result r = createChange();
r = amendChangeWithUploader(r, project, user);
// Add reviewer and cc
TestAccount reviewer = accountCreator.user2();
TestAccount cc = accountCreator.admin2();
ReviewInput reviewInput = new ReviewInput().blockAutomaticAttentionSetRules();
reviewInput = reviewInput.reviewer(reviewer.email());
reviewInput.reviewer(cc.email(), ReviewerState.CC, false);
change(r).current().review(reviewInput);
requestScopeOperations.setApiUser(user.id());
change(r).current().review(new ReviewInput());
// Reviewer and CC not added since the uploader didn't reply to their comments
assertThat(getAttentionSetUpdatesForUser(r, cc)).isEmpty();
assertThat(getAttentionSetUpdatesForUser(r, reviewer)).isEmpty();
// Owner added
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, admin));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(admin.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Someone else replied on the change");
}
@Test
public void repliesWhileAddingAsReviewerStillRemovesUser() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(user.email(), "remove"));
requestScopeOperations.setApiUser(user.id());
ReviewInput reviewInput = ReviewInput.recommend();
change(r).current().review(reviewInput);
// reviewer removed
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("removed on reply");
}
@Test
public void attentionSetUnchangedWithIgnoreAutomaticAttentionSetRules() throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(admin.email(), "reason"));
change(r)
.current()
.review(
ReviewInput.create()
.reviewer(admin.email(), ReviewerState.CC, false)
.blockAutomaticAttentionSetRules());
// admin is still in the attention set, although replies remove from attention set, and removing
// from reviewer also should remove from attention set.
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(admin.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("reason");
}
@Test
public void ownerNotAddedAsReviewerToAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
change(r).current().review(ReviewInput.approve());
assertThat(getAttentionSetUpdatesForUser(r, admin)).isEmpty();
}
@Test
public void ownerNotAddedAsReviewerToAttentionSetWithoutAutomaticRules() throws Exception {
PushOneCommit.Result r = createChange();
change(r).current().review(ReviewInput.approve().blockAutomaticAttentionSetRules());
assertThat(getAttentionSetUpdatesForUser(r, admin)).isEmpty();
}
@Test
public void uploaderNotAddedAsReviewerToAttentionSet() throws Exception {
PushOneCommit.Result r = createChange();
amendChangeWithUploader(r, project, user);
requestScopeOperations.setApiUser(user.id());
change(r).current().review(ReviewInput.recommend());
assertThat(getAttentionSetUpdatesForUser(r, user)).isEmpty();
}
@Test
public void uploaderNotAddedAsReviewerToAttentionSetWithoutAutomaticRules() throws Exception {
PushOneCommit.Result r = createChange();
amendChangeWithUploader(r, project, user);
requestScopeOperations.setApiUser(user.id());
change(r).current().review(ReviewInput.recommend().blockAutomaticAttentionSetRules());
assertThat(getAttentionSetUpdatesForUser(r, user)).isEmpty();
}
@Test
public void attentionSetStillChangesWithIgnoreAutomaticAttentionSetRulesWithInputList()
throws Exception {
PushOneCommit.Result r = createChange();
change(r).addToAttentionSet(new AttentionSetInput(admin.email(), "reason"));
change(r)
.current()
.review(
ReviewInput.create()
.removeUserFromAttentionSet(admin.email(), "removed")
.blockAutomaticAttentionSetRules());
// Admin is still removed although we block default attention set rules, since we remove
// the admin manually.
AttentionSetUpdate attentionSet = Iterables.getOnlyElement(r.getChange().attentionSet());
assertThat(attentionSet).hasAccountIdThat().isEqualTo(admin.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.REMOVE);
assertThat(attentionSet).hasReasonThat().isEqualTo("removed");
}
@Test
public void robotsNotAddedToAttentionSet() throws Exception {
TestAccount robot =
accountCreator.create("robot1", "[email protected]", "Ro Bot", "Ro", "Service Users");
PushOneCommit.Result r = createChange();
// Throw an error when adding a robot explicitly.
BadRequestException exception =
assertThrows(
BadRequestException.class,
() -> change(r).addToAttentionSet(new AttentionSetInput(robot.email(), "reason")));
assertThat(exception.getMessage())
.isEqualTo(
"[email protected] is a robot, and robots can't be added to the attention set.");
// Robots are not added implicitly.
change(r).addReviewer(robot.email());
assertThat(r.getChange().attentionSet()).isEmpty();
}
@Test
public void robotAddingAReviewerChangeAttentionSet() throws Exception {
TestAccount robot =
accountCreator.create("robot2", "[email protected]", "Ro Bot", "Ro", "Service Users");
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(robot.id());
change(r).addReviewer(user.id().toString());
// Bots can still change the attention set, just not when replying.
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer was added");
}
@Test
public void robotReviewDoesNotChangeAttentionSet() throws Exception {
TestAccount robot =
accountCreator.create("robot2", "[email protected]", "Ro Bot", "Ro", "Service Users");
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(robot.id());
change(r).current().review(ReviewInput.recommend());
assertThat(r.getChange().attentionSet()).isEmpty();
}
@Test
public void robotReviewWithNegativeLabelAddsOwner() throws Exception {
TestAccount robot =
accountCreator.create("robot2", "[email protected]", "Ro Bot", "Ro", "Service Users");
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(robot.id());
change(r).current().review(ReviewInput.dislike());
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, admin));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(admin.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("A robot voted negatively on a label");
}
@Test
public void robotCommentDoesNotAddOwnerOnClosedChanges() throws Exception {
TestAccount robot =
accountCreator.create("robot2", "[email protected]", "Ro Bot", "Ro", "Service Users");
PushOneCommit.Result r = createChange();
gApi.changes().id(r.getChangeId()).abandon();
requestScopeOperations.setApiUser(robot.id());
ReviewInput reviewInput = new ReviewInput();
ReviewInput.RobotCommentInput robotCommentInput =
TestCommentHelper.createRobotCommentInputWithMandatoryFields("a.txt");
reviewInput.robotComments = ImmutableMap.of("a.txt", ImmutableList.of(robotCommentInput));
change(r).current().review(reviewInput);
assertThat(r.getChange().attentionSet()).isEmpty();
}
@Test
public void robotCanChangeAttentionSetExplicitly() throws Exception {
TestAccount robot =
accountCreator.create("robot2", "[email protected]", "Ro Bot", "Ro", "Service Users");
PushOneCommit.Result r = createChange();
requestScopeOperations.setApiUser(robot.id());
change(r).current().review(new ReviewInput().addUserToAttentionSet(admin.email(), "reason"));
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, admin));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(admin.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("reason");
}
@Test
public void addUsersToAttentionSetInPrivateChanges() throws Exception {
PushOneCommit.Result r = createChange();
change(r).setPrivate(true);
change(r).current().review(new ReviewInput().addUserToAttentionSet(user.email(), "reason"));
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("reason");
}
@Test
public void addUsersAsReviewerAndAttentionSetInPrivateChanges() throws Exception {
PushOneCommit.Result r = createChange();
change(r).setPrivate(true);
change(r).current().review(new ReviewInput().reviewer(user.email()));
AttentionSetUpdate attentionSet =
Iterables.getOnlyElement(getAttentionSetUpdatesForUser(r, user));
assertThat(attentionSet).hasAccountIdThat().isEqualTo(user.id());
assertThat(attentionSet).hasOperationThat().isEqualTo(AttentionSetUpdate.Operation.ADD);
assertThat(attentionSet).hasReasonThat().isEqualTo("Reviewer was added");
}
@Test
public void attentionSetEmailFooter() throws Exception {
PushOneCommit.Result r = createChange();
// Add user to attention set. They receive an email with the attention footer.
change(r).addReviewer(user.id().toString());
assertThat(Iterables.getOnlyElement(sender.getMessages()).body())
.contains("Gerrit-Attention: " + user.fullName());
sender.clear();
// Irrelevant reply, User is still in the attention set.
change(r).current().review(ReviewInput.approve());
assertThat(Iterables.getOnlyElement(sender.getMessages()).body())
.contains("Gerrit-Attention: " + user.fullName());
sender.clear();
// Abandon the change which removes user from attention set; there is an email but without the
// attention footer.
change(r).abandon();
assertThat(Iterables.getOnlyElement(sender.getMessages()).body())
.doesNotContain("Gerrit-Attention: " + user.fullName());
sender.clear();
}
@Test
@GerritConfig(name = "change.enableAttentionSet", value = "true")
public void attentionSetEmailHeader() throws Exception {
PushOneCommit.Result r = createChange();
TestAccount user2 = accountCreator.user2();
// Add user and user2 to the attention set.
change(r)
.current()
.review(
ReviewInput.create().reviewer(user.email()).reviewer(accountCreator.user2().email()));
assertThat(Iterables.getOnlyElement(sender.getMessages()).body())
.contains(
"Attention is currently required from: "
+ user2.fullName()
+ ", "
+ user.fullName()
+ ".");
assertThat(Iterables.getOnlyElement(sender.getMessages()).htmlBody())
.contains(
"Attention is currently required from: "
+ user2.fullName()
+ ", "
+ user.fullName()
+ ".");
sender.clear();
// Irrelevant reply, User and User2 are still in the attention set.
change(r).current().review(ReviewInput.approve());
assertThat(Iterables.getOnlyElement(sender.getMessages()).body())
.contains(
"Attention is currently required from: "
+ user2.fullName()
+ ", "
+ user.fullName()
+ ".");
assertThat(Iterables.getOnlyElement(sender.getMessages()).htmlBody())
.contains(
"Attention is currently required from: "
+ user2.fullName()
+ ", "
+ user.fullName()
+ ".");
sender.clear();
// Abandon the change which removes user from attention set; there is an email but without the
// attention footer.
change(r).abandon();
assertThat(Iterables.getOnlyElement(sender.getMessages()).body())
.doesNotContain("Attention is currently required");
assertThat(Iterables.getOnlyElement(sender.getMessages()).htmlBody())
.doesNotContain("Attention is currently required");
sender.clear();
}
@Test
@GerritConfig(name = "change.enableAttentionSet", value = "false")
public void noReferenceToAttentionSetInEmailsWhenDisabled() throws Exception {
PushOneCommit.Result r = createChange();
// Add user and to the attention set.
change(r).addReviewer(user.id().toString());
// Attention set is not referenced.
assertThat(Iterables.getOnlyElement(sender.getMessages()).body())
.doesNotContain("Attention is currently required");
assertThat(Iterables.getOnlyElement(sender.getMessages()).htmlBody())
.doesNotContain("Attention is currently required");
sender.clear();
}
@Test
public void attentionSetWithEmailFilter() throws Exception {
PushOneCommit.Result r = createChange();
// Add preference for the user such that they only receive an email on changes that require
// their attention.
requestScopeOperations.setApiUser(user.id());
GeneralPreferencesInfo prefs = gApi.accounts().self().getPreferences();
prefs.emailStrategy = EmailStrategy.ATTENTION_SET_ONLY;
gApi.accounts().self().setPreferences(prefs);
requestScopeOperations.setApiUser(admin.id());
// Add user to attention set. They receive an email since they are in the attention set.
change(r).addReviewer(user.id().toString());
assertThat(sender.getMessages()).isNotEmpty();
sender.clear();
// Irrelevant reply, User is still in the attention set, thus got another email.
change(r).current().review(ReviewInput.approve());
assertThat(sender.getMessages()).isNotEmpty();
sender.clear();
// Abandon the change which removes user from attention set; the user doesn't receive an email
// since they are not in the attention set.
change(r).abandon();
assertThat(sender.getMessages()).isEmpty();
}
@Test
public void attentionSetWithEmailFilterFiltersNewPatchsets() throws Exception {
PushOneCommit.Result r = createChange();
// Add preference for the user such that they only receive an email on changes that require
// their attention.
requestScopeOperations.setApiUser(user.id());
GeneralPreferencesInfo prefs = gApi.accounts().self().getPreferences();
prefs.emailStrategy = EmailStrategy.ATTENTION_SET_ONLY;
gApi.accounts().self().setPreferences(prefs);
requestScopeOperations.setApiUser(admin.id());
// Add user to reviewers but not to the attention set
change(r)
.current()
.review(
ReviewInput.create()
.reviewer(user.email())
.removeUserFromAttentionSet(user.email(), "reason"));
sender.clear();
// amending a change doesn't send an email when user is not in the attention set.
amendChange(r.getChangeId());
assertThat(sender.getMessages()).isEmpty();
}
@Test
public void attentionSetWithEmailFilterImpactingOnlyChangeEmails() throws Exception {
// Add preference for the user such that they only receive an email on changes that require
// their attention.
requestScopeOperations.setApiUser(user.id());
GeneralPreferencesInfo prefs = gApi.accounts().self().getPreferences();
prefs.emailStrategy = EmailStrategy.ATTENTION_SET_ONLY;
gApi.accounts().self().setPreferences(prefs);
requestScopeOperations.setApiUser(admin.id());
// Ensure emails that don't relate to changes are still sent.
gApi.accounts().id(user.id().get()).generateHttpPassword();
assertThat(sender.getMessages()).isNotEmpty();
}
private List<AttentionSetUpdate> getAttentionSetUpdatesForUser(
PushOneCommit.Result r, TestAccount account) {
return getAttentionSetUpdates(r.getChange().getId()).stream()
.filter(a -> a.account().equals(account.id()))
.collect(Collectors.toList());
}
private List<AttentionSetUpdate> getAttentionSetUpdates(Change.Id changeId) {
List<ChangeData> changeData = changeQueryProvider.get().byLegacyChangeId(changeId);
if (changeData.size() != 1) {
throw new IllegalStateException(
String.format("Not exactly one change found for ID %s.", changeId));
}
return new ArrayList<>(Iterables.getOnlyElement(changeData).attentionSet());
}
private ReviewInput reviewWithComment() {
return reviewInReplyToComment(null);
}
private ReviewInput reviewInReplyToComment(@Nullable String id) {
ReviewInput.CommentInput comment = new ReviewInput.CommentInput();
comment.side = Side.REVISION;
comment.path = Patch.COMMIT_MSG;
comment.message = "comment";
comment.updated = TimeUtil.nowTs();
comment.inReplyTo = id;
ReviewInput reviewInput = new ReviewInput();
reviewInput.comments = ImmutableMap.of(Patch.COMMIT_MSG, ImmutableList.of(comment));
return reviewInput;
}
private Correspondence<AttentionSetUpdate, Account.Id> hasAccount() {
return NullAwareCorrespondence.transforming(AttentionSetUpdate::account, "hasAccount");
}
}
|
Make test for attention set header deterministic
The order of appearance in the email headers for attention set is
non-deterministic, which is not a problem. The test should account for
it, though. It now accepts any order between user and user2.
Change-Id: I20f0d43efd8705117e5d05b09ff679f5d2763b57
|
javatests/com/google/gerrit/acceptance/rest/change/AttentionSetIT.java
|
Make test for attention set header deterministic
|
<ide><path>avatests/com/google/gerrit/acceptance/rest/change/AttentionSetIT.java
<ide> import java.util.List;
<ide> import java.util.concurrent.TimeUnit;
<ide> import java.util.function.LongSupplier;
<add>import java.util.regex.Pattern;
<ide> import java.util.stream.Collectors;
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide> public void attentionSetEmailHeader() throws Exception {
<ide> PushOneCommit.Result r = createChange();
<ide> TestAccount user2 = accountCreator.user2();
<add>
<add> // The pattern ensures the header mentions the attention set requirements in any order.
<add> Pattern attentionSetHeaderPattern =
<add> Pattern.compile(
<add> String.format(
<add> "Attention is currently required from: (%s|%s), (%s|%s).",
<add> user2.fullName(), user.fullName(), user.fullName(), user2.fullName()));
<ide> // Add user and user2 to the attention set.
<ide> change(r)
<ide> .current()
<ide> .review(
<ide> ReviewInput.create().reviewer(user.email()).reviewer(accountCreator.user2().email()));
<ide> assertThat(Iterables.getOnlyElement(sender.getMessages()).body())
<del> .contains(
<del> "Attention is currently required from: "
<del> + user2.fullName()
<del> + ", "
<del> + user.fullName()
<del> + ".");
<add> .containsMatch(attentionSetHeaderPattern);
<ide> assertThat(Iterables.getOnlyElement(sender.getMessages()).htmlBody())
<del> .contains(
<del> "Attention is currently required from: "
<del> + user2.fullName()
<del> + ", "
<del> + user.fullName()
<del> + ".");
<add> .containsMatch(attentionSetHeaderPattern);
<ide> sender.clear();
<ide>
<ide> // Irrelevant reply, User and User2 are still in the attention set.
<ide> change(r).current().review(ReviewInput.approve());
<ide> assertThat(Iterables.getOnlyElement(sender.getMessages()).body())
<del> .contains(
<del> "Attention is currently required from: "
<del> + user2.fullName()
<del> + ", "
<del> + user.fullName()
<del> + ".");
<add> .containsMatch(attentionSetHeaderPattern);
<ide> assertThat(Iterables.getOnlyElement(sender.getMessages()).htmlBody())
<del> .contains(
<del> "Attention is currently required from: "
<del> + user2.fullName()
<del> + ", "
<del> + user.fullName()
<del> + ".");
<add> .containsMatch(attentionSetHeaderPattern);
<ide> sender.clear();
<ide>
<ide> // Abandon the change which removes user from attention set; there is an email but without the
|
|
Java
|
apache-2.0
|
31799004e5ec882503038a3af984dddc6441fb31
| 0 |
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,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.parser.clause;
import com.google.common.base.Optional;
import io.shardingsphere.core.constant.AggregationType;
import io.shardingsphere.core.parsing.lexer.LexerEngine;
import io.shardingsphere.core.parsing.lexer.token.DefaultKeyword;
import io.shardingsphere.core.parsing.lexer.token.Keyword;
import io.shardingsphere.core.parsing.lexer.token.Symbol;
import io.shardingsphere.core.parsing.parser.clause.expression.AliasExpressionParser;
import io.shardingsphere.core.parsing.parser.context.selectitem.AggregationDistinctSelectItem;
import io.shardingsphere.core.parsing.parser.context.selectitem.AggregationSelectItem;
import io.shardingsphere.core.parsing.parser.context.selectitem.CommonSelectItem;
import io.shardingsphere.core.parsing.parser.context.selectitem.DistinctSelectItem;
import io.shardingsphere.core.parsing.parser.context.selectitem.SelectItem;
import io.shardingsphere.core.parsing.parser.context.selectitem.StarSelectItem;
import io.shardingsphere.core.parsing.parser.dialect.ExpressionParserFactory;
import io.shardingsphere.core.parsing.parser.sql.dql.select.SelectStatement;
import io.shardingsphere.core.parsing.parser.token.TableToken;
import io.shardingsphere.core.rule.ShardingRule;
import io.shardingsphere.core.util.SQLUtil;
import lombok.Getter;
import java.util.List;
import java.util.regex.Pattern;
/**
* Select list clause parser.
*
* @author zhangliang
*/
@Getter
public abstract class SelectListClauseParser implements SQLClauseParser {
private final ShardingRule shardingRule;
private final LexerEngine lexerEngine;
private final AliasExpressionParser aliasExpressionParser;
public SelectListClauseParser(final ShardingRule shardingRule, final LexerEngine lexerEngine) {
this.shardingRule = shardingRule;
this.lexerEngine = lexerEngine;
aliasExpressionParser = ExpressionParserFactory.createAliasExpressionParser(lexerEngine);
}
/**
* Parse select list.
*
* @param selectStatement select statement
* @param items select items
*/
public void parse(final SelectStatement selectStatement, final List<SelectItem> items) {
do {
selectStatement.getItems().add(parseSelectItem(selectStatement));
} while (lexerEngine.skipIfEqual(Symbol.COMMA));
selectStatement.setSelectListLastPosition(lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length());
items.addAll(selectStatement.getItems());
}
private SelectItem parseSelectItem(final SelectStatement selectStatement) {
lexerEngine.skipIfEqual(getSkippedKeywordsBeforeSelectItem());
SelectItem result;
if (isRowNumberSelectItem()) {
result = parseRowNumberSelectItem(selectStatement);
} else if (isDistinctSelectItem()) {
result = parseDistinctSelectItem();
} else if (isStarSelectItem()) {
selectStatement.setContainStar(true);
result = parseStarSelectItem();
} else if (isAggregationSelectItem()) {
result = parseAggregationSelectItem(selectStatement);
parseRestSelectItem(selectStatement);
} else {
result = parseCommonOrStarSelectItem(selectStatement);
}
return result;
}
protected abstract Keyword[] getSkippedKeywordsBeforeSelectItem();
protected abstract boolean isRowNumberSelectItem();
protected abstract SelectItem parseRowNumberSelectItem(SelectStatement selectStatement);
private boolean isDistinctSelectItem() {
return lexerEngine.equalAny(DefaultKeyword.DISTINCT);
}
private SelectItem parseDistinctSelectItem() {
lexerEngine.nextToken();
return new DistinctSelectItem("", aliasExpressionParser.parseSelectItemAlias());
}
private boolean isStarSelectItem() {
return Symbol.STAR.getLiterals().equals(SQLUtil.getExactlyValue(lexerEngine.getCurrentToken().getLiterals()));
}
private SelectItem parseStarSelectItem() {
lexerEngine.nextToken();
aliasExpressionParser.parseSelectItemAlias();
return new StarSelectItem(Optional.<String>absent());
}
private SelectItem parseStarSelectItem(final String owner) {
lexerEngine.nextToken();
aliasExpressionParser.parseSelectItemAlias();
return new StarSelectItem(Optional.fromNullable(owner));
}
private SelectItem parseCommonOrStarSelectItem(final SelectStatement selectStatement) {
String literals = lexerEngine.getCurrentToken().getLiterals();
int position = lexerEngine.getCurrentToken().getEndPosition() - literals.length();
StringBuilder result = new StringBuilder();
result.append(literals);
lexerEngine.nextToken();
if (lexerEngine.equalAny(Symbol.LEFT_PAREN)) {
result.append(lexerEngine.skipParentheses(selectStatement));
} else if (lexerEngine.equalAny(Symbol.DOT)) {
String tableName = SQLUtil.getExactlyValue(literals);
if (shardingRule.tryFindTableRuleByLogicTable(tableName).isPresent() || shardingRule.isBroadcastTable(tableName) || shardingRule.findBindingTableRule(tableName).isPresent()) {
selectStatement.addSQLToken(new TableToken(position, 0, literals));
}
result.append(lexerEngine.getCurrentToken().getLiterals());
lexerEngine.nextToken();
if (lexerEngine.equalAny(Symbol.STAR)) {
return parseStarSelectItem(literals);
}
result.append(lexerEngine.getCurrentToken().getLiterals());
lexerEngine.nextToken();
}
return new CommonSelectItem(SQLUtil.getExactlyValue(result
+ parseRestSelectItem(selectStatement)), aliasExpressionParser.parseSelectItemAlias());
}
private boolean isAggregationSelectItem() {
return lexerEngine.equalAny(DefaultKeyword.MAX, DefaultKeyword.MIN, DefaultKeyword.SUM, DefaultKeyword.AVG, DefaultKeyword.COUNT);
}
private SelectItem parseAggregationSelectItem(final SelectStatement selectStatement) {
AggregationType aggregationType = AggregationType.valueOf(lexerEngine.getCurrentToken().getLiterals().toUpperCase());
lexerEngine.nextToken();
String innerExpression = lexerEngine.skipParentheses(selectStatement);
return isAggregationDistinctSelectItem(innerExpression) ? new AggregationDistinctSelectItem(aggregationType, innerExpression, aliasExpressionParser.parseSelectItemAlias())
: new AggregationSelectItem(aggregationType, innerExpression, aliasExpressionParser.parseSelectItemAlias());
}
// TODO :panjuan does not use pattern to check
private boolean isAggregationDistinctSelectItem(final String innerExpression) {
String pattern = "(\\s*DISTINCT\\s+.*)";
return Pattern.matches(pattern, innerExpression.toUpperCase());
}
private String parseRestSelectItem(final SelectStatement selectStatement) {
StringBuilder result = new StringBuilder();
while (lexerEngine.equalAny(Symbol.getOperators())) {
result.append(lexerEngine.getCurrentToken().getLiterals());
lexerEngine.nextToken();
SelectItem selectItem = parseCommonOrStarSelectItem(selectStatement);
result.append(selectItem.getExpression());
}
return result.toString();
}
}
|
sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/SelectListClauseParser.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.parser.clause;
import com.google.common.base.Optional;
import io.shardingsphere.core.constant.AggregationType;
import io.shardingsphere.core.parsing.lexer.LexerEngine;
import io.shardingsphere.core.parsing.lexer.token.DefaultKeyword;
import io.shardingsphere.core.parsing.lexer.token.Keyword;
import io.shardingsphere.core.parsing.lexer.token.Symbol;
import io.shardingsphere.core.parsing.parser.clause.expression.AliasExpressionParser;
import io.shardingsphere.core.parsing.parser.context.selectitem.AggregationDistinctSelectItem;
import io.shardingsphere.core.parsing.parser.context.selectitem.AggregationSelectItem;
import io.shardingsphere.core.parsing.parser.context.selectitem.CommonSelectItem;
import io.shardingsphere.core.parsing.parser.context.selectitem.DistinctSelectItem;
import io.shardingsphere.core.parsing.parser.context.selectitem.SelectItem;
import io.shardingsphere.core.parsing.parser.context.selectitem.StarSelectItem;
import io.shardingsphere.core.parsing.parser.dialect.ExpressionParserFactory;
import io.shardingsphere.core.parsing.parser.sql.dql.select.SelectStatement;
import io.shardingsphere.core.parsing.parser.token.TableToken;
import io.shardingsphere.core.rule.ShardingRule;
import io.shardingsphere.core.util.SQLUtil;
import lombok.Getter;
import java.util.List;
import java.util.regex.Pattern;
/**
* Select list clause parser.
*
* @author zhangliang
*/
@Getter
public abstract class SelectListClauseParser implements SQLClauseParser {
private final ShardingRule shardingRule;
private final LexerEngine lexerEngine;
private final AliasExpressionParser aliasExpressionParser;
public SelectListClauseParser(final ShardingRule shardingRule, final LexerEngine lexerEngine) {
this.shardingRule = shardingRule;
this.lexerEngine = lexerEngine;
aliasExpressionParser = ExpressionParserFactory.createAliasExpressionParser(lexerEngine);
}
/**
* Parse select list.
*
* @param selectStatement select statement
* @param items select items
*/
public void parse(final SelectStatement selectStatement, final List<SelectItem> items) {
do {
selectStatement.getItems().add(parseSelectItem(selectStatement));
} while (lexerEngine.skipIfEqual(Symbol.COMMA));
selectStatement.setSelectListLastPosition(lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length());
items.addAll(selectStatement.getItems());
}
private SelectItem parseSelectItem(final SelectStatement selectStatement) {
lexerEngine.skipIfEqual(getSkippedKeywordsBeforeSelectItem());
SelectItem result;
if (isRowNumberSelectItem()) {
result = parseRowNumberSelectItem(selectStatement);
} else if (isDistinctSelectItem()) {
result = parseDistinctSelectItem();
} else if (isStarSelectItem()) {
selectStatement.setContainStar(true);
result = parseStarSelectItem();
} else if (isAggregationSelectItem()) {
result = parseAggregationSelectItem(selectStatement);
parseRestSelectItem(selectStatement);
} else {
result = parseCommonOrStarSelectItem(selectStatement);
}
return result;
}
protected abstract Keyword[] getSkippedKeywordsBeforeSelectItem();
protected abstract boolean isRowNumberSelectItem();
protected abstract SelectItem parseRowNumberSelectItem(SelectStatement selectStatement);
private boolean isDistinctSelectItem() {
return lexerEngine.equalAny(DefaultKeyword.DISTINCT);
}
private SelectItem parseDistinctSelectItem() {
lexerEngine.nextToken();
return new DistinctSelectItem("", aliasExpressionParser.parseSelectItemAlias());
}
private boolean isStarSelectItem() {
return Symbol.STAR.getLiterals().equals(SQLUtil.getExactlyValue(lexerEngine.getCurrentToken().getLiterals()));
}
private SelectItem parseStarSelectItem() {
lexerEngine.nextToken();
aliasExpressionParser.parseSelectItemAlias();
return new StarSelectItem(Optional.<String>absent());
}
private SelectItem parseStarSelectItem(final String owner) {
lexerEngine.nextToken();
aliasExpressionParser.parseSelectItemAlias();
return new StarSelectItem(Optional.fromNullable(owner));
}
private SelectItem parseCommonOrStarSelectItem(final SelectStatement selectStatement) {
String literals = lexerEngine.getCurrentToken().getLiterals();
int position = lexerEngine.getCurrentToken().getEndPosition() - literals.length();
StringBuilder result = new StringBuilder();
result.append(literals);
lexerEngine.nextToken();
if (lexerEngine.equalAny(Symbol.LEFT_PAREN)) {
result.append(lexerEngine.skipParentheses(selectStatement));
} else if (lexerEngine.equalAny(Symbol.DOT)) {
String tableName = SQLUtil.getExactlyValue(literals);
if (shardingRule.tryFindTableRuleByLogicTable(tableName).isPresent() || shardingRule.isBroadcastTable(tableName) || shardingRule.findBindingTableRule(tableName).isPresent()) {
selectStatement.addSQLToken(new TableToken(position, 0, literals));
}
result.append(lexerEngine.getCurrentToken().getLiterals());
lexerEngine.nextToken();
if (lexerEngine.equalAny(Symbol.STAR)) {
return parseStarSelectItem(literals);
}
result.append(lexerEngine.getCurrentToken().getLiterals());
lexerEngine.nextToken();
}
return new CommonSelectItem(SQLUtil.getExactlyValue(result
+ parseRestSelectItem(selectStatement)), aliasExpressionParser.parseSelectItemAlias());
}
private boolean isAggregationSelectItem() {
return lexerEngine.equalAny(DefaultKeyword.MAX, DefaultKeyword.MIN, DefaultKeyword.SUM, DefaultKeyword.AVG, DefaultKeyword.COUNT);
}
private SelectItem parseAggregationSelectItem(final SelectStatement selectStatement) {
AggregationType aggregationType = AggregationType.valueOf(lexerEngine.getCurrentToken().getLiterals().toUpperCase());
lexerEngine.nextToken();
String innerExpression = lexerEngine.skipParentheses(selectStatement);
return isAggregationDistinctSelectItem(innerExpression) ? new AggregationDistinctSelectItem(aggregationType, innerExpression, aliasExpressionParser.parseSelectItemAlias()) : new AggregationSelectItem(aggregationType, innerExpression, aliasExpressionParser.parseSelectItemAlias());
}
private boolean isAggregationDistinctSelectItem(final String innerExpression) {
String pattern = "(\\s*DISTINCT\\s+.*)";
return Pattern.matches(pattern, innerExpression.toUpperCase());
}
private String parseRestSelectItem(final SelectStatement selectStatement) {
StringBuilder result = new StringBuilder();
while (lexerEngine.equalAny(Symbol.getOperators())) {
result.append(lexerEngine.getCurrentToken().getLiterals());
lexerEngine.nextToken();
SelectItem selectItem = parseCommonOrStarSelectItem(selectStatement);
result.append(selectItem.getExpression());
}
return result.toString();
}
}
|
add todo
|
sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/SelectListClauseParser.java
|
add todo
|
<ide><path>harding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/SelectListClauseParser.java
<ide> AggregationType aggregationType = AggregationType.valueOf(lexerEngine.getCurrentToken().getLiterals().toUpperCase());
<ide> lexerEngine.nextToken();
<ide> String innerExpression = lexerEngine.skipParentheses(selectStatement);
<del> return isAggregationDistinctSelectItem(innerExpression) ? new AggregationDistinctSelectItem(aggregationType, innerExpression, aliasExpressionParser.parseSelectItemAlias()) : new AggregationSelectItem(aggregationType, innerExpression, aliasExpressionParser.parseSelectItemAlias());
<add> return isAggregationDistinctSelectItem(innerExpression) ? new AggregationDistinctSelectItem(aggregationType, innerExpression, aliasExpressionParser.parseSelectItemAlias())
<add> : new AggregationSelectItem(aggregationType, innerExpression, aliasExpressionParser.parseSelectItemAlias());
<ide> }
<ide>
<add> // TODO :panjuan does not use pattern to check
<ide> private boolean isAggregationDistinctSelectItem(final String innerExpression) {
<ide> String pattern = "(\\s*DISTINCT\\s+.*)";
<ide> return Pattern.matches(pattern, innerExpression.toUpperCase());
|
|
Java
|
mit
|
0145641855bed65bab8d3370a17db64acc5f0971
| 0 |
Lunatrius/Stackie
|
package lunatrius.stackie;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.TickType;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
import cpw.mods.fml.common.event.FMLServerStoppingEvent;
import cpw.mods.fml.common.registry.TickRegistry;
import cpw.mods.fml.relauncher.ReflectionHelper;
import cpw.mods.fml.relauncher.Side;
import lunatrius.stackie.util.Config;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.item.EntityXPOrb;
import net.minecraft.item.ItemStack;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.Configuration;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
@Mod(modid = "Stackie")
public class Stackie {
@Instance("Stackie")
public static Stackie instance;
// loaded from config
private int interval = 20;
private float distance = 0.75f;
private boolean stackItems = true;
private boolean stackExperience = true;
private Field xpValue = null;
private MinecraftServer server = null;
private int ticks = -1;
@EventHandler
public void preInit(FMLPreInitializationEvent event) {
Configuration config = new Configuration(event.getSuggestedConfigurationFile());
config.load();
this.interval = Config.getInt(config, Configuration.CATEGORY_GENERAL, "interval", this.interval, 5, 500, "Amount of ticks (20 ticks => 1 second) that will pass between each stacking attempt.");
this.distance = (float) Config.getDouble(config, Configuration.CATEGORY_GENERAL, "distance", this.distance, 0.01, 10, "Maximum distance between items that can be still stacked (relative to block size).");
this.stackItems = Config.getBoolean(config, Configuration.CATEGORY_GENERAL, "stackItems", this.stackItems, "Should it stack items?");
this.stackExperience = Config.getBoolean(config, Configuration.CATEGORY_GENERAL, "stackExperience", this.stackExperience, "Should it stack experience orbs?");
config.save();
try {
this.xpValue = ReflectionHelper.findField(EntityXPOrb.class, "e", "field_70530_e", "xpValue");
} catch (Exception e) {
e.printStackTrace();
}
}
@EventHandler
public void init(FMLInitializationEvent event) {
// register a new ticker with normal server ticks
TickRegistry.registerTickHandler(new Ticker(EnumSet.of(TickType.SERVER)), Side.SERVER);
}
@EventHandler
public void serverStarting(FMLServerStartingEvent event) {
this.server = event.getServer();
}
@EventHandler
public void serverStopping(FMLServerStoppingEvent event) {
this.server = null;
}
public boolean onTick(TickType tickType, boolean start) {
// skip starting ticks
if (start) {
return true;
}
// decrease the amount of ticks left; if there are less than 0 ticks left and the world is local stack the entities
if (--this.ticks < 0 && this.server != null && this.server.worldServers != null) {
// stack entities
stackEntities(this.server.worldServers);
// set a new timeout
this.ticks = this.interval;
}
return true;
}
@SuppressWarnings("null")
public void stackEntities(WorldServer[] theWorldServer) {
// loop through all worlds
for (WorldServer world : theWorldServer) {
// create a new array list
List<Entity> entityList = new ArrayList<Entity>();
// save all valid entities to the the previous list
for (int i = 0; i < world.loadedEntityList.size(); i++) {
if (getType((Entity) world.loadedEntityList.get(i)) != -1) {
entityList.add((Entity) world.loadedEntityList.get(i));
}
}
int mcType = -1;
Entity mcEntity = null;
EntityItem mcEntityItem = null;
ItemStack mcItemStack = null;
EntityXPOrb mcEntityXPOrb = null;
double mcWeight = -1;
int localType = -1;
Entity localEntity = null;
EntityItem localEntityItem = null;
ItemStack localItemStack = null;
EntityXPOrb localEntityXPOrb = null;
double localWeight = -1;
boolean merged = false;
double totalWeight = -1;
try {
for (int i = 0; i < entityList.size() - 1; i++) {
// if the entity is dead skip it
mcEntity = entityList.get(i);
if (mcEntity.isDead) {
continue;
}
// get entity's type
mcType = getType(mcEntity);
switch (mcType) {
// EntityItem
case 0:
mcEntityItem = (EntityItem) mcEntity;
mcItemStack = mcEntityItem.getEntityItem();
// if the entity is not stackable or the stack size is 0 or less skip it
if (mcItemStack == null || !mcItemStack.isStackable() || mcItemStack.stackSize <= 0) {
continue;
}
break;
// EntityXPOrb
case 1:
mcEntityXPOrb = (EntityXPOrb) mcEntity;
break;
}
for (int j = i + 1; j < entityList.size(); j++) {
// if the entity is dead skip it
localEntity = entityList.get(j);
if (localEntity.isDead) {
continue;
}
// get entity's type
localType = getType(localEntity);
// entity types match
if (mcType == localType) {
// if positions differ skip it
if (!isEqualPosition(mcEntity, localEntity)) {
continue;
}
// reset the merged flag
merged = false;
switch (mcType) {
// EntityItem
case 0:
localEntityItem = (EntityItem) localEntity;
localItemStack = localEntityItem.getEntityItem();
// if item ID aren't equal, items have a tag compound, position differs or the damage isn't equal skip it
if (localItemStack == null) {
continue;
} else if (mcItemStack.itemID != localItemStack.itemID) {
continue;
} else if (mcItemStack.stackTagCompound != null || localItemStack.stackTagCompound != null) {
continue;
} else if (mcItemStack.getItemDamage() != localItemStack.getItemDamage()) {
continue;
}
mcWeight = mcItemStack.stackSize;
localWeight = localItemStack.stackSize;
// move the items from one stack to the other
int itemsIn = Math.min(2048 - mcItemStack.stackSize, localItemStack.stackSize);
mcItemStack.stackSize += itemsIn;
localItemStack.stackSize -= itemsIn;
// set the new item stacks
mcEntityItem.setEntityItemStack(mcItemStack);
localEntityItem.setEntityItemStack(localItemStack);
// the new stack's age is the lowest age of both stacks
mcEntityItem.age = Math.min(mcEntityItem.age, localEntityItem.age);
// if the stack size is bellow or equal to 0 the entities have merged
if (localItemStack.stackSize <= 0) {
merged = true;
}
break;
// EntityXPOrb
case 1:
localEntityXPOrb = (EntityXPOrb) localEntity;
try {
mcWeight = mcEntityXPOrb.getXpValue();
localWeight = localEntityXPOrb.getXpValue();
// set the new experience values
this.xpValue.setInt(mcEntityXPOrb, mcEntityXPOrb.getXpValue() + localEntityXPOrb.getXpValue());
this.xpValue.setInt(localEntityXPOrb, 0);
// the new orb's age is the lowest age of both orbs
mcEntityXPOrb.xpOrbAge = Math.min(mcEntityXPOrb.xpOrbAge, localEntityXPOrb.xpOrbAge);
// the entities have been merged
merged = true;
} catch (Exception ex) {
ex.printStackTrace();
}
break;
}
if (merged) {
// the entity is dead
localEntity.setDead();
// sum up the weights
totalWeight = mcWeight + localWeight;
// set the new weights
mcWeight /= totalWeight;
localWeight /= totalWeight;
// set the new position to the average of the merged entities
mcEntity.setPosition(mcEntity.posX * mcWeight + localEntity.posX * localWeight, mcEntity.posY * mcWeight + localEntity.posY * localWeight, mcEntity.posZ * mcWeight + localEntity.posZ * localWeight);
// set the new velocity to the average of the merged entities
mcEntity.motionX = mcEntity.motionX * mcWeight + localEntity.motionX * localWeight;
mcEntity.motionY = mcEntity.motionY * mcWeight + localEntity.motionY * localWeight;
mcEntity.motionZ = mcEntity.motionZ * mcWeight + localEntity.motionZ * localWeight;
}
}
}
}
} catch (Exception e) {
}
}
}
private int getType(Entity entity) {
if (entity instanceof EntityItem) {
return 0;
} else if (entity instanceof EntityXPOrb && this.xpValue != null) {
return 1;
}
return -1;
}
private boolean isEqualPosition(Entity a, Entity b) {
return isEqual(a.posX, b.posX) && isEqual(a.posY, b.posY) && isEqual(a.posZ, b.posZ);
}
private boolean isEqual(double a, double b) {
return isEqual(a, b, this.distance);
}
private boolean isEqual(double a, double b, double epsilon) {
return Math.abs(a - b) < epsilon;
}
}
|
minecraft/lunatrius/stackie/Stackie.java
|
package lunatrius.stackie;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.TickType;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
import cpw.mods.fml.common.event.FMLServerStoppingEvent;
import cpw.mods.fml.common.registry.TickRegistry;
import cpw.mods.fml.relauncher.ReflectionHelper;
import cpw.mods.fml.relauncher.Side;
import lunatrius.stackie.util.Config;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.item.EntityXPOrb;
import net.minecraft.item.ItemStack;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.Configuration;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
@Mod(modid = "Stackie")
public class Stackie {
@Instance("Stackie")
public static Stackie instance;
// loaded from config
private int interval = 20;
private float distance = 0.75f;
private boolean stackItems = true;
private boolean stackExperience = true;
private Field xpValue = null;
private MinecraftServer server = null;
private int ticks = -1;
@EventHandler
public void preInit(FMLPreInitializationEvent event) {
Configuration config = new Configuration(event.getSuggestedConfigurationFile());
config.load();
this.interval = Config.getInt(config, Configuration.CATEGORY_GENERAL, "interval", this.interval, 5, 500, "Amount of ticks (20 ticks => 1 second) that will pass between each stacking attempt.");
this.distance = (float) Config.getDouble(config, Configuration.CATEGORY_GENERAL, "distance", this.distance, 0.01, 10, "Maximum distance between items that can be still stacked (relative to block size).");
this.stackItems = Config.getBoolean(config, Configuration.CATEGORY_GENERAL, "stackItems", this.stackItems, "Should it stack items?");
this.stackExperience = Config.getBoolean(config, Configuration.CATEGORY_GENERAL, "stackExperience", this.stackExperience, "Should it stack experience orbs?");
config.save();
try {
this.xpValue = ReflectionHelper.findField(EntityXPOrb.class, "e", "field_70530_e", "xpValue");
} catch (Exception e) {
e.printStackTrace();
}
}
@EventHandler
public void init(FMLInitializationEvent event) {
// register a new ticker with normal server ticks
TickRegistry.registerTickHandler(new Ticker(EnumSet.of(TickType.SERVER)), Side.SERVER);
}
@EventHandler
public void serverStarting(FMLServerStartingEvent event) {
this.server = event.getServer();
}
@EventHandler
public void serverStopping(FMLServerStoppingEvent event) {
this.server = null;
}
public boolean onTick(TickType tickType, boolean start) {
// skip starting ticks
if (start) {
return true;
}
// decrease the amount of ticks left; if there are less than 0 ticks left and the world is local stack the entities
if (--this.ticks < 0 && this.server != null && this.server.worldServers != null) {
// stack entities
stackEntities(this.server.worldServers);
// set a new timeout
this.ticks = this.interval;
}
return true;
}
@SuppressWarnings("null")
public void stackEntities(WorldServer[] theWorldServer) {
// loop through all worlds
for (WorldServer world : theWorldServer) {
// create a new array list
List<Entity> entityList = new ArrayList<Entity>();
// save all valid entities to the the previous list
for (int i = 0; i < world.loadedEntityList.size(); i++) {
if (getType((Entity) world.loadedEntityList.get(i)) != -1) {
entityList.add((Entity) world.loadedEntityList.get(i));
}
}
int mcType = -1;
Entity mcEntity = null;
EntityItem mcEntityItem = null;
ItemStack mcItemStack = null;
EntityXPOrb mcEntityXPOrb = null;
double mcWeight = -1;
int localType = -1;
Entity localEntity = null;
EntityItem localEntityItem = null;
ItemStack localItemStack = null;
EntityXPOrb localEntityXPOrb = null;
double localWeight = -1;
boolean merged = false;
double totalWeight = -1;
try {
for (int i = 0; i < entityList.size() - 1; i++) {
// if the entity is dead skip it
mcEntity = entityList.get(i);
if (mcEntity.isDead) {
continue;
}
// get entity's type
mcType = getType(mcEntity);
switch (mcType) {
// EntityItem
case 0:
mcEntityItem = (EntityItem) mcEntity;
mcItemStack = mcEntityItem.getEntityItem();
// if the entity is not stackable or the stack size is 0 or less skip it
if (mcItemStack == null || !mcItemStack.isStackable() || mcItemStack.stackSize <= 0) {
continue;
}
break;
// EntityXPOrb
case 1:
mcEntityXPOrb = (EntityXPOrb) mcEntity;
break;
}
for (int j = i + 1; j < entityList.size(); j++) {
// if the entity is dead skip it
localEntity = entityList.get(j);
if (localEntity.isDead) {
continue;
}
// get entity's type
localType = getType(localEntity);
// entity types match
if (mcType == localType) {
// if positions differ skip it
if (!isEqualPosition(mcEntity, localEntity)) {
continue;
}
// reset the merged flag
merged = false;
switch (mcType) {
// EntityItem
case 0:
localEntityItem = (EntityItem) localEntity;
localItemStack = localEntityItem.getEntityItem();
// if item ID aren't equal, items have a tag compound, position differs or the damage isn't equal skip it
if (localItemStack == null) {
continue;
} else if (mcItemStack.itemID != localItemStack.itemID) {
continue;
} else if (mcItemStack.stackTagCompound != null || localItemStack.stackTagCompound != null) {
continue;
} else if (mcItemStack.getItemDamage() != localItemStack.getItemDamage()) {
continue;
}
mcWeight = mcItemStack.stackSize;
localWeight = localItemStack.stackSize;
// move the items from one stack to the other
int itemsIn = Math.min(2048 - mcItemStack.stackSize, localItemStack.stackSize);
mcItemStack.stackSize += itemsIn;
localItemStack.stackSize -= itemsIn;
// set the new item stacks
mcEntityItem.setEntityItemStack(mcItemStack);
localEntityItem.setEntityItemStack(localItemStack);
// the new stack's age is the lowest age of both stacks
mcEntityItem.age = Math.min(mcEntityItem.age, localEntityItem.age);
// if the stack size is bellow or equal to 0 the entities have merged
if (localItemStack.stackSize <= 0) {
merged = true;
}
break;
// EntityXPOrb
case 1:
localEntityXPOrb = (EntityXPOrb) localEntity;
try {
mcWeight = mcEntityXPOrb.getXpValue();
localWeight = localEntityXPOrb.getXpValue();
// set the new experience values
this.xpValue.setInt(mcEntityXPOrb, mcEntityXPOrb.getXpValue() + localEntityXPOrb.getXpValue());
this.xpValue.setInt(localEntityXPOrb, 0);
// the new orb's age is the lowest age of both orbs
mcEntityXPOrb.xpOrbAge = Math.min(mcEntityXPOrb.xpOrbAge, localEntityXPOrb.xpOrbAge);
// the entities have been merged
merged = true;
} catch (Exception ex) {
ex.printStackTrace();
}
break;
}
if (merged) {
// the entity is dead
localEntity.setDead();
// sum up the weights
totalWeight = mcWeight + localWeight;
// set the new weights
mcWeight /= totalWeight;
localWeight /= totalWeight;
// set the new position to the average of the merged entities
mcEntity.setPosition(mcEntity.posX * mcWeight + localEntity.posX * localWeight, mcEntity.posY * mcWeight + localEntity.posY * localWeight, mcEntity.posZ * mcWeight + localEntity.posZ * localWeight);
// set the new velocity to the average of the merged entities
mcEntity.setVelocity(mcEntity.motionX * mcWeight + localEntity.motionX * localWeight, mcEntity.motionY * mcWeight + localEntity.motionY * localWeight, mcEntity.motionZ * mcWeight + localEntity.motionZ * localWeight);
}
}
}
}
} catch (Exception e) {
}
}
}
private int getType(Entity entity) {
if (entity instanceof EntityItem) {
return 0;
} else if (entity instanceof EntityXPOrb && this.xpValue != null) {
return 1;
}
return -1;
}
private boolean isEqualPosition(Entity a, Entity b) {
return isEqual(a.posX, b.posX) && isEqual(a.posY, b.posY) && isEqual(a.posZ, b.posZ);
}
private boolean isEqual(double a, double b) {
return isEqual(a, b, this.distance);
}
private boolean isEqual(double a, double b, double epsilon) {
return Math.abs(a - b) < epsilon;
}
}
|
Entity.setVelocity is client side only...
|
minecraft/lunatrius/stackie/Stackie.java
|
Entity.setVelocity is client side only...
|
<ide><path>inecraft/lunatrius/stackie/Stackie.java
<ide> mcEntity.setPosition(mcEntity.posX * mcWeight + localEntity.posX * localWeight, mcEntity.posY * mcWeight + localEntity.posY * localWeight, mcEntity.posZ * mcWeight + localEntity.posZ * localWeight);
<ide>
<ide> // set the new velocity to the average of the merged entities
<del> mcEntity.setVelocity(mcEntity.motionX * mcWeight + localEntity.motionX * localWeight, mcEntity.motionY * mcWeight + localEntity.motionY * localWeight, mcEntity.motionZ * mcWeight + localEntity.motionZ * localWeight);
<add> mcEntity.motionX = mcEntity.motionX * mcWeight + localEntity.motionX * localWeight;
<add> mcEntity.motionY = mcEntity.motionY * mcWeight + localEntity.motionY * localWeight;
<add> mcEntity.motionZ = mcEntity.motionZ * mcWeight + localEntity.motionZ * localWeight;
<ide> }
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
9881dce56b8e574628bf107a7d337c702021147d
| 0 |
djkazic/XNet
|
package gui;
import gui.render.ProgressCellRenderer;
import gui.render.TableModelDL;
import gui.render.TableModelSpec;
import java.awt.Font;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.CountDownLatch;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import main.Core;
import main.Settings;
import main.Utils;
import blocks.BlockedFile;
import javax.swing.JTabbedPane;
@SuppressWarnings("serial")
public class MainWindow extends JFrame {
protected JPanel contentPane;
public JTextField searchInput;
protected JTable searchRes;
protected JTable downloadList;
public DefaultTableModel tableModel;
public DefaultTableModel libraryModel;
public DefaultTableModel downloadModel;
protected DefaultTableCellRenderer betterRenderer;
protected CountDownLatch resLatch;
public CountDownLatch debugLatch;
protected JScrollPane searchResScrollPane;
protected JScrollPane downloadScrollPane;
protected JSeparator separator;
protected JLabel lblPeers;
public String debugHost;
protected JMenuItem mntmAbout;
protected JMenuBar menuBar;
protected JMenu mnFile;
private JPopupMenu downloadPopupMenu;
protected boolean searchMode;
private JMenuItem downloadPopupMenuRemoveFromList;
private JTabbedPane tabbedPane;
private JScrollPane libraryScrollPane;
private JTable libraryTable;
/**
* Create the frame.
*/
public MainWindow() {
setResizable(false);
searchMode = false;
setTitle("XNet v" + Settings.version);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 550, 570);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
//Set title icon
try {
Image iconImage = ImageIO.read(getClass().getResourceAsStream("/res/imgres/titleicon.png"));
setIconImage(iconImage);
} catch (IOException e) {
e.printStackTrace();
}
tableModel = new TableModelSpec();
tableModel.addColumn("Status");
downloadModel = new TableModelDL();
downloadModel.addColumn("Filename");
downloadModel.addColumn("Progress");
libraryModel = new DefaultTableModel();
libraryModel.addColumn("Filename");
libraryModel.addColumn("Size");
libraryModel.addColumn("Date");
libraryModel.addRow(new String[]{"Not yet implemented, feature coming soon!"});
resLatch = new CountDownLatch(1);
searchInput = new JTextField();
searchInput.setBounds(8, 39, 516, 25);
searchInput.setColumns(10);
searchInput.setFocusable(false);
searchInput.setEditable(false);
contentPane.add(searchInput);
contentPane.setLayout(null);
menuBar = new JMenuBar();
menuBar.setBounds(0, -4, 546, 30);
contentPane.add(menuBar);
mnFile = new JMenu("Help");
menuBar.add(mnFile);
mntmAbout = new JMenuItem("About");
try {
ImageIcon imageIcon = new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/res/imgres/glasses.png")));
mntmAbout.setIcon(imageIcon);
} catch (IOException e) {
e.printStackTrace();
}
mntmAbout.setHorizontalAlignment(SwingConstants.LEFT);
mnFile.add(mntmAbout);
downloadScrollPane = new JScrollPane();
downloadScrollPane.setBounds(6, 346, 520, 149);
contentPane.add(downloadScrollPane);
separator = new JSeparator();
separator.setBounds(0, 507, 532, 2);
contentPane.add(separator);
lblPeers = new JLabel("");
lblPeers.setToolTipText("[0|0]");
lblPeers.setIcon(new ImageIcon(MainWindow.class.getResource("/res/imgres/0bars.png")));
lblPeers.setBounds(508, 515, 24, 24);
lblPeers.setFont(new Font("Tahoma", Font.PLAIN, 11));
contentPane.add(lblPeers);
betterRenderer = new DefaultTableCellRenderer();
betterRenderer.setHorizontalAlignment(SwingConstants.CENTER);
downloadPopupMenu = new JPopupMenu();
downloadPopupMenuRemoveFromList = new JMenuItem("Remove from list");
downloadPopupMenu.add(downloadPopupMenuRemoveFromList);
downloadList = new JTable(downloadModel);
downloadList.getColumnModel().getColumn(0).setCellRenderer(betterRenderer);
downloadList.getColumnModel().getColumn(1).setCellRenderer(betterRenderer);
downloadList.getTableHeader().setReorderingAllowed(false);
downloadList.getTableHeader().setResizingAllowed(false);
downloadScrollPane.setViewportView(downloadList);
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(6, 75, 520, 260);
contentPane.add(tabbedPane);
searchResScrollPane = new JScrollPane();
tabbedPane.addTab("Search", null, searchResScrollPane, null);
searchRes = new JTable(tableModel);
searchRes.setDefaultRenderer(Object.class, betterRenderer);
//.getColumn(0).setCellRenderer(betterRenderer);
searchRes.getTableHeader().setReorderingAllowed(false);
searchRes.getTableHeader().setResizingAllowed(false);
searchResScrollPane.setViewportView(searchRes);
searchRes.setCellSelectionEnabled(true);
searchRes.setColumnSelectionAllowed(true);
libraryScrollPane = new JScrollPane();
tabbedPane.addTab("Library", null, libraryScrollPane, null);
libraryTable = new JTable(libraryModel);
libraryTable.getColumnModel().getColumn(0).setPreferredWidth(300);
libraryScrollPane.setViewportView(libraryTable);
}
public void registerListeners() {
downloadPopupMenuRemoveFromList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int[] selectedRows = downloadList.getSelectedRows();
for(Integer i : selectedRows) {
downloadModel.removeRow(i);
}
}
});
downloadList.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent arg0) {
if(arg0.isPopupTrigger()) {
Point clickPoint = arg0.getPoint();
int tableRow = downloadList.rowAtPoint(clickPoint);
if(!downloadList.isRowSelected(tableRow)) {
downloadList.changeSelection(tableRow, 0, false, false);
}
downloadPopupMenu.show(arg0.getComponent(), arg0.getX(), arg0.getY());
}
}
});
mntmAbout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
aboutWindow();
}
});
searchInput.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent arg0) {
int key = arg0.getKeyCode();
if(key == KeyEvent.VK_ENTER) {
//clear any previous res
clearTable();
//clear core index
Core.index.clear();
if(Core.debugServer) {
debugHost = searchInput.getText();
if(debugHost.equals("")) {
out("You cannot enter a blank IP.");
} else {
out("Debug host set!");
debugLatch.countDown();
}
Core.debugServer = false;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Core.mainWindow.resetTable();
} else {
if(Core.peerList.size() == 0) {
out("No peers connected. Query is not possible.");
} else {
String input = searchInput.getText();
if(input.equals("")) {
out("You cannot search for a blank query.");
} else if(input.length() < 3) {
out("You cannot search for a query shorter than 3 characters.");
} else {
if(!searchMode) {
removeColumnAndData(searchRes, 0);
tableModel.addColumn("Filename");
tableModel.addColumn("Checksum");
searchMode = true;
}
Utils.doSearch(input);
}
//dump results
}
}
searchInput.setText("");
}
}
});
searchRes.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
if(searchMode) {
Point clickPoint = arg0.getPoint();
int tableRow = searchRes.rowAtPoint(clickPoint);
if(arg0.getClickCount() == 2) {
String fileName = (String) tableModel.getValueAt(tableRow, 0);
String blockListStr = (String) tableModel.getValueAt(tableRow, 1);
@SuppressWarnings("rawtypes")
Iterator it = Core.index.entrySet().iterator();
//Iterate through HashMap until a match by blockListStr is found
while(it.hasNext()) {
@SuppressWarnings("rawtypes")
Map.Entry pairs = (Map.Entry) it.next();
//TODO: use HashMap to contact known peers first
//Peer mapPeer = (Peer) pairs.getKey();
@SuppressWarnings("unchecked")
ArrayList<String> blockList = (ArrayList<String>) pairs.getValue();
//Check to see if the HashMap's matching is accurate
if(blockList.toString().equals(blockListStr)) {
BlockedFile bf;
//Check if this BlockedFile exists
if(Utils.getBlockedFileByBlockList(blockList) != null) {
bf = Utils.getBlockedFileByBlockList(blockList);
System.out.println(bf.getName());
} else {
//If not, create a new BlockedFile instance
bf = new BlockedFile(fileName, blockList);
}
int numRows = downloadModel.getRowCount();
boolean alreadyDoneInPane = false;
for(int i = 0; i < numRows; i++) {
if(downloadModel.getValueAt(i, 0).equals(bf.getName())) {
if(downloadModel.getValueAt(i, 1).equals("100%")) {
alreadyDoneInPane = true;
break;
}
}
}
if(!alreadyDoneInPane) {
downloadModel.addRow(new String[]{bf.getName(), "0%"});
downloadList.getColumnModel().getColumn(1).setCellRenderer(new ProgressCellRenderer());
bf.download();
}
Core.mainWindow.resetTable();
}
it.remove();
}
}
}
}
});
resLatch.countDown();
setVisible(true);
}
public void out(String str) {
try {
resLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
if(searchMode) {
removeColumnAndData(searchRes, 1);
removeColumnAndData(searchRes, 0);
tableModel.addColumn("Status");
searchMode = false;
}
clearTable();
tableModel.addRow(new String[]{str});
}
public void clearTable() {
for(int i=0; i < tableModel.getRowCount(); i++) {
tableModel.removeRow(i);
}
}
public void removeColumnAndData(JTable table, int vColIndex) {
TableModelSpec model = (TableModelSpec)table.getModel();
TableColumn col = table.getColumnModel().getColumn(vColIndex);
int columnModelIndex = col.getModelIndex();
Vector<?> data = model.getDataVector();
Vector<?> colIds = model.getColumnIdentifiers();
table.removeColumn(col);
colIds.removeElementAt(columnModelIndex);
for (int r=0; r<data.size(); r++) {
Vector<?> row = (Vector<?>)data.get(r);
row.removeElementAt(columnModelIndex);
}
model.setDataVector(data, colIds);
Enumeration<?> enumer = table.getColumnModel().getColumns();
for(;enumer.hasMoreElements();) {
TableColumn c = (TableColumn)enumer.nextElement();
if (c.getModelIndex() >= columnModelIndex) {
c.setModelIndex(c.getModelIndex()-1);
}
}
model.fireTableStructureChanged();
}
public void updatePeerCount() {
String peers = Utils.peersCount();
lblPeers.setIcon(new ImageIcon(MainWindow.class.getResource("/res/imgres/" + peers + ".png")));
lblPeers.setToolTipText(Utils.peerToolTip());
}
public void updateProgress(String forFile, String progress) {
int rowCount = downloadModel.getRowCount();
for(int i=0; i < rowCount; i++) {
if(downloadModel.getValueAt(i, 0).equals(forFile)) {
downloadModel.setValueAt(progress, i, 1);
}
}
}
public void setDebugLatch(CountDownLatch debugLatch) {
this.debugLatch = debugLatch;
}
public void aboutWindow() {
new AboutWindow();
}
public void resetTable() {
Core.mainWindow.out("Enter your search query and press Enter.");
}
}
|
src/gui/MainWindow.java
|
package gui;
import gui.render.ProgressCellRenderer;
import gui.render.TableModelDL;
import gui.render.TableModelSpec;
import java.awt.Font;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.CountDownLatch;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import main.Core;
import main.Settings;
import main.Utils;
import blocks.BlockedFile;
import javax.swing.JTabbedPane;
@SuppressWarnings("serial")
public class MainWindow extends JFrame {
protected JPanel contentPane;
public JTextField searchInput;
protected JTable searchRes;
protected JTable downloadList;
public DefaultTableModel tableModel;
public DefaultTableModel downloadModel;
protected DefaultTableCellRenderer betterRenderer;
protected CountDownLatch resLatch;
public CountDownLatch debugLatch;
protected JScrollPane searchResScrollPane;
protected JScrollPane downloadScrollPane;
protected JSeparator separator;
protected JLabel lblPeers;
public String debugHost;
protected JMenuItem mntmAbout;
protected JMenuBar menuBar;
protected JMenu mnFile;
private JPopupMenu downloadPopupMenu;
protected boolean searchMode;
private JMenuItem downloadPopupMenuRemoveFromList;
private JTabbedPane tabbedPane;
private JScrollPane libraryScrollPane;
private JTable libraryTable;
/**
* Create the frame.
*/
public MainWindow() {
setResizable(false);
searchMode = false;
setTitle("XNet v" + Settings.version);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 550, 570);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
//Set title icon
try {
Image iconImage = ImageIO.read(getClass().getResourceAsStream("/res/imgres/titleicon.png"));
setIconImage(iconImage);
} catch (IOException e) {
e.printStackTrace();
}
tableModel = new TableModelSpec();
tableModel.addColumn("Status");
downloadModel = new TableModelDL();
downloadModel.addColumn("Filename");
downloadModel.addColumn("Progress");
resLatch = new CountDownLatch(1);
searchInput = new JTextField();
searchInput.setBounds(8, 39, 516, 25);
searchInput.setColumns(10);
searchInput.setFocusable(false);
searchInput.setEditable(false);
contentPane.add(searchInput);
contentPane.setLayout(null);
menuBar = new JMenuBar();
menuBar.setBounds(0, -4, 546, 30);
contentPane.add(menuBar);
mnFile = new JMenu("Help");
menuBar.add(mnFile);
mntmAbout = new JMenuItem("About");
try {
ImageIcon imageIcon = new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/res/imgres/glasses.png")));
mntmAbout.setIcon(imageIcon);
} catch (IOException e) {
e.printStackTrace();
}
mntmAbout.setHorizontalAlignment(SwingConstants.LEFT);
mnFile.add(mntmAbout);
downloadScrollPane = new JScrollPane();
downloadScrollPane.setBounds(6, 346, 520, 149);
contentPane.add(downloadScrollPane);
separator = new JSeparator();
separator.setBounds(0, 507, 532, 2);
contentPane.add(separator);
lblPeers = new JLabel("");
lblPeers.setToolTipText("[0|0]");
lblPeers.setIcon(new ImageIcon(MainWindow.class.getResource("/res/imgres/0bars.png")));
lblPeers.setBounds(508, 515, 24, 24);
lblPeers.setFont(new Font("Tahoma", Font.PLAIN, 11));
contentPane.add(lblPeers);
betterRenderer = new DefaultTableCellRenderer();
betterRenderer.setHorizontalAlignment(SwingConstants.CENTER);
downloadPopupMenu = new JPopupMenu();
downloadPopupMenuRemoveFromList = new JMenuItem("Remove from list");
downloadPopupMenu.add(downloadPopupMenuRemoveFromList);
downloadList = new JTable(downloadModel);
downloadList.getColumnModel().getColumn(0).setCellRenderer(betterRenderer);
downloadList.getColumnModel().getColumn(1).setCellRenderer(betterRenderer);
downloadList.getTableHeader().setReorderingAllowed(false);
downloadList.getTableHeader().setResizingAllowed(false);
downloadScrollPane.setViewportView(downloadList);
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(6, 75, 520, 260);
contentPane.add(tabbedPane);
searchResScrollPane = new JScrollPane();
tabbedPane.addTab("Search", null, searchResScrollPane, null);
searchRes = new JTable(tableModel);
searchRes.setDefaultRenderer(Object.class, betterRenderer);
//.getColumn(0).setCellRenderer(betterRenderer);
searchRes.getTableHeader().setReorderingAllowed(false);
searchRes.getTableHeader().setResizingAllowed(false);
searchResScrollPane.setViewportView(searchRes);
searchRes.setCellSelectionEnabled(true);
searchRes.setColumnSelectionAllowed(true);
libraryScrollPane = new JScrollPane();
tabbedPane.addTab("Library", null, libraryScrollPane, null);
libraryTable = new JTable();
libraryScrollPane.setViewportView(libraryTable);
}
public void registerListeners() {
downloadPopupMenuRemoveFromList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int[] selectedRows = downloadList.getSelectedRows();
for(Integer i : selectedRows) {
downloadModel.removeRow(i);
}
}
});
downloadList.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent arg0) {
if(arg0.isPopupTrigger()) {
Point clickPoint = arg0.getPoint();
int tableRow = downloadList.rowAtPoint(clickPoint);
if(!downloadList.isRowSelected(tableRow)) {
downloadList.changeSelection(tableRow, 0, false, false);
}
downloadPopupMenu.show(arg0.getComponent(), arg0.getX(), arg0.getY());
}
}
});
mntmAbout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
aboutWindow();
}
});
searchInput.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent arg0) {
int key = arg0.getKeyCode();
if(key == KeyEvent.VK_ENTER) {
//clear any previous res
clearTable();
//clear core index
Core.index.clear();
if(Core.debugServer) {
debugHost = searchInput.getText();
if(debugHost.equals("")) {
out("You cannot enter a blank IP.");
} else {
out("Debug host set!");
debugLatch.countDown();
}
Core.debugServer = false;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Core.mainWindow.resetTable();
} else {
if(Core.peerList.size() == 0) {
out("No peers connected. Query is not possible.");
} else {
String input = searchInput.getText();
if(input.equals("")) {
out("You cannot search for a blank query.");
} else if(input.length() < 3) {
out("You cannot search for a query shorter than 3 characters.");
} else {
if(!searchMode) {
removeColumnAndData(searchRes, 0);
tableModel.addColumn("Filename");
tableModel.addColumn("Checksum");
searchMode = true;
}
Utils.doSearch(input);
}
//dump results
}
}
searchInput.setText("");
}
}
});
searchRes.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
if(searchMode) {
Point clickPoint = arg0.getPoint();
int tableRow = searchRes.rowAtPoint(clickPoint);
if(arg0.getClickCount() == 2) {
String fileName = (String) tableModel.getValueAt(tableRow, 0);
String blockListStr = (String) tableModel.getValueAt(tableRow, 1);
@SuppressWarnings("rawtypes")
Iterator it = Core.index.entrySet().iterator();
//Iterate through HashMap until a match by blockListStr is found
while(it.hasNext()) {
@SuppressWarnings("rawtypes")
Map.Entry pairs = (Map.Entry) it.next();
//TODO: use HashMap to contact known peers first
//Peer mapPeer = (Peer) pairs.getKey();
@SuppressWarnings("unchecked")
ArrayList<String> blockList = (ArrayList<String>) pairs.getValue();
//Check to see if the HashMap's matching is accurate
if(blockList.toString().equals(blockListStr)) {
BlockedFile bf;
//Check if this BlockedFile exists
if(Utils.getBlockedFileByBlockList(blockList) != null) {
bf = Utils.getBlockedFileByBlockList(blockList);
System.out.println(bf.getName());
} else {
//If not, create a new BlockedFile instance
bf = new BlockedFile(fileName, blockList);
}
int numRows = downloadModel.getRowCount();
boolean alreadyDoneInPane = false;
for(int i = 0; i < numRows; i++) {
if(downloadModel.getValueAt(i, 0).equals(bf.getName())) {
if(downloadModel.getValueAt(i, 1).equals("100%")) {
alreadyDoneInPane = true;
break;
}
}
}
if(!alreadyDoneInPane) {
downloadModel.addRow(new String[]{bf.getName(), "0%"});
downloadList.getColumnModel().getColumn(1).setCellRenderer(new ProgressCellRenderer());
bf.download();
}
Core.mainWindow.resetTable();
}
it.remove();
}
}
}
}
});
resLatch.countDown();
setVisible(true);
}
public void out(String str) {
try {
resLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
if(searchMode) {
removeColumnAndData(searchRes, 1);
removeColumnAndData(searchRes, 0);
tableModel.addColumn("Status");
searchMode = false;
}
clearTable();
tableModel.addRow(new String[]{str});
}
public void clearTable() {
for(int i=0; i < tableModel.getRowCount(); i++) {
tableModel.removeRow(i);
}
}
public void removeColumnAndData(JTable table, int vColIndex) {
TableModelSpec model = (TableModelSpec)table.getModel();
TableColumn col = table.getColumnModel().getColumn(vColIndex);
int columnModelIndex = col.getModelIndex();
Vector<?> data = model.getDataVector();
Vector<?> colIds = model.getColumnIdentifiers();
table.removeColumn(col);
colIds.removeElementAt(columnModelIndex);
for (int r=0; r<data.size(); r++) {
Vector<?> row = (Vector<?>)data.get(r);
row.removeElementAt(columnModelIndex);
}
model.setDataVector(data, colIds);
Enumeration<?> enumer = table.getColumnModel().getColumns();
for(;enumer.hasMoreElements();) {
TableColumn c = (TableColumn)enumer.nextElement();
if (c.getModelIndex() >= columnModelIndex) {
c.setModelIndex(c.getModelIndex()-1);
}
}
model.fireTableStructureChanged();
}
public void updatePeerCount() {
String peers = Utils.peersCount();
lblPeers.setIcon(new ImageIcon(MainWindow.class.getResource("/res/imgres/" + peers + ".png")));
lblPeers.setToolTipText(Utils.peerToolTip());
}
public void updateProgress(String forFile, String progress) {
int rowCount = downloadModel.getRowCount();
for(int i=0; i < rowCount; i++) {
if(downloadModel.getValueAt(i, 0).equals(forFile)) {
downloadModel.setValueAt(progress, i, 1);
}
}
}
public void setDebugLatch(CountDownLatch debugLatch) {
this.debugLatch = debugLatch;
}
public void aboutWindow() {
new AboutWindow();
}
public void resetTable() {
Core.mainWindow.out("Enter your search query and press Enter.");
}
}
|
Added columning to library
|
src/gui/MainWindow.java
|
Added columning to library
|
<ide><path>rc/gui/MainWindow.java
<ide> protected JTable searchRes;
<ide> protected JTable downloadList;
<ide> public DefaultTableModel tableModel;
<add> public DefaultTableModel libraryModel;
<ide> public DefaultTableModel downloadModel;
<ide> protected DefaultTableCellRenderer betterRenderer;
<ide> protected CountDownLatch resLatch;
<ide> downloadModel.addColumn("Filename");
<ide> downloadModel.addColumn("Progress");
<ide>
<add> libraryModel = new DefaultTableModel();
<add> libraryModel.addColumn("Filename");
<add> libraryModel.addColumn("Size");
<add> libraryModel.addColumn("Date");
<add> libraryModel.addRow(new String[]{"Not yet implemented, feature coming soon!"});
<add>
<ide> resLatch = new CountDownLatch(1);
<ide>
<ide> searchInput = new JTextField();
<ide> libraryScrollPane = new JScrollPane();
<ide> tabbedPane.addTab("Library", null, libraryScrollPane, null);
<ide>
<del> libraryTable = new JTable();
<add> libraryTable = new JTable(libraryModel);
<add> libraryTable.getColumnModel().getColumn(0).setPreferredWidth(300);
<ide> libraryScrollPane.setViewportView(libraryTable);
<ide> }
<ide>
|
|
Java
|
apache-2.0
|
error: pathspec 'java/social-api/src/main/java/org/apache/shindig/social/opensocial/spi/RestfulItem.java' did not match any file(s) known to git
|
c8df6d7e90ee5df18f67353b2e10f542188d9d0c
| 1 |
apache/shindig,apparentlymart/shindig,apparentlymart/shindig,apache/shindig,apache/shindig,apparentlymart/shindig,apache/shindig,apache/shindig,apparentlymart/shindig
|
/*
* 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.shindig.social.opensocial.spi;
import org.apache.shindig.social.ResponseItem;
import org.apache.shindig.social.ResponseError;
import java.util.List;
public class RestfulItem<T> extends ResponseItem {
private T entry;
public RestfulItem(ResponseError error, String errorMessage) {
super(error, errorMessage);
}
public RestfulItem(T entry) {
this.entry = entry;
}
public T getEntry() {
return entry;
}
public void setEntry(T entry) {
this.entry = entry;
}
}
|
java/social-api/src/main/java/org/apache/shindig/social/opensocial/spi/RestfulItem.java
|
unbreak build..
git-svn-id: 3f2e04d30bd9db331bbfc569b45e7de8c0d84ef0@688827 13f79535-47bb-0310-9956-ffa450edef68
|
java/social-api/src/main/java/org/apache/shindig/social/opensocial/spi/RestfulItem.java
|
unbreak build..
|
<ide><path>ava/social-api/src/main/java/org/apache/shindig/social/opensocial/spi/RestfulItem.java
<add>/*
<add> * Licensed to the Apache Software Foundation (ASF) under one
<add> * or more contributor license agreements. See the NOTICE file
<add> * distributed with this work for additional information
<add> * regarding copyright ownership. The ASF licenses this file
<add> * to you under the Apache License, Version 2.0 (the
<add> * "License"); you may not use this file except in compliance
<add> * with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing,
<add> * software distributed under the License is distributed on an
<add> * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add> * KIND, either express or implied. See the License for the
<add> * specific language governing permissions and limitations under the License.
<add> */
<add>package org.apache.shindig.social.opensocial.spi;
<add>
<add>import org.apache.shindig.social.ResponseItem;
<add>import org.apache.shindig.social.ResponseError;
<add>
<add>import java.util.List;
<add>
<add>public class RestfulItem<T> extends ResponseItem {
<add> private T entry;
<add>
<add> public RestfulItem(ResponseError error, String errorMessage) {
<add> super(error, errorMessage);
<add> }
<add>
<add> public RestfulItem(T entry) {
<add> this.entry = entry;
<add> }
<add>
<add> public T getEntry() {
<add> return entry;
<add> }
<add>
<add> public void setEntry(T entry) {
<add> this.entry = entry;
<add> }
<add>}
|
|
Java
|
apache-2.0
|
87153e1ba68db9af937947487401fd80579a9be9
| 0 |
s-case/web-service-composition
|
package eu.scasefp7.eclipse.servicecomposition.toolbar;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;
import java.util.Map.Entry;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.zest.core.widgets.Graph;
import org.eclipse.zest.core.widgets.GraphItem;
import org.eclipse.zest.core.widgets.GraphNode;
import edu.uci.ics.jung.graph.SparseMultigraph;
import edu.uci.ics.jung.graph.util.EdgeType;
import eu.scasefp7.eclipse.servicecomposition.Activator;
import eu.scasefp7.eclipse.servicecomposition.codeInterpreter.UserInput;
import eu.scasefp7.eclipse.servicecomposition.codeInterpreter.Value;
import eu.scasefp7.eclipse.servicecomposition.importer.Importer.Argument;
import eu.scasefp7.eclipse.servicecomposition.importer.Importer.Operation;
import eu.scasefp7.eclipse.servicecomposition.importer.JungXMIImporter.Connector;
import eu.scasefp7.eclipse.servicecomposition.operationCaller.RAMLCaller;
import eu.scasefp7.eclipse.servicecomposition.operationCaller.WSDLCaller;
import eu.scasefp7.eclipse.servicecomposition.transformer.PathFinding;
import eu.scasefp7.eclipse.servicecomposition.transformer.Similarity;
import eu.scasefp7.eclipse.servicecomposition.transformer.JungXMItoOwlTransform.OwlService;
import eu.scasefp7.eclipse.servicecomposition.ui.MatchOutputDialog;
import eu.scasefp7.eclipse.servicecomposition.ui.Node;
import eu.scasefp7.eclipse.servicecomposition.views.MyNode;
import eu.scasefp7.eclipse.servicecomposition.views.ServiceCompositionView;
import eu.scasefp7.eclipse.servicecomposition.views.Utils;
public class RunWorkflow {
// constants
private static double VARIABLE_NAME_SIMILARITY_THRESHOLD = 0.5;
private static double MAX_DISTANCE_BETWEEN_SOLUTIONS = 0.1;
private static double VALUE_SIMILARITY_THRESHOLD = 0;
// predicates for special types of branches
private static String[] TRUE_PREDICATES = { "true", "yes" };
private static String[] FALSE_PREDICATES = { "false", "no" };
private static String[] ELSE_PREDICATES = { "else", "otherwise" };
// starting and ending service in the graph
private OwlService startingService = null;
private OwlService endingService = null;
// the selected owlservice
private OwlService currentService;
private TreeViewerColumn columnb;
private TreeViewer treeViewer;
private Composite authParamsComposite;
// eclipse jobs
private Job runWorkflowJob;
protected ServiceCompositionView view;
protected edu.uci.ics.jung.graph.Graph<OwlService, Connector> jungGraph;
public RunWorkflow(ServiceCompositionView view, TreeViewer treeViewer, TreeViewerColumn columnb,
Composite authParamsComposite) {
this.view = view;
this.jungGraph = view.getJungGraph();
this.treeViewer = treeViewer;
this.columnb = columnb;
this.authParamsComposite = authParamsComposite;
}
public void unhighlightAllNodes() {
// unhighlight all nodes
Graph graph = view.getViewer().getGraphControl();
for (int i = 0; i < graph.getNodes().size(); i++) {
GraphNode graphNode = (GraphNode) graph.getNodes().get(i);
graphNode.unhighlight();
}
}
public String runWorkflow() throws Exception {
final Shell shell = view.getSite().getWorkbenchWindow().getShell();
final Display disp = shell.getDisplay();
runWorkflowJob = new Job("Running Workflow") {
@Override
protected IStatus run(IProgressMonitor monitor) {
monitor.beginTask("Workflow execution in progress ...", IProgressMonitor.UNKNOWN);
try {
final Graph destGraph = view.getViewer().getGraphControl();
disp.syncExec(new Runnable() {
@Override
public void run() {
unhighlightAllNodes();
Utils.cleanOutputs(treeViewer.getTree(), jungGraph);
}
});
Properties prop = new Properties();
String propFileName = "/matcher.properties";
// Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID);
// URL fileURL = bundle.getEntry(propFileName);
URL fileURL = new URL("platform:/plugin/" + Activator.PLUGIN_ID + propFileName);
try {
InputStream inputStream = fileURL.openConnection().getInputStream();
prop.load(inputStream);
// File file = new
// File(FileLocator.resolve(fileURL).toURI());
// InputStream inputStream = new FileInputStream(file);
// prop.load(inputStream);
VARIABLE_NAME_SIMILARITY_THRESHOLD = Double
.parseDouble(prop.getProperty("interpreter.VARIABLE_NAME_SIMILARITY_THRESHOLD"));
MAX_DISTANCE_BETWEEN_SOLUTIONS = Double
.parseDouble(prop.getProperty("interpreter.MAX_DISTANCE_BETWEEN_SOLUTIONS"));
VALUE_SIMILARITY_THRESHOLD = Double
.parseDouble(prop.getProperty("interpreter.VALUE_SIMILARITY_THRESHOLD"));
} catch (Exception e) {
Activator.log("Error occured while trying to load matcher settings from " + propFileName, e);
System.err.println("Error occured while trying to load matcher settings from " + propFileName);
}
edu.uci.ics.jung.graph.Graph<OwlService, Connector> graph = new SparseMultigraph<OwlService, Connector>();
// check if user has cancelled
if (monitor.isCanceled())
return Status.CANCEL_STATUS;
// replace all services in the graph with implementations
HashMap<OwlService, OwlService> implementations = new HashMap<OwlService, OwlService>();
for (OwlService service : jungGraph.getVertices()) {
if (service.getOperation() != null) {
// System.out.println("replacing:
// "+service.getOperation());
OwlService created = new OwlService(service);
Implementation test = new Implementation(service.getOperation());
created.editContent(test);
implementations.put(service, created);
graph.addVertex(created);
// System.out.println("with:
// "+created.getOperation());
} else if (service.getArgument() != null) {
try {
service.getArgument().assertCorrectSubtypes();
} catch (Exception e) {
e.printStackTrace();
}
// They get the previous call value-empty for the
// first time.
OwlService created = new OwlService(service);
created.getArgument().setOwlService(created);
Value value = new Value(service.getArgument());
// value.getElements().clear();
// // Value value =
// // (Value.getValue(service.getArgument()));
// // Clear old values
// value.setValue("");
// value.getElements().removeAll(value.getElements());
// ArrayList<Value> list = value.getElements();
//
// for (Iterator<Value> iterator = list.iterator();
// iterator.hasNext(); ) {
// Value v = iterator.next();
// if (v != null) {
// iterator.remove();
// }
// }
created.editContent(value);
// if (service.getisMatchedIO()) {
// created.setisMatchedIO(true);
// }
implementations.put(service, created);
graph.addVertex(created);
} else {
implementations.put(service, service);
graph.addVertex(service);
}
}
for (Connector connector : jungGraph.getEdges(EdgeType.DIRECTED)) {
OwlService source = implementations.get(connector.getSource());
OwlService target = implementations.get(connector.getTarget());
if (graph.findEdge(source, target) == null)
graph.addEdge(new Connector(source, target, connector.getCondition()), source, target,
EdgeType.DIRECTED);
}
for (Connector connector : jungGraph.getEdges(EdgeType.UNDIRECTED)) {
OwlService source = implementations.get(connector.getSource());
OwlService target = implementations.get(connector.getTarget());
if (graph.findEdge(target, source) == null)
graph.addEdge(new Connector(target, source, connector.getCondition()), target, source,
EdgeType.UNDIRECTED);
}
// check if user has cancelled
if (monitor.isCanceled())
return Status.CANCEL_STATUS;
// initialize variable lists
final ArrayList<Value> inputVariables = new ArrayList<Value>();
final ArrayList<Value> outputVariables = new ArrayList<Value>();
final ArrayList<Value> suboutputVariables = new ArrayList<Value>();
final ArrayList<Value> subinputVariables = new ArrayList<Value>();
final ArrayList<Value> authParamVariables = new ArrayList<Value>();
Vector<Node> nodes = new Vector<Node>();
// ArrayList<Value> directAssignVariables = new
// ArrayList<Value>();
// detect all operations
ArrayList<OwlService> remainingOperations = new ArrayList<OwlService>();
// detect all variables(input and output variables could be
// also detected here)
ArrayList<Value> allVariables = new ArrayList<Value>();
for (OwlService service : graph.getVertices()) {
Operation op = service.getOperation();
if (op != null) {
remainingOperations.add(service);
for (Argument arg : op.getInputs()) {
// if (!allVariables.contains(arg))
allVariables.add((Value) arg);
// if (!inputVariables.contains(arg))
inputVariables.add((Value) arg);
for (Argument sub : arg.getSubtypes()) {
// if (!allVariables.contains(sub)) {
allVariables.add((Value) sub);
// }
getSubtypes(subinputVariables, sub, false);
}
}
for (Argument arg : op.getOutputs()) {
// if (!allVariables.contains(arg)) {
allVariables.add((Value) arg);
// }
// if (!outputVariables.contains(arg)) {
outputVariables.add((Value) arg);
// }
System.out.println("OUTPUT DETECTED\t " + arg);
for (Argument sub : arg.getSubtypes()) {
if (!allVariables.contains(sub)) {
allVariables.add((Value) sub);
}
getSubtypes(suboutputVariables, sub, false);
}
}
// if (!op.getUriParameters().isEmpty()) {
// for (Argument arg : op.getUriParameters()) {
// uriParamVariables.add((Value) arg);
// }
// }
if (!op.getAuthenticationParameters().isEmpty()) {
for (Argument arg : op.getAuthenticationParameters()) {
authParamVariables.add((Value) arg);
}
}
}
// detect starting service
if (service.getType().trim().equals("StartNode")) {
startingService = service;
}
// detect ending service
if (service.getType().trim().equals("EndNode")) {
endingService = service;
}
}
if (startingService == null) {
try {
throw new Exception("StartNode was not detected on graph vertices");
} catch (Exception e1) {
e1.printStackTrace();
}
}
if (endingService == null) {
try {
throw new Exception("EndNode was not detected on graph vertices");
} catch (Exception e1) {
e1.printStackTrace();
}
}
// Check if every node has a path to StartNode and to
// EndNode and also a condition has two output edges in
// order to allow execution.
ArrayList<OwlService> previousList = new ArrayList<OwlService>();
ArrayList<OwlService> nextList = new ArrayList<OwlService>();
for (OwlService service : graph.getVertices()) {
if (service.getType().contains("Action") || service.getType().contains("Condition")) {
if (service.getType().contains("Condition") && (graph.getOutEdges(service).size() < 2)) {
final OwlService unlinked = service;
try {
throw new Exception("\"" + unlinked.getName().toString() + "\""
+ " condition should have two output edges.");
} catch (Exception e1) {
e1.printStackTrace();
}
disp.syncExec(new Runnable() {
@Override
public void run() {
MessageDialog.openInformation(disp.getActiveShell(), "Error occured",
"\"" + unlinked.getName().toString() + "\""
+ " condition should have two output edges.");
}
});
return Status.CANCEL_STATUS;
}
previousList = (new PathFinding(graph).findOperationPath(startingService, service));
if (previousList.get(0) != startingService) {
final OwlService unlinked = previousList.get(0);
try {
throw new Exception("\"" + unlinked.getName().toString() + "\""
+ " has no path to StartNode. Check for unlinked operations.");
} catch (Exception e1) {
e1.printStackTrace();
}
disp.syncExec(new Runnable() {
@Override
public void run() {
MessageDialog.openInformation(disp.getActiveShell(), "Error occured",
"\"" + unlinked.getName().toString() + "\""
+ " has no path to StartNode. Check for unlinked operations.");
}
});
return Status.CANCEL_STATUS;
}
nextList = (new PathFinding(graph).findOperationPath(service, endingService));
if (nextList.get(0) != service) {
final OwlService unlinked = service;
try {
throw new Exception("\"" + unlinked.getName().toString() + "\""
+ " has no path to EndNode. Check for unlinked operations.");
} catch (Exception e1) {
e1.printStackTrace();
}
disp.syncExec(new Runnable() {
@Override
public void run() {
MessageDialog.openInformation(disp.getActiveShell(), "Error occured",
"\"" + unlinked.getName().toString() + "\""
+ " has no path to EndNode. Check for unlinked operations.");
}
});
return Status.CANCEL_STATUS;
}
}
}
currentService = startingService;
// check if user has cancelled
if (monitor.isCanceled())
return Status.CANCEL_STATUS;
// get input values
disp.syncExec(new Runnable() {
@SuppressWarnings("unchecked")
@Override
public void run() {
if (currentService == startingService) {
// fill inputs from right panel
for (int i = 0; i < inputVariables.size(); i++) {
Value var = inputVariables.get(i);
for (int j = 0; j < ((Vector<Node>) columnb.getViewer().getInput()).size(); j++) {
if (((Vector<Node>) columnb.getViewer().getInput()).get(j) instanceof Node) {
Node operation = ((Vector<Node>) columnb.getViewer().getInput()).get(j);
for (int k = 0; k < operation.getSubCategories().size(); k++) {
if (operation.getSubCategories().get(k).getOwlService()
.equals(var.getOwlService())) {
Node node = operation.getSubCategories().get(k);
fillInInputValues(var, node);
}
}
}
}
}
}
}
});
// check if user has cancelled
if (monitor.isCanceled())
return Status.CANCEL_STATUS;
// get uri parameters values
disp.syncExec(new Runnable() {
@Override
public void run() {
if (currentService == startingService) {
// fill Authentication params from right panel
for (int i = 0; i < authParamVariables.size(); i++) {
Value var = authParamVariables.get(i);
for (int j = 0; j < authParamsComposite.getChildren().length; j++) {
if (authParamsComposite.getChildren()[j] instanceof Label) {
Label label = (Label) authParamsComposite.getChildren()[j];
if (label.getText().split("\\*")[0].trim()
.equals(var.getName().toString())) {
if (((Text) authParamsComposite.getChildren()[j + 1]).isEnabled())
var.setValue(((Text) authParamsComposite.getChildren()[j + 1])
.getText());
}
}
}
}
}
}
});
WSDLCaller callWSDL = new WSDLCaller();
// PythonCaller callPython = new PythonCaller();
RAMLCaller callRAML = new RAMLCaller();
OwlService previousNode = null;
// highlight nodes
while (currentService != null) {
long startTime = System.currentTimeMillis();
if (monitor.isCanceled()) {
disp.syncExec(new Runnable() {
@Override
public void run() {
unhighlightAllNodes();
}
});
return Status.CANCEL_STATUS;
}
// Highlight Nodes
disp.syncExec(new Runnable() {
@Override
public void run() {
unhighlightAllNodes();
for (int i = 0; i < destGraph.getNodes().size(); i++) {
GraphNode graphNode = (GraphNode) destGraph.getNodes().get(i);
if (currentService.toString().equals("StartNode")) {
if (((OwlService) ((MyNode) graphNode.getData()).getObject()).toString()
.equals("StartNode")) {
destGraph.setSelection(new GraphItem[] { graphNode });
graphNode.highlight();
}
} else if (currentService.toString().equals("EndNode")) {
if (((OwlService) ((MyNode) graphNode.getData()).getObject()).toString()
.equals("EndNode")) {
destGraph.setSelection(new GraphItem[] { graphNode });
graphNode.highlight();
}
} else if (((OwlService) ((MyNode) graphNode.getData()).getObject())
.equals(currentService)) {
destGraph.setSelection(new GraphItem[] { graphNode });
graphNode.highlight();
}
}
}
});
// call the service
if (currentService.getOperation() != null) {
try {
if (currentService.getOperation().getDomain() == null) {
disp.syncExec(new Runnable() {
@Override
public void run() {
MessageDialog.openInformation(disp.getActiveShell(), "Error occured",
"Action \"" + currentService.getOperation().getName()
+ "\" was not replaced. Please replace it manually with one of the available operations or modify and re-import the storyboard diagram before executing the workflow.");
}
});
throw new Exception("Service " + currentService.getOperation().getName()
+ " is missing its domain");
} else if (currentService.getOperation().getType().equalsIgnoreCase("SOAP"))
// else if
// (!currentService.getOperation().getDomain().isLocal())
callWSDL.callOperation(currentService.getOperation());
else if (currentService.getOperation().getType().equalsIgnoreCase("RESTful")) {
callRAML.callRESTfulOperation(currentService.getOperation());
}
/*
* else callPython.callOperation(currentService.
* getOperation());
*/
} catch (Exception e) {
Activator.log("Error occured while calling "
+ currentService.getOperation().getName().toString(), e);
e.printStackTrace();
disp.syncExec(new Runnable() {
@Override
public void run() {
MessageDialog.openInformation(disp.getActiveShell(), "Invocation error occured",
"An error occured during invocation of \"" + currentService.getName()
+ "\"");
}
});
return Status.CANCEL_STATUS;
}
ArrayList<Value> serviceOutputs = new ArrayList<Value>();
for (Argument arg : currentService.getOperation().getOutputs()) {
serviceOutputs.add((Value) arg);
}
if (!serviceOutputs.isEmpty()) {
disp.syncExec(new Runnable() {
@Override
public void run() {
fillInOutputValues(serviceOutputs, nodes, graph);
OwlService array = null;
for (Argument arg : serviceOutputs) {
for (OwlService service : graph.getVertices()) {
if (service.equals(((Value) arg).getOwlService())) {
try {
service.setContent((Value) arg);
} catch (Exception e) {
Activator.log("Error setting outputs content", e);
e.printStackTrace();
}
}
}
}
Vector<Node> matchedOutputNodes = new Vector<Node>();
for (OwlService service : graph.getVertices()) {
if (service.getisMatchedIO()
&& !service.getArgument().getMatchedInputs().isEmpty()
&& service.getArgument().getBelongsToOperation().getName()
.toString().equals(currentService.getOperation().getName()
.toString())) {
boolean isMemberOfArray = false;
for (Object parent : service.getArgument().getParent()) {
if (parent instanceof Argument)
if (((Argument) parent).isArray()) {
isMemberOfArray = true;
}
}
// if predecessor is array
if (isMemberOfArray || service.getArgument().isArray()) {
OwlService initialArray = getInitialArray(service, graph, false);
int subNum = 0;
for (Argument sub : initialArray.getArgument().getSubtypes()) {
if (sub.getOwlService().getisMatchedIO())
subNum++;
}
boolean arrayIsMatched = false;
if (subNum == initialArray.getArgument().getSubtypes().size()) {
arrayIsMatched = true;
}
boolean successorIsMemberOfArray = false;
for (Argument successor : service.getArgument()
.getMatchedInputs()) {
// for each successor
for (Object parent : successor.getParent()) {
if (parent instanceof Argument)
if (((Argument) parent).isArray()) {
successorIsMemberOfArray = true;
}
}
OwlService successorMatched = null;
for (OwlService suc : graph.getSuccessors(service)) {
successorMatched = suc;
}
// if successor is also
// member of array
if (successorIsMemberOfArray) {
OwlService successorInitialArray = getInitialArray(
successorMatched, graph, true);
// clear matched
// elements
int i = 0;
if (arrayIsMatched && array != initialArray) {
for (Value element : initialArray.getArgument()
.getElements()) {
Value value = new Value(element);
value.setOwlService(successorInitialArray
.getArgument().getOwlService());
value.setName(successorInitialArray.getArgument()
.getType() + "[" + i + "]");
successorInitialArray.getArgument().getElements()
.add(value);
for (Argument input : inputVariables) {
if (input.getOwlService()
.equals(successorInitialArray)) {
ArrayList<Value> list = input.getElements();
for (Iterator<Value> iterator = list
.iterator(); iterator.hasNext();) {
Value v = iterator.next();
if (v != null) {
iterator.remove();
}
}
input.getElements().add(value);
break;
}
}
i++;
}
array = initialArray;
}
} else if (successor.isArray()) {
// successor is
// array
for (Value element : service.getArgument().getElements()) {
successor.getElements().add(element);
}
} else {
// successor is
// object
OwlService initialInput = getInitialInput(service, graph);
ServiceCompositionView.showOutputs(
(Value) initialInput.getArgument(), null,
matchedOutputNodes, jungGraph);
disp.syncExec(new Runnable() {
@Override
public void run() {
MatchOutputDialog dialog = new MatchOutputDialog(
shell);
dialog.setDisp(disp);
dialog.setArrayNodes(matchedOutputNodes);
dialog.setName(successor.getName().toString());
dialog.setOutputService(service);
dialog.create();
dialog.setDialogLocation();
if (dialog.open() == Window.OK) {
String value = dialog.getValue();
((Value) successor).setValue(value);
for (Argument input : inputVariables) {
if (input.getOwlService().equals(
successor.getOwlService())) {
((Value) input).setValue(value);
}
}
} else {
return;
}
}
});
}
}
// if predecessor is object
} else {
boolean successorIsMemberOfArray = false;
for (Argument successor : service.getArgument()
.getMatchedInputs()) {
// for each successor
for (Object parent : successor.getParent()) {
if (parent instanceof Argument)
if (((Argument) parent).isArray()) {
successorIsMemberOfArray = true;
}
}
if (successor.isArray()) {
Argument in;
try {
in = new Argument(
successor.getName().toString() + "[0]", "",
successor.isTypeOf(), false,
successor.isNative(), successor.getSubtypes());
in.setOwlService(successor.getOwlService());
Value value = new Value(in);
value.setValue(
((Value) service.getArgument()).getValue());
successor.getElements().add(0, value);
} catch (Exception e) {
// Auto-generated
// catch block
e.printStackTrace();
}
} else if (successorIsMemberOfArray) {
// TODO complex
// array
} else {
((Value) successor).setValue(
((Value) service.getArgument()).getValue());
for (Argument input : inputVariables) {
if (input.getOwlService()
.equals(successor.getOwlService())) {
((Value) input).setValue(
((Value) service.getArgument()).getValue());
}
}
}
}
}
}
}
}
});
}
}
// select next service
ArrayList<Value> previousServiceOutVariables = new ArrayList<Value>();
HashMap<OwlService, Connector> possibleServices = new HashMap<OwlService, Connector>();
for (OwlService next : graph.getSuccessors(currentService))
if (next.getArgument() == null)
possibleServices.put(next, graph.findEdge(currentService, next));
previousNode = currentService;
for (OwlService previousOperation : graph.getPredecessors(currentService)) {
if (previousOperation.getOperation() != null) {
for (Argument output : previousOperation.getOperation().getOutputs()) {
if (!output.isArray()) {
if (output.getSubtypes().isEmpty()) {
previousServiceOutVariables.add((Value) output);
}
for (Argument sub : output.getSubtypes()) {
if (!sub.isArray()) {
getSubtypes(previousServiceOutVariables, sub, true);
}
}
}
}
}
}
currentService = checkCondition(currentService, possibleServices, previousServiceOutVariables);
// Update matched variable values 2
// if (currentService != null) {
// if (currentService.getOperation() != null) {
// for (OwlService service : graph.getVertices()) {
// boolean isMatched = false;
// for (int i = 0; i <
// currentService.getOperation().getInputs().size();
// i++) {
// if (service.getArgument() != null) {
// for (OwlService successor :
// graph.getSuccessors(service)) {
// if (successor.getArgument() != null) {
// if (successor.getisMatchedIO() &&
// service.getisMatchedIO()) {
// isMatched = true;
// }
// if (successor.getArgument()
// .getName().toString().equals(currentService.getOperation()
// .getInputs().get(i).getName().toString())
// && isMatched) {
// ((Value)
// currentService.getOperation().getInputs().get(i))
// .setValue(((Value)
// service.getArgument()).getValue());
// }
// }
// }
//
// }
// }
// }
// }
// }
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
if (elapsedTime < 500) {
try {
Thread.sleep(500 - elapsedTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
if (!outputVariables.isEmpty()) {
disp.syncExec(new Runnable() {
@Override
public void run() {
// fillInOutputValues(outputVariables);
treeViewer.setInput(nodes);
}
});
}
monitor.done();
return Status.OK_STATUS;
} catch (Exception ex) {
Activator.log("Error while running the workflow", ex);
ex.printStackTrace();
monitor.done();
return Status.CANCEL_STATUS;
} finally {
monitor.done();
}
}
};
runWorkflowJob.schedule();
return "";
}
public static OwlService getInitialArray(OwlService matchedVar,
edu.uci.ics.jung.graph.Graph<OwlService, Connector> graph, boolean isSuccessor) {
OwlService initialArray = matchedVar;
if (isSuccessor) {
for (OwlService successor : graph.getSuccessors(matchedVar)) {
if (successor.getArgument() != null) {
if (successor.getArgument().isArray()) {
initialArray = getInitialArray(successor, graph, true);
} else {
break;
}
} else {
break;
}
}
} else {
for (OwlService predecessor : graph.getPredecessors(matchedVar)) {
if (predecessor.getArgument() != null) {
if (predecessor.getArgument().isArray()) {
initialArray = getInitialArray(predecessor, graph, false);
} else {
break;
}
} else {
break;
}
}
}
return initialArray;
}
public static OwlService getInitialInput(OwlService matchedVar,
edu.uci.ics.jung.graph.Graph<OwlService, Connector> graph) {
OwlService initialInput = matchedVar;
for (OwlService predecessor : graph.getPredecessors(matchedVar)) {
if (predecessor.getArgument() != null) {
initialInput = getInitialInput(predecessor, graph);
} else {
break;
}
}
return initialInput;
}
private ArrayList<Value> getSubtypes(ArrayList<Value> suboutputVariables, Argument sub, boolean noObjects) {
if (!suboutputVariables.contains(sub)) {
if (noObjects) {
if (sub.getSubtypes().isEmpty()) {
suboutputVariables.add((Value) sub);
}
} else {
suboutputVariables.add((Value) sub);
}
}
if (!sub.getSubtypes().isEmpty()) {
for (Argument subsub : sub.getSubtypes()) {
if (noObjects) {
if (!sub.isArray()) {
getSubtypes(suboutputVariables, subsub, true);
}
} else {
getSubtypes(suboutputVariables, subsub, true);
}
}
}
return suboutputVariables;
}
private void fillInOutputValues(ArrayList<Value> list, Vector<Node> nodes,
edu.uci.ics.jung.graph.Graph<OwlService, Connector> graph) {
for (int i = 0; i < list.size(); i++) {
Value var = list.get(i);
ServiceCompositionView.showOutputs(var, null, nodes, graph);
}
}
private void fillInInputValues(Value var, Node node) {
String[] datatypes = new String[] { "string", "long", "int", "float", "double", "dateTime", "boolean" };
if (((Value) var).isArray() && RAMLCaller.stringIsItemFromList(((Value) var).getType(), datatypes)) {
for (int k = 0; k < node.getSubCategories().size(); k++) {
if (node.getSubCategories().get(k) != null) {
Argument in;
try {
in = new Argument(var.getName().toString() + "[" + k + "]", "", var.isTypeOf(), false,
var.isNative(), var.getSubtypes());
for (Argument arg : var.getMatchedInputs()) {
in.getMatchedInputs().add(arg);
}
in.setOwlService(var.getOwlService());
Value value = new Value(in);
// Value value = Value.getValue(out);
value.setValue(node.getSubCategories().get(k).getValue());
var.getElements().add(value);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} else if (((Value) var).isArray() && !RAMLCaller.stringIsItemFromList(((Value) var).getType(), datatypes)) {
for (int k = 0; k < node.getSubCategories().size(); k++) {
// create and add site[0]element, device[0]
Argument in = new Argument(var);
in.setOwlService(var.getOwlService());
in.setName(var.getType() + "[" + k + "]");
Value value = new Value(in);
for (Argument sub : var.getSubtypes()) {
if (sub.isArray()) {
Argument out1 = new Argument(sub);
out1.setOwlService(sub.getOwlService());
out1.setName(sub.getName().toString());
Value value2 = new Value(out1);
Node object = (Node) node.getSubCategories().get(k);
for (int i = 0; i < object.getSubCategories().size(); i++) {
int index = object.getSubCategories().get(i).getName().toString().indexOf('[');
if (value2.getName().toString().equals(
object.getSubCategories().get(i).getName().toString().substring(0, index - 1))) {
fillInInputValues(value2, object.getSubCategories().get(i));
value.getElements().add(value2);
break;
}
}
} else {
// create device
Argument in1 = new Argument(sub);
in1.setOwlService(sub.getOwlService());
in1.setName(sub.getName().toString());
Value value1 = new Value(in1);
Node object = (Node) node.getSubCategories().get(k);
for (int i = 0; i < object.getSubCategories().size(); i++) {
int index = object.getSubCategories().get(i).getName().toString().indexOf('[');
if (value1.getName().toString().equals(
object.getSubCategories().get(i).getName().toString().substring(0, index - 1))) {
fillInInputValues(value1, (object.getSubCategories().get(i)));
value.getElements().add(value1);
break;
}
}
}
}
var.getElements().add(value);
}
} else if (!((Value) var).isArray() && !RAMLCaller.stringIsItemFromList(((Value) var).getType(), datatypes)) {
for (int k = 0; k < node.getSubCategories().size(); k++) {
for (Argument sub : var.getSubtypes()) {
int index = node.getSubCategories().get(k).getName().toString().indexOf('[');
if (((Value) sub).getName().toString()
.equals(node.getSubCategories().get(k).getName().toString().substring(0, index - 1))) {
fillInInputValues((Value) sub, (Node) node.getSubCategories().get(k));
}
}
}
} else {
var.setValue(node.getValue());
}
}
private OwlService checkCondition(OwlService source, HashMap<OwlService, Connector> candidates,
ArrayList<Value> allVariables) {
double prevThreshold = Similarity.levenshteinThreshold;
Similarity.levenshteinThreshold = 0;
Iterator<Entry<OwlService, Connector>> it = candidates.entrySet().iterator();
ArrayList<OwlService> resultCandidates = new ArrayList<OwlService>();
HashMap<OwlService, String> text = new HashMap<OwlService, String>();
double bestVal = VALUE_SIMILARITY_THRESHOLD;
while (it.hasNext()) {
Map.Entry<OwlService, Connector> pair = (Map.Entry<OwlService, Connector>) it.next();
double val = checkSingleCondition(source, pair.getValue(), pair.getKey(), allVariables);
if (val >= bestVal) {
if (val >= bestVal + MAX_DISTANCE_BETWEEN_SOLUTIONS) {
resultCandidates.clear();
bestVal = val;
}
resultCandidates.add(pair.getKey());
text.put(pair.getKey(), pair.getValue().toString());
}
}
if ((resultCandidates.isEmpty() || resultCandidates.size() > 1) && !candidates.isEmpty()) {
ArrayList<OwlService> tempCandidates = new ArrayList<OwlService>();
it = candidates.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<OwlService, Connector> pair = (Map.Entry<OwlService, Connector>) it.next();
for (String predicate : ELSE_PREDICATES)
if (Similarity.comparePredicates(pair.getValue().getCondition(), predicate)) {
tempCandidates.add(pair.getKey());
break;
}
}
if (tempCandidates.size() == 1)
resultCandidates = tempCandidates;
}
Similarity.levenshteinThreshold = prevThreshold;
if (resultCandidates.isEmpty() && !candidates.isEmpty() && VALUE_SIMILARITY_THRESHOLD != 0) {
System.out.println("TOO STRICT CONDITIONS\t trying again with VALUE_SIMILARITY_THRESHOLD to zero");
double temp = VALUE_SIMILARITY_THRESHOLD;
VALUE_SIMILARITY_THRESHOLD = 0;
OwlService result = checkCondition(source, candidates, allVariables);
VALUE_SIMILARITY_THRESHOLD = temp;
return result;
}
Similarity.levenshteinThreshold = prevThreshold;
if (resultCandidates.size() == 1)
return resultCandidates.get(0);
return (OwlService) UserInput.getSelection(source.toString(), resultCandidates, text);
}
/**
* <h1>checkSingleCondition</h1> This function returns a weight in range
* [0,1] that represents the match of the given expression to the given
* condition.<br/>
* This function also tries to extract numeric data in order to compare
* expressions in case it yield better results.
*
* @param source
* : an OwlService that represents the expression to be evaluated
* @param condition
* : a Connector that represents the condition to be checked
* @param candidate
* : the next OwlService to be reached if the given Connector is
* selected
* @param allVariables
* : a list of all possible variables
* @return a value in range [0,1]
*/
private double checkSingleCondition(OwlService source, Connector condition, OwlService candidate,
ArrayList<Value> allVariables) {
if (condition.toString().isEmpty())
return 1;
String sourceText = source.toString();
String conditionText = condition.getCondition();
boolean negativeLogic = false;
boolean logicResult = false;
for (String predicate : FALSE_PREDICATES)
if (Similarity.comparePredicates(conditionText, predicate)) {
negativeLogic = true;
logicResult = true;
break;
}
for (String predicate : TRUE_PREDICATES)
if (Similarity.comparePredicates(conditionText, predicate)) {
logicResult = true;
break;
}
double compareMode = 0;
boolean equality = false;
if (logicResult) {
int index;
if ((index = sourceText.indexOf("==")) != -1) {
conditionText = sourceText.substring(index + 2);
sourceText = sourceText.substring(0, index);
equality = true;
} else if ((index = sourceText.indexOf("!=")) != -1) {
conditionText = sourceText.substring(index + 2);
sourceText = sourceText.substring(0, index);
negativeLogic = !negativeLogic;
equality = true;
} else if ((index = sourceText.indexOf("=")) != -1) {
conditionText = sourceText.substring(index + 1);
sourceText = sourceText.substring(0, index);
equality = true;
} else if ((index = sourceText.indexOf("<")) != -1) {
conditionText = sourceText.substring(index + 1);
sourceText = sourceText.substring(0, index);
compareMode = 1;
} else if ((index = sourceText.indexOf(">")) != -1) {
conditionText = sourceText.substring(index + 1);
sourceText = sourceText.substring(0, index);
compareMode = -1;
}
}
String replacableCondition = conditionText.replaceAll("[^\\.0123456789]", "");
if (replacableCondition.isEmpty()) {
replacableCondition = sourceText.replaceAll("[^\\.0123456789]", "");
if (!replacableCondition.isEmpty()) {
String temp = sourceText;
sourceText = conditionText;
conditionText = temp;
compareMode = -compareMode;
}
}
Value bestValue = null;
double bestMatch = VARIABLE_NAME_SIMILARITY_THRESHOLD;
for (Value val : allVariables) {
if (val.getValue() != null) {
if (val.getValue().replaceAll("[^\\.0123456789]", "").isEmpty() != conditionText
.replaceAll("[^\\.0123456789]", "").isEmpty())
continue;
double match = Similarity.similarity(val.getName().toString(), sourceText);
if (match >= bestMatch) {
bestMatch = match;
bestValue = val;
}
}
}
if (bestValue == null)
return 1;
boolean success = true;
double conditionValue = Double.POSITIVE_INFINITY - 1;
double variableValue = 0;
try {
conditionValue = Double.parseDouble(conditionText.replaceAll("[^\\.0123456789]", ""));// careful
// to
// have
// this
// first,
// so
// that
// if
// it
// fails
// POSITIVE_INFINITY
// calculations
// work
// as
// intended
variableValue = Double.parseDouble(bestValue.getValue());
} catch (Exception e) {
success = false;
}
double retValue = 0;
if (success) {
retValue = (conditionValue == variableValue) ? 1
: (Math.abs(conditionValue - variableValue)
/ (Math.abs(conditionValue) + Math.abs(variableValue) + 1));
if (compareMode > 0)
retValue = conditionValue > variableValue ? 1 : 0;
else if (compareMode < 0)
retValue = conditionValue < variableValue ? 1 : 0;
if (negativeLogic)
retValue = 1 - retValue;
}
double retValue2 = Similarity.similarity(conditionText, bestValue.getValue());
// / (conditionText.length() * bestValue.getValue().length() + 1);
if (negativeLogic && equality)
retValue2 = 1 - retValue2;
// System.out.println(sourceText+" vs "+bestValue.getName()+" =
// "+Math.max(retValue,
// retValue2));
return Math.max(retValue, retValue2);
}
public class Implementation extends Operation {
/**
* Generates an implementation out of an operation by converting all
* variables into <code>Value</code> instances using
* <code>Value.getValue</code>.
*/
public Implementation(Operation operation) {
// super(operation.getName().toString(), operation.getDomain());
super(operation);
for (Argument input : operation.getInputs())
getInputs().add(new Value(input));
for (Argument output : operation.getOutputs())
getOutputs().add(new Value(output));
// for (Argument uriParam : operation.getUriParameters())
// getUriParameters().add(new Value(uriParam));
for (Argument authParam : operation.getAuthenticationParameters())
getAuthenticationParameters().add(new Value(authParam));
}
}
}
|
eu.scasefp7.eclipse.servicecomposition/src/eu/scasefp7/eclipse/servicecomposition/toolbar/RunWorkflow.java
|
package eu.scasefp7.eclipse.servicecomposition.toolbar;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;
import java.util.Map.Entry;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.zest.core.widgets.Graph;
import org.eclipse.zest.core.widgets.GraphItem;
import org.eclipse.zest.core.widgets.GraphNode;
import edu.uci.ics.jung.graph.SparseMultigraph;
import edu.uci.ics.jung.graph.util.EdgeType;
import eu.scasefp7.eclipse.servicecomposition.Activator;
import eu.scasefp7.eclipse.servicecomposition.codeInterpreter.UserInput;
import eu.scasefp7.eclipse.servicecomposition.codeInterpreter.Value;
import eu.scasefp7.eclipse.servicecomposition.importer.Importer.Argument;
import eu.scasefp7.eclipse.servicecomposition.importer.Importer.Operation;
import eu.scasefp7.eclipse.servicecomposition.importer.JungXMIImporter.Connector;
import eu.scasefp7.eclipse.servicecomposition.operationCaller.RAMLCaller;
import eu.scasefp7.eclipse.servicecomposition.operationCaller.WSDLCaller;
import eu.scasefp7.eclipse.servicecomposition.transformer.PathFinding;
import eu.scasefp7.eclipse.servicecomposition.transformer.Similarity;
import eu.scasefp7.eclipse.servicecomposition.transformer.JungXMItoOwlTransform.OwlService;
import eu.scasefp7.eclipse.servicecomposition.ui.MatchOutputDialog;
import eu.scasefp7.eclipse.servicecomposition.ui.Node;
import eu.scasefp7.eclipse.servicecomposition.views.MyNode;
import eu.scasefp7.eclipse.servicecomposition.views.ServiceCompositionView;
import eu.scasefp7.eclipse.servicecomposition.views.Utils;
public class RunWorkflow {
// constants
private static double VARIABLE_NAME_SIMILARITY_THRESHOLD = 0.5;
private static double MAX_DISTANCE_BETWEEN_SOLUTIONS = 0.1;
private static double VALUE_SIMILARITY_THRESHOLD = 0;
// predicates for special types of branches
private static String[] TRUE_PREDICATES = { "true", "yes" };
private static String[] FALSE_PREDICATES = { "false", "no" };
private static String[] ELSE_PREDICATES = { "else", "otherwise" };
// starting and ending service in the graph
private OwlService startingService = null;
private OwlService endingService = null;
// the selected owlservice
private OwlService currentService;
private TreeViewerColumn columnb;
private TreeViewer treeViewer;
private Composite authParamsComposite;
// eclipse jobs
private Job runWorkflowJob;
protected ServiceCompositionView view;
protected edu.uci.ics.jung.graph.Graph<OwlService, Connector> jungGraph;
public RunWorkflow(ServiceCompositionView view, TreeViewer treeViewer, TreeViewerColumn columnb, Composite authParamsComposite){
this.view = view;
this.jungGraph = view.getJungGraph();
this.treeViewer = treeViewer;
this.columnb = columnb;
this.authParamsComposite = authParamsComposite;
}
public void unhighlightAllNodes() {
// unhighlight all nodes
Graph graph = view.getViewer().getGraphControl();
for (int i = 0; i < graph.getNodes().size(); i++) {
GraphNode graphNode = (GraphNode) graph.getNodes().get(i);
graphNode.unhighlight();
}
}
public String runWorkflow() throws Exception {
final Shell shell = view.getSite().getWorkbenchWindow().getShell();
final Display disp = shell.getDisplay();
runWorkflowJob = new Job("Running Workflow") {
@Override
protected IStatus run(IProgressMonitor monitor) {
monitor.beginTask("Workflow execution in progress ...", IProgressMonitor.UNKNOWN);
try {
final Graph destGraph = view.getViewer().getGraphControl();
disp.syncExec(new Runnable() {
@Override
public void run() {
unhighlightAllNodes();
Utils.cleanOutputs(treeViewer.getTree(), jungGraph);
}
});
Properties prop = new Properties();
String propFileName = "/matcher.properties";
// Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID);
// URL fileURL = bundle.getEntry(propFileName);
URL fileURL = new URL("platform:/plugin/" + Activator.PLUGIN_ID + propFileName);
try {
InputStream inputStream = fileURL.openConnection().getInputStream();
prop.load(inputStream);
// File file = new
// File(FileLocator.resolve(fileURL).toURI());
// InputStream inputStream = new FileInputStream(file);
// prop.load(inputStream);
VARIABLE_NAME_SIMILARITY_THRESHOLD = Double
.parseDouble(prop.getProperty("interpreter.VARIABLE_NAME_SIMILARITY_THRESHOLD"));
MAX_DISTANCE_BETWEEN_SOLUTIONS = Double
.parseDouble(prop.getProperty("interpreter.MAX_DISTANCE_BETWEEN_SOLUTIONS"));
VALUE_SIMILARITY_THRESHOLD = Double
.parseDouble(prop.getProperty("interpreter.VALUE_SIMILARITY_THRESHOLD"));
} catch (Exception e) {
Activator.log("Error occured while trying to load matcher settings from " + propFileName, e);
System.err.println("Error occured while trying to load matcher settings from " + propFileName);
}
edu.uci.ics.jung.graph.Graph<OwlService, Connector> graph = new SparseMultigraph<OwlService, Connector>();
// check if user has cancelled
if (monitor.isCanceled())
return Status.CANCEL_STATUS;
// replace all services in the graph with implementations
HashMap<OwlService, OwlService> implementations = new HashMap<OwlService, OwlService>();
for (OwlService service : jungGraph.getVertices()) {
if (service.getOperation() != null) {
// System.out.println("replacing:
// "+service.getOperation());
OwlService created = new OwlService(service);
Implementation test = new Implementation(service.getOperation());
created.editContent(test);
implementations.put(service, created);
graph.addVertex(created);
// System.out.println("with:
// "+created.getOperation());
} else if (service.getArgument() != null) {
try {
service.getArgument().assertCorrectSubtypes();
} catch (Exception e) {
e.printStackTrace();
}
// They get the previous call value-empty for the
// first time.
OwlService created = new OwlService(service);
created.getArgument().setOwlService(created);
Value value = new Value(service.getArgument());
// value.getElements().clear();
// // Value value =
// // (Value.getValue(service.getArgument()));
// // Clear old values
// value.setValue("");
// value.getElements().removeAll(value.getElements());
// ArrayList<Value> list = value.getElements();
//
// for (Iterator<Value> iterator = list.iterator();
// iterator.hasNext(); ) {
// Value v = iterator.next();
// if (v != null) {
// iterator.remove();
// }
// }
created.editContent(value);
// if (service.getisMatchedIO()) {
// created.setisMatchedIO(true);
// }
implementations.put(service, created);
graph.addVertex(created);
} else {
implementations.put(service, service);
graph.addVertex(service);
}
}
for (Connector connector : jungGraph.getEdges(EdgeType.DIRECTED)) {
OwlService source = implementations.get(connector.getSource());
OwlService target = implementations.get(connector.getTarget());
if (graph.findEdge(source, target) == null)
graph.addEdge(new Connector(source, target, connector.getCondition()), source, target,
EdgeType.DIRECTED);
}
for (Connector connector : jungGraph.getEdges(EdgeType.UNDIRECTED)) {
OwlService source = implementations.get(connector.getSource());
OwlService target = implementations.get(connector.getTarget());
if (graph.findEdge(target, source) == null)
graph.addEdge(new Connector(target, source, connector.getCondition()), target, source,
EdgeType.UNDIRECTED);
}
// check if user has cancelled
if (monitor.isCanceled())
return Status.CANCEL_STATUS;
// initialize variable lists
final ArrayList<Value> inputVariables = new ArrayList<Value>();
final ArrayList<Value> outputVariables = new ArrayList<Value>();
final ArrayList<Value> suboutputVariables = new ArrayList<Value>();
final ArrayList<Value> subinputVariables = new ArrayList<Value>();
final ArrayList<Value> authParamVariables = new ArrayList<Value>();
Vector<Node> nodes = new Vector<Node>();
// ArrayList<Value> directAssignVariables = new
// ArrayList<Value>();
// detect all operations
ArrayList<OwlService> remainingOperations = new ArrayList<OwlService>();
// detect all variables(input and output variables could be
// also detected here)
ArrayList<Value> allVariables = new ArrayList<Value>();
for (OwlService service : graph.getVertices()) {
Operation op = service.getOperation();
if (op != null) {
remainingOperations.add(service);
for (Argument arg : op.getInputs()) {
// if (!allVariables.contains(arg))
allVariables.add((Value) arg);
// if (!inputVariables.contains(arg))
inputVariables.add((Value) arg);
for (Argument sub : arg.getSubtypes()) {
// if (!allVariables.contains(sub)) {
allVariables.add((Value) sub);
// }
getSubtypes(subinputVariables, sub, false);
}
}
for (Argument arg : op.getOutputs()) {
// if (!allVariables.contains(arg)) {
allVariables.add((Value) arg);
// }
// if (!outputVariables.contains(arg)) {
outputVariables.add((Value) arg);
// }
System.out.println("OUTPUT DETECTED\t " + arg);
for (Argument sub : arg.getSubtypes()) {
if (!allVariables.contains(sub)) {
allVariables.add((Value) sub);
}
getSubtypes(suboutputVariables, sub, false);
}
}
// if (!op.getUriParameters().isEmpty()) {
// for (Argument arg : op.getUriParameters()) {
// uriParamVariables.add((Value) arg);
// }
// }
if (!op.getAuthenticationParameters().isEmpty()) {
for (Argument arg : op.getAuthenticationParameters()) {
authParamVariables.add((Value) arg);
}
}
}
// detect starting service
if (service.getType().trim().equals("StartNode")) {
startingService = service;
}
// detect ending service
if (service.getType().trim().equals("EndNode")) {
endingService = service;
}
}
if (startingService == null) {
try {
throw new Exception("StartNode was not detected on graph vertices");
} catch (Exception e1) {
e1.printStackTrace();
}
}
if (endingService == null) {
try {
throw new Exception("EndNode was not detected on graph vertices");
} catch (Exception e1) {
e1.printStackTrace();
}
}
// Check if every node has a path to StartNode and to
// EndNode and also a condition has two output edges in
// order to allow execution.
ArrayList<OwlService> previousList = new ArrayList<OwlService>();
ArrayList<OwlService> nextList = new ArrayList<OwlService>();
for (OwlService service : graph.getVertices()) {
if (service.getType().contains("Action") || service.getType().contains("Condition")) {
if (service.getType().contains("Condition") && (graph.getOutEdges(service).size() < 2)) {
final OwlService unlinked = service;
try {
throw new Exception("\"" + unlinked.getName().toString() + "\""
+ " condition should have two output edges.");
} catch (Exception e1) {
e1.printStackTrace();
}
disp.syncExec(new Runnable() {
@Override
public void run() {
MessageDialog.openInformation(disp.getActiveShell(), "Error occured",
"\"" + unlinked.getName().toString() + "\""
+ " condition should have two output edges.");
}
});
return Status.CANCEL_STATUS;
}
previousList = (new PathFinding(graph).findOperationPath(startingService, service));
if (previousList.get(0) != startingService) {
final OwlService unlinked = previousList.get(0);
try {
throw new Exception("\"" + unlinked.getName().toString() + "\""
+ " has no path to StartNode. Check for unlinked operations.");
} catch (Exception e1) {
e1.printStackTrace();
}
disp.syncExec(new Runnable() {
@Override
public void run() {
MessageDialog.openInformation(disp.getActiveShell(), "Error occured",
"\"" + unlinked.getName().toString() + "\""
+ " has no path to StartNode. Check for unlinked operations.");
}
});
return Status.CANCEL_STATUS;
}
nextList = (new PathFinding(graph).findOperationPath(service, endingService));
if (nextList.get(0) != service) {
final OwlService unlinked = service;
try {
throw new Exception("\"" + unlinked.getName().toString() + "\""
+ " has no path to EndNode. Check for unlinked operations.");
} catch (Exception e1) {
e1.printStackTrace();
}
disp.syncExec(new Runnable() {
@Override
public void run() {
MessageDialog.openInformation(disp.getActiveShell(), "Error occured",
"\"" + unlinked.getName().toString() + "\""
+ " has no path to EndNode. Check for unlinked operations.");
}
});
return Status.CANCEL_STATUS;
}
}
}
currentService = startingService;
// check if user has cancelled
if (monitor.isCanceled())
return Status.CANCEL_STATUS;
// get input values
disp.syncExec(new Runnable() {
@SuppressWarnings("unchecked")
@Override
public void run() {
if (currentService == startingService) {
// fill inputs from right panel
for (int i = 0; i < inputVariables.size(); i++) {
Value var = inputVariables.get(i);
for (int j = 0; j < ((Vector<Node>) columnb.getViewer().getInput()).size(); j++) {
if (((Vector<Node>) columnb.getViewer().getInput()).get(j) instanceof Node) {
Node operation = ((Vector<Node>) columnb.getViewer().getInput()).get(j);
for (int k = 0; k < operation.getSubCategories().size(); k++) {
if (operation.getSubCategories().get(k).getOwlService()
.equals(var.getOwlService())) {
Node node = operation.getSubCategories().get(k);
fillInInputValues(var, node);
}
}
}
}
}
}
}
});
// check if user has cancelled
if (monitor.isCanceled())
return Status.CANCEL_STATUS;
// get uri parameters values
disp.syncExec(new Runnable() {
@Override
public void run() {
if (currentService == startingService) {
// fill Authentication params from right panel
for (int i = 0; i < authParamVariables.size(); i++) {
Value var = authParamVariables.get(i);
for (int j = 0; j < authParamsComposite.getChildren().length; j++) {
if (authParamsComposite.getChildren()[j] instanceof Label) {
Label label = (Label) authParamsComposite.getChildren()[j];
if (label.getText().split("\\*")[0].trim()
.equals(var.getName().toString())) {
if (((Text) authParamsComposite.getChildren()[j + 1]).isEnabled())
var.setValue(((Text) authParamsComposite.getChildren()[j + 1])
.getText());
}
}
}
}
}
}
});
WSDLCaller callWSDL = new WSDLCaller();
// PythonCaller callPython = new PythonCaller();
RAMLCaller callRAML = new RAMLCaller();
OwlService previousNode = null;
// highlight nodes
while (currentService != null) {
long startTime = System.currentTimeMillis();
if (monitor.isCanceled()) {
disp.syncExec(new Runnable() {
@Override
public void run() {
unhighlightAllNodes();
}
});
return Status.CANCEL_STATUS;
}
// Highlight Nodes
disp.syncExec(new Runnable() {
@Override
public void run() {
unhighlightAllNodes();
for (int i = 0; i < destGraph.getNodes().size(); i++) {
GraphNode graphNode = (GraphNode) destGraph.getNodes().get(i);
if (currentService.toString().equals("StartNode")) {
if (((OwlService) ((MyNode) graphNode.getData()).getObject()).toString()
.equals("StartNode")) {
destGraph.setSelection(new GraphItem[] { graphNode });
graphNode.highlight();
}
} else if (currentService.toString().equals("EndNode")) {
if (((OwlService) ((MyNode) graphNode.getData()).getObject()).toString()
.equals("EndNode")) {
destGraph.setSelection(new GraphItem[] { graphNode });
graphNode.highlight();
}
} else if (((OwlService) ((MyNode) graphNode.getData()).getObject())
.equals(currentService)) {
destGraph.setSelection(new GraphItem[] { graphNode });
graphNode.highlight();
}
}
}
});
// call the service
if (currentService.getOperation() != null) {
try {
if (currentService.getOperation().getDomain() == null) {
disp.syncExec(new Runnable() {
@Override
public void run() {
MessageDialog.openInformation(disp.getActiveShell(), "Error occured",
"Action \"" + currentService.getOperation().getName()
+ "\" was not replaced. Please replace it manually with one of the available operations or modify and re-import the storyboard diagram before executing the workflow.");
}
});
throw new Exception("Service " + currentService.getOperation().getName()
+ " is missing its domain");
} else if (currentService.getOperation().getType().equalsIgnoreCase("SOAP"))
// else if
// (!currentService.getOperation().getDomain().isLocal())
callWSDL.callOperation(currentService.getOperation());
else if (currentService.getOperation().getType().equalsIgnoreCase("RESTful")) {
callRAML.callRESTfulOperation(currentService.getOperation());
}
/*
* else callPython.callOperation(currentService.
* getOperation());
*/
} catch (Exception e) {
Activator.log("Error occured while calling "
+ currentService.getOperation().getName().toString(), e);
e.printStackTrace();
disp.syncExec(new Runnable() {
@Override
public void run() {
MessageDialog.openInformation(disp.getActiveShell(), "Invocation error occured",
"An error occured during invocation of \"" + currentService.getName()
+ "\"");
}
});
return Status.CANCEL_STATUS;
}
ArrayList<Value> serviceOutputs = new ArrayList<Value>();
for (Argument arg : currentService.getOperation().getOutputs()) {
serviceOutputs.add((Value) arg);
}
if (!serviceOutputs.isEmpty()) {
disp.syncExec(new Runnable() {
@Override
public void run() {
fillInOutputValues(serviceOutputs, nodes, graph);
OwlService array = null;
for (Argument arg : serviceOutputs) {
for (OwlService service : graph.getVertices()) {
if (service.equals(((Value) arg).getOwlService())) {
try {
service.setContent((Value) arg);
} catch (Exception e) {
Activator.log("Error setting outputs content", e);
e.printStackTrace();
}
}
}
}
Vector<Node> matchedOutputNodes = new Vector<Node>();
for (OwlService service : graph.getVertices()) {
if (service.getisMatchedIO()
&& !service.getArgument().getMatchedInputs().isEmpty()
&& service.getArgument().getBelongsToOperation().getName()
.toString().equals(currentService.getOperation().getName()
.toString())) {
boolean isMemberOfArray = false;
for (Object parent : service.getArgument().getParent()) {
if (parent instanceof Argument)
if (((Argument) parent).isArray()) {
isMemberOfArray = true;
}
}
// if predecessor is array
if (isMemberOfArray || service.getArgument().isArray()) {
OwlService initialArray = getInitialArray(service, graph, false);
int subNum = 0;
for (Argument sub : initialArray.getArgument().getSubtypes()) {
if (sub.getOwlService().getisMatchedIO())
subNum++;
}
boolean arrayIsMatched = false;
if (subNum == initialArray.getArgument().getSubtypes().size()) {
arrayIsMatched = true;
}
boolean successorIsMemberOfArray = false;
for (Argument successor : service.getArgument()
.getMatchedInputs()) {
// for each successor
for (Object parent : successor.getParent()) {
if (parent instanceof Argument)
if (((Argument) parent).isArray()) {
successorIsMemberOfArray = true;
}
}
OwlService successorMatched = null;
for (OwlService suc : graph.getSuccessors(service)) {
successorMatched = suc;
}
// if successor is also
// member of array
if (successorIsMemberOfArray) {
OwlService successorInitialArray = getInitialArray(
successorMatched, graph, true);
// clear matched
// elements
int i = 0;
if (arrayIsMatched && array != initialArray) {
for (Value element : initialArray.getArgument()
.getElements()) {
Value value = new Value(element);
value.setOwlService(successorInitialArray
.getArgument().getOwlService());
value.setName(successorInitialArray.getArgument()
.getType() + "[" + i + "]");
successorInitialArray.getArgument().getElements()
.add(value);
for (Argument input : inputVariables) {
if (input.getOwlService()
.equals(successorInitialArray)) {
ArrayList<Value> list = input.getElements();
for (Iterator<Value> iterator = list
.iterator(); iterator.hasNext();) {
Value v = iterator.next();
if (v != null) {
iterator.remove();
}
}
input.getElements().add(value);
break;
}
}
i++;
}
array = initialArray;
}
} else if (successor.isArray()) {
// successor is
// array
for (Value element : service.getArgument().getElements()) {
successor.getElements().add(element);
}
} else {
// successor is
// object
for (Value val : initialArray.getArgument().getElements()) {
ServiceCompositionView.showOutputs(val, null, matchedOutputNodes, jungGraph);
}
disp.syncExec(new Runnable() {
@Override
public void run() {
MatchOutputDialog dialog = new MatchOutputDialog(
shell);
dialog.setDisp(disp);
dialog.setArrayNodes(matchedOutputNodes);
dialog.setName(successor.getName().toString());
dialog.setOutputService(service);
dialog.create();
dialog.setDialogLocation();
if (dialog.open() == Window.OK) {
String value = dialog.getValue();
((Value) successor).setValue(value);
for (Argument input : inputVariables) {
if (input.getOwlService().equals(
successor.getOwlService())) {
((Value) input).setValue(value);
}
}
} else {
return;
}
}
});
}
}
// if predecessor is object
} else {
boolean successorIsMemberOfArray = false;
for (Argument successor : service.getArgument()
.getMatchedInputs()) {
// for each successor
for (Object parent : successor.getParent()) {
if (parent instanceof Argument)
if (((Argument) parent).isArray()) {
successorIsMemberOfArray = true;
}
}
if (successor.isArray()) {
Argument in;
try {
in = new Argument(
successor.getName().toString() + "[0]", "",
successor.isTypeOf(), false,
successor.isNative(), successor.getSubtypes());
in.setOwlService(successor.getOwlService());
Value value = new Value(in);
value.setValue(
((Value) service.getArgument()).getValue());
successor.getElements().add(0, value);
} catch (Exception e) {
// Auto-generated
// catch block
e.printStackTrace();
}
} else if (successorIsMemberOfArray) {
// TODO complex
// array
} else {
((Value) successor).setValue(
((Value) service.getArgument()).getValue());
for (Argument input : inputVariables) {
if (input.getOwlService()
.equals(successor.getOwlService())) {
((Value) input).setValue(
((Value) service.getArgument()).getValue());
}
}
}
}
}
}
}
}
});
}
}
// select next service
ArrayList<Value> previousServiceOutVariables = new ArrayList<Value>();
HashMap<OwlService, Connector> possibleServices = new HashMap<OwlService, Connector>();
for (OwlService next : graph.getSuccessors(currentService))
if (next.getArgument() == null)
possibleServices.put(next, graph.findEdge(currentService, next));
previousNode = currentService;
for (OwlService previousOperation : graph.getPredecessors(currentService)) {
if (previousOperation.getOperation() != null) {
for (Argument output : previousOperation.getOperation().getOutputs()) {
if (!output.isArray()) {
if (output.getSubtypes().isEmpty()) {
previousServiceOutVariables.add((Value) output);
}
for (Argument sub : output.getSubtypes()) {
if (!sub.isArray()) {
getSubtypes(previousServiceOutVariables, sub, true);
}
}
}
}
}
}
currentService = checkCondition(currentService, possibleServices, previousServiceOutVariables);
// Update matched variable values 2
// if (currentService != null) {
// if (currentService.getOperation() != null) {
// for (OwlService service : graph.getVertices()) {
// boolean isMatched = false;
// for (int i = 0; i <
// currentService.getOperation().getInputs().size();
// i++) {
// if (service.getArgument() != null) {
// for (OwlService successor :
// graph.getSuccessors(service)) {
// if (successor.getArgument() != null) {
// if (successor.getisMatchedIO() &&
// service.getisMatchedIO()) {
// isMatched = true;
// }
// if (successor.getArgument()
// .getName().toString().equals(currentService.getOperation()
// .getInputs().get(i).getName().toString())
// && isMatched) {
// ((Value)
// currentService.getOperation().getInputs().get(i))
// .setValue(((Value)
// service.getArgument()).getValue());
// }
// }
// }
//
// }
// }
// }
// }
// }
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
if (elapsedTime < 500) {
try {
Thread.sleep(500 - elapsedTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
if (!outputVariables.isEmpty()) {
disp.syncExec(new Runnable() {
@Override
public void run() {
// fillInOutputValues(outputVariables);
treeViewer.setInput(nodes);
}
});
}
monitor.done();
return Status.OK_STATUS;
} catch (Exception ex) {
Activator.log("Error while running the workflow", ex);
ex.printStackTrace();
monitor.done();
return Status.CANCEL_STATUS;
} finally {
monitor.done();
}
}
};
runWorkflowJob.schedule();
return "";
}
public static OwlService getInitialArray(OwlService matchedVar,
edu.uci.ics.jung.graph.Graph<OwlService, Connector> graph, boolean isSuccessor) {
OwlService initialArray = matchedVar;
if (isSuccessor) {
for (OwlService successor : graph.getSuccessors(matchedVar)) {
if (successor.getArgument() != null) {
if (successor.getArgument().isArray()) {
initialArray = getInitialArray(successor, graph, true);
} else {
break;
}
} else {
break;
}
}
} else {
for (OwlService predecessor : graph.getPredecessors(matchedVar)) {
if (predecessor.getArgument() != null) {
if (predecessor.getArgument().isArray()) {
initialArray = getInitialArray(predecessor, graph, false);
} else {
break;
}
} else {
break;
}
}
}
return initialArray;
}
private ArrayList<Value> getSubtypes(ArrayList<Value> suboutputVariables, Argument sub, boolean noObjects) {
if (!suboutputVariables.contains(sub)) {
if (noObjects) {
if (sub.getSubtypes().isEmpty()) {
suboutputVariables.add((Value) sub);
}
} else {
suboutputVariables.add((Value) sub);
}
}
if (!sub.getSubtypes().isEmpty()) {
for (Argument subsub : sub.getSubtypes()) {
if (noObjects) {
if (!sub.isArray()) {
getSubtypes(suboutputVariables, subsub, true);
}
} else {
getSubtypes(suboutputVariables, subsub, true);
}
}
}
return suboutputVariables;
}
private void fillInOutputValues(ArrayList<Value> list, Vector<Node> nodes,
edu.uci.ics.jung.graph.Graph<OwlService, Connector> graph) {
for (int i = 0; i < list.size(); i++) {
Value var = list.get(i);
ServiceCompositionView.showOutputs(var, null, nodes, graph);
}
}
private void fillInInputValues(Value var, Node node) {
String[] datatypes = new String[] { "string", "long", "int", "float", "double", "dateTime", "boolean" };
if (((Value) var).isArray() && RAMLCaller.stringIsItemFromList(((Value) var).getType(), datatypes)) {
for (int k = 0; k < node.getSubCategories().size(); k++) {
if (node.getSubCategories().get(k) != null) {
Argument in;
try {
in = new Argument(var.getName().toString() + "[" + k + "]", "", var.isTypeOf(), false,
var.isNative(), var.getSubtypes());
for (Argument arg : var.getMatchedInputs()) {
in.getMatchedInputs().add(arg);
}
in.setOwlService(var.getOwlService());
Value value = new Value(in);
// Value value = Value.getValue(out);
value.setValue(node.getSubCategories().get(k).getValue());
var.getElements().add(value);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} else if (((Value) var).isArray() && !RAMLCaller.stringIsItemFromList(((Value) var).getType(), datatypes)) {
for (int k = 0; k < node.getSubCategories().size(); k++) {
// create and add site[0]element, device[0]
Argument in = new Argument(var);
in.setOwlService(var.getOwlService());
in.setName(var.getType() + "[" + k + "]");
Value value = new Value(in);
for (Argument sub : var.getSubtypes()) {
if (sub.isArray()) {
Argument out1 = new Argument(sub);
out1.setOwlService(sub.getOwlService());
out1.setName(sub.getName().toString());
Value value2 = new Value(out1);
Node object = (Node) node.getSubCategories().get(k);
for (int i = 0; i < object.getSubCategories().size(); i++) {
int index = object.getSubCategories().get(i).getName().toString().indexOf('[');
if (value2.getName().toString().equals(
object.getSubCategories().get(i).getName().toString().substring(0, index - 1))) {
fillInInputValues(value2, object.getSubCategories().get(i));
value.getElements().add(value2);
break;
}
}
} else {
// create device
Argument in1 = new Argument(sub);
in1.setOwlService(sub.getOwlService());
in1.setName(sub.getName().toString());
Value value1 = new Value(in1);
Node object = (Node) node.getSubCategories().get(k);
for (int i = 0; i < object.getSubCategories().size(); i++) {
int index = object.getSubCategories().get(i).getName().toString().indexOf('[');
if (value1.getName().toString().equals(
object.getSubCategories().get(i).getName().toString().substring(0, index - 1))) {
fillInInputValues(value1, (object.getSubCategories().get(i)));
value.getElements().add(value1);
break;
}
}
}
}
var.getElements().add(value);
}
} else if (!((Value) var).isArray() && !RAMLCaller.stringIsItemFromList(((Value) var).getType(), datatypes)) {
for (int k = 0; k < node.getSubCategories().size(); k++) {
for (Argument sub : var.getSubtypes()) {
int index = node.getSubCategories().get(k).getName().toString().indexOf('[');
if (((Value) sub).getName().toString()
.equals(node.getSubCategories().get(k).getName().toString().substring(0, index - 1))) {
fillInInputValues((Value) sub, (Node) node.getSubCategories().get(k));
}
}
}
} else {
var.setValue(node.getValue());
}
}
private OwlService checkCondition(OwlService source, HashMap<OwlService, Connector> candidates,
ArrayList<Value> allVariables) {
double prevThreshold = Similarity.levenshteinThreshold;
Similarity.levenshteinThreshold = 0;
Iterator<Entry<OwlService, Connector>> it = candidates.entrySet().iterator();
ArrayList<OwlService> resultCandidates = new ArrayList<OwlService>();
HashMap<OwlService, String> text = new HashMap<OwlService, String>();
double bestVal = VALUE_SIMILARITY_THRESHOLD;
while (it.hasNext()) {
Map.Entry<OwlService, Connector> pair = (Map.Entry<OwlService, Connector>) it.next();
double val = checkSingleCondition(source, pair.getValue(), pair.getKey(), allVariables);
if (val >= bestVal) {
if (val >= bestVal + MAX_DISTANCE_BETWEEN_SOLUTIONS) {
resultCandidates.clear();
bestVal = val;
}
resultCandidates.add(pair.getKey());
text.put(pair.getKey(), pair.getValue().toString());
}
}
if ((resultCandidates.isEmpty() || resultCandidates.size() > 1) && !candidates.isEmpty()) {
ArrayList<OwlService> tempCandidates = new ArrayList<OwlService>();
it = candidates.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<OwlService, Connector> pair = (Map.Entry<OwlService, Connector>) it.next();
for (String predicate : ELSE_PREDICATES)
if (Similarity.comparePredicates(pair.getValue().getCondition(), predicate)) {
tempCandidates.add(pair.getKey());
break;
}
}
if (tempCandidates.size() == 1)
resultCandidates = tempCandidates;
}
Similarity.levenshteinThreshold = prevThreshold;
if (resultCandidates.isEmpty() && !candidates.isEmpty() && VALUE_SIMILARITY_THRESHOLD != 0) {
System.out.println("TOO STRICT CONDITIONS\t trying again with VALUE_SIMILARITY_THRESHOLD to zero");
double temp = VALUE_SIMILARITY_THRESHOLD;
VALUE_SIMILARITY_THRESHOLD = 0;
OwlService result = checkCondition(source, candidates, allVariables);
VALUE_SIMILARITY_THRESHOLD = temp;
return result;
}
Similarity.levenshteinThreshold = prevThreshold;
if (resultCandidates.size() == 1)
return resultCandidates.get(0);
return (OwlService) UserInput.getSelection(source.toString(), resultCandidates, text);
}
/**
* <h1>checkSingleCondition</h1> This function returns a weight in range
* [0,1] that represents the match of the given expression to the given
* condition.<br/>
* This function also tries to extract numeric data in order to compare
* expressions in case it yield better results.
*
* @param source
* : an OwlService that represents the expression to be evaluated
* @param condition
* : a Connector that represents the condition to be checked
* @param candidate
* : the next OwlService to be reached if the given Connector is
* selected
* @param allVariables
* : a list of all possible variables
* @return a value in range [0,1]
*/
private double checkSingleCondition(OwlService source, Connector condition, OwlService candidate,
ArrayList<Value> allVariables) {
if (condition.toString().isEmpty())
return 1;
String sourceText = source.toString();
String conditionText = condition.getCondition();
boolean negativeLogic = false;
boolean logicResult = false;
for (String predicate : FALSE_PREDICATES)
if (Similarity.comparePredicates(conditionText, predicate)) {
negativeLogic = true;
logicResult = true;
break;
}
for (String predicate : TRUE_PREDICATES)
if (Similarity.comparePredicates(conditionText, predicate)) {
logicResult = true;
break;
}
double compareMode = 0;
boolean equality = false;
if (logicResult) {
int index;
if ((index = sourceText.indexOf("==")) != -1) {
conditionText = sourceText.substring(index + 2);
sourceText = sourceText.substring(0, index);
equality = true;
} else if ((index = sourceText.indexOf("!=")) != -1) {
conditionText = sourceText.substring(index + 2);
sourceText = sourceText.substring(0, index);
negativeLogic = !negativeLogic;
equality = true;
} else if ((index = sourceText.indexOf("=")) != -1) {
conditionText = sourceText.substring(index + 1);
sourceText = sourceText.substring(0, index);
equality = true;
} else if ((index = sourceText.indexOf("<")) != -1) {
conditionText = sourceText.substring(index + 1);
sourceText = sourceText.substring(0, index);
compareMode = 1;
} else if ((index = sourceText.indexOf(">")) != -1) {
conditionText = sourceText.substring(index + 1);
sourceText = sourceText.substring(0, index);
compareMode = -1;
}
}
String replacableCondition = conditionText.replaceAll("[^\\.0123456789]", "");
if (replacableCondition.isEmpty()) {
replacableCondition = sourceText.replaceAll("[^\\.0123456789]", "");
if (!replacableCondition.isEmpty()) {
String temp = sourceText;
sourceText = conditionText;
conditionText = temp;
compareMode = -compareMode;
}
}
Value bestValue = null;
double bestMatch = VARIABLE_NAME_SIMILARITY_THRESHOLD;
for (Value val : allVariables) {
if (val.getValue() != null) {
if (val.getValue().replaceAll("[^\\.0123456789]", "").isEmpty() != conditionText
.replaceAll("[^\\.0123456789]", "").isEmpty())
continue;
double match = Similarity.similarity(val.getName().toString(), sourceText);
if (match >= bestMatch) {
bestMatch = match;
bestValue = val;
}
}
}
if (bestValue == null)
return 1;
boolean success = true;
double conditionValue = Double.POSITIVE_INFINITY - 1;
double variableValue = 0;
try {
conditionValue = Double.parseDouble(conditionText.replaceAll("[^\\.0123456789]", ""));// careful
// to
// have
// this
// first,
// so
// that
// if
// it
// fails
// POSITIVE_INFINITY
// calculations
// work
// as
// intended
variableValue = Double.parseDouble(bestValue.getValue());
} catch (Exception e) {
success = false;
}
double retValue = 0;
if (success) {
retValue = (conditionValue == variableValue) ? 1
: (Math.abs(conditionValue - variableValue)
/ (Math.abs(conditionValue) + Math.abs(variableValue) + 1));
if (compareMode > 0)
retValue = conditionValue > variableValue ? 1 : 0;
else if (compareMode < 0)
retValue = conditionValue < variableValue ? 1 : 0;
if (negativeLogic)
retValue = 1 - retValue;
}
double retValue2 = Similarity.similarity(conditionText, bestValue.getValue());
// / (conditionText.length() * bestValue.getValue().length() + 1);
if (negativeLogic && equality)
retValue2 = 1 - retValue2;
// System.out.println(sourceText+" vs "+bestValue.getName()+" =
// "+Math.max(retValue,
// retValue2));
return Math.max(retValue, retValue2);
}
public class Implementation extends Operation {
/**
* Generates an implementation out of an operation by converting all
* variables into <code>Value</code> instances using
* <code>Value.getValue</code>.
*/
public Implementation(Operation operation) {
// super(operation.getName().toString(), operation.getDomain());
super(operation);
for (Argument input : operation.getInputs())
getInputs().add(new Value(input));
for (Argument output : operation.getOutputs())
getOutputs().add(new Value(output));
// for (Argument uriParam : operation.getUriParameters())
// getUriParameters().add(new Value(uriParam));
for (Argument authParam : operation.getAuthenticationParameters())
getAuthenticationParameters().add(new Value(authParam));
}
}
}
|
Fix in the MatchedOutputs dialog 2.
|
eu.scasefp7.eclipse.servicecomposition/src/eu/scasefp7/eclipse/servicecomposition/toolbar/RunWorkflow.java
|
Fix in the MatchedOutputs dialog 2.
|
<ide><path>u.scasefp7.eclipse.servicecomposition/src/eu/scasefp7/eclipse/servicecomposition/toolbar/RunWorkflow.java
<ide> protected ServiceCompositionView view;
<ide> protected edu.uci.ics.jung.graph.Graph<OwlService, Connector> jungGraph;
<ide>
<del>
<del> public RunWorkflow(ServiceCompositionView view, TreeViewer treeViewer, TreeViewerColumn columnb, Composite authParamsComposite){
<add> public RunWorkflow(ServiceCompositionView view, TreeViewer treeViewer, TreeViewerColumn columnb,
<add> Composite authParamsComposite) {
<ide> this.view = view;
<ide> this.jungGraph = view.getJungGraph();
<ide> this.treeViewer = treeViewer;
<ide> this.columnb = columnb;
<ide> this.authParamsComposite = authParamsComposite;
<ide> }
<del>
<add>
<ide> public void unhighlightAllNodes() {
<ide> // unhighlight all nodes
<ide> Graph graph = view.getViewer().getGraphControl();
<ide> try {
<ide> service.getArgument().assertCorrectSubtypes();
<ide> } catch (Exception e) {
<del>
<add>
<ide> e.printStackTrace();
<ide> }
<ide> // They get the previous call value-empty for the
<ide> throw new Exception("StartNode was not detected on graph vertices");
<ide>
<ide> } catch (Exception e1) {
<del>
<add>
<ide> e1.printStackTrace();
<ide> }
<ide> }
<ide> try {
<ide> throw new Exception("EndNode was not detected on graph vertices");
<ide> } catch (Exception e1) {
<del>
<add>
<ide> e1.printStackTrace();
<ide> }
<ide> }
<ide> throw new Exception("\"" + unlinked.getName().toString() + "\""
<ide> + " condition should have two output edges.");
<ide> } catch (Exception e1) {
<del>
<add>
<ide> e1.printStackTrace();
<ide> }
<ide>
<ide> throw new Exception("\"" + unlinked.getName().toString() + "\""
<ide> + " has no path to StartNode. Check for unlinked operations.");
<ide> } catch (Exception e1) {
<del>
<add>
<ide> e1.printStackTrace();
<ide> }
<ide> disp.syncExec(new Runnable() {
<ide> throw new Exception("\"" + unlinked.getName().toString() + "\""
<ide> + " has no path to EndNode. Check for unlinked operations.");
<ide> } catch (Exception e1) {
<del>
<add>
<ide> e1.printStackTrace();
<ide> }
<ide>
<ide>
<ide> // successor is
<ide> // object
<del>
<del> for (Value val : initialArray.getArgument().getElements()) {
<del> ServiceCompositionView.showOutputs(val, null, matchedOutputNodes, jungGraph);
<del> }
<add> OwlService initialInput = getInitialInput(service, graph);
<add>
<add> ServiceCompositionView.showOutputs(
<add> (Value) initialInput.getArgument(), null,
<add> matchedOutputNodes, jungGraph);
<ide>
<ide> disp.syncExec(new Runnable() {
<ide> @Override
<ide> ((Value) service.getArgument()).getValue());
<ide> successor.getElements().add(0, value);
<ide> } catch (Exception e) {
<del>
<add>
<ide> // Auto-generated
<ide> // catch block
<ide> e.printStackTrace();
<ide> try {
<ide> Thread.sleep(500 - elapsedTime);
<ide> } catch (InterruptedException e) {
<del>
<add>
<ide> e.printStackTrace();
<ide> }
<ide> }
<ide> public void run() {
<ide> // fillInOutputValues(outputVariables);
<ide> treeViewer.setInput(nodes);
<del>
<add>
<ide> }
<ide> });
<ide>
<ide> return initialArray;
<ide> }
<ide>
<add> public static OwlService getInitialInput(OwlService matchedVar,
<add> edu.uci.ics.jung.graph.Graph<OwlService, Connector> graph) {
<add> OwlService initialInput = matchedVar;
<add>
<add> for (OwlService predecessor : graph.getPredecessors(matchedVar)) {
<add> if (predecessor.getArgument() != null) {
<add>
<add> initialInput = getInitialInput(predecessor, graph);
<add>
<add> } else {
<add> break;
<add> }
<add> }
<add>
<add> return initialInput;
<add> }
<add>
<ide> private ArrayList<Value> getSubtypes(ArrayList<Value> suboutputVariables, Argument sub, boolean noObjects) {
<ide> if (!suboutputVariables.contains(sub)) {
<ide> if (noObjects) {
<ide> value.setValue(node.getSubCategories().get(k).getValue());
<ide> var.getElements().add(value);
<ide> } catch (Exception e) {
<del>
<add>
<ide> e.printStackTrace();
<ide> }
<ide> }
|
|
Java
|
mit
|
6a23523d456938c785784d6aef0078184958008a
| 0 |
curiosone-bot/curiosone-core
|
package com.github.bot.curiosone.core.extraction;
import com.github.bot.curiosone.core.nlp.Phrase;
import com.github.bot.curiosone.core.nlp.Token;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Precomputed answers to some common conversational phrases.
*/
public class Conversation {
private static String conversationsPath = "/conversation/conversation.txt";
/** Path of the database containing known answers. */
/** Map from recognized tokens to possible phrases given in output. */
private static LinkedHashMap<String, String[]> knownQuestions;
/**
* Private constructor.
*/
private Conversation() { }
/**
* Loads the known answers in memory.
*/
private static void loadSentences() {
knownQuestions = new LinkedHashMap<>();
Path path = null;
try {
URL resource = Conversation.class.getResource(conversationsPath);
path = Paths.get(resource.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
try (Stream<String> stream = Files.lines(path)) {
stream.forEach(line -> {
int splitIndex = line.indexOf(":");
String key = line.substring(0, splitIndex);
String[] values = line.substring(splitIndex + 1, line.length()).split("\t");
knownQuestions.put(key, values);
});
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Checks if the given input is present in our known answers.
*
* @param phrase phrase given by user's input
* @return answer if the input is known
*/
public static Optional<BrainResponse> getAnswer(Phrase phrase) {
if (knownQuestions == null) {
loadSentences();
}
List<String> lemmas = phrase.getTokens()
.stream()
.map(Token::getLemma)
.collect(Collectors.toList());
for (Map.Entry<String, String[]> entry : knownQuestions.entrySet()) {
boolean isKnown = true;
for (String s : entry.getKey().split("\t")) {
if (!lemmas.contains(s)) {
isKnown = false;
break;
}
}
if (isKnown) {
int randpos = (int)(Math.random() * entry.getValue().length);
return Optional.of(new BrainResponse(entry.getValue()[randpos], ""));
}
}
return Optional.empty();
}
}
|
src/main/java/com/github/bot/curiosone/core/extraction/Conversation.java
|
package com.github.bot.curiosone.core.extraction;
import com.github.bot.curiosone.core.nlp.Phrase;
import com.github.bot.curiosone.core.nlp.Token;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Precomputed answers to some common conversational phrases.
*/
public class Conversation {
private static String conversationsPath = "/conversation/conversation.txt";
/** Path of the database containing known answers. */
/** Map from recognized tokens to possible phrases given in output. */
private static Map<String[], String[]> knownQuestions;
/**
* Private constructor.
*/
private Conversation() { }
/**
* Loads the known answers in memory.
*/
private static void loadSentences() {
knownQuestions = new HashMap<>();
Path path = null;
try {
URL resource = Conversation.class.getResource(conversationsPath);
path = Paths.get(resource.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
try (Stream<String> stream = Files.lines(path)) {
stream.forEach(line -> {
int splitIndex = line.indexOf(":");
String[] key = line.substring(0, splitIndex).split("\t");
String[] values = line.substring(splitIndex + 1, line.length()).split("\t");
knownQuestions.put(key, values);
});
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Checks if the given input is present in our known answers.
*
* @param phrase phrase given by user's input
* @return answer if the input is known
*/
public static Optional<BrainResponse> getAnswer(Phrase phrase) {
if (knownQuestions == null) {
loadSentences();
}
List<String> lemmas = phrase.getTokens()
.stream()
.map(Token::getLemma)
.collect(Collectors.toList());
for (Map.Entry<String[], String[]> entry : knownQuestions.entrySet()) {
boolean isKnown = true;
for (String s : entry.getKey()) {
if (!lemmas.contains(s)) {
isKnown = false;
break;
}
}
if (isKnown) {
int randpos = (int)(Math.random() * entry.getValue().length);
return Optional.of(new BrainResponse(entry.getValue()[randpos], ""));
}
}
return Optional.empty();
}
}
|
Keep set ordered by the insertion order
|
src/main/java/com/github/bot/curiosone/core/extraction/Conversation.java
|
Keep set ordered by the insertion order
|
<ide><path>rc/main/java/com/github/bot/curiosone/core/extraction/Conversation.java
<ide> import java.nio.file.Files;
<ide> import java.nio.file.Path;
<ide> import java.nio.file.Paths;
<del>import java.util.HashMap;
<add>import java.util.Collections;
<add>import java.util.LinkedHashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> import java.util.Optional;
<ide>
<ide>
<ide> /** Map from recognized tokens to possible phrases given in output. */
<del> private static Map<String[], String[]> knownQuestions;
<add> private static LinkedHashMap<String, String[]> knownQuestions;
<ide>
<ide> /**
<ide> * Private constructor.
<ide> * Loads the known answers in memory.
<ide> */
<ide> private static void loadSentences() {
<del> knownQuestions = new HashMap<>();
<add> knownQuestions = new LinkedHashMap<>();
<ide> Path path = null;
<ide> try {
<ide> URL resource = Conversation.class.getResource(conversationsPath);
<ide> try (Stream<String> stream = Files.lines(path)) {
<ide> stream.forEach(line -> {
<ide> int splitIndex = line.indexOf(":");
<del> String[] key = line.substring(0, splitIndex).split("\t");
<add> String key = line.substring(0, splitIndex);
<ide> String[] values = line.substring(splitIndex + 1, line.length()).split("\t");
<ide> knownQuestions.put(key, values);
<ide> });
<ide> .map(Token::getLemma)
<ide> .collect(Collectors.toList());
<ide>
<del> for (Map.Entry<String[], String[]> entry : knownQuestions.entrySet()) {
<add> for (Map.Entry<String, String[]> entry : knownQuestions.entrySet()) {
<ide> boolean isKnown = true;
<ide>
<del> for (String s : entry.getKey()) {
<add> for (String s : entry.getKey().split("\t")) {
<ide> if (!lemmas.contains(s)) {
<ide> isKnown = false;
<ide> break;
|
|
Java
|
apache-2.0
|
9b50235ed9806805bd7ade67fb9beb387241621a
| 0 |
JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,jacksonokuhn/dataverse,jacksonokuhn/dataverse,jacksonokuhn/dataverse,JayanthyChengan/dataverse,jacksonokuhn/dataverse,jacksonokuhn/dataverse,JayanthyChengan/dataverse,jacksonokuhn/dataverse,jacksonokuhn/dataverse,JayanthyChengan/dataverse,jacksonokuhn/dataverse
|
package edu.harvard.iq.dataverse.api;
import com.jayway.restassured.RestAssured;
import static com.jayway.restassured.RestAssured.given;
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.path.json.JsonPath;
import com.jayway.restassured.response.Response;
import java.util.UUID;
import java.util.logging.Logger;
import javax.json.Json;
import javax.json.JsonObjectBuilder;
import static javax.ws.rs.core.Response.Status.OK;
import static junit.framework.Assert.assertEquals;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
import org.junit.BeforeClass;
import org.junit.Test;
public class BuiltinUsersIT {
private static final Logger logger = Logger.getLogger(BuiltinUsersIT.class.getCanonicalName());
private static final String builtinUserKey = "burrito";
private static final String idKey = "id";
private static final String usernameKey = "userName";
private static final String emailKey = "email";
@BeforeClass
public static void setUp() {
RestAssured.baseURI = UtilIT.getRestAssuredBaseUri();
}
@Test
public void testCreateTimeAndApiLastUse() {
Response createUser = UtilIT.createRandomUser();
createUser.prettyPrint();
createUser.then().assertThat()
.statusCode(OK.getStatusCode());
String username = UtilIT.getUsernameFromResponse(createUser);
String apiToken = UtilIT.getApiTokenFromResponse(createUser);
Response getUserAsJson = UtilIT.getAuthenticatedUser(username, apiToken);
getUserAsJson.prettyPrint();
getUserAsJson.then().assertThat()
// Checking that it's 2017 or whatever. Not y3k compliant!
.body("data.createdTime", startsWith("2"))
.body("data.authenticationProviderId", equalTo("builtin"))
.statusCode(OK.getStatusCode());
Response getUserAsJsonAgain = UtilIT.getAuthenticatedUser(username, apiToken);
getUserAsJsonAgain.prettyPrint();
getUserAsJsonAgain.then().assertThat()
// ApiUseTime should be null, user has not used API yet here
.body("data.lastApiUseTime", equalTo(null))
.statusCode(OK.getStatusCode());
}
@Test
public void testLastApiUse() {
Response createApiUser = UtilIT.createRandomUser();
String apiUsername = UtilIT.getUsernameFromResponse(createApiUser);
String secondApiToken = UtilIT.getApiTokenFromResponse(createApiUser);
Response createDataverse = UtilIT.createRandomDataverse(secondApiToken);
String alias = UtilIT.getAliasFromResponse(createDataverse);
Response createDatasetViaApi = UtilIT.createRandomDatasetViaNativeApi(alias, secondApiToken);
Response getApiUserAsJson = UtilIT.getAuthenticatedUser(apiUsername, secondApiToken);
getApiUserAsJson.prettyPrint();
getApiUserAsJson.then().assertThat()
// Checking that it's 2017 or whatever. Not y3k compliant!
.body("data.lastApiUseTime", startsWith("2"))
.statusCode(OK.getStatusCode());
}
@Test
public void testUserId() {
String email = null;
Response createUserResponse = createUser(getRandomUsername(), "firstName", "lastName", email);
createUserResponse.prettyPrint();
assertEquals(200, createUserResponse.getStatusCode());
JsonPath createdUser = JsonPath.from(createUserResponse.body().asString());
int builtInUserIdFromJsonCreateResponse = createdUser.getInt("data.user." + idKey);
int authenticatedUserIdFromJsonCreateResponse = createdUser.getInt("data.authenticatedUser." + idKey);
String username = createdUser.getString("data.user." + usernameKey);
Response getUserResponse = getUserFromDatabase(username);
getUserResponse.prettyPrint();
assertEquals(200, getUserResponse.getStatusCode());
JsonPath getUserJson = JsonPath.from(getUserResponse.body().asString());
int userIdFromDatabase = getUserJson.getInt("data.id");
Response deleteUserResponse = deleteUser(username);
assertEquals(200, deleteUserResponse.getStatusCode());
deleteUserResponse.prettyPrint();
System.out.println(userIdFromDatabase + " was the id from the database");
System.out.println(builtInUserIdFromJsonCreateResponse + " was the id of the BuiltinUser from JSON response on create");
System.out.println(authenticatedUserIdFromJsonCreateResponse + " was the id of the AuthenticatedUser from JSON response on create");
assertEquals(userIdFromDatabase, authenticatedUserIdFromJsonCreateResponse);
}
@Test
public void testLeadingWhitespaceInEmailAddress() {
String randomUsername = getRandomUsername();
String email = " " + randomUsername + "@mailinator.com";
Response createUserResponse = createUser(randomUsername, "firstName", "lastName", email);
createUserResponse.prettyPrint();
assertEquals(200, createUserResponse.statusCode());
String emailActual = JsonPath.from(createUserResponse.body().asString()).getString("data.user." + emailKey);
// the backend will trim the email address
String emailExpected = email.trim();
assertEquals(emailExpected, emailActual);
}
@Test
public void testLeadingWhitespaceInUsername() {
String randomUsername = " " + getRandomUsername();
String email = randomUsername + "@mailinator.com";
Response createUserResponse = createUser(randomUsername, "firstName", "lastName", email);
createUserResponse.prettyPrint();
assertEquals(400, createUserResponse.statusCode());
}
@Test
public void testBadCharacterInUsername() {
String randomUsername = getRandomUsername() + "/";
String email = randomUsername + "@mailinator.com";
Response createUserResponse = createUser(randomUsername, "firstName", "lastName", email);
createUserResponse.prettyPrint();
assertEquals(400, createUserResponse.statusCode());
}
@Test
public void testAccentInUsername() {
String randomUsername = getRandomUsername();
String randomUsernameWeird = "õÂ" + randomUsername;
String email = randomUsername + "@mailinator.com";
Response createUserResponse = createUser(randomUsernameWeird, "firstName", "lastName", email);
createUserResponse.prettyPrint();
assertEquals(400, createUserResponse.statusCode());
}
@Test
public void testLogin() {
String usernameToCreate = getRandomUsername();
String email = null;
Response createUserResponse = createUser(usernameToCreate, "firstName", "lastName", email);
createUserResponse.prettyPrint();
assertEquals(200, createUserResponse.getStatusCode());
JsonPath createdUser = JsonPath.from(createUserResponse.body().asString());
String createdUsername = createdUser.getString("data.user." + usernameKey);
assertEquals(usernameToCreate, createdUsername);
String createdToken = createdUser.getString("data.apiToken");
logger.info(createdToken);
Response getApiTokenUsingUsername = getApiTokenUsingUsername(usernameToCreate, usernameToCreate);
getApiTokenUsingUsername.prettyPrint();
assertEquals(200, getApiTokenUsingUsername.getStatusCode());
String retrievedTokenUsingUsername = JsonPath.from(getApiTokenUsingUsername.asString()).getString("data.message");
assertEquals(createdToken, retrievedTokenUsingUsername);
Response failExpected = getApiTokenUsingUsername("junk", "junk");
failExpected.prettyPrint();
assertEquals(400, failExpected.getStatusCode());
if (BuiltinUsers.retrievingApiTokenViaEmailEnabled) {
Response getApiTokenUsingEmail = getApiTokenUsingEmail(usernameToCreate + "@mailinator.com", usernameToCreate);
getApiTokenUsingEmail.prettyPrint();
assertEquals(200, getApiTokenUsingEmail.getStatusCode());
String retrievedTokenUsingEmail = JsonPath.from(getApiTokenUsingEmail.asString()).getString("data.message");
assertEquals(createdToken, retrievedTokenUsingEmail);
}
}
private Response createUser(String username, String firstName, String lastName, String email) {
String userAsJson = getUserAsJsonString(username, firstName, lastName, email);
String password = getPassword(userAsJson);
Response response = given()
.body(userAsJson)
.contentType(ContentType.JSON)
.post("/api/builtin-users?key=" + builtinUserKey + "&password=" + password);
return response;
}
private Response getApiTokenUsingUsername(String username, String password) {
Response response = given()
.contentType(ContentType.JSON)
.get("/api/builtin-users/" + username + "/api-token?username=" + username + "&password=" + password);
return response;
}
private Response getApiTokenUsingEmail(String email, String password) {
Response response = given()
.contentType(ContentType.JSON)
.get("/api/builtin-users/" + email + "/api-token?username=" + email + "&password=" + password);
return response;
}
private Response getUserFromDatabase(String username) {
Response getUserResponse = given()
.get("/api/admin/authenticatedUsers/" + username + "/");
return getUserResponse;
}
private static Response deleteUser(String username) {
Response deleteUserResponse = given()
.delete("/api/admin/authenticatedUsers/" + username + "/");
return deleteUserResponse;
}
private static String getRandomUsername() {
return UUID.randomUUID().toString().substring(0, 8);
}
private static String getUserAsJsonString(String username, String firstName, String lastName, String email) {
JsonObjectBuilder builder = Json.createObjectBuilder();
builder.add(usernameKey, username);
builder.add("firstName", firstName);
builder.add("lastName", lastName);
if (email == null) {
builder.add(emailKey, getEmailFromUserName(username));
} else {
builder.add(emailKey, email);
}
String userAsJson = builder.build().toString();
logger.fine("User to create: " + userAsJson);
return userAsJson;
}
private static String getPassword(String jsonStr) {
String password = JsonPath.from(jsonStr).get(usernameKey);
return password;
}
private static String getEmailFromUserName(String username) {
return username + "@mailinator.com";
}
}
|
src/test/java/edu/harvard/iq/dataverse/api/BuiltinUsersIT.java
|
package edu.harvard.iq.dataverse.api;
import com.jayway.restassured.RestAssured;
import static com.jayway.restassured.RestAssured.given;
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.path.json.JsonPath;
import com.jayway.restassured.response.Response;
import java.util.UUID;
import java.util.logging.Logger;
import javax.json.Json;
import javax.json.JsonObjectBuilder;
import static javax.ws.rs.core.Response.Status.OK;
import static junit.framework.Assert.assertEquals;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
import org.junit.BeforeClass;
import org.junit.Test;
public class BuiltinUsersIT {
private static final Logger logger = Logger.getLogger(BuiltinUsersIT.class.getCanonicalName());
private static final String builtinUserKey = "burrito";
private static final String idKey = "id";
private static final String usernameKey = "userName";
private static final String emailKey = "email";
@BeforeClass
public static void setUp() {
RestAssured.baseURI = UtilIT.getRestAssuredBaseUri();
}
@Test
public void testCreateTimeAndApiLastUse() {
Response createUser = UtilIT.createRandomUser();
createUser.prettyPrint();
createUser.then().assertThat()
.statusCode(OK.getStatusCode());
String username = UtilIT.getUsernameFromResponse(createUser);
String apiToken = UtilIT.getApiTokenFromResponse(createUser);
Response getUserAsJson = UtilIT.getAuthenticatedUser(username, apiToken);
getUserAsJson.prettyPrint();
getUserAsJson.then().assertThat()
// Checking that it's 2017 or whatever. Not y3k compliant!
.body("data.createdTime", startsWith("2"))
.body("data.authenticationProviderId", equalTo("builtin"))
.statusCode(OK.getStatusCode());
Response getUserAsJsonAgain = UtilIT.getAuthenticatedUser(username, apiToken);
getUserAsJsonAgain.prettyPrint();
getUserAsJsonAgain.then().assertThat()
// ApiUseTime should be null, user has not used API yet here
.body("data.lastApiUseTime", equalTo(null))
.statusCode(OK.getStatusCode());
}
@Test
public void testLastApiUse() {
Response createApiUser = UtilIT.createRandomUser();
String apiUsername = UtilIT.getUsernameFromResponse(createApiUser);
String secondApiToken = UtilIT.getApiTokenFromResponse(createApiUser);
Response createDataverse = UtilIT.createRandomDataverse(secondApiToken);
String alias = UtilIT.getAliasFromResponse(createDataverse);
Response createDatasetViaApi = UtilIT.createRandomDatasetViaNativeApi(alias, secondApiToken);
Response getApiUserAsJson = UtilIT.getAuthenticatedUser(apiUsername, secondApiToken);
getApiUserAsJson.prettyPrint();
getApiUserAsJson.then().assertThat()
// Checking that it's 2017 or whatever. Not y3k compliant!
.body("data.lastApiUseTime", startsWith("2"))
.statusCode(OK.getStatusCode());
}
@Test
public void testUserId() {
String email = null;
Response createUserResponse = createUser(getRandomUsername(), "firstName", "lastName", email);
createUserResponse.prettyPrint();
assertEquals(200, createUserResponse.getStatusCode());
JsonPath createdUser = JsonPath.from(createUserResponse.body().asString());
int builtInUserIdFromJsonCreateResponse = createdUser.getInt("data.user." + idKey);
int authenticatedUserIdFromJsonCreateResponse = createdUser.getInt("data.authenticatedUser." + idKey);
String username = createdUser.getString("data.user." + usernameKey);
Response getUserResponse = getUserFromDatabase(username);
getUserResponse.prettyPrint();
assertEquals(200, getUserResponse.getStatusCode());
JsonPath getUserJson = JsonPath.from(getUserResponse.body().asString());
int userIdFromDatabase = getUserJson.getInt("data.id");
Response deleteUserResponse = deleteUser(username);
assertEquals(200, deleteUserResponse.getStatusCode());
deleteUserResponse.prettyPrint();
System.out.println(userIdFromDatabase + " was the id from the database");
System.out.println(builtInUserIdFromJsonCreateResponse + " was the id of the BuiltinUser from JSON response on create");
System.out.println(authenticatedUserIdFromJsonCreateResponse + " was the id of the AuthenticatedUser from JSON response on create");
assertEquals(userIdFromDatabase, authenticatedUserIdFromJsonCreateResponse);
}
@Test
public void testLeadingWhitespaceInEmailAddress() {
String randomUsername = getRandomUsername();
String email = " " + randomUsername + "@mailinator.com";
Response createUserResponse = createUser(randomUsername, "firstName", "lastName", email);
createUserResponse.prettyPrint();
assertEquals(200, createUserResponse.statusCode());
String emailActual = JsonPath.from(createUserResponse.body().asString()).getString("data.user." + emailKey);
// the backend will trim the email address
String emailExpected = email.trim();
assertEquals(emailExpected, emailActual);
}
@Test
public void testLeadingWhitespaceInUsername() {
String randomUsername = " " + getRandomUsername();
String email = randomUsername + "@mailinator.com";
Response createUserResponse = createUser(randomUsername, "firstName", "lastName", email);
createUserResponse.prettyPrint();
assertEquals(400, createUserResponse.statusCode());
}
@Test
public void testBadCharacterInUsername() {
String randomUsername = getRandomUsername() + "/";
String email = randomUsername + "@mailinator.com";
Response createUserResponse = createUser(randomUsername, "firstName", "lastName", email);
createUserResponse.prettyPrint();
assertEquals(400, createUserResponse.statusCode());
}
@Test
public void testGoodUsernameWithWeirdCharacters() {
String randomUsername = getRandomUsername();
String randomUsernameWeird = "õÂ" + randomUsername; //+ "爸好"; TODO: Fix -- somehow turn into ?? in API call
String email = randomUsername + "@mailinator.com";
Response createUserResponse = createUser(randomUsernameWeird, "firstName", "lastName", email);
createUserResponse.prettyPrint();
assertEquals(200, createUserResponse.statusCode());
}
@Test
public void testLogin() {
String usernameToCreate = getRandomUsername();
String email = null;
Response createUserResponse = createUser(usernameToCreate, "firstName", "lastName", email);
createUserResponse.prettyPrint();
assertEquals(200, createUserResponse.getStatusCode());
JsonPath createdUser = JsonPath.from(createUserResponse.body().asString());
String createdUsername = createdUser.getString("data.user." + usernameKey);
assertEquals(usernameToCreate, createdUsername);
String createdToken = createdUser.getString("data.apiToken");
logger.info(createdToken);
Response getApiTokenUsingUsername = getApiTokenUsingUsername(usernameToCreate, usernameToCreate);
getApiTokenUsingUsername.prettyPrint();
assertEquals(200, getApiTokenUsingUsername.getStatusCode());
String retrievedTokenUsingUsername = JsonPath.from(getApiTokenUsingUsername.asString()).getString("data.message");
assertEquals(createdToken, retrievedTokenUsingUsername);
Response failExpected = getApiTokenUsingUsername("junk", "junk");
failExpected.prettyPrint();
assertEquals(400, failExpected.getStatusCode());
if (BuiltinUsers.retrievingApiTokenViaEmailEnabled) {
Response getApiTokenUsingEmail = getApiTokenUsingEmail(usernameToCreate + "@mailinator.com", usernameToCreate);
getApiTokenUsingEmail.prettyPrint();
assertEquals(200, getApiTokenUsingEmail.getStatusCode());
String retrievedTokenUsingEmail = JsonPath.from(getApiTokenUsingEmail.asString()).getString("data.message");
assertEquals(createdToken, retrievedTokenUsingEmail);
}
}
private Response createUser(String username, String firstName, String lastName, String email) {
String userAsJson = getUserAsJsonString(username, firstName, lastName, email);
String password = getPassword(userAsJson);
Response response = given()
.body(userAsJson)
.contentType(ContentType.JSON)
.post("/api/builtin-users?key=" + builtinUserKey + "&password=" + password);
return response;
}
private Response getApiTokenUsingUsername(String username, String password) {
Response response = given()
.contentType(ContentType.JSON)
.get("/api/builtin-users/" + username + "/api-token?username=" + username + "&password=" + password);
return response;
}
private Response getApiTokenUsingEmail(String email, String password) {
Response response = given()
.contentType(ContentType.JSON)
.get("/api/builtin-users/" + email + "/api-token?username=" + email + "&password=" + password);
return response;
}
private Response getUserFromDatabase(String username) {
Response getUserResponse = given()
.get("/api/admin/authenticatedUsers/" + username + "/");
return getUserResponse;
}
private static Response deleteUser(String username) {
Response deleteUserResponse = given()
.delete("/api/admin/authenticatedUsers/" + username + "/");
return deleteUserResponse;
}
private static String getRandomUsername() {
return UUID.randomUUID().toString().substring(0, 8);
}
private static String getUserAsJsonString(String username, String firstName, String lastName, String email) {
JsonObjectBuilder builder = Json.createObjectBuilder();
builder.add(usernameKey, username);
builder.add("firstName", firstName);
builder.add("lastName", lastName);
if (email == null) {
builder.add(emailKey, getEmailFromUserName(username));
} else {
builder.add(emailKey, email);
}
String userAsJson = builder.build().toString();
logger.fine("User to create: " + userAsJson);
return userAsJson;
}
private static String getPassword(String jsonStr) {
String password = JsonPath.from(jsonStr).get(usernameKey);
return password;
}
private static String getEmailFromUserName(String username) {
return username + "@mailinator.com";
}
}
|
#4001 Fix for broken test getUsernameWithWeirdCharacters (renamed to testAccentInUsername)
|
src/test/java/edu/harvard/iq/dataverse/api/BuiltinUsersIT.java
|
#4001 Fix for broken test getUsernameWithWeirdCharacters (renamed to testAccentInUsername)
|
<ide><path>rc/test/java/edu/harvard/iq/dataverse/api/BuiltinUsersIT.java
<ide> }
<ide>
<ide> @Test
<del> public void testGoodUsernameWithWeirdCharacters() {
<add> public void testAccentInUsername() {
<ide> String randomUsername = getRandomUsername();
<del> String randomUsernameWeird = "õÂ" + randomUsername; //+ "爸好"; TODO: Fix -- somehow turn into ?? in API call
<add> String randomUsernameWeird = "õÂ" + randomUsername;
<ide> String email = randomUsername + "@mailinator.com";
<ide> Response createUserResponse = createUser(randomUsernameWeird, "firstName", "lastName", email);
<ide> createUserResponse.prettyPrint();
<del> assertEquals(200, createUserResponse.statusCode());
<add> assertEquals(400, createUserResponse.statusCode());
<ide> }
<ide>
<ide> @Test
|
|
Java
|
lgpl-2.1
|
a15ff845ed95e0af30bf9f11a13c44da8affc38c
| 0 |
SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ch.unizh.ini.jaer.projects.minliu;
import ch.unizh.ini.jaer.projects.davis.calibration.SingleCameraCalibration;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import static java.nio.file.Files.list;
import static java.rmi.Naming.list;
import java.util.ArrayList;
import static java.util.Collections.list;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfFloat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.TermCriteria;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.RotatedRect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.video.Video;
import org.opencv.videoio.VideoCapture;
import org.bytedeco.javacpp.opencv_videoio.VideoWriter;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import ch.unizh.ini.jaer.projects.davis.frames.ApsFrameExtractor;
import ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlow;
import ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlowIMU;
import static ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlowIMU.v;
import static ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlowIMU.vx;
import static ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlowIMU.vy;
import com.jogamp.common.util.Bitstream.ByteStream;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.chip.Chip2D;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.ApsDvsEventPacket;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.event.orientation.ApsDvsMotionOrientationEvent;
import net.sf.jaer.eventprocessing.EventFilter;
import static net.sf.jaer.eventprocessing.EventFilter.log;
import net.sf.jaer.eventprocessing.EventFilter2D;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.graphics.AEFrameChipRenderer;
import net.sf.jaer.graphics.ImageDisplay;
import org.apache.commons.lang3.ArrayUtils;
/**
*
* @author minliu
*/
@Description("Optical Flow methods based on OpenCV")
@DevelopmentStatus(DevelopmentStatus.Status.Experimental)
public class OpenCVFlow extends AbstractMotionFlow
implements PropertyChangeListener, Observer /* Observer needed to get change events on chip construction */ {
static {
String jvmVersion = System.getProperty("sun.arch.data.model");
try {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
// System.loadLibrary("opencv_ffmpeg320_" + jvmVersion); // Notice, cannot put the file type extension (.dll) here, it will add it automatically.
} catch (UnsatisfiedLinkError e) {
System.err.println("Native code library failed to load.\n" + e);
// System.exit(1);
}
}
private ApsFrameExtractor apsFrameExtractor;
private JFrame apsFrame = null;
protected boolean showAPSFrameDisplay = getBoolean("showAPSFrameDisplay", true);
private int[][] color = new int[100][3];
private float[] oldBuffer = null, newBuffer = null;
private PatchMatchFlow patchFlow;
public OpenCVFlow(AEChip chip) {
super(chip);
System.out.println("Welcome to OpenCV " + Core.VERSION);
apsFrameExtractor = new ApsFrameExtractor(chip);
apsFrame = new JFrame("Optical Flow Result Frame");
apsFrame.setPreferredSize(new Dimension(800, 800));
apsFrame.getContentPane().add(apsFrameExtractor.apsDisplay, BorderLayout.CENTER);
apsFrame.pack();
apsFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent e) {
setShowAPSFrameDisplay(false);
}
});
FilterChain chain = new FilterChain(chip);
try {
patchFlow = new PatchMatchFlow(chip);
patchFlow.setFilterEnabled(true);
chain.add(patchFlow);
} catch (Exception e) {
log.warning("could not setup PatchMatchFlow fiter.");
}
setEnclosedFilterChain(chain);
// apsFrameExtractor.getSupport().addPropertyChangeListener(ApsFrameExtractor.EVENT_NEW_FRAME, this);
patchFlow.getSupport().addPropertyChangeListener(PatchMatchFlow.EVENT_NEW_SLICES,this);
chip.addObserver(this); // to allocate memory once chip size is known
}
@Override
public EventPacket filterPacket(EventPacket in) {
if(!isFilterEnabled()) {
return in;
}
setupFilter(in);
apsFrameExtractor.apsDisplay.checkPixmapAllocation();
final ApsDvsEventPacket packet = (ApsDvsEventPacket) in;
if (packet == null) {
return null;
}
if (packet.getEventClass() != ApsDvsEvent.class) {
EventFilter.log.warning("wrong input event class, got " + packet.getEventClass() + " but we need to have " + ApsDvsEvent.class);
return null;
}
final Iterator apsItr = packet.fullIterator();
while (apsItr.hasNext()) {
final ApsDvsEvent e = (ApsDvsEvent) apsItr.next();
if (e.isApsData()) {
apsFrameExtractor.putAPSevent(e);
}
}
if(isShowAPSFrameDisplay()) {
apsFrameExtractor.apsDisplay.repaint();
}
return in;
}
@Override
public synchronized void resetFilter() {
super.resetFilter();
apsFrameExtractor = new ApsFrameExtractor(chip);
apsFrameExtractor.resetFilter();
patchFlow = new PatchMatchFlow(chip);
patchFlow.resetFilter();
}
@Override
public void initFilter() {
resetFilter();
}
@Override
public void update(Observable o, Object arg) {
if ((o != null) && (arg != null)) {
if ((o instanceof AEChip) && (arg.equals(Chip2D.EVENT_SIZEX) || arg.equals(Chip2D.EVENT_SIZEY))) {
initFilter();
}
}
}
@Override
public synchronized void setFilterEnabled(final boolean yes) {
super.setFilterEnabled(yes); // To change body of generated methods, choose Tools | Templates.
if (!isFilterEnabled()) {
if (apsFrame != null) {
apsFrame.setVisible(false);
}
}
}
@Override
public synchronized void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(ApsFrameExtractor.EVENT_NEW_FRAME)) {
if(newBuffer == null) {
newBuffer = (float[]) evt.getNewValue();
return;
}
oldBuffer = newBuffer;
float[] buffer = apsFrameExtractor.apsDisplay.getPixmapArray();
byte[] byteBuffer = new byte[buffer.length];
for(int i=0; i<buffer.length;i++) {
byteBuffer[i] = (byte) (buffer[i] * 255);
}
newBuffer = (float[]) evt.getNewValue();
Mat newFrame = new Mat(chip.getSizeY(), chip.getSizeX(), CvType.CV_32F);
newFrame.put(0, 0, newBuffer);
Mat oldFrame = new Mat(chip.getSizeY(), chip.getSizeX(), CvType.CV_32F);
oldFrame.put(0, 0, oldBuffer);
// params for ShiTomasi corner detection
FeatureParams feature_params = new FeatureParams(100, 0.3, 7, 7);
// Feature extraction
MatOfPoint p0 = new MatOfPoint();
Imgproc.goodFeaturesToTrack(newFrame, p0, feature_params.maxCorners, feature_params.qualityLevel, feature_params.minDistance);
MatOfPoint2f prevPts = new MatOfPoint2f(p0.toArray());
MatOfPoint2f nextPts = new MatOfPoint2f();
MatOfByte status = new MatOfByte();
MatOfFloat err = new MatOfFloat();
int featureNum = prevPts.checkVector(2, CvType.CV_32F, true);
System.out.println("The number of feature detected is : " + featureNum);
try {
Video.calcOpticalFlowPyrLK(oldFrame, newFrame, prevPts, nextPts, status, err);
} catch (Exception e) {
System.err.println(e);
// newFrame.copyTo(oldFrame);
}
// TODO: Select good points
// draw the tracks
Point[] prevPoints = prevPts.toArray();
// Point[] nextPoints = nextPts.toArray();
// byte[] st = status.toArray();
// float[] er = err.toArray();
Mat mask = new Mat(newFrame.rows(), newFrame.cols(), CvType.CV_32F);
for (int i = 0; i < prevPoints.length; i++) {
// Imgproc.line(displayFrame, prevPoints[i], nextPoints[i], new Scalar(color[i][0],color[i][1],color[i][2]), 2);
Imgproc.circle(newFrame,prevPoints[i], 5, new Scalar(255,255,255),-1);
}
float[] return_buff = new float[(int) (newFrame.total() *
newFrame.channels())];
newFrame.get(0, 0, return_buff);
apsFrameExtractor.apsDisplay.setPixmapFromGrayArray(return_buff);
}
if (evt.getPropertyName().equals(PatchMatchFlow.EVENT_NEW_SLICES)) {
byte[][][] tMinus2dSlice = (byte[][][]) evt.getOldValue();
byte[][][] tMinusdSlice = (byte[][][]) evt.getNewValue();
Mat newFrame = new Mat(chip.getSizeY(), chip.getSizeX(), CvType.CV_8U);
Mat oldFrame = new Mat(chip.getSizeY(), chip.getSizeX(), CvType.CV_8U);
// /* An example to flatten the nested array to 1D array */
// double[][][] vals = {{{1.1, 2.1}, {3.2, 4.1}}, {{5.2, 6.1}, {7.1, 8.3}}};
//
// double[] test = Arrays.stream(vals)
// .flatMap(Arrays::stream)
// .flatMapToDouble(Arrays::stream)
// .toArray();
//
// System.out.println(Arrays.toString(test));
// Flatten the two arrays to 1D array
byte[] old1DArray = new byte[chip.getSizeY() * chip.getSizeX()],
new1DArray = new byte[chip.getSizeY() * chip.getSizeX()];
for (int i = 0; i < chip.getSizeY(); i++) {
for (int j = 0; j < chip.getSizeX(); j++) {
old1DArray[chip.getSizeX()*i + j] = tMinus2dSlice[0][j][i];
new1DArray[chip.getSizeX()*i + j] = tMinusdSlice[0][j][i];
}
}
List oldList = Arrays.asList(ArrayUtils.toObject(old1DArray));
float oldGrayScale = Collections.max((List<Byte>) oldList); // Set the maximum of tha array as the scale value.
List newList = Arrays.asList(ArrayUtils.toObject(new1DArray));
float newGrayScale = Collections.max((List<Byte>) newList); // Set the maximum of tha array as the scale value.
// for (int i = 0; i < chip.getSizeY(); i++) {
// for (int j = 0; j < chip.getSizeX(); j++) {
// old1DArray[chip.getSizeX()*i + j] /= oldGrayScale;
// new1DArray[chip.getSizeX()*i + j] /= newGrayScale;
// }
// }
newFrame.put(0, 0, new1DArray);
oldFrame.put(0, 0, old1DArray);
// params for ShiTomasi corner detection
FeatureParams feature_params = new FeatureParams(100, 0.3, 7, 7);
// Feature extraction
MatOfPoint p0 = new MatOfPoint();
Imgproc.goodFeaturesToTrack(newFrame, p0, feature_params.maxCorners, feature_params.qualityLevel, feature_params.minDistance);
MatOfPoint2f prevPts = new MatOfPoint2f(p0.toArray());
MatOfPoint2f nextPts = new MatOfPoint2f();
MatOfByte status = new MatOfByte();
MatOfFloat err = new MatOfFloat();
int featureNum = prevPts.checkVector(2, CvType.CV_32F, true);
System.out.println("The number of feature detected is : " + featureNum);
try {
Video.calcOpticalFlowPyrLK(oldFrame, newFrame, prevPts, nextPts, status, err);
} catch (Exception e) {
System.err.println(e);
return;
}
// draw the tracks
Point[] prevPoints = prevPts.toArray();
Point[] nextPoints = nextPts.toArray();
byte[] st = status.toArray();
float[] er = err.toArray();
// Select good points and copy them for output
int index = 0;
for(byte stTmp: st) {
if(stTmp == 1) {
e = new PolarityEvent();
x = (short)(prevPoints[index].x);
y = (short)prevPoints[index].y;
e.x = (short)x;
e.y = (short)y; // e, x and y all of them are used in processGoodEvent();
vx = (float)(nextPoints[index].x - prevPoints[index].x) * 1000000 / patchFlow.getSliceDeltaT();
vy = (float)(nextPoints[index].y - prevPoints[index].y) * 1000000 / patchFlow.getSliceDeltaT();
v = (float) Math.sqrt(vx * vx + vy * vy);
processGoodEvent();
index++;
}
}
Mat mask = new Mat(newFrame.rows(), newFrame.cols(), CvType.CV_32F);
for (int i = 0; i < prevPoints.length; i++) {
// Imgproc.line(displayFrame, prevPoints[i], nextPoints[i], new Scalar(color[i][0],color[i][1],color[i][2]), 2);
// Imgproc.circle(newFrame,prevPoints[i], 5, new Scalar(255,255,255),-1);
}
// showResult(newFrame);
newFrame.convertTo(newFrame, CvType.CV_32F);
float[] return_buff = new float[(int) (newFrame.total() *
newFrame.channels())];
newFrame.get(0, 0, return_buff);
apsFrameExtractor.apsDisplay.setPixmapFromGrayArray(return_buff);
}
}
public class FeatureParams {
int maxCorners;
double qualityLevel;
double minDistance;
int blockSize;
public FeatureParams(int maxCorners, double qualityLevel, int minDistance, int blockSize) {
this.maxCorners = maxCorners;
this.qualityLevel = qualityLevel;
this.minDistance = minDistance;
this.blockSize = blockSize;
}
}
public class LKParams {
int winSizeX;
int winSizeY;
int maxLevel;
TermCriteria criteria = new TermCriteria();
public LKParams(int winSizeX, int winSizeY, int maxLevel, TermCriteria criteria) {
this.winSizeX = winSizeX;
this.winSizeY = winSizeY;
this.maxLevel = maxLevel;
this.criteria = criteria;
}
}
public void showResult(Mat img) {
Imgproc.resize(img, img, new Size(640, 480));
MatOfByte matOfByte = new MatOfByte();
Imgcodecs.imencode(".jpg", img, matOfByte);
byte[] byteArray = matOfByte.toArray();
BufferedImage bufImage = null;
try {
InputStream in = new ByteArrayInputStream(byteArray);
bufImage = ImageIO.read(in);
JFrame frame = new JFrame();
frame.getContentPane().add(new JLabel(new ImageIcon(bufImage)));
frame.pack();
frame.setVisible(true);
} catch (IOException | HeadlessException e) {
e.printStackTrace();
}
}
public BufferedImage Mat2BufferedImage(Mat m){
// source: http://answers.opencv.org/question/10344/opencv-java-load-image-to-gui/
// Fastest code
// The output can be assigned either to a BufferedImage or to an Image
int type = BufferedImage.TYPE_BYTE_GRAY;
if ( m.channels() > 1 ) {
type = BufferedImage.TYPE_3BYTE_BGR;
}
int bufferSize = m.channels()*m.cols()*m.rows();
byte [] b = new byte[bufferSize];
m.get(0,0,b); // get all the pixels
BufferedImage image = new BufferedImage(m.cols(),m.rows(), type);
final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.arraycopy(b, 0, targetPixels, 0, b.length);
return image;
}
public void displayImage(Image img2) {
//BufferedImage img=ImageIO.read(new File("/HelloOpenCV/lena.png"));
ImageIcon icon=new ImageIcon(img2);
JFrame frame=new JFrame();
frame.setLayout(new FlowLayout());
frame.setSize(img2.getWidth(null)+50, img2.getHeight(null)+50);
JLabel lbl=new JLabel();
lbl.setIcon(icon);
frame.add(lbl);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* @return the showAPSFrameDisplay
*/
public boolean isShowAPSFrameDisplay() {
return showAPSFrameDisplay;
}
/**
* @param showAPSFrameDisplay the showAPSFrameDisplay to set
*/
public void setShowAPSFrameDisplay(final boolean showAPSFrameDisplay) {
this.showAPSFrameDisplay = showAPSFrameDisplay;
putBoolean("showAPSFrameDisplay", showAPSFrameDisplay);
if (apsFrame != null) {
apsFrame.setVisible(showAPSFrameDisplay);
}
getSupport().firePropertyChange("showAPSFrameDisplay", null, showAPSFrameDisplay);
}
}
|
src/ch/unizh/ini/jaer/projects/minliu/OpenCVFlow.java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ch.unizh.ini.jaer.projects.minliu;
import ch.unizh.ini.jaer.projects.davis.calibration.SingleCameraCalibration;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import static java.nio.file.Files.list;
import static java.rmi.Naming.list;
import java.util.ArrayList;
import static java.util.Collections.list;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfFloat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.TermCriteria;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.RotatedRect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.video.Video;
import org.opencv.videoio.VideoCapture;
import org.bytedeco.javacpp.opencv_videoio.VideoWriter;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import ch.unizh.ini.jaer.projects.davis.frames.ApsFrameExtractor;
import ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlow;
import ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlowIMU;
import static ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlowIMU.v;
import static ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlowIMU.vx;
import static ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlowIMU.vy;
import com.jogamp.common.util.Bitstream.ByteStream;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.chip.Chip2D;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.ApsDvsEventPacket;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.event.orientation.ApsDvsMotionOrientationEvent;
import net.sf.jaer.eventprocessing.EventFilter;
import static net.sf.jaer.eventprocessing.EventFilter.log;
import net.sf.jaer.eventprocessing.EventFilter2D;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.graphics.AEFrameChipRenderer;
import net.sf.jaer.graphics.ImageDisplay;
import org.apache.commons.lang3.ArrayUtils;
/**
*
* @author minliu
*/
@Description("Optical Flow methods based on OpenCV")
@DevelopmentStatus(DevelopmentStatus.Status.Experimental)
public class OpenCVFlow extends AbstractMotionFlow
implements PropertyChangeListener, Observer /* Observer needed to get change events on chip construction */ {
static {
String jvmVersion = System.getProperty("sun.arch.data.model");
try {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
// System.loadLibrary("opencv_ffmpeg320_" + jvmVersion); // Notice, cannot put the file type extension (.dll) here, it will add it automatically.
} catch (UnsatisfiedLinkError e) {
System.err.println("Native code library failed to load.\n" + e);
// System.exit(1);
}
}
private ApsFrameExtractor apsFrameExtractor;
private JFrame apsFrame = null;
protected boolean showAPSFrameDisplay = getBoolean("showAPSFrameDisplay", true);
private int[][] color = new int[100][3];
private float[] oldBuffer = null, newBuffer = null;
private PatchMatchFlow patchFlow;
public OpenCVFlow(AEChip chip) {
super(chip);
System.out.println("Welcome to OpenCV " + Core.VERSION);
apsFrameExtractor = new ApsFrameExtractor(chip);
apsFrame = new JFrame("Optical Flow Result Frame");
apsFrame.setPreferredSize(new Dimension(800, 800));
apsFrame.getContentPane().add(apsFrameExtractor.apsDisplay, BorderLayout.CENTER);
apsFrame.pack();
apsFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent e) {
setShowAPSFrameDisplay(false);
}
});
FilterChain chain = new FilterChain(chip);
try {
patchFlow = new PatchMatchFlow(chip);
patchFlow.setFilterEnabled(true);
chain.add(patchFlow);
} catch (Exception e) {
log.warning("could not setup PatchMatchFlow fiter.");
}
setEnclosedFilterChain(chain);
// apsFrameExtractor.getSupport().addPropertyChangeListener(ApsFrameExtractor.EVENT_NEW_FRAME, this);
patchFlow.getSupport().addPropertyChangeListener(PatchMatchFlow.EVENT_NEW_SLICES,this);
chip.addObserver(this); // to allocate memory once chip size is known
}
@Override
public EventPacket filterPacket(EventPacket in) {
if(!isFilterEnabled()) {
return in;
}
setupFilter(in);
apsFrameExtractor.apsDisplay.checkPixmapAllocation();
final ApsDvsEventPacket packet = (ApsDvsEventPacket) in;
if (packet == null) {
return null;
}
if (packet.getEventClass() != ApsDvsEvent.class) {
EventFilter.log.warning("wrong input event class, got " + packet.getEventClass() + " but we need to have " + ApsDvsEvent.class);
return null;
}
final Iterator apsItr = packet.fullIterator();
while (apsItr.hasNext()) {
final ApsDvsEvent e = (ApsDvsEvent) apsItr.next();
if (e.isApsData()) {
apsFrameExtractor.putAPSevent(e);
}
}
if(isShowAPSFrameDisplay()) {
apsFrameExtractor.apsDisplay.repaint();
}
return in;
}
@Override
public void resetFilter() {
super.resetFilter();
apsFrameExtractor = new ApsFrameExtractor(chip);
apsFrameExtractor.resetFilter();
patchFlow = new PatchMatchFlow(chip);
patchFlow.resetFilter();
}
@Override
public void initFilter() {
resetFilter();
}
@Override
public void update(Observable o, Object arg) {
if ((o != null) && (arg != null)) {
if ((o instanceof AEChip) && (arg.equals(Chip2D.EVENT_SIZEX) || arg.equals(Chip2D.EVENT_SIZEY))) {
initFilter();
}
}
}
@Override
public synchronized void setFilterEnabled(final boolean yes) {
super.setFilterEnabled(yes); // To change body of generated methods, choose Tools | Templates.
if (!isFilterEnabled()) {
if (apsFrame != null) {
apsFrame.setVisible(false);
}
}
}
@Override
public synchronized void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(ApsFrameExtractor.EVENT_NEW_FRAME)) {
if(newBuffer == null) {
newBuffer = (float[]) evt.getNewValue();
return;
}
oldBuffer = newBuffer;
float[] buffer = apsFrameExtractor.apsDisplay.getPixmapArray();
byte[] byteBuffer = new byte[buffer.length];
for(int i=0; i<buffer.length;i++) {
byteBuffer[i] = (byte) (buffer[i] * 255);
}
newBuffer = (float[]) evt.getNewValue();
Mat newFrame = new Mat(chip.getSizeY(), chip.getSizeX(), CvType.CV_32F);
newFrame.put(0, 0, newBuffer);
Mat oldFrame = new Mat(chip.getSizeY(), chip.getSizeX(), CvType.CV_32F);
oldFrame.put(0, 0, oldBuffer);
// params for ShiTomasi corner detection
FeatureParams feature_params = new FeatureParams(100, 0.3, 7, 7);
// Feature extraction
MatOfPoint p0 = new MatOfPoint();
Imgproc.goodFeaturesToTrack(newFrame, p0, feature_params.maxCorners, feature_params.qualityLevel, feature_params.minDistance);
MatOfPoint2f prevPts = new MatOfPoint2f(p0.toArray());
MatOfPoint2f nextPts = new MatOfPoint2f();
MatOfByte status = new MatOfByte();
MatOfFloat err = new MatOfFloat();
int featureNum = prevPts.checkVector(2, CvType.CV_32F, true);
System.out.println("The number of feature detected is : " + featureNum);
try {
Video.calcOpticalFlowPyrLK(oldFrame, newFrame, prevPts, nextPts, status, err);
} catch (Exception e) {
System.err.println(e);
// newFrame.copyTo(oldFrame);
}
// TODO: Select good points
// draw the tracks
Point[] prevPoints = prevPts.toArray();
// Point[] nextPoints = nextPts.toArray();
// byte[] st = status.toArray();
// float[] er = err.toArray();
Mat mask = new Mat(newFrame.rows(), newFrame.cols(), CvType.CV_32F);
for (int i = 0; i < prevPoints.length; i++) {
// Imgproc.line(displayFrame, prevPoints[i], nextPoints[i], new Scalar(color[i][0],color[i][1],color[i][2]), 2);
Imgproc.circle(newFrame,prevPoints[i], 5, new Scalar(255,255,255),-1);
}
float[] return_buff = new float[(int) (newFrame.total() *
newFrame.channels())];
newFrame.get(0, 0, return_buff);
apsFrameExtractor.apsDisplay.setPixmapFromGrayArray(return_buff);
}
if (evt.getPropertyName().equals(PatchMatchFlow.EVENT_NEW_SLICES)) {
byte[][][] tMinus2dSlice = (byte[][][]) evt.getOldValue();
byte[][][] tMinusdSlice = (byte[][][]) evt.getNewValue();
Mat newFrame = new Mat(chip.getSizeY(), chip.getSizeX(), CvType.CV_8U);
Mat oldFrame = new Mat(chip.getSizeY(), chip.getSizeX(), CvType.CV_8U);
// /* An example to flatten the nested array to 1D array */
// double[][][] vals = {{{1.1, 2.1}, {3.2, 4.1}}, {{5.2, 6.1}, {7.1, 8.3}}};
//
// double[] test = Arrays.stream(vals)
// .flatMap(Arrays::stream)
// .flatMapToDouble(Arrays::stream)
// .toArray();
//
// System.out.println(Arrays.toString(test));
// Flatten the two arrays to 1D array
byte[] old1DArray = new byte[chip.getSizeY() * chip.getSizeX()],
new1DArray = new byte[chip.getSizeY() * chip.getSizeX()];
for (int i = 0; i < chip.getSizeY(); i++) {
for (int j = 0; j < chip.getSizeX(); j++) {
old1DArray[chip.getSizeX()*i + j] = tMinus2dSlice[0][j][i];
new1DArray[chip.getSizeX()*i + j] = tMinusdSlice[0][j][i];
}
}
List oldList = Arrays.asList(ArrayUtils.toObject(old1DArray));
float oldGrayScale = Collections.max((List<Byte>) oldList); // Set the maximum of tha array as the scale value.
List newList = Arrays.asList(ArrayUtils.toObject(new1DArray));
float newGrayScale = Collections.max((List<Byte>) newList); // Set the maximum of tha array as the scale value.
// for (int i = 0; i < chip.getSizeY(); i++) {
// for (int j = 0; j < chip.getSizeX(); j++) {
// old1DArray[chip.getSizeX()*i + j] /= oldGrayScale;
// new1DArray[chip.getSizeX()*i + j] /= newGrayScale;
// }
// }
newFrame.put(0, 0, new1DArray);
oldFrame.put(0, 0, old1DArray);
// params for ShiTomasi corner detection
FeatureParams feature_params = new FeatureParams(100, 0.3, 7, 7);
// Feature extraction
MatOfPoint p0 = new MatOfPoint();
Imgproc.goodFeaturesToTrack(newFrame, p0, feature_params.maxCorners, feature_params.qualityLevel, feature_params.minDistance);
MatOfPoint2f prevPts = new MatOfPoint2f(p0.toArray());
MatOfPoint2f nextPts = new MatOfPoint2f();
MatOfByte status = new MatOfByte();
MatOfFloat err = new MatOfFloat();
int featureNum = prevPts.checkVector(2, CvType.CV_32F, true);
System.out.println("The number of feature detected is : " + featureNum);
try {
Video.calcOpticalFlowPyrLK(oldFrame, newFrame, prevPts, nextPts, status, err);
} catch (Exception e) {
System.err.println(e);
return;
}
// draw the tracks
Point[] prevPoints = prevPts.toArray();
Point[] nextPoints = nextPts.toArray();
byte[] st = status.toArray();
float[] er = err.toArray();
// Select good points and copy them for output
int index = 0;
for(byte stTmp: st) {
if(stTmp == 1) {
e = new PolarityEvent();
x = (short)(prevPoints[index].x);
y = (short)prevPoints[index].y;
e.x = (short)x;
e.y = (short)y; // e, x and y all of them are used in processGoodEvent();
vx = (float)(nextPoints[index].x - prevPoints[index].x) * 1000000 / patchFlow.getSliceDeltaT();
vy = (float)(nextPoints[index].y - prevPoints[index].y) * 1000000 / patchFlow.getSliceDeltaT();
v = (float) Math.sqrt(vx * vx + vy * vy);
processGoodEvent();
index++;
}
}
Mat mask = new Mat(newFrame.rows(), newFrame.cols(), CvType.CV_32F);
for (int i = 0; i < prevPoints.length; i++) {
// Imgproc.line(displayFrame, prevPoints[i], nextPoints[i], new Scalar(color[i][0],color[i][1],color[i][2]), 2);
// Imgproc.circle(newFrame,prevPoints[i], 5, new Scalar(255,255,255),-1);
}
// showResult(newFrame);
newFrame.convertTo(newFrame, CvType.CV_32F);
float[] return_buff = new float[(int) (newFrame.total() *
newFrame.channels())];
newFrame.get(0, 0, return_buff);
apsFrameExtractor.apsDisplay.setPixmapFromGrayArray(return_buff);
}
}
public class FeatureParams {
int maxCorners;
double qualityLevel;
double minDistance;
int blockSize;
public FeatureParams(int maxCorners, double qualityLevel, int minDistance, int blockSize) {
this.maxCorners = maxCorners;
this.qualityLevel = qualityLevel;
this.minDistance = minDistance;
this.blockSize = blockSize;
}
}
public class LKParams {
int winSizeX;
int winSizeY;
int maxLevel;
TermCriteria criteria = new TermCriteria();
public LKParams(int winSizeX, int winSizeY, int maxLevel, TermCriteria criteria) {
this.winSizeX = winSizeX;
this.winSizeY = winSizeY;
this.maxLevel = maxLevel;
this.criteria = criteria;
}
}
public void showResult(Mat img) {
Imgproc.resize(img, img, new Size(640, 480));
MatOfByte matOfByte = new MatOfByte();
Imgcodecs.imencode(".jpg", img, matOfByte);
byte[] byteArray = matOfByte.toArray();
BufferedImage bufImage = null;
try {
InputStream in = new ByteArrayInputStream(byteArray);
bufImage = ImageIO.read(in);
JFrame frame = new JFrame();
frame.getContentPane().add(new JLabel(new ImageIcon(bufImage)));
frame.pack();
frame.setVisible(true);
} catch (IOException | HeadlessException e) {
e.printStackTrace();
}
}
public BufferedImage Mat2BufferedImage(Mat m){
// source: http://answers.opencv.org/question/10344/opencv-java-load-image-to-gui/
// Fastest code
// The output can be assigned either to a BufferedImage or to an Image
int type = BufferedImage.TYPE_BYTE_GRAY;
if ( m.channels() > 1 ) {
type = BufferedImage.TYPE_3BYTE_BGR;
}
int bufferSize = m.channels()*m.cols()*m.rows();
byte [] b = new byte[bufferSize];
m.get(0,0,b); // get all the pixels
BufferedImage image = new BufferedImage(m.cols(),m.rows(), type);
final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.arraycopy(b, 0, targetPixels, 0, b.length);
return image;
}
public void displayImage(Image img2) {
//BufferedImage img=ImageIO.read(new File("/HelloOpenCV/lena.png"));
ImageIcon icon=new ImageIcon(img2);
JFrame frame=new JFrame();
frame.setLayout(new FlowLayout());
frame.setSize(img2.getWidth(null)+50, img2.getHeight(null)+50);
JLabel lbl=new JLabel();
lbl.setIcon(icon);
frame.add(lbl);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* @return the showAPSFrameDisplay
*/
public boolean isShowAPSFrameDisplay() {
return showAPSFrameDisplay;
}
/**
* @param showAPSFrameDisplay the showAPSFrameDisplay to set
*/
public void setShowAPSFrameDisplay(final boolean showAPSFrameDisplay) {
this.showAPSFrameDisplay = showAPSFrameDisplay;
putBoolean("showAPSFrameDisplay", showAPSFrameDisplay);
if (apsFrame != null) {
apsFrame.setVisible(showAPSFrameDisplay);
}
getSupport().firePropertyChange("showAPSFrameDisplay", null, showAPSFrameDisplay);
}
}
|
OpenCVFlow: resetFilter() overrides a synchronized method, and must thus also be synchronized.
|
src/ch/unizh/ini/jaer/projects/minliu/OpenCVFlow.java
|
OpenCVFlow: resetFilter() overrides a synchronized method, and must thus also be synchronized.
|
<ide><path>rc/ch/unizh/ini/jaer/projects/minliu/OpenCVFlow.java
<ide> }
<ide>
<ide> @Override
<del> public void resetFilter() {
<add> public synchronized void resetFilter() {
<ide> super.resetFilter();
<ide>
<ide> apsFrameExtractor = new ApsFrameExtractor(chip);
|
|
Java
|
apache-2.0
|
384410dc860a40f18281d45b3a44792cf636874e
| 0 |
assertj/assertj-core,joel-costigliola/assertj-core,joel-costigliola/assertj-core,assertj/assertj-core,hazendaz/assertj-core,hazendaz/assertj-core
|
/*
* 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 2012-2020 the original author or authors.
*/
package org.assertj.core.api;
import static java.util.Arrays.stream;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.error.ShouldMatch.shouldMatch;
import static org.assertj.core.error.ShouldNotBeNull.shouldNotBeNull;
import static org.assertj.core.util.Preconditions.checkArgument;
import static org.assertj.core.util.Strings.formatIfArgs;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration;
import org.assertj.core.configuration.ConfigurationProvider;
import org.assertj.core.description.Description;
import org.assertj.core.error.AssertionErrorCreator;
import org.assertj.core.error.BasicErrorMessageFactory;
import org.assertj.core.error.ErrorMessageFactory;
import org.assertj.core.error.MessageFormatter;
import org.assertj.core.internal.ComparatorBasedComparisonStrategy;
import org.assertj.core.internal.Conditions;
import org.assertj.core.internal.Failures;
import org.assertj.core.internal.Objects;
import org.assertj.core.presentation.PredicateDescription;
import org.assertj.core.presentation.Representation;
import org.assertj.core.util.CheckReturnValue;
import org.assertj.core.util.VisibleForTesting;
/**
* Base class for all assertions.
*
* @param <SELF> the "self" type of this assertion class. Please read "<a href="http://bit.ly/1IZIRcY"
* target="_blank">Emulating 'self types' using Java Generics to simplify fluent API implementation</a>"
* for more details.
* @param <ACTUAL> the type of the "actual" value.
*
* @author Alex Ruiz
* @author Joel Costigliola
* @author Mikhail Mazursky
* @author Nicolas François
*/
public abstract class AbstractAssert<SELF extends AbstractAssert<SELF, ACTUAL>, ACTUAL> implements Assert<SELF, ACTUAL> {
// https://github.com/joel-costigliola/assertj-core/issues/1128
public static boolean throwUnsupportedExceptionOnEquals = true;
private static final String ORG_ASSERTJ = "org.assert";
protected Objects objects = Objects.instance();
@VisibleForTesting
Conditions conditions = Conditions.instance();
@VisibleForTesting
public WritableAssertionInfo info;
// visibility is protected to allow us write custom assertions that need access to actual
@VisibleForTesting
protected final ACTUAL actual;
protected final SELF myself;
// = ConfigurationProvider.CONFIGURATION_PROVIDER.representation(); ?
private static Representation customRepresentation = null;
@VisibleForTesting
AssertionErrorCreator assertionErrorCreator;
// we prefer not to use Class<? extends S> selfType because it would force inherited
// constructor to cast with a compiler warning
// let's keep compiler warning internal (when we can) and not expose them to our end users.
@SuppressWarnings("unchecked")
public AbstractAssert(ACTUAL actual, Class<?> selfType) {
myself = (SELF) selfType.cast(this);
this.actual = actual;
info = new WritableAssertionInfo(customRepresentation);
assertionErrorCreator = new AssertionErrorCreator();
}
/**
* Exposes the {@link WritableAssertionInfo} used in the current assertion for better extensibility.<br> When writing
* your own assertion class, you can use the returned {@link WritableAssertionInfo} to change the error message and
* still keep the description set by the assertion user.
*
* @return the {@link WritableAssertionInfo} used in the current assertion
*/
public WritableAssertionInfo getWritableAssertionInfo() {
return info;
}
/**
* Utility method to ease writing custom assertions classes using {@link String#format(String, Object...)} specifiers
* in error message.
* <p>
* Moreover, this method honors any description set with {@link #as(String, Object...)} or overridden error message
* defined by the user with {@link #overridingErrorMessage(String, Object...)}.
* <p>
* Example :
* <pre><code class='java'> public TolkienCharacterAssert hasName(String name) {
* // check that actual TolkienCharacter we want to make assertions on is not null.
* isNotNull();
*
* // check condition
* if (!actual.getName().equals(name)) {
* failWithMessage("Expected character's name to be <%s> but was <%s>", name, actual.getName());
* }
*
* // return the current assertion for method chaining
* return this;
* }</code></pre>
*
* @param errorMessage the error message to format
* @param arguments the arguments referenced by the format specifiers in the errorMessage string.
*/
protected void failWithMessage(String errorMessage, Object... arguments) {
AssertionError assertionError = Failures.instance().failureIfErrorMessageIsOverridden(info);
if (assertionError == null) {
// error message was not overridden, build it.
String description = MessageFormatter.instance().format(info.description(), info.representation(), "");
assertionError = new AssertionError(description + String.format(errorMessage, arguments));
}
Failures.instance().removeAssertJRelatedElementsFromStackTraceIfNeeded(assertionError);
removeCustomAssertRelatedElementsFromStackTraceIfNeeded(assertionError);
throw assertionError;
}
/**
* Utility method to throw an {@link AssertionError} given a {@link BasicErrorMessageFactory}.
* <p>
* Instead of writing ...
*
* <pre><code class='java'> throw Failures.instance().failure(info, ShouldBePresent.shouldBePresent());</code></pre>
* ... you can simply write :
*
* <pre><code class='java'> throwAssertionError(info, ShouldBePresent.shouldBePresent());</code></pre>
*
* @param errorMessageFactory used to define the error message.
* @throws AssertionError with a message corresponding to the given {@link BasicErrorMessageFactory}.
*/
protected void throwAssertionError(ErrorMessageFactory errorMessageFactory) {
throw assertionError(errorMessageFactory);
}
protected AssertionError assertionError(ErrorMessageFactory errorMessageFactory) {
AssertionError failure = Failures.instance().failure(info, errorMessageFactory);
removeCustomAssertRelatedElementsFromStackTraceIfNeeded(failure);
return failure;
}
private void removeCustomAssertRelatedElementsFromStackTraceIfNeeded(AssertionError assertionError) {
if (!Failures.instance().isRemoveAssertJRelatedElementsFromStackTrace()) return;
if (isAssertjAssertClass()) return;
StackTraceElement[] newStackTrace = Arrays.stream(assertionError.getStackTrace())
.filter(element -> !isElementOfCustomAssert(element))
.toArray(StackTraceElement[]::new);
assertionError.setStackTrace(newStackTrace);
}
private boolean isAssertjAssertClass() {
return getClass().getName().startsWith(ORG_ASSERTJ);
}
private boolean isElementOfCustomAssert(StackTraceElement stackTraceElement) {
Class<?> currentAssertClass = getClass();
while (currentAssertClass != AbstractAssert.class) {
if (stackTraceElement.getClassName().equals(currentAssertClass.getName())) {
return true;
}
currentAssertClass = currentAssertClass.getSuperclass();
}
return false;
}
/**
* Use hexadecimal object representation instead of standard representation in error messages.
* <p>
* It can be useful when comparing UNICODE characters - many unicode chars have duplicate characters assigned, it is
* thus impossible to find differences from the standard error message:
* <p>
* With standard message:
* <pre><code class='java'> assertThat("µµµ").contains("μμμ");
*
* java.lang.AssertionError:
* Expecting:
* <"µµµ">
* to contain:
* <"μμμ"></code></pre>
*
* With Hexadecimal message:
* <pre><code class='java'> assertThat("µµµ").inHexadecimal().contains("μμμ");
*
* java.lang.AssertionError:
* Expecting:
* <"['00B5', '00B5', '00B5']">
* to contain:
* <"['03BC', '03BC', '03BC']"></code></pre>
*
* @return {@code this} assertion object.
*/
@CheckReturnValue
protected SELF inHexadecimal() {
info.useHexadecimalRepresentation();
return myself;
}
/**
* Use binary object representation instead of standard representation in error messages.
* <p>
* Example:
* <pre><code class='java'> assertThat(1).inBinary().isEqualTo(2);
*
* org.junit.ComparisonFailure:
* Expected :0b00000000_00000000_00000000_00000010
* Actual :0b00000000_00000000_00000000_00000001</code></pre>
*
* @return {@code this} assertion object.
*/
@CheckReturnValue
protected SELF inBinary() {
info.useBinaryRepresentation();
return myself;
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF describedAs(Description description) {
info.description(description);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isEqualTo(Object expected) {
objects.assertEqual(info, actual, expected);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotEqualTo(Object other) {
objects.assertNotEqual(info, actual, other);
return myself;
}
/** {@inheritDoc} */
@Override
public void isNull() {
objects.assertNull(info, actual);
}
/** {@inheritDoc} */
@Override
public SELF isNotNull() {
objects.assertNotNull(info, actual);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isSameAs(Object expected) {
objects.assertSame(info, actual, expected);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotSameAs(Object other) {
objects.assertNotSame(info, actual, other);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isIn(Object... values) {
objects.assertIsIn(info, actual, values);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotIn(Object... values) {
objects.assertIsNotIn(info, actual, values);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isIn(Iterable<?> values) {
objects.assertIsIn(info, actual, values);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotIn(Iterable<?> values) {
objects.assertIsNotIn(info, actual, values);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF is(Condition<? super ACTUAL> condition) {
conditions.assertIs(info, actual, condition);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNot(Condition<? super ACTUAL> condition) {
conditions.assertIsNot(info, actual, condition);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF has(Condition<? super ACTUAL> condition) {
conditions.assertHas(info, actual, condition);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF doesNotHave(Condition<? super ACTUAL> condition) {
conditions.assertDoesNotHave(info, actual, condition);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF satisfies(Condition<? super ACTUAL> condition) {
conditions.assertSatisfies(info, actual, condition);
return myself;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override
@CheckReturnValue
public <ASSERT extends AbstractAssert<?, ?>> ASSERT asInstanceOf(InstanceOfAssertFactory<?, ASSERT> instanceOfAssertFactory) {
requireNonNull(instanceOfAssertFactory, shouldNotBeNull("instanceOfAssertFactory").create());
objects.assertIsInstanceOf(info, actual, instanceOfAssertFactory.getType());
return (ASSERT) instanceOfAssertFactory.createAssert(actual).withAssertionState(myself);
}
/** {@inheritDoc} */
@Override
public SELF isInstanceOf(Class<?> type) {
objects.assertIsInstanceOf(info, actual, type);
return myself;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override
public <T> SELF isInstanceOfSatisfying(Class<T> type, Consumer<T> requirements) {
objects.assertIsInstanceOf(info, actual, type);
requireNonNull(requirements, "The Consumer<T> expressing the assertions requirements must not be null");
requirements.accept((T) actual);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isInstanceOfAny(Class<?>... types) {
objects.assertIsInstanceOfAny(info, actual, types);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotInstanceOf(Class<?> type) {
objects.assertIsNotInstanceOf(info, actual, type);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotInstanceOfAny(Class<?>... types) {
objects.assertIsNotInstanceOfAny(info, actual, types);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF hasSameClassAs(Object other) {
objects.assertHasSameClassAs(info, actual, other);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF hasToString(String expectedToString) {
objects.assertHasToString(info, actual, expectedToString);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF doesNotHaveSameClassAs(Object other) {
objects.assertDoesNotHaveSameClassAs(info, actual, other);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isExactlyInstanceOf(Class<?> type) {
objects.assertIsExactlyInstanceOf(info, actual, type);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotExactlyInstanceOf(Class<?> type) {
objects.assertIsNotExactlyInstanceOf(info, actual, type);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isOfAnyClassIn(Class<?>... types) {
objects.assertIsOfAnyClassIn(info, actual, types);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotOfAnyClassIn(Class<?>... types) {
objects.assertIsNotOfAnyClassIn(info, actual, types);
return myself;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override
@CheckReturnValue
public AbstractListAssert<?, List<?>, Object, ObjectAssert<Object>> asList() {
objects.assertIsInstanceOf(info, actual, List.class);
return newListAssertInstance((List<Object>) actual).as(info.description());
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public AbstractStringAssert<?> asString() {
objects.assertNotNull(info, actual);
return Assertions.assertThat(actual.toString());
}
/**
* The description of this assertion set with {@link #describedAs(String, Object...)} or
* {@link #describedAs(Description)}.
*
* @return the description String representation of this assertion.
*/
public String descriptionText() {
return info.descriptionText();
}
/**
* Overrides AssertJ default error message by the given one.
* <p>
* You must set it <b>before</b> calling the assertion otherwise it is ignored as the failing assertion breaks
* the chained call by throwing an AssertionError.
* <p>
* The new error message is built using {@link String#format(String, Object...)} if you provide args parameter (if you
* don't, the error message is taken as it is).
* <p>
* Example :
* <pre><code class='java'>assertThat(player.isRookie()).overridingErrorMessage("Expecting Player <%s> to be a rookie but was not.", player)
* .isTrue();</code></pre>
*
* @param newErrorMessage the error message that will replace the default one provided by Assertj.
* @param args the args used to fill error message as in {@link String#format(String, Object...)}.
* @return this assertion object.
*/
@CheckReturnValue
public SELF overridingErrorMessage(String newErrorMessage, Object... args) {
info.overridingErrorMessage(formatIfArgs(newErrorMessage, args));
return myself;
}
/**
* Alternative method for {@link AbstractAssert#overridingErrorMessage}
* <p>
* You must set it <b>before</b> calling the assertion otherwise it is ignored as the failing assertion breaks
* the chained call by throwing an AssertionError.
* <p>
* Example:
* <pre><code class='java'>assertThat(player.isRookie()).withFailMessage("Expecting Player <%s> to be a rookie but was not.", player)
* .isTrue();</code></pre>
* @param newErrorMessage the error message that will replace the default one provided by Assertj.
* @param args the args used to fill error message as in {@link String#format(String, Object...)}.
* @return this assertion object.
*/
@CheckReturnValue
public SELF withFailMessage(String newErrorMessage, Object... args) {
return overridingErrorMessage(newErrorMessage, args);
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF usingComparator(Comparator<? super ACTUAL> customComparator) {
return usingComparator(customComparator, null);
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF usingComparator(Comparator<? super ACTUAL> customComparator, String customComparatorDescription) {
// using a specific strategy to compare actual with other objects.
this.objects = new Objects(new ComparatorBasedComparisonStrategy(customComparator, customComparatorDescription));
return myself;
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF usingDefaultComparator() {
// fall back to default strategy to compare actual with other objects.
this.objects = Objects.instance();
return myself;
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF withThreadDumpOnError() {
Failures.instance().enablePrintThreadDump();
return myself;
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF withRepresentation(Representation representation) {
info.useRepresentation(representation);
return myself;
}
/**
* {@inheritDoc}
*
* @deprecated use {@link #isEqualTo} instead
*
* @throws UnsupportedOperationException if this method is called.
*/
@Override
@Deprecated
public boolean equals(Object obj) {
if (throwUnsupportedExceptionOnEquals) {
throw new UnsupportedOperationException("'equals' is not supported...maybe you intended to call 'isEqualTo'");
}
return super.equals(obj);
}
/**
* Always returns 1.
*
* @return 1.
*/
@Override
public int hashCode() {
return 1;
}
/**
* Verifies that the actual object matches the given predicate.
* <p>
* Example :
*
* <pre><code class='java'> assertThat(player).matches(p -> p.isRookie());</code></pre>
*
* @param predicate the {@link Predicate} to match
* @return {@code this} assertion object.
* @throws AssertionError if the actual does not match the given {@link Predicate}.
* @throws NullPointerException if given {@link Predicate} is null.
*/
public SELF matches(Predicate<? super ACTUAL> predicate) {
// use default PredicateDescription
return matches(predicate, PredicateDescription.GIVEN);
}
/**
* Verifies that the actual object matches the given predicate, the predicate description is used to get an
* informative error message.
* <p>
* Example :
*
* <pre><code class='java'> assertThat(player).matches(p -> p.isRookie(), "is rookie");</code></pre>
*
* The error message contains the predicate description, if the previous assertion fails, it will be:
*
* <pre><code class='java'> Expecting:
* <player>
* to match 'is rookie' predicate.</code></pre>
*
* @param predicate the {@link Predicate} to match
* @param predicateDescription a description of the {@link Predicate} used in the error message
* @return {@code this} assertion object.
* @throws AssertionError if the actual does not match the given {@link Predicate}.
* @throws NullPointerException if given {@link Predicate} is null.
* @throws NullPointerException if given predicateDescription is null.
*/
public SELF matches(Predicate<? super ACTUAL> predicate, String predicateDescription) {
return matches(predicate, new PredicateDescription(predicateDescription));
}
/**
* Verifies that the actual object satisfied the given requirements expressed as a {@link Consumer}.
* <p>
* This is useful to perform a group of assertions on a single object.
* <p>
* Grouping assertions example :
* <pre><code class='java'> // second constructor parameter is the light saber color
* Jedi yoda = new Jedi("Yoda", "Green");
* Jedi luke = new Jedi("Luke Skywalker", "Green");
*
* Consumer<Jedi> jediRequirements = jedi -> {
* assertThat(jedi.getLightSaberColor()).isEqualTo("Green");
* assertThat(jedi.getName()).doesNotContain("Dark");
* };
*
* // assertions succeed:
* assertThat(yoda).satisfies(jediRequirements);
* assertThat(luke).satisfies(jediRequirements);
*
* // assertions fails:
* Jedi vader = new Jedi("Vader", "Red");
* assertThat(vader).satisfies(jediRequirements);</code></pre>
* <p>
* In the following example, {@code satisfies} prevents the need of define a local variable in order to run multiple assertions:
* <pre><code class='java'> // no need to define team.getPlayers().get(0).getStats() as a local variable
* assertThat(team.getPlayers().get(0).getStats()).satisfies(stats -> {
* assertThat(stats.pointPerGame).isGreaterThan(25.7);
* assertThat(stats.assistsPerGame).isGreaterThan(7.2);
* assertThat(stats.reboundsPerGame).isBetween(9, 12);
* };</code></pre>
*
* @param requirements to assert on the actual object - must not be null.
* @return this assertion object.
*
* @throws NullPointerException if given Consumer is null
*/
public SELF satisfies(Consumer<ACTUAL> requirements) {
requireNonNull(requirements, "The Consumer<T> expressing the assertions requirements must not be null");
requirements.accept(actual);
return myself;
}
/**
* Verifies that the actual object under test satisfies at least one of the given assertions group expressed as {@link Consumer}s.
* <p>
* This allows users to perform <b>OR like assertions</b> since only one the assertions group has to be met.
* <p>
* {@link #overridingErrorMessage(String, Object...) Overriding error message} is not supported as it would prevent from
* getting the error messages of the failing assertions, these are valuable to figure out what went wrong.<br>
* Describing the assertion is supported (for example with {@link #as(String, Object...)}).
* <p>
* Example:
* <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", HOBBIT);
*
* Consumer<TolkienCharacter> isHobbit = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(HOBBIT);
* Consumer<TolkienCharacter> isElf = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(ELF);
*
* // assertion succeeds:
* assertThat(frodo).satisfiesAnyOf(isElf, isHobbit);
*
* // assertion fails:
* TolkienCharacter boromir = new TolkienCharacter("Boromir", MAN);
* assertThat(boromir).satisfiesAnyOf(isHobbit, isElf);</code></pre>
*
* @param assertions1 the first group of assertions to run against the object under test - must not be null.
* @param assertions2 the second group of assertions to run against the object under test - must not be null.
* @return this assertion object.
*
* @throws IllegalArgumentException if any given assertions group is null
* @since 3.12.0
*/
// Does not take a Consumer<ACTUAL>... to avoid to use @SafeVarargs to suppress the generic array type safety warning.
// @SafeVarargs requires methods to be final which breaks the proxying mechanism used by soft assertions and assumptions
public SELF satisfiesAnyOf(Consumer<ACTUAL> assertions1, Consumer<ACTUAL> assertions2) {
return satisfiesAnyOfAssertionsGroups(assertions1, assertions2);
}
/**
* Verifies that the actual object under test satisfies at least one of the given assertions group expressed as {@link Consumer}s.
* <p>
* This allows users to perform <b>OR like assertions</b> since only one the assertions group has to be met.
* <p>
* {@link #overridingErrorMessage(String, Object...) Overriding error message} is not supported as it would prevent from
* getting the error messages of the failing assertions, these are valuable to figure out what went wrong.<br>
* Describing the assertion is supported (for example with {@link #as(String, Object...)}).
* <p>
* Example:
* <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", HOBBIT);
*
* Consumer<TolkienCharacter> isHobbit = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(HOBBIT);
* Consumer<TolkienCharacter> isElf = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(ELF);
* Consumer<TolkienCharacter> isOrc = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(ORC);
*
* // assertion succeeds:
* assertThat(frodo).satisfiesAnyOf(isElf, isHobbit, isOrc);
*
* // assertion fails:
* TolkienCharacter boromir = new TolkienCharacter("Boromir", MAN);
* assertThat(boromir).satisfiesAnyOf(isHobbit, isElf, isOrc);</code></pre>
*
* @param assertions1 the first group of assertions to run against the object under test - must not be null.
* @param assertions2 the second group of assertions to run against the object under test - must not be null.
* @param assertions3 the third group of assertions to run against the object under test - must not be null.
* @return this assertion object.
*
* @throws IllegalArgumentException if any given assertions group is null
* @since 3.12.0
*/
// Does not take a Consumer<ACTUAL>... to avoid to use @SafeVarargs to suppress the generic array type safety warning.
// @SafeVarargs requires methods to be final which breaks the proxying mechanism used by soft assertions and assumptions
public SELF satisfiesAnyOf(Consumer<ACTUAL> assertions1, Consumer<ACTUAL> assertions2, Consumer<ACTUAL> assertions3) {
return satisfiesAnyOfAssertionsGroups(assertions1, assertions2, assertions3);
}
// can be final as it is not proxied
@SafeVarargs
private final SELF satisfiesAnyOfAssertionsGroups(Consumer<ACTUAL>... assertionsGroups) throws AssertionError {
checkArgument(stream(assertionsGroups).allMatch(java.util.Objects::nonNull), "No assertions group should be null");
if (stream(assertionsGroups).anyMatch(this::satisfiesAssertions)) return myself;
// none of the assertions group was met! let's report all the errors
List<AssertionError> assertionErrors = stream(assertionsGroups).map(this::catchAssertionError).collect(toList());
throw multipleAssertionsError(assertionErrors);
}
private AssertionError multipleAssertionsError(List<AssertionError> assertionErrors) {
// we don't allow overriding the error message to avoid loosing all the failed assertions error message.
return assertionErrorCreator.multipleAssertionsError(info.description(), assertionErrors);
}
@SuppressWarnings("unchecked")
private boolean satisfiesAssertions(@SuppressWarnings("rawtypes") Consumer assertions) {
try {
assertions.accept(actual);
} catch (AssertionError e) {
return false;
}
return true;
}
@SuppressWarnings("unchecked")
private AssertionError catchAssertionError(@SuppressWarnings("rawtypes") Consumer assertions) {
try {
assertions.accept(actual);
} catch (AssertionError assertionError) {
return assertionError;
}
throw new IllegalStateException("Shouldn't arrived here, assertions should have raised an AssertionError (please file a bug)");
}
private SELF matches(Predicate<? super ACTUAL> predicate, PredicateDescription predicateDescription) {
requireNonNull(predicate, "The predicate must not be null");
if (predicate.test(actual)) return myself;
throw Failures.instance().failure(info, shouldMatch(actual, predicate, predicateDescription));
}
public static void setCustomRepresentation(Representation customRepresentation) {
ConfigurationProvider.loadRegisteredConfiguration();
AbstractAssert.customRepresentation = customRepresentation;
}
/** {@inheritDoc} */
@Override
public SELF hasSameHashCodeAs(Object other) {
objects.assertHasSameHashCodeAs(info, actual, other);
return myself;
}
/**
* Create a {@link AbstractListAssert}.
* <p>
* Implementations need to redefine either to be proxy friendly (i.e. no final assertion methods like {@link ProxyableListAssert})
* or generic vararg friendly (to use {@link SafeVarargs} annotation which requires final method)like {@link ListAssert}.
* <p>
* The default implementation will assume that this concrete implementation is NOT a soft assertion.
*
* @param <E> the type of elements.
* @param newActual new value
* @return a new {@link AbstractListAssert}.
*/
protected <E> AbstractListAssert<?, List<? extends E>, E, ObjectAssert<E>> newListAssertInstance(List<? extends E> newActual) {
return new ListAssert<>(newActual);
}
SELF withAssertionState(@SuppressWarnings("rawtypes") AbstractAssert assertInstance) {
this.objects = assertInstance.objects;
propagateAssertionInfoFrom(assertInstance);
return myself;
}
private void propagateAssertionInfoFrom(AbstractAssert<?, ?> assertInstance) {
this.info.useRepresentation(assertInstance.info.representation());
this.info.description(assertInstance.info.description());
this.info.overridingErrorMessage(assertInstance.info.overridingErrorMessage());
}
// this method is meant to be overridden and made public in subclasses that want to expose it
// this would avoid duplicating this code in all subclasses
protected RecursiveComparisonAssert<?> usingRecursiveComparison(RecursiveComparisonConfiguration recursiveComparisonConfiguration) {
return new RecursiveComparisonAssert<>(actual, recursiveComparisonConfiguration).withAssertionState(myself);
}
// this method is meant to be overridden and made public in subclasses that want to expose it
// this would avoid duplicating this code in all subclasses
protected RecursiveComparisonAssert<?> usingRecursiveComparison() {
return usingRecursiveComparison(new RecursiveComparisonConfiguration());
}
}
|
src/main/java/org/assertj/core/api/AbstractAssert.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.
*
* Copyright 2012-2020 the original author or authors.
*/
package org.assertj.core.api;
import static java.util.Arrays.stream;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.error.ShouldMatch.shouldMatch;
import static org.assertj.core.error.ShouldNotBeNull.shouldNotBeNull;
import static org.assertj.core.util.Preconditions.checkArgument;
import static org.assertj.core.util.Strings.formatIfArgs;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration;
import org.assertj.core.configuration.ConfigurationProvider;
import org.assertj.core.description.Description;
import org.assertj.core.error.AssertionErrorCreator;
import org.assertj.core.error.BasicErrorMessageFactory;
import org.assertj.core.error.ErrorMessageFactory;
import org.assertj.core.error.MessageFormatter;
import org.assertj.core.internal.ComparatorBasedComparisonStrategy;
import org.assertj.core.internal.Conditions;
import org.assertj.core.internal.Failures;
import org.assertj.core.internal.Objects;
import org.assertj.core.presentation.PredicateDescription;
import org.assertj.core.presentation.Representation;
import org.assertj.core.util.CheckReturnValue;
import org.assertj.core.util.VisibleForTesting;
/**
* Base class for all assertions.
*
* @param <SELF> the "self" type of this assertion class. Please read "<a href="http://bit.ly/1IZIRcY"
* target="_blank">Emulating 'self types' using Java Generics to simplify fluent API implementation</a>"
* for more details.
* @param <ACTUAL> the type of the "actual" value.
*
* @author Alex Ruiz
* @author Joel Costigliola
* @author Mikhail Mazursky
* @author Nicolas François
*/
public abstract class AbstractAssert<SELF extends AbstractAssert<SELF, ACTUAL>, ACTUAL> implements Assert<SELF, ACTUAL> {
// https://github.com/joel-costigliola/assertj-core/issues/1128
public static boolean throwUnsupportedExceptionOnEquals = true;
private static final String ORG_ASSERTJ = "org.assert";
protected Objects objects = Objects.instance();
@VisibleForTesting
Conditions conditions = Conditions.instance();
@VisibleForTesting
public WritableAssertionInfo info;
// visibility is protected to allow us write custom assertions that need access to actual
@VisibleForTesting
protected final ACTUAL actual;
protected final SELF myself;
// = ConfigurationProvider.CONFIGURATION_PROVIDER.representation(); ?
private static Representation customRepresentation = null;
@VisibleForTesting
AssertionErrorCreator assertionErrorCreator;
// we prefer not to use Class<? extends S> selfType because it would force inherited
// constructor to cast with a compiler warning
// let's keep compiler warning internal (when we can) and not expose them to our end users.
@SuppressWarnings("unchecked")
public AbstractAssert(ACTUAL actual, Class<?> selfType) {
myself = (SELF) selfType.cast(this);
this.actual = actual;
info = new WritableAssertionInfo(customRepresentation);
assertionErrorCreator = new AssertionErrorCreator();
}
/**
* Exposes the {@link WritableAssertionInfo} used in the current assertion for better extensibility.<br> When writing
* your own assertion class, you can use the returned {@link WritableAssertionInfo} to change the error message and
* still keep the description set by the assertion user.
*
* @return the {@link WritableAssertionInfo} used in the current assertion
*/
public WritableAssertionInfo getWritableAssertionInfo() {
return info;
}
/**
* Utility method to ease writing custom assertions classes using {@link String#format(String, Object...)} specifiers
* in error message.
* <p>
* Moreover, this method honors any description set with {@link #as(String, Object...)} or overridden error message
* defined by the user with {@link #overridingErrorMessage(String, Object...)}.
* <p>
* Example :
* <pre><code class='java'> public TolkienCharacterAssert hasName(String name) {
* // check that actual TolkienCharacter we want to make assertions on is not null.
* isNotNull();
*
* // check condition
* if (!actual.getName().equals(name)) {
* failWithMessage("Expected character's name to be <%s> but was <%s>", name, actual.getName());
* }
*
* // return the current assertion for method chaining
* return this;
* }</code></pre>
*
* @param errorMessage the error message to format
* @param arguments the arguments referenced by the format specifiers in the errorMessage string.
*/
protected void failWithMessage(String errorMessage, Object... arguments) {
AssertionError assertionError = Failures.instance().failureIfErrorMessageIsOverridden(info);
if (assertionError == null) {
// error message was not overridden, build it.
String description = MessageFormatter.instance().format(info.description(), info.representation(), "");
assertionError = new AssertionError(description + String.format(errorMessage, arguments));
}
Failures.instance().removeAssertJRelatedElementsFromStackTraceIfNeeded(assertionError);
removeCustomAssertRelatedElementsFromStackTraceIfNeeded(assertionError);
throw assertionError;
}
/**
* Utility method to throw an {@link AssertionError} given a {@link BasicErrorMessageFactory}.
* <p>
* Instead of writing ...
*
* <pre><code class='java'> throw Failures.instance().failure(info, ShouldBePresent.shouldBePresent());</code></pre>
* ... you can simply write :
*
* <pre><code class='java'> throwAssertionError(info, ShouldBePresent.shouldBePresent());</code></pre>
*
* @param errorMessageFactory used to define the error message.
* @throws AssertionError with a message corresponding to the given {@link BasicErrorMessageFactory}.
*/
protected void throwAssertionError(ErrorMessageFactory errorMessageFactory) {
AssertionError failure = assertionError(errorMessageFactory);
throw failure;
}
protected AssertionError assertionError(ErrorMessageFactory errorMessageFactory) {
AssertionError failure = Failures.instance().failure(info, errorMessageFactory);
removeCustomAssertRelatedElementsFromStackTraceIfNeeded(failure);
return failure;
}
private void removeCustomAssertRelatedElementsFromStackTraceIfNeeded(AssertionError assertionError) {
if (!Failures.instance().isRemoveAssertJRelatedElementsFromStackTrace()) return;
if (isAssertjAssertClass()) return;
StackTraceElement[] newStackTrace = Arrays.stream(assertionError.getStackTrace())
.filter(element -> !isElementOfCustomAssert(element))
.toArray(StackTraceElement[]::new);
assertionError.setStackTrace(newStackTrace);
}
private boolean isAssertjAssertClass() {
return getClass().getName().startsWith(ORG_ASSERTJ);
}
private boolean isElementOfCustomAssert(StackTraceElement stackTraceElement) {
Class<?> currentAssertClass = getClass();
while (currentAssertClass != AbstractAssert.class) {
if (stackTraceElement.getClassName().equals(currentAssertClass.getName())) {
return true;
}
currentAssertClass = currentAssertClass.getSuperclass();
}
return false;
}
/**
* Use hexadecimal object representation instead of standard representation in error messages.
* <p>
* It can be useful when comparing UNICODE characters - many unicode chars have duplicate characters assigned, it is
* thus impossible to find differences from the standard error message:
* <p>
* With standard message:
* <pre><code class='java'> assertThat("µµµ").contains("μμμ");
*
* java.lang.AssertionError:
* Expecting:
* <"µµµ">
* to contain:
* <"μμμ"></code></pre>
*
* With Hexadecimal message:
* <pre><code class='java'> assertThat("µµµ").inHexadecimal().contains("μμμ");
*
* java.lang.AssertionError:
* Expecting:
* <"['00B5', '00B5', '00B5']">
* to contain:
* <"['03BC', '03BC', '03BC']"></code></pre>
*
* @return {@code this} assertion object.
*/
@CheckReturnValue
protected SELF inHexadecimal() {
info.useHexadecimalRepresentation();
return myself;
}
/**
* Use binary object representation instead of standard representation in error messages.
* <p>
* Example:
* <pre><code class='java'> assertThat(1).inBinary().isEqualTo(2);
*
* org.junit.ComparisonFailure:
* Expected :0b00000000_00000000_00000000_00000010
* Actual :0b00000000_00000000_00000000_00000001</code></pre>
*
* @return {@code this} assertion object.
*/
@CheckReturnValue
protected SELF inBinary() {
info.useBinaryRepresentation();
return myself;
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF describedAs(Description description) {
info.description(description);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isEqualTo(Object expected) {
objects.assertEqual(info, actual, expected);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotEqualTo(Object other) {
objects.assertNotEqual(info, actual, other);
return myself;
}
/** {@inheritDoc} */
@Override
public void isNull() {
objects.assertNull(info, actual);
}
/** {@inheritDoc} */
@Override
public SELF isNotNull() {
objects.assertNotNull(info, actual);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isSameAs(Object expected) {
objects.assertSame(info, actual, expected);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotSameAs(Object other) {
objects.assertNotSame(info, actual, other);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isIn(Object... values) {
objects.assertIsIn(info, actual, values);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotIn(Object... values) {
objects.assertIsNotIn(info, actual, values);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isIn(Iterable<?> values) {
objects.assertIsIn(info, actual, values);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotIn(Iterable<?> values) {
objects.assertIsNotIn(info, actual, values);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF is(Condition<? super ACTUAL> condition) {
conditions.assertIs(info, actual, condition);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNot(Condition<? super ACTUAL> condition) {
conditions.assertIsNot(info, actual, condition);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF has(Condition<? super ACTUAL> condition) {
conditions.assertHas(info, actual, condition);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF doesNotHave(Condition<? super ACTUAL> condition) {
conditions.assertDoesNotHave(info, actual, condition);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF satisfies(Condition<? super ACTUAL> condition) {
conditions.assertSatisfies(info, actual, condition);
return myself;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override
@CheckReturnValue
public <ASSERT extends AbstractAssert<?, ?>> ASSERT asInstanceOf(InstanceOfAssertFactory<?, ASSERT> instanceOfAssertFactory) {
requireNonNull(instanceOfAssertFactory, shouldNotBeNull("instanceOfAssertFactory").create());
objects.assertIsInstanceOf(info, actual, instanceOfAssertFactory.getType());
return (ASSERT) instanceOfAssertFactory.createAssert(actual).withAssertionState(myself);
}
/** {@inheritDoc} */
@Override
public SELF isInstanceOf(Class<?> type) {
objects.assertIsInstanceOf(info, actual, type);
return myself;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override
public <T> SELF isInstanceOfSatisfying(Class<T> type, Consumer<T> requirements) {
objects.assertIsInstanceOf(info, actual, type);
requireNonNull(requirements, "The Consumer<T> expressing the assertions requirements must not be null");
requirements.accept((T) actual);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isInstanceOfAny(Class<?>... types) {
objects.assertIsInstanceOfAny(info, actual, types);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotInstanceOf(Class<?> type) {
objects.assertIsNotInstanceOf(info, actual, type);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotInstanceOfAny(Class<?>... types) {
objects.assertIsNotInstanceOfAny(info, actual, types);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF hasSameClassAs(Object other) {
objects.assertHasSameClassAs(info, actual, other);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF hasToString(String expectedToString) {
objects.assertHasToString(info, actual, expectedToString);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF doesNotHaveSameClassAs(Object other) {
objects.assertDoesNotHaveSameClassAs(info, actual, other);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isExactlyInstanceOf(Class<?> type) {
objects.assertIsExactlyInstanceOf(info, actual, type);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotExactlyInstanceOf(Class<?> type) {
objects.assertIsNotExactlyInstanceOf(info, actual, type);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isOfAnyClassIn(Class<?>... types) {
objects.assertIsOfAnyClassIn(info, actual, types);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotOfAnyClassIn(Class<?>... types) {
objects.assertIsNotOfAnyClassIn(info, actual, types);
return myself;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override
@CheckReturnValue
public AbstractListAssert<?, List<?>, Object, ObjectAssert<Object>> asList() {
objects.assertIsInstanceOf(info, actual, List.class);
return newListAssertInstance((List<Object>) actual).as(info.description());
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public AbstractStringAssert<?> asString() {
objects.assertNotNull(info, actual);
return Assertions.assertThat(actual.toString());
}
/**
* The description of this assertion set with {@link #describedAs(String, Object...)} or
* {@link #describedAs(Description)}.
*
* @return the description String representation of this assertion.
*/
public String descriptionText() {
return info.descriptionText();
}
/**
* Overrides AssertJ default error message by the given one.
* <p>
* You must set it <b>before</b> calling the assertion otherwise it is ignored as the failing assertion breaks
* the chained call by throwing an AssertionError.
* <p>
* The new error message is built using {@link String#format(String, Object...)} if you provide args parameter (if you
* don't, the error message is taken as it is).
* <p>
* Example :
* <pre><code class='java'>assertThat(player.isRookie()).overridingErrorMessage("Expecting Player <%s> to be a rookie but was not.", player)
* .isTrue();</code></pre>
*
* @param newErrorMessage the error message that will replace the default one provided by Assertj.
* @param args the args used to fill error message as in {@link String#format(String, Object...)}.
* @return this assertion object.
*/
@CheckReturnValue
public SELF overridingErrorMessage(String newErrorMessage, Object... args) {
info.overridingErrorMessage(formatIfArgs(newErrorMessage, args));
return myself;
}
/**
* Alternative method for {@link AbstractAssert#overridingErrorMessage}
* <p>
* You must set it <b>before</b> calling the assertion otherwise it is ignored as the failing assertion breaks
* the chained call by throwing an AssertionError.
* <p>
* Example:
* <pre><code class='java'>assertThat(player.isRookie()).withFailMessage("Expecting Player <%s> to be a rookie but was not.", player)
* .isTrue();</code></pre>
* @param newErrorMessage the error message that will replace the default one provided by Assertj.
* @param args the args used to fill error message as in {@link String#format(String, Object...)}.
* @return this assertion object.
*/
@CheckReturnValue
public SELF withFailMessage(String newErrorMessage, Object... args) {
return overridingErrorMessage(newErrorMessage, args);
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF usingComparator(Comparator<? super ACTUAL> customComparator) {
return usingComparator(customComparator, null);
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF usingComparator(Comparator<? super ACTUAL> customComparator, String customComparatorDescription) {
// using a specific strategy to compare actual with other objects.
this.objects = new Objects(new ComparatorBasedComparisonStrategy(customComparator, customComparatorDescription));
return myself;
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF usingDefaultComparator() {
// fall back to default strategy to compare actual with other objects.
this.objects = Objects.instance();
return myself;
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF withThreadDumpOnError() {
Failures.instance().enablePrintThreadDump();
return myself;
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF withRepresentation(Representation representation) {
info.useRepresentation(representation);
return myself;
}
/**
* {@inheritDoc}
*
* @deprecated use {@link #isEqualTo} instead
*
* @throws UnsupportedOperationException if this method is called.
*/
@Override
@Deprecated
public boolean equals(Object obj) {
if (throwUnsupportedExceptionOnEquals) {
throw new UnsupportedOperationException("'equals' is not supported...maybe you intended to call 'isEqualTo'");
}
return super.equals(obj);
}
/**
* Always returns 1.
*
* @return 1.
*/
@Override
public int hashCode() {
return 1;
}
/**
* Verifies that the actual object matches the given predicate.
* <p>
* Example :
*
* <pre><code class='java'> assertThat(player).matches(p -> p.isRookie());</code></pre>
*
* @param predicate the {@link Predicate} to match
* @return {@code this} assertion object.
* @throws AssertionError if the actual does not match the given {@link Predicate}.
* @throws NullPointerException if given {@link Predicate} is null.
*/
public SELF matches(Predicate<? super ACTUAL> predicate) {
// use default PredicateDescription
return matches(predicate, PredicateDescription.GIVEN);
}
/**
* Verifies that the actual object matches the given predicate, the predicate description is used to get an
* informative error message.
* <p>
* Example :
*
* <pre><code class='java'> assertThat(player).matches(p -> p.isRookie(), "is rookie");</code></pre>
*
* The error message contains the predicate description, if the previous assertion fails, it will be:
*
* <pre><code class='java'> Expecting:
* <player>
* to match 'is rookie' predicate.</code></pre>
*
* @param predicate the {@link Predicate} to match
* @param predicateDescription a description of the {@link Predicate} used in the error message
* @return {@code this} assertion object.
* @throws AssertionError if the actual does not match the given {@link Predicate}.
* @throws NullPointerException if given {@link Predicate} is null.
* @throws NullPointerException if given predicateDescription is null.
*/
public SELF matches(Predicate<? super ACTUAL> predicate, String predicateDescription) {
return matches(predicate, new PredicateDescription(predicateDescription));
}
/**
* Verifies that the actual object satisfied the given requirements expressed as a {@link Consumer}.
* <p>
* This is useful to perform a group of assertions on a single object.
* <p>
* Grouping assertions example :
* <pre><code class='java'> // second constructor parameter is the light saber color
* Jedi yoda = new Jedi("Yoda", "Green");
* Jedi luke = new Jedi("Luke Skywalker", "Green");
*
* Consumer<Jedi> jediRequirements = jedi -> {
* assertThat(jedi.getLightSaberColor()).isEqualTo("Green");
* assertThat(jedi.getName()).doesNotContain("Dark");
* };
*
* // assertions succeed:
* assertThat(yoda).satisfies(jediRequirements);
* assertThat(luke).satisfies(jediRequirements);
*
* // assertions fails:
* Jedi vader = new Jedi("Vader", "Red");
* assertThat(vader).satisfies(jediRequirements);</code></pre>
* <p>
* In the following example, {@code satisfies} prevents the need of define a local variable in order to run multiple assertions:
* <pre><code class='java'> // no need to define team.getPlayers().get(0).getStats() as a local variable
* assertThat(team.getPlayers().get(0).getStats()).satisfies(stats -> {
* assertThat(stats.pointPerGame).isGreaterThan(25.7);
* assertThat(stats.assistsPerGame).isGreaterThan(7.2);
* assertThat(stats.reboundsPerGame).isBetween(9, 12);
* };</code></pre>
*
* @param requirements to assert on the actual object - must not be null.
* @return this assertion object.
*
* @throws NullPointerException if given Consumer is null
*/
public SELF satisfies(Consumer<ACTUAL> requirements) {
requireNonNull(requirements, "The Consumer<T> expressing the assertions requirements must not be null");
requirements.accept(actual);
return myself;
}
/**
* Verifies that the actual object under test satisfies at least one of the given assertions group expressed as {@link Consumer}s.
* <p>
* This allows users to perform <b>OR like assertions</b> since only one the assertions group has to be met.
* <p>
* {@link #overridingErrorMessage(String, Object...) Overriding error message} is not supported as it would prevent from
* getting the error messages of the failing assertions, these are valuable to figure out what went wrong.<br>
* Describing the assertion is supported (for example with {@link #as(String, Object...)}).
* <p>
* Example:
* <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", HOBBIT);
*
* Consumer<TolkienCharacter> isHobbit = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(HOBBIT);
* Consumer<TolkienCharacter> isElf = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(ELF);
*
* // assertion succeeds:
* assertThat(frodo).satisfiesAnyOf(isElf, isHobbit);
*
* // assertion fails:
* TolkienCharacter boromir = new TolkienCharacter("Boromir", MAN);
* assertThat(boromir).satisfiesAnyOf(isHobbit, isElf);</code></pre>
*
* @param assertions1 the first group of assertions to run against the object under test - must not be null.
* @param assertions2 the second group of assertions to run against the object under test - must not be null.
* @return this assertion object.
*
* @throws IllegalArgumentException if any given assertions group is null
* @since 3.12.0
*/
// Does not take a Consumer<ACTUAL>... to avoid to use @SafeVarargs to suppress the generic array type safety warning.
// @SafeVarargs requires methods to be final which breaks the proxying mechanism used by soft assertions and assumptions
public SELF satisfiesAnyOf(Consumer<ACTUAL> assertions1, Consumer<ACTUAL> assertions2) {
return satisfiesAnyOfAssertionsGroups(assertions1, assertions2);
}
/**
* Verifies that the actual object under test satisfies at least one of the given assertions group expressed as {@link Consumer}s.
* <p>
* This allows users to perform <b>OR like assertions</b> since only one the assertions group has to be met.
* <p>
* {@link #overridingErrorMessage(String, Object...) Overriding error message} is not supported as it would prevent from
* getting the error messages of the failing assertions, these are valuable to figure out what went wrong.<br>
* Describing the assertion is supported (for example with {@link #as(String, Object...)}).
* <p>
* Example:
* <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", HOBBIT);
*
* Consumer<TolkienCharacter> isHobbit = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(HOBBIT);
* Consumer<TolkienCharacter> isElf = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(ELF);
* Consumer<TolkienCharacter> isOrc = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(ORC);
*
* // assertion succeeds:
* assertThat(frodo).satisfiesAnyOf(isElf, isHobbit, isOrc);
*
* // assertion fails:
* TolkienCharacter boromir = new TolkienCharacter("Boromir", MAN);
* assertThat(boromir).satisfiesAnyOf(isHobbit, isElf, isOrc);</code></pre>
*
* @param assertions1 the first group of assertions to run against the object under test - must not be null.
* @param assertions2 the second group of assertions to run against the object under test - must not be null.
* @param assertions3 the third group of assertions to run against the object under test - must not be null.
* @return this assertion object.
*
* @throws IllegalArgumentException if any given assertions group is null
* @since 3.12.0
*/
// Does not take a Consumer<ACTUAL>... to avoid to use @SafeVarargs to suppress the generic array type safety warning.
// @SafeVarargs requires methods to be final which breaks the proxying mechanism used by soft assertions and assumptions
public SELF satisfiesAnyOf(Consumer<ACTUAL> assertions1, Consumer<ACTUAL> assertions2, Consumer<ACTUAL> assertions3) {
return satisfiesAnyOfAssertionsGroups(assertions1, assertions2, assertions3);
}
// can be final as it is not proxied
@SafeVarargs
private final SELF satisfiesAnyOfAssertionsGroups(Consumer<ACTUAL>... assertionsGroups) throws AssertionError {
checkArgument(stream(assertionsGroups).allMatch(java.util.Objects::nonNull), "No assertions group should be null");
if (stream(assertionsGroups).anyMatch(this::satisfiesAssertions)) return myself;
// none of the assertions group was met! let's report all the errors
List<AssertionError> assertionErrors = stream(assertionsGroups).map(this::catchAssertionError).collect(toList());
throw multipleAssertionsError(assertionErrors);
}
private AssertionError multipleAssertionsError(List<AssertionError> assertionErrors) {
// we don't allow overriding the error message to avoid loosing all the failed assertions error message.
return assertionErrorCreator.multipleAssertionsError(info.description(), assertionErrors);
}
@SuppressWarnings("unchecked")
private boolean satisfiesAssertions(@SuppressWarnings("rawtypes") Consumer assertions) {
try {
assertions.accept(actual);
} catch (AssertionError e) {
return false;
}
return true;
}
@SuppressWarnings("unchecked")
private AssertionError catchAssertionError(@SuppressWarnings("rawtypes") Consumer assertions) {
try {
assertions.accept(actual);
} catch (AssertionError assertionError) {
return assertionError;
}
throw new IllegalStateException("Shouldn't arrived here, assertions should have raised an AssertionError (please file a bug)");
}
private SELF matches(Predicate<? super ACTUAL> predicate, PredicateDescription predicateDescription) {
requireNonNull(predicate, "The predicate must not be null");
if (predicate.test(actual)) return myself;
throw Failures.instance().failure(info, shouldMatch(actual, predicate, predicateDescription));
}
public static void setCustomRepresentation(Representation customRepresentation) {
ConfigurationProvider.loadRegisteredConfiguration();
AbstractAssert.customRepresentation = customRepresentation;
}
/** {@inheritDoc} */
@Override
public SELF hasSameHashCodeAs(Object other) {
objects.assertHasSameHashCodeAs(info, actual, other);
return myself;
}
/**
* Create a {@link AbstractListAssert}.
* <p>
* Implementations need to redefine either to be proxy friendly (i.e. no final assertion methods like {@link ProxyableListAssert})
* or generic vararg friendly (to use {@link SafeVarargs} annotation which requires final method)like {@link ListAssert}.
* <p>
* The default implementation will assume that this concrete implementation is NOT a soft assertion.
*
* @param <E> the type of elements.
* @param newActual new value
* @return a new {@link AbstractListAssert}.
*/
protected <E> AbstractListAssert<?, List<? extends E>, E, ObjectAssert<E>> newListAssertInstance(List<? extends E> newActual) {
return new ListAssert<>(newActual);
}
SELF withAssertionState(@SuppressWarnings("rawtypes") AbstractAssert assertInstance) {
this.objects = assertInstance.objects;
propagateAssertionInfoFrom(assertInstance);
return myself;
}
private void propagateAssertionInfoFrom(AbstractAssert<?, ?> assertInstance) {
this.info.useRepresentation(assertInstance.info.representation());
this.info.description(assertInstance.info.description());
this.info.overridingErrorMessage(assertInstance.info.overridingErrorMessage());
}
// this method is meant to be ovverridden and made public in subclasses that want to expose it
// this would avoid duplicating this code in all subclasses
protected RecursiveComparisonAssert<?> usingRecursiveComparison(RecursiveComparisonConfiguration recursiveComparisonConfiguration) {
return new RecursiveComparisonAssert<>(actual, recursiveComparisonConfiguration).withAssertionState(myself);
}
// this method is meant to be ovverridden and made public in subclasses that want to expose it
// this would avoid duplicating this code in all subclasses
protected RecursiveComparisonAssert<?> usingRecursiveComparison() {
return usingRecursiveComparison(new RecursiveComparisonConfiguration());
}
}
|
Fix typos
|
src/main/java/org/assertj/core/api/AbstractAssert.java
|
Fix typos
|
<ide><path>rc/main/java/org/assertj/core/api/AbstractAssert.java
<ide> * @throws AssertionError with a message corresponding to the given {@link BasicErrorMessageFactory}.
<ide> */
<ide> protected void throwAssertionError(ErrorMessageFactory errorMessageFactory) {
<del> AssertionError failure = assertionError(errorMessageFactory);
<del> throw failure;
<add> throw assertionError(errorMessageFactory);
<ide> }
<ide>
<ide> protected AssertionError assertionError(ErrorMessageFactory errorMessageFactory) {
<ide> this.info.overridingErrorMessage(assertInstance.info.overridingErrorMessage());
<ide> }
<ide>
<del> // this method is meant to be ovverridden and made public in subclasses that want to expose it
<add> // this method is meant to be overridden and made public in subclasses that want to expose it
<ide> // this would avoid duplicating this code in all subclasses
<ide> protected RecursiveComparisonAssert<?> usingRecursiveComparison(RecursiveComparisonConfiguration recursiveComparisonConfiguration) {
<ide> return new RecursiveComparisonAssert<>(actual, recursiveComparisonConfiguration).withAssertionState(myself);
<ide> }
<ide>
<del> // this method is meant to be ovverridden and made public in subclasses that want to expose it
<add> // this method is meant to be overridden and made public in subclasses that want to expose it
<ide> // this would avoid duplicating this code in all subclasses
<ide> protected RecursiveComparisonAssert<?> usingRecursiveComparison() {
<ide> return usingRecursiveComparison(new RecursiveComparisonConfiguration());
|
|
Java
|
apache-2.0
|
24d6a34951bc52af226800db20a4497711dc2de6
| 0 |
facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho
|
/*
* Copyright 2014-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.litho;
import static androidx.core.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
import static com.facebook.litho.Component.isHostSpec;
import static com.facebook.litho.Component.isMountViewSpec;
import static com.facebook.litho.ComponentHostUtils.maybeInvalidateAccessibilityState;
import static com.facebook.litho.ComponentHostUtils.maybeSetDrawableState;
import static com.facebook.litho.FrameworkLogEvents.EVENT_MOUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_IS_DIRTY;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_CONTENT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_EXTRAS;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_TIME;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MOVED_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_NO_OP_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UNCHANGED_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UNMOUNTED_CONTENT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UNMOUNTED_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UNMOUNTED_TIME;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UPDATED_CONTENT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UPDATED_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UPDATED_TIME;
import static com.facebook.litho.FrameworkLogEvents.PARAM_VISIBILITY_HANDLER;
import static com.facebook.litho.FrameworkLogEvents.PARAM_VISIBILITY_HANDLERS_TOTAL_TIME;
import static com.facebook.litho.FrameworkLogEvents.PARAM_VISIBILITY_HANDLER_TIME;
import static com.facebook.litho.ThreadUtils.assertMainThread;
import android.animation.AnimatorInflater;
import android.animation.StateListAnimator;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.collection.LongSparseArray;
import androidx.core.view.ViewCompat;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.litho.animation.AnimatedProperties;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.drawable.ComparableDrawable;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Encapsulates the mounted state of a {@link Component}. Provides APIs to update state by recycling
* existing UI elements e.g. {@link Drawable}s.
*
* @see #mount(LayoutState, Rect, boolean)
* @see LithoView
* @see LayoutState
*/
@ThreadConfined(ThreadConfined.UI)
class MountState implements TransitionManager.OnAnimationCompleteListener {
static final long ROOT_HOST_ID = 0L;
private static final double NS_IN_MS = 1000000.0;
private static final BitSet sEmptyBitSet = new BitSet(0);
// Holds the current list of mounted items.
// Should always be used within a draw lock.
private final LongSparseArray<MountItem> mIndexToItemMap;
// Holds a list with information about the components linked to the VisibilityOutputs that are
// stored in LayoutState. An item is inserted in this map if its corresponding component is
// visible. When the component exits the viewport, the item associated with it is removed from the
// map.
private final LongSparseArray<VisibilityItem> mVisibilityIdToItemMap;
// Holds a list of MountItems that are currently mounted which can mount incrementally.
private final LongSparseArray<MountItem> mCanMountIncrementallyMountItems;
// A map from test key to a list of one or more `TestItem`s which is only allocated
// and populated during test runs.
private final Map<String, Deque<TestItem>> mTestItemMap;
// Both these arrays are updated in prepareMount(), thus during mounting they hold the information
// about the LayoutState that is being mounted, not mLastMountedLayoutState
@Nullable private long[] mLayoutOutputsIds;
@Nullable private BitSet mSkipMounting;
// True if we are receiving a new LayoutState and we need to completely
// refresh the content of the HostComponent. Always set from the main thread.
private boolean mIsDirty;
// See #needsRemount()
private boolean mNeedsRemount;
// Holds the list of known component hosts during a mount pass.
private final LongSparseArray<ComponentHost> mHostsByMarker = new LongSparseArray<>();
private static final Rect sTempRect = new Rect();
private static final Rect sTempRect2 = new Rect();
private final ComponentContext mContext;
private final LithoView mLithoView;
private final Rect mPreviousLocalVisibleRect = new Rect();
private final PrepareMountStats mPrepareMountStats = new PrepareMountStats();
private final MountStats mMountStats = new MountStats();
private int mPreviousTopsIndex;
private int mPreviousBottomsIndex;
private int mLastMountedComponentTreeId = ComponentTree.INVALID_ID;
private LayoutState mLastMountedLayoutState;
private boolean mIsFirstMountOfComponentTree = false;
private final MountItem mRootHostMountItem;
private TransitionManager mTransitionManager;
private final HashSet<TransitionId> mAnimatingTransitionIds = new HashSet<>();
private int[] mAnimationLockedIndices;
private final Map<TransitionId, OutputUnitsAffinityGroup<MountItem>> mDisappearingMountItems =
new LinkedHashMap<>();
private @Nullable Transition mRootTransition;
private boolean mTransitionsHasBeenCollected = false;
private final Set<Long> mComponentIdsMountedInThisFrame = new HashSet<>();
public MountState(LithoView view) {
mIndexToItemMap = new LongSparseArray<>();
mVisibilityIdToItemMap = new LongSparseArray<>();
mCanMountIncrementallyMountItems = new LongSparseArray<>();
mContext = view.getComponentContext();
mLithoView = view;
mIsDirty = true;
mTestItemMap = ComponentsConfiguration.isEndToEndTestRun
? new HashMap<String, Deque<TestItem>>()
: null;
// The mount item representing the top-level root host (LithoView) which
// is always automatically mounted.
mRootHostMountItem = MountItem.createRootHostMountItem(mLithoView);
}
/**
* To be called whenever the components needs to start the mount process from scratch
* e.g. when the component's props or layout change or when the components
* gets attached to a host.
*/
void setDirty() {
assertMainThread();
mIsDirty = true;
mPreviousLocalVisibleRect.setEmpty();
}
boolean isDirty() {
assertMainThread();
return mIsDirty;
}
/**
* True if we have manually unmounted content (e.g. via unmountAllItems) which means that while we
* may not have a new LayoutState, the mounted content does not match what the viewport for the
* LithoView may be.
*/
boolean needsRemount() {
assertMainThread();
return mNeedsRemount;
}
/**
* Sets whether the next mount will be the first mount of this ComponentTree. This is used to
* determine whether to run animations or not (we want animations to run on the first mount of
* this ComponentTree, but not other times the mounted ComponentTree id changes). Ideally, we want
* animations to only occur when the ComponentTree is updated on screen or is first inserted into
* a list onscreen, but that requires more integration with the list controller, e.g. sections,
* than we currently have.
*/
void setIsFirstMountOfComponentTree() {
assertMainThread();
mIsFirstMountOfComponentTree = true;
}
/**
* Mount the layoutState on the pre-set HostView.
*
* @param layoutState
* @param localVisibleRect If this variable is null, then mount everything, since incremental
* mount is not enabled. Otherwise mount only what the rect (in local coordinates) contains
* @param processVisibilityOutputs whether to process visibility outputs as part of the mount
*/
void mount(LayoutState layoutState, Rect localVisibleRect, boolean processVisibilityOutputs) {
assertMainThread();
if (layoutState == null) {
throw new IllegalStateException("Trying to mount a null layoutState");
}
final ComponentTree componentTree = mLithoView.getComponentTree();
final boolean isIncrementalMountEnabled = localVisibleRect != null;
final boolean isTracing = ComponentsSystrace.isTracing();
if (isTracing) {
final StringBuilder sectionName =
new StringBuilder(isIncrementalMountEnabled ? "incrementalMount" : "mount")
.append("_")
.append(componentTree.getSimpleName());
final String logTag = componentTree.getContext().getLogTag();
if (logTag != null) {
sectionName.append("_").append(logTag);
}
ComponentsSystrace.beginSectionWithArgs(sectionName.toString())
.arg("treeId", layoutState.getComponentTreeId())
.flush();
}
final ComponentsLogger logger = componentTree.getContext().getLogger();
final int componentTreeId = layoutState.getComponentTreeId();
if (componentTreeId != mLastMountedComponentTreeId) {
// If we're mounting a new ComponentTree, don't keep around and use the previous LayoutState
// since things like transition animations aren't relevant.
mLastMountedLayoutState = null;
}
final PerfEvent mountPerfEvent =
logger == null
? null
: LogTreePopulator.populatePerfEventFromLogger(
componentTree.getContext(),
logger,
logger.newPerformanceEvent(componentTree.getContext(), EVENT_MOUNT));
if (mIsDirty) {
updateTransitions(layoutState, componentTree);
suppressInvalidationsOnHosts(true);
// Prepare the data structure for the new LayoutState and removes mountItems
// that are not present anymore if isUpdateMountInPlace is enabled.
if (mountPerfEvent != null) {
mountPerfEvent.markerPoint("PREPARE_MOUNT_START");
}
prepareMount(layoutState, mountPerfEvent);
if (mountPerfEvent != null) {
mountPerfEvent.markerPoint("PREPARE_MOUNT_END");
}
}
mMountStats.reset();
if (mountPerfEvent != null && logger.isTracing(mountPerfEvent)) {
mMountStats.enableLogging();
}
if (!isIncrementalMountEnabled
|| !performIncrementalMount(layoutState, localVisibleRect, processVisibilityOutputs)) {
final MountItem rootMountItem = mIndexToItemMap.get(ROOT_HOST_ID);
for (int i = 0, size = layoutState.getMountableOutputCount(); i < size; i++) {
final LayoutOutput layoutOutput = layoutState.getMountableOutputAt(i);
final Component component = layoutOutput.getComponent();
if (isTracing) {
ComponentsSystrace.beginSection(component.getSimpleName());
}
final MountItem currentMountItem = getItemAt(i);
final boolean isMounted = currentMountItem != null;
final boolean isMountable =
!isIncrementalMountEnabled ||
isMountedHostWithChildContent(currentMountItem) ||
Rect.intersects(localVisibleRect, layoutOutput.getBounds()) ||
isAnimationLocked(i) ||
(currentMountItem != null && currentMountItem == rootMountItem);
if (isMountable && !isMounted) {
mountLayoutOutput(i, layoutOutput, layoutState);
if (isAnimationLocked(i)
&& isIncrementalMountEnabled
&& canMountIncrementally(component)) {
// If the component is locked for animation then we need to make sure that all the
// children are also mounted.
final View view = (View) getItemAt(i).getContent();
// We're mounting everything, don't process visibility outputs as they will not be
// accurate.
mountViewIncrementally(view, false);
}
} else if (!isMountable && isMounted) {
unmountItem(i, mHostsByMarker);
} else if (isMounted) {
if (mIsDirty) {
final boolean useUpdateValueFromLayoutOutput =
mLastMountedLayoutState != null
&& mLastMountedLayoutState.getId() == layoutState.getPreviousLayoutStateId();
final long startTime = System.nanoTime();
final TransitionId transitionId = currentMountItem.getTransitionId();
final boolean itemUpdated =
updateMountItemIfNeeded(
layoutOutput,
layoutState,
currentMountItem,
useUpdateValueFromLayoutOutput,
logger,
componentTreeId,
i);
if (itemUpdated) {
// This mount content might be animating and we may be remounting it as a different
// component in the same tree, or as a component in a totally different tree so we
// will reset animating content for its key
maybeRemoveAnimatingMountContent(transitionId);
}
if (mMountStats.isLoggingEnabled) {
if (itemUpdated) {
mMountStats.updatedNames.add(component.getSimpleName());
mMountStats.updatedTimes.add((System.nanoTime() - startTime) / NS_IN_MS);
mMountStats.updatedCount++;
} else {
mMountStats.noOpCount++;
}
}
}
if (isIncrementalMountEnabled && canMountIncrementally(component)) {
mountItemIncrementally(
currentMountItem,
layoutOutput.getBounds(),
localVisibleRect,
processVisibilityOutputs);
}
}
if (isTracing) {
ComponentsSystrace.endSection();
}
}
if (isIncrementalMountEnabled) {
setupPreviousMountableOutputData(layoutState, localVisibleRect);
}
}
maybeUpdateAnimatingMountContent();
if (shouldAnimateTransitions(layoutState) && hasTransitionsToAnimate()) {
mTransitionManager.runTransitions();
}
if (processVisibilityOutputs) {
ComponentsSystrace.beginSection("processVisibilityOutputs");
processVisibilityOutputs(layoutState, localVisibleRect, mountPerfEvent);
ComponentsSystrace.endSection();
}
mRootTransition = null;
mTransitionsHasBeenCollected = false;
mIsDirty = false;
mNeedsRemount = false;
mIsFirstMountOfComponentTree = false;
if (localVisibleRect != null) {
mPreviousLocalVisibleRect.set(localVisibleRect);
}
mLastMountedLayoutState = null;
mLastMountedComponentTreeId = componentTreeId;
mLastMountedLayoutState = layoutState;
processTestOutputs(layoutState);
suppressInvalidationsOnHosts(false);
if (logger != null) {
logMountPerfEvent(logger, mountPerfEvent);
}
if (isTracing) {
ComponentsSystrace.endSection();
}
}
private void logMountPerfEvent(ComponentsLogger logger, @Nullable PerfEvent mountPerfEvent) {
if (!mMountStats.isLoggingEnabled || mountPerfEvent == null) {
logger.cancelPerfEvent(mountPerfEvent);
return;
}
// MOUNT events that don't mount any content are not valuable enough to log at the moment.
// We will likely enable them again in the future. T31729233
if (mMountStats.mountedCount == 0 || mMountStats.mountedNames.isEmpty()) {
logger.cancelPerfEvent(mountPerfEvent);
return;
}
mountPerfEvent.markerAnnotate(PARAM_MOUNTED_COUNT, mMountStats.mountedCount);
mountPerfEvent.markerAnnotate(
PARAM_MOUNTED_CONTENT, mMountStats.mountedNames.toArray(new String[0]));
mountPerfEvent.markerAnnotate(
PARAM_MOUNTED_TIME, mMountStats.mountTimes.toArray(new Double[0]));
mountPerfEvent.markerAnnotate(PARAM_UNMOUNTED_COUNT, mMountStats.unmountedCount);
mountPerfEvent.markerAnnotate(
PARAM_UNMOUNTED_CONTENT, mMountStats.unmountedNames.toArray(new String[0]));
mountPerfEvent.markerAnnotate(
PARAM_UNMOUNTED_TIME, mMountStats.unmountedTimes.toArray(new Double[0]));
mountPerfEvent.markerAnnotate(PARAM_MOUNTED_EXTRAS, mMountStats.extras.toArray(new String[0]));
mountPerfEvent.markerAnnotate(PARAM_UPDATED_COUNT, mMountStats.updatedCount);
mountPerfEvent.markerAnnotate(
PARAM_UPDATED_CONTENT, mMountStats.updatedNames.toArray(new String[0]));
mountPerfEvent.markerAnnotate(
PARAM_UPDATED_TIME, mMountStats.updatedTimes.toArray(new Double[0]));
mountPerfEvent.markerAnnotate(
PARAM_VISIBILITY_HANDLERS_TOTAL_TIME, mMountStats.visibilityHandlersTotalTime);
mountPerfEvent.markerAnnotate(
PARAM_VISIBILITY_HANDLER, mMountStats.visibilityHandlerNames.toArray(new String[0]));
mountPerfEvent.markerAnnotate(
PARAM_VISIBILITY_HANDLER_TIME, mMountStats.visibilityHandlerTimes.toArray(new Double[0]));
mountPerfEvent.markerAnnotate(PARAM_NO_OP_COUNT, mMountStats.noOpCount);
mountPerfEvent.markerAnnotate(PARAM_IS_DIRTY, mIsDirty);
logger.logPerfEvent(mountPerfEvent);
}
private void maybeRemoveAnimatingMountContent(TransitionId transitionId) {
if (mTransitionManager == null || transitionId == null) {
return;
}
mTransitionManager.setMountContent(transitionId, null);
}
private void maybeRemoveAnimatingMountContent(
TransitionId transitionId, @OutputUnitType int type) {
if (mTransitionManager == null || transitionId == null) {
return;
}
mTransitionManager.removeMountContent(transitionId, type);
}
private void maybeUpdateAnimatingMountContent() {
if (mTransitionManager == null) {
return;
}
// Group mount content (represents current LayoutStates only) into groups and pass it to the
// TransitionManager
final Map<TransitionId, OutputUnitsAffinityGroup<Object>> animatingContent =
new LinkedHashMap<>(mAnimatingTransitionIds.size());
for (int i = 0, size = mIndexToItemMap.size(); i < size; i++) {
final MountItem mountItem = mIndexToItemMap.valueAt(i);
if (!mountItem.hasTransitionId()) {
continue;
}
final long layoutOutputId = mIndexToItemMap.keyAt(i);
final @OutputUnitType int type = LayoutStateOutputIdCalculator.getTypeFromId(layoutOutputId);
OutputUnitsAffinityGroup<Object> group = animatingContent.get(mountItem.getTransitionId());
if (group == null) {
group = new OutputUnitsAffinityGroup<>();
animatingContent.put(mountItem.getTransitionId(), group);
}
group.replace(type, mountItem.getContent());
}
for (TransitionId transitionId : animatingContent.keySet()) {
mTransitionManager.setMountContent(transitionId, animatingContent.get(transitionId));
}
// Retrieve mount content from disappearing mount items and pass it to the TransitionManager
for (TransitionId transitionId : mDisappearingMountItems.keySet()) {
final OutputUnitsAffinityGroup<MountItem> mountItemsGroup =
mDisappearingMountItems.get(transitionId);
final OutputUnitsAffinityGroup<Object> mountContentGroup = new OutputUnitsAffinityGroup<>();
for (int j = 0, sz = mountItemsGroup.size(); j < sz; j++) {
final @OutputUnitType int type = mountItemsGroup.typeAt(j);
final MountItem mountItem = mountItemsGroup.getAt(j);
mountContentGroup.add(type, mountItem.getContent());
}
mTransitionManager.setMountContent(transitionId, mountContentGroup);
}
}
void processVisibilityOutputs(
LayoutState layoutState, Rect localVisibleRect, @Nullable PerfEvent mountPerfEvent) {
assertMainThread();
if (localVisibleRect == null) {
return;
}
if (mountPerfEvent != null) {
mountPerfEvent.markerPoint("VISIBILITY_HANDLERS_START");
}
final boolean isDoingPerfLog = mMountStats.isLoggingEnabled;
final boolean isTracing = ComponentsSystrace.isTracing();
final long totalStartTime = isDoingPerfLog ? System.nanoTime() : 0L;
for (int j = 0, size = layoutState.getVisibilityOutputCount(); j < size; j++) {
final VisibilityOutput visibilityOutput = layoutState.getVisibilityOutputAt(j);
if (isTracing) {
final String componentName =
visibilityOutput.getComponent() != null
? visibilityOutput.getComponent().getSimpleName()
: "Unknown";
ComponentsSystrace.beginSection("visibilityHandlers:" + componentName);
}
final long handlerStartTime = isDoingPerfLog ? System.nanoTime() : 0;
final EventHandler<VisibleEvent> visibleHandler = visibilityOutput.getVisibleEventHandler();
final EventHandler<FocusedVisibleEvent> focusedHandler =
visibilityOutput.getFocusedEventHandler();
final EventHandler<UnfocusedVisibleEvent> unfocusedHandler =
visibilityOutput.getUnfocusedEventHandler();
final EventHandler<FullImpressionVisibleEvent> fullImpressionHandler =
visibilityOutput.getFullImpressionEventHandler();
final EventHandler<InvisibleEvent> invisibleHandler =
visibilityOutput.getInvisibleEventHandler();
final EventHandler<VisibilityChangedEvent> visibilityChangedHandler =
visibilityOutput.getVisibilityChangedEventHandler();
final long visibilityOutputId = visibilityOutput.getId();
final Rect visibilityOutputBounds = visibilityOutput.getBounds();
boolean boundsIntersect = sTempRect.setIntersect(visibilityOutputBounds, localVisibleRect);
final boolean isCurrentlyVisible =
boundsIntersect && isInVisibleRange(visibilityOutput, visibilityOutputBounds, sTempRect);
VisibilityItem visibilityItem = mVisibilityIdToItemMap.get(visibilityOutputId);
if (visibilityItem != null) {
final String previousGlobalKey = visibilityItem.getGlobalKey();
final String currentGlobalKey =
visibilityOutput.getComponent() != null
? visibilityOutput.getComponent().getGlobalKey()
: null;
final boolean hasGlobalKeyChanged =
previousGlobalKey != null && !previousGlobalKey.equals(currentGlobalKey);
if (!hasGlobalKeyChanged) {
// If we did a relayout due to e.g. a state update then the handlers will have changed,
// so we should keep them up to date.
visibilityItem.setUnfocusedHandler(unfocusedHandler);
visibilityItem.setInvisibleHandler(invisibleHandler);
}
if (!isCurrentlyVisible || hasGlobalKeyChanged) {
// Either the component is invisible now, but used to be visible, or the key on the
// component has changed so we should generate new visibility events for the new
// component.
if (visibilityItem.getInvisibleHandler() != null) {
EventDispatcherUtils.dispatchOnInvisible(visibilityItem.getInvisibleHandler());
}
if (visibilityChangedHandler != null) {
EventDispatcherUtils.dispatchOnVisibilityChanged(
visibilityChangedHandler, 0, 0, 0f, 0f);
}
if (visibilityItem.isInFocusedRange()) {
visibilityItem.setFocusedRange(false);
if (visibilityItem.getUnfocusedHandler() != null) {
EventDispatcherUtils.dispatchOnUnfocused(visibilityItem.getUnfocusedHandler());
}
}
mVisibilityIdToItemMap.remove(visibilityOutputId);
visibilityItem = null;
} else {
// Processed, do not clear.
visibilityItem.setDoNotClearInThisPass(mIsDirty);
}
}
if (isCurrentlyVisible) {
// The component is visible now, but used to be outside the viewport.
if (visibilityItem == null) {
final String globalKey =
visibilityOutput.getComponent() != null
? visibilityOutput.getComponent().getGlobalKey()
: null;
visibilityItem =
new VisibilityItem(
globalKey, invisibleHandler, unfocusedHandler, visibilityChangedHandler);
visibilityItem.setDoNotClearInThisPass(mIsDirty);
mVisibilityIdToItemMap.put(visibilityOutputId, visibilityItem);
if (visibleHandler != null) {
EventDispatcherUtils.dispatchOnVisible(visibleHandler);
}
}
// Check if the component has entered or exited the focused range.
if (focusedHandler != null || unfocusedHandler != null) {
if (isInFocusedRange(visibilityOutputBounds, sTempRect)) {
if (!visibilityItem.isInFocusedRange()) {
visibilityItem.setFocusedRange(true);
if (focusedHandler != null) {
EventDispatcherUtils.dispatchOnFocused(focusedHandler);
}
}
} else {
if (visibilityItem.isInFocusedRange()) {
visibilityItem.setFocusedRange(false);
if (unfocusedHandler != null) {
EventDispatcherUtils.dispatchOnUnfocused(unfocusedHandler);
}
}
}
}
// If the component has not entered the full impression range yet, make sure to update the
// information about the visible edges.
if (fullImpressionHandler != null && !visibilityItem.isInFullImpressionRange()) {
visibilityItem.setVisibleEdges(visibilityOutputBounds, sTempRect);
if (visibilityItem.isInFullImpressionRange()) {
EventDispatcherUtils.dispatchOnFullImpression(fullImpressionHandler);
}
}
if (visibilityChangedHandler != null) {
final int visibleWidth = sTempRect.right - sTempRect.left;
final int visibleHeight = sTempRect.bottom - sTempRect.top;
EventDispatcherUtils.dispatchOnVisibilityChanged(
visibilityChangedHandler,
visibleWidth,
visibleHeight,
100f * visibleWidth / visibilityOutputBounds.width(),
100f * visibleHeight / visibilityOutputBounds.height());
}
}
if (isDoingPerfLog) {
final String componentName =
visibilityOutput.getComponent() != null
? visibilityOutput.getComponent().getSimpleName()
: "Unknown";
mMountStats.visibilityHandlerTimes.add((System.nanoTime() - handlerStartTime) / NS_IN_MS);
mMountStats.visibilityHandlerNames.add(componentName);
}
if (isTracing) {
ComponentsSystrace.endSection();
}
}
if (mIsDirty) {
clearVisibilityItems();
}
if (isDoingPerfLog) {
mMountStats.visibilityHandlersTotalTime = (System.nanoTime() - totalStartTime) / NS_IN_MS;
}
if (mountPerfEvent != null) {
mountPerfEvent.markerPoint("VISIBILITY_HANDLERS_END");
}
}
/**
* Clears and re-populates the test item map if we are in e2e test mode.
*/
private void processTestOutputs(LayoutState layoutState) {
if (mTestItemMap == null) {
return;
}
mTestItemMap.clear();
for (int i = 0, size = layoutState.getTestOutputCount(); i < size; i++) {
final TestOutput testOutput = layoutState.getTestOutputAt(i);
final long hostMarker = testOutput.getHostMarker();
final long layoutOutputId = testOutput.getLayoutOutputId();
final MountItem mountItem =
layoutOutputId == -1 ? null : mIndexToItemMap.get(layoutOutputId);
final TestItem testItem = new TestItem();
testItem.setHost(hostMarker == -1 ? null : mHostsByMarker.get(hostMarker));
testItem.setBounds(testOutput.getBounds());
testItem.setTestKey(testOutput.getTestKey());
testItem.setContent(mountItem == null ? null : mountItem.getContent());
final Deque<TestItem> items = mTestItemMap.get(testOutput.getTestKey());
final Deque<TestItem> updatedItems =
items == null ? new LinkedList<TestItem>() : items;
updatedItems.add(testItem);
mTestItemMap.put(testOutput.getTestKey(), updatedItems);
}
}
private boolean isMountedHostWithChildContent(MountItem mountItem) {
if (mountItem == null) {
return false;
}
final Object content = mountItem.getContent();
if (!(content instanceof ComponentHost)) {
return false;
}
final ComponentHost host = (ComponentHost) content;
return host.getMountItemCount() > 0;
}
private void setupPreviousMountableOutputData(LayoutState layoutState, Rect localVisibleRect) {
if (localVisibleRect.isEmpty()) {
return;
}
final ArrayList<LayoutOutput> layoutOutputTops = layoutState.getMountableOutputTops();
final ArrayList<LayoutOutput> layoutOutputBottoms = layoutState.getMountableOutputBottoms();
final int mountableOutputCount = layoutState.getMountableOutputCount();
mPreviousTopsIndex = layoutState.getMountableOutputCount();
for (int i = 0; i < mountableOutputCount; i++) {
if (localVisibleRect.bottom <= layoutOutputTops.get(i).getBounds().top) {
mPreviousTopsIndex = i;
break;
}
}
mPreviousBottomsIndex = layoutState.getMountableOutputCount();
for (int i = 0; i < mountableOutputCount; i++) {
if (localVisibleRect.top < layoutOutputBottoms.get(i).getBounds().bottom) {
mPreviousBottomsIndex = i;
break;
}
}
}
void clearVisibilityItems() {
assertMainThread();
boolean isTracing = ComponentsSystrace.isTracing();
if (isTracing) {
ComponentsSystrace.beginSection("MountState.clearVisibilityItems");
}
for (int i = mVisibilityIdToItemMap.size() - 1; i >= 0; i--) {
final VisibilityItem visibilityItem = mVisibilityIdToItemMap.valueAt(i);
if (visibilityItem.doNotClearInThisPass()) {
// This visibility item has already been accounted for in this pass, so ignore it.
visibilityItem.setDoNotClearInThisPass(false);
} else {
final EventHandler<InvisibleEvent> invisibleHandler = visibilityItem.getInvisibleHandler();
final EventHandler<UnfocusedVisibleEvent> unfocusedHandler =
visibilityItem.getUnfocusedHandler();
final EventHandler<VisibilityChangedEvent> visibilityChangedHandler =
visibilityItem.getVisibilityChangedHandler();
if (invisibleHandler != null) {
EventDispatcherUtils.dispatchOnInvisible(invisibleHandler);
}
if (visibilityItem.isInFocusedRange()) {
visibilityItem.setFocusedRange(false);
if (unfocusedHandler != null) {
EventDispatcherUtils.dispatchOnUnfocused(unfocusedHandler);
}
}
if (visibilityChangedHandler != null) {
EventDispatcherUtils.dispatchOnVisibilityChanged(visibilityChangedHandler, 0, 0, 0f, 0f);
}
mVisibilityIdToItemMap.removeAt(i);
}
}
if (isTracing) {
ComponentsSystrace.endSection();
}
}
private void registerHost(long id, ComponentHost host) {
host.suppressInvalidations(true);
mHostsByMarker.put(id, host);
}
private boolean isInVisibleRange(
VisibilityOutput visibilityOutput,
Rect bounds,
Rect visibleBounds) {
float heightRatio = visibilityOutput.getVisibleHeightRatio();
float widthRatio = visibilityOutput.getVisibleWidthRatio();
if (heightRatio == 0 && widthRatio == 0) {
return true;
}
return isInRatioRange(heightRatio, bounds.height(), visibleBounds.height())
&& isInRatioRange(widthRatio, bounds.width(), visibleBounds.width());
}
private static boolean isInRatioRange(float ratio, int length, int visiblelength) {
return visiblelength >= ratio * length;
}
/**
* Returns true if the component is in the focused visible range.
*/
private boolean isInFocusedRange(
Rect componentBounds,
Rect componentVisibleBounds) {
final View parent = (View) mLithoView.getParent();
if (parent == null) {
return false;
}
final int halfViewportArea = parent.getWidth() * parent.getHeight() / 2;
final int totalComponentArea = computeRectArea(componentBounds);
final int visibleComponentArea = computeRectArea(componentVisibleBounds);
// The component has entered the focused range either if it is larger than half of the viewport
// and it occupies at least half of the viewport or if it is smaller than half of the viewport
// and it is fully visible.
return (totalComponentArea >= halfViewportArea)
? (visibleComponentArea >= halfViewportArea)
: componentBounds.equals(componentVisibleBounds);
}
private static int computeRectArea(Rect rect) {
return rect.isEmpty() ? 0 : (rect.width() * rect.height());
}
private void suppressInvalidationsOnHosts(boolean suppressInvalidations) {
for (int i = mHostsByMarker.size() - 1; i >= 0; i--) {
mHostsByMarker.valueAt(i).suppressInvalidations(suppressInvalidations);
}
}
private boolean updateMountItemIfNeeded(
LayoutOutput layoutOutput,
LayoutState layoutState,
MountItem currentMountItem,
boolean useUpdateValueFromLayoutOutput,
ComponentsLogger logger,
int componentTreeId,
int index) {
final Component layoutOutputComponent = layoutOutput.getComponent();
final Component itemComponent = currentMountItem.getComponent();
if (layoutOutputComponent == null) {
throw new RuntimeException("Trying to update a MountItem with a null Component.");
}
// 1. Check if the mount item generated from the old component should be updated.
final boolean shouldUpdateMountItem =
shouldUpdateMountItem(layoutOutput, currentMountItem, useUpdateValueFromLayoutOutput);
final boolean shouldUpdate = shouldUpdateMountItem;
final boolean shouldUpdateViewInfo =
shouldUpdateMountItem || shouldUpdateViewInfo(layoutOutput, currentMountItem);
// 2. Reset all the properties like click handler, content description and tags related to
// this item if it needs to be updated. the update mount item will re-set the new ones.
if (shouldUpdate) {
// If we're remounting this ComponentHost for a new ComponentTree, remove all disappearing
// mount content that was animating since those disappearing animations belong to the old
// ComponentTree
if (mLastMountedComponentTreeId != componentTreeId) {
final Component component = currentMountItem.getComponent();
if (isHostSpec(component)) {
final ComponentHost componentHost = (ComponentHost) currentMountItem.getContent();
removeDisappearingMountContentFromComponentHost(componentHost);
}
}
maybeUnsetViewAttributes(currentMountItem);
final ComponentHost host = currentMountItem.getHost();
host.maybeUnregisterTouchExpansion(index, currentMountItem);
} else if (shouldUpdateViewInfo) {
maybeUnsetViewAttributes(currentMountItem);
final ComponentHost host = currentMountItem.getHost();
host.maybeUnregisterTouchExpansion(index, currentMountItem);
}
// 3. We will re-bind this later in 7 regardless so let's make sure it's currently unbound.
if (currentMountItem.isBound()) {
itemComponent.onUnbind(getContextForComponent(itemComponent), currentMountItem.getContent());
currentMountItem.setIsBound(false);
}
// 4. Re initialize the MountItem internal state with the new attributes from LayoutOutput
currentMountItem.update(layoutOutput);
// 5. If the mount item is not valid for this component update its content and view attributes.
if (shouldUpdate) {
final ComponentHost host = currentMountItem.getHost();
host.maybeRegisterTouchExpansion(index, currentMountItem);
updateMountedContent(currentMountItem, layoutOutput, itemComponent);
setViewAttributes(currentMountItem);
} else if (shouldUpdateViewInfo) {
final ComponentHost host = currentMountItem.getHost();
host.maybeRegisterTouchExpansion(index, currentMountItem);
setViewAttributes(currentMountItem);
}
final Object currentContent = currentMountItem.getContent();
// 6. Set the mounted content on the Component and call the bind callback.
layoutOutputComponent.bind(getContextForComponent(layoutOutputComponent), currentContent);
currentMountItem.setIsBound(true);
// 7. Update the bounds of the mounted content. This needs to be done regardless of whether
// the component has been updated or not since the mounted item might might have the same
// size and content but a different position.
updateBoundsForMountedLayoutOutput(layoutOutput, layoutState, mSkipMounting, currentMountItem);
maybeInvalidateAccessibilityState(currentMountItem);
if (currentMountItem.getContent() instanceof Drawable) {
maybeSetDrawableState(
currentMountItem.getHost(),
(Drawable) currentMountItem.getContent(),
currentMountItem.getLayoutFlags(),
currentMountItem.getNodeInfo());
}
return shouldUpdate;
}
private static boolean shouldUpdateViewInfo(
LayoutOutput layoutOutput, MountItem currentMountItem) {
final ViewNodeInfo nextViewNodeInfo = layoutOutput.getViewNodeInfo();
final ViewNodeInfo currentViewNodeInfo = currentMountItem.getViewNodeInfo();
if ((currentViewNodeInfo == null && nextViewNodeInfo != null)
|| (currentViewNodeInfo != null && !currentViewNodeInfo.isEquivalentTo(nextViewNodeInfo))) {
return true;
}
final NodeInfo nextNodeInfo = layoutOutput.getNodeInfo();
final NodeInfo currentNodeInfo = currentMountItem.getNodeInfo();
if ((currentNodeInfo == null && nextNodeInfo != null)
|| (currentNodeInfo != null && !currentNodeInfo.isEquivalentTo(nextNodeInfo))) {
return true;
}
return false;
}
private static boolean shouldUpdateMountItem(
LayoutOutput layoutOutput,
MountItem currentMountItem,
boolean useUpdateValueFromLayoutOutput) {
@LayoutOutput.UpdateState final int updateState = layoutOutput.getUpdateState();
final Component currentComponent = currentMountItem.getComponent();
final ComponentLifecycle currentLifecycle = currentComponent;
final Component nextComponent = layoutOutput.getComponent();
final ComponentLifecycle nextLifecycle = nextComponent;
// If the orientation has changed, we should definitely update.
if (layoutOutput.getOrientation() != currentMountItem.getOrientation()) {
return true;
}
// If the two components have different sizes and the mounted content depends on the size we
// just return true immediately.
if (!sameSize(layoutOutput, currentMountItem) && nextLifecycle.isMountSizeDependent()) {
return true;
}
if (useUpdateValueFromLayoutOutput) {
if (updateState == LayoutOutput.STATE_UPDATED) {
// Check for incompatible ReferenceLifecycle.
return currentLifecycle instanceof DrawableComponent
&& nextLifecycle instanceof DrawableComponent
&& currentLifecycle.shouldComponentUpdate(currentComponent, nextComponent);
} else if (updateState == LayoutOutput.STATE_DIRTY) {
return true;
}
}
if (!currentLifecycle.callsShouldUpdateOnMount()) {
return true;
}
return currentLifecycle.shouldComponentUpdate(
currentComponent,
nextComponent);
}
private static boolean sameSize(LayoutOutput layoutOutput, MountItem item) {
final Rect layoutOutputBounds = layoutOutput.getBounds();
final Object mountedContent = item.getContent();
return layoutOutputBounds.width() == getWidthForMountedContent(mountedContent) &&
layoutOutputBounds.height() == getHeightForMountedContent(mountedContent);
}
private static int getWidthForMountedContent(Object content) {
return content instanceof Drawable ?
((Drawable) content).getBounds().width() :
((View) content).getWidth();
}
private static int getHeightForMountedContent(Object content) {
return content instanceof Drawable ?
((Drawable) content).getBounds().height() :
((View) content).getHeight();
}
private static void updateBoundsForMountedLayoutOutput(
LayoutOutput layoutOutput, LayoutState layoutState, BitSet skipMounting, MountItem item) {
// MountState should never update the bounds of the top-level host as this
// should be done by the ViewGroup containing the LithoView.
if (layoutOutput.getId() == ROOT_HOST_ID) {
return;
}
getActualBounds(layoutOutput, layoutState, skipMounting, sTempRect);
final boolean forceTraversal =
Component.isMountViewSpec(layoutOutput.getComponent())
&& ((View) item.getContent()).isLayoutRequested();
applyBoundsToMountContent(
item.getContent(),
sTempRect.left,
sTempRect.top,
sTempRect.right,
sTempRect.bottom,
forceTraversal /* force */);
}
/** Prepare the {@link MountState} to mount a new {@link LayoutState}. */
@SuppressWarnings("unchecked")
private void prepareMount(LayoutState layoutState, @Nullable PerfEvent perfEvent) {
final List<Integer> disappearingItems = extractDisappearingItems(layoutState);
final BitSet skipMounting = calculateSkipMounting(layoutState);
final PrepareMountStats stats =
unmountOrMoveOldItems(layoutState, skipMounting, disappearingItems);
if (perfEvent != null) {
perfEvent.markerAnnotate(PARAM_UNMOUNTED_COUNT, stats.unmountedCount);
perfEvent.markerAnnotate(PARAM_MOVED_COUNT, stats.movedCount);
perfEvent.markerAnnotate(PARAM_UNCHANGED_COUNT, stats.unchangedCount);
}
if (mHostsByMarker.get(ROOT_HOST_ID) == null) {
// Mounting always starts with the root host.
registerHost(ROOT_HOST_ID, mLithoView);
// Root host is implicitly marked as mounted.
mIndexToItemMap.put(ROOT_HOST_ID, mRootHostMountItem);
}
final int outputCount = layoutState.getMountableOutputCount();
if (mLayoutOutputsIds == null || outputCount != mLayoutOutputsIds.length) {
mLayoutOutputsIds = new long[outputCount];
}
for (int i = 0; i < outputCount; i++) {
mLayoutOutputsIds[i] = layoutState.getMountableOutputAt(i).getId();
}
mSkipMounting = skipMounting;
}
/**
* Determine whether to apply disappear animation to the given {@link MountItem}
*/
private boolean isItemDisappearing(LayoutState layoutState, int index) {
if (!shouldAnimateTransitions(layoutState) || !hasTransitionsToAnimate()) {
return false;
}
if (mTransitionManager == null || mLastMountedLayoutState == null) {
return false;
}
final LayoutOutput layoutOutput = mLastMountedLayoutState.getMountableOutputAt(index);
final TransitionId transitionId = layoutOutput.getTransitionId();
if (transitionId == null) {
return false;
}
return mTransitionManager.isDisappearing(transitionId);
}
/**
* Takes care of disappearing items from the last mounted layout (re-mounts them to the root if
* needed, starts disappearing, removes them from mapping). Returns the list of ids, which for
* every disappearing subtree contains a pair [index of the root of the subtree, index of the last
* descendant of that subtree]
*/
private List<Integer> extractDisappearingItems(LayoutState newLayoutState) {
if (mLayoutOutputsIds == null) {
return Collections.emptyList();
}
List<Integer> indices = null;
int index = 0;
while (index < mLayoutOutputsIds.length) {
if (isItemDisappearing(newLayoutState, index)) {
final int lastDescendantIndex = findLastDescendantIndex(mLastMountedLayoutState, index);
final LayoutOutput root = mLastMountedLayoutState.getMountableOutputAt(index);
if (mSkipMounting.get(index)) {
// The direct descendants of the root have been mounted to another host, thus here we'll
// unmount them from where they are mounted, and will remount to the root at the next step
final long rootId = root.getId();
for (int j = index + 1; j <= lastDescendantIndex; j++) {
if (mLastMountedLayoutState.getMountableOutputAt(j).getHostMarker() == rootId) {
unmountItem(j, mHostsByMarker);
}
}
// Need to override skip mounting value, otherwise it won't be mounted
mSkipMounting.clear(index);
}
// Go though disappearing subtree, mount everything that is not mounted yet
// That's okay to mount here *before* we call unmountOrMoveOldItems() and only passing
// last mount LayoutState
// This item representing the root of the disappearing subtree will be unmounted immediately
// after this cycle is over and will be moved to the root. If any if its parents have been
// mounted as well, they will get picked up in unmountOrMoveOldItems()
for (int j = index; j <= lastDescendantIndex; j++) {
final MountItem mountedItem = getItemAt(j);
if (mountedItem != null) {
// Item is already mounted - skip
continue;
}
final LayoutOutput layoutOutput = mLastMountedLayoutState.getMountableOutputAt(j);
mountLayoutOutput(j, layoutOutput, mLastMountedLayoutState);
}
// Reference to the root of the disappearing subtree
final MountItem disappearingItem = getItemAt(index);
// Moving item to the root
remountComponentHostToRootIfNeeded(index);
// Removing references of all the items of the disappearing subtree from mIndexToItemMap and
// mHostsByMaker
removeDisappearingItemMappings(index, lastDescendantIndex);
// Start animating disappearing
startUnmountDisappearingItem(disappearingItem, index);
if (indices == null) {
indices = new ArrayList<>(2);
}
indices.add(index);
indices.add(lastDescendantIndex);
index = lastDescendantIndex + 1;
} else {
index++;
}
}
return indices != null ? indices : Collections.<Integer>emptyList();
}
private void remountComponentHostToRootIfNeeded(int index) {
final ComponentHost rootHost = mHostsByMarker.get(ROOT_HOST_ID);
final MountItem item = getItemAt(index);
if (item.getHost() == rootHost) {
// Already mounted to the root
return;
}
final Object content = item.getContent();
// Before unmounting item get its position inside the root
int left = 0;
int top = 0;
int right;
int bottom;
// Get left/top position of the item's host first
ComponentHost componentHost = item.getHost();
while (componentHost != rootHost) {
left += componentHost.getLeft();
top += componentHost.getTop();
componentHost = (ComponentHost) componentHost.getParent();
}
if (content instanceof View) {
final View view = (View) content;
left += view.getLeft();
top += view.getTop();
right = left + view.getWidth();
bottom = top + view.getHeight();
} else {
final Rect bounds = ((Drawable) content).getBounds();
left += bounds.left;
right = left + bounds.width();
top += bounds.top;
bottom = top + bounds.height();
}
// Unmount from the current host
item.getHost().unmount(index, item);
// Apply new bounds to the content as it will be mounted in the root now
applyBoundsToMountContent(content, left, top, right, bottom, false);
// Mount to the root
rootHost.mount(index, item, sTempRect);
// Set new host to the MountItem
item.setHost(rootHost);
}
private void removeDisappearingItemMappings(int fromIndex, int toIndex) {
for (int i = fromIndex; i <= toIndex; i++) {
final MountItem item = getItemAt(i);
// We do not need this mapping for disappearing items.
mIndexToItemMap.remove(mLayoutOutputsIds[i]);
if (item.getComponent() != null && item.getComponent().hasChildLithoViews()) {
mCanMountIncrementallyMountItems.remove(mLayoutOutputsIds[i]);
}
// Likewise we no longer need host mapping for disappearing items.
if (isHostSpec(item.getComponent())) {
mHostsByMarker.removeAt(mHostsByMarker.indexOfValue((ComponentHost) item.getContent()));
}
}
}
private void startUnmountDisappearingItem(MountItem item, int index) {
final TransitionId transitionId = item.getTransitionId();
OutputUnitsAffinityGroup<MountItem> disappearingGroup =
mDisappearingMountItems.get(transitionId);
if (disappearingGroup == null) {
disappearingGroup = new OutputUnitsAffinityGroup<>();
mDisappearingMountItems.put(transitionId, disappearingGroup);
}
final @OutputUnitType int type =
LayoutStateOutputIdCalculator.getTypeFromId(mLayoutOutputsIds[index]);
disappearingGroup.add(type, item);
final ComponentHost host = item.getHost();
host.startUnmountDisappearingItem(index, item);
}
private BitSet calculateSkipMounting(LayoutState layoutState) {
if (!ComponentsConfiguration.createPhantomLayoutOutputsForTransitions) {
return sEmptyBitSet;
}
final BitSet skipMounting = new BitSet();
for (int index = layoutState.getMountableOutputCount() - 1; index >= 0; index--) {
if (shouldSkipMounting(layoutState, index)) {
skipMounting.set(index);
}
}
return skipMounting;
}
private boolean shouldSkipMounting(LayoutState layoutState, int index) {
if (!ComponentsConfiguration.createPhantomLayoutOutputsForTransitions) {
return false;
}
final LayoutOutput layoutOutput = layoutState.getMountableOutputAt(index);
final boolean isPhantom = (layoutOutput.getFlags() & MountItem.LAYOUT_FLAG_PHANTOM) != 0;
final boolean isAnimating = mAnimatingTransitionIds.contains(layoutOutput.getTransitionId());
return isPhantom && !isAnimating;
}
/**
* Go over all the mounted items from the leaves to the root and unmount only the items that are
* not present in the new LayoutOutputs. If an item is still present but in a new position move
* the item inside its host. The condition where an item changed host doesn't need any special
* treatment here since we mark them as removed and re-added when calculating the new
* LayoutOutputs
*/
private PrepareMountStats unmountOrMoveOldItems(
LayoutState newLayoutState, BitSet newSkipMounting, List<Integer> disappearingItems) {
mPrepareMountStats.reset();
if (mLayoutOutputsIds == null) {
return mPrepareMountStats;
}
int disappearingItemsPointer = 0;
// Traversing from the beginning since mLayoutOutputsIds unmounting won't remove entries there
// but only from mIndexToItemMap. If an host changes we're going to unmount it and recursively
// all its mounted children.
for (int i = 0; i < mLayoutOutputsIds.length; i++) {
final LayoutOutput newLayoutOutput = newLayoutState.getLayoutOutput(mLayoutOutputsIds[i]);
final int newPosition =
newLayoutOutput == null || newSkipMounting.get(newLayoutOutput.getIndex())
? -1
: newLayoutOutput.getIndex();
final MountItem oldItem = getItemAt(i);
// Just skip disappearing items here
if (disappearingItems.size() > disappearingItemsPointer
&& disappearingItems.get(disappearingItemsPointer) == i) {
// Updating i to the index of the last member of the disappearing subtree, so the whole
// subtree will be skipped, as it's been dealt with at extractDisappearingItems()
i = disappearingItems.get(disappearingItemsPointer + 1);
disappearingItemsPointer += 2;
continue;
}
if (newPosition == -1) {
unmountItem(i, mHostsByMarker);
mPrepareMountStats.unmountedCount++;
} else {
final long newHostMarker =
getActualHostMarker(newLayoutOutput, newLayoutState, newSkipMounting);
if (oldItem == null) {
// This was previously unmounted.
mPrepareMountStats.unmountedCount++;
} else if (oldItem.getHost() != mHostsByMarker.get(newHostMarker)) {
// If the id is the same but the parent host is different we simply unmount the item and
// re-mount it later. If the item to unmount is a ComponentHost, all the children will be
// recursively unmounted.
unmountItem(i, mHostsByMarker);
mPrepareMountStats.unmountedCount++;
} else if (newPosition != i) {
// If a MountItem for this id exists and the hostMarker has not changed but its position
// in the outputs array has changed we need to update the position in the Host to ensure
// the z-ordering.
oldItem.getHost().moveItem(oldItem, i, newPosition);
mPrepareMountStats.movedCount++;
} else {
mPrepareMountStats.unchangedCount++;
}
}
}
return mPrepareMountStats;
}
private void updateMountedContent(
MountItem item,
LayoutOutput layoutOutput,
Component previousComponent) {
final Component newComponent = layoutOutput.getComponent();
if (isHostSpec(newComponent)) {
return;
}
final Object previousContent = item.getContent();
// Call unmount and mount in sequence to make sure all the the resources are correctly
// de-allocated. It's possible for previousContent to equal null - when the root is
// interactive we create a LayoutOutput without content in order to set up click handling.
previousComponent.unmount(
getContextForComponent(previousComponent), previousContent);
newComponent.mount(getContextForComponent(newComponent), previousContent);
}
private void mountLayoutOutput(int index, LayoutOutput layoutOutput, LayoutState layoutState) {
// 0. Make sure we really need to mount this LayoutOutput
if (mSkipMounting.get(index)) {
return;
}
// 1. Resolve the correct host to mount our content to.
final long startTime = System.nanoTime();
final long hostMarker = getActualHostMarker(layoutOutput, layoutState, mSkipMounting);
ComponentHost host = mHostsByMarker.get(hostMarker);
if (host == null) {
// Host has not yet been mounted - mount it now.
final int hostMountIndex = layoutState.getLayoutOutputPositionForId(hostMarker);
final LayoutOutput hostLayoutOutput = layoutState.getMountableOutputAt(hostMountIndex);
mountLayoutOutput(hostMountIndex, hostLayoutOutput, layoutState);
host = mHostsByMarker.get(hostMarker);
}
// 2. Generate the component's mount state (this might also be a ComponentHost View).
final Component component = layoutOutput.getComponent();
if (component == null) {
throw new RuntimeException("Trying to mount a LayoutOutput with a null Component.");
}
final Object content =
ComponentsPools.acquireMountContent(mContext.getAndroidContext(), component);
final ComponentContext context = getContextForComponent(component);
component.mount(
context,
content);
// 3. If it's a ComponentHost, add the mounted View to the list of Hosts.
if (isHostSpec(component)) {
ComponentHost componentHost = (ComponentHost) content;
componentHost.setParentHostMarker(hostMarker);
registerHost(layoutOutput.getId(), componentHost);
}
// 4. Mount the content into the selected host.
final MountItem item = mountContent(index, component, content, host, layoutOutput);
// 5. Notify the component that mounting has completed
component.bind(context, content);
item.setIsBound(true);
// 6. Apply the bounds to the Mount content now. It's important to do so after bind as calling
// bind might have triggered a layout request within a View.
getActualBounds(layoutOutput, layoutState, mSkipMounting, sTempRect);
applyBoundsToMountContent(
item.getContent(),
sTempRect.left,
sTempRect.top,
sTempRect.right,
sTempRect.bottom,
true /* force */);
// 6. Update the mount stats
if (mMountStats.isLoggingEnabled) {
mMountStats.mountTimes.add((System.nanoTime() - startTime) / NS_IN_MS);
mMountStats.mountedNames.add(component.getSimpleName());
mMountStats.mountedCount++;
mMountStats.extras.add(
LogTreePopulator.getAnnotationBundleFromLogger(component, context.getLogger()));
}
}
// The content might be null because it's the LayoutSpec for the root host
// (the very first LayoutOutput).
private MountItem mountContent(
int index,
Component component,
Object content,
ComponentHost host,
LayoutOutput layoutOutput) {
final MountItem item = new MountItem(component, host, content, layoutOutput);
// Create and keep a MountItem even for the layoutSpec with null content
// that sets the root host interactions.
mIndexToItemMap.put(mLayoutOutputsIds[index], item);
if (component.hasChildLithoViews()) {
mCanMountIncrementallyMountItems.put(mLayoutOutputsIds[index], item);
}
layoutOutput.getMountBounds(sTempRect);
host.mount(index, item, sTempRect);
setViewAttributes(item);
return item;
}
private static void applyBoundsToMountContent(
Object content,
int left,
int top,
int right,
int bottom,
boolean force) {
assertMainThread();
if (content instanceof View) {
BoundsHelper.applyBoundsToView((View) content, left, top, right, bottom, force);
} else if (content instanceof Drawable) {
((Drawable) content).setBounds(left, top, right, bottom);
} else {
throw new IllegalStateException("Unsupported mounted content " + content);
}
}
private static boolean canMountIncrementally(Component component) {
return component.hasChildLithoViews();
}
/**
* @return an id if a host that should be used for a given LayoutOutput, taking into account that
* some of nodes on LayoutOutput tree may not be mounted (e.g. "phantom" LayoutOutputs)
*/
private static long getActualHostMarker(
LayoutOutput layoutOutput, LayoutState layoutState, BitSet skipMounting) {
if (skipMounting.get(layoutOutput.getIndex())) {
return -1;
}
long hostMarker;
do {
hostMarker = layoutOutput.getHostMarker();
layoutOutput = layoutState.getLayoutOutput(hostMarker);
if (layoutOutput == null) {
// We got to the root LayoutOutput without finding a host that should be used
return -1;
}
} while (skipMounting.get(layoutOutput.getIndex()));
return hostMarker;
}
/** @return bounds for a given LayoutOutput within its actual host, {@see getActualHostMarker} */
private static void getActualBounds(
LayoutOutput layoutOutput, LayoutState layoutState, BitSet skipMounting, Rect outRect) {
final long actualHostMarker = getActualHostMarker(layoutOutput, layoutState, skipMounting);
layoutOutput.getMountBounds(outRect);
long hostMarker = layoutOutput.getHostMarker();
while (hostMarker != actualHostMarker) {
final LayoutOutput ancestor = layoutState.getLayoutOutput(hostMarker);
ancestor.getMountBounds(sTempRect2);
outRect.offset(sTempRect2.left, sTempRect2.top);
hostMarker = ancestor.getHostMarker();
}
}
private static void setViewAttributes(MountItem item) {
final Component component = item.getComponent();
if (!isMountViewSpec(component)) {
return;
}
final View view = (View) item.getContent();
final NodeInfo nodeInfo = item.getNodeInfo();
if (nodeInfo != null) {
setClickHandler(nodeInfo.getClickHandler(), view);
setLongClickHandler(nodeInfo.getLongClickHandler(), view);
setFocusChangeHandler(nodeInfo.getFocusChangeHandler(), view);
setTouchHandler(nodeInfo.getTouchHandler(), view);
setInterceptTouchHandler(nodeInfo.getInterceptTouchHandler(), view);
setAccessibilityDelegate(view, nodeInfo);
setViewTag(view, nodeInfo.getViewTag());
setViewTags(view, nodeInfo.getViewTags());
setShadowElevation(view, nodeInfo.getShadowElevation());
setOutlineProvider(view, nodeInfo.getOutlineProvider());
setClipToOutline(view, nodeInfo.getClipToOutline());
setClipChildren(view, nodeInfo);
setContentDescription(view, nodeInfo.getContentDescription());
setFocusable(view, nodeInfo.getFocusState());
setClickable(view, nodeInfo.getClickableState());
setEnabled(view, nodeInfo.getEnabledState());
setSelected(view, nodeInfo.getSelectedState());
setScale(view, nodeInfo);
setAlpha(view, nodeInfo);
setRotation(view, nodeInfo);
setRotationX(view, nodeInfo);
setRotationY(view, nodeInfo);
}
setImportantForAccessibility(view, item.getImportantForAccessibility());
final ViewNodeInfo viewNodeInfo = item.getViewNodeInfo();
if (viewNodeInfo != null) {
setViewStateListAnimator(view, viewNodeInfo);
if (!isHostSpec(component)) {
// Set view background, if applicable. Do this before padding
// as it otherwise overrides the padding.
setViewBackground(view, viewNodeInfo);
setViewPadding(view, viewNodeInfo);
setViewForeground(view, viewNodeInfo);
setViewLayoutDirection(view, viewNodeInfo);
}
}
}
private static void maybeUnsetViewAttributes(MountItem item) {
final Component component = item.getComponent();
if (!isMountViewSpec(component)) {
return;
}
unsetViewAttributes(item, isHostSpec(component));
}
private static void unsetViewAttributes(MountItem item, boolean isHostView) {
final View view = (View) item.getContent();
final NodeInfo nodeInfo = item.getNodeInfo();
if (nodeInfo != null) {
if (nodeInfo.getClickHandler() != null) {
unsetClickHandler(view);
}
if (nodeInfo.getLongClickHandler() != null) {
unsetLongClickHandler(view);
}
if (nodeInfo.getFocusChangeHandler() != null) {
unsetFocusChangeHandler(view);
}
if (nodeInfo.getTouchHandler() != null) {
unsetTouchHandler(view);
}
if (nodeInfo.getInterceptTouchHandler() != null) {
unsetInterceptTouchEventHandler(view);
}
unsetViewTag(view);
unsetViewTags(view, nodeInfo.getViewTags());
unsetShadowElevation(view, nodeInfo.getShadowElevation());
unsetOutlineProvider(view, nodeInfo.getOutlineProvider());
unsetClipToOutline(view, nodeInfo.getClipToOutline());
unsetClipChildren(view, nodeInfo.getClipChildren());
if (!TextUtils.isEmpty(nodeInfo.getContentDescription())) {
unsetContentDescription(view);
}
unsetScale(view, nodeInfo);
unsetAlpha(view, nodeInfo);
unsetRotation(view, nodeInfo);
unsetRotationX(view, nodeInfo);
unsetRotationY(view, nodeInfo);
}
view.setClickable(item.isViewClickable());
view.setLongClickable(item.isViewLongClickable());
unsetFocusable(view, item);
unsetEnabled(view, item);
unsetSelected(view, item);
if (item.getImportantForAccessibility() != IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
unsetImportantForAccessibility(view);
}
unsetAccessibilityDelegate(view);
final ViewNodeInfo viewNodeInfo = item.getViewNodeInfo();
if (viewNodeInfo != null) {
unsetViewStateListAnimator(view, viewNodeInfo);
// Host view doesn't set its own padding, but gets absolute positions for inner content from
// Yoga. Also bg/fg is used as separate drawables instead of using View's bg/fg attribute.
if (!isHostView) {
unsetViewPadding(view, viewNodeInfo);
unsetViewBackground(view, viewNodeInfo);
unsetViewForeground(view, viewNodeInfo);
unsetViewLayoutDirection(view, viewNodeInfo);
}
}
}
/**
* Store a {@link NodeInfo} as a tag in {@code view}. {@link LithoView} contains the logic for
* setting/unsetting it whenever accessibility is enabled/disabled
*
* <p>For non {@link ComponentHost}s this is only done if any {@link EventHandler}s for
* accessibility events have been implemented, we want to preserve the original behaviour since
* {@code view} might have had a default delegate.
*/
private static void setAccessibilityDelegate(View view, NodeInfo nodeInfo) {
if (!(view instanceof ComponentHost) && !nodeInfo.needsAccessibilityDelegate()) {
return;
}
view.setTag(
R.id.component_node_info,
nodeInfo);
}
private static void unsetAccessibilityDelegate(View view) {
if (!(view instanceof ComponentHost)
&& view.getTag(R.id.component_node_info) == null) {
return;
}
view.setTag(R.id.component_node_info, null);
if (!(view instanceof ComponentHost)) {
ViewCompat.setAccessibilityDelegate(view, null);
}
}
/**
* Installs the click listeners that will dispatch the click handler
* defined in the component's props. Unconditionally set the clickable
* flag on the view.
*/
private static void setClickHandler(EventHandler<ClickEvent> clickHandler, View view) {
if (clickHandler == null) {
return;
}
ComponentClickListener listener = getComponentClickListener(view);
if (listener == null) {
listener = new ComponentClickListener();
setComponentClickListener(view, listener);
}
listener.setEventHandler(clickHandler);
view.setClickable(true);
}
private static void unsetClickHandler(View view) {
final ComponentClickListener listener = getComponentClickListener(view);
if (listener != null) {
listener.setEventHandler(null);
}
}
static ComponentClickListener getComponentClickListener(View v) {
if (v instanceof ComponentHost) {
return ((ComponentHost) v).getComponentClickListener();
} else {
return (ComponentClickListener) v.getTag(R.id.component_click_listener);
}
}
static void setComponentClickListener(View v, ComponentClickListener listener) {
if (v instanceof ComponentHost) {
((ComponentHost) v).setComponentClickListener(listener);
} else {
v.setOnClickListener(listener);
v.setTag(R.id.component_click_listener, listener);
}
}
/**
* Installs the long click listeners that will dispatch the click handler
* defined in the component's props. Unconditionally set the clickable
* flag on the view.
*/
private static void setLongClickHandler(
EventHandler<LongClickEvent> longClickHandler, View view) {
if (longClickHandler != null) {
ComponentLongClickListener listener = getComponentLongClickListener(view);
if (listener == null) {
listener = new ComponentLongClickListener();
setComponentLongClickListener(view, listener);
}
listener.setEventHandler(longClickHandler);
view.setLongClickable(true);
}
}
private static void unsetLongClickHandler(View view) {
final ComponentLongClickListener listener = getComponentLongClickListener(view);
if (listener != null) {
listener.setEventHandler(null);
}
}
static ComponentLongClickListener getComponentLongClickListener(View v) {
if (v instanceof ComponentHost) {
return ((ComponentHost) v).getComponentLongClickListener();
} else {
return (ComponentLongClickListener) v.getTag(R.id.component_long_click_listener);
}
}
static void setComponentLongClickListener(View v, ComponentLongClickListener listener) {
if (v instanceof ComponentHost) {
((ComponentHost) v).setComponentLongClickListener(listener);
} else {
v.setOnLongClickListener(listener);
v.setTag(R.id.component_long_click_listener, listener);
}
}
/**
* Installs the on focus change listeners that will dispatch the click handler
* defined in the component's props. Unconditionally set the clickable
* flag on the view.
*/
private static void setFocusChangeHandler(
EventHandler<FocusChangedEvent> focusChangeHandler, View view) {
if (focusChangeHandler == null) {
return;
}
ComponentFocusChangeListener listener = getComponentFocusChangeListener(view);
if (listener == null) {
listener = new ComponentFocusChangeListener();
setComponentFocusChangeListener(view, listener);
}
listener.setEventHandler(focusChangeHandler);
}
private static void unsetFocusChangeHandler(View view) {
final ComponentFocusChangeListener listener = getComponentFocusChangeListener(view);
if (listener != null) {
listener.setEventHandler(null);
}
}
static ComponentFocusChangeListener getComponentFocusChangeListener(View v) {
if (v instanceof ComponentHost) {
return ((ComponentHost) v).getComponentFocusChangeListener();
} else {
return (ComponentFocusChangeListener) v.getTag(R.id.component_focus_change_listener);
}
}
static void setComponentFocusChangeListener(View v, ComponentFocusChangeListener listener) {
if (v instanceof ComponentHost) {
((ComponentHost) v).setComponentFocusChangeListener(listener);
} else {
v.setOnFocusChangeListener(listener);
v.setTag(R.id.component_focus_change_listener, listener);
}
}
/**
* Installs the touch listeners that will dispatch the touch handler
* defined in the component's props.
*/
private static void setTouchHandler(EventHandler<TouchEvent> touchHandler, View view) {
if (touchHandler != null) {
ComponentTouchListener listener = getComponentTouchListener(view);
if (listener == null) {
listener = new ComponentTouchListener();
setComponentTouchListener(view, listener);
}
listener.setEventHandler(touchHandler);
}
}
private static void unsetTouchHandler(View view) {
final ComponentTouchListener listener = getComponentTouchListener(view);
if (listener != null) {
listener.setEventHandler(null);
}
}
/**
* Sets the intercept touch handler defined in the component's props.
*/
private static void setInterceptTouchHandler(
EventHandler<InterceptTouchEvent> interceptTouchHandler,
View view) {
if (interceptTouchHandler == null) {
return;
}
if (view instanceof ComponentHost) {
((ComponentHost) view).setInterceptTouchEventHandler(interceptTouchHandler);
}
}
private static void unsetInterceptTouchEventHandler(View view) {
if (view instanceof ComponentHost) {
((ComponentHost) view).setInterceptTouchEventHandler(null);
}
}
static ComponentTouchListener getComponentTouchListener(View v) {
if (v instanceof ComponentHost) {
return ((ComponentHost) v).getComponentTouchListener();
} else {
return (ComponentTouchListener) v.getTag(R.id.component_touch_listener);
}
}
static void setComponentTouchListener(View v, ComponentTouchListener listener) {
if (v instanceof ComponentHost) {
((ComponentHost) v).setComponentTouchListener(listener);
} else {
v.setOnTouchListener(listener);
v.setTag(R.id.component_touch_listener, listener);
}
}
private static void setViewTag(View view, Object viewTag) {
if (view instanceof ComponentHost) {
final ComponentHost host = (ComponentHost) view;
host.setViewTag(viewTag);
} else {
view.setTag(viewTag);
}
}
private static void setViewTags(View view, SparseArray<Object> viewTags) {
if (viewTags == null) {
return;
}
if (view instanceof ComponentHost) {
final ComponentHost host = (ComponentHost) view;
host.setViewTags(viewTags);
} else {
for (int i = 0, size = viewTags.size(); i < size; i++) {
view.setTag(viewTags.keyAt(i), viewTags.valueAt(i));
}
}
}
private static void unsetViewTag(View view) {
if (view instanceof ComponentHost) {
final ComponentHost host = (ComponentHost) view;
host.setViewTag(null);
} else {
view.setTag(null);
}
}
private static void unsetViewTags(View view, SparseArray<Object> viewTags) {
if (view instanceof ComponentHost) {
final ComponentHost host = (ComponentHost) view;
host.setViewTags(null);
} else {
if (viewTags != null) {
for (int i = 0, size = viewTags.size(); i < size; i++) {
view.setTag(viewTags.keyAt(i), null);
}
}
}
}
private static void setShadowElevation(View view, float shadowElevation) {
if (shadowElevation != 0) {
ViewCompat.setElevation(view, shadowElevation);
}
}
private static void unsetShadowElevation(View view, float shadowElevation) {
if (shadowElevation != 0) {
ViewCompat.setElevation(view, 0);
}
}
private static void setOutlineProvider(View view, ViewOutlineProvider outlineProvider) {
if (outlineProvider != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.setOutlineProvider(outlineProvider);
}
}
private static void unsetOutlineProvider(View view, ViewOutlineProvider outlineProvider) {
if (outlineProvider != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.setOutlineProvider(ViewOutlineProvider.BACKGROUND);
}
}
private static void setClipToOutline(View view, boolean clipToOutline) {
if (clipToOutline && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.setClipToOutline(clipToOutline);
}
}
private static void unsetClipToOutline(View view, boolean clipToOutline) {
if (clipToOutline && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.setClipToOutline(false);
}
}
private static void setClipChildren(View view, NodeInfo nodeInfo) {
if (nodeInfo.isClipChildrenSet() && view instanceof ViewGroup) {
((ViewGroup) view).setClipChildren(nodeInfo.getClipChildren());
}
}
private static void unsetClipChildren(View view, boolean clipChildren) {
if (!clipChildren && view instanceof ViewGroup) {
// Default value for clipChildren is 'true'.
// If this ViewGroup had clipChildren set to 'false' before mounting we would reset this
// property here on recycling.
((ViewGroup) view).setClipChildren(true);
}
}
private static void setContentDescription(View view, CharSequence contentDescription) {
if (TextUtils.isEmpty(contentDescription)) {
return;
}
view.setContentDescription(contentDescription);
}
private static void unsetContentDescription(View view) {
view.setContentDescription(null);
}
private static void setImportantForAccessibility(View view, int importantForAccessibility) {
if (importantForAccessibility == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
return;
}
ViewCompat.setImportantForAccessibility(view, importantForAccessibility);
}
private static void unsetImportantForAccessibility(View view) {
ViewCompat.setImportantForAccessibility(view, IMPORTANT_FOR_ACCESSIBILITY_AUTO);
}
private static void setFocusable(View view, @NodeInfo.FocusState int focusState) {
if (focusState == NodeInfo.FOCUS_SET_TRUE) {
view.setFocusable(true);
} else if (focusState == NodeInfo.FOCUS_SET_FALSE) {
view.setFocusable(false);
}
}
private static void unsetFocusable(View view, MountItem mountItem) {
view.setFocusable(mountItem.isViewFocusable());
}
private static void setClickable(View view, @NodeInfo.FocusState int clickableState) {
if (clickableState == NodeInfo.CLICKABLE_SET_TRUE) {
view.setClickable(true);
} else if (clickableState == NodeInfo.CLICKABLE_SET_FALSE) {
view.setClickable(false);
}
}
private static void setEnabled(View view, @NodeInfo.EnabledState int enabledState) {
if (enabledState == NodeInfo.ENABLED_SET_TRUE) {
view.setEnabled(true);
} else if (enabledState == NodeInfo.ENABLED_SET_FALSE) {
view.setEnabled(false);
}
}
private static void unsetEnabled(View view, MountItem mountItem) {
view.setEnabled(mountItem.isViewEnabled());
}
private static void setSelected(View view, @NodeInfo.SelectedState int selectedState) {
if (selectedState == NodeInfo.SELECTED_SET_TRUE) {
view.setSelected(true);
} else if (selectedState == NodeInfo.SELECTED_SET_FALSE) {
view.setSelected(false);
}
}
private static void unsetSelected(View view, MountItem mountItem) {
view.setSelected(mountItem.isViewSelected());
}
private static void setScale(View view, NodeInfo nodeInfo) {
if (Build.VERSION.SDK_INT >= 11) {
if (nodeInfo.isScaleSet()) {
final float scale = nodeInfo.getScale();
view.setScaleX(scale);
view.setScaleY(scale);
}
}
}
private static void unsetScale(View view, NodeInfo nodeInfo) {
if (Build.VERSION.SDK_INT >= 11) {
if (nodeInfo.isScaleSet()) {
if (view.getScaleX() != 1) {
view.setScaleX(1);
}
if (view.getScaleY() != 1) {
view.setScaleY(1);
}
}
}
}
private static void setAlpha(View view, NodeInfo nodeInfo) {
if (Build.VERSION.SDK_INT >= 11) {
if (nodeInfo.isAlphaSet()) {
view.setAlpha(nodeInfo.getAlpha());
}
}
}
private static void unsetAlpha(View view, NodeInfo nodeInfo) {
if (Build.VERSION.SDK_INT >= 11) {
if (nodeInfo.isAlphaSet() && view.getAlpha() != 1) {
view.setAlpha(1);
}
}
}
private static void setRotation(View view, NodeInfo nodeInfo) {
if (Build.VERSION.SDK_INT >= 11) {
if (nodeInfo.isRotationSet()) {
view.setRotation(nodeInfo.getRotation());
}
}
}
private static void unsetRotation(View view, NodeInfo nodeInfo) {
if (Build.VERSION.SDK_INT >= 11) {
if (nodeInfo.isRotationSet() && view.getRotation() != 0) {
view.setRotation(0);
}
}
}
private static void setRotationX(View view, NodeInfo nodeInfo) {
if (Build.VERSION.SDK_INT >= 11) {
if (nodeInfo.isRotationXSet()) {
view.setRotationX(nodeInfo.getRotationX());
}
}
}
private static void unsetRotationX(View view, NodeInfo nodeInfo) {
if (Build.VERSION.SDK_INT >= 11) {
if (nodeInfo.isRotationXSet() && view.getRotationX() != 0) {
view.setRotationX(0);
}
}
}
private static void setRotationY(View view, NodeInfo nodeInfo) {
if (Build.VERSION.SDK_INT >= 11) {
if (nodeInfo.isRotationYSet()) {
view.setRotationY(nodeInfo.getRotationY());
}
}
}
private static void unsetRotationY(View view, NodeInfo nodeInfo) {
if (Build.VERSION.SDK_INT >= 11) {
if (nodeInfo.isRotationYSet() && view.getRotationY() != 0) {
view.setRotationY(0);
}
}
}
private static void setViewPadding(View view, ViewNodeInfo viewNodeInfo) {
if (!viewNodeInfo.hasPadding()) {
return;
}
view.setPadding(
viewNodeInfo.getPaddingLeft(),
viewNodeInfo.getPaddingTop(),
viewNodeInfo.getPaddingRight(),
viewNodeInfo.getPaddingBottom());
}
private static void unsetViewPadding(View view, ViewNodeInfo viewNodeInfo) {
if (!viewNodeInfo.hasPadding()) {
return;
}
view.setPadding(0, 0, 0, 0);
}
private static void setViewBackground(View view, ViewNodeInfo viewNodeInfo) {
final ComparableDrawable background = viewNodeInfo.getBackground();
if (background != null) {
setBackgroundCompat(view, background);
}
}
private static void unsetViewBackground(View view, ViewNodeInfo viewNodeInfo) {
final ComparableDrawable background = viewNodeInfo.getBackground();
final Drawable drawable = view.getBackground();
if (background != null) {
setBackgroundCompat(view, null);
}
}
@SuppressWarnings("deprecation")
private static void setBackgroundCompat(View view, Drawable drawable) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(drawable);
} else {
view.setBackground(drawable);
}
}
private static void setViewForeground(View view, ViewNodeInfo viewNodeInfo) {
final Drawable foreground = viewNodeInfo.getForeground();
if (foreground != null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
throw new IllegalStateException("MountState has a ViewNodeInfo with foreground however " +
"the current Android version doesn't support foreground on Views");
}
view.setForeground(foreground);
}
}
private static void unsetViewForeground(View view, ViewNodeInfo viewNodeInfo) {
final Drawable foreground = viewNodeInfo.getForeground();
if (foreground != null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
throw new IllegalStateException("MountState has a ViewNodeInfo with foreground however " +
"the current Android version doesn't support foreground on Views");
}
view.setForeground(null);
}
}
private static void setViewLayoutDirection(View view, ViewNodeInfo viewNodeInfo) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return;
}
final int viewLayoutDirection;
switch (viewNodeInfo.getLayoutDirection()) {
case LTR:
viewLayoutDirection = View.LAYOUT_DIRECTION_LTR;
break;
case RTL:
viewLayoutDirection = View.LAYOUT_DIRECTION_RTL;
break;
default:
viewLayoutDirection = View.LAYOUT_DIRECTION_INHERIT;
}
view.setLayoutDirection(viewLayoutDirection);
}
private static void unsetViewLayoutDirection(View view, ViewNodeInfo viewNodeInfo) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return;
}
view.setLayoutDirection(View.LAYOUT_DIRECTION_INHERIT);
}
private static void setViewStateListAnimator(View view, ViewNodeInfo viewNodeInfo) {
StateListAnimator stateListAnimator = viewNodeInfo.getStateListAnimator();
final int stateListAnimatorRes = viewNodeInfo.getStateListAnimatorRes();
if (stateListAnimator == null && stateListAnimatorRes == 0) {
return;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
throw new IllegalStateException(
"MountState has a ViewNodeInfo with stateListAnimator, "
+ "however the current Android version doesn't support stateListAnimator on Views");
}
if (stateListAnimator == null) {
stateListAnimator =
AnimatorInflater.loadStateListAnimator(view.getContext(), stateListAnimatorRes);
}
view.setStateListAnimator(stateListAnimator);
}
private static void unsetViewStateListAnimator(View view, ViewNodeInfo viewNodeInfo) {
if (viewNodeInfo.getStateListAnimator() == null
&& viewNodeInfo.getStateListAnimatorRes() == 0) {
return;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
throw new IllegalStateException(
"MountState has a ViewNodeInfo with stateListAnimator, "
+ "however the current Android version doesn't support stateListAnimator on Views");
}
view.setStateListAnimator(null);
}
private static void mountItemIncrementally(
MountItem item, Rect itemBounds, Rect localVisibleRect, boolean processVisibilityOutputs) {
final Component component = item.getComponent();
if (!isMountViewSpec(component)) {
return;
}
// We can't just use the bounds of the View since we need the bounds relative to the
// hosting LithoView (which is what the localVisibleRect is measured relative to).
final View view = (View) item.getContent();
mountViewIncrementally(view, processVisibilityOutputs);
}
private static void mountViewIncrementally(View view, boolean processVisibilityOutputs) {
assertMainThread();
if (view instanceof LithoView) {
final LithoView lithoView = (LithoView) view;
if (lithoView.isIncrementalMountEnabled()) {
if (!processVisibilityOutputs) {
lithoView.performIncrementalMount(
new Rect(0, 0, view.getWidth(), view.getHeight()), false);
} else {
lithoView.performIncrementalMount();
}
}
} else if (view instanceof ViewGroup) {
final ViewGroup viewGroup = (ViewGroup) view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
final View childView = viewGroup.getChildAt(i);
mountViewIncrementally(childView, processVisibilityOutputs);
}
}
}
private void unmountDisappearingItemChild(ComponentContext context, MountItem item) {
maybeRemoveAnimatingMountContent(item.getTransitionId());
final Object content = item.getContent();
// Recursively unmount mounted children items.
if (content instanceof ComponentHost) {
final ComponentHost host = (ComponentHost) content;
for (int i = host.getMountItemCount() - 1; i >= 0; i--) {
final MountItem mountItem = host.getMountItemAt(i);
unmountDisappearingItemChild(context, mountItem);
}
if (host.getMountItemCount() > 0) {
throw new IllegalStateException("Recursively unmounting items from a ComponentHost, left" +
" some items behind maybe because not tracked by its MountState");
}
}
final ComponentHost host = item.getHost();
host.unmount(item);
maybeUnsetViewAttributes(item);
unbindAndUnmountLifecycle(item);
if (item.getComponent().hasChildLithoViews()) {
final int index = mCanMountIncrementallyMountItems.indexOfValue(item);
if (index > 0) {
mCanMountIncrementallyMountItems.removeAt(index);
}
}
item.releaseMountContent(context.getAndroidContext());
}
void unmountAllItems() {
assertMainThread();
if (mLayoutOutputsIds == null) {
return;
}
for (int i = mLayoutOutputsIds.length - 1; i >= 0; i--) {
unmountItem(i, mHostsByMarker);
}
mPreviousLocalVisibleRect.setEmpty();
mNeedsRemount = true;
}
private void unmountItem(
int index,
LongSparseArray<ComponentHost> hostsByMarker) {
final MountItem item = getItemAt(index);
final long startTime = System.nanoTime();
// Already has been unmounted.
if (item == null) {
return;
}
// The root host item should never be unmounted as it's a reference
// to the top-level LithoView.
if (mLayoutOutputsIds[index] == ROOT_HOST_ID) {
unsetViewAttributes(item, true);
return;
}
final Object content = item.getContent();
// Recursively unmount mounted children items.
// This is the case when mountDiffing is enabled and unmountOrMoveOldItems() has a matching
// sub tree. However, traversing the tree bottom-up, it needs to unmount a node holding that
// sub tree, that will still have mounted items. (Different sequence number on LayoutOutput id)
if ((content instanceof ComponentHost) && !(content instanceof LithoView)) {
final ComponentHost host = (ComponentHost) content;
// Concurrently remove items therefore traverse backwards.
for (int i = host.getMountItemCount() - 1; i >= 0; i--) {
final MountItem mountItem = host.getMountItemAt(i);
final long layoutOutputId = mIndexToItemMap.keyAt(mIndexToItemMap.indexOfValue(mountItem));
for (int mountIndex = mLayoutOutputsIds.length - 1; mountIndex >= 0; mountIndex--) {
if (mLayoutOutputsIds[mountIndex] == layoutOutputId) {
unmountItem(mountIndex, hostsByMarker);
break;
}
}
}
if (host.getMountItemCount() > 0) {
throw new IllegalStateException("Recursively unmounting items from a ComponentHost, left" +
" some items behind maybe because not tracked by its MountState");
}
}
/*
* The mounted content might contain other LithoViews which are not reachable from
* this MountState. If that content contains other LithoViews, we need to unmount them as well,
* so that their contents are recycled and reused next time.
*/
if (content instanceof HasLithoViewChildren) {
final ArrayList<LithoView> lithoViews = new ArrayList<>();
((HasLithoViewChildren) content).obtainLithoViewChildren(lithoViews);
for (int i = lithoViews.size() - 1; i >= 0; i--) {
final LithoView lithoView = lithoViews.get(i);
lithoView.unmountAllItems();
}
}
final ComponentHost host = item.getHost();
host.unmount(index, item);
maybeUnsetViewAttributes(item);
final Component component = item.getComponent();
if (isHostSpec(component)) {
final ComponentHost componentHost = (ComponentHost) content;
hostsByMarker.removeAt(hostsByMarker.indexOfValue(componentHost));
removeDisappearingMountContentFromComponentHost(componentHost);
}
unbindAndUnmountLifecycle(item);
final long layoutOutputId = mLayoutOutputsIds[index];
mIndexToItemMap.remove(layoutOutputId);
if (item.hasTransitionId()) {
final @OutputUnitType int type = LayoutStateOutputIdCalculator.getTypeFromId(layoutOutputId);
maybeRemoveAnimatingMountContent(item.getTransitionId(), type);
}
if (component.hasChildLithoViews()) {
mCanMountIncrementallyMountItems.delete(mLayoutOutputsIds[index]);
}
final String rootComponentName =
mLastMountedLayoutState == null
? "null_layout"
: mLastMountedLayoutState.mRootComponentName;
if (!(isHostSpec(component)
&& ComponentHostRecycleUtil.shouldSkipRecyclingComponentHost(index, rootComponentName))) {
item.releaseMountContent(mContext.getAndroidContext());
}
if (mMountStats.isLoggingEnabled) {
mMountStats.unmountedTimes.add((System.nanoTime() - startTime) / NS_IN_MS);
mMountStats.unmountedNames.add(component.getSimpleName());
mMountStats.unmountedCount++;
}
}
private void unbindAndUnmountLifecycle(
MountItem item) {
final Component component = item.getComponent();
final Object content = item.getContent();
final ComponentContext context = getContextForComponent(component);
// Call the component's unmount() method.
if (item.isBound()) {
component.onUnbind(context, content);
item.setIsBound(false);
}
component.unmount(context, content);
}
private void endUnmountDisappearingItem(OutputUnitsAffinityGroup<MountItem> group) {
maybeRemoveAnimatingMountContent(group.getMostSignificantUnit().getTransitionId());
for (int i = 0, size = group.size(); i < size; i++) {
final MountItem item = group.getAt(i);
// We used to do (item.getContent() instanceof ComponentHost) check here, which didn't
// take
// into consideration MountSpecs that mount a LithoView which would pass the check while
// shouldn't
if (group.typeAt(i) == OutputUnitType.HOST) {
final ComponentHost content = (ComponentHost) item.getContent();
// Unmount descendant items in reverse order.
for (int j = content.getMountItemCount() - 1; j >= 0; j--) {
final MountItem mountItem = content.getMountItemAt(j);
unmountDisappearingItemChild(mContext, mountItem);
}
if (content.getMountItemCount() > 0) {
throw new IllegalStateException(
"Recursively unmounting items from a ComponentHost, left"
+ " some items behind maybe because not tracked by its MountState");
}
}
final ComponentHost host = item.getHost();
host.unmountDisappearingItem(item);
maybeUnsetViewAttributes(item);
unbindAndUnmountLifecycle(item);
if (item.getComponent().hasChildLithoViews()) {
final int index = mCanMountIncrementallyMountItems.indexOfValue(item);
if (index > 0) {
mCanMountIncrementallyMountItems.removeAt(index);
}
}
item.releaseMountContent(mContext.getAndroidContext());
}
}
int getItemCount() {
assertMainThread();
return mLayoutOutputsIds == null ? 0 : mLayoutOutputsIds.length;
}
MountItem getItemAt(int i) {
assertMainThread();
return mIndexToItemMap.get(mLayoutOutputsIds[i]);
}
/**
* Creates and updates transitions for a new LayoutState. The steps are as follows:
*
* <p>1. Disappearing items: Update disappearing mount items that are no longer disappearing (e.g.
* because they came back). This means canceling the animation and cleaning up the corresponding
* ComponentHost.
*
* <p>2. New transitions: Use the transition manager to create new animations.
*
* <p>3. Update locked indices: Based on running/new animations, there are some mount items we
* want to make sure are not unmounted due to incremental mount and being outside of visibility
* bounds.
*/
private void updateTransitions(LayoutState layoutState, ComponentTree componentTree) {
if (!mIsDirty) {
throw new RuntimeException("Should only process transitions on dirty mounts");
}
final boolean isTracing = ComponentsSystrace.isTracing();
if (isTracing) {
String logTag = componentTree.getContext().getLogTag();
if (logTag == null) {
ComponentsSystrace.beginSection("MountState.updateTransitions");
} else {
ComponentsSystrace.beginSection("MountState.updateTransitions:" + logTag);
}
}
try {
// If this is a new component tree but isn't the first time it's been mounted, then we shouldn't
// do any transition animations for changed mount content as it's just being remounted on a
// new LithoView.
final int componentTreeId = layoutState.getComponentTreeId();
if (mLastMountedComponentTreeId != componentTreeId) {
resetAnimationState();
if (!mIsFirstMountOfComponentTree) {
return;
}
}
if (!mDisappearingMountItems.isEmpty()) {
updateDisappearingMountItems(layoutState);
}
if (shouldAnimateTransitions(layoutState)) {
collectAllTransitions(layoutState, componentTree);
if (hasTransitionsToAnimate()) {
createNewTransitions(layoutState, mRootTransition);
}
}
mAnimationLockedIndices = null;
if (!mAnimatingTransitionIds.isEmpty()) {
regenerateAnimationLockedIndices(layoutState);
}
} finally {
if (isTracing) {
ComponentsSystrace.endSection();
}
}
}
private void resetAnimationState() {
if (mTransitionManager == null) {
return;
}
for (OutputUnitsAffinityGroup<MountItem> group : mDisappearingMountItems.values()) {
endUnmountDisappearingItem(group);
}
mDisappearingMountItems.clear();
mAnimatingTransitionIds.clear();
mTransitionManager.reset();
mAnimationLockedIndices = null;
}
private void updateDisappearingMountItems(LayoutState newLayoutState) {
final Map<TransitionId, ?> nextMountedTransitionIds = newLayoutState.getTransitionIdMapping();
for (TransitionId transitionId : nextMountedTransitionIds.keySet()) {
final OutputUnitsAffinityGroup<MountItem> disappearingItem =
mDisappearingMountItems.remove(transitionId);
if (disappearingItem != null) {
endUnmountDisappearingItem(disappearingItem);
}
}
}
private void createNewTransitions(LayoutState newLayoutState, Transition rootTransition) {
prepareTransitionManager(newLayoutState);
mTransitionManager.setupTransitions(mLastMountedLayoutState, newLayoutState, rootTransition);
final Map<TransitionId, ?> nextTransitionIds = newLayoutState.getTransitionIdMapping();
for (TransitionId transitionId : nextTransitionIds.keySet()) {
if (mTransitionManager.isAnimating(transitionId)) {
mAnimatingTransitionIds.add(transitionId);
}
}
}
private void regenerateAnimationLockedIndices(LayoutState newLayoutState) {
final Map<TransitionId, OutputUnitsAffinityGroup<LayoutOutput>> transitionMapping =
newLayoutState.getTransitionIdMapping();
if (transitionMapping != null) {
for (TransitionId transitionId : transitionMapping.keySet()) {
if (!mAnimatingTransitionIds.contains(transitionId)) {
continue;
}
if (mAnimationLockedIndices == null) {
mAnimationLockedIndices = new int[newLayoutState.getMountableOutputCount()];
}
final OutputUnitsAffinityGroup<LayoutOutput> group = transitionMapping.get(transitionId);
for (int j = 0, sz = group.size(); j < sz; j++) {
final LayoutOutput layoutOutput = group.getAt(j);
final int position = newLayoutState.getLayoutOutputPositionForId(layoutOutput.getId());
updateAnimationLockCount(newLayoutState, position, true);
}
}
} else {
mAnimationLockedIndices = null;
}
if (AnimationsDebug.ENABLED) {
AnimationsDebug.debugPrintAnimationLockedIndices(newLayoutState, mAnimationLockedIndices);
}
}
private int findLastDescendantIndex(LayoutState layoutState, int index) {
final LayoutOutput host = layoutState.getMountableOutputAt(index);
final long hostId = host.getId();
for (int i = index + 1, size = layoutState.getMountableOutputCount(); i < size; i++) {
final LayoutOutput layoutOutput = layoutState.getMountableOutputAt(i);
// Walk up the parents looking for the host's id: if we find it, it's a descendant. If we
// reach the root, then it's not a descendant and we can stop.
long curentHostId = layoutOutput.getHostMarker();
while (curentHostId != hostId) {
if (curentHostId == ROOT_HOST_ID) {
return i - 1;
}
final int parentIndex = layoutState.getLayoutOutputPositionForId(curentHostId);
final LayoutOutput parent = layoutState.getMountableOutputAt(parentIndex);
curentHostId = parent.getHostMarker();
}
}
return layoutState.getMountableOutputCount() - 1;
}
/**
* Update the animation locked count for all children and each parent of the animating item.
* Mount items that have a lock count > 0 will not be unmounted during incremental mount.
*/
private void updateAnimationLockCount(LayoutState layoutState, int index, boolean increment) {
// Update children
final int lastDescendantIndex = findLastDescendantIndex(layoutState, index);
for (int i = index; i <= lastDescendantIndex; i++) {
if (increment) {
mAnimationLockedIndices[i]++;
} else {
if (--mAnimationLockedIndices[i] < 0) {
ComponentsReporter.emitMessage(
ComponentsReporter.LogLevel.FATAL, "Decremented animation lock count below 0!");
mAnimationLockedIndices[i] = 0;
}
}
}
// Update parents
long hostId = layoutState.getMountableOutputAt(index).getHostMarker();
while (hostId != ROOT_HOST_ID) {
final int hostIndex = layoutState.getLayoutOutputPositionForId(hostId);
if (increment) {
mAnimationLockedIndices[hostIndex]++;
} else {
if (--mAnimationLockedIndices[hostIndex] < 0) {
ComponentsReporter.emitMessage(
ComponentsReporter.LogLevel.FATAL, "Decremented animation lock count below 0!");
mAnimationLockedIndices[hostIndex] = 0;
}
}
hostId = layoutState.getMountableOutputAt(hostIndex).getHostMarker();
}
}
/**
* @return whether we should animate transitions if we have any when mounting the new LayoutState.
*/
private boolean shouldAnimateTransitions(LayoutState newLayoutState) {
return mIsDirty
&& (mLastMountedComponentTreeId == newLayoutState.getComponentTreeId()
|| mIsFirstMountOfComponentTree);
}
/**
* @return whether we have any transitions to animate for the current mount of the given
* LayoutState
*/
private boolean hasTransitionsToAnimate() {
return mRootTransition != null;
}
@Override
public void onAnimationComplete(TransitionId transitionId) {
final OutputUnitsAffinityGroup<MountItem> disappearingGroup =
mDisappearingMountItems.remove(transitionId);
if (disappearingGroup != null) {
endUnmountDisappearingItem(disappearingGroup);
} else {
if (!mAnimatingTransitionIds.remove(transitionId)) {
if (AnimationsDebug.ENABLED) {
Log.e(
AnimationsDebug.TAG,
"Ending animation for id " + transitionId + " but it wasn't recorded as animating!");
}
}
final OutputUnitsAffinityGroup<LayoutOutput> layoutOutputGroup =
mLastMountedLayoutState.getLayoutOutputsForTransitionId(transitionId);
if (layoutOutputGroup == null) {
// This can happen if the component was unmounted without animation or the transitionId
// was removed from the component.
return;
}
for (int i = 0, size = layoutOutputGroup.size(); i < size; i++) {
final LayoutOutput layoutOutput = layoutOutputGroup.getAt(i);
final int position = layoutOutput.getIndex();
updateAnimationLockCount(mLastMountedLayoutState, position, false);
if (shouldSkipMounting(mLastMountedLayoutState, position)) {
// So this item should not be mounted anymore
// 1. Update the records
mSkipMounting.set(position);
// 2. Unmount the item
unmountItem(position, mHostsByMarker);
// 3. Re-mount all the children of the item
final int lastDescendantIndex =
findLastDescendantIndex(mLastMountedLayoutState, position);
for (int j = position + 1; j <= lastDescendantIndex; j++) {
final LayoutOutput childLayoutOutput = mLastMountedLayoutState.getMountableOutputAt(j);
mountLayoutOutput(j, childLayoutOutput, mLastMountedLayoutState);
}
}
}
if (ComponentsConfiguration.isDebugModeEnabled && mAnimatingTransitionIds.isEmpty()) {
for (int i = 0, size = mAnimationLockedIndices.length; i < size; i++) {
if (mAnimationLockedIndices[i] != 0) {
throw new RuntimeException(
"No running animations but index " + i + " is still animation locked!");
}
}
}
}
}
private static class PrepareMountStats {
private int unmountedCount = 0;
private int movedCount = 0;
private int unchangedCount = 0;
private PrepareMountStats() {}
private void reset() {
unchangedCount = 0;
movedCount = 0;
unmountedCount = 0;
}
}
private static class MountStats {
private List<String> mountedNames;
private List<String> unmountedNames;
private List<String> updatedNames;
private List<String> visibilityHandlerNames;
private List<String> extras;
private List<Double> mountTimes;
private List<Double> unmountedTimes;
private List<Double> updatedTimes;
private List<Double> visibilityHandlerTimes;
private int mountedCount;
private int unmountedCount;
private int updatedCount;
private int noOpCount;
private double visibilityHandlersTotalTime;
private boolean isLoggingEnabled;
private boolean isInitialized;
private void enableLogging() {
isLoggingEnabled = true;
if (!isInitialized) {
isInitialized = true;
mountedNames = new ArrayList<>();
unmountedNames = new ArrayList<>();
updatedNames = new ArrayList<>();
visibilityHandlerNames = new ArrayList<>();
extras = new ArrayList<>();
mountTimes = new ArrayList<>();
unmountedTimes = new ArrayList<>();
updatedTimes = new ArrayList<>();
visibilityHandlerTimes = new ArrayList<>();
}
}
private void reset() {
mountedCount = 0;
unmountedCount = 0;
updatedCount = 0;
noOpCount = 0;
visibilityHandlersTotalTime = 0;
if (isInitialized) {
mountedNames.clear();
unmountedNames.clear();
updatedNames.clear();
visibilityHandlerNames.clear();
extras.clear();
mountTimes.clear();
unmountedTimes.clear();
updatedTimes.clear();
visibilityHandlerTimes.clear();
}
isLoggingEnabled = false;
}
}
/**
* Unbinds all the MountItems currently mounted on this MountState. Unbinding a MountItem means
* calling unbind on its {@link Component}. The MountItem is not yet unmounted after unbind is
* called and can be re-used in place to re-mount another {@link Component} with the same
* {@link ComponentLifecycle}.
*/
void unbind() {
assertMainThread();
if (mLayoutOutputsIds == null) {
return;
}
boolean isTracing = ComponentsSystrace.isTracing();
if (isTracing) {
ComponentsSystrace.beginSection("MountState.unbind");
}
for (int i = 0, size = mLayoutOutputsIds.length; i < size; i++) {
MountItem mountItem = getItemAt(i);
if (mountItem == null || !mountItem.isBound()) {
continue;
}
final Component component = mountItem.getComponent();
component.unbind(getContextForComponent(component), mountItem.getContent());
mountItem.setIsBound(false);
}
clearVisibilityItems();
if (isTracing) {
ComponentsSystrace.endSection();
}
}
void detach() {
assertMainThread();
unbind();
}
/**
* This is called when the {@link MountItem}s mounted on this {@link MountState} need to be
* re-bound with the same component. The common case here is a detach/attach happens on the
* {@link LithoView} that owns the MountState.
*/
void rebind() {
assertMainThread();
if (mLayoutOutputsIds == null) {
return;
}
for (int i = 0, size = mLayoutOutputsIds.length; i < size; i++) {
final MountItem mountItem = getItemAt(i);
if (mountItem == null || mountItem.isBound()) {
continue;
}
final Component component = mountItem.getComponent();
final Object content = mountItem.getContent();
component.bind(getContextForComponent(component), content);
mountItem.setIsBound(true);
if (content instanceof View &&
!(content instanceof ComponentHost) &&
((View) content).isLayoutRequested()) {
final View view = (View) content;
applyBoundsToMountContent(
view,
view.getLeft(),
view.getTop(),
view.getRight(),
view.getBottom(),
true);
}
}
}
/**
* Whether the item at this index (or one of its parents) are animating. In that case, we don't
* want to unmount this index for visibility reasons (e.g. incremental mount). The reason for this
* is that this item (or it's parent) may have a translation X/Y that actually shows it on the
* screen, even though the non-translated bounds are off the screen.
*/
private boolean isAnimationLocked(int index) {
if (mAnimationLockedIndices == null) {
return false;
}
return mAnimationLockedIndices[index] > 0;
}
/**
* @return true if this method did all the work that was necessary and there is no other content
* that needs mounting/unmounting in this mount step. If false then a full mount step should
* take place.
*/
private boolean performIncrementalMount(
LayoutState layoutState, Rect localVisibleRect, boolean processVisibilityOutputs) {
if (mPreviousLocalVisibleRect.isEmpty()) {
return false;
}
if (localVisibleRect.left != mPreviousLocalVisibleRect.left ||
localVisibleRect.right != mPreviousLocalVisibleRect.right) {
return false;
}
final ArrayList<LayoutOutput> layoutOutputTops = layoutState.getMountableOutputTops();
final ArrayList<LayoutOutput> layoutOutputBottoms = layoutState.getMountableOutputBottoms();
final int count = layoutState.getMountableOutputCount();
if (localVisibleRect.top > 0 || mPreviousLocalVisibleRect.top > 0) {
// View is going on/off the top of the screen. Check the bottoms to see if there is anything
// that has moved on/off the top of the screen.
while (mPreviousBottomsIndex < count &&
localVisibleRect.top >=
layoutOutputBottoms.get(mPreviousBottomsIndex).getBounds().bottom) {
final long id = layoutOutputBottoms.get(mPreviousBottomsIndex).getId();
final int layoutOutputIndex = layoutState.getLayoutOutputPositionForId(id);
if (!isAnimationLocked(layoutOutputIndex)) {
unmountItem(layoutOutputIndex, mHostsByMarker);
}
mPreviousBottomsIndex++;
}
while (mPreviousBottomsIndex > 0 &&
localVisibleRect.top <
layoutOutputBottoms.get(mPreviousBottomsIndex - 1).getBounds().bottom) {
mPreviousBottomsIndex--;
final LayoutOutput layoutOutput = layoutOutputBottoms.get(mPreviousBottomsIndex);
final int layoutOutputIndex =
layoutState.getLayoutOutputPositionForId(layoutOutput.getId());
if (getItemAt(layoutOutputIndex) == null) {
mountLayoutOutput(
layoutState.getLayoutOutputPositionForId(layoutOutput.getId()),
layoutOutput,
layoutState);
mComponentIdsMountedInThisFrame.add(layoutOutput.getId());
}
}
}
final int height = mLithoView.getHeight();
if (localVisibleRect.bottom < height || mPreviousLocalVisibleRect.bottom < height) {
// View is going on/off the bottom of the screen. Check the tops to see if there is anything
// that has changed.
while (mPreviousTopsIndex < count &&
localVisibleRect.bottom > layoutOutputTops.get(mPreviousTopsIndex).getBounds().top) {
final LayoutOutput layoutOutput = layoutOutputTops.get(mPreviousTopsIndex);
final int layoutOutputIndex =
layoutState.getLayoutOutputPositionForId(layoutOutput.getId());
if (getItemAt(layoutOutputIndex) == null) {
mountLayoutOutput(
layoutState.getLayoutOutputPositionForId(layoutOutput.getId()),
layoutOutput,
layoutState);
mComponentIdsMountedInThisFrame.add(layoutOutput.getId());
}
mPreviousTopsIndex++;
}
while (mPreviousTopsIndex > 0 &&
localVisibleRect.bottom <=
layoutOutputTops.get(mPreviousTopsIndex - 1).getBounds().top) {
mPreviousTopsIndex--;
final long id = layoutOutputTops.get(mPreviousTopsIndex).getId();
final int layoutOutputIndex = layoutState.getLayoutOutputPositionForId(id);
if (!isAnimationLocked(layoutOutputIndex)) {
unmountItem(layoutOutputIndex, mHostsByMarker);
}
}
}
for (int i = 0, size = mCanMountIncrementallyMountItems.size(); i < size; i++) {
final MountItem mountItem = mCanMountIncrementallyMountItems.valueAt(i);
final long layoutOutputId = mCanMountIncrementallyMountItems.keyAt(i);
if (!mComponentIdsMountedInThisFrame.contains(layoutOutputId)) {
final int layoutOutputPosition = layoutState.getLayoutOutputPositionForId(layoutOutputId);
if (layoutOutputPosition != -1) {
mountItemIncrementally(
mountItem,
layoutState.getMountableOutputAt(layoutOutputPosition).getBounds(),
localVisibleRect,
processVisibilityOutputs);
}
}
}
mComponentIdsMountedInThisFrame.clear();
return true;
}
LithoView getLithoView() {
assertMainThread();
return mLithoView;
}
private void prepareTransitionManager(LayoutState layoutState) {
if (mTransitionManager == null) {
mTransitionManager = new TransitionManager(this, this);
}
}
private void removeDisappearingMountContentFromComponentHost(ComponentHost componentHost) {
if (componentHost.hasDisappearingItems()) {
List<TransitionId> ids = componentHost.getDisappearingItemTransitionIds();
for (int i = 0, size = ids.size(); i < size; i++) {
mTransitionManager.setMountContent(ids.get(i), null);
}
}
}
/**
* Collect transitions from layout time, mount time and from state updates.
*
* @param layoutState that is going to be mounted.
*/
void collectAllTransitions(LayoutState layoutState, ComponentTree componentTree) {
assertMainThread();
if (mTransitionsHasBeenCollected) {
return;
}
final ArrayList<Transition> allTransitions = new ArrayList<>();
if (layoutState.getTransitions() != null) {
allTransitions.addAll(layoutState.getTransitions());
}
componentTree.applyPreviousRenderData(layoutState);
collectMountTimeTransitions(layoutState, allTransitions);
componentTree.consumeStateUpdateTransitions(allTransitions, layoutState.mRootComponentName);
Transition.RootBoundsTransition rootWidthTransition = new Transition.RootBoundsTransition();
Transition.RootBoundsTransition rootHeightTransition = new Transition.RootBoundsTransition();
final TransitionId rootTransitionId = layoutState.getRootTransitionId();
if (rootTransitionId != null) {
for (int i = 0, size = allTransitions.size(); i < size; i++) {
final Transition transition = allTransitions.get(i);
if (transition == null) {
throw new IllegalStateException(
"NULL_TRANSITION when collecting root bounds anim. Root: "
+ layoutState.mRootComponentName
+ ", root TransitionId: "
+ rootTransitionId);
}
TransitionUtils.collectRootBoundsTransitions(
rootTransitionId, transition, AnimatedProperties.WIDTH, rootWidthTransition);
TransitionUtils.collectRootBoundsTransitions(
rootTransitionId, transition, AnimatedProperties.HEIGHT, rootHeightTransition);
}
}
rootWidthTransition = rootWidthTransition.hasTransition ? rootWidthTransition : null;
rootHeightTransition = rootHeightTransition.hasTransition ? rootHeightTransition : null;
componentTree.setRootWidthAnimation(rootWidthTransition);
componentTree.setRootHeightAnimation(rootHeightTransition);
mRootTransition = TransitionManager.getRootTransition(allTransitions);
mTransitionsHasBeenCollected = true;
}
private static @Nullable void collectMountTimeTransitions(
LayoutState layoutState, List<Transition> outList) {
final List<Component> componentsNeedingPreviousRenderData =
layoutState.getComponentsNeedingPreviousRenderData();
if (componentsNeedingPreviousRenderData == null) {
return;
}
for (int i = 0, size = componentsNeedingPreviousRenderData.size(); i < size; i++) {
final Component component = componentsNeedingPreviousRenderData.get(i);
final Transition transition = component.createTransition(component.getScopedContext());
if (transition != null) {
TransitionUtils.addTransitions(transition, outList, layoutState.mRootComponentName);
}
}
}
/**
* @see LithoViewTestHelper#findTestItems(LithoView, String)
*/
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
Deque<TestItem> findTestItems(String testKey) {
if (mTestItemMap == null) {
throw new UnsupportedOperationException("Trying to access TestItems while " +
"ComponentsConfiguration.isEndToEndTestRun is false.");
}
final Deque<TestItem> items = mTestItemMap.get(testKey);
return items == null ? new LinkedList<TestItem>() : items;
}
/**
* For HostComponents, we don't set a scoped context during layout calculation because we don't
* need one, as we could never call a state update on it. Instead it's okay to use the context
* that is passed to MountState from the LithoView, which is not scoped.
*/
private ComponentContext getContextForComponent(Component component) {
final ComponentContext c = component.getScopedContext();
return c == null ? mContext : c;
}
}
|
litho-core/src/main/java/com/facebook/litho/MountState.java
|
/*
* Copyright 2014-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.litho;
import static androidx.core.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
import static com.facebook.litho.Component.isHostSpec;
import static com.facebook.litho.Component.isMountViewSpec;
import static com.facebook.litho.ComponentHostUtils.maybeInvalidateAccessibilityState;
import static com.facebook.litho.ComponentHostUtils.maybeSetDrawableState;
import static com.facebook.litho.FrameworkLogEvents.EVENT_MOUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_IS_DIRTY;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_CONTENT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_EXTRAS;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_TIME;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MOVED_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_NO_OP_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UNCHANGED_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UNMOUNTED_CONTENT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UNMOUNTED_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UNMOUNTED_TIME;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UPDATED_CONTENT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UPDATED_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UPDATED_TIME;
import static com.facebook.litho.FrameworkLogEvents.PARAM_VISIBILITY_HANDLER;
import static com.facebook.litho.FrameworkLogEvents.PARAM_VISIBILITY_HANDLERS_TOTAL_TIME;
import static com.facebook.litho.FrameworkLogEvents.PARAM_VISIBILITY_HANDLER_TIME;
import static com.facebook.litho.ThreadUtils.assertMainThread;
import android.animation.AnimatorInflater;
import android.animation.StateListAnimator;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.collection.LongSparseArray;
import androidx.core.view.ViewCompat;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.litho.animation.AnimatedProperties;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.drawable.ComparableDrawable;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Encapsulates the mounted state of a {@link Component}. Provides APIs to update state by recycling
* existing UI elements e.g. {@link Drawable}s.
*
* @see #mount(LayoutState, Rect, boolean)
* @see LithoView
* @see LayoutState
*/
@ThreadConfined(ThreadConfined.UI)
class MountState implements TransitionManager.OnAnimationCompleteListener {
static final long ROOT_HOST_ID = 0L;
private static final double NS_IN_MS = 1000000.0;
private static final BitSet sEmptyBitSet = new BitSet(0);
// Holds the current list of mounted items.
// Should always be used within a draw lock.
private final LongSparseArray<MountItem> mIndexToItemMap;
// Holds a list with information about the components linked to the VisibilityOutputs that are
// stored in LayoutState. An item is inserted in this map if its corresponding component is
// visible. When the component exits the viewport, the item associated with it is removed from the
// map.
private final LongSparseArray<VisibilityItem> mVisibilityIdToItemMap;
// Holds a list of MountItems that are currently mounted which can mount incrementally.
private final LongSparseArray<MountItem> mCanMountIncrementallyMountItems;
// A map from test key to a list of one or more `TestItem`s which is only allocated
// and populated during test runs.
private final Map<String, Deque<TestItem>> mTestItemMap;
// Both these arrays are updated in prepareMount(), thus during mounting they hold the information
// about the LayoutState that is being mounted, not mLastMountedLayoutState
@Nullable private long[] mLayoutOutputsIds;
@Nullable private BitSet mSkipMounting;
// True if we are receiving a new LayoutState and we need to completely
// refresh the content of the HostComponent. Always set from the main thread.
private boolean mIsDirty;
// See #needsRemount()
private boolean mNeedsRemount;
// Holds the list of known component hosts during a mount pass.
private final LongSparseArray<ComponentHost> mHostsByMarker = new LongSparseArray<>();
private static final Rect sTempRect = new Rect();
private static final Rect sTempRect2 = new Rect();
private final ComponentContext mContext;
private final LithoView mLithoView;
private final Rect mPreviousLocalVisibleRect = new Rect();
private final PrepareMountStats mPrepareMountStats = new PrepareMountStats();
private final MountStats mMountStats = new MountStats();
private int mPreviousTopsIndex;
private int mPreviousBottomsIndex;
private int mLastMountedComponentTreeId = ComponentTree.INVALID_ID;
private LayoutState mLastMountedLayoutState;
private boolean mIsFirstMountOfComponentTree = false;
private final MountItem mRootHostMountItem;
private TransitionManager mTransitionManager;
private final HashSet<TransitionId> mAnimatingTransitionIds = new HashSet<>();
private int[] mAnimationLockedIndices;
private final Map<TransitionId, OutputUnitsAffinityGroup<MountItem>> mDisappearingMountItems =
new LinkedHashMap<>();
private @Nullable Transition mRootTransition;
private boolean mTransitionsHasBeenCollected = false;
private final Set<Long> mComponentIdsMountedInThisFrame = new HashSet<>();
public MountState(LithoView view) {
mIndexToItemMap = new LongSparseArray<>();
mVisibilityIdToItemMap = new LongSparseArray<>();
mCanMountIncrementallyMountItems = new LongSparseArray<>();
mContext = view.getComponentContext();
mLithoView = view;
mIsDirty = true;
mTestItemMap = ComponentsConfiguration.isEndToEndTestRun
? new HashMap<String, Deque<TestItem>>()
: null;
// The mount item representing the top-level root host (LithoView) which
// is always automatically mounted.
mRootHostMountItem = MountItem.createRootHostMountItem(mLithoView);
}
/**
* To be called whenever the components needs to start the mount process from scratch
* e.g. when the component's props or layout change or when the components
* gets attached to a host.
*/
void setDirty() {
assertMainThread();
mIsDirty = true;
mPreviousLocalVisibleRect.setEmpty();
}
boolean isDirty() {
assertMainThread();
return mIsDirty;
}
/**
* True if we have manually unmounted content (e.g. via unmountAllItems) which means that while we
* may not have a new LayoutState, the mounted content does not match what the viewport for the
* LithoView may be.
*/
boolean needsRemount() {
assertMainThread();
return mNeedsRemount;
}
/**
* Sets whether the next mount will be the first mount of this ComponentTree. This is used to
* determine whether to run animations or not (we want animations to run on the first mount of
* this ComponentTree, but not other times the mounted ComponentTree id changes). Ideally, we want
* animations to only occur when the ComponentTree is updated on screen or is first inserted into
* a list onscreen, but that requires more integration with the list controller, e.g. sections,
* than we currently have.
*/
void setIsFirstMountOfComponentTree() {
assertMainThread();
mIsFirstMountOfComponentTree = true;
}
/**
* Mount the layoutState on the pre-set HostView.
*
* @param layoutState
* @param localVisibleRect If this variable is null, then mount everything, since incremental
* mount is not enabled. Otherwise mount only what the rect (in local coordinates) contains
* @param processVisibilityOutputs whether to process visibility outputs as part of the mount
*/
void mount(LayoutState layoutState, Rect localVisibleRect, boolean processVisibilityOutputs) {
assertMainThread();
if (layoutState == null) {
throw new IllegalStateException("Trying to mount a null layoutState");
}
final ComponentTree componentTree = mLithoView.getComponentTree();
final boolean isIncrementalMountEnabled = localVisibleRect != null;
final boolean isTracing = ComponentsSystrace.isTracing();
if (isTracing) {
final StringBuilder sectionName =
new StringBuilder(isIncrementalMountEnabled ? "incrementalMount" : "mount")
.append("_")
.append(componentTree.getSimpleName());
final String logTag = componentTree.getContext().getLogTag();
if (logTag != null) {
sectionName.append("_").append(logTag);
}
ComponentsSystrace.beginSectionWithArgs(sectionName.toString())
.arg("treeId", layoutState.getComponentTreeId())
.flush();
}
final ComponentsLogger logger = componentTree.getContext().getLogger();
final int componentTreeId = layoutState.getComponentTreeId();
if (componentTreeId != mLastMountedComponentTreeId) {
// If we're mounting a new ComponentTree, don't keep around and use the previous LayoutState
// since things like transition animations aren't relevant.
mLastMountedLayoutState = null;
}
final PerfEvent mountPerfEvent =
logger == null
? null
: LogTreePopulator.populatePerfEventFromLogger(
componentTree.getContext(),
logger,
logger.newPerformanceEvent(componentTree.getContext(), EVENT_MOUNT));
if (mIsDirty) {
updateTransitions(layoutState, componentTree);
suppressInvalidationsOnHosts(true);
// Prepare the data structure for the new LayoutState and removes mountItems
// that are not present anymore if isUpdateMountInPlace is enabled.
if (mountPerfEvent != null) {
mountPerfEvent.markerPoint("PREPARE_MOUNT_START");
}
prepareMount(layoutState, mountPerfEvent);
if (mountPerfEvent != null) {
mountPerfEvent.markerPoint("PREPARE_MOUNT_END");
}
}
mMountStats.reset();
if (mountPerfEvent != null && logger.isTracing(mountPerfEvent)) {
mMountStats.enableLogging();
}
if (!isIncrementalMountEnabled
|| !performIncrementalMount(layoutState, localVisibleRect, processVisibilityOutputs)) {
final MountItem rootMountItem = mIndexToItemMap.get(ROOT_HOST_ID);
for (int i = 0, size = layoutState.getMountableOutputCount(); i < size; i++) {
final LayoutOutput layoutOutput = layoutState.getMountableOutputAt(i);
final Component component = layoutOutput.getComponent();
if (isTracing) {
ComponentsSystrace.beginSection(component.getSimpleName());
}
final MountItem currentMountItem = getItemAt(i);
final boolean isMounted = currentMountItem != null;
final boolean isMountable =
!isIncrementalMountEnabled ||
isMountedHostWithChildContent(currentMountItem) ||
Rect.intersects(localVisibleRect, layoutOutput.getBounds()) ||
isAnimationLocked(i) ||
(currentMountItem != null && currentMountItem == rootMountItem);
if (isMountable && !isMounted) {
mountLayoutOutput(i, layoutOutput, layoutState);
if (isAnimationLocked(i)
&& isIncrementalMountEnabled
&& canMountIncrementally(component)) {
// If the component is locked for animation then we need to make sure that all the
// children are also mounted.
final View view = (View) getItemAt(i).getContent();
// We're mounting everything, don't process visibility outputs as they will not be
// accurate.
mountViewIncrementally(view, false);
}
} else if (!isMountable && isMounted) {
unmountItem(i, mHostsByMarker);
} else if (isMounted) {
if (mIsDirty) {
final boolean useUpdateValueFromLayoutOutput =
mLastMountedLayoutState != null
&& mLastMountedLayoutState.getId() == layoutState.getPreviousLayoutStateId();
final long startTime = System.nanoTime();
final TransitionId transitionId = currentMountItem.getTransitionId();
final boolean itemUpdated =
updateMountItemIfNeeded(
layoutOutput,
layoutState,
currentMountItem,
useUpdateValueFromLayoutOutput,
logger,
componentTreeId,
i);
if (itemUpdated) {
// This mount content might be animating and we may be remounting it as a different
// component in the same tree, or as a component in a totally different tree so we
// will reset animating content for its key
maybeRemoveAnimatingMountContent(transitionId);
}
if (mMountStats.isLoggingEnabled) {
if (itemUpdated) {
mMountStats.updatedNames.add(component.getSimpleName());
mMountStats.updatedTimes.add((System.nanoTime() - startTime) / NS_IN_MS);
mMountStats.updatedCount++;
} else {
mMountStats.noOpCount++;
}
}
}
if (isIncrementalMountEnabled && canMountIncrementally(component)) {
mountItemIncrementally(
currentMountItem,
layoutOutput.getBounds(),
localVisibleRect,
processVisibilityOutputs);
}
}
if (isTracing) {
ComponentsSystrace.endSection();
}
}
if (isIncrementalMountEnabled) {
setupPreviousMountableOutputData(layoutState, localVisibleRect);
}
}
maybeUpdateAnimatingMountContent();
if (shouldAnimateTransitions(layoutState) && hasTransitionsToAnimate()) {
mTransitionManager.runTransitions();
}
if (processVisibilityOutputs) {
ComponentsSystrace.beginSection("processVisibilityOutputs");
processVisibilityOutputs(layoutState, localVisibleRect, mountPerfEvent);
ComponentsSystrace.endSection();
}
mRootTransition = null;
mTransitionsHasBeenCollected = false;
mIsDirty = false;
mNeedsRemount = false;
mIsFirstMountOfComponentTree = false;
if (localVisibleRect != null) {
mPreviousLocalVisibleRect.set(localVisibleRect);
}
mLastMountedLayoutState = null;
mLastMountedComponentTreeId = componentTreeId;
mLastMountedLayoutState = layoutState;
processTestOutputs(layoutState);
suppressInvalidationsOnHosts(false);
if (logger != null) {
logMountPerfEvent(logger, mountPerfEvent);
}
if (isTracing) {
ComponentsSystrace.endSection();
}
}
private void logMountPerfEvent(ComponentsLogger logger, @Nullable PerfEvent mountPerfEvent) {
if (!mMountStats.isLoggingEnabled || mountPerfEvent == null) {
logger.cancelPerfEvent(mountPerfEvent);
return;
}
// MOUNT events that don't mount any content are not valuable enough to log at the moment.
// We will likely enable them again in the future. T31729233
if (mMountStats.mountedCount == 0 || mMountStats.mountedNames.isEmpty()) {
logger.cancelPerfEvent(mountPerfEvent);
return;
}
mountPerfEvent.markerAnnotate(PARAM_MOUNTED_COUNT, mMountStats.mountedCount);
mountPerfEvent.markerAnnotate(
PARAM_MOUNTED_CONTENT, mMountStats.mountedNames.toArray(new String[0]));
mountPerfEvent.markerAnnotate(
PARAM_MOUNTED_TIME, mMountStats.mountTimes.toArray(new Double[0]));
mountPerfEvent.markerAnnotate(PARAM_UNMOUNTED_COUNT, mMountStats.unmountedCount);
mountPerfEvent.markerAnnotate(
PARAM_UNMOUNTED_CONTENT, mMountStats.unmountedNames.toArray(new String[0]));
mountPerfEvent.markerAnnotate(
PARAM_UNMOUNTED_TIME, mMountStats.unmountedTimes.toArray(new Double[0]));
mountPerfEvent.markerAnnotate(PARAM_MOUNTED_EXTRAS, mMountStats.extras.toArray(new String[0]));
mountPerfEvent.markerAnnotate(PARAM_UPDATED_COUNT, mMountStats.updatedCount);
mountPerfEvent.markerAnnotate(
PARAM_UPDATED_CONTENT, mMountStats.updatedNames.toArray(new String[0]));
mountPerfEvent.markerAnnotate(
PARAM_UPDATED_TIME, mMountStats.updatedTimes.toArray(new Double[0]));
mountPerfEvent.markerAnnotate(
PARAM_VISIBILITY_HANDLERS_TOTAL_TIME, mMountStats.visibilityHandlersTotalTime);
mountPerfEvent.markerAnnotate(
PARAM_VISIBILITY_HANDLER, mMountStats.visibilityHandlerNames.toArray(new String[0]));
mountPerfEvent.markerAnnotate(
PARAM_VISIBILITY_HANDLER_TIME, mMountStats.visibilityHandlerTimes.toArray(new Double[0]));
mountPerfEvent.markerAnnotate(PARAM_NO_OP_COUNT, mMountStats.noOpCount);
mountPerfEvent.markerAnnotate(PARAM_IS_DIRTY, mIsDirty);
logger.logPerfEvent(mountPerfEvent);
}
private void maybeRemoveAnimatingMountContent(TransitionId transitionId) {
if (mTransitionManager == null || transitionId == null) {
return;
}
mTransitionManager.setMountContent(transitionId, null);
}
private void maybeRemoveAnimatingMountContent(
TransitionId transitionId, @OutputUnitType int type) {
if (mTransitionManager == null || transitionId == null) {
return;
}
mTransitionManager.removeMountContent(transitionId, type);
}
private void maybeUpdateAnimatingMountContent() {
if (mTransitionManager == null) {
return;
}
// Group mount content (represents current LayoutStates only) into groups and pass it to the
// TransitionManager
final Map<TransitionId, OutputUnitsAffinityGroup<Object>> animatingContent =
new LinkedHashMap<>(mAnimatingTransitionIds.size());
for (int i = 0, size = mIndexToItemMap.size(); i < size; i++) {
final MountItem mountItem = mIndexToItemMap.valueAt(i);
if (!mountItem.hasTransitionId()) {
continue;
}
final long layoutOutputId = mIndexToItemMap.keyAt(i);
final @OutputUnitType int type = LayoutStateOutputIdCalculator.getTypeFromId(layoutOutputId);
OutputUnitsAffinityGroup<Object> group = animatingContent.get(mountItem.getTransitionId());
if (group == null) {
group = new OutputUnitsAffinityGroup<>();
animatingContent.put(mountItem.getTransitionId(), group);
}
group.replace(type, mountItem.getContent());
}
for (TransitionId transitionId : animatingContent.keySet()) {
mTransitionManager.setMountContent(transitionId, animatingContent.get(transitionId));
}
// Retrieve mount content from disappearing mount items and pass it to the TransitionManager
for (TransitionId transitionId : mDisappearingMountItems.keySet()) {
final OutputUnitsAffinityGroup<MountItem> mountItemsGroup =
mDisappearingMountItems.get(transitionId);
final OutputUnitsAffinityGroup<Object> mountContentGroup = new OutputUnitsAffinityGroup<>();
for (int j = 0, sz = mountItemsGroup.size(); j < sz; j++) {
final @OutputUnitType int type = mountItemsGroup.typeAt(j);
final MountItem mountItem = mountItemsGroup.getAt(j);
mountContentGroup.add(type, mountItem.getContent());
}
mTransitionManager.setMountContent(transitionId, mountContentGroup);
}
}
void processVisibilityOutputs(
LayoutState layoutState, Rect localVisibleRect, @Nullable PerfEvent mountPerfEvent) {
assertMainThread();
if (localVisibleRect == null) {
return;
}
if (mountPerfEvent != null) {
mountPerfEvent.markerPoint("VISIBILITY_HANDLERS_START");
}
final boolean isDoingPerfLog = mMountStats.isLoggingEnabled;
final boolean isTracing = ComponentsSystrace.isTracing();
final long totalStartTime = isDoingPerfLog ? System.nanoTime() : 0L;
for (int j = 0, size = layoutState.getVisibilityOutputCount(); j < size; j++) {
final VisibilityOutput visibilityOutput = layoutState.getVisibilityOutputAt(j);
if (isTracing) {
final String componentName =
visibilityOutput.getComponent() != null
? visibilityOutput.getComponent().getSimpleName()
: "Unknown";
ComponentsSystrace.beginSection("visibilityHandlers:" + componentName);
}
final long handlerStartTime = isDoingPerfLog ? System.nanoTime() : 0;
final EventHandler<VisibleEvent> visibleHandler = visibilityOutput.getVisibleEventHandler();
final EventHandler<FocusedVisibleEvent> focusedHandler =
visibilityOutput.getFocusedEventHandler();
final EventHandler<UnfocusedVisibleEvent> unfocusedHandler =
visibilityOutput.getUnfocusedEventHandler();
final EventHandler<FullImpressionVisibleEvent> fullImpressionHandler =
visibilityOutput.getFullImpressionEventHandler();
final EventHandler<InvisibleEvent> invisibleHandler =
visibilityOutput.getInvisibleEventHandler();
final EventHandler<VisibilityChangedEvent> visibilityChangedHandler =
visibilityOutput.getVisibilityChangedEventHandler();
final long visibilityOutputId = visibilityOutput.getId();
final Rect visibilityOutputBounds = visibilityOutput.getBounds();
boolean boundsIntersect = sTempRect.setIntersect(visibilityOutputBounds, localVisibleRect);
final boolean isCurrentlyVisible =
boundsIntersect && isInVisibleRange(visibilityOutput, visibilityOutputBounds, sTempRect);
VisibilityItem visibilityItem = mVisibilityIdToItemMap.get(visibilityOutputId);
if (visibilityItem != null) {
final String previousGlobalKey = visibilityItem.getGlobalKey();
final String currentGlobalKey =
visibilityOutput.getComponent() != null
? visibilityOutput.getComponent().getGlobalKey()
: null;
final boolean hasGlobalKeyChanged =
previousGlobalKey != null && !previousGlobalKey.equals(currentGlobalKey);
if (!hasGlobalKeyChanged) {
// If we did a relayout due to e.g. a state update then the handlers will have changed,
// so we should keep them up to date.
visibilityItem.setUnfocusedHandler(unfocusedHandler);
visibilityItem.setInvisibleHandler(invisibleHandler);
}
if (!isCurrentlyVisible || hasGlobalKeyChanged) {
// Either the component is invisible now, but used to be visible, or the key on the
// component has changed so we should generate new visibility events for the new
// component.
if (visibilityItem.getInvisibleHandler() != null) {
EventDispatcherUtils.dispatchOnInvisible(visibilityItem.getInvisibleHandler());
}
if (visibilityChangedHandler != null) {
EventDispatcherUtils.dispatchOnVisibilityChanged(
visibilityChangedHandler, 0, 0, 0f, 0f);
}
if (visibilityItem.isInFocusedRange()) {
visibilityItem.setFocusedRange(false);
if (visibilityItem.getUnfocusedHandler() != null) {
EventDispatcherUtils.dispatchOnUnfocused(visibilityItem.getUnfocusedHandler());
}
}
mVisibilityIdToItemMap.remove(visibilityOutputId);
visibilityItem = null;
} else {
// Processed, do not clear.
visibilityItem.setDoNotClearInThisPass(mIsDirty);
}
}
if (isCurrentlyVisible) {
// The component is visible now, but used to be outside the viewport.
if (visibilityItem == null) {
final String globalKey =
visibilityOutput.getComponent() != null
? visibilityOutput.getComponent().getGlobalKey()
: null;
visibilityItem =
new VisibilityItem(
globalKey, invisibleHandler, unfocusedHandler, visibilityChangedHandler);
visibilityItem.setDoNotClearInThisPass(mIsDirty);
mVisibilityIdToItemMap.put(visibilityOutputId, visibilityItem);
if (visibleHandler != null) {
EventDispatcherUtils.dispatchOnVisible(visibleHandler);
}
}
// Check if the component has entered or exited the focused range.
if (focusedHandler != null || unfocusedHandler != null) {
if (isInFocusedRange(visibilityOutputBounds, sTempRect)) {
if (!visibilityItem.isInFocusedRange()) {
visibilityItem.setFocusedRange(true);
if (focusedHandler != null) {
EventDispatcherUtils.dispatchOnFocused(focusedHandler);
}
}
} else {
if (visibilityItem.isInFocusedRange()) {
visibilityItem.setFocusedRange(false);
if (unfocusedHandler != null) {
EventDispatcherUtils.dispatchOnUnfocused(unfocusedHandler);
}
}
}
}
// If the component has not entered the full impression range yet, make sure to update the
// information about the visible edges.
if (fullImpressionHandler != null && !visibilityItem.isInFullImpressionRange()) {
visibilityItem.setVisibleEdges(visibilityOutputBounds, sTempRect);
if (visibilityItem.isInFullImpressionRange()) {
EventDispatcherUtils.dispatchOnFullImpression(fullImpressionHandler);
}
}
if (visibilityChangedHandler != null) {
final int visibleWidth = sTempRect.right - sTempRect.left;
final int visibleHeight = sTempRect.bottom - sTempRect.top;
EventDispatcherUtils.dispatchOnVisibilityChanged(
visibilityChangedHandler,
visibleWidth,
visibleHeight,
100f * visibleWidth / visibilityOutputBounds.width(),
100f * visibleHeight / visibilityOutputBounds.height());
}
}
if (isDoingPerfLog) {
final String componentName =
visibilityOutput.getComponent() != null
? visibilityOutput.getComponent().getSimpleName()
: "Unknown";
mMountStats.visibilityHandlerTimes.add((System.nanoTime() - handlerStartTime) / NS_IN_MS);
mMountStats.visibilityHandlerNames.add(componentName);
}
if (isTracing) {
ComponentsSystrace.endSection();
}
}
if (mIsDirty) {
clearVisibilityItems();
}
if (isDoingPerfLog) {
mMountStats.visibilityHandlersTotalTime = (System.nanoTime() - totalStartTime) / NS_IN_MS;
}
if (mountPerfEvent != null) {
mountPerfEvent.markerPoint("VISIBILITY_HANDLERS_END");
}
}
/**
* Clears and re-populates the test item map if we are in e2e test mode.
*/
private void processTestOutputs(LayoutState layoutState) {
if (mTestItemMap == null) {
return;
}
mTestItemMap.clear();
for (int i = 0, size = layoutState.getTestOutputCount(); i < size; i++) {
final TestOutput testOutput = layoutState.getTestOutputAt(i);
final long hostMarker = testOutput.getHostMarker();
final long layoutOutputId = testOutput.getLayoutOutputId();
final MountItem mountItem =
layoutOutputId == -1 ? null : mIndexToItemMap.get(layoutOutputId);
final TestItem testItem = new TestItem();
testItem.setHost(hostMarker == -1 ? null : mHostsByMarker.get(hostMarker));
testItem.setBounds(testOutput.getBounds());
testItem.setTestKey(testOutput.getTestKey());
testItem.setContent(mountItem == null ? null : mountItem.getContent());
final Deque<TestItem> items = mTestItemMap.get(testOutput.getTestKey());
final Deque<TestItem> updatedItems =
items == null ? new LinkedList<TestItem>() : items;
updatedItems.add(testItem);
mTestItemMap.put(testOutput.getTestKey(), updatedItems);
}
}
private boolean isMountedHostWithChildContent(MountItem mountItem) {
if (mountItem == null) {
return false;
}
final Object content = mountItem.getContent();
if (!(content instanceof ComponentHost)) {
return false;
}
final ComponentHost host = (ComponentHost) content;
return host.getMountItemCount() > 0;
}
private void setupPreviousMountableOutputData(LayoutState layoutState, Rect localVisibleRect) {
if (localVisibleRect.isEmpty()) {
return;
}
final ArrayList<LayoutOutput> layoutOutputTops = layoutState.getMountableOutputTops();
final ArrayList<LayoutOutput> layoutOutputBottoms = layoutState.getMountableOutputBottoms();
final int mountableOutputCount = layoutState.getMountableOutputCount();
mPreviousTopsIndex = layoutState.getMountableOutputCount();
for (int i = 0; i < mountableOutputCount; i++) {
if (localVisibleRect.bottom <= layoutOutputTops.get(i).getBounds().top) {
mPreviousTopsIndex = i;
break;
}
}
mPreviousBottomsIndex = layoutState.getMountableOutputCount();
for (int i = 0; i < mountableOutputCount; i++) {
if (localVisibleRect.top < layoutOutputBottoms.get(i).getBounds().bottom) {
mPreviousBottomsIndex = i;
break;
}
}
}
void clearVisibilityItems() {
assertMainThread();
boolean isTracing = ComponentsSystrace.isTracing();
if (isTracing) {
ComponentsSystrace.beginSection("MountState.clearVisibilityItems");
}
for (int i = mVisibilityIdToItemMap.size() - 1; i >= 0; i--) {
final VisibilityItem visibilityItem = mVisibilityIdToItemMap.valueAt(i);
if (visibilityItem.doNotClearInThisPass()) {
// This visibility item has already been accounted for in this pass, so ignore it.
visibilityItem.setDoNotClearInThisPass(false);
} else {
final EventHandler<InvisibleEvent> invisibleHandler = visibilityItem.getInvisibleHandler();
final EventHandler<UnfocusedVisibleEvent> unfocusedHandler =
visibilityItem.getUnfocusedHandler();
final EventHandler<VisibilityChangedEvent> visibilityChangedHandler =
visibilityItem.getVisibilityChangedHandler();
if (invisibleHandler != null) {
EventDispatcherUtils.dispatchOnInvisible(invisibleHandler);
}
if (visibilityItem.isInFocusedRange()) {
visibilityItem.setFocusedRange(false);
if (unfocusedHandler != null) {
EventDispatcherUtils.dispatchOnUnfocused(unfocusedHandler);
}
}
if (visibilityChangedHandler != null) {
EventDispatcherUtils.dispatchOnVisibilityChanged(visibilityChangedHandler, 0, 0, 0f, 0f);
}
mVisibilityIdToItemMap.removeAt(i);
}
}
if (isTracing) {
ComponentsSystrace.endSection();
}
}
private void registerHost(long id, ComponentHost host) {
host.suppressInvalidations(true);
mHostsByMarker.put(id, host);
}
private boolean isInVisibleRange(
VisibilityOutput visibilityOutput,
Rect bounds,
Rect visibleBounds) {
float heightRatio = visibilityOutput.getVisibleHeightRatio();
float widthRatio = visibilityOutput.getVisibleWidthRatio();
if (heightRatio == 0 && widthRatio == 0) {
return true;
}
return isInRatioRange(heightRatio, bounds.height(), visibleBounds.height())
&& isInRatioRange(widthRatio, bounds.width(), visibleBounds.width());
}
private static boolean isInRatioRange(float ratio, int length, int visiblelength) {
return visiblelength >= ratio * length;
}
/**
* Returns true if the component is in the focused visible range.
*/
private boolean isInFocusedRange(
Rect componentBounds,
Rect componentVisibleBounds) {
final View parent = (View) mLithoView.getParent();
if (parent == null) {
return false;
}
final int halfViewportArea = parent.getWidth() * parent.getHeight() / 2;
final int totalComponentArea = computeRectArea(componentBounds);
final int visibleComponentArea = computeRectArea(componentVisibleBounds);
// The component has entered the focused range either if it is larger than half of the viewport
// and it occupies at least half of the viewport or if it is smaller than half of the viewport
// and it is fully visible.
return (totalComponentArea >= halfViewportArea)
? (visibleComponentArea >= halfViewportArea)
: componentBounds.equals(componentVisibleBounds);
}
private static int computeRectArea(Rect rect) {
return rect.isEmpty() ? 0 : (rect.width() * rect.height());
}
private void suppressInvalidationsOnHosts(boolean suppressInvalidations) {
for (int i = mHostsByMarker.size() - 1; i >= 0; i--) {
mHostsByMarker.valueAt(i).suppressInvalidations(suppressInvalidations);
}
}
private boolean updateMountItemIfNeeded(
LayoutOutput layoutOutput,
LayoutState layoutState,
MountItem currentMountItem,
boolean useUpdateValueFromLayoutOutput,
ComponentsLogger logger,
int componentTreeId,
int index) {
final Component layoutOutputComponent = layoutOutput.getComponent();
final Component itemComponent = currentMountItem.getComponent();
if (layoutOutputComponent == null) {
throw new RuntimeException("Trying to update a MountItem with a null Component.");
}
// 1. Check if the mount item generated from the old component should be updated.
final boolean shouldUpdateMountItem =
shouldUpdateMountItem(layoutOutput, currentMountItem, useUpdateValueFromLayoutOutput);
final boolean shouldUpdate = shouldUpdateMountItem;
final boolean shouldUpdateViewInfo =
shouldUpdateMountItem || shouldUpdateViewInfo(layoutOutput, currentMountItem);
// 2. Reset all the properties like click handler, content description and tags related to
// this item if it needs to be updated. the update mount item will re-set the new ones.
if (shouldUpdate) {
// If we're remounting this ComponentHost for a new ComponentTree, remove all disappearing
// mount content that was animating since those disappearing animations belong to the old
// ComponentTree
if (mLastMountedComponentTreeId != componentTreeId) {
final Component component = currentMountItem.getComponent();
if (isHostSpec(component)) {
final ComponentHost componentHost = (ComponentHost) currentMountItem.getContent();
removeDisappearingMountContentFromComponentHost(componentHost);
}
}
maybeUnsetViewAttributes(currentMountItem);
final ComponentHost host = currentMountItem.getHost();
host.maybeUnregisterTouchExpansion(index, currentMountItem);
} else if (shouldUpdateViewInfo) {
maybeUnsetViewAttributes(currentMountItem);
final ComponentHost host = currentMountItem.getHost();
host.maybeUnregisterTouchExpansion(index, currentMountItem);
}
// 3. We will re-bind this later in 7 regardless so let's make sure it's currently unbound.
if (currentMountItem.isBound()) {
itemComponent.onUnbind(getContextForComponent(itemComponent), currentMountItem.getContent());
currentMountItem.setIsBound(false);
}
// 4. Re initialize the MountItem internal state with the new attributes from LayoutOutput
currentMountItem.update(layoutOutput);
// 5. If the mount item is not valid for this component update its content and view attributes.
if (shouldUpdate) {
final ComponentHost host = currentMountItem.getHost();
host.maybeRegisterTouchExpansion(index, currentMountItem);
updateMountedContent(currentMountItem, layoutOutput, itemComponent);
setViewAttributes(currentMountItem);
} else if (shouldUpdateViewInfo) {
final ComponentHost host = currentMountItem.getHost();
host.maybeRegisterTouchExpansion(index, currentMountItem);
setViewAttributes(currentMountItem);
}
final Object currentContent = currentMountItem.getContent();
// 6. Set the mounted content on the Component and call the bind callback.
layoutOutputComponent.bind(getContextForComponent(layoutOutputComponent), currentContent);
currentMountItem.setIsBound(true);
// 7. Update the bounds of the mounted content. This needs to be done regardless of whether
// the component has been updated or not since the mounted item might might have the same
// size and content but a different position.
updateBoundsForMountedLayoutOutput(layoutOutput, layoutState, mSkipMounting, currentMountItem);
maybeInvalidateAccessibilityState(currentMountItem);
if (currentMountItem.getContent() instanceof Drawable) {
maybeSetDrawableState(
currentMountItem.getHost(),
(Drawable) currentMountItem.getContent(),
currentMountItem.getLayoutFlags(),
currentMountItem.getNodeInfo());
}
return shouldUpdate;
}
private static boolean shouldUpdateViewInfo(
LayoutOutput layoutOutput, MountItem currentMountItem) {
final ViewNodeInfo nextViewNodeInfo = layoutOutput.getViewNodeInfo();
final ViewNodeInfo currentViewNodeInfo = currentMountItem.getViewNodeInfo();
if ((currentViewNodeInfo == null && nextViewNodeInfo != null)
|| (currentViewNodeInfo != null && !currentViewNodeInfo.isEquivalentTo(nextViewNodeInfo))) {
return true;
}
final NodeInfo nextNodeInfo = layoutOutput.getNodeInfo();
final NodeInfo currentNodeInfo = currentMountItem.getNodeInfo();
if ((currentNodeInfo == null && nextNodeInfo != null)
|| (currentNodeInfo != null && !currentNodeInfo.isEquivalentTo(nextNodeInfo))) {
return true;
}
return false;
}
private static boolean shouldUpdateMountItem(
LayoutOutput layoutOutput,
MountItem currentMountItem,
boolean useUpdateValueFromLayoutOutput) {
@LayoutOutput.UpdateState final int updateState = layoutOutput.getUpdateState();
final Component currentComponent = currentMountItem.getComponent();
final ComponentLifecycle currentLifecycle = currentComponent;
final Component nextComponent = layoutOutput.getComponent();
final ComponentLifecycle nextLifecycle = nextComponent;
// If the orientation has changed, we should definitely update.
if (layoutOutput.getOrientation() != currentMountItem.getOrientation()) {
return true;
}
// If the two components have different sizes and the mounted content depends on the size we
// just return true immediately.
if (!sameSize(layoutOutput, currentMountItem) && nextLifecycle.isMountSizeDependent()) {
return true;
}
if (useUpdateValueFromLayoutOutput) {
if (updateState == LayoutOutput.STATE_UPDATED) {
// Check for incompatible ReferenceLifecycle.
return currentLifecycle instanceof DrawableComponent
&& nextLifecycle instanceof DrawableComponent
&& currentLifecycle.shouldComponentUpdate(currentComponent, nextComponent);
} else if (updateState == LayoutOutput.STATE_DIRTY) {
return true;
}
}
if (!currentLifecycle.callsShouldUpdateOnMount()) {
return true;
}
return currentLifecycle.shouldComponentUpdate(
currentComponent,
nextComponent);
}
private static boolean sameSize(LayoutOutput layoutOutput, MountItem item) {
final Rect layoutOutputBounds = layoutOutput.getBounds();
final Object mountedContent = item.getContent();
return layoutOutputBounds.width() == getWidthForMountedContent(mountedContent) &&
layoutOutputBounds.height() == getHeightForMountedContent(mountedContent);
}
private static int getWidthForMountedContent(Object content) {
return content instanceof Drawable ?
((Drawable) content).getBounds().width() :
((View) content).getWidth();
}
private static int getHeightForMountedContent(Object content) {
return content instanceof Drawable ?
((Drawable) content).getBounds().height() :
((View) content).getHeight();
}
private static void updateBoundsForMountedLayoutOutput(
LayoutOutput layoutOutput, LayoutState layoutState, BitSet skipMounting, MountItem item) {
// MountState should never update the bounds of the top-level host as this
// should be done by the ViewGroup containing the LithoView.
if (layoutOutput.getId() == ROOT_HOST_ID) {
return;
}
getActualBounds(layoutOutput, layoutState, skipMounting, sTempRect);
final boolean forceTraversal =
Component.isMountViewSpec(layoutOutput.getComponent())
&& ((View) item.getContent()).isLayoutRequested();
applyBoundsToMountContent(
item.getContent(),
sTempRect.left,
sTempRect.top,
sTempRect.right,
sTempRect.bottom,
forceTraversal /* force */);
}
/** Prepare the {@link MountState} to mount a new {@link LayoutState}. */
@SuppressWarnings("unchecked")
private void prepareMount(LayoutState layoutState, @Nullable PerfEvent perfEvent) {
final List<Integer> disappearingItems = extractDisappearingItems(layoutState);
final BitSet skipMounting = calculateSkipMounting(layoutState);
final PrepareMountStats stats =
unmountOrMoveOldItems(layoutState, skipMounting, disappearingItems);
if (perfEvent != null) {
perfEvent.markerAnnotate(PARAM_UNMOUNTED_COUNT, stats.unmountedCount);
perfEvent.markerAnnotate(PARAM_MOVED_COUNT, stats.movedCount);
perfEvent.markerAnnotate(PARAM_UNCHANGED_COUNT, stats.unchangedCount);
}
if (mHostsByMarker.get(ROOT_HOST_ID) == null) {
// Mounting always starts with the root host.
registerHost(ROOT_HOST_ID, mLithoView);
// Root host is implicitly marked as mounted.
mIndexToItemMap.put(ROOT_HOST_ID, mRootHostMountItem);
}
final int outputCount = layoutState.getMountableOutputCount();
if (mLayoutOutputsIds == null || outputCount != mLayoutOutputsIds.length) {
mLayoutOutputsIds = new long[outputCount];
}
for (int i = 0; i < outputCount; i++) {
mLayoutOutputsIds[i] = layoutState.getMountableOutputAt(i).getId();
}
mSkipMounting = skipMounting;
}
/**
* Determine whether to apply disappear animation to the given {@link MountItem}
*/
private boolean isItemDisappearing(LayoutState layoutState, int index) {
if (!shouldAnimateTransitions(layoutState) || !hasTransitionsToAnimate()) {
return false;
}
if (mTransitionManager == null || mLastMountedLayoutState == null) {
return false;
}
final LayoutOutput layoutOutput = mLastMountedLayoutState.getMountableOutputAt(index);
final TransitionId transitionId = layoutOutput.getTransitionId();
if (transitionId == null) {
return false;
}
return mTransitionManager.isDisappearing(transitionId);
}
/**
* Takes care of disappearing items from the last mounted layout (re-mounts them to the root if
* needed, starts disappearing, removes them from mapping). Returns the list of ids, which for
* every disappearing subtree contains a pair [index of the root of the subtree, index of the last
* descendant of that subtree]
*/
private List<Integer> extractDisappearingItems(LayoutState newLayoutState) {
if (mLayoutOutputsIds == null) {
return Collections.emptyList();
}
List<Integer> indices = null;
int index = 0;
while (index < mLayoutOutputsIds.length) {
if (isItemDisappearing(newLayoutState, index)) {
final int lastDescendantIndex = findLastDescendantIndex(mLastMountedLayoutState, index);
final LayoutOutput root = mLastMountedLayoutState.getMountableOutputAt(index);
if (mSkipMounting.get(index)) {
// The direct descendants of the root have been mounted to another host, thus here we'll
// unmount them from where they are mounted, and will remount to the root at the next step
final long rootId = root.getId();
for (int j = index + 1; j <= lastDescendantIndex; j++) {
if (mLastMountedLayoutState.getMountableOutputAt(j).getHostMarker() == rootId) {
unmountItem(j, mHostsByMarker);
}
}
// Need to override skip mounting value, otherwise it won't be mounted
mSkipMounting.clear(index);
}
// Go though disappearing subtree, mount everything that is not mounted yet
// That's okay to mount here *before* we call unmountOrMoveOldItems() and only passing
// last mount LayoutState
// This item representing the root of the disappearing subtree will be unmounted immediately
// after this cycle is over and will be moved to the root. If any if its parents have been
// mounted as well, they will get picked up in unmountOrMoveOldItems()
for (int j = index; j <= lastDescendantIndex; j++) {
final MountItem mountedItem = getItemAt(j);
if (mountedItem != null) {
// Item is already mounted - skip
continue;
}
final LayoutOutput layoutOutput = mLastMountedLayoutState.getMountableOutputAt(j);
mountLayoutOutput(j, layoutOutput, mLastMountedLayoutState);
}
// Reference to the root of the disappearing subtree
final MountItem disappearingItem = getItemAt(index);
// Moving item to the root
remountComponentHostToRootIfNeeded(index);
// Removing references of all the items of the disappearing subtree from mIndexToItemMap and
// mHostsByMaker
removeDisappearingItemMappings(index, lastDescendantIndex);
// Start animating disappearing
startUnmountDisappearingItem(disappearingItem, index);
if (indices == null) {
indices = new ArrayList<>(2);
}
indices.add(index);
indices.add(lastDescendantIndex);
index = lastDescendantIndex + 1;
} else {
index++;
}
}
return indices != null ? indices : Collections.<Integer>emptyList();
}
private void remountComponentHostToRootIfNeeded(int index) {
final ComponentHost rootHost = mHostsByMarker.get(ROOT_HOST_ID);
final MountItem item = getItemAt(index);
if (item.getHost() == rootHost) {
// Already mounted to the root
return;
}
final Object content = item.getContent();
// Before unmounting item get its position inside the root
int left = 0;
int top = 0;
int right;
int bottom;
// Get left/top position of the item's host first
ComponentHost componentHost = item.getHost();
while (componentHost != rootHost) {
left += componentHost.getLeft();
top += componentHost.getTop();
componentHost = (ComponentHost) componentHost.getParent();
}
if (content instanceof View) {
final View view = (View) content;
left += view.getLeft();
top += view.getTop();
right = left + view.getWidth();
bottom = top + view.getHeight();
} else {
final Rect bounds = ((Drawable) content).getBounds();
left += bounds.left;
right = left + bounds.width();
top += bounds.top;
bottom = top + bounds.height();
}
// Unmount from the current host
item.getHost().unmount(index, item);
// Apply new bounds to the content as it will be mounted in the root now
applyBoundsToMountContent(content, left, top, right, bottom, false);
// Mount to the root
rootHost.mount(index, item, sTempRect);
// Set new host to the MountItem
item.setHost(rootHost);
}
private void removeDisappearingItemMappings(int fromIndex, int toIndex) {
for (int i = fromIndex; i <= toIndex; i++) {
final MountItem item = getItemAt(i);
// We do not need this mapping for disappearing items.
mIndexToItemMap.remove(mLayoutOutputsIds[i]);
if (item.getComponent() != null && item.getComponent().hasChildLithoViews()) {
mCanMountIncrementallyMountItems.remove(mLayoutOutputsIds[i]);
}
// Likewise we no longer need host mapping for disappearing items.
if (isHostSpec(item.getComponent())) {
mHostsByMarker.removeAt(mHostsByMarker.indexOfValue((ComponentHost) item.getContent()));
}
}
}
private void startUnmountDisappearingItem(MountItem item, int index) {
final TransitionId transitionId = item.getTransitionId();
OutputUnitsAffinityGroup<MountItem> disappearingGroup =
mDisappearingMountItems.get(transitionId);
if (disappearingGroup == null) {
disappearingGroup = new OutputUnitsAffinityGroup<>();
mDisappearingMountItems.put(transitionId, disappearingGroup);
}
final @OutputUnitType int type =
LayoutStateOutputIdCalculator.getTypeFromId(mLayoutOutputsIds[index]);
disappearingGroup.add(type, item);
final ComponentHost host = item.getHost();
host.startUnmountDisappearingItem(index, item);
}
private BitSet calculateSkipMounting(LayoutState layoutState) {
if (!ComponentsConfiguration.createPhantomLayoutOutputsForTransitions) {
return sEmptyBitSet;
}
final BitSet skipMounting = new BitSet();
for (int index = layoutState.getMountableOutputCount() - 1; index >= 0; index--) {
if (shouldSkipMounting(layoutState, index)) {
skipMounting.set(index);
}
}
return skipMounting;
}
private boolean shouldSkipMounting(LayoutState layoutState, int index) {
if (!ComponentsConfiguration.createPhantomLayoutOutputsForTransitions) {
return false;
}
final LayoutOutput layoutOutput = layoutState.getMountableOutputAt(index);
final boolean isPhantom = (layoutOutput.getFlags() & MountItem.LAYOUT_FLAG_PHANTOM) != 0;
final boolean isAnimating = mAnimatingTransitionIds.contains(layoutOutput.getTransitionId());
return isPhantom && !isAnimating;
}
/**
* Go over all the mounted items from the leaves to the root and unmount only the items that are
* not present in the new LayoutOutputs. If an item is still present but in a new position move
* the item inside its host. The condition where an item changed host doesn't need any special
* treatment here since we mark them as removed and re-added when calculating the new
* LayoutOutputs
*/
private PrepareMountStats unmountOrMoveOldItems(
LayoutState newLayoutState, BitSet newSkipMounting, List<Integer> disappearingItems) {
mPrepareMountStats.reset();
if (mLayoutOutputsIds == null) {
return mPrepareMountStats;
}
int disappearingItemsPointer = 0;
// Traversing from the beginning since mLayoutOutputsIds unmounting won't remove entries there
// but only from mIndexToItemMap. If an host changes we're going to unmount it and recursively
// all its mounted children.
for (int i = 0; i < mLayoutOutputsIds.length; i++) {
final LayoutOutput newLayoutOutput = newLayoutState.getLayoutOutput(mLayoutOutputsIds[i]);
final int newPosition =
newLayoutOutput == null || newSkipMounting.get(newLayoutOutput.getIndex())
? -1
: newLayoutOutput.getIndex();
final MountItem oldItem = getItemAt(i);
// Just skip disappearing items here
if (disappearingItems.size() > disappearingItemsPointer
&& disappearingItems.get(disappearingItemsPointer) == i) {
// Updating i to the index of the last member of the disappearing subtree, so the whole
// subtree will be skipped, as it's been dealt with at extractDisappearingItems()
i = disappearingItems.get(disappearingItemsPointer + 1);
disappearingItemsPointer += 2;
continue;
}
if (newPosition == -1) {
unmountItem(i, mHostsByMarker);
mPrepareMountStats.unmountedCount++;
} else {
final long newHostMarker =
getActualHostMarker(newLayoutOutput, newLayoutState, newSkipMounting);
if (oldItem == null) {
// This was previously unmounted.
mPrepareMountStats.unmountedCount++;
} else if (oldItem.getHost() != mHostsByMarker.get(newHostMarker)) {
// If the id is the same but the parent host is different we simply unmount the item and
// re-mount it later. If the item to unmount is a ComponentHost, all the children will be
// recursively unmounted.
unmountItem(i, mHostsByMarker);
mPrepareMountStats.unmountedCount++;
} else if (newPosition != i) {
// If a MountItem for this id exists and the hostMarker has not changed but its position
// in the outputs array has changed we need to update the position in the Host to ensure
// the z-ordering.
oldItem.getHost().moveItem(oldItem, i, newPosition);
mPrepareMountStats.movedCount++;
} else {
mPrepareMountStats.unchangedCount++;
}
}
}
return mPrepareMountStats;
}
private void updateMountedContent(
MountItem item,
LayoutOutput layoutOutput,
Component previousComponent) {
final Component newComponent = layoutOutput.getComponent();
if (isHostSpec(newComponent)) {
return;
}
final Object previousContent = item.getContent();
// Call unmount and mount in sequence to make sure all the the resources are correctly
// de-allocated. It's possible for previousContent to equal null - when the root is
// interactive we create a LayoutOutput without content in order to set up click handling.
previousComponent.unmount(
getContextForComponent(previousComponent), previousContent);
newComponent.mount(getContextForComponent(newComponent), previousContent);
}
private void mountLayoutOutput(int index, LayoutOutput layoutOutput, LayoutState layoutState) {
// 0. Make sure we really need to mount this LayoutOutput
if (mSkipMounting.get(index)) {
return;
}
// 1. Resolve the correct host to mount our content to.
final long startTime = System.nanoTime();
final long hostMarker = getActualHostMarker(layoutOutput, layoutState, mSkipMounting);
ComponentHost host = mHostsByMarker.get(hostMarker);
if (host == null) {
// Host has not yet been mounted - mount it now.
final int hostMountIndex = layoutState.getLayoutOutputPositionForId(hostMarker);
final LayoutOutput hostLayoutOutput = layoutState.getMountableOutputAt(hostMountIndex);
mountLayoutOutput(hostMountIndex, hostLayoutOutput, layoutState);
host = mHostsByMarker.get(hostMarker);
}
// 2. Generate the component's mount state (this might also be a ComponentHost View).
final Component component = layoutOutput.getComponent();
if (component == null) {
throw new RuntimeException("Trying to mount a LayoutOutput with a null Component.");
}
final Object content =
ComponentsPools.acquireMountContent(mContext.getAndroidContext(), component);
final ComponentContext context = getContextForComponent(component);
component.mount(
context,
content);
// 3. If it's a ComponentHost, add the mounted View to the list of Hosts.
if (isHostSpec(component)) {
ComponentHost componentHost = (ComponentHost) content;
componentHost.setParentHostMarker(hostMarker);
registerHost(layoutOutput.getId(), componentHost);
}
// 4. Mount the content into the selected host.
final MountItem item = mountContent(index, component, content, host, layoutOutput);
// 5. Notify the component that mounting has completed
component.bind(context, content);
item.setIsBound(true);
// 6. Apply the bounds to the Mount content now. It's important to do so after bind as calling
// bind might have triggered a layout request within a View.
getActualBounds(layoutOutput, layoutState, mSkipMounting, sTempRect);
applyBoundsToMountContent(
item.getContent(),
sTempRect.left,
sTempRect.top,
sTempRect.right,
sTempRect.bottom,
true /* force */);
// 6. Update the mount stats
if (mMountStats.isLoggingEnabled) {
mMountStats.mountTimes.add((System.nanoTime() - startTime) / NS_IN_MS);
mMountStats.mountedNames.add(component.getSimpleName());
mMountStats.mountedCount++;
mMountStats.extras.add(
LogTreePopulator.getAnnotationBundleFromLogger(component, context.getLogger()));
}
}
// The content might be null because it's the LayoutSpec for the root host
// (the very first LayoutOutput).
private MountItem mountContent(
int index,
Component component,
Object content,
ComponentHost host,
LayoutOutput layoutOutput) {
final MountItem item = new MountItem(component, host, content, layoutOutput);
// Create and keep a MountItem even for the layoutSpec with null content
// that sets the root host interactions.
mIndexToItemMap.put(mLayoutOutputsIds[index], item);
if (component.hasChildLithoViews()) {
mCanMountIncrementallyMountItems.put(mLayoutOutputsIds[index], item);
}
layoutOutput.getMountBounds(sTempRect);
host.mount(index, item, sTempRect);
setViewAttributes(item);
return item;
}
private static void applyBoundsToMountContent(
Object content,
int left,
int top,
int right,
int bottom,
boolean force) {
assertMainThread();
if (content instanceof View) {
BoundsHelper.applyBoundsToView((View) content, left, top, right, bottom, force);
} else if (content instanceof Drawable) {
((Drawable) content).setBounds(left, top, right, bottom);
} else {
throw new IllegalStateException("Unsupported mounted content " + content);
}
}
private static boolean canMountIncrementally(Component component) {
return component.hasChildLithoViews();
}
/**
* @return an id if a host that should be used for a given LayoutOutput, taking into account that
* some of nodes on LayoutOutput tree may not be mounted (e.g. "phantom" LayoutOutputs)
*/
private static long getActualHostMarker(
LayoutOutput layoutOutput, LayoutState layoutState, BitSet skipMounting) {
if (skipMounting.get(layoutOutput.getIndex())) {
return -1;
}
long hostMarker;
do {
hostMarker = layoutOutput.getHostMarker();
layoutOutput = layoutState.getLayoutOutput(hostMarker);
if (layoutOutput == null) {
// We got to the root LayoutOutput without finding a host that should be used
return -1;
}
} while (skipMounting.get(layoutOutput.getIndex()));
return hostMarker;
}
/** @return bounds for a given LayoutOutput within its actual host, {@see getActualHostMarker} */
private static void getActualBounds(
LayoutOutput layoutOutput, LayoutState layoutState, BitSet skipMounting, Rect outRect) {
final long actualHostMarker = getActualHostMarker(layoutOutput, layoutState, skipMounting);
layoutOutput.getMountBounds(outRect);
long hostMarker = layoutOutput.getHostMarker();
while (hostMarker != actualHostMarker) {
final LayoutOutput ancestor = layoutState.getLayoutOutput(hostMarker);
ancestor.getMountBounds(sTempRect2);
outRect.offset(sTempRect2.left, sTempRect2.top);
hostMarker = ancestor.getHostMarker();
}
}
private static void setViewAttributes(MountItem item) {
final Component component = item.getComponent();
if (!isMountViewSpec(component)) {
return;
}
final View view = (View) item.getContent();
final NodeInfo nodeInfo = item.getNodeInfo();
if (nodeInfo != null) {
setClickHandler(nodeInfo.getClickHandler(), view);
setLongClickHandler(nodeInfo.getLongClickHandler(), view);
setFocusChangeHandler(nodeInfo.getFocusChangeHandler(), view);
setTouchHandler(nodeInfo.getTouchHandler(), view);
setInterceptTouchHandler(nodeInfo.getInterceptTouchHandler(), view);
setAccessibilityDelegate(view, nodeInfo);
setViewTag(view, nodeInfo.getViewTag());
setViewTags(view, nodeInfo.getViewTags());
setShadowElevation(view, nodeInfo.getShadowElevation());
setOutlineProvider(view, nodeInfo.getOutlineProvider());
setClipToOutline(view, nodeInfo.getClipToOutline());
setClipChildren(view, nodeInfo);
setContentDescription(view, nodeInfo.getContentDescription());
setFocusable(view, nodeInfo.getFocusState());
setClickable(view, nodeInfo.getClickableState());
setEnabled(view, nodeInfo.getEnabledState());
setSelected(view, nodeInfo.getSelectedState());
setScale(view, nodeInfo);
setAlpha(view, nodeInfo);
setRotation(view, nodeInfo);
setRotationX(view, nodeInfo);
setRotationY(view, nodeInfo);
}
setImportantForAccessibility(view, item.getImportantForAccessibility());
final ViewNodeInfo viewNodeInfo = item.getViewNodeInfo();
if (viewNodeInfo != null) {
setViewStateListAnimator(view, viewNodeInfo);
if (!isHostSpec(component)) {
// Set view background, if applicable. Do this before padding
// as it otherwise overrides the padding.
setViewBackground(view, viewNodeInfo);
setViewPadding(view, viewNodeInfo);
setViewForeground(view, viewNodeInfo);
setViewLayoutDirection(view, viewNodeInfo);
}
}
}
private static void maybeUnsetViewAttributes(MountItem item) {
final Component component = item.getComponent();
if (!isMountViewSpec(component)) {
return;
}
unsetViewAttributes(item, isHostSpec(component));
}
private static void unsetViewAttributes(MountItem item, boolean isHostView) {
final View view = (View) item.getContent();
final NodeInfo nodeInfo = item.getNodeInfo();
if (nodeInfo != null) {
if (nodeInfo.getClickHandler() != null) {
unsetClickHandler(view);
}
if (nodeInfo.getLongClickHandler() != null) {
unsetLongClickHandler(view);
}
if (nodeInfo.getFocusChangeHandler() != null) {
unsetFocusChangeHandler(view);
}
if (nodeInfo.getTouchHandler() != null) {
unsetTouchHandler(view);
}
if (nodeInfo.getInterceptTouchHandler() != null) {
unsetInterceptTouchEventHandler(view);
}
unsetViewTag(view);
unsetViewTags(view, nodeInfo.getViewTags());
unsetShadowElevation(view, nodeInfo.getShadowElevation());
unsetOutlineProvider(view, nodeInfo.getOutlineProvider());
unsetClipToOutline(view, nodeInfo.getClipToOutline());
unsetClipChildren(view, nodeInfo.getClipChildren());
if (!TextUtils.isEmpty(nodeInfo.getContentDescription())) {
unsetContentDescription(view);
}
unsetScale(view, nodeInfo);
unsetAlpha(view, nodeInfo);
unsetRotation(view, nodeInfo);
unsetRotationX(view, nodeInfo);
unsetRotationY(view, nodeInfo);
}
view.setClickable(item.isViewClickable());
view.setLongClickable(item.isViewLongClickable());
unsetFocusable(view, item);
unsetEnabled(view, item);
unsetSelected(view, item);
if (item.getImportantForAccessibility() != IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
unsetImportantForAccessibility(view);
}
unsetAccessibilityDelegate(view);
final ViewNodeInfo viewNodeInfo = item.getViewNodeInfo();
if (viewNodeInfo != null) {
unsetViewStateListAnimator(view, viewNodeInfo);
// Host view doesn't set its own padding, but gets absolute positions for inner content from
// Yoga. Also bg/fg is used as separate drawables instead of using View's bg/fg attribute.
if (!isHostView) {
unsetViewPadding(view, viewNodeInfo);
unsetViewBackground(view, viewNodeInfo);
unsetViewForeground(view, viewNodeInfo);
unsetViewLayoutDirection(view, viewNodeInfo);
}
}
}
/**
* Store a {@link NodeInfo} as a tag in {@code view}. {@link LithoView} contains the logic for
* setting/unsetting it whenever accessibility is enabled/disabled
*
* <p>For non {@link ComponentHost}s this is only done if any {@link EventHandler}s for
* accessibility events have been implemented, we want to preserve the original behaviour since
* {@code view} might have had a default delegate.
*/
private static void setAccessibilityDelegate(View view, NodeInfo nodeInfo) {
if (!(view instanceof ComponentHost) && !nodeInfo.needsAccessibilityDelegate()) {
return;
}
view.setTag(
R.id.component_node_info,
nodeInfo);
}
private static void unsetAccessibilityDelegate(View view) {
if (!(view instanceof ComponentHost)
&& view.getTag(R.id.component_node_info) == null) {
return;
}
view.setTag(R.id.component_node_info, null);
if (!(view instanceof ComponentHost)) {
ViewCompat.setAccessibilityDelegate(view, null);
}
}
/**
* Installs the click listeners that will dispatch the click handler
* defined in the component's props. Unconditionally set the clickable
* flag on the view.
*/
private static void setClickHandler(EventHandler<ClickEvent> clickHandler, View view) {
if (clickHandler == null) {
return;
}
ComponentClickListener listener = getComponentClickListener(view);
if (listener == null) {
listener = new ComponentClickListener();
setComponentClickListener(view, listener);
}
listener.setEventHandler(clickHandler);
view.setClickable(true);
}
private static void unsetClickHandler(View view) {
final ComponentClickListener listener = getComponentClickListener(view);
if (listener != null) {
listener.setEventHandler(null);
}
}
static ComponentClickListener getComponentClickListener(View v) {
if (v instanceof ComponentHost) {
return ((ComponentHost) v).getComponentClickListener();
} else {
return (ComponentClickListener) v.getTag(R.id.component_click_listener);
}
}
static void setComponentClickListener(View v, ComponentClickListener listener) {
if (v instanceof ComponentHost) {
((ComponentHost) v).setComponentClickListener(listener);
} else {
v.setOnClickListener(listener);
v.setTag(R.id.component_click_listener, listener);
}
}
/**
* Installs the long click listeners that will dispatch the click handler
* defined in the component's props. Unconditionally set the clickable
* flag on the view.
*/
private static void setLongClickHandler(
EventHandler<LongClickEvent> longClickHandler, View view) {
if (longClickHandler != null) {
ComponentLongClickListener listener = getComponentLongClickListener(view);
if (listener == null) {
listener = new ComponentLongClickListener();
setComponentLongClickListener(view, listener);
}
listener.setEventHandler(longClickHandler);
view.setLongClickable(true);
}
}
private static void unsetLongClickHandler(View view) {
final ComponentLongClickListener listener = getComponentLongClickListener(view);
if (listener != null) {
listener.setEventHandler(null);
}
}
static ComponentLongClickListener getComponentLongClickListener(View v) {
if (v instanceof ComponentHost) {
return ((ComponentHost) v).getComponentLongClickListener();
} else {
return (ComponentLongClickListener) v.getTag(R.id.component_long_click_listener);
}
}
static void setComponentLongClickListener(View v, ComponentLongClickListener listener) {
if (v instanceof ComponentHost) {
((ComponentHost) v).setComponentLongClickListener(listener);
} else {
v.setOnLongClickListener(listener);
v.setTag(R.id.component_long_click_listener, listener);
}
}
/**
* Installs the on focus change listeners that will dispatch the click handler
* defined in the component's props. Unconditionally set the clickable
* flag on the view.
*/
private static void setFocusChangeHandler(
EventHandler<FocusChangedEvent> focusChangeHandler, View view) {
if (focusChangeHandler == null) {
return;
}
ComponentFocusChangeListener listener = getComponentFocusChangeListener(view);
if (listener == null) {
listener = new ComponentFocusChangeListener();
setComponentFocusChangeListener(view, listener);
}
listener.setEventHandler(focusChangeHandler);
}
private static void unsetFocusChangeHandler(View view) {
final ComponentFocusChangeListener listener = getComponentFocusChangeListener(view);
if (listener != null) {
listener.setEventHandler(null);
}
}
static ComponentFocusChangeListener getComponentFocusChangeListener(View v) {
if (v instanceof ComponentHost) {
return ((ComponentHost) v).getComponentFocusChangeListener();
} else {
return (ComponentFocusChangeListener) v.getTag(R.id.component_focus_change_listener);
}
}
static void setComponentFocusChangeListener(View v, ComponentFocusChangeListener listener) {
if (v instanceof ComponentHost) {
((ComponentHost) v).setComponentFocusChangeListener(listener);
} else {
v.setOnFocusChangeListener(listener);
v.setTag(R.id.component_focus_change_listener, listener);
}
}
/**
* Installs the touch listeners that will dispatch the touch handler
* defined in the component's props.
*/
private static void setTouchHandler(EventHandler<TouchEvent> touchHandler, View view) {
if (touchHandler != null) {
ComponentTouchListener listener = getComponentTouchListener(view);
if (listener == null) {
listener = new ComponentTouchListener();
setComponentTouchListener(view, listener);
}
listener.setEventHandler(touchHandler);
}
}
private static void unsetTouchHandler(View view) {
final ComponentTouchListener listener = getComponentTouchListener(view);
if (listener != null) {
listener.setEventHandler(null);
}
}
/**
* Sets the intercept touch handler defined in the component's props.
*/
private static void setInterceptTouchHandler(
EventHandler<InterceptTouchEvent> interceptTouchHandler,
View view) {
if (interceptTouchHandler == null) {
return;
}
if (view instanceof ComponentHost) {
((ComponentHost) view).setInterceptTouchEventHandler(interceptTouchHandler);
}
}
private static void unsetInterceptTouchEventHandler(View view) {
if (view instanceof ComponentHost) {
((ComponentHost) view).setInterceptTouchEventHandler(null);
}
}
static ComponentTouchListener getComponentTouchListener(View v) {
if (v instanceof ComponentHost) {
return ((ComponentHost) v).getComponentTouchListener();
} else {
return (ComponentTouchListener) v.getTag(R.id.component_touch_listener);
}
}
static void setComponentTouchListener(View v, ComponentTouchListener listener) {
if (v instanceof ComponentHost) {
((ComponentHost) v).setComponentTouchListener(listener);
} else {
v.setOnTouchListener(listener);
v.setTag(R.id.component_touch_listener, listener);
}
}
private static void setViewTag(View view, Object viewTag) {
if (view instanceof ComponentHost) {
final ComponentHost host = (ComponentHost) view;
host.setViewTag(viewTag);
} else {
view.setTag(viewTag);
}
}
private static void setViewTags(View view, SparseArray<Object> viewTags) {
if (viewTags == null) {
return;
}
if (view instanceof ComponentHost) {
final ComponentHost host = (ComponentHost) view;
host.setViewTags(viewTags);
} else {
for (int i = 0, size = viewTags.size(); i < size; i++) {
view.setTag(viewTags.keyAt(i), viewTags.valueAt(i));
}
}
}
private static void unsetViewTag(View view) {
if (view instanceof ComponentHost) {
final ComponentHost host = (ComponentHost) view;
host.setViewTag(null);
} else {
view.setTag(null);
}
}
private static void unsetViewTags(View view, SparseArray<Object> viewTags) {
if (view instanceof ComponentHost) {
final ComponentHost host = (ComponentHost) view;
host.setViewTags(null);
} else {
if (viewTags != null) {
for (int i = 0, size = viewTags.size(); i < size; i++) {
view.setTag(viewTags.keyAt(i), null);
}
}
}
}
private static void setShadowElevation(View view, float shadowElevation) {
if (shadowElevation != 0) {
ViewCompat.setElevation(view, shadowElevation);
}
}
private static void unsetShadowElevation(View view, float shadowElevation) {
if (shadowElevation != 0) {
ViewCompat.setElevation(view, 0);
}
}
private static void setOutlineProvider(View view, ViewOutlineProvider outlineProvider) {
if (outlineProvider != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.setOutlineProvider(outlineProvider);
}
}
private static void unsetOutlineProvider(View view, ViewOutlineProvider outlineProvider) {
if (outlineProvider != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.setOutlineProvider(ViewOutlineProvider.BACKGROUND);
}
}
private static void setClipToOutline(View view, boolean clipToOutline) {
if (clipToOutline && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.setClipToOutline(clipToOutline);
}
}
private static void unsetClipToOutline(View view, boolean clipToOutline) {
if (clipToOutline && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.setClipToOutline(false);
}
}
private static void setClipChildren(View view, NodeInfo nodeInfo) {
if (nodeInfo.isClipChildrenSet() && view instanceof ViewGroup) {
((ViewGroup) view).setClipChildren(nodeInfo.getClipChildren());
}
}
private static void unsetClipChildren(View view, boolean clipChildren) {
if (!clipChildren && view instanceof ViewGroup) {
// Default value for clipChildren is 'true'.
// If this ViewGroup had clipChildren set to 'false' before mounting we would reset this
// property here on recycling.
((ViewGroup) view).setClipChildren(true);
}
}
private static void setContentDescription(View view, CharSequence contentDescription) {
if (TextUtils.isEmpty(contentDescription)) {
return;
}
view.setContentDescription(contentDescription);
}
private static void unsetContentDescription(View view) {
view.setContentDescription(null);
}
private static void setImportantForAccessibility(View view, int importantForAccessibility) {
if (importantForAccessibility == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
return;
}
ViewCompat.setImportantForAccessibility(view, importantForAccessibility);
}
private static void unsetImportantForAccessibility(View view) {
ViewCompat.setImportantForAccessibility(view, IMPORTANT_FOR_ACCESSIBILITY_AUTO);
}
private static void setFocusable(View view, @NodeInfo.FocusState int focusState) {
if (focusState == NodeInfo.FOCUS_SET_TRUE) {
view.setFocusable(true);
} else if (focusState == NodeInfo.FOCUS_SET_FALSE) {
view.setFocusable(false);
}
}
private static void unsetFocusable(View view, MountItem mountItem) {
view.setFocusable(mountItem.isViewFocusable());
}
private static void setClickable(View view, @NodeInfo.FocusState int clickableState) {
if (clickableState == NodeInfo.CLICKABLE_SET_TRUE) {
view.setClickable(true);
} else if (clickableState == NodeInfo.CLICKABLE_SET_FALSE) {
view.setClickable(false);
}
}
private static void setEnabled(View view, @NodeInfo.EnabledState int enabledState) {
if (enabledState == NodeInfo.ENABLED_SET_TRUE) {
view.setEnabled(true);
} else if (enabledState == NodeInfo.ENABLED_SET_FALSE) {
view.setEnabled(false);
}
}
private static void unsetEnabled(View view, MountItem mountItem) {
view.setEnabled(mountItem.isViewEnabled());
}
private static void setSelected(View view, @NodeInfo.SelectedState int selectedState) {
if (selectedState == NodeInfo.SELECTED_SET_TRUE) {
view.setSelected(true);
} else if (selectedState == NodeInfo.SELECTED_SET_FALSE) {
view.setSelected(false);
}
}
private static void unsetSelected(View view, MountItem mountItem) {
view.setSelected(mountItem.isViewSelected());
}
private static void setScale(View view, NodeInfo nodeInfo) {
if (Build.VERSION.SDK_INT >= 11) {
if (nodeInfo.isScaleSet()) {
final float scale = nodeInfo.getScale();
view.setScaleX(scale);
view.setScaleY(scale);
}
}
}
private static void unsetScale(View view, NodeInfo nodeInfo) {
if (Build.VERSION.SDK_INT >= 11) {
if (nodeInfo.isScaleSet()) {
if (view.getScaleX() != 1) {
view.setScaleX(1);
}
if (view.getScaleY() != 1) {
view.setScaleY(1);
}
}
}
}
private static void setAlpha(View view, NodeInfo nodeInfo) {
if (Build.VERSION.SDK_INT >= 11) {
if (nodeInfo.isAlphaSet()) {
view.setAlpha(nodeInfo.getAlpha());
}
}
}
private static void unsetAlpha(View view, NodeInfo nodeInfo) {
if (Build.VERSION.SDK_INT >= 11) {
if (nodeInfo.isAlphaSet() && view.getAlpha() != 1) {
view.setAlpha(1);
}
}
}
private static void setRotation(View view, NodeInfo nodeInfo) {
if (Build.VERSION.SDK_INT >= 11) {
if (nodeInfo.isRotationSet()) {
view.setRotation(nodeInfo.getRotation());
}
}
}
private static void unsetRotation(View view, NodeInfo nodeInfo) {
if (Build.VERSION.SDK_INT >= 11) {
if (nodeInfo.isRotationSet() && view.getRotation() != 0) {
view.setRotation(0);
}
}
}
private static void setRotationX(View view, NodeInfo nodeInfo) {
if (Build.VERSION.SDK_INT >= 11) {
if (nodeInfo.isRotationXSet()) {
view.setRotationX(nodeInfo.getRotationX());
}
}
}
private static void unsetRotationX(View view, NodeInfo nodeInfo) {
if (Build.VERSION.SDK_INT >= 11) {
if (nodeInfo.isRotationXSet() && view.getRotationX() != 0) {
view.setRotationX(0);
}
}
}
private static void setRotationY(View view, NodeInfo nodeInfo) {
if (Build.VERSION.SDK_INT >= 11) {
if (nodeInfo.isRotationYSet()) {
view.setRotationY(nodeInfo.getRotationY());
}
}
}
private static void unsetRotationY(View view, NodeInfo nodeInfo) {
if (Build.VERSION.SDK_INT >= 11) {
if (nodeInfo.isRotationYSet() && view.getRotationY() != 0) {
view.setRotationY(0);
}
}
}
private static void setViewPadding(View view, ViewNodeInfo viewNodeInfo) {
if (!viewNodeInfo.hasPadding()) {
return;
}
view.setPadding(
viewNodeInfo.getPaddingLeft(),
viewNodeInfo.getPaddingTop(),
viewNodeInfo.getPaddingRight(),
viewNodeInfo.getPaddingBottom());
}
private static void unsetViewPadding(View view, ViewNodeInfo viewNodeInfo) {
if (!viewNodeInfo.hasPadding()) {
return;
}
view.setPadding(0, 0, 0, 0);
}
private static void setViewBackground(View view, ViewNodeInfo viewNodeInfo) {
final ComparableDrawable background = viewNodeInfo.getBackground();
if (background != null) {
setBackgroundCompat(view, background);
}
}
private static void unsetViewBackground(View view, ViewNodeInfo viewNodeInfo) {
final ComparableDrawable background = viewNodeInfo.getBackground();
final Drawable drawable = view.getBackground();
if (background != null) {
setBackgroundCompat(view, null);
}
}
@SuppressWarnings("deprecation")
private static void setBackgroundCompat(View view, Drawable drawable) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(drawable);
} else {
view.setBackground(drawable);
}
}
private static void setViewForeground(View view, ViewNodeInfo viewNodeInfo) {
final Drawable foreground = viewNodeInfo.getForeground();
if (foreground != null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
throw new IllegalStateException("MountState has a ViewNodeInfo with foreground however " +
"the current Android version doesn't support foreground on Views");
}
view.setForeground(foreground);
}
}
private static void unsetViewForeground(View view, ViewNodeInfo viewNodeInfo) {
final Drawable foreground = viewNodeInfo.getForeground();
if (foreground != null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
throw new IllegalStateException("MountState has a ViewNodeInfo with foreground however " +
"the current Android version doesn't support foreground on Views");
}
view.setForeground(null);
}
}
private static void setViewLayoutDirection(View view, ViewNodeInfo viewNodeInfo) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return;
}
final int viewLayoutDirection;
switch (viewNodeInfo.getLayoutDirection()) {
case LTR:
viewLayoutDirection = View.LAYOUT_DIRECTION_LTR;
break;
case RTL:
viewLayoutDirection = View.LAYOUT_DIRECTION_RTL;
break;
default:
viewLayoutDirection = View.LAYOUT_DIRECTION_INHERIT;
}
view.setLayoutDirection(viewLayoutDirection);
}
private static void unsetViewLayoutDirection(View view, ViewNodeInfo viewNodeInfo) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return;
}
view.setLayoutDirection(View.LAYOUT_DIRECTION_INHERIT);
}
private static void setViewStateListAnimator(View view, ViewNodeInfo viewNodeInfo) {
StateListAnimator stateListAnimator = viewNodeInfo.getStateListAnimator();
final int stateListAnimatorRes = viewNodeInfo.getStateListAnimatorRes();
if (stateListAnimator == null && stateListAnimatorRes == 0) {
return;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
throw new IllegalStateException(
"MountState has a ViewNodeInfo with stateListAnimator, "
+ "however the current Android version doesn't support stateListAnimator on Views");
}
if (stateListAnimator == null) {
stateListAnimator =
AnimatorInflater.loadStateListAnimator(view.getContext(), stateListAnimatorRes);
}
view.setStateListAnimator(stateListAnimator);
}
private static void unsetViewStateListAnimator(View view, ViewNodeInfo viewNodeInfo) {
if (viewNodeInfo.getStateListAnimator() == null
&& viewNodeInfo.getStateListAnimatorRes() == 0) {
return;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
throw new IllegalStateException(
"MountState has a ViewNodeInfo with stateListAnimator, "
+ "however the current Android version doesn't support stateListAnimator on Views");
}
view.setStateListAnimator(null);
}
private static void mountItemIncrementally(
MountItem item, Rect itemBounds, Rect localVisibleRect, boolean processVisibilityOutputs) {
final Component component = item.getComponent();
if (!isMountViewSpec(component)) {
return;
}
// We can't just use the bounds of the View since we need the bounds relative to the
// hosting LithoView (which is what the localVisibleRect is measured relative to).
final View view = (View) item.getContent();
mountViewIncrementally(view, processVisibilityOutputs);
}
private static void mountViewIncrementally(View view, boolean processVisibilityOutputs) {
assertMainThread();
if (view instanceof LithoView) {
final LithoView lithoView = (LithoView) view;
if (lithoView.isIncrementalMountEnabled()) {
if (!processVisibilityOutputs) {
lithoView.performIncrementalMount(
new Rect(0, 0, view.getWidth(), view.getHeight()), false);
} else {
lithoView.performIncrementalMount();
}
}
} else if (view instanceof ViewGroup) {
final ViewGroup viewGroup = (ViewGroup) view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
final View childView = viewGroup.getChildAt(i);
mountViewIncrementally(childView, processVisibilityOutputs);
}
}
}
private void unmountDisappearingItemChild(ComponentContext context, MountItem item) {
maybeRemoveAnimatingMountContent(item.getTransitionId());
final Object content = item.getContent();
// Recursively unmount mounted children items.
if (content instanceof ComponentHost) {
final ComponentHost host = (ComponentHost) content;
for (int i = host.getMountItemCount() - 1; i >= 0; i--) {
final MountItem mountItem = host.getMountItemAt(i);
unmountDisappearingItemChild(context, mountItem);
}
if (host.getMountItemCount() > 0) {
throw new IllegalStateException("Recursively unmounting items from a ComponentHost, left" +
" some items behind maybe because not tracked by its MountState");
}
}
final ComponentHost host = item.getHost();
host.unmount(item);
maybeUnsetViewAttributes(item);
unbindAndUnmountLifecycle(item);
if (item.getComponent().hasChildLithoViews()) {
final int index = mCanMountIncrementallyMountItems.indexOfValue(item);
if (index > 0) {
mCanMountIncrementallyMountItems.removeAt(index);
}
}
item.releaseMountContent(context.getAndroidContext());
}
void unmountAllItems() {
assertMainThread();
if (mLayoutOutputsIds == null) {
return;
}
for (int i = mLayoutOutputsIds.length - 1; i >= 0; i--) {
unmountItem(i, mHostsByMarker);
}
mPreviousLocalVisibleRect.setEmpty();
mNeedsRemount = true;
}
private void unmountItem(
int index,
LongSparseArray<ComponentHost> hostsByMarker) {
final MountItem item = getItemAt(index);
final long startTime = System.nanoTime();
// Already has been unmounted.
if (item == null) {
return;
}
// The root host item should never be unmounted as it's a reference
// to the top-level LithoView.
if (mLayoutOutputsIds[index] == ROOT_HOST_ID) {
unsetViewAttributes(item, true);
return;
}
final Object content = item.getContent();
// Recursively unmount mounted children items.
// This is the case when mountDiffing is enabled and unmountOrMoveOldItems() has a matching
// sub tree. However, traversing the tree bottom-up, it needs to unmount a node holding that
// sub tree, that will still have mounted items. (Different sequence number on LayoutOutput id)
if ((content instanceof ComponentHost) && !(content instanceof LithoView)) {
final ComponentHost host = (ComponentHost) content;
// Concurrently remove items therefore traverse backwards.
for (int i = host.getMountItemCount() - 1; i >= 0; i--) {
final MountItem mountItem = host.getMountItemAt(i);
final long layoutOutputId = mIndexToItemMap.keyAt(mIndexToItemMap.indexOfValue(mountItem));
for (int mountIndex = mLayoutOutputsIds.length - 1; mountIndex >= 0; mountIndex--) {
if (mLayoutOutputsIds[mountIndex] == layoutOutputId) {
unmountItem(mountIndex, hostsByMarker);
break;
}
}
}
if (host.getMountItemCount() > 0) {
throw new IllegalStateException("Recursively unmounting items from a ComponentHost, left" +
" some items behind maybe because not tracked by its MountState");
}
}
/*
* The mounted content might contain other LithoViews which are not reachable from
* this MountState. If that content contains other LithoViews, we need to unmount them as well,
* so that their contents are recycled and reused next time.
*/
if (content instanceof HasLithoViewChildren) {
final ArrayList<LithoView> lithoViews = new ArrayList<>();
((HasLithoViewChildren) content).obtainLithoViewChildren(lithoViews);
for (int i = lithoViews.size() - 1; i >= 0; i--) {
final LithoView lithoView = lithoViews.get(i);
lithoView.unmountAllItems();
}
}
final ComponentHost host = item.getHost();
host.unmount(index, item);
maybeUnsetViewAttributes(item);
final Component component = item.getComponent();
if (isHostSpec(component)) {
final ComponentHost componentHost = (ComponentHost) content;
hostsByMarker.removeAt(hostsByMarker.indexOfValue(componentHost));
removeDisappearingMountContentFromComponentHost(componentHost);
}
unbindAndUnmountLifecycle(item);
final long layoutOutputId = mLayoutOutputsIds[index];
mIndexToItemMap.remove(layoutOutputId);
if (item.hasTransitionId()) {
final @OutputUnitType int type = LayoutStateOutputIdCalculator.getTypeFromId(layoutOutputId);
maybeRemoveAnimatingMountContent(item.getTransitionId(), type);
}
if (component.hasChildLithoViews()) {
mCanMountIncrementallyMountItems.delete(mLayoutOutputsIds[index]);
}
final String rootComponentName =
mLastMountedLayoutState == null
? "null_layout"
: mLastMountedLayoutState.mRootComponentName;
if (!(isHostSpec(component)
&& ComponentHostRecycleUtil.shouldSkipRecyclingComponentHost(index, rootComponentName))) {
item.releaseMountContent(mContext.getAndroidContext());
}
if (mMountStats.isLoggingEnabled) {
mMountStats.unmountedTimes.add((System.nanoTime() - startTime) / NS_IN_MS);
mMountStats.unmountedNames.add(component.getSimpleName());
mMountStats.unmountedCount++;
}
}
private void unbindAndUnmountLifecycle(
MountItem item) {
final Component component = item.getComponent();
final Object content = item.getContent();
final ComponentContext context = getContextForComponent(component);
// Call the component's unmount() method.
if (item.isBound()) {
component.onUnbind(context, content);
item.setIsBound(false);
}
component.unmount(context, content);
}
private void endUnmountDisappearingItem(OutputUnitsAffinityGroup<MountItem> group) {
maybeRemoveAnimatingMountContent(group.getMostSignificantUnit().getTransitionId());
for (int i = 0, size = group.size(); i < size; i++) {
final MountItem item = group.getAt(i);
// We used to do (item.getContent() instanceof ComponentHost) check here, which didn't
// take
// into consideration MountSpecs that mount a LithoView which would pass the check while
// shouldn't
if (group.typeAt(i) == OutputUnitType.HOST) {
final ComponentHost content = (ComponentHost) item.getContent();
// Unmount descendant items in reverse order.
for (int j = content.getMountItemCount() - 1; j >= 0; j--) {
final MountItem mountItem = content.getMountItemAt(j);
unmountDisappearingItemChild(mContext, mountItem);
}
if (content.getMountItemCount() > 0) {
throw new IllegalStateException(
"Recursively unmounting items from a ComponentHost, left"
+ " some items behind maybe because not tracked by its MountState");
}
}
final ComponentHost host = item.getHost();
host.unmountDisappearingItem(item);
maybeUnsetViewAttributes(item);
unbindAndUnmountLifecycle(item);
if (item.getComponent().hasChildLithoViews()) {
final int index = mCanMountIncrementallyMountItems.indexOfValue(item);
if (index > 0) {
mCanMountIncrementallyMountItems.removeAt(index);
}
}
item.releaseMountContent(mContext.getAndroidContext());
}
}
int getItemCount() {
assertMainThread();
return mLayoutOutputsIds == null ? 0 : mLayoutOutputsIds.length;
}
MountItem getItemAt(int i) {
assertMainThread();
return mIndexToItemMap.get(mLayoutOutputsIds[i]);
}
/**
* Creates and updates transitions for a new LayoutState. The steps are as follows:
*
* <p>1. Disappearing items: Update disappearing mount items that are no longer disappearing (e.g.
* because they came back). This means canceling the animation and cleaning up the corresponding
* ComponentHost.
*
* <p>2. New transitions: Use the transition manager to create new animations.
*
* <p>3. Update locked indices: Based on running/new animations, there are some mount items we
* want to make sure are not unmounted due to incremental mount and being outside of visibility
* bounds.
*/
private void updateTransitions(LayoutState layoutState, ComponentTree componentTree) {
if (!mIsDirty) {
throw new RuntimeException("Should only process transitions on dirty mounts");
}
final boolean isTracing = ComponentsSystrace.isTracing();
if (isTracing) {
String logTag = componentTree.getContext().getLogTag();
if (logTag == null) {
ComponentsSystrace.beginSection("MountState.updateTransitions");
} else {
ComponentsSystrace.beginSection("MountState.updateTransitions:" + logTag);
}
}
try {
// If this is a new component tree but isn't the first time it's been mounted, then we shouldn't
// do any transition animations for changed mount content as it's just being remounted on a
// new LithoView.
final int componentTreeId = layoutState.getComponentTreeId();
if (mLastMountedComponentTreeId != componentTreeId) {
resetAnimationState();
if (!mIsFirstMountOfComponentTree) {
return;
}
}
if (!mDisappearingMountItems.isEmpty()) {
updateDisappearingMountItems(layoutState);
}
if (shouldAnimateTransitions(layoutState)) {
collectAllTransitions(layoutState, componentTree);
if (hasTransitionsToAnimate()) {
createNewTransitions(layoutState, mRootTransition);
}
}
mAnimationLockedIndices = null;
if (!mAnimatingTransitionIds.isEmpty()) {
regenerateAnimationLockedIndices(layoutState);
}
} finally {
if (isTracing) {
ComponentsSystrace.endSection();
}
}
}
private void resetAnimationState() {
if (mTransitionManager == null) {
return;
}
for (OutputUnitsAffinityGroup<MountItem> group : mDisappearingMountItems.values()) {
endUnmountDisappearingItem(group);
}
mDisappearingMountItems.clear();
mAnimatingTransitionIds.clear();
mTransitionManager.reset();
mAnimationLockedIndices = null;
}
private void updateDisappearingMountItems(LayoutState newLayoutState) {
final Map<TransitionId, ?> nextMountedTransitionIds = newLayoutState.getTransitionIdMapping();
for (TransitionId transitionId : nextMountedTransitionIds.keySet()) {
final OutputUnitsAffinityGroup<MountItem> disappearingItem =
mDisappearingMountItems.remove(transitionId);
if (disappearingItem != null) {
endUnmountDisappearingItem(disappearingItem);
}
}
}
private void createNewTransitions(LayoutState newLayoutState, Transition rootTransition) {
prepareTransitionManager(newLayoutState);
mTransitionManager.setupTransitions(mLastMountedLayoutState, newLayoutState, rootTransition);
final Map<TransitionId, ?> nextTransitionIds = newLayoutState.getTransitionIdMapping();
for (TransitionId transitionId : nextTransitionIds.keySet()) {
if (mTransitionManager.isAnimating(transitionId)) {
mAnimatingTransitionIds.add(transitionId);
}
}
}
private void regenerateAnimationLockedIndices(LayoutState newLayoutState) {
final Map<TransitionId, OutputUnitsAffinityGroup<LayoutOutput>> transitionMapping =
newLayoutState.getTransitionIdMapping();
if (transitionMapping != null) {
for (TransitionId transitionId : transitionMapping.keySet()) {
if (!mAnimatingTransitionIds.contains(transitionId)) {
continue;
}
if (mAnimationLockedIndices == null) {
mAnimationLockedIndices = new int[newLayoutState.getMountableOutputCount()];
}
final OutputUnitsAffinityGroup<LayoutOutput> group = transitionMapping.get(transitionId);
for (int j = 0, sz = group.size(); j < sz; j++) {
final LayoutOutput layoutOutput = group.getAt(j);
final int position = newLayoutState.getLayoutOutputPositionForId(layoutOutput.getId());
updateAnimationLockCount(newLayoutState, position, true);
}
}
} else {
mAnimationLockedIndices = null;
}
if (AnimationsDebug.ENABLED) {
AnimationsDebug.debugPrintAnimationLockedIndices(newLayoutState, mAnimationLockedIndices);
}
}
private int findLastDescendantIndex(LayoutState layoutState, int index) {
final LayoutOutput host = layoutState.getMountableOutputAt(index);
final long hostId = host.getId();
for (int i = index + 1, size = layoutState.getMountableOutputCount(); i < size; i++) {
final LayoutOutput layoutOutput = layoutState.getMountableOutputAt(i);
// Walk up the parents looking for the host's id: if we find it, it's a descendant. If we
// reach the root, then it's not a descendant and we can stop.
long curentHostId = layoutOutput.getHostMarker();
while (curentHostId != hostId) {
if (curentHostId == ROOT_HOST_ID) {
return i - 1;
}
final int parentIndex = layoutState.getLayoutOutputPositionForId(curentHostId);
final LayoutOutput parent = layoutState.getMountableOutputAt(parentIndex);
curentHostId = parent.getHostMarker();
}
}
return layoutState.getMountableOutputCount() - 1;
}
/**
* Update the animation locked count for all children and each parent of the animating item.
* Mount items that have a lock count > 0 will not be unmounted during incremental mount.
*/
private void updateAnimationLockCount(LayoutState layoutState, int index, boolean increment) {
// Update children
final int lastDescendantIndex = findLastDescendantIndex(layoutState, index);
for (int i = index; i <= lastDescendantIndex; i++) {
if (increment) {
mAnimationLockedIndices[i]++;
} else {
if (--mAnimationLockedIndices[i] < 0) {
throw new RuntimeException("Decremented animation lock count below 0!");
}
}
}
// Update parents
long hostId = layoutState.getMountableOutputAt(index).getHostMarker();
while (hostId != ROOT_HOST_ID) {
final int hostIndex = layoutState.getLayoutOutputPositionForId(hostId);
if (increment) {
mAnimationLockedIndices[hostIndex]++;
} else {
if (--mAnimationLockedIndices[hostIndex] < 0) {
throw new RuntimeException("Decremented animation lock count below 0!");
}
}
hostId = layoutState.getMountableOutputAt(hostIndex).getHostMarker();
}
}
/**
* @return whether we should animate transitions if we have any when mounting the new LayoutState.
*/
private boolean shouldAnimateTransitions(LayoutState newLayoutState) {
return mIsDirty
&& (mLastMountedComponentTreeId == newLayoutState.getComponentTreeId()
|| mIsFirstMountOfComponentTree);
}
/**
* @return whether we have any transitions to animate for the current mount of the given
* LayoutState
*/
private boolean hasTransitionsToAnimate() {
return mRootTransition != null;
}
@Override
public void onAnimationComplete(TransitionId transitionId) {
final OutputUnitsAffinityGroup<MountItem> disappearingGroup =
mDisappearingMountItems.remove(transitionId);
if (disappearingGroup != null) {
endUnmountDisappearingItem(disappearingGroup);
} else {
if (!mAnimatingTransitionIds.remove(transitionId)) {
if (AnimationsDebug.ENABLED) {
Log.e(
AnimationsDebug.TAG,
"Ending animation for id " + transitionId + " but it wasn't recorded as animating!");
}
}
final OutputUnitsAffinityGroup<LayoutOutput> layoutOutputGroup =
mLastMountedLayoutState.getLayoutOutputsForTransitionId(transitionId);
if (layoutOutputGroup == null) {
// This can happen if the component was unmounted without animation or the transitionId
// was removed from the component.
return;
}
for (int i = 0, size = layoutOutputGroup.size(); i < size; i++) {
final LayoutOutput layoutOutput = layoutOutputGroup.getAt(i);
final int position = layoutOutput.getIndex();
updateAnimationLockCount(mLastMountedLayoutState, position, false);
if (shouldSkipMounting(mLastMountedLayoutState, position)) {
// So this item should not be mounted anymore
// 1. Update the records
mSkipMounting.set(position);
// 2. Unmount the item
unmountItem(position, mHostsByMarker);
// 3. Re-mount all the children of the item
final int lastDescendantIndex =
findLastDescendantIndex(mLastMountedLayoutState, position);
for (int j = position + 1; j <= lastDescendantIndex; j++) {
final LayoutOutput childLayoutOutput = mLastMountedLayoutState.getMountableOutputAt(j);
mountLayoutOutput(j, childLayoutOutput, mLastMountedLayoutState);
}
}
}
if (ComponentsConfiguration.isDebugModeEnabled && mAnimatingTransitionIds.isEmpty()) {
for (int i = 0, size = mAnimationLockedIndices.length; i < size; i++) {
if (mAnimationLockedIndices[i] != 0) {
throw new RuntimeException(
"No running animations but index " + i + " is still animation locked!");
}
}
}
}
}
private static class PrepareMountStats {
private int unmountedCount = 0;
private int movedCount = 0;
private int unchangedCount = 0;
private PrepareMountStats() {}
private void reset() {
unchangedCount = 0;
movedCount = 0;
unmountedCount = 0;
}
}
private static class MountStats {
private List<String> mountedNames;
private List<String> unmountedNames;
private List<String> updatedNames;
private List<String> visibilityHandlerNames;
private List<String> extras;
private List<Double> mountTimes;
private List<Double> unmountedTimes;
private List<Double> updatedTimes;
private List<Double> visibilityHandlerTimes;
private int mountedCount;
private int unmountedCount;
private int updatedCount;
private int noOpCount;
private double visibilityHandlersTotalTime;
private boolean isLoggingEnabled;
private boolean isInitialized;
private void enableLogging() {
isLoggingEnabled = true;
if (!isInitialized) {
isInitialized = true;
mountedNames = new ArrayList<>();
unmountedNames = new ArrayList<>();
updatedNames = new ArrayList<>();
visibilityHandlerNames = new ArrayList<>();
extras = new ArrayList<>();
mountTimes = new ArrayList<>();
unmountedTimes = new ArrayList<>();
updatedTimes = new ArrayList<>();
visibilityHandlerTimes = new ArrayList<>();
}
}
private void reset() {
mountedCount = 0;
unmountedCount = 0;
updatedCount = 0;
noOpCount = 0;
visibilityHandlersTotalTime = 0;
if (isInitialized) {
mountedNames.clear();
unmountedNames.clear();
updatedNames.clear();
visibilityHandlerNames.clear();
extras.clear();
mountTimes.clear();
unmountedTimes.clear();
updatedTimes.clear();
visibilityHandlerTimes.clear();
}
isLoggingEnabled = false;
}
}
/**
* Unbinds all the MountItems currently mounted on this MountState. Unbinding a MountItem means
* calling unbind on its {@link Component}. The MountItem is not yet unmounted after unbind is
* called and can be re-used in place to re-mount another {@link Component} with the same
* {@link ComponentLifecycle}.
*/
void unbind() {
assertMainThread();
if (mLayoutOutputsIds == null) {
return;
}
boolean isTracing = ComponentsSystrace.isTracing();
if (isTracing) {
ComponentsSystrace.beginSection("MountState.unbind");
}
for (int i = 0, size = mLayoutOutputsIds.length; i < size; i++) {
MountItem mountItem = getItemAt(i);
if (mountItem == null || !mountItem.isBound()) {
continue;
}
final Component component = mountItem.getComponent();
component.unbind(getContextForComponent(component), mountItem.getContent());
mountItem.setIsBound(false);
}
clearVisibilityItems();
if (isTracing) {
ComponentsSystrace.endSection();
}
}
void detach() {
assertMainThread();
unbind();
}
/**
* This is called when the {@link MountItem}s mounted on this {@link MountState} need to be
* re-bound with the same component. The common case here is a detach/attach happens on the
* {@link LithoView} that owns the MountState.
*/
void rebind() {
assertMainThread();
if (mLayoutOutputsIds == null) {
return;
}
for (int i = 0, size = mLayoutOutputsIds.length; i < size; i++) {
final MountItem mountItem = getItemAt(i);
if (mountItem == null || mountItem.isBound()) {
continue;
}
final Component component = mountItem.getComponent();
final Object content = mountItem.getContent();
component.bind(getContextForComponent(component), content);
mountItem.setIsBound(true);
if (content instanceof View &&
!(content instanceof ComponentHost) &&
((View) content).isLayoutRequested()) {
final View view = (View) content;
applyBoundsToMountContent(
view,
view.getLeft(),
view.getTop(),
view.getRight(),
view.getBottom(),
true);
}
}
}
/**
* Whether the item at this index (or one of its parents) are animating. In that case, we don't
* want to unmount this index for visibility reasons (e.g. incremental mount). The reason for this
* is that this item (or it's parent) may have a translation X/Y that actually shows it on the
* screen, even though the non-translated bounds are off the screen.
*/
private boolean isAnimationLocked(int index) {
if (mAnimationLockedIndices == null) {
return false;
}
return mAnimationLockedIndices[index] > 0;
}
/**
* @return true if this method did all the work that was necessary and there is no other content
* that needs mounting/unmounting in this mount step. If false then a full mount step should
* take place.
*/
private boolean performIncrementalMount(
LayoutState layoutState, Rect localVisibleRect, boolean processVisibilityOutputs) {
if (mPreviousLocalVisibleRect.isEmpty()) {
return false;
}
if (localVisibleRect.left != mPreviousLocalVisibleRect.left ||
localVisibleRect.right != mPreviousLocalVisibleRect.right) {
return false;
}
final ArrayList<LayoutOutput> layoutOutputTops = layoutState.getMountableOutputTops();
final ArrayList<LayoutOutput> layoutOutputBottoms = layoutState.getMountableOutputBottoms();
final int count = layoutState.getMountableOutputCount();
if (localVisibleRect.top > 0 || mPreviousLocalVisibleRect.top > 0) {
// View is going on/off the top of the screen. Check the bottoms to see if there is anything
// that has moved on/off the top of the screen.
while (mPreviousBottomsIndex < count &&
localVisibleRect.top >=
layoutOutputBottoms.get(mPreviousBottomsIndex).getBounds().bottom) {
final long id = layoutOutputBottoms.get(mPreviousBottomsIndex).getId();
final int layoutOutputIndex = layoutState.getLayoutOutputPositionForId(id);
if (!isAnimationLocked(layoutOutputIndex)) {
unmountItem(layoutOutputIndex, mHostsByMarker);
}
mPreviousBottomsIndex++;
}
while (mPreviousBottomsIndex > 0 &&
localVisibleRect.top <
layoutOutputBottoms.get(mPreviousBottomsIndex - 1).getBounds().bottom) {
mPreviousBottomsIndex--;
final LayoutOutput layoutOutput = layoutOutputBottoms.get(mPreviousBottomsIndex);
final int layoutOutputIndex =
layoutState.getLayoutOutputPositionForId(layoutOutput.getId());
if (getItemAt(layoutOutputIndex) == null) {
mountLayoutOutput(
layoutState.getLayoutOutputPositionForId(layoutOutput.getId()),
layoutOutput,
layoutState);
mComponentIdsMountedInThisFrame.add(layoutOutput.getId());
}
}
}
final int height = mLithoView.getHeight();
if (localVisibleRect.bottom < height || mPreviousLocalVisibleRect.bottom < height) {
// View is going on/off the bottom of the screen. Check the tops to see if there is anything
// that has changed.
while (mPreviousTopsIndex < count &&
localVisibleRect.bottom > layoutOutputTops.get(mPreviousTopsIndex).getBounds().top) {
final LayoutOutput layoutOutput = layoutOutputTops.get(mPreviousTopsIndex);
final int layoutOutputIndex =
layoutState.getLayoutOutputPositionForId(layoutOutput.getId());
if (getItemAt(layoutOutputIndex) == null) {
mountLayoutOutput(
layoutState.getLayoutOutputPositionForId(layoutOutput.getId()),
layoutOutput,
layoutState);
mComponentIdsMountedInThisFrame.add(layoutOutput.getId());
}
mPreviousTopsIndex++;
}
while (mPreviousTopsIndex > 0 &&
localVisibleRect.bottom <=
layoutOutputTops.get(mPreviousTopsIndex - 1).getBounds().top) {
mPreviousTopsIndex--;
final long id = layoutOutputTops.get(mPreviousTopsIndex).getId();
final int layoutOutputIndex = layoutState.getLayoutOutputPositionForId(id);
if (!isAnimationLocked(layoutOutputIndex)) {
unmountItem(layoutOutputIndex, mHostsByMarker);
}
}
}
for (int i = 0, size = mCanMountIncrementallyMountItems.size(); i < size; i++) {
final MountItem mountItem = mCanMountIncrementallyMountItems.valueAt(i);
final long layoutOutputId = mCanMountIncrementallyMountItems.keyAt(i);
if (!mComponentIdsMountedInThisFrame.contains(layoutOutputId)) {
final int layoutOutputPosition = layoutState.getLayoutOutputPositionForId(layoutOutputId);
if (layoutOutputPosition != -1) {
mountItemIncrementally(
mountItem,
layoutState.getMountableOutputAt(layoutOutputPosition).getBounds(),
localVisibleRect,
processVisibilityOutputs);
}
}
}
mComponentIdsMountedInThisFrame.clear();
return true;
}
LithoView getLithoView() {
assertMainThread();
return mLithoView;
}
private void prepareTransitionManager(LayoutState layoutState) {
if (mTransitionManager == null) {
mTransitionManager = new TransitionManager(this, this);
}
}
private void removeDisappearingMountContentFromComponentHost(ComponentHost componentHost) {
if (componentHost.hasDisappearingItems()) {
List<TransitionId> ids = componentHost.getDisappearingItemTransitionIds();
for (int i = 0, size = ids.size(); i < size; i++) {
mTransitionManager.setMountContent(ids.get(i), null);
}
}
}
/**
* Collect transitions from layout time, mount time and from state updates.
*
* @param layoutState that is going to be mounted.
*/
void collectAllTransitions(LayoutState layoutState, ComponentTree componentTree) {
assertMainThread();
if (mTransitionsHasBeenCollected) {
return;
}
final ArrayList<Transition> allTransitions = new ArrayList<>();
if (layoutState.getTransitions() != null) {
allTransitions.addAll(layoutState.getTransitions());
}
componentTree.applyPreviousRenderData(layoutState);
collectMountTimeTransitions(layoutState, allTransitions);
componentTree.consumeStateUpdateTransitions(allTransitions, layoutState.mRootComponentName);
Transition.RootBoundsTransition rootWidthTransition = new Transition.RootBoundsTransition();
Transition.RootBoundsTransition rootHeightTransition = new Transition.RootBoundsTransition();
final TransitionId rootTransitionId = layoutState.getRootTransitionId();
if (rootTransitionId != null) {
for (int i = 0, size = allTransitions.size(); i < size; i++) {
final Transition transition = allTransitions.get(i);
if (transition == null) {
throw new IllegalStateException(
"NULL_TRANSITION when collecting root bounds anim. Root: "
+ layoutState.mRootComponentName
+ ", root TransitionId: "
+ rootTransitionId);
}
TransitionUtils.collectRootBoundsTransitions(
rootTransitionId, transition, AnimatedProperties.WIDTH, rootWidthTransition);
TransitionUtils.collectRootBoundsTransitions(
rootTransitionId, transition, AnimatedProperties.HEIGHT, rootHeightTransition);
}
}
rootWidthTransition = rootWidthTransition.hasTransition ? rootWidthTransition : null;
rootHeightTransition = rootHeightTransition.hasTransition ? rootHeightTransition : null;
componentTree.setRootWidthAnimation(rootWidthTransition);
componentTree.setRootHeightAnimation(rootHeightTransition);
mRootTransition = TransitionManager.getRootTransition(allTransitions);
mTransitionsHasBeenCollected = true;
}
private static @Nullable void collectMountTimeTransitions(
LayoutState layoutState, List<Transition> outList) {
final List<Component> componentsNeedingPreviousRenderData =
layoutState.getComponentsNeedingPreviousRenderData();
if (componentsNeedingPreviousRenderData == null) {
return;
}
for (int i = 0, size = componentsNeedingPreviousRenderData.size(); i < size; i++) {
final Component component = componentsNeedingPreviousRenderData.get(i);
final Transition transition = component.createTransition(component.getScopedContext());
if (transition != null) {
TransitionUtils.addTransitions(transition, outList, layoutState.mRootComponentName);
}
}
}
/**
* @see LithoViewTestHelper#findTestItems(LithoView, String)
*/
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
Deque<TestItem> findTestItems(String testKey) {
if (mTestItemMap == null) {
throw new UnsupportedOperationException("Trying to access TestItems while " +
"ComponentsConfiguration.isEndToEndTestRun is false.");
}
final Deque<TestItem> items = mTestItemMap.get(testKey);
return items == null ? new LinkedList<TestItem>() : items;
}
/**
* For HostComponents, we don't set a scoped context during layout calculation because we don't
* need one, as we could never call a state update on it. Instead it's okay to use the context
* that is passed to MountState from the LithoView, which is not scoped.
*/
private ComponentContext getContextForComponent(Component component) {
final ComponentContext c = component.getScopedContext();
return c == null ? mContext : c;
}
}
|
use ComponentReporter instead of throwing an exception in MountState#updateAnimationLockCount
Summary: Use `ComponentReporter` instead of throwing an exception in `MountState.udpateAnimationLockCount()` when encountering a negative lock count
Reviewed By: muraziz
Differential Revision: D14420289
fbshipit-source-id: 0cb9d85006084b508dc4d5f53fa74b8b765d82c7
|
litho-core/src/main/java/com/facebook/litho/MountState.java
|
use ComponentReporter instead of throwing an exception in MountState#updateAnimationLockCount
|
<ide><path>itho-core/src/main/java/com/facebook/litho/MountState.java
<ide> mAnimationLockedIndices[i]++;
<ide> } else {
<ide> if (--mAnimationLockedIndices[i] < 0) {
<del> throw new RuntimeException("Decremented animation lock count below 0!");
<add> ComponentsReporter.emitMessage(
<add> ComponentsReporter.LogLevel.FATAL, "Decremented animation lock count below 0!");
<add> mAnimationLockedIndices[i] = 0;
<ide> }
<ide> }
<ide> }
<ide> mAnimationLockedIndices[hostIndex]++;
<ide> } else {
<ide> if (--mAnimationLockedIndices[hostIndex] < 0) {
<del> throw new RuntimeException("Decremented animation lock count below 0!");
<add> ComponentsReporter.emitMessage(
<add> ComponentsReporter.LogLevel.FATAL, "Decremented animation lock count below 0!");
<add> mAnimationLockedIndices[hostIndex] = 0;
<ide> }
<ide> }
<ide> hostId = layoutState.getMountableOutputAt(hostIndex).getHostMarker();
|
|
Java
|
apache-2.0
|
b43d5d55f79634a8c2b54ad7af1543e2a4f827d6
| 0 |
linkhub-sdk/popbill.example.springMVC
|
/*
* 팝빌 현금영수증 API Java SDK SpringMVC Example
*
* - SpringMVC SDK 연동환경 설정방법 안내 : https://docs.popbill.com/cashbill/tutorial/java
* - 업데이트 일자 : 2020-01-20
* - 연동 기술지원 연락처 : 1600-9854 / 070-4304-2991~2
* - 연동 기술지원 이메일 : [email protected]
*
* <테스트 연동개발 준비사항>
* 1) src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml 파일에 선언된
* util:properties 의 링크아이디(LinkID)와 비밀키(SecretKey)를 링크허브 가입시 메일로
* 발급받은 인증정보를 참조하여 변경합니다.
* 2) 팝빌 개발용 사이트(test.popbill.com)에 연동회원으로 가입합니다.
*
* Copyright 2006-2014 linkhub.co.kr, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* or in the "license" file accompanying this file. This file 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.popbill.example;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.popbill.api.CashbillService;
import com.popbill.api.ChargeInfo;
import com.popbill.api.EmailSendConfig;
import com.popbill.api.PopbillException;
import com.popbill.api.Response;
import com.popbill.api.cashbill.CBSearchResult;
import com.popbill.api.cashbill.Cashbill;
import com.popbill.api.cashbill.CashbillInfo;
import com.popbill.api.cashbill.CashbillLog;
/*
* 팝빌 현금영수증 API 예제.
*/
@Controller
@RequestMapping("CashbillService")
public class CashbillServiceExample {
@Autowired
private CashbillService cashbillService;
// 팝빌회원 사업자번호
@Value("#{EXAMPLE_CONFIG.TestCorpNum}")
private String testCorpNum;
// 팝빌회원 아이디
@Value("#{EXAMPLE_CONFIG.TestUserID}")
private String testUserID;
@RequestMapping(value = "", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
return "Cashbill/index";
}
@RequestMapping(value = "checkMgtKeyInUse", method = RequestMethod.GET)
public String checkMgtKeyInUse(Model m) {
/*
* 현금영수증 관리번호 중복여부를 확인합니다.
* - 관리번호는 1~24자리로 숫자, 영문 '-', '_' 조합으로 구성할 수 있습니다.
* - https://docs.popbill.com/cashbill/java/api#CheckMgtKeyInUse
*/
// 문서번호, 최대 24자리 영문, 숫자 , '-', '_'로 구성
String mgtKey = "20190104-001";
String isUseStr;
try {
boolean IsUse = cashbillService.checkMgtKeyInUse(testCorpNum, mgtKey);
isUseStr = (IsUse) ? "사용중" : "미사용중";
m.addAttribute("Result", isUseStr);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "result";
}
@RequestMapping(value = "registIssue", method = RequestMethod.GET)
public String registIssue(Model m) {
/*
* 1건의 현금영수증을 [즉시발행]합니다.
* - 발행일 기준 오후 5시 이전에 발행된 현금영수증은 다음날 오후 2시에 국세청 전송결과를 확인할 수 있습니다.
* - 현금영수증 국세청 전송 정책 : https://docs.popbill.com/cashbill/ntsSendPolicy?lang=java
* - https://docs.popbill.com/cashbill/java/api#RegistIssue
*/
// 메모
String Memo = "현금영수증 즉시발행 메모";
// 현금영수증 정보 객체
Cashbill cashbill = new Cashbill();
// 문서번호, 최대 24자리, 영문, 숫자 '-', '_'로 구성
cashbill.setMgtKey("20191022-001");
// 문서형태, {승인거래, 취소거래} 중 기재
cashbill.setTradeType("승인거래");
// 취소거래시 기재, 원본 현금영수증 국세청 승인번호 - getInfo API를 통해 confirmNum 값 기재
cashbill.setOrgConfirmNum("");
// 취소거래시 기재, 원본 현금영수증 거래일자 - getInfo API를 통해 tradeDate 값 기재
cashbill.setOrgTradeDate("");
// 과세형태, {과세, 비과세} 중 기재
cashbill.setTaxationType("과세");
// 거래처 식별번호, 거래유형에 따라 작성
// 소득공제용 - 주민등록/휴대폰/카드번호 기재가능
// 지출증빙용 - 사업자번호/주민등록/휴대폰/카드번호 기재가능
cashbill.setIdentityNum("0101112222");
// 거래구분, {소득공제용, 지출증빙용} 중 기재
cashbill.setTradeUsage("소득공제용");
// 거래유형, {읿반, 도서공연, 대중교통} 중 기재
cashbill.setTradeOpt("대중교통");
// 공급가액, 숫자만 가능
cashbill.setSupplyCost("10000");
// 부가세, 숫자만 가능
cashbill.setTax("1000");
// 봉사료, 숫자만 가능
cashbill.setServiceFee("0");
// 합계금액, 숫자만 가능, 봉사료 + 공급가액 + 부가세
cashbill.setTotalAmount("11000");
// 발행자 사업자번호, '-'제외 10자리
cashbill.setFranchiseCorpNum("1234567890");
// 발행자 상호
cashbill.setFranchiseCorpName("발행자 상호");
// 발행자 대표자명
cashbill.setFranchiseCEOName("발행자 대표자");
// 발행자 주소
cashbill.setFranchiseAddr("발행자 주소");
// 발행자 연락처
cashbill.setFranchiseTEL("07043042991");
// 발행안내 문자 전송여부
cashbill.setSmssendYN(false);
// 거래처 고객명
cashbill.setCustomerName("고객명");
// 거래처 주문상품명
cashbill.setItemName("상품명");
// 거래처 주문번호
cashbill.setOrderNumber("주문번호");
// 거래처 이메일
// 팝빌 개발환경에서 테스트하는 경우에도 안내 메일이 전송되므로,
// 실제 거래처의 메일주소가 기재되지 않도록 주의
cashbill.setEmail("[email protected]");
// 거래처 휴대폰
cashbill.setHp("010111222");
// 발행안내 메일제목, 미기재시 기본양식으로 메일 전송
String emailSubject = "";
try {
Response response = cashbillService.registIssue(testCorpNum, cashbill, Memo, testUserID, emailSubject);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "register", method = RequestMethod.GET)
public String register(Model m) {
/*
* 1건의 현금영수증을 [임시저장]합니다.
* - [임시저장] 상태의 현금영수증은 발행(Issue API)을 호출해야만 국세청에 전송됩니다.
* - 발행일 기준 오후 5시 이전에 발행된 현금영수증은 다음날 오후 2시에 국세청 전송결과를 확인할 수 있습니다.
* - https://docs.popbill.com/cashbill/java/api#Register
*/
// 현금영수증 정보 객체
Cashbill cashbill = new Cashbill();
// 문서번호, 최대 24자리, 영문, 숫자 '-', '_'로 구성
cashbill.setMgtKey("20190104-001");
// 문서형태, {승인거래, 취소거래} 중 기재
cashbill.setTradeType("승인거래");
// 취소거래시 기재, 원본 현금영수증 국세청 승인번호 - getInfo API를 통해 confirmNum 값 기재
cashbill.setOrgConfirmNum("");
// 취소거래시 기재, 원본 현금영수증 거래일자 - getInfo API를 통해 tradeDate 값 기재
cashbill.setOrgTradeDate("");
// 과세형태, {과세, 비과세} 중 기재
cashbill.setTaxationType("과세");
// 거래처 식별번호, 거래유형에 따라 작성
// 소득공제용 - 주민등록/휴대폰/카드번호 기재가능
// 지출증빙용 - 사업자번호/주민등록/휴대폰/카드번호 기재가능
cashbill.setIdentityNum("01011112222");
// 거래구분, {소득공제용, 지출증빙용} 중 기재
cashbill.setTradeUsage("소득공제용");
// 거래유형, {일반, 도서공연, 대중교통} 중 기재
cashbill.setTradeOpt("일반");
// 공급가액, 숫자만 가능
cashbill.setSupplyCost("10000");
// 부가세, 숫자만 가능
cashbill.setTax("1000");
// 봉사료, 숫자만 가능
cashbill.setServiceFee("0");
// 합계금액, 숫자만 가능, 봉사료 + 공급가액 + 부가세
cashbill.setTotalAmount("11000");
// 발행자 사업자번호, '-'제외 10자리
cashbill.setFranchiseCorpNum("1234567890");
// 발행자 상호
cashbill.setFranchiseCorpName("발행자 상호");
// 발행자 대표자명
cashbill.setFranchiseCEOName("발행자 대표자");
// 발행자 주소
cashbill.setFranchiseAddr("발행자 주소");
// 발행자 연락처
cashbill.setFranchiseTEL("07043042991");
// 발행안내 문자 전송여부
cashbill.setSmssendYN(false);
// 거래처 고객명
cashbill.setCustomerName("고객명");
// 거래처 주문상품명
cashbill.setItemName("상품명");
// 거래처 주문번호
cashbill.setOrderNumber("주문번호");
// 거래처 이메일
cashbill.setEmail("[email protected]");
// 거래처 휴대폰
cashbill.setHp("010111222");
try {
Response response = cashbillService.register(testCorpNum, cashbill);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "update", method = RequestMethod.GET)
public String update(Model m) {
/*
* 1건의 현금영수증을 [수정]합니다.
* - [임시저장] 상태의 현금영수증만 수정할 수 있습니다.
* - https://docs.popbill.com/cashbill/java/api#Update
*/
// 수정할 현금영수증 문서번호
String mgtKey = "20190104-001";
// 현금영수증 정보 객체
Cashbill cashbill = new Cashbill();
// 문서번호, 최대 24자리, 영문, 숫자 '-', '_'로 구성
cashbill.setMgtKey(mgtKey);
// 문서형태, {승인거래, 취소거래} 중 기재
cashbill.setTradeType("승인거래");
// 취소거래시 기재, 원본현금영수증 국세청 승인번호 - getInfo API를 통해 confirmNum 값 기재
//cashbill.setOrgConfirmNum("");
// 과세형태, {과세, 비과세} 중 기재
cashbill.setTaxationType("과세");
// 거래처 식별번호, 거래유형에 따라 작성
// 소득공제용 - 주민등록/휴대폰/카드번호 기재가능
// 지출증빙용 - 사업자번호/주민등록/휴대폰/카드번호 기재가능
cashbill.setIdentityNum("01011112222");
// 거래유형, {소득공제용, 지출증빙용} 중 기재
cashbill.setTradeUsage("소득공제용");
// 공급가액, 숫자만 가능
cashbill.setSupplyCost("10000");
// 부가세, 숫자만 가능
cashbill.setTax("1000");
// 봉사료, 숫자만 가능
cashbill.setServiceFee("0");
// 합계금액, 숫자만 가능, 봉사료 + 공급가액 + 부가세
cashbill.setTotalAmount("11000");
// 발행자 사업자번호, '-'제외 10자리
cashbill.setFranchiseCorpNum("1234567890");
// 발행자 상호
cashbill.setFranchiseCorpName("발행자 상호_수정");
// 발행자 대표자명
cashbill.setFranchiseCEOName("발행자 대표자_수정");
// 발행자 주소
cashbill.setFranchiseAddr("발행자 주소");
// 발행자 연락처
cashbill.setFranchiseTEL("07043042991");
// 발행안내 문자 전송여부
cashbill.setSmssendYN(false);
// 거래처 고객명
cashbill.setCustomerName("고객명");
// 거래처 주문상품명
cashbill.setItemName("상품명");
// 거래처 주문번호
cashbill.setOrderNumber("주문번호");
// 거래처 이메일
cashbill.setEmail("[email protected]");
// 거래처 휴대폰
cashbill.setHp("010111222");
try {
Response response = cashbillService.update(testCorpNum, mgtKey,
cashbill);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "issue", method = RequestMethod.GET)
public String issue(Model m) {
/*
* 1건의 [임시저장] 현금영수증을 [발행]합니다.
* - 발행일 기준 오후 5시 이전에 발행된 현금영수증은 다음날 오후 2시에 국세청 전송결과를 확인할 수 있습니다.
* - https://docs.popbill.com/cashbill/java/api#CBIssue
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
// 메모
String memo = "발행메모";
try {
Response response = cashbillService.issue(testCorpNum, mgtKey, memo);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "cancelIssue", method = RequestMethod.GET)
public String cancelIssue(Model m) {
/*
* [발행완료] 상태의 현금영수증을 [발행취소]합니다.
* - 발행취소는 국세청 전송전에만 가능합니다.
* - 발행취소된 형금영수증은 국세청에 전송되지 않습니다.
* - https://docs.popbill.com/cashbill/java/api#CancelIssue
*/
// 문서번호
String mgtKey = "20190104-001";
// 메모
String memo = "발행취소 메모";
try {
Response response = cashbillService.cancelIssue(testCorpNum, mgtKey, memo);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "delete", method = RequestMethod.GET)
public String delete(Model m) {
/*
* 1건의 현금영수증을 [삭제]합니다.
* - 현금영수증을 삭제하면 사용된 문서번호(mgtKey)를 재사용할 수 있습니다.
* - 삭제가능한 문서 상태 : [임시저장], [발행취소]
* - https://docs.popbill.com/cashbill/java/api#Delete
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
try {
Response response = cashbillService.delete(testCorpNum, mgtKey);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "revokeRegister", method = RequestMethod.GET)
public String revokeRegister(Model m) {
/*
* 1건의 취소현금영수증을 [임시저장]합니다.
* - [임시저장] 상태의 현금영수증은 [발행(Issue API)]을 해야만 국세청에 전송됩니다.
* - https://docs.popbill.com/cashbill/java/api#RevokeRegister
*/
// 문서번호, 영문, 숫자, 하이픈(-), 언더바(_)를 조합하여 24자리 문자열로 사업자별로
// 중복되지 않도록 구성
String mgtKey = "20190104-001";
// 원본현금영수증 승인번호
String orgConfirmNum = "820116333";
// 원본현금영수증 거래일자
String orgTradeDate = "20190102";
try {
Response response = cashbillService.revokeRegister(testCorpNum, mgtKey, orgConfirmNum, orgTradeDate);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "revokeRegister_part", method = RequestMethod.GET)
public String revokeRegister_part(Model m) {
/*
* 1건의 (부분)취소현금영수증을 [임시저장]합니다.
* - [임시저장] 상태의 현금영수증은 [발행(Issue API)]을 해야만 국세청에 전송됩니다.
* - https://docs.popbill.com/cashbill/java/api#RevokeRegister
*/
// 문서번호, 영문, 숫자, 하이픈(-), 언더바(_)를 조합하여 24자리 문자열로 사업자별로
// 중복되지 않도록 구성
String mgtKey = "20190104-001";
// 원본현금영수증 승인번호
String orgConfirmNum = "820116333";
// 원본현금영수증 거래일자
String orgTradeDate = "20190103";
// 안내문자 전송여부
Boolean smssendYN = false;
// 부분취소 여부, false 기재시
Boolean isPartCancel = true;
// 취소사유 (integer 타입) / 1-거래취소, 2-오류발급취소 3-기타
Integer cancelType = 1;
// [취소] 공급가액
String supplyCost = "3000";
// [취소] 부가세
String tax = "300";
// [취소] 봉사료
String serviceFee = "0";
// [취소] 합계금액
String totalAmount = "3300";
try {
Response response = cashbillService.revokeRegister(testCorpNum, mgtKey,
orgConfirmNum, orgTradeDate, smssendYN, isPartCancel, cancelType,
supplyCost, tax, serviceFee, totalAmount);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "revokeRegistIssue", method = RequestMethod.GET)
public String revokeRegistIssue(Model m) {
/*
* 1건의 취소현금영수증을 [즉시발행]합니다.
* - 발행일 기준 오후 5시 이전에 발행된 현금영수증은 다음날 오후 2시에 국세청 전송결과를 확인할 수 있습니다.
* - https://docs.popbill.com/cashbill/java/api#RevokeRegistIssue
*/
// 문서번호, 영문, 숫자, 하이픈(-), 언더바(_)를 조합하여 24자리 문자열로 사업자별로
// 중복되지 않도록 구성
String mgtKey = "20190104-001";
// 원본현금영수증 승인번호
String orgConfirmNum = "820116333";
// 원본현금영수증 거래일자
String orgTradeDate = "201901003";
try {
Response response = cashbillService.revokeRegistIssue(testCorpNum, mgtKey, orgConfirmNum, orgTradeDate);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "revokeRegistIssue_part", method = RequestMethod.GET)
public String revokeRegistIssue_part(Model m) {
/*
* 1건의 (부분)취소현금영수증을 [즉시발행]합니다.
* - 발행일 기준 오후 5시 이전에 발행된 현금영수증은 다음날 오후 2시에 국세청 전송결과를 확인할 수 있습니다.
* - https://docs.popbill.com/cashbill/java/api#RevokeRegistIssue
*/
// 문서번호, 영문, 숫자, 하이픈(-), 언더바(_)를 조합하여 24자리 문자열로 사업자별로
// 중복되지 않도록 구성
String mgtKey = "20190104-001";
// 원본현금영수증 승인번호
String orgConfirmNum = "820116333";
// 원본현금영수증 거래일자
String orgTradeDate = "20190103";
// 안내문자 전송여부
Boolean smssendYN = false;
// 발행 메모
String memo = "취소 현금영수증 발행 메모";
// 부분취소 여부
Boolean isPartCancel = true;
// 취소사유 (integer 타입) / 1-거래취소, 2-오류발급취소 3-기타
Integer cancelType = 1;
// [취소] 공급가액
String supplyCost = "3000";
// [취소] 부가세
String tax = "300";
// [취소] 봉사료
String serviceFee = "0";
// [취소] 합계금액
String totalAmount = "3300";
try {
Response response = cashbillService.revokeRegistIssue(testCorpNum, mgtKey,
orgConfirmNum, orgTradeDate, smssendYN, memo, isPartCancel, cancelType,
supplyCost, tax, serviceFee, totalAmount);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "getInfo", method = RequestMethod.GET)
public String getInfo(Model m) {
/*
* 1건의 현금영수증 상태/요약 정보를 확인합니다.
* - https://docs.popbill.com/cashbill/java/api#GetInfo
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
try {
CashbillInfo cashbillInfo = cashbillService.getInfo(testCorpNum, mgtKey);
m.addAttribute("CashbillInfo", cashbillInfo);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "Cashbill/CashbillInfo";
}
@RequestMapping(value = "getInfos", method = RequestMethod.GET)
public String getInfos(Model m) {
/*
* 대량의 현금영수증 상태/요약 정보를 확인합니다. (최대 1000건)
* - https://docs.popbill.com/cashbill/java/api#GetInfos
*/
// 현금영수증 문서번호 배열 최대(1000건)
String[] mgtKeyList = new String[]{"20190104-001", "20190104-002", "20190104-003"};
try {
CashbillInfo[] cashbillInfos = cashbillService.getInfos(testCorpNum, mgtKeyList);
m.addAttribute("CashbillInfos", cashbillInfos);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "Cashbill/CashbillInfo";
}
@RequestMapping(value = "getDetailInfo", method = RequestMethod.GET)
public String getDetailInfo(Model m) {
/*
* 현금영수증 1건의 상세정보를 조회합니다.
* - https://docs.popbill.com/cashbill/java/api#GetDetailInfo
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
try {
Cashbill cashbill = cashbillService.getDetailInfo(testCorpNum, mgtKey);
m.addAttribute("Cashbill", cashbill);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "Cashbill/Cashbill";
}
@RequestMapping(value = "assignMgtKey", method = RequestMethod.GET)
public String assignMgtKey(Model m) {
/*
* 팝빌 사이트에서 작성한 현금영수증에 파트너의 문서번호를 할당합니다.
*/
// 현금영수증 아이템키, 문서 목록조회(Search) API의 반환항목중 ItemKey 참조
String itemKey = "020080716195300001";
// 할당할 문서번호, 숫자, 영문 '-', '_' 조합으로 1~24자리까지
// 사업자번호별 중복없는 고유번호 할당
String mgtKey = "20200807-100";
try {
Response response = cashbillService.assignMgtKey(testCorpNum, itemKey, mgtKey);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "search", method = RequestMethod.GET)
public String search(Model m) {
/*
* 검색조건을 사용하여 현금영수증 목록을 조회합니다.
* - https://docs.popbill.com/cashbill/java/api#Search
*/
// 일자유형, R-등록일자, T-거래일자, I-발행일자
String DType = "T";
// 시작일자, 날짜형식(yyyyMMdd)
String SDate = "20181201";
// 종료일자, 날짜형식(yyyyMMdd)
String EDate = "20190103";
// 상태코드 배열, 2,3번째 자리에 와일드카드(*) 사용 가능
String[] State = {"100", "2**", "3**", "4**"};
// 문서형태 배열, N-승인거래, C-취소거래
String[] TradeType = {"N", "C"};
// 거래구분 배열, P-소득공제용, C-지출증빙용
String[] TradeUsage = {"P", "C"};
// 거래유형 배열, N-일반, B-도서공연, T-대중교통
String[] TradeOpt = {"N", "B", "T"};
// 과세형태 배열, T-과세, N-비과세
String[] TaxationType = {"T", "N"};
// 식별번호 조회, 미기재시 전체조회
String QString = "";
// 페이지 번호
int Page = 1;
// 페이지당 목록개수, 최대 1000건
int PerPage = 20;
// 정렬방향, A-오름차순, D-내림차순
String Order = "D";
try {
CBSearchResult searchResult = cashbillService.search(testCorpNum, DType, SDate, EDate,
State, TradeType, TradeUsage, TradeOpt, TaxationType, QString,
Page, PerPage, Order);
m.addAttribute("SearchResult", searchResult);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "Cashbill/SearchResult";
}
@RequestMapping(value = "getLogs", method = RequestMethod.GET)
public String getLogs(Model m) {
/*
* 현금영수증 상태 변경이력을 확인합니다.
* - https://docs.popbill.com/cashbill/java/api#GetLogs
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
try {
CashbillLog[] cashbillLogs = cashbillService.getLogs(testCorpNum, mgtKey);
m.addAttribute("CashbillLogs", cashbillLogs);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "Cashbill/CashbillLog";
}
@RequestMapping(value = "getURL", method = RequestMethod.GET)
public String getURL(Model m) {
/*
* 팝빌 현금영수증 문서함 팝업 URL을 반환합니다.
* - https://docs.popbill.com/cashbill/java/api#GetURL
*/
// TBOX : 임시문서함 , PBOX : 매출문서함, WRITE : 현금영수증 작성
String TOGO = "WRITE";
try {
String url = cashbillService.getURL(testCorpNum, TOGO);
m.addAttribute("Result", url);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "result";
}
@RequestMapping(value = "getPopUpURL", method = RequestMethod.GET)
public String getPopUpURL(Model m) {
/*
* 1건의 현금영수증 보기 팝업 URL을 반환합니다.
* - https://docs.popbill.com/cashbill/java/api#GetPopUpURL
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
try {
String url = cashbillService.getPopUpURL(testCorpNum, mgtKey);
m.addAttribute("Result", url);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "result";
}
@RequestMapping(value = "getPrintURL", method = RequestMethod.GET)
public String getPrintURL(Model m) {
/*
* 1건의 현금영수증 인쇄팝업 URL을 반환합니다.
* - https://docs.popbill.com/cashbill/java/api#GetPrintURL
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
try {
String url = cashbillService.getPrintURL(testCorpNum, mgtKey);
m.addAttribute("Result", url);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "result";
}
@RequestMapping(value = "getPDFURL", method = RequestMethod.GET)
public String getPDFURL(Model m) {
/*
* 1건의 현금영수증 PDF 다운로드 URL을 반환합니다.
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
try {
String url = cashbillService.getPDFURL(testCorpNum, mgtKey);
m.addAttribute("Result", url);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "result";
}
@RequestMapping(value = "getEPrintURL", method = RequestMethod.GET)
public String getEPrintURL(Model m) {
/*
* 현금영수증 인쇄(공급받는자) URL을 반환합니다.
* - URL 보안정책에 따라 반환된 URL은 30초의 유효시간을 갖습니다.
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
try {
String url = cashbillService.getEPrintURL(testCorpNum, mgtKey);
m.addAttribute("Result", url);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "result";
}
@RequestMapping(value = "getMassPrintURL", method = RequestMethod.GET)
public String getMassPrintURL(Model m) {
/*
* 대량의 현금영수증 인쇄팝업 URL을 반환합니다. (최대 100건)
* - https://docs.popbill.com/cashbill/java/api#GetMassPrintURL
*/
// 문서번호 배열, 최대 100건
String[] mgtKeyList = new String[]{"20190104-001", "20190104-002", "20190104-003"};
try {
String url = cashbillService.getMassPrintURL(testCorpNum, mgtKeyList);
m.addAttribute("Result", url);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "result";
}
@RequestMapping(value = "getMailURL", method = RequestMethod.GET)
public String getMailURL(Model m) {
/*
* 현금영수증 수신메일 링크주소를 반환합니다.
* - https://docs.popbill.com/cashbill/java/api#GetMailURL
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
try {
String url = cashbillService.getMailURL(testCorpNum, mgtKey);
m.addAttribute("Result", url);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "result";
}
@RequestMapping(value = "sendEmail", method = RequestMethod.GET)
public String sendEmail(Model m) {
/*
* 현금영수증 발행 안내메일을 재전송합니다.
* - https://docs.popbill.com/cashbill/java/api#SendEmail
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
// 수신자 메일주소
String receiver = "[email protected]";
try {
Response response = cashbillService.sendEmail(testCorpNum, mgtKey, receiver);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "sendSMS", method = RequestMethod.GET)
public String sendSMS(Model m) {
/*
* 알림문자를 전송합니다. (단문/SMS - 한글 최대 45자)
* - 알림문자 전송시 포인트가 차감됩니다. (전송실패시 환불처리)
* - 전송내역 확인은 "팝빌 로그인" > [문자 팩스] > [문자] > [전송내역] 탭에서 전송결과를 확인할 수 있습니다.
* - https://docs.popbill.com/cashbill/java/api#SendSMS
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
// 발신번호
String sender = "07043042991";
// 수신번호
String receiver = "010111222";
// 문자 전송 내용 (90Byte 초과시 길이가 조정되어 전송)
String contents = "현금영수증 문자메시지 전송 테스트입니다.";
try {
Response response = cashbillService.sendSMS(testCorpNum, mgtKey,
sender, receiver, contents);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "sendFAX", method = RequestMethod.GET)
public String sendFAX(Model m) {
/*
* 현금영수증을 팩스전송합니다.
* - 팩스 전송 요청시 포인트가 차감됩니다. (전송실패시 환불처리)
* - 전송내역 확인은 "팝빌 로그인" > [문자 팩스] > [팩스] > [전송내역] 메뉴에서 전송결과를 확인할 수 있습니다.
* - https://docs.popbill.com/cashbill/java/api#SendFAX
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
// 발신자 번호
String sender = "07043042991";
// 수신자 팩스번호
String receiver = "010111222";
try {
Response response = cashbillService.sendFAX(testCorpNum, mgtKey,
sender, receiver);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "listEmailConfig", method = RequestMethod.GET)
public String listEmailConfig(Model m) {
/*
* 현금영수증 관련 메일전송 항목에 대한 전송여부를 목록을 반환합니다.
* - https://docs.popbill.com/cashbill/java/api#ListEmailConfig
*/
try {
EmailSendConfig[] emailSendConfigs = cashbillService.listEmailConfig(testCorpNum);
m.addAttribute("EmailSendConfigs", emailSendConfigs);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "Cashbill/EmailSendConfig";
}
@RequestMapping(value = "updateEmailConfig", method = RequestMethod.GET)
public String updateEmailConfig(Model m) {
/*
* 현금영수증 관련 메일전송 항목에 대한 전송여부를 수정합니다.
* - https://docs.popbill.com/cashbill/java/api#UpdateEmailConfig
*
* 메일전송유형
* CSH_ISSUE : 고객에게 현금영수증이 발행 되었음을 알려주는 메일 입니다.
* CSH_CANCEL : 고객에게 현금영수증이 발행취소 되었음을 알려주는 메일 입니다.
*
*/
// 메일 전송 유형
String emailType = "CSH_ISSUE";
// 전송 여부 (true = 전송, false = 미전송)
Boolean sendYN = true;
try {
Response response = cashbillService.updateEmailConfig(testCorpNum,
emailType, sendYN);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "getUnitCost", method = RequestMethod.GET)
public String getUnitCost(Model m) {
/*
* 현금영수증 발행단가를 확인합니다.
* - https://docs.popbill.com/cashbill/java/api#GetUnitCost
*/
try {
float unitCost = cashbillService.getUnitCost(testCorpNum);
m.addAttribute("Result", unitCost);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "result";
}
@RequestMapping(value = "getChargeInfo", method = RequestMethod.GET)
public String chargeInfo(Model m) {
/*
* 현금영수증 API 서비스 과금정보를 확인합니다.
* - https://docs.popbill.com/cashbill/java/api#GetChargeInfo
*/
try {
ChargeInfo chrgInfo = cashbillService.getChargeInfo(testCorpNum);
m.addAttribute("ChargeInfo", chrgInfo);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "getChargeInfo";
}
}
|
src/main/java/com/popbill/example/CashbillServiceExample.java
|
/*
* 팝빌 현금영수증 API Java SDK SpringMVC Example
*
* - SpringMVC SDK 연동환경 설정방법 안내 : https://docs.popbill.com/cashbill/tutorial/java
* - 업데이트 일자 : 2020-01-20
* - 연동 기술지원 연락처 : 1600-9854 / 070-4304-2991~2
* - 연동 기술지원 이메일 : [email protected]
*
* <테스트 연동개발 준비사항>
* 1) src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml 파일에 선언된
* util:properties 의 링크아이디(LinkID)와 비밀키(SecretKey)를 링크허브 가입시 메일로
* 발급받은 인증정보를 참조하여 변경합니다.
* 2) 팝빌 개발용 사이트(test.popbill.com)에 연동회원으로 가입합니다.
*
* Copyright 2006-2014 linkhub.co.kr, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* or in the "license" file accompanying this file. This file 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.popbill.example;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.popbill.api.CashbillService;
import com.popbill.api.ChargeInfo;
import com.popbill.api.EmailSendConfig;
import com.popbill.api.PopbillException;
import com.popbill.api.Response;
import com.popbill.api.cashbill.CBSearchResult;
import com.popbill.api.cashbill.Cashbill;
import com.popbill.api.cashbill.CashbillInfo;
import com.popbill.api.cashbill.CashbillLog;
import com.popbill.api.taxinvoice.MgtKeyType;
/*
* 팝빌 현금영수증 API 예제.
*/
@Controller
@RequestMapping("CashbillService")
public class CashbillServiceExample {
@Autowired
private CashbillService cashbillService;
// 팝빌회원 사업자번호
@Value("#{EXAMPLE_CONFIG.TestCorpNum}")
private String testCorpNum;
// 팝빌회원 아이디
@Value("#{EXAMPLE_CONFIG.TestUserID}")
private String testUserID;
@RequestMapping(value = "", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
return "Cashbill/index";
}
@RequestMapping(value = "checkMgtKeyInUse", method = RequestMethod.GET)
public String checkMgtKeyInUse(Model m) {
/*
* 현금영수증 관리번호 중복여부를 확인합니다.
* - 관리번호는 1~24자리로 숫자, 영문 '-', '_' 조합으로 구성할 수 있습니다.
* - https://docs.popbill.com/cashbill/java/api#CheckMgtKeyInUse
*/
// 문서번호, 최대 24자리 영문, 숫자 , '-', '_'로 구성
String mgtKey = "20190104-001";
String isUseStr;
try {
boolean IsUse = cashbillService.checkMgtKeyInUse(testCorpNum, mgtKey);
isUseStr = (IsUse) ? "사용중" : "미사용중";
m.addAttribute("Result", isUseStr);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "result";
}
@RequestMapping(value = "registIssue", method = RequestMethod.GET)
public String registIssue(Model m) {
/*
* 1건의 현금영수증을 [즉시발행]합니다.
* - 발행일 기준 오후 5시 이전에 발행된 현금영수증은 다음날 오후 2시에 국세청 전송결과를 확인할 수 있습니다.
* - 현금영수증 국세청 전송 정책 : https://docs.popbill.com/cashbill/ntsSendPolicy?lang=java
* - https://docs.popbill.com/cashbill/java/api#RegistIssue
*/
// 메모
String Memo = "현금영수증 즉시발행 메모";
// 현금영수증 정보 객체
Cashbill cashbill = new Cashbill();
// 문서번호, 최대 24자리, 영문, 숫자 '-', '_'로 구성
cashbill.setMgtKey("20191022-001");
// 문서형태, {승인거래, 취소거래} 중 기재
cashbill.setTradeType("승인거래");
// 취소거래시 기재, 원본 현금영수증 국세청 승인번호 - getInfo API를 통해 confirmNum 값 기재
cashbill.setOrgConfirmNum("");
// 취소거래시 기재, 원본 현금영수증 거래일자 - getInfo API를 통해 tradeDate 값 기재
cashbill.setOrgTradeDate("");
// 과세형태, {과세, 비과세} 중 기재
cashbill.setTaxationType("과세");
// 거래처 식별번호, 거래유형에 따라 작성
// 소득공제용 - 주민등록/휴대폰/카드번호 기재가능
// 지출증빙용 - 사업자번호/주민등록/휴대폰/카드번호 기재가능
cashbill.setIdentityNum("0101112222");
// 거래구분, {소득공제용, 지출증빙용} 중 기재
cashbill.setTradeUsage("소득공제용");
// 거래유형, {읿반, 도서공연, 대중교통} 중 기재
cashbill.setTradeOpt("대중교통");
// 공급가액, 숫자만 가능
cashbill.setSupplyCost("10000");
// 부가세, 숫자만 가능
cashbill.setTax("1000");
// 봉사료, 숫자만 가능
cashbill.setServiceFee("0");
// 합계금액, 숫자만 가능, 봉사료 + 공급가액 + 부가세
cashbill.setTotalAmount("11000");
// 발행자 사업자번호, '-'제외 10자리
cashbill.setFranchiseCorpNum("1234567890");
// 발행자 상호
cashbill.setFranchiseCorpName("발행자 상호");
// 발행자 대표자명
cashbill.setFranchiseCEOName("발행자 대표자");
// 발행자 주소
cashbill.setFranchiseAddr("발행자 주소");
// 발행자 연락처
cashbill.setFranchiseTEL("07043042991");
// 발행안내 문자 전송여부
cashbill.setSmssendYN(false);
// 거래처 고객명
cashbill.setCustomerName("고객명");
// 거래처 주문상품명
cashbill.setItemName("상품명");
// 거래처 주문번호
cashbill.setOrderNumber("주문번호");
// 거래처 이메일
// 팝빌 개발환경에서 테스트하는 경우에도 안내 메일이 전송되므로,
// 실제 거래처의 메일주소가 기재되지 않도록 주의
cashbill.setEmail("[email protected]");
// 거래처 휴대폰
cashbill.setHp("010111222");
// 발행안내 메일제목, 미기재시 기본양식으로 메일 전송
String emailSubject = "";
try {
Response response = cashbillService.registIssue(testCorpNum, cashbill, Memo, testUserID, emailSubject);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "register", method = RequestMethod.GET)
public String register(Model m) {
/*
* 1건의 현금영수증을 [임시저장]합니다.
* - [임시저장] 상태의 현금영수증은 발행(Issue API)을 호출해야만 국세청에 전송됩니다.
* - 발행일 기준 오후 5시 이전에 발행된 현금영수증은 다음날 오후 2시에 국세청 전송결과를 확인할 수 있습니다.
* - https://docs.popbill.com/cashbill/java/api#Register
*/
// 현금영수증 정보 객체
Cashbill cashbill = new Cashbill();
// 문서번호, 최대 24자리, 영문, 숫자 '-', '_'로 구성
cashbill.setMgtKey("20190104-001");
// 문서형태, {승인거래, 취소거래} 중 기재
cashbill.setTradeType("승인거래");
// 취소거래시 기재, 원본 현금영수증 국세청 승인번호 - getInfo API를 통해 confirmNum 값 기재
cashbill.setOrgConfirmNum("");
// 취소거래시 기재, 원본 현금영수증 거래일자 - getInfo API를 통해 tradeDate 값 기재
cashbill.setOrgTradeDate("");
// 과세형태, {과세, 비과세} 중 기재
cashbill.setTaxationType("과세");
// 거래처 식별번호, 거래유형에 따라 작성
// 소득공제용 - 주민등록/휴대폰/카드번호 기재가능
// 지출증빙용 - 사업자번호/주민등록/휴대폰/카드번호 기재가능
cashbill.setIdentityNum("01011112222");
// 거래구분, {소득공제용, 지출증빙용} 중 기재
cashbill.setTradeUsage("소득공제용");
// 거래유형, {일반, 도서공연, 대중교통} 중 기재
cashbill.setTradeOpt("일반");
// 공급가액, 숫자만 가능
cashbill.setSupplyCost("10000");
// 부가세, 숫자만 가능
cashbill.setTax("1000");
// 봉사료, 숫자만 가능
cashbill.setServiceFee("0");
// 합계금액, 숫자만 가능, 봉사료 + 공급가액 + 부가세
cashbill.setTotalAmount("11000");
// 발행자 사업자번호, '-'제외 10자리
cashbill.setFranchiseCorpNum("1234567890");
// 발행자 상호
cashbill.setFranchiseCorpName("발행자 상호");
// 발행자 대표자명
cashbill.setFranchiseCEOName("발행자 대표자");
// 발행자 주소
cashbill.setFranchiseAddr("발행자 주소");
// 발행자 연락처
cashbill.setFranchiseTEL("07043042991");
// 발행안내 문자 전송여부
cashbill.setSmssendYN(false);
// 거래처 고객명
cashbill.setCustomerName("고객명");
// 거래처 주문상품명
cashbill.setItemName("상품명");
// 거래처 주문번호
cashbill.setOrderNumber("주문번호");
// 거래처 이메일
cashbill.setEmail("[email protected]");
// 거래처 휴대폰
cashbill.setHp("010111222");
try {
Response response = cashbillService.register(testCorpNum, cashbill);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "update", method = RequestMethod.GET)
public String update(Model m) {
/*
* 1건의 현금영수증을 [수정]합니다.
* - [임시저장] 상태의 현금영수증만 수정할 수 있습니다.
* - https://docs.popbill.com/cashbill/java/api#Update
*/
// 수정할 현금영수증 문서번호
String mgtKey = "20190104-001";
// 현금영수증 정보 객체
Cashbill cashbill = new Cashbill();
// 문서번호, 최대 24자리, 영문, 숫자 '-', '_'로 구성
cashbill.setMgtKey(mgtKey);
// 문서형태, {승인거래, 취소거래} 중 기재
cashbill.setTradeType("승인거래");
// 취소거래시 기재, 원본현금영수증 국세청 승인번호 - getInfo API를 통해 confirmNum 값 기재
//cashbill.setOrgConfirmNum("");
// 과세형태, {과세, 비과세} 중 기재
cashbill.setTaxationType("과세");
// 거래처 식별번호, 거래유형에 따라 작성
// 소득공제용 - 주민등록/휴대폰/카드번호 기재가능
// 지출증빙용 - 사업자번호/주민등록/휴대폰/카드번호 기재가능
cashbill.setIdentityNum("01011112222");
// 거래유형, {소득공제용, 지출증빙용} 중 기재
cashbill.setTradeUsage("소득공제용");
// 공급가액, 숫자만 가능
cashbill.setSupplyCost("10000");
// 부가세, 숫자만 가능
cashbill.setTax("1000");
// 봉사료, 숫자만 가능
cashbill.setServiceFee("0");
// 합계금액, 숫자만 가능, 봉사료 + 공급가액 + 부가세
cashbill.setTotalAmount("11000");
// 발행자 사업자번호, '-'제외 10자리
cashbill.setFranchiseCorpNum("1234567890");
// 발행자 상호
cashbill.setFranchiseCorpName("발행자 상호_수정");
// 발행자 대표자명
cashbill.setFranchiseCEOName("발행자 대표자_수정");
// 발행자 주소
cashbill.setFranchiseAddr("발행자 주소");
// 발행자 연락처
cashbill.setFranchiseTEL("07043042991");
// 발행안내 문자 전송여부
cashbill.setSmssendYN(false);
// 거래처 고객명
cashbill.setCustomerName("고객명");
// 거래처 주문상품명
cashbill.setItemName("상품명");
// 거래처 주문번호
cashbill.setOrderNumber("주문번호");
// 거래처 이메일
cashbill.setEmail("[email protected]");
// 거래처 휴대폰
cashbill.setHp("010111222");
try {
Response response = cashbillService.update(testCorpNum, mgtKey,
cashbill);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "issue", method = RequestMethod.GET)
public String issue(Model m) {
/*
* 1건의 [임시저장] 현금영수증을 [발행]합니다.
* - 발행일 기준 오후 5시 이전에 발행된 현금영수증은 다음날 오후 2시에 국세청 전송결과를 확인할 수 있습니다.
* - https://docs.popbill.com/cashbill/java/api#CBIssue
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
// 메모
String memo = "발행메모";
try {
Response response = cashbillService.issue(testCorpNum, mgtKey, memo);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "cancelIssue", method = RequestMethod.GET)
public String cancelIssue(Model m) {
/*
* [발행완료] 상태의 현금영수증을 [발행취소]합니다.
* - 발행취소는 국세청 전송전에만 가능합니다.
* - 발행취소된 형금영수증은 국세청에 전송되지 않습니다.
* - https://docs.popbill.com/cashbill/java/api#CancelIssue
*/
// 문서번호
String mgtKey = "20190104-001";
// 메모
String memo = "발행취소 메모";
try {
Response response = cashbillService.cancelIssue(testCorpNum, mgtKey, memo);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "delete", method = RequestMethod.GET)
public String delete(Model m) {
/*
* 1건의 현금영수증을 [삭제]합니다.
* - 현금영수증을 삭제하면 사용된 문서번호(mgtKey)를 재사용할 수 있습니다.
* - 삭제가능한 문서 상태 : [임시저장], [발행취소]
* - https://docs.popbill.com/cashbill/java/api#Delete
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
try {
Response response = cashbillService.delete(testCorpNum, mgtKey);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "revokeRegister", method = RequestMethod.GET)
public String revokeRegister(Model m) {
/*
* 1건의 취소현금영수증을 [임시저장]합니다.
* - [임시저장] 상태의 현금영수증은 [발행(Issue API)]을 해야만 국세청에 전송됩니다.
* - https://docs.popbill.com/cashbill/java/api#RevokeRegister
*/
// 문서번호, 영문, 숫자, 하이픈(-), 언더바(_)를 조합하여 24자리 문자열로 사업자별로
// 중복되지 않도록 구성
String mgtKey = "20190104-001";
// 원본현금영수증 승인번호
String orgConfirmNum = "820116333";
// 원본현금영수증 거래일자
String orgTradeDate = "20190102";
try {
Response response = cashbillService.revokeRegister(testCorpNum, mgtKey, orgConfirmNum, orgTradeDate);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "revokeRegister_part", method = RequestMethod.GET)
public String revokeRegister_part(Model m) {
/*
* 1건의 (부분)취소현금영수증을 [임시저장]합니다.
* - [임시저장] 상태의 현금영수증은 [발행(Issue API)]을 해야만 국세청에 전송됩니다.
* - https://docs.popbill.com/cashbill/java/api#RevokeRegister
*/
// 문서번호, 영문, 숫자, 하이픈(-), 언더바(_)를 조합하여 24자리 문자열로 사업자별로
// 중복되지 않도록 구성
String mgtKey = "20190104-001";
// 원본현금영수증 승인번호
String orgConfirmNum = "820116333";
// 원본현금영수증 거래일자
String orgTradeDate = "20190103";
// 안내문자 전송여부
Boolean smssendYN = false;
// 부분취소 여부, false 기재시
Boolean isPartCancel = true;
// 취소사유 (integer 타입) / 1-거래취소, 2-오류발급취소 3-기타
Integer cancelType = 1;
// [취소] 공급가액
String supplyCost = "3000";
// [취소] 부가세
String tax = "300";
// [취소] 봉사료
String serviceFee = "0";
// [취소] 합계금액
String totalAmount = "3300";
try {
Response response = cashbillService.revokeRegister(testCorpNum, mgtKey,
orgConfirmNum, orgTradeDate, smssendYN, isPartCancel, cancelType,
supplyCost, tax, serviceFee, totalAmount);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "revokeRegistIssue", method = RequestMethod.GET)
public String revokeRegistIssue(Model m) {
/*
* 1건의 취소현금영수증을 [즉시발행]합니다.
* - 발행일 기준 오후 5시 이전에 발행된 현금영수증은 다음날 오후 2시에 국세청 전송결과를 확인할 수 있습니다.
* - https://docs.popbill.com/cashbill/java/api#RevokeRegistIssue
*/
// 문서번호, 영문, 숫자, 하이픈(-), 언더바(_)를 조합하여 24자리 문자열로 사업자별로
// 중복되지 않도록 구성
String mgtKey = "20190104-001";
// 원본현금영수증 승인번호
String orgConfirmNum = "820116333";
// 원본현금영수증 거래일자
String orgTradeDate = "201901003";
try {
Response response = cashbillService.revokeRegistIssue(testCorpNum, mgtKey, orgConfirmNum, orgTradeDate);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "revokeRegistIssue_part", method = RequestMethod.GET)
public String revokeRegistIssue_part(Model m) {
/*
* 1건의 (부분)취소현금영수증을 [즉시발행]합니다.
* - 발행일 기준 오후 5시 이전에 발행된 현금영수증은 다음날 오후 2시에 국세청 전송결과를 확인할 수 있습니다.
* - https://docs.popbill.com/cashbill/java/api#RevokeRegistIssue
*/
// 문서번호, 영문, 숫자, 하이픈(-), 언더바(_)를 조합하여 24자리 문자열로 사업자별로
// 중복되지 않도록 구성
String mgtKey = "20190104-001";
// 원본현금영수증 승인번호
String orgConfirmNum = "820116333";
// 원본현금영수증 거래일자
String orgTradeDate = "20190103";
// 안내문자 전송여부
Boolean smssendYN = false;
// 발행 메모
String memo = "취소 현금영수증 발행 메모";
// 부분취소 여부
Boolean isPartCancel = true;
// 취소사유 (integer 타입) / 1-거래취소, 2-오류발급취소 3-기타
Integer cancelType = 1;
// [취소] 공급가액
String supplyCost = "3000";
// [취소] 부가세
String tax = "300";
// [취소] 봉사료
String serviceFee = "0";
// [취소] 합계금액
String totalAmount = "3300";
try {
Response response = cashbillService.revokeRegistIssue(testCorpNum, mgtKey,
orgConfirmNum, orgTradeDate, smssendYN, memo, isPartCancel, cancelType,
supplyCost, tax, serviceFee, totalAmount);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "getInfo", method = RequestMethod.GET)
public String getInfo(Model m) {
/*
* 1건의 현금영수증 상태/요약 정보를 확인합니다.
* - https://docs.popbill.com/cashbill/java/api#GetInfo
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
try {
CashbillInfo cashbillInfo = cashbillService.getInfo(testCorpNum, mgtKey);
m.addAttribute("CashbillInfo", cashbillInfo);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "Cashbill/CashbillInfo";
}
@RequestMapping(value = "getInfos", method = RequestMethod.GET)
public String getInfos(Model m) {
/*
* 대량의 현금영수증 상태/요약 정보를 확인합니다. (최대 1000건)
* - https://docs.popbill.com/cashbill/java/api#GetInfos
*/
// 현금영수증 문서번호 배열 최대(1000건)
String[] mgtKeyList = new String[]{"20190104-001", "20190104-002", "20190104-003"};
try {
CashbillInfo[] cashbillInfos = cashbillService.getInfos(testCorpNum, mgtKeyList);
m.addAttribute("CashbillInfos", cashbillInfos);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "Cashbill/CashbillInfo";
}
@RequestMapping(value = "getDetailInfo", method = RequestMethod.GET)
public String getDetailInfo(Model m) {
/*
* 현금영수증 1건의 상세정보를 조회합니다.
* - https://docs.popbill.com/cashbill/java/api#GetDetailInfo
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
try {
Cashbill cashbill = cashbillService.getDetailInfo(testCorpNum, mgtKey);
m.addAttribute("Cashbill", cashbill);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "Cashbill/Cashbill";
}
@RequestMapping(value = "assignMgtKey", method = RequestMethod.GET)
public String assignMgtKey(Model m) {
/*
* 팝빌 사이트에서 작성한 현금영수증에 파트너의 문서번호를 할당합니다.
*/
// 현금영수증 아이템키, 문서 목록조회(Search) API의 반환항목중 ItemKey 참조
String itemKey = "020080716195300001";
// 할당할 문서번호, 숫자, 영문 '-', '_' 조합으로 1~24자리까지
// 사업자번호별 중복없는 고유번호 할당
String mgtKey = "20200807-100";
try {
Response response = cashbillService.assignMgtKey(testCorpNum, itemKey, mgtKey);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "search", method = RequestMethod.GET)
public String search(Model m) {
/*
* 검색조건을 사용하여 현금영수증 목록을 조회합니다.
* - https://docs.popbill.com/cashbill/java/api#Search
*/
// 일자유형, R-등록일자, T-거래일자, I-발행일자
String DType = "T";
// 시작일자, 날짜형식(yyyyMMdd)
String SDate = "20181201";
// 종료일자, 날짜형식(yyyyMMdd)
String EDate = "20190103";
// 상태코드 배열, 2,3번째 자리에 와일드카드(*) 사용 가능
String[] State = {"100", "2**", "3**", "4**"};
// 문서형태 배열, N-승인거래, C-취소거래
String[] TradeType = {"N", "C"};
// 거래구분 배열, P-소득공제용, C-지출증빙용
String[] TradeUsage = {"P", "C"};
// 거래유형 배열, N-일반, B-도서공연, T-대중교통
String[] TradeOpt = {"N", "B", "T"};
// 과세형태 배열, T-과세, N-비과세
String[] TaxationType = {"T", "N"};
// 식별번호 조회, 미기재시 전체조회
String QString = "";
// 페이지 번호
int Page = 1;
// 페이지당 목록개수, 최대 1000건
int PerPage = 20;
// 정렬방향, A-오름차순, D-내림차순
String Order = "D";
try {
CBSearchResult searchResult = cashbillService.search(testCorpNum, DType, SDate, EDate,
State, TradeType, TradeUsage, TradeOpt, TaxationType, QString,
Page, PerPage, Order);
m.addAttribute("SearchResult", searchResult);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "Cashbill/SearchResult";
}
@RequestMapping(value = "getLogs", method = RequestMethod.GET)
public String getLogs(Model m) {
/*
* 현금영수증 상태 변경이력을 확인합니다.
* - https://docs.popbill.com/cashbill/java/api#GetLogs
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
try {
CashbillLog[] cashbillLogs = cashbillService.getLogs(testCorpNum, mgtKey);
m.addAttribute("CashbillLogs", cashbillLogs);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "Cashbill/CashbillLog";
}
@RequestMapping(value = "getURL", method = RequestMethod.GET)
public String getURL(Model m) {
/*
* 팝빌 현금영수증 문서함 팝업 URL을 반환합니다.
* - https://docs.popbill.com/cashbill/java/api#GetURL
*/
// TBOX : 임시문서함 , PBOX : 매출문서함, WRITE : 현금영수증 작성
String TOGO = "WRITE";
try {
String url = cashbillService.getURL(testCorpNum, TOGO);
m.addAttribute("Result", url);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "result";
}
@RequestMapping(value = "getPopUpURL", method = RequestMethod.GET)
public String getPopUpURL(Model m) {
/*
* 1건의 현금영수증 보기 팝업 URL을 반환합니다.
* - https://docs.popbill.com/cashbill/java/api#GetPopUpURL
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
try {
String url = cashbillService.getPopUpURL(testCorpNum, mgtKey);
m.addAttribute("Result", url);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "result";
}
@RequestMapping(value = "getPrintURL", method = RequestMethod.GET)
public String getPrintURL(Model m) {
/*
* 1건의 현금영수증 인쇄팝업 URL을 반환합니다.
* - https://docs.popbill.com/cashbill/java/api#GetPrintURL
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
try {
String url = cashbillService.getPrintURL(testCorpNum, mgtKey);
m.addAttribute("Result", url);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "result";
}
@RequestMapping(value = "getPDFURL", method = RequestMethod.GET)
public String getPDFURL(Model m) {
/*
* 1건의 현금영수증 PDF 다운로드 URL을 반환합니다.
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
try {
String url = cashbillService.getPDFURL(testCorpNum, mgtKey);
m.addAttribute("Result", url);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "result";
}
@RequestMapping(value = "getEPrintURL", method = RequestMethod.GET)
public String getEPrintURL(Model m) {
/*
* 현금영수증 인쇄(공급받는자) URL을 반환합니다.
* - URL 보안정책에 따라 반환된 URL은 30초의 유효시간을 갖습니다.
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
try {
String url = cashbillService.getEPrintURL(testCorpNum, mgtKey);
m.addAttribute("Result", url);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "result";
}
@RequestMapping(value = "getMassPrintURL", method = RequestMethod.GET)
public String getMassPrintURL(Model m) {
/*
* 대량의 현금영수증 인쇄팝업 URL을 반환합니다. (최대 100건)
* - https://docs.popbill.com/cashbill/java/api#GetMassPrintURL
*/
// 문서번호 배열, 최대 100건
String[] mgtKeyList = new String[]{"20190104-001", "20190104-002", "20190104-003"};
try {
String url = cashbillService.getMassPrintURL(testCorpNum, mgtKeyList);
m.addAttribute("Result", url);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "result";
}
@RequestMapping(value = "getMailURL", method = RequestMethod.GET)
public String getMailURL(Model m) {
/*
* 현금영수증 수신메일 링크주소를 반환합니다.
* - https://docs.popbill.com/cashbill/java/api#GetMailURL
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
try {
String url = cashbillService.getMailURL(testCorpNum, mgtKey);
m.addAttribute("Result", url);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "result";
}
@RequestMapping(value = "sendEmail", method = RequestMethod.GET)
public String sendEmail(Model m) {
/*
* 현금영수증 발행 안내메일을 재전송합니다.
* - https://docs.popbill.com/cashbill/java/api#SendEmail
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
// 수신자 메일주소
String receiver = "[email protected]";
try {
Response response = cashbillService.sendEmail(testCorpNum, mgtKey, receiver);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "sendSMS", method = RequestMethod.GET)
public String sendSMS(Model m) {
/*
* 알림문자를 전송합니다. (단문/SMS - 한글 최대 45자)
* - 알림문자 전송시 포인트가 차감됩니다. (전송실패시 환불처리)
* - 전송내역 확인은 "팝빌 로그인" > [문자 팩스] > [문자] > [전송내역] 탭에서 전송결과를 확인할 수 있습니다.
* - https://docs.popbill.com/cashbill/java/api#SendSMS
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
// 발신번호
String sender = "07043042991";
// 수신번호
String receiver = "010111222";
// 문자 전송 내용 (90Byte 초과시 길이가 조정되어 전송)
String contents = "현금영수증 문자메시지 전송 테스트입니다.";
try {
Response response = cashbillService.sendSMS(testCorpNum, mgtKey,
sender, receiver, contents);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "sendFAX", method = RequestMethod.GET)
public String sendFAX(Model m) {
/*
* 현금영수증을 팩스전송합니다.
* - 팩스 전송 요청시 포인트가 차감됩니다. (전송실패시 환불처리)
* - 전송내역 확인은 "팝빌 로그인" > [문자 팩스] > [팩스] > [전송내역] 메뉴에서 전송결과를 확인할 수 있습니다.
* - https://docs.popbill.com/cashbill/java/api#SendFAX
*/
// 현금영수증 문서번호
String mgtKey = "20190104-001";
// 발신자 번호
String sender = "07043042991";
// 수신자 팩스번호
String receiver = "010111222";
try {
Response response = cashbillService.sendFAX(testCorpNum, mgtKey,
sender, receiver);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "listEmailConfig", method = RequestMethod.GET)
public String listEmailConfig(Model m) {
/*
* 현금영수증 관련 메일전송 항목에 대한 전송여부를 목록을 반환합니다.
* - https://docs.popbill.com/cashbill/java/api#ListEmailConfig
*/
try {
EmailSendConfig[] emailSendConfigs = cashbillService.listEmailConfig(testCorpNum);
m.addAttribute("EmailSendConfigs", emailSendConfigs);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "Cashbill/EmailSendConfig";
}
@RequestMapping(value = "updateEmailConfig", method = RequestMethod.GET)
public String updateEmailConfig(Model m) {
/*
* 현금영수증 관련 메일전송 항목에 대한 전송여부를 수정합니다.
* - https://docs.popbill.com/cashbill/java/api#UpdateEmailConfig
*
* 메일전송유형
* CSH_ISSUE : 고객에게 현금영수증이 발행 되었음을 알려주는 메일 입니다.
* CSH_CANCEL : 고객에게 현금영수증이 발행취소 되었음을 알려주는 메일 입니다.
*
*/
// 메일 전송 유형
String emailType = "CSH_ISSUE";
// 전송 여부 (true = 전송, false = 미전송)
Boolean sendYN = true;
try {
Response response = cashbillService.updateEmailConfig(testCorpNum,
emailType, sendYN);
m.addAttribute("Response", response);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "response";
}
@RequestMapping(value = "getUnitCost", method = RequestMethod.GET)
public String getUnitCost(Model m) {
/*
* 현금영수증 발행단가를 확인합니다.
* - https://docs.popbill.com/cashbill/java/api#GetUnitCost
*/
try {
float unitCost = cashbillService.getUnitCost(testCorpNum);
m.addAttribute("Result", unitCost);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "result";
}
@RequestMapping(value = "getChargeInfo", method = RequestMethod.GET)
public String chargeInfo(Model m) {
/*
* 현금영수증 API 서비스 과금정보를 확인합니다.
* - https://docs.popbill.com/cashbill/java/api#GetChargeInfo
*/
try {
ChargeInfo chrgInfo = cashbillService.getChargeInfo(testCorpNum);
m.addAttribute("ChargeInfo", chrgInfo);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "getChargeInfo";
}
}
|
remove unused import.
|
src/main/java/com/popbill/example/CashbillServiceExample.java
|
remove unused import.
|
<ide><path>rc/main/java/com/popbill/example/CashbillServiceExample.java
<ide> import com.popbill.api.cashbill.Cashbill;
<ide> import com.popbill.api.cashbill.CashbillInfo;
<ide> import com.popbill.api.cashbill.CashbillLog;
<del>import com.popbill.api.taxinvoice.MgtKeyType;
<ide>
<ide> /*
<ide> * 팝빌 현금영수증 API 예제.
|
|
JavaScript
|
mit
|
eb210ea5041dcb245b66e892aa92c0f38d2c5a93
| 0 |
twhite96/The-Lens-Cap,twhite96/The-Lens-Cap,twhite96/The-Lens-Cap
|
$(document).ready(function() {
$('.slide').slick({
slidesToShow: 1,
});
});
$('.slide').slick({
infinite: true,
speed: 300,
slidesToShow: 3,
slidesToScroll: 3,
accessibility: true,
arrows: true,
cssEase: 'ease',
dots: true,
autoplay: true,
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 2,
slidesToScroll: 2,
infinite: true,
dots: true
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 2,
slidesToScroll: 2
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
// You can unslick at a given breakpoint now by adding:
// settings: "unslick"
// instead of a settings object
]
});
|
src/slides.js
|
$('.slide').slick({
infinite: true,
speed: 300,
slidesToShow: 3,
slidesToScroll: 3,
accessibility: true,
arrows: true,
cssEase: 'ease',
dots: true,
autoplay: true,
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 2,
slidesToScroll: 2,
infinite: true,
dots: true
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 2,
slidesToScroll: 2
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
// You can unslick at a given breakpoint now by adding:
// settings: "unslick"
// instead of a settings object
]
});
|
Added slides initialization script to slides.js file and out of index.html. Slowed down slider
|
src/slides.js
|
Added slides initialization script to slides.js file and out of index.html. Slowed down slider
|
<ide><path>rc/slides.js
<del>
<add>$(document).ready(function() {
<add> $('.slide').slick({
<add> slidesToShow: 1,
<add> });
<add>});
<ide> $('.slide').slick({
<ide> infinite: true,
<ide> speed: 300,
|
|
Java
|
mit
|
56afaf8a52d2e25d22ffd5578b4fecf65eb1559c
| 0 |
ONSdigital/babbage,ONSdigital/babbage,ONSdigital/babbage,ONSdigital/babbage
|
package com.github.onsdigital.babbage.request.handler.base;
import com.github.onsdigital.babbage.content.client.ContentClient;
import com.github.onsdigital.babbage.request.response.BabbageResponse;
import com.github.onsdigital.babbage.request.response.BabbageStringResponse;
import com.github.onsdigital.babbage.template.TemplateService;
import com.github.onsdigital.content.util.URIUtil;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Map;
import static com.github.onsdigital.babbage.util.RequestUtil.getQueryParameters;
/**
* Render a list page for bulletins under the given URI.
*/
public abstract class ListPageBaseRequestHandler implements RequestHandler {
private final static String DATA_REQUEST = "data";
public static final String CONTENT_TYPE = "text/html";
/**
* The type of page to be returned in the list page
* @return
*/
public abstract String[] getListTypes();
/**
* The template to use when rendering the page.
* @return
*/
public abstract String getTemplateName();
/**
* Return true if the list page is localised to a uri.
* e.g the bulletin page is localised to t3 level uri, whereas the FOI
* list page is not localised and contains all FOI's.
* @return
*/
public abstract boolean useLocalisedUri();
@Override
public BabbageResponse get(String requestedUri, HttpServletRequest request) throws Exception {
System.out.println("List page request from " + this.getClass().getSimpleName() + " for uri: " + requestedUri) ;
BabbageResponse babbageResponse;
String type = URIUtil.resolveRequestType(request.getRequestURI());
// trim /data from the uri if its a data request.
if (type.equals(DATA_REQUEST)) {
requestedUri = URIUtil.removeEndpoint(requestedUri);
}
String uri = "";
if (useLocalisedUri()) {
uri = requestedUri;
}
Map<String, String[]> queryParameters = getQueryParameters(request);
queryParameters.put("type", getListTypes());
try (InputStream dataStream = ContentClient.getInstance().getList(uri, queryParameters).getDataStream()) {
String html = TemplateService.getInstance().renderTemplate(getTemplateName(), dataStream);
babbageResponse = new BabbageStringResponse(html, CONTENT_TYPE);
}
// switch (type) {
// case DATA_REQUEST:
// babbageResponse = new BabbageStringResponse(IOUtils.toString(zebedeeResponse));
// break;
// default:
// SearchResultsPage searchResultsPage = ContentUtil.deserialise(zebedeeResponse, SearchResultsPage.class);
// searchResultsPage.setNavigation(NavigationUtil.getNavigation());
// String html = TemplateService.getInstance().render(searchResultsPage, getTemplateName());
//
// babbageResponse = new BabbageStringResponse(html, CONTENT_TYPE);
// break;
// }
return babbageResponse;
}
}
|
src/main/java/com/github/onsdigital/babbage/request/handler/base/ListPageBaseRequestHandler.java
|
package com.github.onsdigital.babbage.request.handler.base;
import com.github.onsdigital.babbage.content.client.ContentClient;
import com.github.onsdigital.babbage.request.response.BabbageResponse;
import com.github.onsdigital.babbage.request.response.BabbageStringResponse;
import com.github.onsdigital.babbage.template.TemplateService;
import com.github.onsdigital.content.util.URIUtil;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Map;
import static com.github.onsdigital.babbage.util.RequestUtil.getQueryParameters;
/**
* Render a list page for bulletins under the given URI.
*/
public abstract class ListPageBaseRequestHandler implements RequestHandler {
private final static String DATA_REQUEST = "data";
public static final String CONTENT_TYPE = "text/html";
/**
* The type of page to be returned in the list page
* @return
*/
public abstract String[] getListTypes();
/**
* The template to use when rendering the page.
* @return
*/
public abstract String getTemplateName();
/**
* Return true if the list page is localised to a uri.
* e.g the bulletin page is localised to t3 level uri, whereas the FOI
* list page is not localised and contains all FOI's.
* @return
*/
public abstract boolean useLocalisedUri();
@Override
public BabbageResponse get(String requestedUri, HttpServletRequest request) throws Exception {
BabbageResponse babbageResponse;
String type = URIUtil.resolveRequestType(request.getRequestURI());
// trim /data from the uri if its a data request.
if (type.equals(DATA_REQUEST)) {
requestedUri = URIUtil.removeEndpoint(requestedUri);
}
String uri = "";
if (useLocalisedUri()) {
uri = requestedUri;
}
Map<String, String[]> queryParameters = getQueryParameters(request);
queryParameters.put("type", getListTypes());
try (InputStream dataStream = ContentClient.getInstance().getList(uri, queryParameters).getDataStream()) {
String html = TemplateService.getInstance().renderTemplate(getTemplateName(), dataStream);
babbageResponse = new BabbageStringResponse(html, CONTENT_TYPE);
}
// switch (type) {
// case DATA_REQUEST:
// babbageResponse = new BabbageStringResponse(IOUtils.toString(zebedeeResponse));
// break;
// default:
// SearchResultsPage searchResultsPage = ContentUtil.deserialise(zebedeeResponse, SearchResultsPage.class);
// searchResultsPage.setNavigation(NavigationUtil.getNavigation());
// String html = TemplateService.getInstance().render(searchResultsPage, getTemplateName());
//
// babbageResponse = new BabbageStringResponse(html, CONTENT_TYPE);
// break;
// }
return babbageResponse;
}
}
|
Added debug output.
|
src/main/java/com/github/onsdigital/babbage/request/handler/base/ListPageBaseRequestHandler.java
|
Added debug output.
|
<ide><path>rc/main/java/com/github/onsdigital/babbage/request/handler/base/ListPageBaseRequestHandler.java
<ide> @Override
<ide> public BabbageResponse get(String requestedUri, HttpServletRequest request) throws Exception {
<ide>
<add> System.out.println("List page request from " + this.getClass().getSimpleName() + " for uri: " + requestedUri) ;
<add>
<ide> BabbageResponse babbageResponse;
<ide> String type = URIUtil.resolveRequestType(request.getRequestURI());
<ide>
|
|
JavaScript
|
mit
|
eb007bb65f496715d0d29f2d25ef5fb734944bb0
| 0 |
azu/Unhandled-Rejection-Tracking
|
// LICENSE : MIT
"use strict";
var Promise = require("bluebird");
process.on("unhandledRejection", function (reason, promise) {
console.log("unhandledRejection", reason, promise);
});
function doAsync() {
return new Promise(function () {
throw Error("doAsyncで何か例外が起きた")
});
}
doAsync();// catchしてない => unhandledRejection
|
unhandled-rejection.js
|
// LICENSE : MIT
"use strict";
var Promise = require("bluebird");
process.on("unhandledRejection", function (reason, promise) {
console.log("unhandledRejection");
});
process.on("rejectionHandled", function (promise) {
console.log("rejectionHandled");
});
function doAsync(){
return new Promise(function () {
throw Error("doAsyncで何か例外が起きた")
});
}
doAsync();// catchしてない => unhandledRejection
|
fix example
|
unhandled-rejection.js
|
fix example
|
<ide><path>nhandled-rejection.js
<ide> "use strict";
<ide> var Promise = require("bluebird");
<ide> process.on("unhandledRejection", function (reason, promise) {
<del> console.log("unhandledRejection");
<add> console.log("unhandledRejection", reason, promise);
<ide> });
<ide>
<del>process.on("rejectionHandled", function (promise) {
<del> console.log("rejectionHandled");
<del>});
<del>
<del>function doAsync(){
<add>function doAsync() {
<ide> return new Promise(function () {
<ide> throw Error("doAsyncで何か例外が起きた")
<ide> });
|
|
Java
|
lgpl-2.1
|
0f7fd4a91412b6c530bb8c7e6f05f582b7e9c1b7
| 0 |
samskivert/samskivert,samskivert/samskivert
|
//
// $Id$
//
// samskivert library - useful routines for java programs
// Copyright (C) 2001-2010 Michael Bayne, et al.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.util;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
* Provides utility routines to simplify obtaining randomized values.
*
* Each instance of Randoms is completely thread safe, but will share an underlying
* {@link Random} object. If you wish to have a private stream of pseudorandom numbers,
* use the {@link #with} factory.
*/
public class Randoms
{
/** A default Randoms that can be safely shared by any caller. */
public static final Randoms RAND = with(new Random());
/**
* A factory to create a new Randoms object.
*/
public static Randoms with (Random rand)
{
return new Randoms(rand);
}
/**
* Get a thread-local Randoms instance that will not contend with any other thread
* for random number generation.
*
* <p><b>Note:</b> while all Randoms instances are thread-safe, normally they use a
* java.util.Random internally that must protect against multiple threads generating
* psuedorandom numbers with it simultaneously. This method will return a Randoms
* that uses an internal Random subclass with no such safeguards, resulting in much
* less overhead. However, you should probably not store a reference to the result,
* but instead always use it immediately as in the following example:
* <pre style="code">
* Puppy pick = Randoms.threadLocal().pick(Puppy.LITTER, null);
* </pre>
*/
public static Randoms threadLocal ()
{
return _localRandoms.get();
}
/**
* Returns a pseudorandom, uniformly distributed <code>int</code> value between 0 (inclusive)
* and the specified value (exclusive).
*
* @param high the high value limiting the random number sought.
*
* @throws IllegalArgumentException if <code>high</code> is not positive.
*/
public int getInt (int high)
{
return _r.nextInt(high);
}
/**
* Returns a pseudorandom, uniformly distributed <code>int</code> value between
* <code>low</code> (inclusive) and <code>high</code> (exclusive).
*
* @throws IllegalArgumentException if <code>high - low</code> is not positive.
*/
public int getInRange (int low, int high)
{
return low + _r.nextInt(high - low);
}
/**
* Returns a pseudorandom, uniformly distributed float value between 0.0 (inclusive) and the
* specified value (exclusive).
*
* @param high the high value limiting the random number sought.
*/
public float getFloat (float high)
{
return _r.nextFloat() * high;
}
/**
* Returns a pseudorandom, uniformly distributed <code>float</code> value between
* <code>low</code> (inclusive) and <code>high</code> (exclusive).
*/
public float getInRange (float low, float high)
{
return low + (_r.nextFloat() * (high - low));
}
/**
* Returns true approximately one in n times.
*
* @throws IllegalArgumentException if <code>n</code> is not positive.
*/
public boolean getChance (int n)
{
return (0 == _r.nextInt(n));
}
/**
* Has a probability p of returning true.
*/
public boolean getProbability (float p)
{
return _r.nextFloat() < p;
}
/**
* Returns true or false with approximately even distribution.
*/
public boolean getBoolean ()
{
return _r.nextBoolean();
}
/**
* Returns a key from the supplied map according to a probability computed as
* the key's value divided by the total of all the key's values.
*
* @throws NullPointerException if the map is null.
* @throws IllegalArgumentException if the sum of the weights is not positive.
*/
public <T> T getWeighted (Map<T, Integer> valuesToWeights)
{
// TODO: validation?
int idx = _r.nextInt(Folds.sum(0, valuesToWeights.values()));
for (Map.Entry<T, Integer> entry : valuesToWeights.entrySet()) {
idx -= entry.getValue();
if (idx < 0) {
return entry.getKey();
}
}
throw new AssertionError("Not possible");
}
/**
* Pick a random element from the specified Iterator, or return <code>ifEmpty</code>
* if it is empty.
*
* <p><b>Implementation note:</b> because the total size of the Iterator is not known,
* the random number generator is queried after the second element and every element
* thereafter.
*
* @throws NullPointerException if the iterator is null.
*/
public <T> T pick (Iterator<? extends T> iterator, T ifEmpty)
{
if (!iterator.hasNext()) {
return ifEmpty;
}
T pick = iterator.next();
for (int count = 2; iterator.hasNext(); count++) {
T next = iterator.next();
if (0 == _r.nextInt(count)) {
pick = next;
}
}
return pick;
}
/**
* Pick a random element from the specified Iterable, or return <code>ifEmpty</code>
* if it is empty.
*
* <p><b>Implementation note:</b> optimized implementations are used if the Iterable
* is a List or Collection. Otherwise, it behaves as if calling {@link #pick(Iterator)} with
* the Iterable's Iterator.
*
* @throws NullPointerException if the iterable is null.
*/
public <T> T pick (Iterable<? extends T> iterable, T ifEmpty)
{
return pickPluck(iterable, ifEmpty, false);
}
/**
* Pluck (remove) a random element from the specified Iterable, or return <code>ifEmpty</code>
* if it is empty.
*
* <p><b>Implementation note:</b> optimized implementations are used if the Iterable
* is a List or Collection. Otherwise, two Iterators are created from the Iterable
* and a random number is generated after the second element and all beyond.
*
* @throws NullPointerException if the iterable is null.
* @throws UnsupportedOperationException if the iterable is unmodifiable or its Iterator
* does not support {@link Iterator#remove()}.
*/
public <T> T pluck (Iterable<? extends T> iterable, T ifEmpty)
{
return pickPluck(iterable, ifEmpty, true);
}
/**
* Construct a Randoms.
*/
protected Randoms (Random rand)
{
_r = rand;
}
/**
* Shared code for pick and pluck.
*/
@SuppressWarnings("unchecked")
protected <T> T pickPluck (Iterable<? extends T> iterable, T ifEmpty, boolean remove)
{
if (iterable instanceof Collection) {
// optimized path for Collection
Collection<? extends T> coll = (Collection<? extends T>)iterable;
int size = coll.size();
if (size == 0) {
return ifEmpty;
}
if (coll instanceof List) {
// extra-special optimized path for Lists
List<? extends T> list = (List<? extends T>)coll;
int idx = _r.nextInt(size);
return (T) (remove ? list.remove(idx) : list.get(idx));
}
// for other Collections, we must iterate
Iterator<? extends T> it = coll.iterator();
for (int idx = _r.nextInt(size); idx > 0; idx--) {
it.next();
}
try {
return it.next();
} finally {
if (remove) {
it.remove();
}
}
}
if (!remove) {
return pick(iterable.iterator(), ifEmpty);
}
// from here on out, we're doing a pluck with a complicated two-iterator solution
Iterator<? extends T> it = iterable.iterator();
if (!it.hasNext()) {
return ifEmpty;
}
Iterator<? extends T> lagIt = iterable.iterator();
T pick = it.next();
lagIt.next();
for (int count = 2, lag = 1; it.hasNext(); count++, lag++) {
T next = it.next();
if (0 == _r.nextInt(count)) {
pick = next;
for ( ; lag > 0; lag--) {
lagIt.next();
}
}
}
lagIt.remove();
return pick;
}
/** The random number generator. */
protected final Random _r;
/** A ThreadLocal for accessing a thread-local version of Randoms. */
protected static final ThreadLocal<Randoms> _localRandoms = new ThreadLocal<Randoms>() {
@Override
public Randoms initialValue () {
return with(new ThreadLocalRandom());
}
};
/*
* TODO: This can be updated and this inner class removed
* when the samskivert library is JDK 1.7 compatible.
*-----------------------------------------------------------------
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*
* A random number generator isolated to the current thread. Like the
* global {@link java.util.Random} generator used by the {@link
* java.lang.Math} class, a {@code ThreadLocalRandom} is initialized
* with an internally generated seed that may not otherwise be
* modified. When applicable, use of {@code ThreadLocalRandom} rather
* than shared {@code Random} objects in concurrent programs will
* typically encounter much less overhead and contention. Use of
* {@code ThreadLocalRandom} is particularly appropriate when multiple
* tasks (for example, each a {@link ForkJoinTask}) use random numbers
* in parallel in thread pools.
*
* <p>This class also provides additional commonly used bounded random
* generation methods.
*
* @since 1.7
* @author Doug Lea
*/
protected static class ThreadLocalRandom extends Random {
// same constants as Random, but must be redeclared because private
private final static long multiplier = 0x5DEECE66DL;
private final static long addend = 0xBL;
private final static long mask = (1L << 48) - 1;
/**
* The random seed. We can't use super.seed.
*/
private long rnd;
/**
* Initialization flag to permit calls to setSeed to succeed only
* while executing the Random constructor. We can't allow others
* since it would cause setting seed in one part of a program to
* unintentionally impact other usages by the thread.
*/
boolean initialized;
// Padding to help avoid memory contention among seed updates in
// different TLRs in the common case that they are located near
// each other.
@SuppressWarnings("unused")
private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7;
/**
* Constructor called only by localRandom.initialValue.
*/
ThreadLocalRandom() {
super();
initialized = true;
}
/**
* Throws {@code UnsupportedOperationException}. Setting seeds in
* this generator is not supported.
*
* @throws UnsupportedOperationException always
*/
@Override
public void setSeed(long seed) {
if (initialized)
throw new UnsupportedOperationException();
rnd = (seed ^ multiplier) & mask;
}
@Override
protected int next(int bits) {
rnd = (rnd * multiplier + addend) & mask;
return (int) (rnd >>> (48-bits));
}
// as of JDK 1.6, this method does not exist in java.util.Random
// /**
// * Returns a pseudorandom, uniformly distributed value between the
// * given least value (inclusive) and bound (exclusive).
// *
// * @param least the least value returned
// * @param bound the upper bound (exclusive)
// * @throws IllegalArgumentException if least greater than or equal
// * to bound
// * @return the next value
// */
// public int nextInt(int least, int bound) {
// if (least >= bound)
// throw new IllegalArgumentException();
// return nextInt(bound - least) + least;
// }
/**
* Returns a pseudorandom, uniformly distributed value
* between 0 (inclusive) and the specified value (exclusive).
*
* @param n the bound on the random number to be returned. Must be
* positive.
* @return the next value
* @throws IllegalArgumentException if n is not positive
*/
public long nextLong(long n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
// Divide n by two until small enough for nextInt. On each
// iteration (at most 31 of them but usually much less),
// randomly choose both whether to include high bit in result
// (offset) and whether to continue with the lower vs upper
// half (which makes a difference only if odd).
long offset = 0;
while (n >= Integer.MAX_VALUE) {
int bits = next(2);
long half = n >>> 1;
long nextn = ((bits & 2) == 0) ? half : n - half;
if ((bits & 1) == 0)
offset += n - nextn;
n = nextn;
}
return offset + nextInt((int) n);
}
/**
* Returns a pseudorandom, uniformly distributed value between the
* given least value (inclusive) and bound (exclusive).
*
* @param least the least value returned
* @param bound the upper bound (exclusive)
* @return the next value
* @throws IllegalArgumentException if least greater than or equal
* to bound
*/
public long nextLong(long least, long bound) {
if (least >= bound)
throw new IllegalArgumentException();
return nextLong(bound - least) + least;
}
/**
* Returns a pseudorandom, uniformly distributed {@code double} value
* between 0 (inclusive) and the specified value (exclusive).
*
* @param n the bound on the random number to be returned. Must be
* positive.
* @return the next value
* @throws IllegalArgumentException if n is not positive
*/
public double nextDouble(double n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
return nextDouble() * n;
}
/**
* Returns a pseudorandom, uniformly distributed value between the
* given least value (inclusive) and bound (exclusive).
*
* @param least the least value returned
* @param bound the upper bound (exclusive)
* @return the next value
* @throws IllegalArgumentException if least greater than or equal
* to bound
*/
public double nextDouble(double least, double bound) {
if (least >= bound)
throw new IllegalArgumentException();
return nextDouble() * (bound - least) + least;
}
private static final long serialVersionUID = -5851777807851030925L;
}
}
|
src/main/java/com/samskivert/util/Randoms.java
|
//
// $Id$
//
// samskivert library - useful routines for java programs
// Copyright (C) 2001-2010 Michael Bayne, et al.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.util;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
* Provides utility routines to simplify obtaining randomized values.
*
* Each instance of Randoms is completely thread safe, but will share an underlying
* {@link Random} object. If you wish to have a private stream of pseudorandom numbers,
* use the {@link #with} factory.
*/
public class Randoms
{
/** A default Randoms that can be safely shared by any caller. */
public static final Randoms RAND = with(new Random());
/**
* A factory to create a new Randoms object.
*/
public static Randoms with (Random rand)
{
return new Randoms(rand);
}
/**
* Get a thread-local Randoms instance that will not contend with any other thread
* for random number generation.
*
* <p><b>Note:</b> while all Randoms instances are thread-safe, normally they use a
* java.util.Random internally that must protect against multiple threads generating
* psuedorandom numbers with it simultaneously. This method will return a Randoms
* that uses an internal Random subclass with no such safeguards, resulting in much
* less overhead. However, you should probably not store a reference to the result,
* but instead always use it immediately as in the following example:
* <pre style="code">
* Puppy pick = Randoms.threadLocal().pick(Puppy.LITTER, null);
* </pre>
*/
public static Randoms threadLocal ()
{
return _localRandoms.get();
}
/**
* Returns a pseudorandom, uniformly distributed <code>int</code> value between 0 (inclusive)
* and the specified value (exclusive).
*
* @param high the high value limiting the random number sought.
*
* @throws IllegalArgumentException if <code>high</code> is not positive.
*/
public int getInt (int high)
{
return _r.nextInt(high);
}
/**
* Returns a pseudorandom, uniformly distributed <code>int</code> value between
* <code>low</code> (inclusive) and <code>high</code> (exclusive).
*
* @throws IllegalArgumentException if <code>high - low</code> is not positive.
*/
public int getInRange (int low, int high)
{
return low + _r.nextInt(high - low);
}
/**
* Returns a pseudorandom, uniformly distributed float value between 0.0 (inclusive) and the
* specified value (exclusive).
*
* @param high the high value limiting the random number sought.
*/
public float getFloat (float high)
{
return _r.nextFloat() * high;
}
/**
* Returns a pseudorandom, uniformly distributed <code>float</code> value between
* <code>low</code> (inclusive) and <code>high</code> (exclusive).
*/
public float getInRange (float low, float high)
{
return low + (_r.nextFloat() * (high - low));
}
/**
* Returns true approximately one in n times.
*
* @throws IllegalArgumentException if <code>n</code> is not positive.
*/
public boolean getChance (int n)
{
return (0 == _r.nextInt(n));
}
/**
* Has a probability p of returning true.
*/
public boolean getProbability (float p)
{
return _r.nextFloat() < p;
}
/**
* Returns true or false with approximately even distribution.
*/
public boolean getBoolean ()
{
return _r.nextBoolean();
}
/**
* Returns a key from the supplied map according to a probability computed as
* the key's value divided by the total of all the key's values.
*
* @throws NullPointerException if the map is null.
* @throws IllegalArgumentException if the sum of the weights is not positive.
*/
public <T> T getWeighted (Map<T, Integer> valuesToWeights)
{
// TODO: validation?
int idx = _r.nextInt(Folds.sum(0, valuesToWeights.values()));
for (Map.Entry<T, Integer> entry : valuesToWeights.entrySet()) {
idx -= entry.getValue();
if (idx < 0) {
return entry.getKey();
}
}
throw new AssertionError("Not possible");
}
/**
* Pick a random element from the specified Iterator, or return <code>ifEmpty</code>
* if it is empty.
*
* <p><b>Implementation note:</b> because the total size of the Iterator is not known,
* the random number generator is queried after the second element and every element
* thereafter.
*
* @throws NullPointerException if the iterator is null.
*/
public <T> T pick (Iterator<? extends T> iterator, T ifEmpty)
{
if (!iterator.hasNext()) {
return ifEmpty;
}
T pick = iterator.next();
for (int count = 2; iterator.hasNext(); count++) {
T next = iterator.next();
if (0 == _r.nextInt(count)) {
pick = next;
}
}
return pick;
}
/**
* Pick a random element from the specified Iterable, or return <code>ifEmpty</code>
* if it is empty.
*
* <p><b>Implementation note:</b> optimized implementations are used if the Iterable
* is a List or Collection. Otherwise, it behaves as if calling {@link #pick(Iterator)} with
* the Iterable's Iterator.
*
* @throws NullPointerException if the iterable is null.
*/
public <T> T pick (Iterable<? extends T> iterable, T ifEmpty)
{
return pickPluck(iterable, ifEmpty, false);
}
/**
* Pluck (remove) a random element from the specified Iterable, or return <code>ifEmpty</code>
* if it is empty.
*
* <p><b>Implementation note:</b> optimized implementations are used if the Iterable
* is a List or Collection. Otherwise, two Iterators are created from the Iterable
* and a random number is generated after the second element and all beyond.
*
* @throws NullPointerException if the iterable is null.
* @throws UnsupportedOperationException if the iterable is unmodifiable or its Iterator
* does not support {@link Iterator#remove()}.
*/
public <T> T pluck (Iterable<? extends T> iterable, T ifEmpty)
{
return pickPluck(iterable, ifEmpty, true);
}
/**
* Construct a Randoms.
*/
protected Randoms (Random rand)
{
_r = rand;
}
/**
* Shared code for pick and pluck.
*/
protected <T> T pickPluck (Iterable<? extends T> iterable, T ifEmpty, boolean remove)
{
if (iterable instanceof Collection) {
// optimized path for Collection
Collection<? extends T> coll = (Collection<? extends T>)iterable;
int size = coll.size();
if (size == 0) {
return ifEmpty;
}
if (coll instanceof List) {
// extra-special optimized path for Lists
List<? extends T> list = (List<? extends T>)coll;
int idx = _r.nextInt(size);
return remove ? list.remove(idx) : list.get(idx);
}
// for other Collections, we must iterate
Iterator<? extends T> it = coll.iterator();
for (int idx = _r.nextInt(size); idx > 0; idx--) {
it.next();
}
try {
return it.next();
} finally {
if (remove) {
it.remove();
}
}
}
if (!remove) {
return pick(iterable.iterator(), ifEmpty);
}
// from here on out, we're doing a pluck with a complicated two-iterator solution
Iterator<? extends T> it = iterable.iterator();
if (!it.hasNext()) {
return ifEmpty;
}
Iterator<? extends T> lagIt = iterable.iterator();
T pick = it.next();
lagIt.next();
for (int count = 2, lag = 1; it.hasNext(); count++, lag++) {
T next = it.next();
if (0 == _r.nextInt(count)) {
pick = next;
for ( ; lag > 0; lag--) {
lagIt.next();
}
}
}
lagIt.remove();
return pick;
}
/** The random number generator. */
protected final Random _r;
/** A ThreadLocal for accessing a thread-local version of Randoms. */
protected static final ThreadLocal<Randoms> _localRandoms = new ThreadLocal<Randoms>() {
@Override
public Randoms initialValue () {
return with(new ThreadLocalRandom());
}
};
/*
* TODO: This can be updated and this inner class removed
* when the samskivert library is JDK 1.7 compatible.
*-----------------------------------------------------------------
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*
* A random number generator isolated to the current thread. Like the
* global {@link java.util.Random} generator used by the {@link
* java.lang.Math} class, a {@code ThreadLocalRandom} is initialized
* with an internally generated seed that may not otherwise be
* modified. When applicable, use of {@code ThreadLocalRandom} rather
* than shared {@code Random} objects in concurrent programs will
* typically encounter much less overhead and contention. Use of
* {@code ThreadLocalRandom} is particularly appropriate when multiple
* tasks (for example, each a {@link ForkJoinTask}) use random numbers
* in parallel in thread pools.
*
* <p>This class also provides additional commonly used bounded random
* generation methods.
*
* @since 1.7
* @author Doug Lea
*/
protected static class ThreadLocalRandom extends Random {
// same constants as Random, but must be redeclared because private
private final static long multiplier = 0x5DEECE66DL;
private final static long addend = 0xBL;
private final static long mask = (1L << 48) - 1;
/**
* The random seed. We can't use super.seed.
*/
private long rnd;
/**
* Initialization flag to permit calls to setSeed to succeed only
* while executing the Random constructor. We can't allow others
* since it would cause setting seed in one part of a program to
* unintentionally impact other usages by the thread.
*/
boolean initialized;
// Padding to help avoid memory contention among seed updates in
// different TLRs in the common case that they are located near
// each other.
@SuppressWarnings("unused")
private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7;
/**
* Constructor called only by localRandom.initialValue.
*/
ThreadLocalRandom() {
super();
initialized = true;
}
/**
* Throws {@code UnsupportedOperationException}. Setting seeds in
* this generator is not supported.
*
* @throws UnsupportedOperationException always
*/
@Override
public void setSeed(long seed) {
if (initialized)
throw new UnsupportedOperationException();
rnd = (seed ^ multiplier) & mask;
}
@Override
protected int next(int bits) {
rnd = (rnd * multiplier + addend) & mask;
return (int) (rnd >>> (48-bits));
}
// as of JDK 1.6, this method does not exist in java.util.Random
// /**
// * Returns a pseudorandom, uniformly distributed value between the
// * given least value (inclusive) and bound (exclusive).
// *
// * @param least the least value returned
// * @param bound the upper bound (exclusive)
// * @throws IllegalArgumentException if least greater than or equal
// * to bound
// * @return the next value
// */
// public int nextInt(int least, int bound) {
// if (least >= bound)
// throw new IllegalArgumentException();
// return nextInt(bound - least) + least;
// }
/**
* Returns a pseudorandom, uniformly distributed value
* between 0 (inclusive) and the specified value (exclusive).
*
* @param n the bound on the random number to be returned. Must be
* positive.
* @return the next value
* @throws IllegalArgumentException if n is not positive
*/
public long nextLong(long n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
// Divide n by two until small enough for nextInt. On each
// iteration (at most 31 of them but usually much less),
// randomly choose both whether to include high bit in result
// (offset) and whether to continue with the lower vs upper
// half (which makes a difference only if odd).
long offset = 0;
while (n >= Integer.MAX_VALUE) {
int bits = next(2);
long half = n >>> 1;
long nextn = ((bits & 2) == 0) ? half : n - half;
if ((bits & 1) == 0)
offset += n - nextn;
n = nextn;
}
return offset + nextInt((int) n);
}
/**
* Returns a pseudorandom, uniformly distributed value between the
* given least value (inclusive) and bound (exclusive).
*
* @param least the least value returned
* @param bound the upper bound (exclusive)
* @return the next value
* @throws IllegalArgumentException if least greater than or equal
* to bound
*/
public long nextLong(long least, long bound) {
if (least >= bound)
throw new IllegalArgumentException();
return nextLong(bound - least) + least;
}
/**
* Returns a pseudorandom, uniformly distributed {@code double} value
* between 0 (inclusive) and the specified value (exclusive).
*
* @param n the bound on the random number to be returned. Must be
* positive.
* @return the next value
* @throws IllegalArgumentException if n is not positive
*/
public double nextDouble(double n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
return nextDouble() * n;
}
/**
* Returns a pseudorandom, uniformly distributed value between the
* given least value (inclusive) and bound (exclusive).
*
* @param least the least value returned
* @param bound the upper bound (exclusive)
* @return the next value
* @throws IllegalArgumentException if least greater than or equal
* to bound
*/
public double nextDouble(double least, double bound) {
if (least >= bound)
throw new IllegalArgumentException();
return nextDouble() * (bound - least) + least;
}
private static final long serialVersionUID = -5851777807851030925L;
}
}
|
Revert the meat of r2908.
Maybe mdb is using a newer compiler that is behaving correctly,
but my 1.6 freaks out without these.
git-svn-id: 64ebf368729f38804935acb7146e017e0f909c6b@2910 6335cc39-0255-0410-8fd6-9bcaacd3b74c
|
src/main/java/com/samskivert/util/Randoms.java
|
Revert the meat of r2908. Maybe mdb is using a newer compiler that is behaving correctly, but my 1.6 freaks out without these.
|
<ide><path>rc/main/java/com/samskivert/util/Randoms.java
<ide> /**
<ide> * Shared code for pick and pluck.
<ide> */
<add> @SuppressWarnings("unchecked")
<ide> protected <T> T pickPluck (Iterable<? extends T> iterable, T ifEmpty, boolean remove)
<ide> {
<ide> if (iterable instanceof Collection) {
<ide> // extra-special optimized path for Lists
<ide> List<? extends T> list = (List<? extends T>)coll;
<ide> int idx = _r.nextInt(size);
<del> return remove ? list.remove(idx) : list.get(idx);
<add> return (T) (remove ? list.remove(idx) : list.get(idx));
<ide> }
<ide> // for other Collections, we must iterate
<ide> Iterator<? extends T> it = coll.iterator();
|
|
Java
|
apache-2.0
|
144f5259622b1fe99876fbcc1a4da8f24772b51f
| 0 |
mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile
|
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2017 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package ti.modules.titanium.media;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiBaseActivity;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.TiLifecycle.OnLifecycleEvent;
import org.appcelerator.titanium.TiLifecycle.OnWindowFocusChangedEvent;
import org.appcelerator.titanium.util.TiConvert;
import ti.modules.titanium.filesystem.FileProxy;
import android.app.Activity;
import android.media.AudioManager;
@Kroll.proxy(creatableInModule=MediaModule.class, propertyAccessors={
TiC.PROPERTY_VOLUME
})
public class AudioPlayerProxy extends KrollProxy
implements OnLifecycleEvent, OnWindowFocusChangedEvent
{
private static final String TAG = "AudioPlayerProxy";
@Kroll.constant public static final int STATE_BUFFERING = TiSound.STATE_BUFFERING;
@Kroll.constant public static final int STATE_INITIALIZED = TiSound.STATE_INITIALIZED;
@Kroll.constant public static final int STATE_PAUSED = TiSound.STATE_PAUSED;
@Kroll.constant public static final int STATE_PLAYING = TiSound.STATE_PLAYING;
@Kroll.constant public static final int STATE_STARTING = TiSound.STATE_STARTING;
@Kroll.constant public static final int STATE_STOPPED = TiSound.STATE_STOPPED;
@Kroll.constant public static final int STATE_STOPPING = TiSound.STATE_STOPPING;
@Kroll.constant public static final int STATE_WAITING_FOR_DATA = TiSound.STATE_WAITING_FOR_DATA;
@Kroll.constant public static final int STATE_WAITING_FOR_QUEUE = TiSound.STATE_WAITING_FOR_QUEUE;
@Kroll.constant public static final int STREAM_ALARM = AudioManager.STREAM_ALARM;
@Kroll.constant public static final int STREAM_DTMF = AudioManager.STREAM_DTMF;
@Kroll.constant public static final int STREAM_MUSIC = AudioManager.STREAM_MUSIC;
@Kroll.constant public static final int STREAM_NOTIFICATION = AudioManager.STREAM_NOTIFICATION;
@Kroll.constant public static final int STREAM_RING = AudioManager.STREAM_RING;
@Kroll.constant public static final int STREAM_SYSTEM = AudioManager.STREAM_SYSTEM;
@Kroll.constant public static final int STREAM_VOICE_CALL = AudioManager.STREAM_VOICE_CALL;
protected TiSound snd;
private boolean windowFocused;
private boolean resumeInOnWindowFocusChanged;
public AudioPlayerProxy()
{
super();
// TODO - we shouldnt need this as this proxy is created only from the runtime - double check
// TODO this needs to happen post-set
//((TiBaseActivity)getActivity()).addOnLifecycleEventListener(this);
defaultValues.put(TiC.PROPERTY_VOLUME, 1.0f);
defaultValues.put(TiC.PROPERTY_TIME,0);
defaultValues.put(TiC.PROPERTY_AUDIO_STREAM_TYPE, AudioManager.STREAM_MUSIC);
}
@Override
protected void initActivity(Activity activity) {
super.initActivity(activity);
((TiBaseActivity) getActivity()).addOnLifecycleEventListener(this);
((TiBaseActivity) getActivity()).addOnWindowFocusChangedEventListener(this);
}
@Override
public void handleCreationDict(KrollDict options) {
super.handleCreationDict(options);
if (options.containsKey(TiC.PROPERTY_URL)) {
setProperty(TiC.PROPERTY_URL, resolveUrl(null, TiConvert.toString(options, TiC.PROPERTY_URL)));
} else if (options.containsKey(TiC.PROPERTY_SOUND)) {
FileProxy fp = (FileProxy) options.get(TiC.PROPERTY_SOUND);
if (fp != null) {
String url = fp.getNativePath();
setProperty(TiC.PROPERTY_URL, url);
}
}
if (options.containsKey(TiC.PROPERTY_ALLOW_BACKGROUND)) {
setProperty(TiC.PROPERTY_ALLOW_BACKGROUND, options.get(TiC.PROPERTY_ALLOW_BACKGROUND));
}
if (options.containsKey(TiC.PROPERTY_AUDIO_FOCUS)) {
boolean audioFocus = TiConvert.toBoolean(options.get(TiC.PROPERTY_AUDIO_FOCUS));
setProperty(TiC.PROPERTY_AUDIO_FOCUS, audioFocus);
TiSound.audioFocus = audioFocus;
}
Log.i(TAG, "Creating audio player proxy for url: " + TiConvert.toString(getProperty(TiC.PROPERTY_URL)),
Log.DEBUG_MODE);
}
@Kroll.getProperty @Kroll.method
public String getUrl() {
return TiConvert.toString(getProperty(TiC.PROPERTY_URL));
}
@Kroll.setProperty @Kroll.method
public void setUrl(String url) {
if (url != null) {
setProperty(TiC.PROPERTY_URL, resolveUrl(null, TiConvert.toString(url)));
}
}
@Kroll.getProperty @Kroll.method
public int getDuration() {
TiSound s = getSound();
if (s != null) {
return s.getDuration();
}
return 0;
}
@Kroll.method @Kroll.getProperty
public int getAudioStreamType() {
return TiConvert.toInt(getProperty(TiC.PROPERTY_AUDIO_STREAM_TYPE));
}
@Kroll.method @Kroll.setProperty
public void setAudioStreamType(int val) {
setProperty(TiC.PROPERTY_AUDIO_STREAM_TYPE, val);
}
@Kroll.getProperty @Kroll.method
public boolean isPlaying() {
TiSound s = getSound();
if (s != null) {
return s.isPlaying();
}
return false;
}
@Kroll.getProperty @Kroll.method
public boolean isPaused() {
TiSound s = getSound();
if (s != null) {
return s.isPaused();
}
return false;
}
// An alias for play so that
@Kroll.method
public void start() {
play();
}
@Kroll.method
public void play() {
TiSound s = getSound();
if (s != null) {
s.play();
}
}
@Kroll.method
public void pause() {
TiSound s = getSound();
if (s != null) {
s.pause();
}
}
@Kroll.method
public void release() {
TiSound s = getSound();
if (s != null) {
s.release();
snd = null;
}
}
@Kroll.method
public void destroy() {
release();
}
@Kroll.method
public void stop() {
TiSound s = getSound();
if (s != null) {
s.stop();
}
}
@Kroll.method
public int getAudioSessionId() {
TiSound s = getSound();
if (s != null) {
return s.getAudioSessionId();
}
return 0;
}
@Kroll.method @Kroll.getProperty
public double getTime() {
TiSound s = getSound();
if (s != null) {
int time = s.getTime();
setProperty(TiC.PROPERTY_TIME, time);
}
return TiConvert.toDouble(getProperty(TiC.PROPERTY_TIME));
}
@Kroll.method @Kroll.setProperty
public void setTime(Object pos) {
if (pos != null) {
TiSound s = getSound();
if (s != null) {
s.setTime(TiConvert.toInt(pos));
} else {
setProperty(TiC.PROPERTY_TIME, TiConvert.toDouble(pos));
}
}
}
protected TiSound getSound()
{
if (snd == null) {
snd = new TiSound(this);
setModelListener(snd);
}
return snd;
}
private boolean allowBackground() {
boolean allow = false;
if (hasProperty(TiC.PROPERTY_ALLOW_BACKGROUND)) {
allow = TiConvert.toBoolean(getProperty(TiC.PROPERTY_ALLOW_BACKGROUND));
}
return allow;
}
public void onStart(Activity activity) {
}
public void onResume(Activity activity)
{
if (windowFocused && !allowBackground()) {
if (snd != null) {
snd.onResume();
}
} else {
resumeInOnWindowFocusChanged = true;
}
}
public void onPause(Activity activity) {
if (!allowBackground()) {
if (snd != null) {
snd.onPause();
}
}
}
public void onStop(Activity activity) {
}
public void onDestroy(Activity activity) {
if (snd != null) {
snd.onDestroy();
}
snd = null;
}
public void onWindowFocusChanged(boolean hasFocus)
{
windowFocused = hasFocus;
if (resumeInOnWindowFocusChanged && !allowBackground()) {
if (snd != null) {
snd.onResume();
}
resumeInOnWindowFocusChanged = false;
}
}
@Override
public String getApiName()
{
return "Ti.Media.AudioPlayer";
}
}
|
android/modules/media/src/java/ti/modules/titanium/media/AudioPlayerProxy.java
|
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2016 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package ti.modules.titanium.media;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiBaseActivity;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.TiLifecycle.OnLifecycleEvent;
import org.appcelerator.titanium.TiLifecycle.OnWindowFocusChangedEvent;
import org.appcelerator.titanium.util.TiConvert;
import ti.modules.titanium.filesystem.FileProxy;
import android.app.Activity;
import android.media.AudioManager;
@Kroll.proxy(creatableInModule=MediaModule.class, propertyAccessors={
TiC.PROPERTY_VOLUME
})
public class AudioPlayerProxy extends KrollProxy
implements OnLifecycleEvent, OnWindowFocusChangedEvent
{
private static final String TAG = "AudioPlayerProxy";
@Kroll.constant public static final int STATE_BUFFERING = TiSound.STATE_BUFFERING;
@Kroll.constant public static final int STATE_INITIALIZED = TiSound.STATE_INITIALIZED;
@Kroll.constant public static final int STATE_PAUSED = TiSound.STATE_PAUSED;
@Kroll.constant public static final int STATE_PLAYING = TiSound.STATE_PLAYING;
@Kroll.constant public static final int STATE_STARTING = TiSound.STATE_STARTING;
@Kroll.constant public static final int STATE_STOPPED = TiSound.STATE_STOPPED;
@Kroll.constant public static final int STATE_STOPPING = TiSound.STATE_STOPPING;
@Kroll.constant public static final int STATE_WAITING_FOR_DATA = TiSound.STATE_WAITING_FOR_DATA;
@Kroll.constant public static final int STATE_WAITING_FOR_QUEUE = TiSound.STATE_WAITING_FOR_QUEUE;
@Kroll.constant public static final int STREAM_ALARM = AudioManager.STREAM_ALARM;
@Kroll.constant public static final int STREAM_DTMF = AudioManager.STREAM_DTMF;
@Kroll.constant public static final int STREAM_MUSIC = AudioManager.STREAM_MUSIC;
@Kroll.constant public static final int STREAM_NOTIFICATION = AudioManager.STREAM_NOTIFICATION;
@Kroll.constant public static final int STREAM_RING = AudioManager.STREAM_RING;
@Kroll.constant public static final int STREAM_SYSTEM = AudioManager.STREAM_SYSTEM;
@Kroll.constant public static final int STREAM_VOICE_CALL = AudioManager.STREAM_VOICE_CALL;
protected TiSound snd;
private boolean windowFocused;
private boolean resumeInOnWindowFocusChanged;
public AudioPlayerProxy()
{
super();
// TODO - we shouldnt need this as this proxy is created only from the runtime - double check
// TODO this needs to happen post-set
//((TiBaseActivity)getActivity()).addOnLifecycleEventListener(this);
defaultValues.put(TiC.PROPERTY_VOLUME, 1.0f);
defaultValues.put(TiC.PROPERTY_TIME,0);
defaultValues.put(TiC.PROPERTY_AUDIO_STREAM_TYPE, AudioManager.STREAM_MUSIC);
}
@Override
protected void initActivity(Activity activity) {
super.initActivity(activity);
((TiBaseActivity) getActivity()).addOnLifecycleEventListener(this);
((TiBaseActivity) getActivity()).addOnWindowFocusChangedEventListener(this);
}
@Override
public void handleCreationDict(KrollDict options) {
super.handleCreationDict(options);
if (options.containsKey(TiC.PROPERTY_URL)) {
setProperty(TiC.PROPERTY_URL, resolveUrl(null, TiConvert.toString(options, TiC.PROPERTY_URL)));
} else if (options.containsKey(TiC.PROPERTY_SOUND)) {
FileProxy fp = (FileProxy) options.get(TiC.PROPERTY_SOUND);
if (fp != null) {
String url = fp.getNativePath();
setProperty(TiC.PROPERTY_URL, url);
}
}
if (options.containsKey(TiC.PROPERTY_ALLOW_BACKGROUND)) {
setProperty(TiC.PROPERTY_ALLOW_BACKGROUND, options.get(TiC.PROPERTY_ALLOW_BACKGROUND));
}
if (options.containsKey(TiC.PROPERTY_AUDIO_FOCUS)) {
boolean audioFocus = TiConvert.toBoolean(options.get(TiC.PROPERTY_AUDIO_FOCUS));
setProperty(TiC.PROPERTY_AUDIO_FOCUS, audioFocus);
TiSound.audioFocus = audioFocus;
}
Log.i(TAG, "Creating audio player proxy for url: " + TiConvert.toString(getProperty(TiC.PROPERTY_URL)),
Log.DEBUG_MODE);
}
@Kroll.getProperty @Kroll.method
public String getUrl() {
return TiConvert.toString(getProperty(TiC.PROPERTY_URL));
}
@Kroll.setProperty @Kroll.method
public void setUrl(String url) {
if (url != null) {
setProperty(TiC.PROPERTY_URL, resolveUrl(null, TiConvert.toString(url)));
}
}
@Kroll.getProperty @Kroll.method
public int getDuration() {
TiSound s = getSound();
if (s != null) {
return s.getDuration();
}
return 0;
}
@Kroll.method @Kroll.getProperty
public int getAudioStreamType() {
return TiConvert.toInt(getProperty(TiC.PROPERTY_AUDIO_STREAM_TYPE));
}
@Kroll.method @Kroll.setProperty
public void setAudioStreamType(int val) {
setProperty(TiC.PROPERTY_AUDIO_STREAM_TYPE, val);
}
@Kroll.getProperty @Kroll.method
public boolean isPlaying() {
TiSound s = getSound();
if (s != null) {
return s.isPlaying();
}
return false;
}
@Kroll.getProperty @Kroll.method
public boolean isPaused() {
TiSound s = getSound();
if (s != null) {
return s.isPaused();
}
return false;
}
// An alias for play so that
@Kroll.method
public void start() {
play();
}
@Kroll.method
public void play() {
TiSound s = getSound();
if (s != null) {
s.play();
}
}
@Kroll.method
public void pause() {
TiSound s = getSound();
if (s != null) {
s.pause();
}
}
@Kroll.method
public void release() {
TiSound s = getSound();
if (s != null) {
s.release();
snd = null;
}
}
@Kroll.method
public void destroy() {
release();
}
@Kroll.method
public void stop() {
TiSound s = getSound();
if (s != null) {
s.stop();
}
}
@Kroll.method
public int getAudioSessionId() {
TiSound s = getSound();
if (s != null) {
return s.getAudioSessionId();
}
return 0;
}
@Kroll.method @Kroll.getProperty
public double getTime() {
TiSound s = getSound();
if (s != null) {
int time = s.getTime();
setProperty(TiC.PROPERTY_TIME, time);
}
return TiConvert.toDouble(getProperty(TiC.PROPERTY_TIME));
}
@Kroll.method @Kroll.setProperty
public void setTime(Object pos) {
if (pos != null) {
TiSound s = getSound();
if (s != null) {
s.setTime(TiConvert.toInt(pos));
} else {
setProperty(TiC.PROPERTY_TIME, TiConvert.toDouble(pos));
}
}
}
protected TiSound getSound()
{
if (snd == null) {
snd = new TiSound(this);
setModelListener(snd);
}
return snd;
}
private boolean allowBackground() {
boolean allow = false;
if (hasProperty(TiC.PROPERTY_ALLOW_BACKGROUND)) {
allow = TiConvert.toBoolean(getProperty(TiC.PROPERTY_ALLOW_BACKGROUND));
}
return allow;
}
public void onStart(Activity activity) {
}
public void onResume(Activity activity)
{
if (windowFocused && !allowBackground()) {
if (snd != null) {
snd.onResume();
}
} else {
resumeInOnWindowFocusChanged = true;
}
}
public void onPause(Activity activity) {
if (!allowBackground()) {
if (snd != null) {
snd.onPause();
}
}
}
public void onStop(Activity activity) {
}
public void onDestroy(Activity activity) {
if (snd != null) {
snd.onDestroy();
}
snd = null;
}
public void onWindowFocusChanged(boolean hasFocus)
{
windowFocused = hasFocus;
if (resumeInOnWindowFocusChanged && !allowBackground()) {
if (snd != null) {
snd.onResume();
}
resumeInOnWindowFocusChanged = false;
}
}
@Override
public String getApiName()
{
return "Ti.Media.AudioPlayer";
}
}
|
Update AudioPlayerProxy.java
|
android/modules/media/src/java/ti/modules/titanium/media/AudioPlayerProxy.java
|
Update AudioPlayerProxy.java
|
<ide><path>ndroid/modules/media/src/java/ti/modules/titanium/media/AudioPlayerProxy.java
<ide> /**
<ide> * Appcelerator Titanium Mobile
<del> * Copyright (c) 2009-2016 by Appcelerator, Inc. All Rights Reserved.
<add> * Copyright (c) 2009-2017 by Appcelerator, Inc. All Rights Reserved.
<ide> * Licensed under the terms of the Apache Public License
<ide> * Please see the LICENSE included with this distribution for details.
<ide> */
<ide> return 0;
<ide> }
<ide>
<del> @Kroll.method @Kroll.getProperty
<add> @Kroll.method @Kroll.getProperty
<ide> public int getAudioStreamType() {
<ide> return TiConvert.toInt(getProperty(TiC.PROPERTY_AUDIO_STREAM_TYPE));
<ide> }
<ide>
<ide> @Kroll.method @Kroll.setProperty
<ide> public void setAudioStreamType(int val) {
<del> setProperty(TiC.PROPERTY_AUDIO_STREAM_TYPE, val);
<add> setProperty(TiC.PROPERTY_AUDIO_STREAM_TYPE, val);
<ide> }
<ide>
<ide> @Kroll.getProperty @Kroll.method
|
|
Java
|
apache-2.0
|
a860d773d7b7407040149a9049acaf1683ffd799
| 0 |
aduprat/james,rouazana/james,aduprat/james,chibenwa/james,aduprat/james,chibenwa/james,aduprat/james,chibenwa/james,rouazana/james,rouazana/james,chibenwa/james,rouazana/james
|
/****************************************************************
* 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.james.socket;
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.security.Provider;
import java.security.Security;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.PostConstruct;
import org.apache.avalon.cornerstone.services.connection.AbstractHandlerFactory;
import org.apache.avalon.cornerstone.services.connection.ConnectionHandler;
import org.apache.avalon.cornerstone.services.connection.ConnectionHandlerFactory;
import org.apache.avalon.cornerstone.services.sockets.ServerSocketFactory;
import org.apache.avalon.cornerstone.services.sockets.SocketManager;
import org.apache.avalon.cornerstone.services.threads.ThreadManager;
import org.apache.avalon.excalibur.pool.DefaultPool;
import org.apache.avalon.excalibur.pool.HardResourceLimitingPool;
import org.apache.avalon.excalibur.pool.ObjectFactory;
import org.apache.avalon.excalibur.pool.Pool;
import org.apache.avalon.excalibur.pool.Poolable;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.container.ContainerUtil;
import org.apache.avalon.framework.logger.Logger;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.avalon.framework.service.Serviceable;
import org.apache.excalibur.thread.ThreadPool;
import org.apache.james.api.dnsservice.DNSService;
/**
* Server which creates connection handlers. All new James service must
* inherit from this abstract implementation.
*
*/
public abstract class AbstractProtocolServer extends AbstractHandlerFactory
implements Serviceable, Configurable, Disposable, ConnectionHandlerFactory, ObjectFactory {
/**
* The default value for the connection timeout.
*/
protected static final int DEFAULT_TIMEOUT = 5* 60 * 1000;
/**
* The name of the parameter defining the connection timeout.
*/
protected static final String TIMEOUT_NAME = "connectiontimeout";
/**
* The default value for the connection backlog.
*/
protected static final int DEFAULT_BACKLOG = 5;
/**
* The name of the parameter defining the connection backlog.
*/
protected static final String BACKLOG_NAME = "connectionBacklog";
/**
* The name of the parameter defining the service hello name.
*/
public static final String HELLO_NAME = "helloName";
/**
* The ConnectionManager that spawns and manages service connections.
*/
private JamesConnectionManager connectionManager;
/**
* The name of the thread group to be used by this service for
* generating connections
*/
protected String threadGroup;
/**
* The thread pool used by this service that holds the threads
* that service the client connections.
*/
protected ThreadPool threadPool = null;
/**
* The server socket type used to generate connections for this server.
*/
protected String serverSocketType = "plain";
/**
* The port on which this service will be made available.
*/
protected int port = -1;
/**
* Network interface to which the service will bind. If not set,
* the server binds to all available interfaces.
*/
protected InetAddress bindTo = null;
/**
* The server socket associated with this service
*/
protected ServerSocket serverSocket;
/**
* The name of the connection used by this service. We need to
* track this so we can tell the ConnectionManager which service
* to disconnect upon shutdown.
*/
protected String connectionName;
/**
* The maximum number of connections allowed for this service.
*/
protected Integer connectionLimit;
/**
* The connection idle timeout. Used primarily to prevent server
* problems from hanging a connection.
*/
protected int timeout;
/**
* The connection backlog.
*/
protected int backlog;
/**
* The hello name for the service.
*/
protected String helloName;
/**
* The component manager used by this service.
*/
private ServiceManager componentManager;
/**
* Whether this service is enabled.
*/
private volatile boolean enabled;
/**
* Flag holding the disposed state of the component.
*/
private boolean m_disposed = false;
/**
* The pool used to provide Protocol Handler objects
*/
protected Pool theHandlerPool = null;
/**
* The factory used to generate Watchdog objects
*/
protected WatchdogFactory theWatchdogFactory = null;
/**
* The DNSService
*/
private DNSService dnsService = null;
/**
* Counts the number of handler instances created.
* This allows a unique identity to be assigned to each for
* context sensitive logging.
*/
private AtomicLong handlerCount = new AtomicLong(0);
private boolean connPerIPConfigured = false;
private int connPerIP = 0;
/**
* If not null, it will be used to dump the tcp commands for debugging purpose
*/
private String streamDumpDir = null;
/**
* Gets the DNS Service.
* @return the dnsServer
*/
public final DNSService getDnsServer() {
return dnsService;
}
/**
* Sets the DNS service.
* @param dnsServer the dnsServer to set
*/
public final void setDnsServer(DNSService dnsServer) {
this.dnsService = dnsServer;
}
public void setConnectionManager(JamesConnectionManager connectionManager) {
this.connectionManager = connectionManager;
}
/**
* @see org.apache.avalon.framework.service.Serviceable#service(ServiceManager)
*/
public void service(ServiceManager comp) throws ServiceException {
super.service( comp );
componentManager = comp;
JamesConnectionManager connectionManager =
(JamesConnectionManager)componentManager.lookup(JamesConnectionManager.ROLE);
setConnectionManager(connectionManager);
dnsService = (DNSService) comp.lookup(DNSService.ROLE);
}
/**
* @see org.apache.avalon.framework.configuration.Configurable#configure(Configuration)
*/
public void configure(Configuration conf) throws ConfigurationException {
enabled = conf.getAttributeAsBoolean("enabled", true);
final Logger logger = getLogger();
if (!enabled) {
logger.info(getServiceType() + " disabled by configuration");
return;
}
Configuration handlerConfiguration = conf.getChild("handler");
// Send the handler subconfiguration to the super class. This
// ensures that the handler config is passed to the handlers.
//
// TODO: This should be rationalized. The handler element of the
// server configuration doesn't really make a whole lot of
// sense. We should modify the config to get rid of it.
// Keeping it for now to maintain backwards compatibility.
super.configure(handlerConfiguration);
boolean streamdump=handlerConfiguration.getChild("streamdump").getAttributeAsBoolean("enabled", false);
String streamdumpDir=streamdump ? handlerConfiguration.getChild("streamdump").getAttribute("directory", null) : null;
setStreamDumpDir(streamdumpDir);
port = conf.getChild("port").getValueAsInteger(getDefaultPort());
Configuration serverSocketTypeConf = conf.getChild("serverSocketType", false);
String confSocketType = null;
if (serverSocketTypeConf != null ) {
confSocketType = serverSocketTypeConf.getValue();
}
if (confSocketType == null) {
// Only load the useTLS parameter if a specific socket type has not
// been specified. This maintains backwards compatibility while
// allowing us to have more complex (i.e. multiple SSL configuration)
// deployments
final boolean useTLS = conf.getChild("useTLS").getValueAsBoolean(isDefaultTLSEnabled());
if (useTLS) {
serverSocketType = "ssl";
loadJCEProviders(conf, logger);
}
} else {
serverSocketType = confSocketType;
}
StringBuilder infoBuffer;
threadGroup = conf.getChild("threadGroup").getValue(null);
if (threadGroup != null) {
infoBuffer =
new StringBuilder(64)
.append(getServiceType())
.append(" uses thread group: ")
.append(threadGroup);
logger.info(infoBuffer.toString());
}
else {
logger.info(getServiceType() + " uses default thread group.");
}
try {
final String bindAddress = conf.getChild("bind").getValue(null);
if( null != bindAddress ) {
bindTo = InetAddress.getByName(bindAddress);
infoBuffer =
new StringBuilder(64)
.append(getServiceType())
.append(" bound to: ")
.append(bindTo);
logger.info(infoBuffer.toString());
}
}
catch( final UnknownHostException unhe ) {
throw new ConfigurationException( "Malformed bind parameter in configuration of service " + getServiceType(), unhe );
}
configureHelloName(handlerConfiguration);
timeout = handlerConfiguration.getChild(TIMEOUT_NAME).getValueAsInteger(DEFAULT_TIMEOUT);
infoBuffer =
new StringBuilder(64)
.append(getServiceType())
.append(" handler connection timeout is: ")
.append(timeout);
logger.info(infoBuffer.toString());
backlog = conf.getChild(BACKLOG_NAME).getValueAsInteger(DEFAULT_BACKLOG);
infoBuffer =
new StringBuilder(64)
.append(getServiceType())
.append(" connection backlog is: ")
.append(backlog);
logger.info(infoBuffer.toString());
String connectionLimitString = conf.getChild("connectionLimit").getValue(null);
if (connectionLimitString != null) {
try {
connectionLimit = new Integer(connectionLimitString);
} catch (NumberFormatException nfe) {
logger.error("Connection limit value is not properly formatted.", nfe);
}
if (connectionLimit.intValue() < 0) {
logger.error("Connection limit value cannot be less than zero.");
throw new ConfigurationException("Connection limit value cannot be less than zero.");
}
} else {
connectionLimit = new Integer(connectionManager.getMaximumNumberOfOpenConnections());
}
infoBuffer = new StringBuilder(128)
.append(getServiceType())
.append(" will allow a maximum of ")
.append(connectionLimit.intValue())
.append(" connections.");
logger.info(infoBuffer.toString());
String connectionLimitPerIP = conf.getChild("connectionLimitPerIP").getValue(null);
if (connectionLimitPerIP != null) {
try {
connPerIP = new Integer(connectionLimitPerIP).intValue();
connPerIPConfigured = true;
} catch (NumberFormatException nfe) {
logger.error("Connection limit per IP value is not properly formatted.", nfe);
}
if (connPerIP < 0) {
logger.error("Connection limit per IP value cannot be less than zero.");
throw new ConfigurationException("Connection limit value cannot be less than zero.");
}
} else {
connPerIP = connectionManager.getMaximumNumberOfOpenConnectionsPerIP();
}
infoBuffer = new StringBuilder(128)
.append(getServiceType())
.append(" will allow a maximum of ")
.append(connPerIP)
.append(" per IP connections for " +getServiceType());
logger.info(infoBuffer.toString());
}
private void loadJCEProviders(Configuration conf, final Logger logger) throws ConfigurationException {
final Configuration [] providerConfiguration = conf.getChildren("provider");
for (int i = 0; i < providerConfiguration.length; i++) {
final String providerName = providerConfiguration[i].getValue();
loadProvider(logger, providerName);
}
}
private void loadProvider(final Logger logger, final String providerName) {
if (providerName == null) {
logger.warn("Failed to specify provider. Continuing but JCE provider will not be loaded");
} else {
try {
logger.debug("Trying to load JCE provider '" + providerName + "'");
Security.addProvider((Provider) Class.forName(providerName).newInstance());
logger.info("Load JCE provider '" + providerName + "'");
} catch (IllegalAccessException e) {
logJCELoadFailure(logger, providerName, e);
} catch (InstantiationException e) {
logJCELoadFailure(logger, providerName, e);
} catch (ClassNotFoundException e) {
logJCELoadFailure(logger, providerName, e);
} catch (RuntimeException e) {
logJCELoadFailure(logger, providerName, e);
}
}
}
private void logJCELoadFailure(final Logger logger, final String providerName, Exception e) {
logger.warn("Cannot load JCE provider" + providerName);
logger.debug(e.getMessage(), e);
}
protected void setStreamDumpDir(String streamdumpDir) {
this.streamDumpDir = streamdumpDir;
}
protected String getLocalHostName() {
String hostName = null;
try {
hostName = dnsService.getHostName(dnsService.getLocalHost());
} catch (UnknownHostException ue) {
hostName = "localhost";
}
return hostName;
}
private void configureHelloName(Configuration handlerConfiguration) {
StringBuilder infoBuffer;
String hostName = null;
try {
hostName = dnsService.getHostName(dnsService.getLocalHost());
} catch (UnknownHostException ue) {
hostName = "localhost";
}
infoBuffer =
new StringBuilder(64)
.append(getServiceType())
.append(" is running on: ")
.append(hostName);
getLogger().info(infoBuffer.toString());
Configuration helloConf = handlerConfiguration.getChild(HELLO_NAME);
if (helloConf != null) {
boolean autodetect = helloConf.getAttributeAsBoolean("autodetect", true);
if (autodetect) {
helloName = hostName;
} else {
// Should we use the defaultdomain here ?
helloName = helloConf.getValue("localhost");
}
} else {
helloName = null;
}
infoBuffer =
new StringBuilder(64)
.append(getServiceType())
.append(" handler hello name is: ")
.append(helloName);
getLogger().info(infoBuffer.toString());
}
/**
* @see org.apache.avalon.framework.activity.Initializable#initialize()
*/
@PostConstruct
public final void initialize() throws Exception {
if (!isEnabled()) {
getLogger().info(getServiceType() + " Disabled");
System.out.println(getServiceType() + " Disabled");
return;
}
getLogger().debug(getServiceType() + " init...");
prepareInit();
// keeping these looked up services locally, because they are only needed beyond initialization
ThreadManager threadManager = (ThreadManager) componentManager.lookup(ThreadManager.ROLE);
SocketManager socketManager = (SocketManager) componentManager.lookup(SocketManager.ROLE);
initializeThreadPool(threadManager);
initializeServerSocket(socketManager);
getLogger().debug(getServiceType() + " ...init end");
initializeHandlerPool();
// do avalon specific preparations
ContainerUtil.enableLogging(theHandlerPool, getLogger());
ContainerUtil.initialize(theHandlerPool);
theWatchdogFactory = getWatchdogFactory();
// Allow subclasses to perform initialisation
doInit();
}
/**
* Hook for subclasses to perform an required initialisation
* before the superclass has been initialised.
* Called before the super class has completed it's initialisation.
* @throws Exception
*/
protected void prepareInit() throws Exception {
}
/**
* Hook for subclasses to perform an required initialisation.
* Called after the super class has completed it's initialisation.
* @throws Exception
*/
protected void doInit() throws Exception {
}
private void initializeThreadPool(ThreadManager threadManager) {
if (threadGroup != null) {
threadPool = threadManager.getThreadPool(threadGroup);
} else {
threadPool = threadManager.getDefaultThreadPool();
}
}
private void initializeServerSocket(SocketManager socketManager) throws Exception {
try {
initializeServerSocketWorker(socketManager);
} catch (BindException e) {
// handle a common exception and give detailed error message
String errorMessage = getBindingErrorMessage(e);
System.out.println("------------------------------");
System.out.println(errorMessage);
System.out.println("------------------------------");
getLogger().fatalError(errorMessage);
throw e;
}
}
private String getBindingErrorMessage(BindException e) {
// general info about binding error
StringBuilder errorMessage = new StringBuilder();
errorMessage.append("FATAL ERROR when starting service '").append(getServiceType()).append("'! ");
errorMessage.append("could not bind to ");
errorMessage.append(bindTo == null ? "0.0.0.0" : bindTo.toString());
errorMessage.append(":").append(port).append(". ");
// try to deliver more specific information
if (e.getMessage().indexOf("Address already in use") != -1) {
errorMessage.append("Port is already exclusively in use by another application.");
} else if (e.getMessage().indexOf("Permission denied") != -1) {
errorMessage.append("The user account James is running under has not enough privileges to bind to this ");
if (port < 1024) errorMessage.append("privileged ");
errorMessage.append("port.");
} else {
errorMessage.append(e.getMessage());
}
return errorMessage.toString();
}
private void initializeServerSocketWorker(SocketManager socketManager) throws Exception {
ServerSocketFactory factory = socketManager.getServerSocketFactory(serverSocketType);
ServerSocket serverSocket = factory.createServerSocket(port, backlog, bindTo);
if (null == connectionName) {
final StringBuilder sb = new StringBuilder();
sb.append(serverSocketType);
sb.append(':');
sb.append(port);
if (null != bindTo) {
sb.append('/');
sb.append(bindTo);
}
connectionName = sb.toString();
}
if ((connectionLimit != null)) {
if (null != threadPool) {
if (connPerIPConfigured) {
connectionManager.connect(connectionName, serverSocket, this, threadPool, connectionLimit.intValue(),connPerIP);
} else {
connectionManager.connect(connectionName, serverSocket, this, threadPool, connectionLimit.intValue());
}
} else {
if (connPerIPConfigured) {
connectionManager.connect(connectionName, serverSocket, this, connectionLimit.intValue(),connPerIP); // default pool
} else {
connectionManager.connect(connectionName, serverSocket, this, connectionLimit.intValue());
}
}
} else {
if (null != threadPool) {
if (connPerIPConfigured) {
connectionManager.connect(connectionName, serverSocket, this, threadPool);
} else {
connectionManager.connect(connectionName, serverSocket, this, threadPool, 0, connPerIP);
}
} else {
if (connPerIPConfigured) {
connectionManager.connect(connectionName, serverSocket, this); // default pool
} else {
connectionManager.connect(connectionName, serverSocket, this, 0, connPerIP);
}
}
}
}
private void initializeHandlerPool() throws Exception {
StringBuilder logBuffer =
new StringBuilder(64)
.append(getServiceType())
.append(" started ")
.append(connectionName);
String logString = logBuffer.toString();
System.out.println(logString);
getLogger().info(logString);
if (connectionLimit != null) {
theHandlerPool = new HardResourceLimitingPool(this, 5, connectionLimit.intValue());
if (getLogger().isDebugEnabled()) {
getLogger().debug("Using a bounded pool for "+getServiceType()+" handlers with upper limit " + connectionLimit.intValue());
}
} else {
// NOTE: The maximum here is not a real maximum. The handler pool will continue to
// provide handlers beyond this value.
theHandlerPool = new DefaultPool(this, null, 5, 30);
getLogger().debug("Using an unbounded pool for "+getServiceType()+" handlers.");
}
}
/**
* @see org.apache.avalon.framework.activity.Disposable#dispose()
*/
public void dispose() {
if (!isEnabled()) {
return;
}
if( m_disposed )
{
if( getLogger().isWarnEnabled() )
{
getLogger().warn( "ignoring disposal request - already disposed" );
}
return;
}
if( getLogger().isDebugEnabled() )
{
getLogger().debug( "disposal" );
}
m_disposed = true;
if( getLogger().isDebugEnabled() )
{
StringBuilder infoBuffer =
new StringBuilder(64).append(getServiceType()).append(
" dispose... ").append(connectionName);
getLogger().debug(infoBuffer.toString());
}
try {
connectionManager.disconnect(connectionName, true);
} catch (final Exception e) {
StringBuilder warnBuffer =
new StringBuilder(64)
.append("Error disconnecting ")
.append(getServiceType())
.append(": ");
getLogger().warn(warnBuffer.toString(), e);
}
componentManager = null;
connectionManager = null;
threadPool = null;
// This is needed to make sure sockets are promptly closed on Windows 2000
// TODO: Check this - shouldn't need to explicitly gc to force socket closure
System.gc();
getLogger().debug(getServiceType() + " ...dispose end");
}
/**
* This constructs the WatchdogFactory that will be used to guard
* against runaway or stuck behavior. Should only be called once
* by a subclass in its initialize() method.
*
* @return the WatchdogFactory to be employed by subclasses.
*/
protected WatchdogFactory getWatchdogFactory() {
WatchdogFactory theWatchdogFactory = null;
theWatchdogFactory = new ThreadPerWatchdogFactory(threadPool, timeout);
ContainerUtil.enableLogging(theWatchdogFactory,getLogger());
return theWatchdogFactory;
}
/**
* Describes whether this service is enabled by configuration.
*
* @return is the service enabled.
*/
public final boolean isEnabled() {
return enabled;
}
/**
* Override this method to create actual instance of connection handler.
*
* @return the new ConnectionHandler
* @exception Exception if an error occurs
*/
protected ConnectionHandler newHandler()
throws Exception {
JamesConnectionBridge theHandler = (JamesConnectionBridge)theHandlerPool.get();
if (getLogger().isDebugEnabled()) {
getLogger().debug("Handler [" + theHandler + "] obtained from pool.");
}
Watchdog theWatchdog = theWatchdogFactory.getWatchdog(theHandler);
theHandler.setStreamDumpDir(streamDumpDir);
theHandler.setWatchdog(theWatchdog);
return theHandler;
}
/**
* @see org.apache.avalon.cornerstone.services.connection.ConnectionHandlerFactory#releaseConnectionHandler(ConnectionHandler)
*/
public void releaseConnectionHandler( ConnectionHandler connectionHandler ) {
if (getLogger().isDebugEnabled()) {
getLogger().debug("Returning Handler [" + connectionHandler + "] to pool.");
}
theHandlerPool.put((Poolable)connectionHandler);
}
/**
* Get the default port for this server type.
*
* It is strongly recommended that subclasses of this class
* override this method to specify the default port for their
* specific server type.
*
* @return the default port
*/
protected int getDefaultPort() {
return 0;
}
/**
* Get whether TLS is enabled for this server's socket by default.
*
* @return the default port
*/
protected boolean isDefaultTLSEnabled() {
return false;
}
/**
* This method returns the type of service provided by this server.
* This should be invariant over the life of the class.
*
* Subclasses may override this implementation. This implementation
* parses the complete class name and returns the undecorated class
* name.
*
* @return description of this server
*/
public String getServiceType() {
String name = getClass().getName();
int p = name.lastIndexOf(".");
if (p > 0 && p < name.length() - 2) {
name = name.substring(p + 1);
}
return name;
}
/**
* Returns the port that the service is bound to
*
* @return int The port number
*/
public int getPort() {
return port;
}
/**
* Returns the address if the network interface the socket is bound to
*
* @return String The network interface name
*/
public String getNetworkInterface() {
if (bindTo == null) {
return "All";
} else {
return bindTo.getHostAddress();
}
}
/**
* Returns the server socket type, plain or SSL
*
* @return String The socket type, plain or SSL
*/
public String getSocketType() {
return serverSocketType;
}
/**
* @see org.apache.avalon.excalibur.pool.ObjectFactory#decommission(Object)
*/
public void decommission( Object object ) throws Exception {
return;
}
/**
* @see org.apache.avalon.cornerstone.services.connection.AbstractHandlerFactory#createConnectionHandler()
*/
public ConnectionHandler createConnectionHandler() throws Exception {
ConnectionHandler conn = super.createConnectionHandler();
ContainerUtil.service(conn, componentManager);
return conn;
}
/**
* @see org.apache.avalon.excalibur.pool.ObjectFactory#newInstance()
*/
public Object newInstance() throws Exception {
final String serviceShortNameString;
final String serviceType = getServiceType();
final int firstSpace = serviceType.indexOf(' ');
if (firstSpace > 0) {
serviceShortNameString = serviceType.substring(0, firstSpace);
} else {
serviceShortNameString = serviceType;
}
final String name = serviceShortNameString + "Handler-" + handlerCount.getAndAdd(1);
final JamesConnectionBridge delegatingJamesHandler =
new JamesConnectionBridge(newProtocolHandlerInstance(), dnsService, name, getLogger());
return delegatingJamesHandler;
}
protected abstract ProtocolHandler newProtocolHandlerInstance();
/**
* @see org.apache.avalon.excalibur.pool.ObjectFactory#getCreatedClass()
*/
@SuppressWarnings("unchecked")
public Class getCreatedClass() {
return JamesConnectionBridge.class;
}
}
|
trunk/avalon-socket-library/src/main/java/org/apache/james/socket/AbstractProtocolServer.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.james.socket;
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.security.Provider;
import java.security.Security;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.PostConstruct;
import org.apache.avalon.cornerstone.services.connection.AbstractHandlerFactory;
import org.apache.avalon.cornerstone.services.connection.ConnectionHandler;
import org.apache.avalon.cornerstone.services.connection.ConnectionHandlerFactory;
import org.apache.avalon.cornerstone.services.sockets.ServerSocketFactory;
import org.apache.avalon.cornerstone.services.sockets.SocketManager;
import org.apache.avalon.cornerstone.services.threads.ThreadManager;
import org.apache.avalon.excalibur.pool.DefaultPool;
import org.apache.avalon.excalibur.pool.HardResourceLimitingPool;
import org.apache.avalon.excalibur.pool.ObjectFactory;
import org.apache.avalon.excalibur.pool.Pool;
import org.apache.avalon.excalibur.pool.Poolable;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.container.ContainerUtil;
import org.apache.avalon.framework.logger.Logger;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.avalon.framework.service.Serviceable;
import org.apache.excalibur.thread.ThreadPool;
import org.apache.james.api.dnsservice.DNSService;
/**
* Server which creates connection handlers. All new James service must
* inherit from this abstract implementation.
*
*/
public abstract class AbstractProtocolServer extends AbstractHandlerFactory
implements Serviceable, Configurable, Disposable, ConnectionHandlerFactory, ObjectFactory {
/**
* The default value for the connection timeout.
*/
protected static final int DEFAULT_TIMEOUT = 5* 60 * 1000;
/**
* The name of the parameter defining the connection timeout.
*/
protected static final String TIMEOUT_NAME = "connectiontimeout";
/**
* The default value for the connection backlog.
*/
protected static final int DEFAULT_BACKLOG = 5;
/**
* The name of the parameter defining the connection backlog.
*/
protected static final String BACKLOG_NAME = "connectionBacklog";
/**
* The name of the parameter defining the service hello name.
*/
public static final String HELLO_NAME = "helloName";
/**
* The ConnectionManager that spawns and manages service connections.
*/
private JamesConnectionManager connectionManager;
/**
* The name of the thread group to be used by this service for
* generating connections
*/
protected String threadGroup;
/**
* The thread pool used by this service that holds the threads
* that service the client connections.
*/
protected ThreadPool threadPool = null;
/**
* The server socket type used to generate connections for this server.
*/
protected String serverSocketType = "plain";
/**
* The port on which this service will be made available.
*/
protected int port = -1;
/**
* Network interface to which the service will bind. If not set,
* the server binds to all available interfaces.
*/
protected InetAddress bindTo = null;
/**
* The server socket associated with this service
*/
protected ServerSocket serverSocket;
/**
* The name of the connection used by this service. We need to
* track this so we can tell the ConnectionManager which service
* to disconnect upon shutdown.
*/
protected String connectionName;
/**
* The maximum number of connections allowed for this service.
*/
protected Integer connectionLimit;
/**
* The connection idle timeout. Used primarily to prevent server
* problems from hanging a connection.
*/
protected int timeout;
/**
* The connection backlog.
*/
protected int backlog;
/**
* The hello name for the service.
*/
protected String helloName;
/**
* The component manager used by this service.
*/
private ServiceManager componentManager;
/**
* Whether this service is enabled.
*/
private volatile boolean enabled;
/**
* Flag holding the disposed state of the component.
*/
private boolean m_disposed = false;
/**
* The pool used to provide Protocol Handler objects
*/
protected Pool theHandlerPool = null;
/**
* The factory used to generate Watchdog objects
*/
protected WatchdogFactory theWatchdogFactory = null;
/**
* The DNSService
*/
private DNSService dnsService = null;
/**
* Counts the number of handler instances created.
* This allows a unique identity to be assigned to each for
* context sensitive logging.
*/
private AtomicLong handlerCount = new AtomicLong(0);
private boolean connPerIPConfigured = false;
private int connPerIP = 0;
/**
* If not null, it will be used to dump the tcp commands for debugging purpose
*/
private String streamDumpDir = null;
/**
* Gets the DNS Service.
* @return the dnsServer
*/
public final DNSService getDnsServer() {
return dnsService;
}
/**
* Sets the DNS service.
* @param dnsServer the dnsServer to set
*/
public final void setDnsServer(DNSService dnsServer) {
this.dnsService = dnsServer;
}
public void setConnectionManager(JamesConnectionManager connectionManager) {
this.connectionManager = connectionManager;
}
/**
* @see org.apache.avalon.framework.service.Serviceable#service(ServiceManager)
*/
public void service(ServiceManager comp) throws ServiceException {
super.service( comp );
componentManager = comp;
JamesConnectionManager connectionManager =
(JamesConnectionManager)componentManager.lookup(JamesConnectionManager.ROLE);
setConnectionManager(connectionManager);
dnsService = (DNSService) comp.lookup(DNSService.ROLE);
}
/**
* @see org.apache.avalon.framework.configuration.Configurable#configure(Configuration)
*/
public void configure(Configuration conf) throws ConfigurationException {
enabled = conf.getAttributeAsBoolean("enabled", true);
final Logger logger = getLogger();
if (!enabled) {
logger.info(getServiceType() + " disabled by configuration");
return;
}
Configuration handlerConfiguration = conf.getChild("handler");
// Send the handler subconfiguration to the super class. This
// ensures that the handler config is passed to the handlers.
//
// TODO: This should be rationalized. The handler element of the
// server configuration doesn't really make a whole lot of
// sense. We should modify the config to get rid of it.
// Keeping it for now to maintain backwards compatibility.
super.configure(handlerConfiguration);
boolean streamdump=handlerConfiguration.getChild("streamdump").getAttributeAsBoolean("enabled", false);
String streamdumpDir=streamdump ? handlerConfiguration.getChild("streamdump").getAttribute("directory", null) : null;
setStreamDumpDir(streamdumpDir);
port = conf.getChild("port").getValueAsInteger(getDefaultPort());
Configuration serverSocketTypeConf = conf.getChild("serverSocketType", false);
String confSocketType = null;
if (serverSocketTypeConf != null ) {
confSocketType = serverSocketTypeConf.getValue();
}
if (confSocketType == null) {
// Only load the useTLS parameter if a specific socket type has not
// been specified. This maintains backwards compatibility while
// allowing us to have more complex (i.e. multiple SSL configuration)
// deployments
final boolean useTLS = conf.getChild("useTLS").getValueAsBoolean(isDefaultTLSEnabled());
if (useTLS) {
serverSocketType = "ssl";
loadJCEProviders(conf, logger);
}
} else {
serverSocketType = confSocketType;
}
StringBuilder infoBuffer;
threadGroup = conf.getChild("threadGroup").getValue(null);
if (threadGroup != null) {
infoBuffer =
new StringBuilder(64)
.append(getServiceType())
.append(" uses thread group: ")
.append(threadGroup);
logger.info(infoBuffer.toString());
}
else {
logger.info(getServiceType() + " uses default thread group.");
}
try {
final String bindAddress = conf.getChild("bind").getValue(null);
if( null != bindAddress ) {
bindTo = InetAddress.getByName(bindAddress);
infoBuffer =
new StringBuilder(64)
.append(getServiceType())
.append(" bound to: ")
.append(bindTo);
logger.info(infoBuffer.toString());
}
}
catch( final UnknownHostException unhe ) {
throw new ConfigurationException( "Malformed bind parameter in configuration of service " + getServiceType(), unhe );
}
configureHelloName(handlerConfiguration);
timeout = handlerConfiguration.getChild(TIMEOUT_NAME).getValueAsInteger(DEFAULT_TIMEOUT);
infoBuffer =
new StringBuilder(64)
.append(getServiceType())
.append(" handler connection timeout is: ")
.append(timeout);
logger.info(infoBuffer.toString());
backlog = conf.getChild(BACKLOG_NAME).getValueAsInteger(DEFAULT_BACKLOG);
infoBuffer =
new StringBuilder(64)
.append(getServiceType())
.append(" connection backlog is: ")
.append(backlog);
logger.info(infoBuffer.toString());
String connectionLimitString = conf.getChild("connectionLimit").getValue(null);
if (connectionLimitString != null) {
try {
connectionLimit = new Integer(connectionLimitString);
} catch (NumberFormatException nfe) {
logger.error("Connection limit value is not properly formatted.", nfe);
}
if (connectionLimit.intValue() < 0) {
logger.error("Connection limit value cannot be less than zero.");
throw new ConfigurationException("Connection limit value cannot be less than zero.");
}
} else {
connectionLimit = new Integer(connectionManager.getMaximumNumberOfOpenConnections());
}
infoBuffer = new StringBuilder(128)
.append(getServiceType())
.append(" will allow a maximum of ")
.append(connectionLimit.intValue())
.append(" connections.");
logger.info(infoBuffer.toString());
String connectionLimitPerIP = conf.getChild("connectionLimitPerIP").getValue(null);
if (connectionLimitPerIP != null) {
try {
connPerIP = new Integer(connectionLimitPerIP).intValue();
connPerIPConfigured = true;
} catch (NumberFormatException nfe) {
logger.error("Connection limit per IP value is not properly formatted.", nfe);
}
if (connPerIP < 0) {
logger.error("Connection limit per IP value cannot be less than zero.");
throw new ConfigurationException("Connection limit value cannot be less than zero.");
}
} else {
connPerIP = connectionManager.getMaximumNumberOfOpenConnectionsPerIP();
}
infoBuffer = new StringBuilder(128)
.append(getServiceType())
.append(" will allow a maximum of ")
.append(connPerIP)
.append(" per IP connections for " +getServiceType());
logger.info(infoBuffer.toString());
}
private void loadJCEProviders(Configuration conf, final Logger logger) throws ConfigurationException {
final Configuration [] providerConfiguration = conf.getChildren("provider");
for (int i = 0; i < providerConfiguration.length; i++) {
final String providerName = providerConfiguration[i].getValue();
loadProvider(logger, providerName);
}
}
private void loadProvider(final Logger logger, final String providerName) {
if (providerName == null) {
logger.warn("Failed to specify provider. Continuing but JCE provider will not be loaded");
} else {
try {
logger.debug("Trying to load JCE provider '" + providerName + "'");
Security.addProvider((Provider) Class.forName(providerName).newInstance());
logger.info("Load JCE provider '" + providerName + "'");
} catch (IllegalAccessException e) {
logJCELoadFailure(logger, providerName, e);
} catch (InstantiationException e) {
logJCELoadFailure(logger, providerName, e);
} catch (ClassNotFoundException e) {
logJCELoadFailure(logger, providerName, e);
} catch (RuntimeException e) {
logJCELoadFailure(logger, providerName, e);
}
}
}
private void logJCELoadFailure(final Logger logger, final String providerName, Exception e) {
logger.warn("Cannot load JCE provider" + providerName);
logger.debug(e.getMessage(), e);
}
protected void setStreamDumpDir(String streamdumpDir) {
this.streamDumpDir = streamdumpDir;
}
protected String getLocalHostName() {
String hostName = null;
try {
hostName = dnsService.getHostName(dnsService.getLocalHost());
} catch (UnknownHostException ue) {
hostName = "localhost";
}
return hostName;
}
private void configureHelloName(Configuration handlerConfiguration) {
StringBuilder infoBuffer;
String hostName = null;
try {
hostName = dnsService.getHostName(dnsService.getLocalHost());
} catch (UnknownHostException ue) {
hostName = "localhost";
}
infoBuffer =
new StringBuilder(64)
.append(getServiceType())
.append(" is running on: ")
.append(hostName);
getLogger().info(infoBuffer.toString());
Configuration helloConf = handlerConfiguration.getChild(HELLO_NAME);
if (helloConf != null) {
boolean autodetect = helloConf.getAttributeAsBoolean("autodetect", true);
if (autodetect) {
helloName = hostName;
} else {
// Should we use the defaultdomain here ?
helloName = helloConf.getValue("localhost");
}
} else {
helloName = null;
}
infoBuffer =
new StringBuilder(64)
.append(getServiceType())
.append(" handler hello name is: ")
.append(helloName);
getLogger().info(infoBuffer.toString());
}
/**
* @see org.apache.avalon.framework.activity.Initializable#initialize()
*/
@PostConstruct
public final void initialize() throws Exception {
if (!isEnabled()) {
getLogger().info(getServiceType() + " Disabled");
System.out.println(getServiceType() + " Disabled");
return;
}
getLogger().debug(getServiceType() + " init...");
prepareInit();
// keeping these looked up services locally, because they are only needed beyond initialization
ThreadManager threadManager = (ThreadManager) componentManager.lookup(ThreadManager.ROLE);
SocketManager socketManager = (SocketManager) componentManager.lookup(SocketManager.ROLE);
initializeThreadPool(threadManager);
initializeServerSocket(socketManager);
getLogger().debug(getServiceType() + " ...init end");
initializeHandlerPool();
// do avalon specific preparations
ContainerUtil.enableLogging(theHandlerPool, getLogger());
ContainerUtil.initialize(theHandlerPool);
theWatchdogFactory = getWatchdogFactory();
// Allow subclasses to perform initialisation
doInit();
}
/**
* Hook for subclasses to perform an required initialisation
* before the superclass has been initialised.
* Called before the super class has completed it's initialisation.
* @throws Exception
*/
protected void prepareInit() throws Exception {
}
/**
* Hook for subclasses to perform an required initialisation.
* Called after the super class has completed it's initialisation.
* @throws Exception
*/
protected void doInit() throws Exception {
}
private void initializeThreadPool(ThreadManager threadManager) {
if (threadGroup != null) {
threadPool = threadManager.getThreadPool(threadGroup);
} else {
threadPool = threadManager.getDefaultThreadPool();
}
}
private void initializeServerSocket(SocketManager socketManager) throws Exception {
try {
initializeServerSocketWorker(socketManager);
} catch (BindException e) {
// handle a common exception and give detailed error message
String errorMessage = getBindingErrorMessage(e);
System.out.println("------------------------------");
System.out.println(errorMessage);
System.out.println("------------------------------");
getLogger().fatalError(errorMessage);
throw e;
}
}
private String getBindingErrorMessage(BindException e) {
// general info about binding error
StringBuilder errorMessage = new StringBuilder();
errorMessage.append("FATAL ERROR when starting service '").append(getServiceType()).append("'! ");
errorMessage.append("could not bind to ");
errorMessage.append(bindTo == null ? "0.0.0.0" : bindTo.toString());
errorMessage.append(":").append(port).append(". ");
// try to deliver more specific information
if (e.getMessage().indexOf("Address already in use") != -1) {
errorMessage.append("Port is already exclusively in use by another application.");
} else if (e.getMessage().indexOf("Permission denied") != -1) {
errorMessage.append("The user account James is running under has not enough privileges to bind to this ");
if (port < 1024) errorMessage.append("privileged ");
errorMessage.append("port.");
} else {
errorMessage.append(e.getMessage());
}
return errorMessage.toString();
}
private void initializeServerSocketWorker(SocketManager socketManager) throws Exception {
ServerSocketFactory factory = socketManager.getServerSocketFactory(serverSocketType);
ServerSocket serverSocket = factory.createServerSocket(port, backlog, bindTo);
if (null == connectionName) {
final StringBuilder sb = new StringBuilder();
sb.append(serverSocketType);
sb.append(':');
sb.append(port);
if (null != bindTo) {
sb.append('/');
sb.append(bindTo);
}
connectionName = sb.toString();
}
if ((connectionLimit != null)) {
if (null != threadPool) {
if (connPerIPConfigured) {
connectionManager.connect(connectionName, serverSocket, this, threadPool, connectionLimit.intValue(),connPerIP);
} else {
connectionManager.connect(connectionName, serverSocket, this, threadPool, connectionLimit.intValue());
}
} else {
if (connPerIPConfigured) {
connectionManager.connect(connectionName, serverSocket, this, connectionLimit.intValue(),connPerIP); // default pool
} else {
connectionManager.connect(connectionName, serverSocket, this, connectionLimit.intValue());
}
}
} else {
if (null != threadPool) {
if (connPerIPConfigured) {
connectionManager.connect(connectionName, serverSocket, this, threadPool);
} else {
connectionManager.connect(connectionName, serverSocket, this, threadPool, 0, connPerIP);
}
} else {
if (connPerIPConfigured) {
connectionManager.connect(connectionName, serverSocket, this); // default pool
} else {
connectionManager.connect(connectionName, serverSocket, this, 0, connPerIP);
}
}
}
}
private void initializeHandlerPool() throws Exception {
StringBuilder logBuffer =
new StringBuilder(64)
.append(getServiceType())
.append(" started ")
.append(connectionName);
String logString = logBuffer.toString();
System.out.println(logString);
getLogger().info(logString);
if (connectionLimit != null) {
theHandlerPool = new HardResourceLimitingPool(this, 5, connectionLimit.intValue());
if (getLogger().isDebugEnabled()) {
getLogger().debug("Using a bounded pool for "+getServiceType()+" handlers with upper limit " + connectionLimit.intValue());
}
} else {
// NOTE: The maximum here is not a real maximum. The handler pool will continue to
// provide handlers beyond this value.
theHandlerPool = new DefaultPool(this, null, 5, 30);
getLogger().debug("Using an unbounded pool for "+getServiceType()+" handlers.");
}
}
/**
* @see org.apache.avalon.framework.activity.Disposable#dispose()
*/
public void dispose() {
if (!isEnabled()) {
return;
}
if( m_disposed )
{
if( getLogger().isWarnEnabled() )
{
getLogger().warn( "ignoring disposal request - already disposed" );
}
return;
}
if( getLogger().isDebugEnabled() )
{
getLogger().debug( "disposal" );
}
m_disposed = true;
if( getLogger().isDebugEnabled() )
{
StringBuilder infoBuffer =
new StringBuilder(64).append(getServiceType()).append(
" dispose... ").append(connectionName);
getLogger().debug(infoBuffer.toString());
}
try {
connectionManager.disconnect(connectionName, true);
} catch (final Exception e) {
StringBuilder warnBuffer =
new StringBuilder(64)
.append("Error disconnecting ")
.append(getServiceType())
.append(": ");
getLogger().warn(warnBuffer.toString(), e);
}
componentManager = null;
connectionManager = null;
threadPool = null;
// This is needed to make sure sockets are promptly closed on Windows 2000
// TODO: Check this - shouldn't need to explicitly gc to force socket closure
System.gc();
getLogger().debug(getServiceType() + " ...dispose end");
}
/**
* This constructs the WatchdogFactory that will be used to guard
* against runaway or stuck behavior. Should only be called once
* by a subclass in its initialize() method.
*
* @return the WatchdogFactory to be employed by subclasses.
*/
protected WatchdogFactory getWatchdogFactory() {
WatchdogFactory theWatchdogFactory = null;
theWatchdogFactory = new ThreadPerWatchdogFactory(threadPool, timeout);
ContainerUtil.enableLogging(theWatchdogFactory,getLogger());
return theWatchdogFactory;
}
/**
* Describes whether this service is enabled by configuration.
*
* @return is the service enabled.
*/
public final boolean isEnabled() {
return enabled;
}
/**
* Override this method to create actual instance of connection handler.
*
* @return the new ConnectionHandler
* @exception Exception if an error occurs
*/
protected ConnectionHandler newHandler()
throws Exception {
JamesConnectionBridge theHandler = (JamesConnectionBridge)theHandlerPool.get();
if (getLogger().isDebugEnabled()) {
getLogger().debug("Handler [" + theHandler + "] obtained from pool.");
}
Watchdog theWatchdog = theWatchdogFactory.getWatchdog(theHandler);
theHandler.setStreamDumpDir(streamDumpDir);
theHandler.setWatchdog(theWatchdog);
return theHandler;
}
/**
* @see org.apache.avalon.cornerstone.services.connection.ConnectionHandlerFactory#releaseConnectionHandler(ConnectionHandler)
*/
public void releaseConnectionHandler( ConnectionHandler connectionHandler ) {
if (getLogger().isDebugEnabled()) {
getLogger().debug("Returning Handler [" + connectionHandler + "] to pool.");
}
theHandlerPool.put((Poolable)connectionHandler);
}
/**
* Get the default port for this server type.
*
* It is strongly recommended that subclasses of this class
* override this method to specify the default port for their
* specific server type.
*
* @return the default port
*/
protected int getDefaultPort() {
return 0;
}
/**
* Get whether TLS is enabled for this server's socket by default.
*
* @return the default port
*/
protected boolean isDefaultTLSEnabled() {
return false;
}
/**
* This method returns the type of service provided by this server.
* This should be invariant over the life of the class.
*
* Subclasses may override this implementation. This implementation
* parses the complete class name and returns the undecorated class
* name.
*
* @return description of this server
*/
public String getServiceType() {
String name = getClass().getName();
int p = name.lastIndexOf(".");
if (p > 0 && p < name.length() - 2) {
name = name.substring(p + 1);
}
return name;
}
/**
* Returns the port that the service is bound to
*
* @return int The port number
*/
public int getPort() {
return port;
}
/**
* Returns the address if the network interface the socket is bound to
*
* @return String The network interface name
*/
public String getNetworkInterface() {
if (bindTo == null) {
return "All";
} else {
return bindTo.getHostAddress();
}
}
/**
* Returns the server socket type, plain or SSL
*
* @return String The socket type, plain or SSL
*/
public String getSocketType() {
return serverSocketType;
}
/**
* @see org.apache.avalon.excalibur.pool.ObjectFactory#decommission(Object)
*/
public void decommission( Object object ) throws Exception {
return;
}
/**
* @see org.apache.avalon.cornerstone.services.connection.AbstractHandlerFactory#createConnectionHandler()
*/
public ConnectionHandler createConnectionHandler() throws Exception {
ConnectionHandler conn = super.createConnectionHandler();
ContainerUtil.service(conn, componentManager);
return conn;
}
/**
* @see org.apache.avalon.excalibur.pool.ObjectFactory#newInstance()
*/
public Object newInstance() throws Exception {
final String name = "Handler-" + handlerCount.getAndAdd(1);
final JamesConnectionBridge delegatingJamesHandler =
new JamesConnectionBridge(newProtocolHandlerInstance(), dnsService, name, getLogger());
return delegatingJamesHandler;
}
protected abstract ProtocolHandler newProtocolHandlerInstance();
/**
* @see org.apache.avalon.excalibur.pool.ObjectFactory#getCreatedClass()
*/
@SuppressWarnings("unchecked")
public Class getCreatedClass() {
return JamesConnectionBridge.class;
}
}
|
Add service to name. This is included in the name of each streamdump forming a prefix. This allows the dumps of each service to be easily recognised.
git-svn-id: 88158f914d5603334254b4adf21dfd50ec107162@817833 13f79535-47bb-0310-9956-ffa450edef68
|
trunk/avalon-socket-library/src/main/java/org/apache/james/socket/AbstractProtocolServer.java
|
Add service to name. This is included in the name of each streamdump forming a prefix. This allows the dumps of each service to be easily recognised.
|
<ide><path>runk/avalon-socket-library/src/main/java/org/apache/james/socket/AbstractProtocolServer.java
<ide> * @see org.apache.avalon.excalibur.pool.ObjectFactory#newInstance()
<ide> */
<ide> public Object newInstance() throws Exception {
<del> final String name = "Handler-" + handlerCount.getAndAdd(1);
<add> final String serviceShortNameString;
<add> final String serviceType = getServiceType();
<add> final int firstSpace = serviceType.indexOf(' ');
<add> if (firstSpace > 0) {
<add> serviceShortNameString = serviceType.substring(0, firstSpace);
<add> } else {
<add> serviceShortNameString = serviceType;
<add> }
<add> final String name = serviceShortNameString + "Handler-" + handlerCount.getAndAdd(1);
<ide> final JamesConnectionBridge delegatingJamesHandler =
<ide> new JamesConnectionBridge(newProtocolHandlerInstance(), dnsService, name, getLogger());
<ide> return delegatingJamesHandler;
|
|
Java
|
apache-2.0
|
09766c30441c0b46d62c2f6b6777c29c89124bfa
| 0 |
suncycheng/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,allotria/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,signed/intellij-community,da1z/intellij-community,clumsy/intellij-community,FHannes/intellij-community,retomerz/intellij-community,retomerz/intellij-community,signed/intellij-community,fitermay/intellij-community,fitermay/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,signed/intellij-community,vvv1559/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,signed/intellij-community,ibinti/intellij-community,allotria/intellij-community,kdwink/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,semonte/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,apixandru/intellij-community,hurricup/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,retomerz/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,retomerz/intellij-community,ibinti/intellij-community,signed/intellij-community,allotria/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,semonte/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,xfournet/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,hurricup/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,xfournet/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,kdwink/intellij-community,retomerz/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,fitermay/intellij-community,semonte/intellij-community,signed/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,allotria/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,signed/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,ibinti/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,allotria/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,allotria/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,retomerz/intellij-community,signed/intellij-community,xfournet/intellij-community,semonte/intellij-community,clumsy/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,FHannes/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,da1z/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,retomerz/intellij-community,hurricup/intellij-community,da1z/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,hurricup/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,ibinti/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,fitermay/intellij-community,apixandru/intellij-community,hurricup/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,ibinti/intellij-community,retomerz/intellij-community,ibinti/intellij-community,kdwink/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,semonte/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,da1z/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,asedunov/intellij-community,asedunov/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,fitermay/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,semonte/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community
|
package com.intellij.structuralsearch.impl.matcher;
import com.intellij.dupLocator.iterators.ArrayBackedNodeIterator;
import com.intellij.dupLocator.iterators.NodeIterator;
import com.intellij.lang.Language;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypes;
import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ContentIterator;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.structuralsearch.*;
import com.intellij.structuralsearch.impl.matcher.compiler.PatternCompiler;
import com.intellij.structuralsearch.impl.matcher.handlers.MatchingHandler;
import com.intellij.structuralsearch.impl.matcher.handlers.TopLevelMatchingHandler;
import com.intellij.structuralsearch.impl.matcher.iterators.SsrFilteringNodeIterator;
import com.intellij.structuralsearch.impl.matcher.strategies.MatchingStrategy;
import com.intellij.structuralsearch.plugin.ui.Configuration;
import com.intellij.structuralsearch.plugin.util.CollectingMatchResultSink;
import com.intellij.structuralsearch.plugin.util.DuplicateFilteringResultSink;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.PairProcessor;
import com.intellij.util.SmartList;
import com.intellij.util.indexing.FileBasedIndex;
import org.jetbrains.annotations.NotNull;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* This class makes program structure tree matching:
*/
public class MatcherImpl {
private static final Logger LOG = Logger.getInstance("#com.intellij.structuralsearch.impl.matcher.MatcherImpl");
// project being worked on
private final Project project;
private final DumbService myDumbService;
// context of matching
private final MatchContext matchContext;
private boolean isTesting;
// visitor to delegate the real work
private final GlobalMatchingVisitor visitor = new GlobalMatchingVisitor();
private ProgressIndicator progress;
private final TaskScheduler scheduler = new TaskScheduler();
private int totalFilesToScan;
private int scannedFilesCount;
public MatcherImpl(final Project project, final MatchOptions matchOptions) {
this.project = project;
matchContext = new MatchContext();
matchContext.setMatcher(visitor);
if (matchOptions != null) {
matchContext.setOptions(matchOptions);
cacheCompiledPattern(matchOptions, PatternCompiler.compilePattern(project,matchOptions));
}
myDumbService = DumbService.getInstance(project);
}
static class LastMatchData {
CompiledPattern lastPattern;
MatchOptions lastOptions;
}
private static SoftReference<LastMatchData> lastMatchData;
protected MatcherImpl(Project project) {
this(project, null);
}
public static void validate(Project project, MatchOptions options) {
synchronized(MatcherImpl.class) {
final LastMatchData data = new LastMatchData();
data.lastPattern = PatternCompiler.compilePattern(project, options);
data.lastOptions = options;
lastMatchData = new SoftReference<LastMatchData>(data);
}
final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(options.getFileType());
assert profile != null;
profile.checkSearchPattern(project, options);
}
public static boolean checkIfShouldAttemptToMatch(MatchContext context, NodeIterator matchedNodes) {
final CompiledPattern pattern = context.getPattern();
final NodeIterator patternNodes = pattern.getNodes();
try {
while (true) {
final PsiElement patternNode = patternNodes.current();
if (patternNode == null) {
return true;
}
final PsiElement matchedNode = matchedNodes.current();
if (matchedNode == null) {
return false;
}
final MatchingHandler matchingHandler = pattern.getHandler(patternNode);
if (matchingHandler == null || !matchingHandler.canMatch(patternNode, matchedNode)) {
return false;
}
matchedNodes.advance();
patternNodes.advance();
}
} finally {
patternNodes.reset();
matchedNodes.reset();
}
}
public void processMatchesInElement(MatchContext context, Configuration configuration,
NodeIterator matchedNodes,
PairProcessor<MatchResult, Configuration> processor) {
try {
configureOptions(context, configuration, matchedNodes.current(), processor);
context.setShouldRecursivelyMatch(false);
visitor.matchContext(matchedNodes);
} finally {
matchedNodes.reset();
context.getOptions().setScope(null);
}
}
public void clearContext() {
matchContext.clear();
}
private void configureOptions(MatchContext context,
final Configuration configuration,
PsiElement psiFile,
final PairProcessor<MatchResult, Configuration> processor) {
if (psiFile == null) return;
LocalSearchScope scope = new LocalSearchScope(psiFile);
matchContext.clear();
matchContext.setMatcher(visitor);
MatchOptions options = context.getOptions();
matchContext.setOptions(options);
matchContext.setPattern(context.getPattern());
matchContext.setShouldRecursivelyMatch(context.shouldRecursivelyMatch());
visitor.setMatchContext(matchContext);
matchContext.setSink(
new DuplicateFilteringResultSink(
new DefaultMatchResultSink() {
@Override
public void newMatch(MatchResult result) {
processor.process(result, configuration);
}
}
)
);
options.setScope(scope);
}
public void precompileOptions(List<Configuration> configurations, final Map<Configuration, MatchContext> out) {
for (final Configuration configuration : configurations) {
if (out.containsKey(configuration)) {
continue;
}
final MatchContext matchContext = new MatchContext();
matchContext.setMatcher(visitor);
final MatchOptions matchOptions = configuration.getMatchOptions();
matchContext.setOptions(matchOptions);
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
try {
final CompiledPattern compiledPattern = PatternCompiler.compilePattern(project, matchOptions);
matchContext.setPattern(compiledPattern);
out.put(configuration, matchContext);
}
catch (UnsupportedPatternException ignored) {}
catch (MalformedPatternException ignored) {}
}
});
}
}
/**
* Finds the matches of given pattern starting from given tree element.
* @throws MalformedPatternException
* @throws UnsupportedPatternException
*/
protected void findMatches(MatchResultSink sink, final MatchOptions options) throws MalformedPatternException, UnsupportedPatternException
{
CompiledPattern compiledPattern = prepareMatching(sink, options);
if (compiledPattern== null) {
return;
}
matchContext.getSink().setMatchingProcess( scheduler );
scheduler.init();
progress = matchContext.getSink().getProgressIndicator();
if (isTesting) {
// testing mode;
final PsiElement[] elements = ((LocalSearchScope)options.getScope()).getScope();
PsiElement parent = elements[0].getParent();
if (elements.length > 0 && matchContext.getPattern().getStrategy().continueMatching(parent != null ? parent : elements[0])) {
visitor.matchContext(new SsrFilteringNodeIterator(new ArrayBackedNodeIterator(elements)));
}
else {
final LanguageFileType fileType = (LanguageFileType)matchContext.getOptions().getFileType();
final Language language = fileType.getLanguage();
for (PsiElement element : elements) {
match(element, language);
}
}
matchContext.getSink().matchingFinished();
return;
}
if (!findMatches(options, compiledPattern)) {
return;
}
if (scheduler.getTaskQueueEndAction()==null) {
scheduler.setTaskQueueEndAction(
new Runnable() {
@Override
public void run() {
matchContext.getSink().matchingFinished();
}
}
);
}
scheduler.executeNext();
}
private boolean findMatches(MatchOptions options, CompiledPattern compiledPattern) {
SearchScope searchScope = compiledPattern.getScope();
final boolean ourOptimizedScope = searchScope != null;
if (!ourOptimizedScope) searchScope = options.getScope();
if (searchScope instanceof GlobalSearchScope) {
final GlobalSearchScope scope = (GlobalSearchScope)searchScope;
final ContentIterator ci = new ContentIterator() {
@Override
public boolean processFile(final VirtualFile fileOrDir) {
if (!fileOrDir.isDirectory() && scope.contains(fileOrDir) && fileOrDir.getFileType() != FileTypes.UNKNOWN) {
++totalFilesToScan;
scheduler.addOneTask(new MatchOneVirtualFile(fileOrDir));
}
return true;
}
};
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
FileBasedIndex.getInstance().iterateIndexableFiles(ci, project, progress);
}
});
progress.setText2("");
}
else {
final PsiElement[] elementsToScan = ((LocalSearchScope)searchScope).getScope();
totalFilesToScan = elementsToScan.length;
for (int i = 0; i < elementsToScan.length; ++i) {
final PsiElement psiElement = elementsToScan[i];
if (psiElement == null) continue;
scheduler.addOneTask(new MatchOnePsiFile(psiElement));
if (ourOptimizedScope) elementsToScan[i] = null; // to prevent long PsiElement reference
}
}
return true;
}
private CompiledPattern prepareMatching(final MatchResultSink sink, final MatchOptions options) {
CompiledPattern savedPattern = null;
if (matchContext.getOptions() == options && matchContext.getPattern() != null &&
matchContext.getOptions().hashCode() == matchContext.getPattern().getOptionsHashStamp()) {
savedPattern = matchContext.getPattern();
}
matchContext.clear();
matchContext.setSink(new DuplicateFilteringResultSink(sink));
matchContext.setOptions(options);
matchContext.setMatcher(visitor);
visitor.setMatchContext(matchContext);
CompiledPattern compiledPattern = savedPattern;
if (compiledPattern == null) {
synchronized(getClass()) {
final LastMatchData data = com.intellij.reference.SoftReference.dereference(lastMatchData);
if (data != null && options == data.lastOptions) {
compiledPattern = data.lastPattern;
}
lastMatchData = null;
}
if (compiledPattern==null) {
compiledPattern = ApplicationManager.getApplication().runReadAction(new Computable<CompiledPattern>() {
@Override
public CompiledPattern compute() {
return PatternCompiler.compilePattern(project,options);
}
});
}
}
cacheCompiledPattern(options, compiledPattern);
return compiledPattern;
}
private void cacheCompiledPattern(final MatchOptions options, final CompiledPattern compiledPattern) {
matchContext.setPattern(compiledPattern);
compiledPattern.setOptionsHashStamp(options.hashCode());
}
/**
* Finds the matches of given pattern starting from given tree element.
* @param sink match result destination
* @throws MalformedPatternException
* @throws UnsupportedPatternException
*/
protected void testFindMatches(MatchResultSink sink, MatchOptions options)
throws MalformedPatternException, UnsupportedPatternException {
isTesting = true;
try {
findMatches(sink,options);
} finally {
isTesting = false;
}
}
/**
* Finds the matches of given pattern starting from given tree element.
* @param source string for search
* @param pattern to be searched
* @return list of matches found
* @throws MalformedPatternException
* @throws UnsupportedPatternException
*/
protected List<MatchResult> testFindMatches(String source,
String pattern,
MatchOptions options,
boolean filePattern,
FileType sourceFileType,
String sourceExtension,
boolean physicalSourceFile)
throws MalformedPatternException, UnsupportedPatternException {
CollectingMatchResultSink sink = new CollectingMatchResultSink();
try {
PsiElement[] elements = MatcherImplUtil.createSourceTreeFromText(source,
filePattern ? PatternTreeContext.File : PatternTreeContext.Block,
sourceFileType,
sourceExtension,
project, physicalSourceFile);
options.setSearchPattern(pattern);
options.setScope(new LocalSearchScope(elements));
testFindMatches(sink, options);
}
catch (IncorrectOperationException e) {
MalformedPatternException exception = new MalformedPatternException();
exception.initCause(e);
throw exception;
} finally {
options.setScope(null);
}
return sink.getMatches();
}
protected List<MatchResult> testFindMatches(String source, String pattern, MatchOptions options, boolean filePattern) {
return testFindMatches(source, pattern, options, filePattern, options.getFileType(), null, false);
}
class TaskScheduler implements MatchingProcess {
private ArrayList<Runnable> tasks = new ArrayList<Runnable>();
private boolean ended;
private Runnable taskQueueEndAction;
private boolean suspended;
@Override
public void stop() {
ended = true;
}
@Override
public void pause() {
suspended = true;
}
@Override
public void resume() {
if (!suspended) return;
suspended = false;
executeNext();
}
@Override
public boolean isSuspended() {
return suspended;
}
@Override
public boolean isEnded() {
return ended;
}
void setTaskQueueEndAction(Runnable taskQueueEndAction) {
this.taskQueueEndAction = taskQueueEndAction;
}
Runnable getTaskQueueEndAction () {
return taskQueueEndAction;
}
void addOneTask(Runnable runnable) {
tasks.add(runnable);
}
private void executeNext() {
while(!suspended && !ended) {
if (tasks.isEmpty()) {
ended = true;
break;
}
final Runnable task = tasks.remove(tasks.size() - 1);
try {
task.run();
}
catch (ProcessCanceledException e) {
ended = true;
clearSchedule();
throw e;
}
catch (StructuralSearchException e) {
ended = true;
clearSchedule();
throw e;
}
catch (Throwable th) {
LOG.error(th);
}
}
if (ended) clearSchedule();
}
private void init() {
ended = false;
suspended = false;
PsiManager.getInstance(project).startBatchFilesProcessingMode();
}
private void clearSchedule() {
if (tasks != null) {
taskQueueEndAction.run();
if (!project.isDisposed()) {
PsiManager.getInstance(project).finishBatchFilesProcessingMode();
}
tasks = null;
}
}
}
private class MatchOnePsiFile extends MatchOneFile {
private PsiElement file;
MatchOnePsiFile(PsiElement file) {
this.file = file;
}
@NotNull
@Override
protected List<PsiElement> getPsiElementsToProcess() {
final PsiElement file = this.file;
this.file = null;
return new SmartList<PsiElement>(file);
}
}
private abstract class MatchOneFile implements Runnable {
@Override
public void run() {
final List<PsiElement> files = getPsiElementsToProcess();
if (progress!=null) {
progress.setFraction((double)scannedFilesCount/totalFilesToScan);
}
++scannedFilesCount;
if (files.size() == 0) return;
final LanguageFileType fileType = (LanguageFileType)matchContext.getOptions().getFileType();
final Language patternLanguage = fileType.getLanguage();
for (final PsiElement file : files) {
if (file instanceof PsiFile) {
matchContext.getSink().processFile((PsiFile)file);
}
myDumbService.runReadActionInSmartMode(new Runnable() {
@Override
public void run() {
if (!file.isValid()) return;
final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByLanguage(file.getLanguage());
if (profile == null) {
return;
}
match(profile.extendMatchOnePsiFile(file), patternLanguage);
}
}
);
}
}
@NotNull
protected abstract List<PsiElement> getPsiElementsToProcess();
}
// Initiates the matching process for given element
// @param element the current search tree element
void match(PsiElement element, final Language language) {
final MatchingStrategy strategy = matchContext.getPattern().getStrategy();
final Language elementLanguage = element.getLanguage();
if (strategy.continueMatching(element) && elementLanguage.isKindOf(language)) {
visitor.matchContext(new ArrayBackedNodeIterator(new PsiElement[] {element}));
return;
}
for(PsiElement el=element.getFirstChild();el!=null;el=el.getNextSibling()) {
match(el, language);
}
if (element instanceof PsiLanguageInjectionHost) {
InjectedLanguageUtil.enumerate(element, new PsiLanguageInjectionHost.InjectedPsiVisitor() {
@Override
public void visit(@NotNull PsiFile injectedPsi, @NotNull List<PsiLanguageInjectionHost.Shred> places) {
match(injectedPsi, language);
}
});
}
}
@NotNull
protected List<MatchResult> matchByDownUp(PsiElement element, final MatchOptions options) {
final CollectingMatchResultSink sink = new CollectingMatchResultSink();
final CompiledPattern compiledPattern = prepareMatching(sink, options);
matchContext.setShouldRecursivelyMatch(false);
PsiElement targetNode = compiledPattern.getTargetNode();
PsiElement elementToStartMatching = null;
if (targetNode == null) {
targetNode = compiledPattern.getNodes().current();
if (targetNode != null) {
compiledPattern.getNodes().advance();
assert !compiledPattern.getNodes().hasNext();
compiledPattern.getNodes().rewind();
element = element.getParent();
if (element == null) {
return Collections.emptyList();
}
while (element.getClass() != targetNode.getClass()) {
element = element.getParent();
if (element == null) return Collections.emptyList();
}
elementToStartMatching = element;
}
} else {
final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByPsiElement(element);
if (profile == null) return Collections.emptyList();
targetNode = profile.extendMatchedByDownUp(targetNode);
MatchingHandler handler = null;
while (element.getClass() == targetNode.getClass() ||
compiledPattern.isTypedVar(targetNode) && compiledPattern.getHandler(targetNode).canMatch(targetNode, element)) {
handler = compiledPattern.getHandler(targetNode);
handler.setPinnedElement(element);
elementToStartMatching = element;
if (handler instanceof TopLevelMatchingHandler) break;
element = element.getParent();
targetNode = targetNode.getParent();
if (options.isLooseMatching()) {
element = profile.updateCurrentNode(element);
targetNode = profile.updateCurrentNode(targetNode);
}
}
if (!(handler instanceof TopLevelMatchingHandler)) return Collections.emptyList();
}
assert targetNode != null : "Could not match down up when no target node";
final LanguageFileType fileType = (LanguageFileType)matchContext.getOptions().getFileType();
match(elementToStartMatching, fileType.getLanguage());
matchContext.getSink().matchingFinished();
return sink.getMatches();
}
private class MatchOneVirtualFile extends MatchOneFile {
private final VirtualFile myFile;
public MatchOneVirtualFile(VirtualFile file) {
myFile = file;
}
@NotNull
@Override
protected List<PsiElement> getPsiElementsToProcess() {
return ApplicationManager.getApplication().runReadAction(new Computable<List<PsiElement>>() {
@Override
public List<PsiElement> compute() {
final PsiFile file = PsiManager.getInstance(project).findFile(myFile);
if (file == null) {
return Collections.emptyList();
}
final FileViewProvider viewProvider = file.getViewProvider();
final List<PsiElement> elementsToProcess = new SmartList<PsiElement>();
for (Language lang : viewProvider.getLanguages()) {
elementsToProcess.add(viewProvider.getPsi(lang));
}
return elementsToProcess;
}
});
}
}
}
|
platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatcherImpl.java
|
package com.intellij.structuralsearch.impl.matcher;
import com.intellij.dupLocator.iterators.ArrayBackedNodeIterator;
import com.intellij.dupLocator.iterators.NodeIterator;
import com.intellij.lang.Language;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypes;
import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ContentIterator;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.structuralsearch.*;
import com.intellij.structuralsearch.impl.matcher.compiler.PatternCompiler;
import com.intellij.structuralsearch.impl.matcher.handlers.MatchingHandler;
import com.intellij.structuralsearch.impl.matcher.handlers.TopLevelMatchingHandler;
import com.intellij.structuralsearch.impl.matcher.iterators.SsrFilteringNodeIterator;
import com.intellij.structuralsearch.impl.matcher.strategies.MatchingStrategy;
import com.intellij.structuralsearch.plugin.ui.Configuration;
import com.intellij.structuralsearch.plugin.util.CollectingMatchResultSink;
import com.intellij.structuralsearch.plugin.util.DuplicateFilteringResultSink;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.PairProcessor;
import com.intellij.util.SmartList;
import com.intellij.util.indexing.FileBasedIndex;
import org.jetbrains.annotations.NotNull;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* This class makes program structure tree matching:
*/
public class MatcherImpl {
private static final Logger LOG = Logger.getInstance("#com.intellij.structuralsearch.impl.matcher.MatcherImpl");
// project being worked on
private final Project project;
private final PsiDocumentManager documentManager;
// context of matching
private final MatchContext matchContext;
private boolean isTesting;
// visitor to delegate the real work
private final GlobalMatchingVisitor visitor = new GlobalMatchingVisitor();
private ProgressIndicator progress;
private final TaskScheduler scheduler = new TaskScheduler();
private int totalFilesToScan;
private int scannedFilesCount;
public MatcherImpl(final Project project, final MatchOptions matchOptions) {
this.project = project;
matchContext = new MatchContext();
matchContext.setMatcher(visitor);
if (matchOptions != null) {
matchContext.setOptions(matchOptions);
cacheCompiledPattern(matchOptions, PatternCompiler.compilePattern(project,matchOptions));
}
documentManager = PsiDocumentManager.getInstance(this.project);
}
static class LastMatchData {
CompiledPattern lastPattern;
MatchOptions lastOptions;
}
private static SoftReference<LastMatchData> lastMatchData;
protected MatcherImpl(Project project) {
this(project, null);
}
public static void validate(Project project, MatchOptions options) {
synchronized(MatcherImpl.class) {
final LastMatchData data = new LastMatchData();
data.lastPattern = PatternCompiler.compilePattern(project, options);
data.lastOptions = options;
lastMatchData = new SoftReference<LastMatchData>(data);
}
final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(options.getFileType());
assert profile != null;
profile.checkSearchPattern(project, options);
}
public static boolean checkIfShouldAttemptToMatch(MatchContext context, NodeIterator matchedNodes) {
final CompiledPattern pattern = context.getPattern();
final NodeIterator patternNodes = pattern.getNodes();
try {
while (true) {
final PsiElement patternNode = patternNodes.current();
if (patternNode == null) {
return true;
}
final PsiElement matchedNode = matchedNodes.current();
if (matchedNode == null) {
return false;
}
final MatchingHandler matchingHandler = pattern.getHandler(patternNode);
if (matchingHandler == null || !matchingHandler.canMatch(patternNode, matchedNode)) {
return false;
}
matchedNodes.advance();
patternNodes.advance();
}
} finally {
patternNodes.reset();
matchedNodes.reset();
}
}
public void processMatchesInElement(MatchContext context, Configuration configuration,
NodeIterator matchedNodes,
PairProcessor<MatchResult, Configuration> processor) {
try {
configureOptions(context, configuration, matchedNodes.current(), processor);
context.setShouldRecursivelyMatch(false);
visitor.matchContext(matchedNodes);
} finally {
matchedNodes.reset();
context.getOptions().setScope(null);
}
}
public void clearContext() {
matchContext.clear();
}
private void configureOptions(MatchContext context,
final Configuration configuration,
PsiElement psiFile,
final PairProcessor<MatchResult, Configuration> processor) {
if (psiFile == null) return;
LocalSearchScope scope = new LocalSearchScope(psiFile);
matchContext.clear();
matchContext.setMatcher(visitor);
MatchOptions options = context.getOptions();
matchContext.setOptions(options);
matchContext.setPattern(context.getPattern());
matchContext.setShouldRecursivelyMatch(context.shouldRecursivelyMatch());
visitor.setMatchContext(matchContext);
matchContext.setSink(
new DuplicateFilteringResultSink(
new DefaultMatchResultSink() {
@Override
public void newMatch(MatchResult result) {
processor.process(result, configuration);
}
}
)
);
options.setScope(scope);
}
public void precompileOptions(List<Configuration> configurations, final Map<Configuration, MatchContext> out) {
for (final Configuration configuration : configurations) {
if (out.containsKey(configuration)) {
continue;
}
final MatchContext matchContext = new MatchContext();
matchContext.setMatcher(visitor);
final MatchOptions matchOptions = configuration.getMatchOptions();
matchContext.setOptions(matchOptions);
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
try {
final CompiledPattern compiledPattern = PatternCompiler.compilePattern(project, matchOptions);
matchContext.setPattern(compiledPattern);
out.put(configuration, matchContext);
}
catch (UnsupportedPatternException ignored) {}
catch (MalformedPatternException ignored) {}
}
});
}
}
/**
* Finds the matches of given pattern starting from given tree element.
* @throws MalformedPatternException
* @throws UnsupportedPatternException
*/
protected void findMatches(MatchResultSink sink, final MatchOptions options) throws MalformedPatternException, UnsupportedPatternException
{
CompiledPattern compiledPattern = prepareMatching(sink, options);
if (compiledPattern== null) {
return;
}
matchContext.getSink().setMatchingProcess( scheduler );
scheduler.init();
progress = matchContext.getSink().getProgressIndicator();
if (isTesting) {
// testing mode;
final PsiElement[] elements = ((LocalSearchScope)options.getScope()).getScope();
PsiElement parent = elements[0].getParent();
if (elements.length > 0 && matchContext.getPattern().getStrategy().continueMatching(parent != null ? parent : elements[0])) {
visitor.matchContext(new SsrFilteringNodeIterator(new ArrayBackedNodeIterator(elements)));
}
else {
final LanguageFileType fileType = (LanguageFileType)matchContext.getOptions().getFileType();
final Language language = fileType.getLanguage();
for (PsiElement element : elements) {
match(element, language);
}
}
matchContext.getSink().matchingFinished();
return;
}
if (!findMatches(options, compiledPattern)) {
return;
}
if (scheduler.getTaskQueueEndAction()==null) {
scheduler.setTaskQueueEndAction(
new Runnable() {
@Override
public void run() {
matchContext.getSink().matchingFinished();
}
}
);
}
scheduler.executeNext();
}
private boolean findMatches(MatchOptions options, CompiledPattern compiledPattern) {
SearchScope searchScope = compiledPattern.getScope();
final boolean ourOptimizedScope = searchScope != null;
if (!ourOptimizedScope) searchScope = options.getScope();
if (searchScope instanceof GlobalSearchScope) {
final GlobalSearchScope scope = (GlobalSearchScope)searchScope;
final ContentIterator ci = new ContentIterator() {
@Override
public boolean processFile(final VirtualFile fileOrDir) {
if (!fileOrDir.isDirectory() && scope.contains(fileOrDir) && fileOrDir.getFileType() != FileTypes.UNKNOWN) {
++totalFilesToScan;
scheduler.addOneTask(new MatchOneVirtualFile(fileOrDir));
}
return true;
}
};
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
FileBasedIndex.getInstance().iterateIndexableFiles(ci, project, progress);
}
});
progress.setText2("");
}
else {
final PsiElement[] elementsToScan = ((LocalSearchScope)searchScope).getScope();
totalFilesToScan = elementsToScan.length;
for (int i = 0; i < elementsToScan.length; ++i) {
final PsiElement psiElement = elementsToScan[i];
if (psiElement == null) continue;
scheduler.addOneTask(new MatchOnePsiFile(psiElement));
if (ourOptimizedScope) elementsToScan[i] = null; // to prevent long PsiElement reference
}
}
return true;
}
private CompiledPattern prepareMatching(final MatchResultSink sink, final MatchOptions options) {
CompiledPattern savedPattern = null;
if (matchContext.getOptions() == options && matchContext.getPattern() != null &&
matchContext.getOptions().hashCode() == matchContext.getPattern().getOptionsHashStamp()) {
savedPattern = matchContext.getPattern();
}
matchContext.clear();
matchContext.setSink(new DuplicateFilteringResultSink(sink));
matchContext.setOptions(options);
matchContext.setMatcher(visitor);
visitor.setMatchContext(matchContext);
CompiledPattern compiledPattern = savedPattern;
if (compiledPattern == null) {
synchronized(getClass()) {
final LastMatchData data = com.intellij.reference.SoftReference.dereference(lastMatchData);
if (data != null && options == data.lastOptions) {
compiledPattern = data.lastPattern;
}
lastMatchData = null;
}
if (compiledPattern==null) {
compiledPattern = ApplicationManager.getApplication().runReadAction(new Computable<CompiledPattern>() {
@Override
public CompiledPattern compute() {
return PatternCompiler.compilePattern(project,options);
}
});
}
}
cacheCompiledPattern(options, compiledPattern);
return compiledPattern;
}
private void cacheCompiledPattern(final MatchOptions options, final CompiledPattern compiledPattern) {
matchContext.setPattern(compiledPattern);
compiledPattern.setOptionsHashStamp(options.hashCode());
}
/**
* Finds the matches of given pattern starting from given tree element.
* @param sink match result destination
* @throws MalformedPatternException
* @throws UnsupportedPatternException
*/
protected void testFindMatches(MatchResultSink sink, MatchOptions options)
throws MalformedPatternException, UnsupportedPatternException {
isTesting = true;
try {
findMatches(sink,options);
} finally {
isTesting = false;
}
}
/**
* Finds the matches of given pattern starting from given tree element.
* @param source string for search
* @param pattern to be searched
* @return list of matches found
* @throws MalformedPatternException
* @throws UnsupportedPatternException
*/
protected List<MatchResult> testFindMatches(String source,
String pattern,
MatchOptions options,
boolean filePattern,
FileType sourceFileType,
String sourceExtension,
boolean physicalSourceFile)
throws MalformedPatternException, UnsupportedPatternException {
CollectingMatchResultSink sink = new CollectingMatchResultSink();
try {
PsiElement[] elements = MatcherImplUtil.createSourceTreeFromText(source,
filePattern ? PatternTreeContext.File : PatternTreeContext.Block,
sourceFileType,
sourceExtension,
project, physicalSourceFile);
options.setSearchPattern(pattern);
options.setScope(new LocalSearchScope(elements));
testFindMatches(sink, options);
}
catch (IncorrectOperationException e) {
MalformedPatternException exception = new MalformedPatternException();
exception.initCause(e);
throw exception;
} finally {
options.setScope(null);
}
return sink.getMatches();
}
protected List<MatchResult> testFindMatches(String source, String pattern, MatchOptions options, boolean filePattern) {
return testFindMatches(source, pattern, options, filePattern, options.getFileType(), null, false);
}
class TaskScheduler implements MatchingProcess {
private ArrayList<Runnable> tasks = new ArrayList<Runnable>();
private boolean ended;
private Runnable taskQueueEndAction;
private boolean suspended;
@Override
public void stop() {
ended = true;
}
@Override
public void pause() {
suspended = true;
}
@Override
public void resume() {
if (!suspended) return;
suspended = false;
executeNext();
}
@Override
public boolean isSuspended() {
return suspended;
}
@Override
public boolean isEnded() {
return ended;
}
void setTaskQueueEndAction(Runnable taskQueueEndAction) {
this.taskQueueEndAction = taskQueueEndAction;
}
Runnable getTaskQueueEndAction () {
return taskQueueEndAction;
}
void addOneTask(Runnable runnable) {
tasks.add(runnable);
}
private void executeNext() {
while(!suspended && !ended) {
if (tasks.isEmpty()) {
ended = true;
break;
}
final Runnable task = tasks.remove(tasks.size() - 1);
try {
task.run();
}
catch (ProcessCanceledException e) {
ended = true;
clearSchedule();
throw e;
}
catch (StructuralSearchException e) {
ended = true;
clearSchedule();
throw e;
}
catch (Throwable th) {
LOG.error(th);
}
}
if (ended) clearSchedule();
}
private void init() {
ended = false;
suspended = false;
PsiManager.getInstance(project).startBatchFilesProcessingMode();
}
private void clearSchedule() {
if (tasks != null) {
taskQueueEndAction.run();
if (!project.isDisposed()) {
PsiManager.getInstance(project).finishBatchFilesProcessingMode();
}
tasks = null;
}
}
}
private class MatchOnePsiFile extends MatchOneFile {
private PsiElement file;
MatchOnePsiFile(PsiElement file) {
this.file = file;
}
@NotNull
@Override
protected List<PsiElement> getPsiElementsToProcess() {
final PsiElement file = this.file;
this.file = null;
return new SmartList<PsiElement>(file);
}
}
private abstract class MatchOneFile implements Runnable {
@Override
public void run() {
final List<PsiElement> files = getPsiElementsToProcess();
if (progress!=null) {
progress.setFraction((double)scannedFilesCount/totalFilesToScan);
}
++scannedFilesCount;
if (files.size() == 0) return;
final LanguageFileType fileType = (LanguageFileType)matchContext.getOptions().getFileType();
final Language patternLanguage = fileType.getLanguage();
for (final PsiElement file : files) {
if (file instanceof PsiFile) {
matchContext.getSink().processFile((PsiFile)file);
}
documentManager.commitAndRunReadAction(new Runnable() {
@Override
public void run() {
if (!file.isValid()) return;
final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByLanguage(file.getLanguage());
if (profile == null) {
return;
}
match(profile.extendMatchOnePsiFile(file), patternLanguage);
}
}
);
}
}
@NotNull
protected abstract List<PsiElement> getPsiElementsToProcess();
}
// Initiates the matching process for given element
// @param element the current search tree element
void match(PsiElement element, final Language language) {
final MatchingStrategy strategy = matchContext.getPattern().getStrategy();
final Language elementLanguage = element.getLanguage();
if (strategy.continueMatching(element) && elementLanguage.isKindOf(language)) {
visitor.matchContext(new ArrayBackedNodeIterator(new PsiElement[] {element}));
return;
}
for(PsiElement el=element.getFirstChild();el!=null;el=el.getNextSibling()) {
match(el, language);
}
if (element instanceof PsiLanguageInjectionHost) {
InjectedLanguageUtil.enumerate(element, new PsiLanguageInjectionHost.InjectedPsiVisitor() {
@Override
public void visit(@NotNull PsiFile injectedPsi, @NotNull List<PsiLanguageInjectionHost.Shred> places) {
match(injectedPsi, language);
}
});
}
}
@NotNull
protected List<MatchResult> matchByDownUp(PsiElement element, final MatchOptions options) {
final CollectingMatchResultSink sink = new CollectingMatchResultSink();
final CompiledPattern compiledPattern = prepareMatching(sink, options);
matchContext.setShouldRecursivelyMatch(false);
PsiElement targetNode = compiledPattern.getTargetNode();
PsiElement elementToStartMatching = null;
if (targetNode == null) {
targetNode = compiledPattern.getNodes().current();
if (targetNode != null) {
compiledPattern.getNodes().advance();
assert !compiledPattern.getNodes().hasNext();
compiledPattern.getNodes().rewind();
element = element.getParent();
if (element == null) {
return Collections.emptyList();
}
while (element.getClass() != targetNode.getClass()) {
element = element.getParent();
if (element == null) return Collections.emptyList();
}
elementToStartMatching = element;
}
} else {
final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByPsiElement(element);
if (profile == null) return Collections.emptyList();
targetNode = profile.extendMatchedByDownUp(targetNode);
MatchingHandler handler = null;
while (element.getClass() == targetNode.getClass() ||
compiledPattern.isTypedVar(targetNode) && compiledPattern.getHandler(targetNode).canMatch(targetNode, element)) {
handler = compiledPattern.getHandler(targetNode);
handler.setPinnedElement(element);
elementToStartMatching = element;
if (handler instanceof TopLevelMatchingHandler) break;
element = element.getParent();
targetNode = targetNode.getParent();
if (options.isLooseMatching()) {
element = profile.updateCurrentNode(element);
targetNode = profile.updateCurrentNode(targetNode);
}
}
if (!(handler instanceof TopLevelMatchingHandler)) return Collections.emptyList();
}
assert targetNode != null : "Could not match down up when no target node";
final LanguageFileType fileType = (LanguageFileType)matchContext.getOptions().getFileType();
match(elementToStartMatching, fileType.getLanguage());
matchContext.getSink().matchingFinished();
return sink.getMatches();
}
private class MatchOneVirtualFile extends MatchOneFile {
private final VirtualFile myFile;
public MatchOneVirtualFile(VirtualFile file) {
myFile = file;
}
@NotNull
@Override
protected List<PsiElement> getPsiElementsToProcess() {
return ApplicationManager.getApplication().runReadAction(new Computable<List<PsiElement>>() {
@Override
public List<PsiElement> compute() {
final PsiFile file = PsiManager.getInstance(project).findFile(myFile);
if (file == null) {
return Collections.emptyList();
}
final FileViewProvider viewProvider = file.getViewProvider();
final List<PsiElement> elementsToProcess = new SmartList<PsiElement>();
for (Language lang : viewProvider.getLanguages()) {
elementsToProcess.add(viewProvider.getPsi(lang));
}
return elementsToProcess;
}
});
}
}
}
|
run structural search in smart mode (EA-75808 - NA: FileBasedIndexImpl.handleDumbMode; assume the documents are committed by other clients)
|
platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatcherImpl.java
|
run structural search in smart mode (EA-75808 - NA: FileBasedIndexImpl.handleDumbMode; assume the documents are committed by other clients)
|
<ide><path>latform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatcherImpl.java
<ide> import com.intellij.openapi.fileTypes.LanguageFileType;
<ide> import com.intellij.openapi.progress.ProcessCanceledException;
<ide> import com.intellij.openapi.progress.ProgressIndicator;
<add>import com.intellij.openapi.project.DumbService;
<ide> import com.intellij.openapi.project.Project;
<ide> import com.intellij.openapi.roots.ContentIterator;
<ide> import com.intellij.openapi.util.Computable;
<ide> private static final Logger LOG = Logger.getInstance("#com.intellij.structuralsearch.impl.matcher.MatcherImpl");
<ide> // project being worked on
<ide> private final Project project;
<del> private final PsiDocumentManager documentManager;
<add> private final DumbService myDumbService;
<ide>
<ide> // context of matching
<ide> private final MatchContext matchContext;
<ide> matchContext.setOptions(matchOptions);
<ide> cacheCompiledPattern(matchOptions, PatternCompiler.compilePattern(project,matchOptions));
<ide> }
<del> documentManager = PsiDocumentManager.getInstance(this.project);
<add> myDumbService = DumbService.getInstance(project);
<ide> }
<ide>
<ide> static class LastMatchData {
<ide> matchContext.getSink().processFile((PsiFile)file);
<ide> }
<ide>
<del> documentManager.commitAndRunReadAction(new Runnable() {
<add> myDumbService.runReadActionInSmartMode(new Runnable() {
<ide> @Override
<ide> public void run() {
<ide> if (!file.isValid()) return;
|
|
Java
|
agpl-3.0
|
9d364cfbb90cc5b660bcd03d163a2de7cc38db94
| 0 |
PeterWithers/temp-to-delete1,KinshipSoftware/KinOathKinshipArchiver,KinshipSoftware/KinOathKinshipArchiver,PeterWithers/temp-to-delete1
|
package nl.mpi.kinnate.uniqueidentifiers;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlValue;
import nl.mpi.arbil.data.ArbilField;
/**
* Document : UniqueIdentifier
* Created on : Jul 21, 2011, 3:23:17 PM
* Author : Peter Withers
*/
public class UniqueIdentifier {
public enum IdentifierType {
pid /*Persistent Identifier*/, lid /*Local Identifier*/, tid /*Transient Identifier produced by md5 summing a string */, gid /*Graphics Identifier*/
}
@XmlValue
private String identifierString = null;
@XmlAttribute(name = "type", namespace = "http://mpi.nl/tla/kin")
private IdentifierType identifierType = null;
private UniqueIdentifier() {
}
public UniqueIdentifier(IdentifierType identifierTypeLocal) {
identifierType = identifierTypeLocal;
identifierString = UUID.randomUUID().toString();
}
public UniqueIdentifier(ArbilField arbilField) {
if (arbilField.getFullXmlPath().endsWith(".UniqueIdentifier.LocalIdentifier")) {
identifierType = IdentifierType.lid;
} else if (arbilField.getFullXmlPath().endsWith(".UniqueIdentifier.PersistantIdentifier")) {
identifierType = IdentifierType.pid;
} else {
throw new UnsupportedOperationException("Incorrect ArbilField: " + arbilField.getFullXmlPath());
}
identifierString = arbilField.getFieldValue();
}
public UniqueIdentifier(String attributeIdentifier) {
// reconstruct the identifier from an attribte string originally obtained by getAttributeIdentifier
String[] attributeIdentifierParts = attributeIdentifier.split("\\:");
if (attributeIdentifierParts.length != 2) {
throw new UnsupportedOperationException("Incorrect identifier format: " + attributeIdentifier);
}
identifierType = IdentifierType.valueOf(attributeIdentifierParts[0]);
identifierString = attributeIdentifierParts[1];
}
public UniqueIdentifier(String userDefinedIdentifier, IdentifierType identifierTypeLocal) {
// this is required so that transient entities have the same identifier on each redraw and on loading a saved document, otherwise the entity positions on the graph get lost
// hash the string text so that it is valid in xml attributes but still reconstructable from the same user input
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
byte[] digestbytes = messageDigest.digest(userDefinedIdentifier.getBytes());
StringBuilder hexString = new StringBuilder();
for (int i = 0; i < digestbytes.length; ++i) {
hexString.append(Integer.toHexString(0x0100 + (digestbytes[i] & 0x00FF)).substring(1));
}
switch (identifierTypeLocal) {
case tid:
identifierString = hexString.toString();
identifierType = identifierTypeLocal;
break;
case pid:
case lid:
case gid:
throw new UnsupportedOperationException("Unsupported user defined identifier, these must be transient identifiers");
}
} catch (NoSuchAlgorithmException exception) {
throw new UnsupportedOperationException("Cannot hash the transient identifier");
}
}
public String getQueryIdentifier() {
// todo: limit the query to local or persistent
if (identifierString != null) {
return identifierString;
} else {
throw new UnsupportedOperationException();
}
}
public String getAttributeIdentifier() {
return identifierType.name() + ":" + identifierString;
}
public boolean isGraphicsIdentifier() {
return identifierType == IdentifierType.gid;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final UniqueIdentifier other = (UniqueIdentifier) obj;
if ((this.identifierString == null) ? (other.identifierString != null) : !this.identifierString.equals(other.identifierString)) {
return false;
}
if (this.identifierType != other.identifierType) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 5;
hash = 19 * hash + (this.identifierString != null ? this.identifierString.hashCode() : 0);
hash = 19 * hash + (this.identifierType != null ? this.identifierType.hashCode() : 0);
return hash;
}
@Override
public String toString() {
throw new UnsupportedOperationException();
}
}
|
desktop/src/main/java/nl/mpi/kinnate/uniqueidentifiers/UniqueIdentifier.java
|
package nl.mpi.kinnate.uniqueidentifiers;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import nl.mpi.arbil.data.ArbilField;
/**
* Document : UniqueIdentifier
* Created on : Jul 21, 2011, 3:23:17 PM
* Author : Peter Withers
*/
@XmlRootElement(name = "UniqueIdentifier")
public class UniqueIdentifier {
public enum IdentifierType {
pid /*Persistent Identifier*/, lid /*Local Identifier*/, tid /*Transient Identifier produced by md5 summing a string */, gid /*Graphics Identifier*/
}
@XmlValue
private String identifierString = null;
@XmlAttribute(name = "type")
private IdentifierType identifierType = null;
private UniqueIdentifier() {
}
public UniqueIdentifier(IdentifierType identifierTypeLocal) {
identifierType = identifierTypeLocal;
identifierString = UUID.randomUUID().toString();
}
public UniqueIdentifier(ArbilField arbilField) {
if (arbilField.getFullXmlPath().endsWith(".UniqueIdentifier.LocalIdentifier")) {
identifierType = IdentifierType.lid;
} else if (arbilField.getFullXmlPath().endsWith(".UniqueIdentifier.PersistantIdentifier")) {
identifierType = IdentifierType.pid;
} else {
throw new UnsupportedOperationException("Incorrect ArbilField: " + arbilField.getFullXmlPath());
}
identifierString = arbilField.getFieldValue();
}
public UniqueIdentifier(String attributeIdentifier) {
// reconstruct the identifier from an attribte string originally obtained by getAttributeIdentifier
String[] attributeIdentifierParts = attributeIdentifier.split("\\:");
if (attributeIdentifierParts.length != 2) {
throw new UnsupportedOperationException("Incorrect identifier format: " + attributeIdentifier);
}
identifierType = IdentifierType.valueOf(attributeIdentifierParts[0]);
identifierString = attributeIdentifierParts[1];
}
public UniqueIdentifier(String userDefinedIdentifier, IdentifierType identifierTypeLocal) {
// this is required so that transient entities have the same identifier on each redraw and on loading a saved document, otherwise the entity positions on the graph get lost
// hash the string text so that it is valid in xml attributes but still reconstructable from the same user input
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
byte[] digestbytes = messageDigest.digest(userDefinedIdentifier.getBytes());
StringBuilder hexString = new StringBuilder();
for (int i = 0; i < digestbytes.length; ++i) {
hexString.append(Integer.toHexString(0x0100 + (digestbytes[i] & 0x00FF)).substring(1));
}
switch (identifierTypeLocal) {
case tid:
identifierString = hexString.toString();
identifierType = identifierTypeLocal;
break;
case pid:
case lid:
case gid:
throw new UnsupportedOperationException("Unsupported user defined identifier, these must be transient identifiers");
}
} catch (NoSuchAlgorithmException exception) {
throw new UnsupportedOperationException("Cannot hash the transient identifier");
}
}
public String getQueryIdentifier() {
// todo: limit the query to local or persistent
if (identifierString != null) {
return identifierString;
} else {
throw new UnsupportedOperationException();
}
}
public String getAttributeIdentifier() {
return identifierType.name() + ":" + identifierString;
}
public boolean isGraphicsIdentifier() {
return identifierType == IdentifierType.gid;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final UniqueIdentifier other = (UniqueIdentifier) obj;
if ((this.identifierString == null) ? (other.identifierString != null) : !this.identifierString.equals(other.identifierString)) {
return false;
}
if (this.identifierType != other.identifierType) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 5;
hash = 19 * hash + (this.identifierString != null ? this.identifierString.hashCode() : 0);
hash = 19 * hash + (this.identifierType != null ? this.identifierType.hashCode() : 0);
return hash;
}
@Override
public String toString() {
throw new UnsupportedOperationException();
}
}
|
Updated the namespace for the kin xml data. Modified the csv and gedcom import to use the entitydata and jaxb to create the xml adding any extra metadata later in the file, so that entity relations are always created in the same way. Modified the unique identifier that transient entities use to be based on an md5 sum of the users input so that they have the same identifier on each redraw and on loading a saved document, otherwise the entity positions on the graph get lost. Simplified the unique identifier and its xml form. Modified the import process to insert back references for each entity relation so that the xml queries can take 1/10th of the time. Added options to highlight or not the relation lines of selected entities and to hide or show the diagram border. Replaced the string based unique identifier with the unique identifier object. Added a common unique identifier used by entities and graphics elements alike.
|
desktop/src/main/java/nl/mpi/kinnate/uniqueidentifiers/UniqueIdentifier.java
|
Updated the namespace for the kin xml data. Modified the csv and gedcom import to use the entitydata and jaxb to create the xml adding any extra metadata later in the file, so that entity relations are always created in the same way. Modified the unique identifier that transient entities use to be based on an md5 sum of the users input so that they have the same identifier on each redraw and on loading a saved document, otherwise the entity positions on the graph get lost. Simplified the unique identifier and its xml form. Modified the import process to insert back references for each entity relation so that the xml queries can take 1/10th of the time. Added options to highlight or not the relation lines of selected entities and to hide or show the diagram border. Replaced the string based unique identifier with the unique identifier object. Added a common unique identifier used by entities and graphics elements alike.
|
<ide><path>esktop/src/main/java/nl/mpi/kinnate/uniqueidentifiers/UniqueIdentifier.java
<ide> import java.security.NoSuchAlgorithmException;
<ide> import java.util.UUID;
<ide> import javax.xml.bind.annotation.XmlAttribute;
<del>import javax.xml.bind.annotation.XmlRootElement;
<ide> import javax.xml.bind.annotation.XmlValue;
<ide> import nl.mpi.arbil.data.ArbilField;
<ide>
<ide> * Created on : Jul 21, 2011, 3:23:17 PM
<ide> * Author : Peter Withers
<ide> */
<del>@XmlRootElement(name = "UniqueIdentifier")
<ide> public class UniqueIdentifier {
<ide>
<ide> public enum IdentifierType {
<ide> }
<ide> @XmlValue
<ide> private String identifierString = null;
<del> @XmlAttribute(name = "type")
<add> @XmlAttribute(name = "type", namespace = "http://mpi.nl/tla/kin")
<ide> private IdentifierType identifierType = null;
<ide>
<ide> private UniqueIdentifier() {
|
|
Java
|
apache-2.0
|
0647c6c7df3486200d05e14610a83eadaf081918
| 0 |
hsaputra/cdap,hsaputra/cdap,hsaputra/cdap,mpouttuclarke/cdap,caskdata/cdap,chtyim/cdap,anthcp/cdap,mpouttuclarke/cdap,chtyim/cdap,caskdata/cdap,caskdata/cdap,caskdata/cdap,caskdata/cdap,mpouttuclarke/cdap,anthcp/cdap,anthcp/cdap,anthcp/cdap,chtyim/cdap,chtyim/cdap,anthcp/cdap,caskdata/cdap,mpouttuclarke/cdap,hsaputra/cdap,mpouttuclarke/cdap,hsaputra/cdap,chtyim/cdap,chtyim/cdap
|
/*
* Copyright 2014 Cask Data, 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 co.cask.cdap.hive.datasets;
import co.cask.cdap.common.conf.Constants;
import co.cask.cdap.hive.context.NullJobConfException;
import co.cask.cdap.hive.objectinspector.ObjectInspectorFactory;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.serde2.SerDe;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.apache.hadoop.hive.serde2.SerDeStats;
import org.apache.hadoop.hive.serde2.io.ByteWritable;
import org.apache.hadoop.hive.serde2.io.DateWritable;
import org.apache.hadoop.hive.serde2.io.HiveBaseCharWritable;
import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable;
import org.apache.hadoop.hive.serde2.io.TimestampWritable;
import org.apache.hadoop.hive.serde2.lazy.LazyArray;
import org.apache.hadoop.hive.serde2.lazy.LazyMap;
import org.apache.hadoop.hive.serde2.lazy.LazyNonPrimitive;
import org.apache.hadoop.hive.serde2.lazy.LazyPrimitive;
import org.apache.hadoop.hive.serde2.lazy.LazyStruct;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.MapTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
import org.apache.hadoop.io.BooleanWritable;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.ObjectWritable;
import org.apache.hadoop.io.ShortWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* SerDe to serialize Dataset Objects.
*/
public class DatasetSerDe implements SerDe {
private static final Gson GSON = new Gson();
private static final Logger LOG = LoggerFactory.getLogger(DatasetSerDe.class);
private ArrayList<String> columnNames;
private Type recordType;
@Override
public void initialize(Configuration entries, Properties properties) throws SerDeException {
// The column names are saved as the given inspector to #serialize doesn't preserves them
// - maybe because it's an external table
// The columns property comes from the Hive metastore, which has it from the create table statement
// It is then important that this schema be accurate and in the right order - the same order as
// object inspectors will reflect them.
columnNames = new ArrayList<String>(Arrays.asList(StringUtils.split(properties.getProperty("columns"), ",")));
String datasetName = properties.getProperty(Constants.Explore.DATASET_NAME);
try {
if (entries != null) {
// Here, we can't say whether Hive wants to read the table, or write to it
Configuration conf = new Configuration(entries);
conf.set(Constants.Explore.DATASET_NAME, datasetName);
recordType = DatasetAccessor.getRecordType(conf);
} else {
// When initialize is called to write to a table, entries is null
try {
recordType = DatasetAccessor.getRecordWritableType(datasetName);
} catch (NullJobConfException e) {
// This is the case when this serDe is used by Hive only for its serialize method. In that case,
// We don't need to initialize a context since serialize does not need any dataset information.
LOG.warn("Could not initialize record writable dataset. Carrying on.");
recordType = null;
}
}
} catch (IOException e) {
LOG.error("Got exception while trying to instantiate dataset {}", datasetName, e);
throw new SerDeException(e);
}
}
@Override
public Class<? extends Writable> getSerializedClass() {
return Text.class;
}
@Override
public Writable serialize(Object o, ObjectInspector objectInspector) throws SerDeException {
// NOTE: the object inspector here is not one that we build. It's a default one that Hive built,
// that contains generic names for columns. The object is a list of objects, each element
// representing one attribute of the Record type.
// The object and the objectInspector represent one row of a query result to write into a dataset.
// Therefore, it is not guaranteed that the object exactly matches the schema of the dataset
// we want to write into.
if (!(objectInspector instanceof StructObjectInspector)) {
throw new SerDeException("Trying to serialize with unknown object inspector type " +
objectInspector.getClass().getName() + ". Expected StructObjectInspector.");
}
//overwrite field names (as they get lost by Hive)
StructTypeInfo structTypeInfo = (StructTypeInfo) TypeInfoUtils.getTypeInfoFromObjectInspector(objectInspector);
structTypeInfo.setAllStructFieldNames(columnNames);
List<TypeInfo> info = structTypeInfo.getAllStructFieldTypeInfos();
List<String> names = structTypeInfo.getAllStructFieldNames();
Map<String, Object> recordMap = Maps.newConcurrentMap();
List<Object> recordObjects = ((StructObjectInspector) objectInspector).getStructFieldsDataAsList(o);
for (int structIndex = 0; structIndex < info.size(); structIndex++) {
Object obj = recordObjects.get(structIndex);
if (obj instanceof LazyNonPrimitive || obj instanceof LazyPrimitive) {
// In case the SerDe that deserialized the object is the one of a native table
recordMap.put(names.get(structIndex), fromLazyObject(info.get(structIndex), obj));
} else if (obj instanceof Writable) {
// Native tables sometimes introduce primitive Writable objects at this point
recordMap.put(names.get(structIndex), fromWritable((Writable) obj));
} else {
// In case the deserializer is the DatasetSerDe
recordMap.put(names.get(structIndex), obj);
}
}
// TODO Improve serialization logic - REACTOR-927
return new Text(GSON.toJson(recordMap));
}
@Override
public SerDeStats getSerDeStats() {
// TODO: add real Sataset stats - REACTOR-278
return new SerDeStats();
}
@Override
public Object deserialize(Writable writable) throws SerDeException {
ObjectWritable objectWritable = (ObjectWritable) writable;
return objectWritable.get();
}
@Override
public ObjectInspector getObjectInspector() throws SerDeException {
Preconditions.checkNotNull(recordType, "Record type should not be null.");
return ObjectInspectorFactory.getReflectionObjectInspector(recordType);
}
private Object fromWritable(Writable writable) {
if (writable instanceof IntWritable) {
return ((IntWritable) writable).get();
} else if (writable instanceof LongWritable) {
return ((LongWritable) writable).get();
} else if (writable instanceof ShortWritable) {
return ((ShortWritable) writable).get();
} else if (writable instanceof BooleanWritable) {
return ((BooleanWritable) writable).get();
} else if (writable instanceof DoubleWritable) {
return ((DoubleWritable) writable).get();
} else if (writable instanceof FloatWritable) {
return ((FloatWritable) writable).get();
} else if (writable instanceof Text) {
return writable.toString();
} else if (writable instanceof BytesWritable) {
return ((BytesWritable) writable).getBytes();
} else if (writable instanceof ByteWritable) {
return ((ByteWritable) writable).get();
} else if (writable instanceof DateWritable) {
return ((DateWritable) writable).get();
} else if (writable instanceof org.apache.hadoop.hive.serde2.io.ShortWritable) {
return ((org.apache.hadoop.hive.serde2.io.ShortWritable) writable).get();
} else if (writable instanceof HiveBaseCharWritable) {
return ((HiveBaseCharWritable) writable).getTextValue().toString();
} else if (writable instanceof TimestampWritable) {
return ((TimestampWritable) writable).getTimestamp();
} else if (writable instanceof org.apache.hadoop.hive.serde2.io.DoubleWritable) {
return ((org.apache.hadoop.hive.serde2.io.DoubleWritable) writable).get();
} else if (writable instanceof HiveDecimalWritable) {
return ((HiveDecimalWritable) writable).getHiveDecimal();
} else if (writable instanceof NullWritable) {
return null;
}
return writable.toString();
}
private Object fromLazyObject(TypeInfo type, Object data) {
if (data == null) {
return null;
}
switch (type.getCategory()) {
case PRIMITIVE:
Writable writable = ((LazyPrimitive) data).getWritableObject();
return fromWritable(writable);
case LIST:
ListTypeInfo listType = (ListTypeInfo) type;
TypeInfo listElementType = listType.getListElementTypeInfo();
List<Object> list = ((LazyArray) data).getList();
if (list.isEmpty()) {
return ImmutableList.of();
}
Object[] arrayContent = new Object[list.size()];
for (int i = 0; i < arrayContent.length; i++) {
arrayContent[i] = fromLazyObject(listElementType, list.get(i));
}
return arrayContent;
case MAP:
MapTypeInfo mapType = (MapTypeInfo) type;
Map<Object, Object> mapContent = Maps.newConcurrentMap();
Map<Object, Object> map = ((LazyMap) data).getMap();
for (Map.Entry<Object, Object> entry : map.entrySet()) {
mapContent.put(fromLazyObject(mapType.getMapKeyTypeInfo(), entry.getKey()),
fromLazyObject(mapType.getMapValueTypeInfo(), entry.getValue()));
}
return mapContent;
case STRUCT:
StructTypeInfo structType = (StructTypeInfo) type;
List<TypeInfo> info = structType.getAllStructFieldTypeInfos();
List<String> names = structType.getAllStructFieldNames();
Map<String, Object> structMap = Maps.newConcurrentMap();
List<Object> struct = ((LazyStruct) data).getFieldsAsList();
for (int structIndex = 0; structIndex < info.size(); structIndex++) {
structMap.put(names.get(structIndex),
fromLazyObject(info.get(structIndex), struct.get(structIndex)));
}
return structMap;
case UNION:
throw new UnsupportedOperationException("union not yet supported");
default:
return data.toString();
}
}
}
|
explore/src/main/java/co/cask/cdap/hive/datasets/DatasetSerDe.java
|
/*
* Copyright 2014 Cask Data, 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 co.cask.cdap.hive.datasets;
import co.cask.cdap.common.conf.Constants;
import co.cask.cdap.hive.context.NullJobConfException;
import co.cask.cdap.hive.objectinspector.ObjectInspectorFactory;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.serde2.SerDe;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.apache.hadoop.hive.serde2.SerDeStats;
import org.apache.hadoop.hive.serde2.io.ByteWritable;
import org.apache.hadoop.hive.serde2.io.DateWritable;
import org.apache.hadoop.hive.serde2.io.HiveBaseCharWritable;
import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable;
import org.apache.hadoop.hive.serde2.io.TimestampWritable;
import org.apache.hadoop.hive.serde2.lazy.LazyArray;
import org.apache.hadoop.hive.serde2.lazy.LazyMap;
import org.apache.hadoop.hive.serde2.lazy.LazyNonPrimitive;
import org.apache.hadoop.hive.serde2.lazy.LazyPrimitive;
import org.apache.hadoop.hive.serde2.lazy.LazyStruct;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.MapTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
import org.apache.hadoop.io.BooleanWritable;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.ObjectWritable;
import org.apache.hadoop.io.ShortWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* SerDe to serialize Dataset Objects.
*/
public class DatasetSerDe implements SerDe {
private static final Gson GSON = new Gson();
private static final Logger LOG = LoggerFactory.getLogger(DatasetSerDe.class);
private ArrayList<String> columnNames;
private Type recordType;
@Override
public void initialize(Configuration entries, Properties properties) throws SerDeException {
// The column names are saved as the given inspector to #serialize doesn't preserves them
// - maybe because it's an external table
columnNames = new ArrayList<String>(Arrays.asList(StringUtils.split(properties.getProperty("columns"), ",")));
String datasetName = properties.getProperty(Constants.Explore.DATASET_NAME);
try {
if (entries != null) {
// Here, we can't say whether Hive wants to read the table, or write to it
Configuration conf = new Configuration(entries);
conf.set(Constants.Explore.DATASET_NAME, datasetName);
recordType = DatasetAccessor.getRecordType(conf);
} else {
// When initialize is called to write to a table, entries is null
try {
recordType = DatasetAccessor.getRecordWritableType(datasetName);
} catch (NullJobConfException e) {
// This is the case when this serDe is used by Hive only for its serialize method. In that case,
// We don't need to initialize a context since serialize does not need any dataset information.
LOG.warn("Could not initialize record writable dataset. Carrying on.");
recordType = null;
}
}
} catch (IOException e) {
LOG.error("Got exception while trying to instantiate dataset {}", datasetName, e);
throw new SerDeException(e);
}
}
@Override
public Class<? extends Writable> getSerializedClass() {
return Text.class;
}
@Override
public Writable serialize(Object o, ObjectInspector objectInspector) throws SerDeException {
// NOTE: the object inspector here is not one that we build. It's a default one that Hive built,
// that contains generic names for columns. The object is a list of objects, each element
// representing one attribute of the Record type.
// The object and the objectInspector represent one row of a query result to write into a dataset.
// Therefore, it is not guaranteed that the object exactly matches the schema of the dataset
// we want to write into.
if (!(objectInspector instanceof StructObjectInspector)) {
throw new SerDeException("Trying to serialize with unknown object inspector type " +
objectInspector.getClass().getName() + ". Expected StructObjectInspector.");
}
//overwrite field names (as they get lost by Hive)
StructTypeInfo structTypeInfo = (StructTypeInfo) TypeInfoUtils.getTypeInfoFromObjectInspector(objectInspector);
structTypeInfo.setAllStructFieldNames(columnNames);
List<TypeInfo> info = structTypeInfo.getAllStructFieldTypeInfos();
List<String> names = structTypeInfo.getAllStructFieldNames();
Map<String, Object> structMap = Maps.newConcurrentMap();
List<Object> struct = ((StructObjectInspector) objectInspector).getStructFieldsDataAsList(o);
for (int structIndex = 0; structIndex < info.size(); structIndex++) {
Object obj = struct.get(structIndex);
if (obj instanceof LazyNonPrimitive || obj instanceof LazyPrimitive) {
// In case the SerDe that deserialized the object is the one of a native table
structMap.put(names.get(structIndex),
fromLazyObject(info.get(structIndex), obj));
} else if (obj instanceof LongWritable) {
// TODO take care of all the writables
structMap.put(names.get(structIndex), ((LongWritable) obj).get());
} else {
// In case the deserializer is the DatasetSerDe
structMap.put(names.get(structIndex), obj);
}
}
// TODO Improve serialization logic - REACTOR-927
return new Text(GSON.toJson(structMap));
}
@Override
public SerDeStats getSerDeStats() {
// TODO: add real Sataset stats - REACTOR-278
return new SerDeStats();
}
@Override
public Object deserialize(Writable writable) throws SerDeException {
ObjectWritable objectWritable = (ObjectWritable) writable;
return objectWritable.get();
}
@Override
public ObjectInspector getObjectInspector() throws SerDeException {
Preconditions.checkNotNull(recordType, "Record type should not be null.");
return ObjectInspectorFactory.getReflectionObjectInspector(recordType);
}
private Object fromLazyObject(TypeInfo type, Object data) {
if (data == null) {
return null;
}
switch (type.getCategory()) {
case PRIMITIVE:
Writable writable = ((LazyPrimitive) data).getWritableObject();
if (writable instanceof IntWritable) {
return ((IntWritable) writable).get();
} else if (writable instanceof LongWritable) {
return ((LongWritable) writable).get();
} else if (writable instanceof ShortWritable) {
return ((ShortWritable) writable).get();
} else if (writable instanceof BooleanWritable) {
return ((BooleanWritable) writable).get();
} else if (writable instanceof DoubleWritable) {
return ((DoubleWritable) writable).get();
} else if (writable instanceof FloatWritable) {
return ((FloatWritable) writable).get();
} else if (writable instanceof Text) {
return writable.toString();
} else if (writable instanceof BytesWritable) {
return ((BytesWritable) writable).getBytes();
} else if (writable instanceof ByteWritable) {
return ((ByteWritable) writable).get();
} else if (writable instanceof DateWritable) {
return ((DateWritable) writable).get();
} else if (writable instanceof org.apache.hadoop.hive.serde2.io.ShortWritable) {
return ((org.apache.hadoop.hive.serde2.io.ShortWritable) writable).get();
} else if (writable instanceof HiveBaseCharWritable) {
return ((HiveBaseCharWritable) writable).getTextValue().toString();
} else if (writable instanceof TimestampWritable) {
return ((TimestampWritable) writable).getTimestamp();
} else if (writable instanceof org.apache.hadoop.hive.serde2.io.DoubleWritable) {
return ((org.apache.hadoop.hive.serde2.io.DoubleWritable) writable).get();
} else if (writable instanceof HiveDecimalWritable) {
return ((HiveDecimalWritable) writable).getHiveDecimal();
} else if (writable instanceof NullWritable) {
return null;
}
return writable.toString();
case LIST:
ListTypeInfo listType = (ListTypeInfo) type;
TypeInfo listElementType = listType.getListElementTypeInfo();
List<Object> list = ((LazyArray) data).getList();
if (list.isEmpty()) {
return ImmutableList.of();
}
Object[] arrayContent = new Object[list.size()];
for (int i = 0; i < arrayContent.length; i++) {
arrayContent[i] = fromLazyObject(listElementType, list.get(i));
}
return arrayContent;
case MAP:
MapTypeInfo mapType = (MapTypeInfo) type;
Map<Object, Object> mapContent = Maps.newConcurrentMap();
Map<Object, Object> map = ((LazyMap) data).getMap();
for (Map.Entry<Object, Object> entry : map.entrySet()) {
mapContent.put(fromLazyObject(mapType.getMapKeyTypeInfo(), entry.getKey()),
fromLazyObject(mapType.getMapValueTypeInfo(), entry.getValue()));
}
return mapContent;
case STRUCT:
StructTypeInfo structType = (StructTypeInfo) type;
List<TypeInfo> info = structType.getAllStructFieldTypeInfos();
List<String> names = structType.getAllStructFieldNames();
Map<String, Object> structMap = Maps.newConcurrentMap();
List<Object> struct = ((LazyStruct) data).getFieldsAsList();
for (int structIndex = 0; structIndex < info.size(); structIndex++) {
structMap.put(names.get(structIndex),
fromLazyObject(info.get(structIndex), struct.get(structIndex)));
}
return structMap;
case UNION:
throw new UnsupportedOperationException("union not yet supported");
default:
return data.toString();
}
}
}
|
Fix writing from native tables to datasets
|
explore/src/main/java/co/cask/cdap/hive/datasets/DatasetSerDe.java
|
Fix writing from native tables to datasets
|
<ide><path>xplore/src/main/java/co/cask/cdap/hive/datasets/DatasetSerDe.java
<ide> public void initialize(Configuration entries, Properties properties) throws SerDeException {
<ide> // The column names are saved as the given inspector to #serialize doesn't preserves them
<ide> // - maybe because it's an external table
<add> // The columns property comes from the Hive metastore, which has it from the create table statement
<add> // It is then important that this schema be accurate and in the right order - the same order as
<add> // object inspectors will reflect them.
<ide> columnNames = new ArrayList<String>(Arrays.asList(StringUtils.split(properties.getProperty("columns"), ",")));
<ide>
<ide> String datasetName = properties.getProperty(Constants.Explore.DATASET_NAME);
<ide> List<TypeInfo> info = structTypeInfo.getAllStructFieldTypeInfos();
<ide> List<String> names = structTypeInfo.getAllStructFieldNames();
<ide>
<del> Map<String, Object> structMap = Maps.newConcurrentMap();
<del> List<Object> struct = ((StructObjectInspector) objectInspector).getStructFieldsDataAsList(o);
<add> Map<String, Object> recordMap = Maps.newConcurrentMap();
<add> List<Object> recordObjects = ((StructObjectInspector) objectInspector).getStructFieldsDataAsList(o);
<ide>
<ide> for (int structIndex = 0; structIndex < info.size(); structIndex++) {
<del> Object obj = struct.get(structIndex);
<add> Object obj = recordObjects.get(structIndex);
<ide> if (obj instanceof LazyNonPrimitive || obj instanceof LazyPrimitive) {
<ide> // In case the SerDe that deserialized the object is the one of a native table
<del> structMap.put(names.get(structIndex),
<del> fromLazyObject(info.get(structIndex), obj));
<del> } else if (obj instanceof LongWritable) {
<del> // TODO take care of all the writables
<del> structMap.put(names.get(structIndex), ((LongWritable) obj).get());
<add> recordMap.put(names.get(structIndex), fromLazyObject(info.get(structIndex), obj));
<add> } else if (obj instanceof Writable) {
<add> // Native tables sometimes introduce primitive Writable objects at this point
<add> recordMap.put(names.get(structIndex), fromWritable((Writable) obj));
<ide> } else {
<ide> // In case the deserializer is the DatasetSerDe
<del> structMap.put(names.get(structIndex), obj);
<add> recordMap.put(names.get(structIndex), obj);
<ide> }
<ide> }
<ide>
<ide> // TODO Improve serialization logic - REACTOR-927
<del> return new Text(GSON.toJson(structMap));
<add> return new Text(GSON.toJson(recordMap));
<ide> }
<ide>
<ide> @Override
<ide> return ObjectInspectorFactory.getReflectionObjectInspector(recordType);
<ide> }
<ide>
<add> private Object fromWritable(Writable writable) {
<add> if (writable instanceof IntWritable) {
<add> return ((IntWritable) writable).get();
<add> } else if (writable instanceof LongWritable) {
<add> return ((LongWritable) writable).get();
<add> } else if (writable instanceof ShortWritable) {
<add> return ((ShortWritable) writable).get();
<add> } else if (writable instanceof BooleanWritable) {
<add> return ((BooleanWritable) writable).get();
<add> } else if (writable instanceof DoubleWritable) {
<add> return ((DoubleWritable) writable).get();
<add> } else if (writable instanceof FloatWritable) {
<add> return ((FloatWritable) writable).get();
<add> } else if (writable instanceof Text) {
<add> return writable.toString();
<add> } else if (writable instanceof BytesWritable) {
<add> return ((BytesWritable) writable).getBytes();
<add> } else if (writable instanceof ByteWritable) {
<add> return ((ByteWritable) writable).get();
<add> } else if (writable instanceof DateWritable) {
<add> return ((DateWritable) writable).get();
<add> } else if (writable instanceof org.apache.hadoop.hive.serde2.io.ShortWritable) {
<add> return ((org.apache.hadoop.hive.serde2.io.ShortWritable) writable).get();
<add> } else if (writable instanceof HiveBaseCharWritable) {
<add> return ((HiveBaseCharWritable) writable).getTextValue().toString();
<add> } else if (writable instanceof TimestampWritable) {
<add> return ((TimestampWritable) writable).getTimestamp();
<add> } else if (writable instanceof org.apache.hadoop.hive.serde2.io.DoubleWritable) {
<add> return ((org.apache.hadoop.hive.serde2.io.DoubleWritable) writable).get();
<add> } else if (writable instanceof HiveDecimalWritable) {
<add> return ((HiveDecimalWritable) writable).getHiveDecimal();
<add> } else if (writable instanceof NullWritable) {
<add> return null;
<add> }
<add> return writable.toString();
<add> }
<add>
<ide> private Object fromLazyObject(TypeInfo type, Object data) {
<ide> if (data == null) {
<ide> return null;
<ide> switch (type.getCategory()) {
<ide> case PRIMITIVE:
<ide> Writable writable = ((LazyPrimitive) data).getWritableObject();
<del> if (writable instanceof IntWritable) {
<del> return ((IntWritable) writable).get();
<del> } else if (writable instanceof LongWritable) {
<del> return ((LongWritable) writable).get();
<del> } else if (writable instanceof ShortWritable) {
<del> return ((ShortWritable) writable).get();
<del> } else if (writable instanceof BooleanWritable) {
<del> return ((BooleanWritable) writable).get();
<del> } else if (writable instanceof DoubleWritable) {
<del> return ((DoubleWritable) writable).get();
<del> } else if (writable instanceof FloatWritable) {
<del> return ((FloatWritable) writable).get();
<del> } else if (writable instanceof Text) {
<del> return writable.toString();
<del> } else if (writable instanceof BytesWritable) {
<del> return ((BytesWritable) writable).getBytes();
<del> } else if (writable instanceof ByteWritable) {
<del> return ((ByteWritable) writable).get();
<del> } else if (writable instanceof DateWritable) {
<del> return ((DateWritable) writable).get();
<del> } else if (writable instanceof org.apache.hadoop.hive.serde2.io.ShortWritable) {
<del> return ((org.apache.hadoop.hive.serde2.io.ShortWritable) writable).get();
<del> } else if (writable instanceof HiveBaseCharWritable) {
<del> return ((HiveBaseCharWritable) writable).getTextValue().toString();
<del> } else if (writable instanceof TimestampWritable) {
<del> return ((TimestampWritable) writable).getTimestamp();
<del> } else if (writable instanceof org.apache.hadoop.hive.serde2.io.DoubleWritable) {
<del> return ((org.apache.hadoop.hive.serde2.io.DoubleWritable) writable).get();
<del> } else if (writable instanceof HiveDecimalWritable) {
<del> return ((HiveDecimalWritable) writable).getHiveDecimal();
<del> } else if (writable instanceof NullWritable) {
<del> return null;
<del> }
<del> return writable.toString();
<add> return fromWritable(writable);
<ide>
<ide> case LIST:
<ide> ListTypeInfo listType = (ListTypeInfo) type;
|
|
Java
|
apache-2.0
|
ba0372acc1840f8c219cefb4edda843895fe9a42
| 0 |
lucasponce/hawkular-alerts,hawkular/hawkular-alerts,hawkular/hawkular-alerts,hawkular/hawkular-alerts,hawkular/hawkular-alerts,lucasponce/hawkular-alerts,lucasponce/hawkular-alerts,lucasponce/hawkular-alerts
|
/*
* Copyright 2015-2017 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.hawkular.alerts.engine.impl.ispn;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hawkular.alerts.api.model.Severity;
import org.hawkular.alerts.api.model.event.Alert;
import org.hawkular.alerts.api.services.AlertsCriteria;
import org.hawkular.commons.log.MsgLogger;
import org.hawkular.commons.log.MsgLogging;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* @author Jay Shaughnessy
* @author Lucas Ponce
*/
public class IspnAlertsServiceImplTest extends IspnBaseServiceImplTest {
static final MsgLogger log = MsgLogging.getMsgLogger(IspnAlertsServiceImplTest.class);
@BeforeClass
public static void init() {
System.setProperty("hawkular.data", "./target/ispn");
alerts = new IspnAlertsServiceImpl();
alerts.init();
}
@Test
public void addAlerts() throws Exception {
int numTenants = 2;
int numTriggers = 5;
int numAlerts = 100;
createTestAlerts(numTenants, numTriggers, numAlerts);
Set<String> tenantIds = new HashSet<>();
tenantIds.add("tenant0");
tenantIds.add("tenant1");
assertEquals(2 * 5 * 100, alerts.getAlerts(tenantIds, null, null).size());
tenantIds.remove("tenant0");
assertEquals(1 * 5 * 100, alerts.getAlerts(tenantIds, null, null).size());
List<Alert> testAlerts = alerts.getAlerts(tenantIds, null, null);
tenantIds.clear();
Set<String> alertIds = new HashSet<>();
for (int i = 0; i < 3; i++) {
Alert alertX = testAlerts.get(i);
tenantIds.add(alertX.getTenantId());
alertIds.add(alertX.getAlertId());
}
AlertsCriteria criteria = new AlertsCriteria();
criteria.setAlertIds(alertIds);
assertEquals(3, alerts.getAlerts(tenantIds, criteria, null).size());
deleteTestAlerts(numTenants);
}
@Test
public void evaluateTagQuery() throws Exception {
StringBuilder query = new StringBuilder();
String e1 = "tagA";
alerts.parseTagQuery(e1, query);
assertEquals("('tagA')", query.toString());
String e2 = "not tagA";
query = new StringBuilder();
alerts.parseTagQuery(e2, query);
assertEquals("(not 'tagA')", query.toString());
String e3 = "tagA = 'abc'";
query = new StringBuilder();
alerts.parseTagQuery(e3, query);
assertEquals("('tagA' and (/abc/))", query.toString().trim());
String e4 = " tagA != 'abc'";
query = new StringBuilder();
alerts.parseTagQuery(e4, query);
assertEquals("('tagA' and (not /abc/))", query.toString().trim());
String e5 = "tagA IN ['abc', 'def', 'ghi']";
query = new StringBuilder();
alerts.parseTagQuery(e5, query);
assertEquals("('tagA' and (/abc/ or /def/ or /ghi/))", query.toString().trim());
String e6 = "tagA NOT IN ['abc', 'def', 'ghi']";
query = new StringBuilder();
alerts.parseTagQuery(e6, query);
assertEquals("('tagA' and (not /abc/ and not /def/ and not /ghi/))", query.toString().trim());
String e7 = "tagA = '*'";
query = new StringBuilder();
alerts.parseTagQuery(e7, query);
assertEquals("('tagA' and (/.*/))", query.toString().trim());
String e8 = "tagA = abc";
query = new StringBuilder();
alerts.parseTagQuery(e8, query);
assertEquals("('tagA' and ('abc'))", query.toString().trim());
String e9 = " tagA != abc";
query = new StringBuilder();
alerts.parseTagQuery(e9, query);
assertEquals("('tagA' and (not 'abc'))", query.toString().trim());
String e10 = "tagA IN [abc, def, ghi]";
query = new StringBuilder();
alerts.parseTagQuery(e10, query);
assertEquals("('tagA' and ('abc' or 'def' or 'ghi'))", query.toString().trim());
String e11 = "tagA NOT IN [abc, def, ghi]";
query = new StringBuilder();
alerts.parseTagQuery(e11, query);
assertEquals("('tagA' and (not 'abc' and not 'def' and not 'ghi'))", query.toString().trim());
String e12 = "tagA = *";
query = new StringBuilder();
try {
alerts.parseTagQuery(e12, query);
fail("* should be used with single quotes");
} catch (Exception e) {
// Expected
}
String e13 = "tagA-01";
query = new StringBuilder();
alerts.parseTagQuery(e13, query);
assertEquals("('tagA-01')", query.toString().trim());
String e14 = "tagA and not tagB";
query = new StringBuilder();
alerts.parseTagQuery(e14, query);
assertEquals("(('tagA') and (not 'tagB'))", query.toString().trim());
String e15 = "not tagB and tagA";
query = new StringBuilder();
alerts.parseTagQuery(e15, query);
assertEquals("(('tagA') and (not 'tagB'))", query.toString().trim());
String e16 = "not tagB or tagA";
query = new StringBuilder();
alerts.parseTagQuery(e16, query);
assertEquals("(('tagA') or (not 'tagB'))", query.toString().trim());
String e17 = "tagA = 'abc' and tagB = 'def'";
query = new StringBuilder();
alerts.parseTagQuery(e17, query);
assertEquals("(('tagA' and (/abc/)) and ('tagB' and (/def/)))", query.toString().trim());
String e18 = "tagA and not tagB or tagC";
query = new StringBuilder();
alerts.parseTagQuery(e18, query);
assertEquals("(('tagC') or (('tagA') and (not 'tagB')))", query.toString().trim());
String e19 = "not tagA and tagB or tagC";
query = new StringBuilder();
alerts.parseTagQuery(e19, query);
assertEquals("(('tagC') or (('tagB') and (not 'tagA')))", query.toString().trim());
String e20 = "not tagA or tagB and tagC";
query = new StringBuilder();
alerts.parseTagQuery(e20, query);
assertEquals("(('tagC') and (('tagB') or (not 'tagA')))", query.toString().trim());
String e21 = "tagA and (not tagB or tagC)";
query = new StringBuilder();
alerts.parseTagQuery(e21, query);
assertEquals("(('tagA') and (('tagC') or (not 'tagB')))", query.toString().trim());
String e22 = "tagA and (not tagB and tagC)";
query = new StringBuilder();
alerts.parseTagQuery(e22, query);
assertEquals("(('tagA') and (('tagC') and (not 'tagB')))", query.toString().trim());
String e23 = "(not tagB or tagC) and tagA";
query = new StringBuilder();
alerts.parseTagQuery(e23, query);
assertEquals("(('tagA') and (('tagC') or (not 'tagB')))", query.toString().trim());
String e24 = "(tagA and not tagB) and (not tagC or tagD)";
query = new StringBuilder();
alerts.parseTagQuery(e24, query);
assertEquals("((('tagA') and (not 'tagB')) and (('tagD') or (not 'tagC')))", query.toString().trim());
}
@Test
public void addAlertTagsTest() throws Exception {
int numTenants = 2;
int numTriggers = 5;
int numAlerts = 2;
createTestAlerts(numTenants, numTriggers, numAlerts);
Set<String> tenantIds = new HashSet<>();
tenantIds.add("tenant0");
tenantIds.add("tenant1");
List<Alert> nonTaggedAlerts = alerts.getAlerts(tenantIds, null, null);
assertEquals(2 * 5 * 2, nonTaggedAlerts.size());
int count = 0;
for (Alert alert : nonTaggedAlerts) {
Map<String, String> tags = new HashMap<>();
if (count < 5) {
tags.put("tag1", "value" + (count % 5));
} else if (count >= 5 && count < 10) {
tags.put("tag2", "value" + (count % 5));
} else {
// Yes, tag3/valueX can be repeated twice
tags.put("tag3", "value" + (count % 5));
}
alerts.addAlertTags(alert.getTenantId(), Arrays.asList(alert.getAlertId()), tags);
count++;
}
AlertsCriteria criteria = new AlertsCriteria();
criteria.setTagQuery("tag1");
List<Alert> tag1Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5, tag1Alerts.size());
criteria.setTagQuery("tag2");
List<Alert> tag2Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5, tag2Alerts.size());
criteria.setTagQuery("tag3");
List<Alert> tag3Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(10, tag3Alerts.size());
criteria.setTagQuery("tag1 = 'value1'");
List<Alert> tag1Value1Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(1, tag1Value1Alerts.size());
criteria.setTagQuery("tag2 = 'value1'");
List<Alert> tag2Value1Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(1, tag2Value1Alerts.size());
criteria.setTagQuery("tag3 = 'value2'");
List<Alert> tag3Value2Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(2, tag3Value2Alerts.size());
criteria.setTagQuery("tag1 = 'value10'");
List<Alert> tag1Value10Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(0, tag1Value10Alerts.size());
criteria.setTagQuery("tag1 or tag2");
List<Alert> tag1OrTag2Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(10, tag1OrTag2Alerts.size());
criteria.setTagQuery("tag1 = 'value.*'");
List<Alert> tag1ValueAlerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5, tag1ValueAlerts.size());
criteria.setTagQuery("tag1 != 'value0'");
List<Alert> tag1NotValue0Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(4, tag1NotValue0Alerts.size());
criteria.setTagQuery("tag1 != 'value0' or tag2 != 'value0'");
List<Alert> tag1NotValue0Tag2NotValue0Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(8, tag1NotValue0Tag2NotValue0Alerts.size());
deleteTestAlerts(numTenants);
}
@Test
public void queryAlertsByTriggerId() throws Exception {
int numTenants = 2;
int numTriggers = 5;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
Set<String> tenantIds = new HashSet<>();
tenantIds.add("tenant0");
tenantIds.add("tenant1");
AlertsCriteria criteria = new AlertsCriteria();
criteria.setTriggerId("trigger0");
List<Alert> trigger0Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(10, trigger0Alerts.size());
criteria.setTriggerIds(Arrays.asList("trigger0", "trigger1", "trigger2"));
List<Alert> trigger012Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(30, trigger012Alerts.size());
deleteTestAlerts(numTenants);
}
@Test
public void queryAlertsByCTime() throws Exception {
int numTenants = 1;
int numTriggers = 5;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
Set<String> tenantIds = new HashSet<>();
tenantIds.add("tenant0");
AlertsCriteria criteria = new AlertsCriteria();
criteria.setStartTime(2l);
criteria.setEndTime(2l);
List<Alert> ctime2Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5, ctime2Alerts.size());
criteria.setEndTime(null);
List<Alert> ctimeGTE2Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5 * 4, ctimeGTE2Alerts.size());
deleteTestAlerts(numTenants);
}
@Test
public void queryAlertsByResolvedTime() throws Exception {
int numTenants = 1;
int numTriggers = 5;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
Set<String> tenantIds = new HashSet<>();
tenantIds.add("tenant0");
AlertsCriteria criteria = new AlertsCriteria();
criteria.setStartResolvedTime(1l);
// Alerts on stime 1 and 4 are RESOLVED
List<Alert> stimeGTE2Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5 * 2, stimeGTE2Alerts.size());
deleteTestAlerts(numTenants);
}
@Test
public void queryAlertsByAcknowledgedTime() throws Exception {
int numTenants = 1;
int numTriggers = 5;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
Set<String> tenantIds = new HashSet<>();
tenantIds.add("tenant0");
AlertsCriteria criteria = new AlertsCriteria();
criteria.setStartAckTime(1l);
// Alerts on stime 2 and 5 are ACKNOWLEDGED
List<Alert> stimeGTE2Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5 * 2, stimeGTE2Alerts.size());
deleteTestAlerts(numTenants);
}
@Test
public void queryAlertsByStatusTime() throws Exception {
int numTenants = 1;
int numTriggers = 5;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
Set<String> tenantIds = new HashSet<>();
tenantIds.add("tenant0");
AlertsCriteria criteria = new AlertsCriteria();
criteria.setStartStatusTime(5l);
criteria.setEndStatusTime(5l);
List<Alert> stimeGTE5Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5, stimeGTE5Alerts.size());
deleteTestAlerts(numTenants);
}
@Test
public void queryAlertsBySeverity() throws Exception {
int numTenants = 1;
int numTriggers = 5;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
Set<String> tenantIds = new HashSet<>();
tenantIds.add("tenant0");
AlertsCriteria criteria = new AlertsCriteria();
criteria.setSeverities(Arrays.asList(Severity.LOW));
// Alerts on stime 2 and 5 are severity LOW
List<Alert> lowAlerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5 * 2, lowAlerts.size());
// Alerts on stime 3 are severity CRITICAL
criteria.setSeverities(Arrays.asList(Severity.CRITICAL));
List<Alert> criticalAlerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5, criticalAlerts.size());
// Alerts on stime 1 and 4 are severity MEDIUM
criteria.setSeverities(Arrays.asList(Severity.MEDIUM));
List<Alert> mediumAlerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5 * 2, mediumAlerts.size());
criteria.setSeverities(Arrays.asList(Severity.MEDIUM, Severity.CRITICAL));
List<Alert> mediumCriticalAlerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5 * 3, mediumCriticalAlerts.size());
deleteTestAlerts(numTenants);
}
@Test
public void queryAlertsByStatus() throws Exception {
int numTenants = 1;
int numTriggers = 5;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
Set<String> tenantIds = new HashSet<>();
tenantIds.add("tenant0");
AlertsCriteria criteria = new AlertsCriteria();
criteria.setStatus(Alert.Status.OPEN);
List<Alert> openAlerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5, openAlerts.size());
criteria.setStatus(Alert.Status.ACKNOWLEDGED);
List<Alert> acknowledgedAlerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5 * 2, acknowledgedAlerts.size());
criteria.setStatus(Alert.Status.RESOLVED);
List<Alert> resolvedAlerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5 * 2, resolvedAlerts.size());
criteria.setStatusSet(Arrays.asList(Alert.Status.ACKNOWLEDGED, Alert.Status.RESOLVED));
List<Alert> ackResolvedAlerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5 * 4, ackResolvedAlerts.size());
deleteTestAlerts(numTenants);
}
@Test
public void queryAlertsCombined() throws Exception {
int numTenants = 1;
int numTriggers = 5;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
Set<String> tenantIds = new HashSet<>();
tenantIds.add("tenant0");
AlertsCriteria criteria = new AlertsCriteria();
criteria.setStatus(Alert.Status.RESOLVED);
criteria.setTriggerId("trigger0");
criteria.setStartTime(3l);
List<Alert> resolvedAlerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(1, resolvedAlerts.size());
deleteTestAlerts(numTenants);
}
@Test
public void ackAlert() throws Exception {
int numTenants = 1;
int numTriggers = 1;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
AlertsCriteria criteria = new AlertsCriteria();
criteria.setStatus(Alert.Status.OPEN);
List<Alert> openAlerts = alerts.getAlerts("tenant0", criteria, null);
assertEquals(1, openAlerts.size());
String alertId = openAlerts.iterator().next().getAlertId();
alerts.ackAlerts("tenant0", Arrays.asList(alertId), "test", "ACK from ackAlert() test");
openAlerts = alerts.getAlerts("tenant0", criteria, null);
assertEquals(0, openAlerts.size());
Alert ackAlert = alerts.getAlert("tenant0", alertId, false);
assertEquals(Alert.Status.ACKNOWLEDGED, ackAlert.getStatus());
deleteTestAlerts(numTenants);
}
@Test
public void addNote() throws Exception {
int numTenants = 1;
int numTriggers = 1;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
AlertsCriteria criteria = new AlertsCriteria();
criteria.setStatus(Alert.Status.OPEN);
List<Alert> openAlerts = alerts.getAlerts("tenant0", criteria, null);
assertEquals(1, openAlerts.size());
String alertId = openAlerts.iterator().next().getAlertId();
alerts.addNote("tenant0", alertId, "xyz1", "Note1");
Alert alert = alerts.getAlert("tenant0", alertId, false);
assertEquals(1, alert.getNotes().size());
alerts.addNote("tenant0", alertId, "xyz2", "Note2");
alerts.addNote("tenant0", alertId, "xyz3", "Note3");
alert = alerts.getAlert("tenant0", alertId, false);
assertEquals(3, alert.getNotes().size());
deleteTestAlerts(numTenants);
}
@Test
public void resolveAlert() throws Exception {
int numTenants = 1;
int numTriggers = 1;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
AlertsCriteria criteria = new AlertsCriteria();
criteria.setStatus(Alert.Status.OPEN);
List<Alert> openAlerts = alerts.getAlerts("tenant0", criteria, null);
assertEquals(1, openAlerts.size());
String alertId = openAlerts.iterator().next().getAlertId();
alerts.resolveAlerts("tenant0", Arrays.asList(alertId), "test", "RESOLVED from resolveAlert() test", null);
openAlerts = alerts.getAlerts("tenant0", criteria, null);
assertEquals(0, openAlerts.size());
Alert resolvedAlert = alerts.getAlert("tenant0", alertId, false);
assertEquals(Alert.Status.RESOLVED, resolvedAlert.getStatus());
deleteTestAlerts(numTenants);
}
@Test
public void resolveAlertForTrigger() throws Exception {
int numTenants = 1;
int numTriggers = 1;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
alerts.resolveAlertsForTrigger("tenant0", "trigger0", "test", "RESOLVED from resolveAlert() test", null);
AlertsCriteria criteria = new AlertsCriteria();
criteria.setStatus(Alert.Status.RESOLVED);
List<Alert> resolvedAlerts = alerts.getAlerts("tenant0", criteria, null);
assertEquals(5, resolvedAlerts.size());
deleteTestAlerts(numTenants);
}
@Test
public void addRemoveTag() throws Exception {
int numTenants = 1;
int numTriggers = 1;
int numAlerts = 1;
createTestAlerts(numTenants, numTriggers, numAlerts);
List<Alert> nonTaggedAlerts = alerts.getAlerts("tenant0", null, null);
assertEquals(1, nonTaggedAlerts.size());
String alertId = nonTaggedAlerts.iterator().next().getAlertId();
Map<String, String> tags = new HashMap<>();
tags.put("tag1", "value1");
tags.put("tag2", "value2");
tags.put("tag3", "value3");
alerts.addAlertTags("tenant0", Arrays.asList(alertId), tags);
Alert alert = alerts.getAlert("tenant0", alertId, false);
assertEquals(3, alert.getTags().size());
alerts.removeAlertTags("tenant0", Arrays.asList(alertId), Arrays.asList("tag1", "tag2"));
alert = alerts.getAlert("tenant0", alertId, false);
assertEquals(1, alert.getTags().size());
assertEquals("value3", alert.getTags().get("tag3"));
deleteTestAlerts(numTenants);
}
}
|
engine/src/test/java/org/hawkular/alerts/engine/impl/ispn/IspnAlertsServiceImplTest.java
|
/*
* Copyright 2015-2017 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.hawkular.alerts.engine.impl.ispn;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hawkular.alerts.api.model.Severity;
import org.hawkular.alerts.api.model.event.Alert;
import org.hawkular.alerts.api.services.AlertsCriteria;
import org.hawkular.commons.log.MsgLogger;
import org.hawkular.commons.log.MsgLogging;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* @author Jay Shaughnessy
* @author Lucas Ponce
*/
public class IspnAlertsServiceImplTest extends IspnBaseServiceImplTest {
static final MsgLogger log = MsgLogging.getMsgLogger(IspnAlertsServiceImplTest.class);
@BeforeClass
public static void init() {
System.setProperty("hawkular.data", "./target/ispn");
alerts = new IspnAlertsServiceImpl();
alerts.init();
}
@Test
public void addAlerts() throws Exception {
int numTenants = 2;
int numTriggers = 5;
int numAlerts = 100;
createTestAlerts(numTenants, numTriggers, numAlerts);
Set<String> tenantIds = new HashSet<>();
tenantIds.add("tenant0");
tenantIds.add("tenant1");
assertEquals(2 * 5 * 100, alerts.getAlerts(tenantIds, null, null).size());
tenantIds.remove("tenant0");
assertEquals(1 * 5 * 100, alerts.getAlerts(tenantIds, null, null).size());
List<Alert> testAlerts = alerts.getAlerts(tenantIds, null, null);
tenantIds.clear();
Set<String> alertIds = new HashSet<>();
for (int i = 0; i < 3; i++) {
Alert alertX = testAlerts.get(i);
tenantIds.add(alertX.getTenantId());
alertIds.add(alertX.getAlertId());
}
AlertsCriteria criteria = new AlertsCriteria();
criteria.setAlertIds(alertIds);
assertEquals(3, alerts.getAlerts(tenantIds, criteria, null).size());
deleteTestAlerts(numTenants);
}
@Test
public void evaluateTagQuery() throws Exception {
StringBuilder query = new StringBuilder();
String e1 = "tagA";
alerts.parseTagQuery(e1, query);
assertEquals("('tagA')", query.toString());
String e2 = "not tagA";
query = new StringBuilder();
alerts.parseTagQuery(e2, query);
assertEquals("(not 'tagA')", query.toString());
String e3 = "tagA = 'abc'";
query = new StringBuilder();
alerts.parseTagQuery(e3, query);
assertEquals("('tagA' and (/abc/))", query.toString().trim());
String e4 = " tagA != 'abc'";
query = new StringBuilder();
alerts.parseTagQuery(e4, query);
assertEquals("('tagA' and (not /abc/))", query.toString().trim());
String e5 = "tagA IN ['abc', 'def', 'ghi']";
query = new StringBuilder();
alerts.parseTagQuery(e5, query);
assertEquals("('tagA' and (/abc/ or /def/ or /ghi/))", query.toString().trim());
String e6 = "tagA NOT IN ['abc', 'def', 'ghi']";
query = new StringBuilder();
alerts.parseTagQuery(e6, query);
assertEquals("('tagA' and (not /abc/ and not /def/ and not /ghi/))", query.toString().trim());
String e7 = "tagA = '*'";
query = new StringBuilder();
alerts.parseTagQuery(e7, query);
assertEquals("('tagA' and (/.*/))", query.toString().trim());
String e8 = "tagA = abc";
query = new StringBuilder();
alerts.parseTagQuery(e8, query);
assertEquals("('tagA' and ('abc'))", query.toString().trim());
String e9 = " tagA != abc";
query = new StringBuilder();
alerts.parseTagQuery(e9, query);
assertEquals("('tagA' and (not 'abc'))", query.toString().trim());
String e10 = "tagA IN [abc, def, ghi]";
query = new StringBuilder();
alerts.parseTagQuery(e10, query);
assertEquals("('tagA' and ('abc' or 'def' or 'ghi'))", query.toString().trim());
String e11 = "tagA NOT IN [abc, def, ghi]";
query = new StringBuilder();
alerts.parseTagQuery(e11, query);
assertEquals("('tagA' and (not 'abc' and not 'def' and not 'ghi'))", query.toString().trim());
String e12 = "tagA = *";
query = new StringBuilder();
try {
alerts.parseTagQuery(e12, query);
fail("* should be used with single quotes");
} catch (Exception e) {
// Expected
}
String e13 = "tagA-01";
query = new StringBuilder();
alerts.parseTagQuery(e13, query);
assertEquals("('tagA-01')", query.toString().trim());
String e14 = "tagA and not tagB";
query = new StringBuilder();
alerts.parseTagQuery(e14, query);
assertEquals("(('tagA') and (not 'tagB'))", query.toString().trim());
String e15 = "not tagB and tagA";
query = new StringBuilder();
alerts.parseTagQuery(e15, query);
assertEquals("(('tagA') and (not 'tagB'))", query.toString().trim());
String e16 = "not tagB or tagA";
query = new StringBuilder();
alerts.parseTagQuery(e16, query);
assertEquals("(('tagA') or (not 'tagB'))", query.toString().trim());
String e17 = "tagA = 'abc' and tagB = 'def'";
query = new StringBuilder();
alerts.parseTagQuery(e17, query);
assertEquals("(('tagA' and (/abc/)) and ('tagB' and (/def/)))", query.toString().trim());
String e18 = "tagA and not tagB or tagC";
query = new StringBuilder();
alerts.parseTagQuery(e18, query);
assertEquals("(('tagC') or (('tagA') and (not 'tagB')))", query.toString().trim());
String e19 = "not tagA and tagB or tagC";
query = new StringBuilder();
alerts.parseTagQuery(e19, query);
assertEquals("(('tagC') or (('tagB') and (not 'tagA')))", query.toString().trim());
String e20 = "not tagA or tagB and tagC";
query = new StringBuilder();
alerts.parseTagQuery(e20, query);
assertEquals("(('tagC') and (('tagB') or (not 'tagA')))", query.toString().trim());
String e21 = "tagA and (not tagB or tagC)";
query = new StringBuilder();
alerts.parseTagQuery(e21, query);
assertEquals("(('tagA') and (('tagC') or (not 'tagB')))", query.toString().trim());
String e22 = "tagA and (not tagB and tagC)";
query = new StringBuilder();
alerts.parseTagQuery(e22, query);
assertEquals("(('tagA') and (('tagC') and (not 'tagB')))", query.toString().trim());
String e23 = "(not tagB or tagC) and tagA";
query = new StringBuilder();
alerts.parseTagQuery(e23, query);
assertEquals("(('tagA') and (('tagC') or (not 'tagB')))", query.toString().trim());
String e24 = "(tagA and not tagB) and (not tagC or tagD)";
query = new StringBuilder();
alerts.parseTagQuery(e24, query);
assertEquals("((('tagA') and (not 'tagB')) and (('tagD') or (not 'tagC')))", query.toString().trim());
}
@Test
public void addAlertTagsTest() throws Exception {
int numTenants = 2;
int numTriggers = 5;
int numAlerts = 2;
createTestAlerts(numTenants, numTriggers, numAlerts);
Set<String> tenantIds = new HashSet<>();
tenantIds.add("tenant0");
tenantIds.add("tenant1");
List<Alert> nonTaggedAlerts = alerts.getAlerts(tenantIds, null, null);
assertEquals(2 * 5 * 2, nonTaggedAlerts.size());
int count = 0;
for (Alert alert : nonTaggedAlerts) {
Map<String, String> tags = new HashMap<>();
if (count < 5) {
tags.put("tag1", "value" + (count % 5));
} else if (count >= 5 && count < 10) {
tags.put("tag2", "value" + (count % 5));
} else {
// Yes, tag3/valueX can be repeated twice
tags.put("tag3", "value" + (count % 5));
}
alerts.addAlertTags(alert.getTenantId(), Arrays.asList(alert.getAlertId()), tags);
count++;
}
AlertsCriteria criteria = new AlertsCriteria();
criteria.setTagQuery("tag1");
List<Alert> tag1Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5, tag1Alerts.size());
criteria.setTagQuery("tag2");
List<Alert> tag2Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5, tag2Alerts.size());
criteria.setTagQuery("tag3");
List<Alert> tag3Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(10, tag3Alerts.size());
criteria.setTagQuery("tag1 = 'value1'");
List<Alert> tag1Value1Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(1, tag1Value1Alerts.size());
criteria.setTagQuery("tag2 = 'value1'");
List<Alert> tag2Value1Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(1, tag2Value1Alerts.size());
criteria.setTagQuery("tag3 = 'value2'");
List<Alert> tag3Value2Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(2, tag3Value2Alerts.size());
criteria.setTagQuery("tag1 = 'value10'");
List<Alert> tag1Value10Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(0, tag1Value10Alerts.size());
criteria.setTagQuery("tag1 or tag2");
List<Alert> tag1OrTag2Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(10, tag1OrTag2Alerts.size());
criteria.setTagQuery("tag1 = 'value.*'");
List<Alert> tag1ValueAlerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5, tag1ValueAlerts.size());
criteria.setTagQuery("tag1 != 'value0'");
List<Alert> tag1NotValue0Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(4, tag1NotValue0Alerts.size());
criteria.setTagQuery("tag1 != 'value0' or tag2 != 'value0'");
List<Alert> tag1NotValue0Tag2NotValue0Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(8, tag1NotValue0Tag2NotValue0Alerts.size());
deleteTestAlerts(numTenants);
}
@Test
public void queryAlertsByTriggerId() throws Exception {
int numTenants = 2;
int numTriggers = 5;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
Set<String> tenantIds = new HashSet<>();
tenantIds.add("tenant0");
tenantIds.add("tenant1");
AlertsCriteria criteria = new AlertsCriteria();
criteria.setTriggerId("trigger0");
List<Alert> trigger0Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(10, trigger0Alerts.size());
criteria.setTriggerIds(Arrays.asList("trigger0", "trigger1", "trigger2"));
List<Alert> trigger012Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(30, trigger012Alerts.size());
deleteTestAlerts(numTenants);
}
@Test
public void queryAlertsByCTime() throws Exception {
int numTenants = 1;
int numTriggers = 5;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
Set<String> tenantIds = new HashSet<>();
tenantIds.add("tenant0");
AlertsCriteria criteria = new AlertsCriteria();
criteria.setStartTime(2l);
criteria.setEndTime(2l);
List<Alert> ctime2Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5, ctime2Alerts.size());
criteria.setEndTime(null);
List<Alert> ctimeGTE2Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5 * 4, ctimeGTE2Alerts.size());
deleteTestAlerts(numTenants);
}
@Test
public void queryAlertsByResolvedTime() throws Exception {
int numTenants = 1;
int numTriggers = 5;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
Set<String> tenantIds = new HashSet<>();
tenantIds.add("tenant0");
AlertsCriteria criteria = new AlertsCriteria();
criteria.setStartResolvedTime(1l);
// Alerts on stime 1 and 4 are RESOLVED
List<Alert> stimeGTE2Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5 * 2, stimeGTE2Alerts.size());
deleteTestAlerts(numTenants);
}
@Test
public void queryAlertsByAcknowledgedTime() throws Exception {
int numTenants = 1;
int numTriggers = 5;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
Set<String> tenantIds = new HashSet<>();
tenantIds.add("tenant0");
AlertsCriteria criteria = new AlertsCriteria();
criteria.setStartAckTime(1l);
// Alerts on stime 2 and 5 are ACKNOWLEDGED
List<Alert> stimeGTE2Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5 * 2, stimeGTE2Alerts.size());
deleteTestAlerts(numTenants);
}
@Test
public void queryAlertsByStatusTime() throws Exception {
int numTenants = 1;
int numTriggers = 5;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
Set<String> tenantIds = new HashSet<>();
tenantIds.add("tenant0");
AlertsCriteria criteria = new AlertsCriteria();
criteria.setStartStatusTime(5l);
criteria.setEndStatusTime(5l);
List<Alert> stimeGTE5Alerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5, stimeGTE5Alerts.size());
deleteTestAlerts(numTenants);
}
@Test
public void queryAlertsBySeverity() throws Exception {
int numTenants = 1;
int numTriggers = 5;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
Set<String> tenantIds = new HashSet<>();
tenantIds.add("tenant0");
AlertsCriteria criteria = new AlertsCriteria();
criteria.setSeverities(Arrays.asList(Severity.LOW));
// Alerts on stime 2 and 5 are severity LOW
List<Alert> lowAlerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5 * 2, lowAlerts.size());
// Alerts on stime 3 are severity CRITICAL
criteria.setSeverities(Arrays.asList(Severity.CRITICAL));
List<Alert> criticalAlerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5, criticalAlerts.size());
// Alerts on stime 1 and 4 are severity MEDIUM
criteria.setSeverities(Arrays.asList(Severity.MEDIUM));
List<Alert> mediumAlerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5 * 2, mediumAlerts.size());
criteria.setSeverities(Arrays.asList(Severity.MEDIUM, Severity.CRITICAL));
List<Alert> mediumCriticalAlerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5 * 3, mediumCriticalAlerts.size());
deleteTestAlerts(numTenants);
}
@Test
public void queryAlertsByStatus() throws Exception {
int numTenants = 1;
int numTriggers = 5;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
Set<String> tenantIds = new HashSet<>();
tenantIds.add("tenant0");
AlertsCriteria criteria = new AlertsCriteria();
criteria.setStatus(Alert.Status.OPEN);
List<Alert> openAlerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5, openAlerts.size());
criteria.setStatus(Alert.Status.ACKNOWLEDGED);
List<Alert> acknowledgedAlerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5 * 2, acknowledgedAlerts.size());
criteria.setStatus(Alert.Status.RESOLVED);
List<Alert> resolvedAlerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5 * 2, resolvedAlerts.size());
criteria.setStatusSet(Arrays.asList(Alert.Status.ACKNOWLEDGED, Alert.Status.RESOLVED));
List<Alert> ackResolvedAlerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(5 * 4, ackResolvedAlerts.size());
deleteTestAlerts(numTenants);
}
@Test
public void queryAlertsCombined() throws Exception {
int numTenants = 1;
int numTriggers = 5;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
Set<String> tenantIds = new HashSet<>();
tenantIds.add("tenant0");
AlertsCriteria criteria = new AlertsCriteria();
criteria.setStatus(Alert.Status.RESOLVED);
criteria.setTriggerId("trigger0");
criteria.setStartTime(3l);
List<Alert> resolvedAlerts = alerts.getAlerts(tenantIds, criteria, null);
assertEquals(1, resolvedAlerts.size());
deleteTestAlerts(numTenants);
}
@Test
public void ackAlert() throws Exception {
int numTenants = 1;
int numTriggers = 1;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
AlertsCriteria criteria = new AlertsCriteria();
criteria.setStatus(Alert.Status.OPEN);
List<Alert> openAlerts = alerts.getAlerts("tenant0", criteria, null);
assertEquals(1, openAlerts.size());
String alertId = openAlerts.iterator().next().getAlertId();
alerts.ackAlerts("tenant0", Arrays.asList(alertId), "test", "ACK from ackAlert() test");
openAlerts = alerts.getAlerts("tenant0", criteria, null);
assertEquals(0, openAlerts.size());
Alert ackAlert = alerts.getAlert("tenant0", alertId, false);
assertEquals(Alert.Status.ACKNOWLEDGED, ackAlert.getStatus());
removeAllAlerts(numTenants);
}
@Test
public void addNote() throws Exception {
int numTenants = 1;
int numTriggers = 1;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
AlertsCriteria criteria = new AlertsCriteria();
criteria.setStatus(Alert.Status.OPEN);
List<Alert> openAlerts = alerts.getAlerts("tenant0", criteria, null);
assertEquals(1, openAlerts.size());
String alertId = openAlerts.iterator().next().getAlertId();
alerts.addNote("tenant0", alertId, "xyz1", "Note1");
Alert alert = alerts.getAlert("tenant0", alertId, false);
assertEquals(1, alert.getNotes().size());
alerts.addNote("tenant0", alertId, "xyz2", "Note2");
alerts.addNote("tenant0", alertId, "xyz3", "Note3");
alert = alerts.getAlert("tenant0", alertId, false);
assertEquals(3, alert.getNotes().size());
removeAllAlerts(numTenants);
}
@Test
public void resolveAlert() throws Exception {
int numTenants = 1;
int numTriggers = 1;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
AlertsCriteria criteria = new AlertsCriteria();
criteria.setStatus(Alert.Status.OPEN);
List<Alert> openAlerts = alerts.getAlerts("tenant0", criteria, null);
assertEquals(1, openAlerts.size());
String alertId = openAlerts.iterator().next().getAlertId();
alerts.resolveAlerts("tenant0", Arrays.asList(alertId), "test", "RESOLVED from resolveAlert() test", null);
openAlerts = alerts.getAlerts("tenant0", criteria, null);
assertEquals(0, openAlerts.size());
Alert resolvedAlert = alerts.getAlert("tenant0", alertId, false);
assertEquals(Alert.Status.RESOLVED, resolvedAlert.getStatus());
removeAllAlerts(numTenants);
}
@Test
public void resolveAlertForTrigger() throws Exception {
int numTenants = 1;
int numTriggers = 1;
int numAlerts = 5;
createTestAlerts(numTenants, numTriggers, numAlerts);
alerts.resolveAlertsForTrigger("tenant0", "trigger0", "test", "RESOLVED from resolveAlert() test", null);
AlertsCriteria criteria = new AlertsCriteria();
criteria.setStatus(Alert.Status.RESOLVED);
List<Alert> resolvedAlerts = alerts.getAlerts("tenant0", criteria, null);
assertEquals(5, resolvedAlerts.size());
removeAllAlerts(numTenants);
}
@Test
public void addRemoveTag() throws Exception {
int numTenants = 1;
int numTriggers = 1;
int numAlerts = 1;
createTestAlerts(numTenants, numTriggers, numAlerts);
List<Alert> nonTaggedAlerts = alerts.getAlerts("tenant0", null, null);
assertEquals(1, nonTaggedAlerts.size());
String alertId = nonTaggedAlerts.iterator().next().getAlertId();
Map<String, String> tags = new HashMap<>();
tags.put("tag1", "value1");
tags.put("tag2", "value2");
tags.put("tag3", "value3");
alerts.addAlertTags("tenant0", Arrays.asList(alertId), tags);
Alert alert = alerts.getAlert("tenant0", alertId, false);
assertEquals(3, alert.getTags().size());
alerts.removeAlertTags("tenant0", Arrays.asList(alertId), Arrays.asList("tag1", "tag2"));
alert = alerts.getAlert("tenant0", alertId, false);
assertEquals(1, alert.getTags().size());
assertEquals("value3", alert.getTags().get("tag3"));
removeAllAlerts(numTenants);
}
}
|
Fix method name after rebase PR
|
engine/src/test/java/org/hawkular/alerts/engine/impl/ispn/IspnAlertsServiceImplTest.java
|
Fix method name after rebase PR
|
<ide><path>ngine/src/test/java/org/hawkular/alerts/engine/impl/ispn/IspnAlertsServiceImplTest.java
<ide> Alert ackAlert = alerts.getAlert("tenant0", alertId, false);
<ide> assertEquals(Alert.Status.ACKNOWLEDGED, ackAlert.getStatus());
<ide>
<del> removeAllAlerts(numTenants);
<add> deleteTestAlerts(numTenants);
<ide> }
<ide>
<ide> @Test
<ide> alert = alerts.getAlert("tenant0", alertId, false);
<ide> assertEquals(3, alert.getNotes().size());
<ide>
<del> removeAllAlerts(numTenants);
<add> deleteTestAlerts(numTenants);
<ide> }
<ide>
<ide> @Test
<ide> Alert resolvedAlert = alerts.getAlert("tenant0", alertId, false);
<ide> assertEquals(Alert.Status.RESOLVED, resolvedAlert.getStatus());
<ide>
<del> removeAllAlerts(numTenants);
<add> deleteTestAlerts(numTenants);
<ide> }
<ide>
<ide> @Test
<ide> List<Alert> resolvedAlerts = alerts.getAlerts("tenant0", criteria, null);
<ide> assertEquals(5, resolvedAlerts.size());
<ide>
<del> removeAllAlerts(numTenants);
<add> deleteTestAlerts(numTenants);
<ide> }
<ide>
<ide> @Test
<ide> assertEquals(1, alert.getTags().size());
<ide> assertEquals("value3", alert.getTags().get("tag3"));
<ide>
<del> removeAllAlerts(numTenants);
<add> deleteTestAlerts(numTenants);
<ide> }
<ide> }
|
|
Java
|
mit
|
2323091b13cbe6f012bb47bf9a348eca8490b145
| 0 |
Microsoft/mssql-jdbc
|
/*
* Microsoft JDBC Driver for SQL Server Copyright(c) Microsoft Corporation All rights reserved. This program is made
* available under the terms of the MIT License. See the LICENSE file in the project root for more information.
*/
package com.microsoft.sqlserver.jdbc;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
/**
* Various driver utilities.
*
*/
final class Util {
final static String SYSTEM_SPEC_VERSION = System.getProperty("java.specification.version");
final static char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
final static String WSIDNotAvailable = ""; // default string when WSID is not available
final static String ACTIVITY_ID_TRACE_PROPERTY = "com.microsoft.sqlserver.jdbc.traceactivity";
// The JRE is identified by the string below so that the driver can make
// any vendor or version specific decisions
static final String SYSTEM_JRE = System.getProperty("java.vendor") + " " + System.getProperty("java.version");
static boolean isIBM() {
return SYSTEM_JRE.startsWith("IBM");
}
static String getJVMArchOnWindows() {
return System.getProperty("os.arch").contains("64") ? "x64" : "x86";
}
static final boolean isCharType(int jdbcType) {
switch (jdbcType) {
case java.sql.Types.CHAR:
case java.sql.Types.NCHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.NVARCHAR:
case java.sql.Types.LONGVARCHAR:
case java.sql.Types.LONGNVARCHAR:
return true;
default:
return false;
}
}
static final Boolean isCharType(SSType ssType) {
switch (ssType) {
case CHAR:
case NCHAR:
case VARCHAR:
case NVARCHAR:
case VARCHARMAX:
case NVARCHARMAX:
return true;
default:
return false;
}
}
static final Boolean isBinaryType(SSType ssType) {
switch (ssType) {
case BINARY:
case VARBINARY:
case VARBINARYMAX:
case IMAGE:
return true;
default:
return false;
}
}
static final Boolean isBinaryType(int jdbcType) {
switch (jdbcType) {
case java.sql.Types.BINARY:
case java.sql.Types.VARBINARY:
case java.sql.Types.LONGVARBINARY:
return true;
default:
return false;
}
}
/**
* Read a short int from a byte stream
*
* @param data
* the databytes
* @param nOffset
* offset to read from
* @return the value
*/
/* L0 */ static short readShort(byte data[], int nOffset) {
return (short) ((data[nOffset] & 0xff) | ((data[nOffset + 1] & 0xff) << 8));
}
/**
* Read an unsigned short int (16 bits) from a byte stream
*
* @param data
* the databytes
* @param nOffset
* offset to read from
* @return the value
*/
/* L0 */ static int readUnsignedShort(byte data[], int nOffset) {
return ((data[nOffset] & 0xff) | ((data[nOffset + 1] & 0xff) << 8));
}
static int readUnsignedShortBigEndian(byte data[], int nOffset) {
return ((data[nOffset] & 0xFF) << 8) | (data[nOffset + 1] & 0xFF);
}
static void writeShort(short value, byte valueBytes[], int offset) {
valueBytes[offset + 0] = (byte) ((value >> 0) & 0xFF);
valueBytes[offset + 1] = (byte) ((value >> 8) & 0xFF);
}
static void writeShortBigEndian(short value, byte valueBytes[], int offset) {
valueBytes[offset + 0] = (byte) ((value >> 8) & 0xFF);
valueBytes[offset + 1] = (byte) ((value >> 0) & 0xFF);
}
/**
* Read an int from a byte stream
*
* @param data
* the databytes
* @param nOffset
* offset to read from
* @return the value
*/
/* L0 */ static int readInt(byte data[], int nOffset) {
int b1 = ((int) data[nOffset + 0] & 0xff);
int b2 = ((int) data[nOffset + 1] & 0xff) << 8;
int b3 = ((int) data[nOffset + 2] & 0xff) << 16;
int b4 = ((int) data[nOffset + 3] & 0xff) << 24;
return b4 | b3 | b2 | b1;
}
static int readIntBigEndian(byte data[], int nOffset) {
return ((data[nOffset + 3] & 0xFF) << 0) | ((data[nOffset + 2] & 0xFF) << 8)
| ((data[nOffset + 1] & 0xFF) << 16) | ((data[nOffset + 0] & 0xFF) << 24);
}
static void writeInt(int value, byte valueBytes[], int offset) {
valueBytes[offset + 0] = (byte) ((value >> 0) & 0xFF);
valueBytes[offset + 1] = (byte) ((value >> 8) & 0xFF);
valueBytes[offset + 2] = (byte) ((value >> 16) & 0xFF);
valueBytes[offset + 3] = (byte) ((value >> 24) & 0xFF);
}
static void writeIntBigEndian(int value, byte valueBytes[], int offset) {
valueBytes[offset + 0] = (byte) ((value >> 24) & 0xFF);
valueBytes[offset + 1] = (byte) ((value >> 16) & 0xFF);
valueBytes[offset + 2] = (byte) ((value >> 8) & 0xFF);
valueBytes[offset + 3] = (byte) ((value >> 0) & 0xFF);
}
static void writeLongBigEndian(long value, byte valueBytes[], int offset) {
valueBytes[offset + 0] = (byte) ((value >> 56) & 0xFF);
valueBytes[offset + 1] = (byte) ((value >> 48) & 0xFF);
valueBytes[offset + 2] = (byte) ((value >> 40) & 0xFF);
valueBytes[offset + 3] = (byte) ((value >> 32) & 0xFF);
valueBytes[offset + 4] = (byte) ((value >> 24) & 0xFF);
valueBytes[offset + 5] = (byte) ((value >> 16) & 0xFF);
valueBytes[offset + 6] = (byte) ((value >> 8) & 0xFF);
valueBytes[offset + 7] = (byte) ((value >> 0) & 0xFF);
}
static BigDecimal readBigDecimal(byte valueBytes[], int valueLength, int scale) {
int sign = (0 == valueBytes[0]) ? -1 : 1;
byte[] magnitude = new byte[valueLength - 1];
for (int i = 1; i <= magnitude.length; i++)
magnitude[magnitude.length - i] = valueBytes[i];
return new BigDecimal(new BigInteger(sign, magnitude), scale);
}
/**
* Reads a long value from byte array.
*
* @param data
* the byte array.
* @param nOffset
* the offset into byte array to start reading.
* @return long value as read from bytes.
*/
/* L0 */static long readLong(byte data[], int nOffset) {
return ((long) (data[nOffset + 7] & 0xff) << 56) | ((long) (data[nOffset + 6] & 0xff) << 48)
| ((long) (data[nOffset + 5] & 0xff) << 40) | ((long) (data[nOffset + 4] & 0xff) << 32)
| ((long) (data[nOffset + 3] & 0xff) << 24) | ((long) (data[nOffset + 2] & 0xff) << 16)
| ((long) (data[nOffset + 1] & 0xff) << 8) | ((long) (data[nOffset] & 0xff));
}
/**
* Writes a long to byte array.
*
* @param value
* long value to write.
* @param valueBytes
* the byte array.
* @param offset
* the offset inside byte array.
*/
static void writeLong(long value, byte valueBytes[], int offset) {
valueBytes[offset++] = (byte) ((value) & 0xFF);
valueBytes[offset++] = (byte) ((value >> 8) & 0xFF);
valueBytes[offset++] = (byte) ((value >> 16) & 0xFF);
valueBytes[offset++] = (byte) ((value >> 24) & 0xFF);
valueBytes[offset++] = (byte) ((value >> 32) & 0xFF);
valueBytes[offset++] = (byte) ((value >> 40) & 0xFF);
valueBytes[offset++] = (byte) ((value >> 48) & 0xFF);
valueBytes[offset] = (byte) ((value >> 56) & 0xFF);
}
/**
* Parse a JDBC URL into a set of properties.
*
* @param url
* the JDBC URL
* @param logger
* @return the properties
* @throws SQLServerException
*/
/* L0 */ static Properties parseUrl(String url, Logger logger) throws SQLServerException {
Properties p = new Properties();
String tmpUrl = url;
String sPrefix = "jdbc:sqlserver://";
StringBuilder result = new StringBuilder();
String name = "";
String value = "";
if (!tmpUrl.startsWith(sPrefix))
return null;
tmpUrl = tmpUrl.substring(sPrefix.length());
int i;
// Simple finite state machine.
// always look at one char at a time
final int inStart = 0;
final int inServerName = 1;
final int inPort = 2;
final int inInstanceName = 3;
final int inEscapedValueStart = 4;
final int inEscapedValueEnd = 5;
final int inValue = 6;
final int inName = 7;
int state = inStart;
char ch;
i = 0;
while (i < tmpUrl.length()) {
ch = tmpUrl.charAt(i);
switch (state) {
case inStart: {
if (ch == ';') {
// done immediately
state = inName;
} else {
result.append(ch);
state = inServerName;
}
break;
}
case inServerName: {
if (ch == ';' || ch == ':' || ch == '\\') {
// non escaped trim the string
String property = result.toString().trim();
if (property.length() > 0) {
p.put(SQLServerDriverStringProperty.SERVER_NAME.toString(), property);
if (logger.isLoggable(Level.FINE)) {
logger.fine("Property:serverName " + "Value:" + property);
}
}
result.setLength(0);
if (ch == ';')
state = inName;
else if (ch == ':')
state = inPort;
else
state = inInstanceName;
} else {
result.append(ch);
// same state
}
break;
}
case inPort: {
if (ch == ';') {
String property = result.toString().trim();
if (logger.isLoggable(Level.FINE)) {
logger.fine("Property:portNumber " + "Value:" + property);
}
p.put(SQLServerDriverIntProperty.PORT_NUMBER.toString(), property);
result.setLength(0);
state = inName;
} else {
result.append(ch);
// same state
}
break;
}
case inInstanceName: {
if (ch == ';' || ch == ':') {
// non escaped trim the string
String property = result.toString().trim();
if (logger.isLoggable(Level.FINE)) {
logger.fine("Property:instanceName " + "Value:" + property);
}
p.put(SQLServerDriverStringProperty.INSTANCE_NAME.toString(), property.toLowerCase(Locale.US));
result.setLength(0);
if (ch == ';')
state = inName;
else
state = inPort;
} else {
result.append(ch);
// same state
}
break;
}
case inName: {
if (ch == '=') {
// name is never escaped!
name = name.trim();
if (name.length() <= 0) {
SQLServerException.makeFromDriverError(null, null,
SQLServerException.getErrString("R_errorConnectionString"), null, true);
}
state = inValue;
} else if (ch == ';') {
name = name.trim();
if (name.length() > 0) {
SQLServerException.makeFromDriverError(null, null,
SQLServerException.getErrString("R_errorConnectionString"), null, true);
}
// same state
} else {
StringBuilder builder = new StringBuilder();
builder.append(name);
builder.append(ch);
name = builder.toString();
// same state
}
break;
}
case inValue: {
if (ch == ';') {
// simple value trim
value = value.trim();
name = SQLServerDriver.getNormalizedPropertyName(name, logger);
if (null != name) {
if (logger.isLoggable(Level.FINE)) {
if (!name.equals(SQLServerDriverStringProperty.USER.toString())) {
if (!name.toLowerCase(Locale.ENGLISH).contains("password")
&& !name.toLowerCase(Locale.ENGLISH).contains("keystoresecret")) {
logger.fine("Property:" + name + " Value:" + value);
} else {
logger.fine("Property:" + name);
}
}
}
p.put(name, value);
}
name = "";
value = "";
state = inName;
} else if (ch == '{') {
state = inEscapedValueStart;
value = value.trim();
if (value.length() > 0) {
SQLServerException.makeFromDriverError(null, null,
SQLServerException.getErrString("R_errorConnectionString"), null, true);
}
} else {
StringBuilder builder = new StringBuilder();
builder.append(value);
builder.append(ch);
value = builder.toString();
// same state
}
break;
}
case inEscapedValueStart: {
/*
* check for escaped }. when we see a }, first check to see if this is before the end of the string
* to avoid index out of range exception then check if the character immediately after is also a }.
* if it is, then we have a }}, which is not the closing of the escaped state.
*/
if (ch == '}' && i + 1 < tmpUrl.length() && tmpUrl.charAt(i + 1) == '}') {
StringBuilder builder = new StringBuilder();
builder.append(value);
builder.append(ch);
value = builder.toString();
i++; // escaped }} into a }, so increment the counter once more
// same state
} else {
if (ch == '}') {
// no trimming use the value as it is.
name = SQLServerDriver.getNormalizedPropertyName(name, logger);
if (null != name) {
if (logger.isLoggable(Level.FINE)) {
if (!name.equals(SQLServerDriverStringProperty.USER.toString())
&& !name.equals(SQLServerDriverStringProperty.PASSWORD.toString()))
logger.fine("Property:" + name + " Value:" + value);
}
p.put(name, value);
}
name = "";
value = "";
// to eat the spaces until the ; potentially we could do without the state but
// it would not be clean
state = inEscapedValueEnd;
} else {
StringBuilder builder = new StringBuilder();
builder.append(value);
builder.append(ch);
value = builder.toString();
// same state
}
}
break;
}
case inEscapedValueEnd: {
if (ch == ';') // eat space chars till ; anything else is an error
{
state = inName;
} else if (ch != ' ') {
// error if the chars are not space
SQLServerException.makeFromDriverError(null, null,
SQLServerException.getErrString("R_errorConnectionString"), null, true);
}
break;
}
default:
assert false : "parseURL: Invalid state " + state;
}
i++;
}
// Exit
switch (state) {
case inServerName:
String property = result.toString().trim();
if (property.length() > 0) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Property:serverName " + "Value:" + property);
}
p.put(SQLServerDriverStringProperty.SERVER_NAME.toString(), property);
}
break;
case inPort:
property = result.toString().trim();
if (logger.isLoggable(Level.FINE)) {
logger.fine("Property:portNumber " + "Value:" + property);
}
p.put(SQLServerDriverIntProperty.PORT_NUMBER.toString(), property);
break;
case inInstanceName:
property = result.toString().trim();
if (logger.isLoggable(Level.FINE)) {
logger.fine("Property:instanceName " + "Value:" + property);
}
p.put(SQLServerDriverStringProperty.INSTANCE_NAME.toString(), property);
break;
case inValue:
// simple value trim
value = value.trim();
name = SQLServerDriver.getNormalizedPropertyName(name, logger);
if (null != name) {
if (logger.isLoggable(Level.FINE)) {
if (!name.equals(SQLServerDriverStringProperty.USER.toString())
&& !name.equals(SQLServerDriverStringProperty.PASSWORD.toString())
&& !name.equals(SQLServerDriverStringProperty.KEY_STORE_SECRET.toString()))
logger.fine("Property:" + name + " Value:" + value);
}
p.put(name, value);
}
break;
case inEscapedValueEnd:
case inStart:
// do nothing!
break;
case inName: {
name = name.trim();
if (name.length() > 0) {
SQLServerException.makeFromDriverError(null, null,
SQLServerException.getErrString("R_errorConnectionString"), null, true);
}
break;
}
default:
SQLServerException.makeFromDriverError(null, null,
SQLServerException.getErrString("R_errorConnectionString"), null, true);
}
return p;
}
/**
* Accepts a SQL identifier (such as a column name or table name) and escapes the identifier using SQL Server
* bracket escaping rules. Assumes that the incoming identifier is unescaped.
*
* @inID input identifier to escape.
* @return the escaped value.
*/
static String escapeSQLId(String inID) {
// SQL bracket escaping rules.
// Given <identifier> yields -> [<identifier>]
// Where <identifier> is first escaped to replace all
// instances of "]" with "]]".
// For example, column name "abc" -> "[abc]"
// For example, column name "]" -> "[]]]"
// For example, column name "]ab]cd" -> "[]]ab]]cd]"
char ch;
// Add 2 extra chars for open and closing brackets.
StringBuilder outID = new StringBuilder(inID.length() + 2);
outID.append('[');
for (int i = 0; i < inID.length(); i++) {
ch = inID.charAt(i);
if (']' == ch)
outID.append("]]");
else
outID.append(ch);
}
outID.append(']');
return outID.toString();
}
/**
* Checks if duplicate columns exists, in O(n) time.
*
* @param columnName
* the name of the column
* @throws SQLServerException
* when a duplicate column exists
*/
static void checkDuplicateColumnName(String columnName, Set<String> columnNames) throws SQLServerException {
// columnList.add will return false if the same column name already exists
if (!columnNames.add(columnName)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName"));
Object[] msgArgs = {columnName};
throw new SQLServerException(null, form.format(msgArgs), null, 0, false);
}
}
/**
* Reads a UNICODE string from byte buffer at offset (up to byteLength).
*
* @param b
* the buffer containing UNICODE bytes.
* @param offset
* - the offset into b where the UNICODE string starts.
* @param byteLength
* - the length in bytes of the UNICODE string.
* @param conn
* - the SQLServerConnection object.
* @return new String with UNICODE data inside.
*/
static String readUnicodeString(byte[] b, int offset, int byteLength,
SQLServerConnection conn) throws SQLServerException {
try {
return new String(b, offset, byteLength, Encoding.UNICODE.charset());
} catch (IndexOutOfBoundsException ex) {
String txtMsg = SQLServerException
.checkAndAppendClientConnId(SQLServerException.getErrString("R_stringReadError"), conn);
MessageFormat form = new MessageFormat(txtMsg);
Object[] msgArgs = {offset};
// Re-throw SQLServerException if conversion fails.
throw new SQLServerException(form.format(msgArgs), null, 0, ex);
}
}
// NOTE: This is for display purposes ONLY. NOT TO BE USED for data conversion.
/**
* Converts byte array to a string representation of hex bytes for display purposes.
*
* @param b
* the source buffer.
* @return "hexized" string representation of bytes.
*/
static String byteToHexDisplayString(byte[] b) {
if (null == b)
return "(null)";
int hexVal;
StringBuilder sb = new StringBuilder(b.length * 2 + 2);
sb.append("0x");
for (byte aB : b) {
hexVal = aB & 0xFF;
sb.append(hexChars[(hexVal & 0xF0) >> 4]);
sb.append(hexChars[(hexVal & 0x0F)]);
}
return sb.toString();
}
/**
* Converts byte array to a string representation of hex bytes.
*
* @param b
* the source buffer.
* @return "hexized" string representation of bytes.
*/
static String bytesToHexString(byte[] b, int length) {
StringBuilder sb = new StringBuilder(length * 2);
for (int i = 0; i < length; i++) {
int hexVal = b[i] & 0xFF;
sb.append(hexChars[(hexVal & 0xF0) >> 4]);
sb.append(hexChars[(hexVal & 0x0F)]);
}
return sb.toString();
}
/**
* Looks up local hostname of client machine.
*
* @exception UnknownHostException
* if local hostname is not found.
* @return hostname string or ip of host if hostname cannot be resolved. If neither hostname or ip found returns ""
* per spec.
*/
static String lookupHostName() {
try {
InetAddress localAddress = InetAddress.getLocalHost();
if (null != localAddress) {
String value = localAddress.getHostName();
if (null != value && value.length() > 0)
return value;
value = localAddress.getHostAddress();
if (null != value && value.length() > 0)
return value;
}
} catch (UnknownHostException e) {
return WSIDNotAvailable;
}
// If hostname not found, return standard "" string.
return WSIDNotAvailable;
}
static final byte[] asGuidByteArray(UUID aId) {
long msb = aId.getMostSignificantBits();
long lsb = aId.getLeastSignificantBits();
byte[] buffer = new byte[16];
Util.writeLongBigEndian(msb, buffer, 0);
Util.writeLongBigEndian(lsb, buffer, 8);
// For the first three fields, UUID uses network byte order,
// Guid uses native byte order. So we need to reverse
// the first three fields before sending to server.
byte tmpByte;
// Reverse the first 4 bytes
tmpByte = buffer[0];
buffer[0] = buffer[3];
buffer[3] = tmpByte;
tmpByte = buffer[1];
buffer[1] = buffer[2];
buffer[2] = tmpByte;
// Reverse the 5th and the 6th
tmpByte = buffer[4];
buffer[4] = buffer[5];
buffer[5] = tmpByte;
// Reverse the 7th and the 8th
tmpByte = buffer[6];
buffer[6] = buffer[7];
buffer[7] = tmpByte;
return buffer;
}
static final UUID readGUIDtoUUID(byte[] inputGUID) throws SQLServerException {
if (inputGUID.length != 16) {
throw new SQLServerException("guid length must be 16", null);
}
// For the first three fields, UUID uses network byte order,
// Guid uses native byte order. So we need to reverse
// the first three fields before creating a UUID.
byte tmpByte;
// Reverse the first 4 bytes
tmpByte = inputGUID[0];
inputGUID[0] = inputGUID[3];
inputGUID[3] = tmpByte;
tmpByte = inputGUID[1];
inputGUID[1] = inputGUID[2];
inputGUID[2] = tmpByte;
// Reverse the 5th and the 6th
tmpByte = inputGUID[4];
inputGUID[4] = inputGUID[5];
inputGUID[5] = tmpByte;
// Reverse the 7th and the 8th
tmpByte = inputGUID[6];
inputGUID[6] = inputGUID[7];
inputGUID[7] = tmpByte;
long msb = 0L;
for (int i = 0; i < 8; i++) {
msb = msb << 8 | ((long) inputGUID[i] & 0xFFL);
}
long lsb = 0L;
for (int i = 8; i < 16; i++) {
lsb = lsb << 8 | ((long) inputGUID[i] & 0xFFL);
}
return new UUID(msb, lsb);
}
static final String readGUID(byte[] inputGUID) throws SQLServerException {
String guidTemplate = "NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN";
byte guid[] = inputGUID;
StringBuilder sb = new StringBuilder(guidTemplate.length());
for (int i = 0; i < 4; i++) {
sb.append(Util.hexChars[(guid[3 - i] & 0xF0) >> 4]);
sb.append(Util.hexChars[guid[3 - i] & 0x0F]);
}
sb.append('-');
for (int i = 0; i < 2; i++) {
sb.append(Util.hexChars[(guid[5 - i] & 0xF0) >> 4]);
sb.append(Util.hexChars[guid[5 - i] & 0x0F]);
}
sb.append('-');
for (int i = 0; i < 2; i++) {
sb.append(Util.hexChars[(guid[7 - i] & 0xF0) >> 4]);
sb.append(Util.hexChars[guid[7 - i] & 0x0F]);
}
sb.append('-');
for (int i = 0; i < 2; i++) {
sb.append(Util.hexChars[(guid[8 + i] & 0xF0) >> 4]);
sb.append(Util.hexChars[guid[8 + i] & 0x0F]);
}
sb.append('-');
for (int i = 0; i < 6; i++) {
sb.append(Util.hexChars[(guid[10 + i] & 0xF0) >> 4]);
sb.append(Util.hexChars[guid[10 + i] & 0x0F]);
}
return sb.toString();
}
static boolean isActivityTraceOn() {
LogManager lm = LogManager.getLogManager();
String activityTrace = lm.getProperty(ACTIVITY_ID_TRACE_PROPERTY);
return ("on".equalsIgnoreCase(activityTrace));
}
/**
* Determines if a column value should be transparently decrypted (based on SQLServerStatement and the connection
* string settings).
*
* @return true if the value should be transparently decrypted, false otherwise.
*/
static boolean shouldHonorAEForRead(SQLServerStatementColumnEncryptionSetting stmtColumnEncryptionSetting,
SQLServerConnection connection) {
// Command leve setting trumps all
switch (stmtColumnEncryptionSetting) {
case Disabled:
return false;
case Enabled:
case ResultSetOnly:
return true;
default:
// Check connection level setting!
assert SQLServerStatementColumnEncryptionSetting.UseConnectionSetting == stmtColumnEncryptionSetting : "Unexpected value for command level override";
return (connection != null && connection.isColumnEncryptionSettingEnabled());
}
}
/**
* Determines if parameters should be transparently encrypted (based on SQLServerStatement and the connection string
* settings).
*
* @return true if the value should be transparently encrypted, false otherwise.
*/
static boolean shouldHonorAEForParameters(SQLServerStatementColumnEncryptionSetting stmtColumnEncryptionSetting,
SQLServerConnection connection) {
// Command leve setting trumps all
switch (stmtColumnEncryptionSetting) {
case Disabled:
case ResultSetOnly:
return false;
case Enabled:
return true;
default:
// Check connection level setting!
assert SQLServerStatementColumnEncryptionSetting.UseConnectionSetting == stmtColumnEncryptionSetting : "Unexpected value for command level override";
return (connection != null && connection.isColumnEncryptionSettingEnabled());
}
}
static void validateMoneyRange(BigDecimal bd, JDBCType jdbcType) throws SQLServerException {
if (null == bd)
return;
switch (jdbcType) {
case MONEY:
if ((1 != bd.compareTo(SSType.MAX_VALUE_MONEY)) && (-1 != bd.compareTo(SSType.MIN_VALUE_MONEY))) {
return;
}
break;
case SMALLMONEY:
if ((1 != bd.compareTo(SSType.MAX_VALUE_SMALLMONEY))
&& (-1 != bd.compareTo(SSType.MIN_VALUE_SMALLMONEY))) {
return;
}
break;
default:
break;
}
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange"));
Object[] msgArgs = {jdbcType};
throw new SQLServerException(form.format(msgArgs), null);
}
static int getValueLengthBaseOnJavaType(Object value, JavaType javaType, Integer precision, Integer scale,
JDBCType jdbcType) throws SQLServerException {
switch (javaType) {
// when the value of setObject() is null, the javaType stays
// as OBJECT. We need to get the javaType base on jdbcType
case OBJECT:
switch (jdbcType) {
case DECIMAL:
case NUMERIC:
javaType = JavaType.BIGDECIMAL;
break;
case TIME:
javaType = JavaType.TIME;
break;
case TIMESTAMP:
javaType = JavaType.TIMESTAMP;
break;
case DATETIMEOFFSET:
javaType = JavaType.DATETIMEOFFSET;
break;
default:
break;
}
break;
default:
break;
}
switch (javaType) {
case STRING:
if (JDBCType.GUID == jdbcType) {
String guidTemplate = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";
return ((null == value) ? 0 : guidTemplate.length());
} else if (JDBCType.TIMESTAMP == jdbcType || JDBCType.TIME == jdbcType
|| JDBCType.DATETIMEOFFSET == jdbcType) {
return ((null == scale) ? TDS.MAX_FRACTIONAL_SECONDS_SCALE : scale);
} else if (JDBCType.BINARY == jdbcType || JDBCType.VARBINARY == jdbcType) {
return ((null == value) ? 0 : (ParameterUtils.HexToBin((String) value).length));
} else {
return ((null == value) ? 0 : ((String) value).length());
}
case BYTEARRAY:
return ((null == value) ? 0 : ((byte[]) value).length);
case BIGDECIMAL:
int length;
if (null == precision) {
if (null == value) {
length = 0;
} else {
if (0 == ((BigDecimal) value).intValue()) {
String s = "" + value;
s = s.replaceAll("\\-", "");
if (s.startsWith("0.")) {
// remove the leading zero, eg., for 0.32, the precision should be 2 and not 3
s = s.replaceAll("0\\.", "");
} else {
s = s.replaceAll("\\.", "");
}
length = s.length();
}
// if the value is in scientific notation format
else if (("" + value).contains("E")) {
DecimalFormat dform = new DecimalFormat("###.#####");
String s = dform.format(value);
s = s.replaceAll("\\.", "");
s = s.replaceAll("\\-", "");
length = s.length();
} else {
length = ((BigDecimal) value).precision();
}
}
} else {
length = precision;
}
return length;
case TIMESTAMP:
case TIME:
case DATETIMEOFFSET:
return ((null == scale) ? TDS.MAX_FRACTIONAL_SECONDS_SCALE : scale);
case CLOB:
return ((null == value) ? 0 : (DataTypes.NTEXT_MAX_CHARS * 2));
case NCLOB:
case READER:
return ((null == value) ? 0 : DataTypes.NTEXT_MAX_CHARS);
default:
return 0;
}
}
// If the access token is expiring within next 10 minutes, lets just re-create a token for this connection attempt.
// If the token is expiring within the next 45 mins, try to fetch a new token if there is no thread already doing
// it.
// If a thread is already doing the refresh, just use the existing token and proceed.
static synchronized boolean checkIfNeedNewAccessToken(SQLServerConnection connection, Date accessTokenExpireDate) {
Date now = new Date();
// if the token's expiration is within the next 45 mins
// 45 mins * 60 sec/min * 1000 millisec/sec
if ((accessTokenExpireDate.getTime() - now.getTime()) < (45 * 60 * 1000)) {
// within the next 10 mins
if ((accessTokenExpireDate.getTime() - now.getTime()) < (10 * 60 * 1000)) {
return true;
} else {
// check if another thread is already updating the access token
if (connection.attemptRefreshTokenLocked) {
return false;
} else {
connection.attemptRefreshTokenLocked = true;
return true;
}
}
}
return false;
}
static final boolean use43Wrapper;
static {
boolean supportJDBC43 = true;
try {
DriverJDBCVersion.checkSupportsJDBC43();
} catch (UnsupportedOperationException e) {
supportJDBC43 = false;
}
double jvmVersion = Double.parseDouble(Util.SYSTEM_SPEC_VERSION);
use43Wrapper = supportJDBC43 && (9 <= jvmVersion);
}
// if driver is for JDBC 43 and jvm version is 9 or higher, then always return as SQLServerConnection43,
// otherwise return SQLServerConnection
static boolean use43Wrapper() {
return use43Wrapper;
}
@SuppressWarnings("unchecked")
static <T> T newInstance(Class<?> returnType, String className, String constructorArg,
Object[] msgArgs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException {
Class<?> clazz = Class.forName(className);
if (!returnType.isAssignableFrom(clazz)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_unassignableError"));
throw new IllegalArgumentException(form.format(msgArgs));
}
if (constructorArg == null) {
return (T) clazz.getDeclaredConstructor().newInstance();
} else {
return (T) clazz.getDeclaredConstructor(String.class).newInstance(constructorArg);
}
}
/**
* Escapes single quotes (') in object name to convert and pass it as String safely.
*
* @param name
* Object name to be passed as String
* @return Converted object name
*/
static String escapeSingleQuotes(String name) {
return name.replace("'", "''");
}
static String convertInputStreamToString(java.io.InputStream is) throws IOException {
java.io.ByteArrayOutputStream result = new java.io.ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
return result.toString();
}
}
final class SQLIdentifier {
// Component names default to empty string (rather than null) for consistency
// with API behavior which returns empty string (rather than null) when the
// particular value is not present.
private String serverName = "";
final String getServerName() {
return serverName;
}
final void setServerName(String name) {
serverName = name;
}
private String databaseName = "";
final String getDatabaseName() {
return databaseName;
}
final void setDatabaseName(String name) {
databaseName = name;
}
private String schemaName = "";
final String getSchemaName() {
return schemaName;
}
final void setSchemaName(String name) {
schemaName = name;
}
private String objectName = "";
final String getObjectName() {
return objectName;
}
final void setObjectName(String name) {
objectName = name;
}
final String asEscapedString() {
StringBuilder fullName = new StringBuilder(256);
if (serverName.length() > 0)
fullName.append("[").append(serverName).append("].");
if (databaseName.length() > 0)
fullName.append("[").append(databaseName).append("].");
else
assert 0 == serverName.length();
if (schemaName.length() > 0)
fullName.append("[").append(schemaName).append("].");
else if (databaseName.length() > 0)
fullName.append('.');
fullName.append("[").append(objectName).append("]");
return fullName.toString();
}
}
|
src/main/java/com/microsoft/sqlserver/jdbc/Util.java
|
/*
* Microsoft JDBC Driver for SQL Server Copyright(c) Microsoft Corporation All rights reserved. This program is made
* available under the terms of the MIT License. See the LICENSE file in the project root for more information.
*/
package com.microsoft.sqlserver.jdbc;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
/**
* Various driver utilities.
*
*/
final class Util {
final static String SYSTEM_SPEC_VERSION = System.getProperty("java.specification.version");
final static char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
final static String WSIDNotAvailable = ""; // default string when WSID is not available
final static String ACTIVITY_ID_TRACE_PROPERTY = "com.microsoft.sqlserver.jdbc.traceactivity";
// The JRE is identified by the string below so that the driver can make
// any vendor or version specific decisions
static final String SYSTEM_JRE = System.getProperty("java.vendor") + " " + System.getProperty("java.version");
static boolean isIBM() {
return SYSTEM_JRE.startsWith("IBM");
}
static String getJVMArchOnWindows() {
return System.getProperty("os.arch").contains("64") ? "x64" : "x86";
}
static final boolean isCharType(int jdbcType) {
switch (jdbcType) {
case java.sql.Types.CHAR:
case java.sql.Types.NCHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.NVARCHAR:
case java.sql.Types.LONGVARCHAR:
case java.sql.Types.LONGNVARCHAR:
return true;
default:
return false;
}
}
static final Boolean isCharType(SSType ssType) {
switch (ssType) {
case CHAR:
case NCHAR:
case VARCHAR:
case NVARCHAR:
case VARCHARMAX:
case NVARCHARMAX:
return true;
default:
return false;
}
}
static final Boolean isBinaryType(SSType ssType) {
switch (ssType) {
case BINARY:
case VARBINARY:
case VARBINARYMAX:
case IMAGE:
return true;
default:
return false;
}
}
static final Boolean isBinaryType(int jdbcType) {
switch (jdbcType) {
case java.sql.Types.BINARY:
case java.sql.Types.VARBINARY:
case java.sql.Types.LONGVARBINARY:
return true;
default:
return false;
}
}
/**
* Read a short int from a byte stream
*
* @param data
* the databytes
* @param nOffset
* offset to read from
* @return the value
*/
/* L0 */ static short readShort(byte data[], int nOffset) {
return (short) ((data[nOffset] & 0xff) | ((data[nOffset + 1] & 0xff) << 8));
}
/**
* Read an unsigned short int (16 bits) from a byte stream
*
* @param data
* the databytes
* @param nOffset
* offset to read from
* @return the value
*/
/* L0 */ static int readUnsignedShort(byte data[], int nOffset) {
return ((data[nOffset] & 0xff) | ((data[nOffset + 1] & 0xff) << 8));
}
static int readUnsignedShortBigEndian(byte data[], int nOffset) {
return ((data[nOffset] & 0xFF) << 8) | (data[nOffset + 1] & 0xFF);
}
static void writeShort(short value, byte valueBytes[], int offset) {
valueBytes[offset + 0] = (byte) ((value >> 0) & 0xFF);
valueBytes[offset + 1] = (byte) ((value >> 8) & 0xFF);
}
static void writeShortBigEndian(short value, byte valueBytes[], int offset) {
valueBytes[offset + 0] = (byte) ((value >> 8) & 0xFF);
valueBytes[offset + 1] = (byte) ((value >> 0) & 0xFF);
}
/**
* Read an int from a byte stream
*
* @param data
* the databytes
* @param nOffset
* offset to read from
* @return the value
*/
/* L0 */ static int readInt(byte data[], int nOffset) {
int b1 = ((int) data[nOffset + 0] & 0xff);
int b2 = ((int) data[nOffset + 1] & 0xff) << 8;
int b3 = ((int) data[nOffset + 2] & 0xff) << 16;
int b4 = ((int) data[nOffset + 3] & 0xff) << 24;
return b4 | b3 | b2 | b1;
}
static int readIntBigEndian(byte data[], int nOffset) {
return ((data[nOffset + 3] & 0xFF) << 0) | ((data[nOffset + 2] & 0xFF) << 8)
| ((data[nOffset + 1] & 0xFF) << 16) | ((data[nOffset + 0] & 0xFF) << 24);
}
static void writeInt(int value, byte valueBytes[], int offset) {
valueBytes[offset + 0] = (byte) ((value >> 0) & 0xFF);
valueBytes[offset + 1] = (byte) ((value >> 8) & 0xFF);
valueBytes[offset + 2] = (byte) ((value >> 16) & 0xFF);
valueBytes[offset + 3] = (byte) ((value >> 24) & 0xFF);
}
static void writeIntBigEndian(int value, byte valueBytes[], int offset) {
valueBytes[offset + 0] = (byte) ((value >> 24) & 0xFF);
valueBytes[offset + 1] = (byte) ((value >> 16) & 0xFF);
valueBytes[offset + 2] = (byte) ((value >> 8) & 0xFF);
valueBytes[offset + 3] = (byte) ((value >> 0) & 0xFF);
}
static void writeLongBigEndian(long value, byte valueBytes[], int offset) {
valueBytes[offset + 0] = (byte) ((value >> 56) & 0xFF);
valueBytes[offset + 1] = (byte) ((value >> 48) & 0xFF);
valueBytes[offset + 2] = (byte) ((value >> 40) & 0xFF);
valueBytes[offset + 3] = (byte) ((value >> 32) & 0xFF);
valueBytes[offset + 4] = (byte) ((value >> 24) & 0xFF);
valueBytes[offset + 5] = (byte) ((value >> 16) & 0xFF);
valueBytes[offset + 6] = (byte) ((value >> 8) & 0xFF);
valueBytes[offset + 7] = (byte) ((value >> 0) & 0xFF);
}
static BigDecimal readBigDecimal(byte valueBytes[], int valueLength, int scale) {
int sign = (0 == valueBytes[0]) ? -1 : 1;
byte[] magnitude = new byte[valueLength - 1];
for (int i = 1; i <= magnitude.length; i++)
magnitude[magnitude.length - i] = valueBytes[i];
return new BigDecimal(new BigInteger(sign, magnitude), scale);
}
/**
* Reads a long value from byte array.
*
* @param data
* the byte array.
* @param nOffset
* the offset into byte array to start reading.
* @return long value as read from bytes.
*/
/* L0 */static long readLong(byte data[], int nOffset) {
return ((long) (data[nOffset + 7] & 0xff) << 56) | ((long) (data[nOffset + 6] & 0xff) << 48)
| ((long) (data[nOffset + 5] & 0xff) << 40) | ((long) (data[nOffset + 4] & 0xff) << 32)
| ((long) (data[nOffset + 3] & 0xff) << 24) | ((long) (data[nOffset + 2] & 0xff) << 16)
| ((long) (data[nOffset + 1] & 0xff) << 8) | ((long) (data[nOffset] & 0xff));
}
/**
* Writes a long to byte array.
*
* @param value
* long value to write.
* @param valueBytes
* the byte array.
* @param offset
* the offset inside byte array.
*/
static void writeLong(long value, byte valueBytes[], int offset) {
valueBytes[offset++] = (byte) ((value) & 0xFF);
valueBytes[offset++] = (byte) ((value >> 8) & 0xFF);
valueBytes[offset++] = (byte) ((value >> 16) & 0xFF);
valueBytes[offset++] = (byte) ((value >> 24) & 0xFF);
valueBytes[offset++] = (byte) ((value >> 32) & 0xFF);
valueBytes[offset++] = (byte) ((value >> 40) & 0xFF);
valueBytes[offset++] = (byte) ((value >> 48) & 0xFF);
valueBytes[offset] = (byte) ((value >> 56) & 0xFF);
}
/**
* Parse a JDBC URL into a set of properties.
*
* @param url
* the JDBC URL
* @param logger
* @return the properties
* @throws SQLServerException
*/
/* L0 */ static Properties parseUrl(String url, Logger logger) throws SQLServerException {
Properties p = new Properties();
String tmpUrl = url;
String sPrefix = "jdbc:sqlserver://";
String result = "";
String name = "";
String value = "";
StringBuilder builder;
if (!tmpUrl.startsWith(sPrefix))
return null;
tmpUrl = tmpUrl.substring(sPrefix.length());
int i;
// Simple finite state machine.
// always look at one char at a time
final int inStart = 0;
final int inServerName = 1;
final int inPort = 2;
final int inInstanceName = 3;
final int inEscapedValueStart = 4;
final int inEscapedValueEnd = 5;
final int inValue = 6;
final int inName = 7;
int state = inStart;
char ch;
i = 0;
while (i < tmpUrl.length()) {
ch = tmpUrl.charAt(i);
switch (state) {
case inStart: {
if (ch == ';') {
// done immediately
state = inName;
} else {
builder = new StringBuilder();
builder.append(result);
builder.append(ch);
result = builder.toString();
state = inServerName;
}
break;
}
case inServerName: {
if (ch == ';' || ch == ':' || ch == '\\') {
// non escaped trim the string
result = result.trim();
if (result.length() > 0) {
p.put(SQLServerDriverStringProperty.SERVER_NAME.toString(), result);
if (logger.isLoggable(Level.FINE)) {
logger.fine("Property:serverName " + "Value:" + result);
}
}
result = "";
if (ch == ';')
state = inName;
else if (ch == ':')
state = inPort;
else
state = inInstanceName;
} else {
builder = new StringBuilder();
builder.append(result);
builder.append(ch);
result = builder.toString();
// same state
}
break;
}
case inPort: {
if (ch == ';') {
result = result.trim();
if (logger.isLoggable(Level.FINE)) {
logger.fine("Property:portNumber " + "Value:" + result);
}
p.put(SQLServerDriverIntProperty.PORT_NUMBER.toString(), result);
result = "";
state = inName;
} else {
builder = new StringBuilder();
builder.append(result);
builder.append(ch);
result = builder.toString();
// same state
}
break;
}
case inInstanceName: {
if (ch == ';' || ch == ':') {
// non escaped trim the string
result = result.trim();
if (logger.isLoggable(Level.FINE)) {
logger.fine("Property:instanceName " + "Value:" + result);
}
p.put(SQLServerDriverStringProperty.INSTANCE_NAME.toString(), result.toLowerCase(Locale.US));
result = "";
if (ch == ';')
state = inName;
else
state = inPort;
} else {
builder = new StringBuilder();
builder.append(result);
builder.append(ch);
result = builder.toString();
// same state
}
break;
}
case inName: {
if (ch == '=') {
// name is never escaped!
name = name.trim();
if (name.length() <= 0) {
SQLServerException.makeFromDriverError(null, null,
SQLServerException.getErrString("R_errorConnectionString"), null, true);
}
state = inValue;
} else if (ch == ';') {
name = name.trim();
if (name.length() > 0) {
SQLServerException.makeFromDriverError(null, null,
SQLServerException.getErrString("R_errorConnectionString"), null, true);
}
// same state
} else {
builder = new StringBuilder();
builder.append(name);
builder.append(ch);
name = builder.toString();
// same state
}
break;
}
case inValue: {
if (ch == ';') {
// simple value trim
value = value.trim();
name = SQLServerDriver.getNormalizedPropertyName(name, logger);
if (null != name) {
if (logger.isLoggable(Level.FINE)) {
if (!name.equals(SQLServerDriverStringProperty.USER.toString())) {
if (!name.toLowerCase(Locale.ENGLISH).contains("password")
&& !name.toLowerCase(Locale.ENGLISH).contains("keystoresecret")) {
logger.fine("Property:" + name + " Value:" + value);
} else {
logger.fine("Property:" + name);
}
}
}
p.put(name, value);
}
name = "";
value = "";
state = inName;
} else if (ch == '{') {
state = inEscapedValueStart;
value = value.trim();
if (value.length() > 0) {
SQLServerException.makeFromDriverError(null, null,
SQLServerException.getErrString("R_errorConnectionString"), null, true);
}
} else {
builder = new StringBuilder();
builder.append(value);
builder.append(ch);
value = builder.toString();
// same state
}
break;
}
case inEscapedValueStart: {
/*
* check for escaped }. when we see a }, first check to see if this is before the end of the string
* to avoid index out of range exception then check if the character immediately after is also a }.
* if it is, then we have a }}, which is not the closing of the escaped state.
*/
if (ch == '}' && i + 1 < tmpUrl.length() && tmpUrl.charAt(i + 1) == '}') {
builder = new StringBuilder();
builder.append(value);
builder.append(ch);
value = builder.toString();
i++; // escaped }} into a }, so increment the counter once more
// same state
} else {
if (ch == '}') {
// no trimming use the value as it is.
name = SQLServerDriver.getNormalizedPropertyName(name, logger);
if (null != name) {
if (logger.isLoggable(Level.FINE)) {
if (!name.equals(SQLServerDriverStringProperty.USER.toString())
&& !name.equals(SQLServerDriverStringProperty.PASSWORD.toString()))
logger.fine("Property:" + name + " Value:" + value);
}
p.put(name, value);
}
name = "";
value = "";
// to eat the spaces until the ; potentially we could do without the state but
// it would not be clean
state = inEscapedValueEnd;
} else {
builder = new StringBuilder();
builder.append(value);
builder.append(ch);
value = builder.toString();
// same state
}
}
break;
}
case inEscapedValueEnd: {
if (ch == ';') // eat space chars till ; anything else is an error
{
state = inName;
} else if (ch != ' ') {
// error if the chars are not space
SQLServerException.makeFromDriverError(null, null,
SQLServerException.getErrString("R_errorConnectionString"), null, true);
}
break;
}
default:
assert false : "parseURL: Invalid state " + state;
}
i++;
}
// Exit
switch (state) {
case inServerName:
result = result.trim();
if (result.length() > 0) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Property:serverName " + "Value:" + result);
}
p.put(SQLServerDriverStringProperty.SERVER_NAME.toString(), result);
}
break;
case inPort:
result = result.trim();
if (logger.isLoggable(Level.FINE)) {
logger.fine("Property:portNumber " + "Value:" + result);
}
p.put(SQLServerDriverIntProperty.PORT_NUMBER.toString(), result);
break;
case inInstanceName:
result = result.trim();
if (logger.isLoggable(Level.FINE)) {
logger.fine("Property:instanceName " + "Value:" + result);
}
p.put(SQLServerDriverStringProperty.INSTANCE_NAME.toString(), result);
break;
case inValue:
// simple value trim
value = value.trim();
name = SQLServerDriver.getNormalizedPropertyName(name, logger);
if (null != name) {
if (logger.isLoggable(Level.FINE)) {
if (!name.equals(SQLServerDriverStringProperty.USER.toString())
&& !name.equals(SQLServerDriverStringProperty.PASSWORD.toString())
&& !name.equals(SQLServerDriverStringProperty.KEY_STORE_SECRET.toString()))
logger.fine("Property:" + name + " Value:" + value);
}
p.put(name, value);
}
break;
case inEscapedValueEnd:
case inStart:
// do nothing!
break;
case inName: {
name = name.trim();
if (name.length() > 0) {
SQLServerException.makeFromDriverError(null, null,
SQLServerException.getErrString("R_errorConnectionString"), null, true);
}
break;
}
default:
SQLServerException.makeFromDriverError(null, null,
SQLServerException.getErrString("R_errorConnectionString"), null, true);
}
return p;
}
/**
* Accepts a SQL identifier (such as a column name or table name) and escapes the identifier using SQL Server
* bracket escaping rules. Assumes that the incoming identifier is unescaped.
*
* @inID input identifier to escape.
* @return the escaped value.
*/
static String escapeSQLId(String inID) {
// SQL bracket escaping rules.
// Given <identifier> yields -> [<identifier>]
// Where <identifier> is first escaped to replace all
// instances of "]" with "]]".
// For example, column name "abc" -> "[abc]"
// For example, column name "]" -> "[]]]"
// For example, column name "]ab]cd" -> "[]]ab]]cd]"
char ch;
// Add 2 extra chars for open and closing brackets.
StringBuilder outID = new StringBuilder(inID.length() + 2);
outID.append('[');
for (int i = 0; i < inID.length(); i++) {
ch = inID.charAt(i);
if (']' == ch)
outID.append("]]");
else
outID.append(ch);
}
outID.append(']');
return outID.toString();
}
/**
* Checks if duplicate columns exists, in O(n) time.
*
* @param columnName
* the name of the column
* @throws SQLServerException
* when a duplicate column exists
*/
static void checkDuplicateColumnName(String columnName, Set<String> columnNames) throws SQLServerException {
// columnList.add will return false if the same column name already exists
if (!columnNames.add(columnName)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName"));
Object[] msgArgs = {columnName};
throw new SQLServerException(null, form.format(msgArgs), null, 0, false);
}
}
/**
* Reads a UNICODE string from byte buffer at offset (up to byteLength).
*
* @param b
* the buffer containing UNICODE bytes.
* @param offset
* - the offset into b where the UNICODE string starts.
* @param byteLength
* - the length in bytes of the UNICODE string.
* @param conn
* - the SQLServerConnection object.
* @return new String with UNICODE data inside.
*/
static String readUnicodeString(byte[] b, int offset, int byteLength,
SQLServerConnection conn) throws SQLServerException {
try {
return new String(b, offset, byteLength, Encoding.UNICODE.charset());
} catch (IndexOutOfBoundsException ex) {
String txtMsg = SQLServerException
.checkAndAppendClientConnId(SQLServerException.getErrString("R_stringReadError"), conn);
MessageFormat form = new MessageFormat(txtMsg);
Object[] msgArgs = {offset};
// Re-throw SQLServerException if conversion fails.
throw new SQLServerException(form.format(msgArgs), null, 0, ex);
}
}
// NOTE: This is for display purposes ONLY. NOT TO BE USED for data conversion.
/**
* Converts byte array to a string representation of hex bytes for display purposes.
*
* @param b
* the source buffer.
* @return "hexized" string representation of bytes.
*/
static String byteToHexDisplayString(byte[] b) {
if (null == b)
return "(null)";
int hexVal;
StringBuilder sb = new StringBuilder(b.length * 2 + 2);
sb.append("0x");
for (byte aB : b) {
hexVal = aB & 0xFF;
sb.append(hexChars[(hexVal & 0xF0) >> 4]);
sb.append(hexChars[(hexVal & 0x0F)]);
}
return sb.toString();
}
/**
* Converts byte array to a string representation of hex bytes.
*
* @param b
* the source buffer.
* @return "hexized" string representation of bytes.
*/
static String bytesToHexString(byte[] b, int length) {
StringBuilder sb = new StringBuilder(length * 2);
for (int i = 0; i < length; i++) {
int hexVal = b[i] & 0xFF;
sb.append(hexChars[(hexVal & 0xF0) >> 4]);
sb.append(hexChars[(hexVal & 0x0F)]);
}
return sb.toString();
}
/**
* Looks up local hostname of client machine.
*
* @exception UnknownHostException
* if local hostname is not found.
* @return hostname string or ip of host if hostname cannot be resolved. If neither hostname or ip found returns ""
* per spec.
*/
static String lookupHostName() {
try {
InetAddress localAddress = InetAddress.getLocalHost();
if (null != localAddress) {
String value = localAddress.getHostName();
if (null != value && value.length() > 0)
return value;
value = localAddress.getHostAddress();
if (null != value && value.length() > 0)
return value;
}
} catch (UnknownHostException e) {
return WSIDNotAvailable;
}
// If hostname not found, return standard "" string.
return WSIDNotAvailable;
}
static final byte[] asGuidByteArray(UUID aId) {
long msb = aId.getMostSignificantBits();
long lsb = aId.getLeastSignificantBits();
byte[] buffer = new byte[16];
Util.writeLongBigEndian(msb, buffer, 0);
Util.writeLongBigEndian(lsb, buffer, 8);
// For the first three fields, UUID uses network byte order,
// Guid uses native byte order. So we need to reverse
// the first three fields before sending to server.
byte tmpByte;
// Reverse the first 4 bytes
tmpByte = buffer[0];
buffer[0] = buffer[3];
buffer[3] = tmpByte;
tmpByte = buffer[1];
buffer[1] = buffer[2];
buffer[2] = tmpByte;
// Reverse the 5th and the 6th
tmpByte = buffer[4];
buffer[4] = buffer[5];
buffer[5] = tmpByte;
// Reverse the 7th and the 8th
tmpByte = buffer[6];
buffer[6] = buffer[7];
buffer[7] = tmpByte;
return buffer;
}
static final UUID readGUIDtoUUID(byte[] inputGUID) throws SQLServerException {
if (inputGUID.length != 16) {
throw new SQLServerException("guid length must be 16", null);
}
// For the first three fields, UUID uses network byte order,
// Guid uses native byte order. So we need to reverse
// the first three fields before creating a UUID.
byte tmpByte;
// Reverse the first 4 bytes
tmpByte = inputGUID[0];
inputGUID[0] = inputGUID[3];
inputGUID[3] = tmpByte;
tmpByte = inputGUID[1];
inputGUID[1] = inputGUID[2];
inputGUID[2] = tmpByte;
// Reverse the 5th and the 6th
tmpByte = inputGUID[4];
inputGUID[4] = inputGUID[5];
inputGUID[5] = tmpByte;
// Reverse the 7th and the 8th
tmpByte = inputGUID[6];
inputGUID[6] = inputGUID[7];
inputGUID[7] = tmpByte;
long msb = 0L;
for (int i = 0; i < 8; i++) {
msb = msb << 8 | ((long) inputGUID[i] & 0xFFL);
}
long lsb = 0L;
for (int i = 8; i < 16; i++) {
lsb = lsb << 8 | ((long) inputGUID[i] & 0xFFL);
}
return new UUID(msb, lsb);
}
static final String readGUID(byte[] inputGUID) throws SQLServerException {
String guidTemplate = "NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN";
byte guid[] = inputGUID;
StringBuilder sb = new StringBuilder(guidTemplate.length());
for (int i = 0; i < 4; i++) {
sb.append(Util.hexChars[(guid[3 - i] & 0xF0) >> 4]);
sb.append(Util.hexChars[guid[3 - i] & 0x0F]);
}
sb.append('-');
for (int i = 0; i < 2; i++) {
sb.append(Util.hexChars[(guid[5 - i] & 0xF0) >> 4]);
sb.append(Util.hexChars[guid[5 - i] & 0x0F]);
}
sb.append('-');
for (int i = 0; i < 2; i++) {
sb.append(Util.hexChars[(guid[7 - i] & 0xF0) >> 4]);
sb.append(Util.hexChars[guid[7 - i] & 0x0F]);
}
sb.append('-');
for (int i = 0; i < 2; i++) {
sb.append(Util.hexChars[(guid[8 + i] & 0xF0) >> 4]);
sb.append(Util.hexChars[guid[8 + i] & 0x0F]);
}
sb.append('-');
for (int i = 0; i < 6; i++) {
sb.append(Util.hexChars[(guid[10 + i] & 0xF0) >> 4]);
sb.append(Util.hexChars[guid[10 + i] & 0x0F]);
}
return sb.toString();
}
static boolean isActivityTraceOn() {
LogManager lm = LogManager.getLogManager();
String activityTrace = lm.getProperty(ACTIVITY_ID_TRACE_PROPERTY);
return ("on".equalsIgnoreCase(activityTrace));
}
/**
* Determines if a column value should be transparently decrypted (based on SQLServerStatement and the connection
* string settings).
*
* @return true if the value should be transparently decrypted, false otherwise.
*/
static boolean shouldHonorAEForRead(SQLServerStatementColumnEncryptionSetting stmtColumnEncryptionSetting,
SQLServerConnection connection) {
// Command leve setting trumps all
switch (stmtColumnEncryptionSetting) {
case Disabled:
return false;
case Enabled:
case ResultSetOnly:
return true;
default:
// Check connection level setting!
assert SQLServerStatementColumnEncryptionSetting.UseConnectionSetting == stmtColumnEncryptionSetting : "Unexpected value for command level override";
return (connection != null && connection.isColumnEncryptionSettingEnabled());
}
}
/**
* Determines if parameters should be transparently encrypted (based on SQLServerStatement and the connection string
* settings).
*
* @return true if the value should be transparently encrypted, false otherwise.
*/
static boolean shouldHonorAEForParameters(SQLServerStatementColumnEncryptionSetting stmtColumnEncryptionSetting,
SQLServerConnection connection) {
// Command leve setting trumps all
switch (stmtColumnEncryptionSetting) {
case Disabled:
case ResultSetOnly:
return false;
case Enabled:
return true;
default:
// Check connection level setting!
assert SQLServerStatementColumnEncryptionSetting.UseConnectionSetting == stmtColumnEncryptionSetting : "Unexpected value for command level override";
return (connection != null && connection.isColumnEncryptionSettingEnabled());
}
}
static void validateMoneyRange(BigDecimal bd, JDBCType jdbcType) throws SQLServerException {
if (null == bd)
return;
switch (jdbcType) {
case MONEY:
if ((1 != bd.compareTo(SSType.MAX_VALUE_MONEY)) && (-1 != bd.compareTo(SSType.MIN_VALUE_MONEY))) {
return;
}
break;
case SMALLMONEY:
if ((1 != bd.compareTo(SSType.MAX_VALUE_SMALLMONEY))
&& (-1 != bd.compareTo(SSType.MIN_VALUE_SMALLMONEY))) {
return;
}
break;
default:
break;
}
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange"));
Object[] msgArgs = {jdbcType};
throw new SQLServerException(form.format(msgArgs), null);
}
static int getValueLengthBaseOnJavaType(Object value, JavaType javaType, Integer precision, Integer scale,
JDBCType jdbcType) throws SQLServerException {
switch (javaType) {
// when the value of setObject() is null, the javaType stays
// as OBJECT. We need to get the javaType base on jdbcType
case OBJECT:
switch (jdbcType) {
case DECIMAL:
case NUMERIC:
javaType = JavaType.BIGDECIMAL;
break;
case TIME:
javaType = JavaType.TIME;
break;
case TIMESTAMP:
javaType = JavaType.TIMESTAMP;
break;
case DATETIMEOFFSET:
javaType = JavaType.DATETIMEOFFSET;
break;
default:
break;
}
break;
default:
break;
}
switch (javaType) {
case STRING:
if (JDBCType.GUID == jdbcType) {
String guidTemplate = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";
return ((null == value) ? 0 : guidTemplate.length());
} else if (JDBCType.TIMESTAMP == jdbcType || JDBCType.TIME == jdbcType
|| JDBCType.DATETIMEOFFSET == jdbcType) {
return ((null == scale) ? TDS.MAX_FRACTIONAL_SECONDS_SCALE : scale);
} else if (JDBCType.BINARY == jdbcType || JDBCType.VARBINARY == jdbcType) {
return ((null == value) ? 0 : (ParameterUtils.HexToBin((String) value).length));
} else {
return ((null == value) ? 0 : ((String) value).length());
}
case BYTEARRAY:
return ((null == value) ? 0 : ((byte[]) value).length);
case BIGDECIMAL:
int length;
if (null == precision) {
if (null == value) {
length = 0;
} else {
if (0 == ((BigDecimal) value).intValue()) {
String s = "" + value;
s = s.replaceAll("\\-", "");
if (s.startsWith("0.")) {
// remove the leading zero, eg., for 0.32, the precision should be 2 and not 3
s = s.replaceAll("0\\.", "");
} else {
s = s.replaceAll("\\.", "");
}
length = s.length();
}
// if the value is in scientific notation format
else if (("" + value).contains("E")) {
DecimalFormat dform = new DecimalFormat("###.#####");
String s = dform.format(value);
s = s.replaceAll("\\.", "");
s = s.replaceAll("\\-", "");
length = s.length();
} else {
length = ((BigDecimal) value).precision();
}
}
} else {
length = precision;
}
return length;
case TIMESTAMP:
case TIME:
case DATETIMEOFFSET:
return ((null == scale) ? TDS.MAX_FRACTIONAL_SECONDS_SCALE : scale);
case CLOB:
return ((null == value) ? 0 : (DataTypes.NTEXT_MAX_CHARS * 2));
case NCLOB:
case READER:
return ((null == value) ? 0 : DataTypes.NTEXT_MAX_CHARS);
default:
return 0;
}
}
// If the access token is expiring within next 10 minutes, lets just re-create a token for this connection attempt.
// If the token is expiring within the next 45 mins, try to fetch a new token if there is no thread already doing
// it.
// If a thread is already doing the refresh, just use the existing token and proceed.
static synchronized boolean checkIfNeedNewAccessToken(SQLServerConnection connection, Date accessTokenExpireDate) {
Date now = new Date();
// if the token's expiration is within the next 45 mins
// 45 mins * 60 sec/min * 1000 millisec/sec
if ((accessTokenExpireDate.getTime() - now.getTime()) < (45 * 60 * 1000)) {
// within the next 10 mins
if ((accessTokenExpireDate.getTime() - now.getTime()) < (10 * 60 * 1000)) {
return true;
} else {
// check if another thread is already updating the access token
if (connection.attemptRefreshTokenLocked) {
return false;
} else {
connection.attemptRefreshTokenLocked = true;
return true;
}
}
}
return false;
}
static final boolean use43Wrapper;
static {
boolean supportJDBC43 = true;
try {
DriverJDBCVersion.checkSupportsJDBC43();
} catch (UnsupportedOperationException e) {
supportJDBC43 = false;
}
double jvmVersion = Double.parseDouble(Util.SYSTEM_SPEC_VERSION);
use43Wrapper = supportJDBC43 && (9 <= jvmVersion);
}
// if driver is for JDBC 43 and jvm version is 9 or higher, then always return as SQLServerConnection43,
// otherwise return SQLServerConnection
static boolean use43Wrapper() {
return use43Wrapper;
}
@SuppressWarnings("unchecked")
static <T> T newInstance(Class<?> returnType, String className, String constructorArg,
Object[] msgArgs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException {
Class<?> clazz = Class.forName(className);
if (!returnType.isAssignableFrom(clazz)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_unassignableError"));
throw new IllegalArgumentException(form.format(msgArgs));
}
if (constructorArg == null) {
return (T) clazz.getDeclaredConstructor().newInstance();
} else {
return (T) clazz.getDeclaredConstructor(String.class).newInstance(constructorArg);
}
}
/**
* Escapes single quotes (') in object name to convert and pass it as String safely.
*
* @param name
* Object name to be passed as String
* @return Converted object name
*/
static String escapeSingleQuotes(String name) {
return name.replace("'", "''");
}
static String convertInputStreamToString(java.io.InputStream is) throws IOException {
java.io.ByteArrayOutputStream result = new java.io.ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
return result.toString();
}
}
final class SQLIdentifier {
// Component names default to empty string (rather than null) for consistency
// with API behavior which returns empty string (rather than null) when the
// particular value is not present.
private String serverName = "";
final String getServerName() {
return serverName;
}
final void setServerName(String name) {
serverName = name;
}
private String databaseName = "";
final String getDatabaseName() {
return databaseName;
}
final void setDatabaseName(String name) {
databaseName = name;
}
private String schemaName = "";
final String getSchemaName() {
return schemaName;
}
final void setSchemaName(String name) {
schemaName = name;
}
private String objectName = "";
final String getObjectName() {
return objectName;
}
final void setObjectName(String name) {
objectName = name;
}
final String asEscapedString() {
StringBuilder fullName = new StringBuilder(256);
if (serverName.length() > 0)
fullName.append("[").append(serverName).append("].");
if (databaseName.length() > 0)
fullName.append("[").append(databaseName).append("].");
else
assert 0 == serverName.length();
if (schemaName.length() > 0)
fullName.append("[").append(schemaName).append("].");
else if (databaseName.length() > 0)
fullName.append('.');
fullName.append("[").append(objectName).append("]");
return fullName.toString();
}
}
|
Fix | Use a StringBuilder in SQLServerConnection.parseUrl() (#1317)
|
src/main/java/com/microsoft/sqlserver/jdbc/Util.java
|
Fix | Use a StringBuilder in SQLServerConnection.parseUrl() (#1317)
|
<ide><path>rc/main/java/com/microsoft/sqlserver/jdbc/Util.java
<ide> Properties p = new Properties();
<ide> String tmpUrl = url;
<ide> String sPrefix = "jdbc:sqlserver://";
<del> String result = "";
<add> StringBuilder result = new StringBuilder();
<ide> String name = "";
<ide> String value = "";
<del> StringBuilder builder;
<ide>
<ide> if (!tmpUrl.startsWith(sPrefix))
<ide> return null;
<ide> // done immediately
<ide> state = inName;
<ide> } else {
<del> builder = new StringBuilder();
<del> builder.append(result);
<del> builder.append(ch);
<del> result = builder.toString();
<add> result.append(ch);
<ide> state = inServerName;
<ide> }
<ide> break;
<ide> case inServerName: {
<ide> if (ch == ';' || ch == ':' || ch == '\\') {
<ide> // non escaped trim the string
<del> result = result.trim();
<del> if (result.length() > 0) {
<del> p.put(SQLServerDriverStringProperty.SERVER_NAME.toString(), result);
<add> String property = result.toString().trim();
<add> if (property.length() > 0) {
<add> p.put(SQLServerDriverStringProperty.SERVER_NAME.toString(), property);
<ide> if (logger.isLoggable(Level.FINE)) {
<del> logger.fine("Property:serverName " + "Value:" + result);
<add> logger.fine("Property:serverName " + "Value:" + property);
<ide> }
<ide> }
<del> result = "";
<add> result.setLength(0);
<ide>
<ide> if (ch == ';')
<ide> state = inName;
<ide> else
<ide> state = inInstanceName;
<ide> } else {
<del> builder = new StringBuilder();
<del> builder.append(result);
<del> builder.append(ch);
<del> result = builder.toString();
<add> result.append(ch);
<ide> // same state
<ide> }
<ide> break;
<ide>
<ide> case inPort: {
<ide> if (ch == ';') {
<del> result = result.trim();
<add> String property = result.toString().trim();
<ide> if (logger.isLoggable(Level.FINE)) {
<del> logger.fine("Property:portNumber " + "Value:" + result);
<add> logger.fine("Property:portNumber " + "Value:" + property);
<ide> }
<del> p.put(SQLServerDriverIntProperty.PORT_NUMBER.toString(), result);
<del> result = "";
<add> p.put(SQLServerDriverIntProperty.PORT_NUMBER.toString(), property);
<add> result.setLength(0);
<ide> state = inName;
<ide> } else {
<del> builder = new StringBuilder();
<del> builder.append(result);
<del> builder.append(ch);
<del> result = builder.toString();
<add> result.append(ch);
<ide> // same state
<ide> }
<ide> break;
<ide> case inInstanceName: {
<ide> if (ch == ';' || ch == ':') {
<ide> // non escaped trim the string
<del> result = result.trim();
<add> String property = result.toString().trim();
<ide> if (logger.isLoggable(Level.FINE)) {
<del> logger.fine("Property:instanceName " + "Value:" + result);
<add> logger.fine("Property:instanceName " + "Value:" + property);
<ide> }
<del> p.put(SQLServerDriverStringProperty.INSTANCE_NAME.toString(), result.toLowerCase(Locale.US));
<del> result = "";
<add> p.put(SQLServerDriverStringProperty.INSTANCE_NAME.toString(), property.toLowerCase(Locale.US));
<add> result.setLength(0);
<ide>
<ide> if (ch == ';')
<ide> state = inName;
<ide> else
<ide> state = inPort;
<ide> } else {
<del> builder = new StringBuilder();
<del> builder.append(result);
<del> builder.append(ch);
<del> result = builder.toString();
<add> result.append(ch);
<ide> // same state
<ide> }
<ide> break;
<ide> }
<ide> // same state
<ide> } else {
<del> builder = new StringBuilder();
<add> StringBuilder builder = new StringBuilder();
<ide> builder.append(name);
<ide> builder.append(ch);
<ide> name = builder.toString();
<ide> SQLServerException.getErrString("R_errorConnectionString"), null, true);
<ide> }
<ide> } else {
<del> builder = new StringBuilder();
<add> StringBuilder builder = new StringBuilder();
<ide> builder.append(value);
<ide> builder.append(ch);
<ide> value = builder.toString();
<ide> * if it is, then we have a }}, which is not the closing of the escaped state.
<ide> */
<ide> if (ch == '}' && i + 1 < tmpUrl.length() && tmpUrl.charAt(i + 1) == '}') {
<del> builder = new StringBuilder();
<add> StringBuilder builder = new StringBuilder();
<ide> builder.append(value);
<ide> builder.append(ch);
<ide> value = builder.toString();
<ide> // it would not be clean
<ide> state = inEscapedValueEnd;
<ide> } else {
<del> builder = new StringBuilder();
<add> StringBuilder builder = new StringBuilder();
<ide> builder.append(value);
<ide> builder.append(ch);
<ide> value = builder.toString();
<ide> // Exit
<ide> switch (state) {
<ide> case inServerName:
<del> result = result.trim();
<del> if (result.length() > 0) {
<add> String property = result.toString().trim();
<add> if (property.length() > 0) {
<ide> if (logger.isLoggable(Level.FINE)) {
<del> logger.fine("Property:serverName " + "Value:" + result);
<add> logger.fine("Property:serverName " + "Value:" + property);
<ide> }
<del> p.put(SQLServerDriverStringProperty.SERVER_NAME.toString(), result);
<add> p.put(SQLServerDriverStringProperty.SERVER_NAME.toString(), property);
<ide> }
<ide> break;
<ide> case inPort:
<del> result = result.trim();
<add> property = result.toString().trim();
<ide> if (logger.isLoggable(Level.FINE)) {
<del> logger.fine("Property:portNumber " + "Value:" + result);
<del> }
<del> p.put(SQLServerDriverIntProperty.PORT_NUMBER.toString(), result);
<add> logger.fine("Property:portNumber " + "Value:" + property);
<add> }
<add> p.put(SQLServerDriverIntProperty.PORT_NUMBER.toString(), property);
<ide> break;
<ide> case inInstanceName:
<del> result = result.trim();
<add> property = result.toString().trim();
<ide> if (logger.isLoggable(Level.FINE)) {
<del> logger.fine("Property:instanceName " + "Value:" + result);
<del> }
<del> p.put(SQLServerDriverStringProperty.INSTANCE_NAME.toString(), result);
<add> logger.fine("Property:instanceName " + "Value:" + property);
<add> }
<add> p.put(SQLServerDriverStringProperty.INSTANCE_NAME.toString(), property);
<ide> break;
<ide> case inValue:
<ide> // simple value trim
|
|
JavaScript
|
agpl-3.0
|
ff389d47f648411643a9c42a3992278a3e26ce7d
| 0 |
MattiSG/Watai,MattiSG/Watai
|
var promises = require('q');
var FunctionalStep = new Class({
Extends: require('./AbstractStep'),
/** A function, promise-returning or not, to be executed. If it throws, or returns a rejected promise, this step will fail. Otherwise, it will succeed.
*
*@type {Function}
*@private
*/
action: null,
/**
*@param {Function} action A function, promise-returning or not, to be executed. If it throws, or returns a rejected promise, this step will fail. Otherwise, it will succeed.
*/
initialize: function init(action) {
this.action = action;
},
start: function start() {
promises.fcall(this.action)
.done(this.succeed.bind(this), this.fail.bind(this));
},
formatFailure: function formatFailure(report) {
return (this.getDescription()
+ ' failed'
+ (report
? ', returning "' + report + '"'
: '')
);
},
/**
*@see AbstractStep#getDescription
*/
getDescription: function getDescription() {
if (this.action.widget) // this is a Widget action
return this.describeAction();
// this is a custom user function, hopefully the user provided a good name for it
return this.action.name || '[unnamed action]';
},
/** Tries to describe the wrapped step, assuming it is a Widget-generated action.
*
*@returns {String} A user-presentable action description.
*@see Widget
*/
describeAction: function describeAction() {
var humanizedAction = (this.action.title || this.action.element).humanize() // makes naming functions themselves optional, but let them have higher precedence: users can thus provide more details in function names without making it long to access them in tests
return this.action.widget
+ ' '
+ humanizedAction
+ (this.action.args.length
? ' with "' + this.action.args.join('", "') + '"'
: '')
+ (humanizedAction != this.action.element // make it easier to locate source
? ' (as ' + this.action.element + ')'
: '')
}
});
module.exports = FunctionalStep; // CommonJS export
|
src/model/scenario/FunctionalStep.js
|
var promises = require('q');
var FunctionalStep = new Class({
Extends: require('./AbstractStep'),
/** A function, promise-returning or not, to be executed. If it throws, or returns a rejected promise, this step will fail. Otherwise, it will succeed.
*
*@type {Function}
*@private
*/
action: null,
/**
*@param {Function} action A function, promise-returning or not, to be executed. If it throws, or returns a rejected promise, this step will fail. Otherwise, it will succeed.
*/
initialize: function init(action) {
this.action = action;
},
start: function start() {
promises.fcall(this.action)
.done(this.succeed.bind(this), this.fail.bind(this));
},
formatFailure: function formatFailure(report) {
return (this.getDescription()
+ ' failed'
+ (report
? ', returning "' + report + '"'
: '')
);
},
/**
*@see AbstractStep#getDescription
*/
getDescription: function getDescription() {
if (this.action.widget) // this is a Widget action
return this.describeAction();
// this is a custom user function, hopefully the user provided a good name for it
return this.action.name || '[unnamed action]';
},
/** Tries to describe the wrapped step, assuming it is a Widget-generated action.
*
*@returns {String} A user-presentable action description.
*@see Widget
*/
describeAction: function describeAction() {
var humanizedAction = (this.action.title || this.action.element).humanize() // makes naming functions themselves optional, but let them have higher precedence: users can thus provide more details in function names without making it long to access them in tests
return this.action.widget
+ ' '
+ humanizedAction
+ (this.action.args
? ' ' + this.action.args
: '')
+ (humanizedAction != this.action.element // make it easier to locate source
? ' (as ' + this.action.element + ')'
: '')
}
});
module.exports = FunctionalStep; // CommonJS export
|
Improve actions parameters listing in reports
|
src/model/scenario/FunctionalStep.js
|
Improve actions parameters listing in reports
|
<ide><path>rc/model/scenario/FunctionalStep.js
<ide> return this.action.widget
<ide> + ' '
<ide> + humanizedAction
<del> + (this.action.args
<del> ? ' ' + this.action.args
<add> + (this.action.args.length
<add> ? ' with "' + this.action.args.join('", "') + '"'
<ide> : '')
<ide> + (humanizedAction != this.action.element // make it easier to locate source
<ide> ? ' (as ' + this.action.element + ')'
|
|
Java
|
agpl-3.0
|
634d723f6c2f71f9ba1f36e09afaf7d93764480a
| 0 |
splicemachine/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine
|
package com.splicemachine.db.impl.sql.compile;
import com.splicemachine.db.catalog.IndexDescriptor;
import com.splicemachine.db.iapi.error.StandardException;
import com.splicemachine.db.iapi.sql.compile.*;
import com.splicemachine.db.iapi.sql.dictionary.ConglomerateDescriptor;
import com.splicemachine.db.iapi.sql.dictionary.IndexRowGenerator;
import java.util.List;
/**
*
* This class incorporates all join selectivity algorithms for splice machine. This still needs a little work with identifying situations where the
* relational structure (one to many, many to one) can provide better join selectivity estimates.
*
*
*/
public class SelectivityUtil {
public enum SelectivityJoinType {
OUTER, INNER, ANTIJOIN
}
public static double estimateJoinSelectivity(Optimizable innerTable, ConglomerateDescriptor innerCD,
OptimizablePredicateList predList,
long innerRowCount,long outerRowCount,
CostEstimate outerCost) throws StandardException {
if (outerCost.isOuterJoin())
return estimateJoinSelectivity(innerTable,innerCD,predList,innerRowCount,outerRowCount,SelectivityJoinType.OUTER);
else if (outerCost.isAntiJoin())
return estimateJoinSelectivity(innerTable,innerCD,predList,innerRowCount,outerRowCount,SelectivityJoinType.ANTIJOIN);
else
return estimateJoinSelectivity(innerTable,innerCD,predList,innerRowCount,outerRowCount,SelectivityJoinType.INNER);
}
public static double estimateJoinSelectivity(Optimizable innerTable, ConglomerateDescriptor innerCD,
OptimizablePredicateList predList,
long innerRowCount,long outerRowCount,
SelectivityJoinType selectivityJoinType) throws StandardException {
assert innerTable!=null:"Null values passed in to estimateJoinSelectivity " + innerTable ;
assert innerTable!=null:"Null values passed in to hashJoinSelectivity";
if (isOneRowResultSet(innerTable, innerCD, predList)) {
switch (selectivityJoinType) {
case OUTER:
case INNER:
return 1d/innerRowCount;
case ANTIJOIN:
return 1-1d/innerRowCount;
}
}
double selectivity = 1.d;
if (predList != null) {
for (int i = 0; i < predList.size(); i++) {
Predicate p = (Predicate) predList.getOptPredicate(i);
if (!p.isJoinPredicate()) continue;
selectivity = Math.min(selectivity, p.joinSelectivity(innerTable, innerCD, innerRowCount, outerRowCount, selectivityJoinType));
}
}
return selectivity;
};
public static double estimateScanSelectivity(Optimizable innerTable, OptimizablePredicateList predList) throws StandardException {
double selectivity = 1d;
if (innerTable == null) {
return selectivity;
}
for (int i = 0; i < predList.size(); i++) {
Predicate p = (Predicate) predList.getOptPredicate(i);
if (!p.isJoinPredicate()) continue;
selectivity *= p.scanSelectivity(innerTable);
}
return selectivity;
}
public static boolean isOneRowResultSet(Optimizable innerTable, ConglomerateDescriptor cd,
OptimizablePredicateList predList) throws StandardException{
if(predList==null || cd == null ){
return false;
}
assert predList instanceof PredicateList;
@SuppressWarnings("ConstantConditions") PredicateList restrictionList=(PredicateList)predList;
if(!cd.isIndex()){
IndexDescriptor indexDec=cd.getIndexDescriptor();
if(indexDec==null || indexDec.indexType()==null || !indexDec.indexType().contains("PRIMARY")){
return false;
}
}
IndexRowGenerator irg= cd.getIndexDescriptor();
if (irg == null)
return false;
// is this a unique index
if(!irg.isUnique()){
return false;
}
int[] baseColumnPositions=irg.baseColumnPositions();
// Do we have an exact match on the full key
for(int curCol : baseColumnPositions){
// get the column number at this position
/* Is there a pushable equality predicate on this key column?
* (IS NULL is also acceptable)
*/
List<Predicate> optimizableEqualityPredicateList =
restrictionList.getOptimizableEqualityPredicateList(innerTable, curCol, true);
// No equality predicate for this column, so this is not a one row result set
if (optimizableEqualityPredicateList == null)
return false;
// Look for equality predicate that is not a join predicate
boolean existsNonjoinPredicate = false;
for (int i = 0; i < optimizableEqualityPredicateList.size(); ++i) {
Predicate predicate = optimizableEqualityPredicateList.get(i);
if (!predicate.isJoinPredicate()) {
existsNonjoinPredicate = true;
break;
}
}
// If all equality predicates are join predicates, then this is NOT a one row result set
if (!existsNonjoinPredicate)
return false;
}
return true;
}
public static double existsFraction(ConglomerateDescriptor cd, OptimizablePredicateList predList) {
double fraction = 1.0d;
if (predList != null) {
for (int i = 0; i < predList.size(); i++) {
Predicate p = (Predicate) predList.getOptPredicate(i);
if (!p.isJoinPredicate()) continue;
}
}
return fraction;
}
public static double getTotalHeapSize(CostEstimate innerCostEstimate,
CostEstimate outerCostEstimate,
double totalOutputRows){
return getTotalHeapSize(outerCostEstimate.getEstimatedHeapSize(),innerCostEstimate.getEstimatedHeapSize(),
outerCostEstimate.rowCount(),innerCostEstimate.rowCount(),totalOutputRows);
}
public static double getTotalHeapSize(double outerHeapSize,
double innerHeapSize,
double outerRowCount,
double innerRowCount,
double totalOutputRows){
return totalOutputRows*(
(innerHeapSize/(innerRowCount<1.0d?1.0d:innerRowCount)) +
(outerHeapSize/(outerRowCount<1.0d?1.0d:outerRowCount)));
}
public static double getTotalRemoteCost(CostEstimate innerCostEstimate,
CostEstimate outerCostEstimate,
double totalOutputRows){
return getTotalRemoteCost(outerCostEstimate.remoteCost(),innerCostEstimate.remoteCost(),
outerCostEstimate.rowCount(),innerCostEstimate.rowCount(),totalOutputRows);
}
public static double getTotalRemoteCost(double outerRemoteCost,
double innerRemoteCost,
double outerRowCount,
double innerRowCount,
double totalOutputRows){
return totalOutputRows*(
(innerRemoteCost/(innerRowCount<1.0d?1.0d:innerRowCount)) +
(outerRemoteCost/(outerRowCount<1.0d?1.0d:outerRowCount)));
}
public static double getTotalRows(Double joinSelectivity, double outerRowCount, double innerRowCount) {
return joinSelectivity*
(outerRowCount<1.0d?1.0d:outerRowCount)*
(innerRowCount<1.0d?1.0d:innerRowCount);
}
/**
*
* Broadcast Join Local Cost Computation
*
* Total Cost = (Left Side Cost/Partition Count) + Right Side Cost + Right Side Transfer Cost + Open Cost + Close Cost + 0.1
*
* @param innerCost
* @param outerCost
* @return
*/
public static double broadcastJoinStrategyLocalCost(CostEstimate innerCost, CostEstimate outerCost) {
return (outerCost.localCost())/outerCost.partitionCount()+innerCost.localCost()+innerCost.remoteCost()+innerCost.getOpenCost()+innerCost.getCloseCost()+.01; // .01 Hash Cost
}
/**
*
* Merge Join Local Cost Computation
*
* Total Cost = (Left Side Cost + Right Side Cost + Right Side Remote Cost)/Left Side Partition Count) + Open Cost + Close Cost
*
* @param innerCost
* @param outerCost
* @return
*/
public static double mergeJoinStrategyLocalCost(CostEstimate innerCost, CostEstimate outerCost, boolean outerTableEmpty) {
if (outerTableEmpty) {
return (outerCost.localCost())/outerCost.partitionCount()+innerCost.getOpenCost()+innerCost.getCloseCost();
}
else
return (outerCost.localCost()+innerCost.localCost()+innerCost.remoteCost())/outerCost.partitionCount()+innerCost.getOpenCost()+innerCost.getCloseCost();
}
/**
*
* Merge Sort Join Local Cost Computation
*
* Total Cost = Max( (Left Side Cost+ReplicationFactor*Left Transfer Cost)/Left Number of Partitions),
* (Right Side Cost+ReplicationFactor*Right Transfer Cost)/Right Number of Partitions)
*
* Replication Factor Based
*
* @param innerCost
* @param outerCost
* @return
*/
public static double mergeSortJoinStrategyLocalCost(CostEstimate innerCost, CostEstimate outerCost, double replicationFactor) {
return Math.max( (outerCost.localCost()+replicationFactor*outerCost.getRemoteCost())/outerCost.partitionCount(),
(innerCost.localCost()+replicationFactor*innerCost.getRemoteCost())/innerCost.partitionCount());
}
/**
*
* Half Merge Sort Join Local Cost Computation
*
* Total Cost = (Left Side Cost + Right Side Cost + Right Side Remote Cost)/Left Side Partition Count) + Open Cost + Close Cost
*
* Replication Factor Based
*
* @param innerCost
* @param outerCost
* @return
*/
public static double halfMergeSortJoinStrategyLocalCost(CostEstimate innerCost, CostEstimate outerCost, double replicationFactor) {
return 1.1*((outerCost.localCost()+innerCost.localCost()+innerCost.remoteCost())/outerCost.partitionCount()+innerCost.getOpenCost()+innerCost.getCloseCost());
}
/**
*
* Nested Loop Join Local Cost Computation
*
* Total Cost = (Left Side Cost)/Left Side Partition Count) + (Left Side Row Count/Left Side Partition Count)*(Right Side Cost + Right Side Transfer Cost + Open Cost + Close Cost)
*
* @param innerCost
* @param outerCost
* @return
*/
public static double nestedLoopJoinStrategyLocalCost(CostEstimate innerCost, CostEstimate outerCost) {
return outerCost.localCost()/outerCost.partitionCount() + (outerCost.rowCount()/outerCost.partitionCount())*(innerCost.localCost()+innerCost.getRemoteCost()+innerCost.getOpenCost()+innerCost.getCloseCost());
}
}
|
db-engine/src/main/java/com/splicemachine/db/impl/sql/compile/SelectivityUtil.java
|
package com.splicemachine.db.impl.sql.compile;
import com.splicemachine.db.catalog.IndexDescriptor;
import com.splicemachine.db.iapi.error.StandardException;
import com.splicemachine.db.iapi.sql.compile.*;
import com.splicemachine.db.iapi.sql.dictionary.ConglomerateDescriptor;
import com.splicemachine.db.iapi.sql.dictionary.IndexRowGenerator;
import java.util.List;
/**
*
* This class incorporates all join selectivity algorithms for splice machine. This still needs a little work with identifying situations where the
* relational structure (one to many, many to one) can provide better join selectivity estimates.
*
*
*/
public class SelectivityUtil {
public enum SelectivityJoinType {
OUTER, INNER, ANTIJOIN
}
public static double estimateJoinSelectivity(Optimizable innerTable, ConglomerateDescriptor innerCD,
OptimizablePredicateList predList,
long innerRowCount,long outerRowCount,
CostEstimate outerCost) throws StandardException {
if (outerCost.isOuterJoin())
return estimateJoinSelectivity(innerTable,innerCD,predList,innerRowCount,outerRowCount,SelectivityJoinType.OUTER);
else if (outerCost.isAntiJoin())
return estimateJoinSelectivity(innerTable,innerCD,predList,innerRowCount,outerRowCount,SelectivityJoinType.ANTIJOIN);
else
return estimateJoinSelectivity(innerTable,innerCD,predList,innerRowCount,outerRowCount,SelectivityJoinType.INNER);
}
public static double estimateJoinSelectivity(Optimizable innerTable, ConglomerateDescriptor innerCD,
OptimizablePredicateList predList,
long innerRowCount,long outerRowCount,
SelectivityJoinType selectivityJoinType) throws StandardException {
assert innerTable!=null:"Null values passed in to estimateJoinSelectivity " + innerTable ;
assert innerTable!=null:"Null values passed in to hashJoinSelectivity";
if (isOneRowResultSet(innerTable, innerCD, predList)) {
switch (selectivityJoinType) {
case OUTER:
case INNER:
return 1d/innerRowCount;
case ANTIJOIN:
return 1-1d/innerRowCount;
}
}
double selectivity = 1.d;
if (predList != null) {
for (int i = 0; i < predList.size(); i++) {
Predicate p = (Predicate) predList.getOptPredicate(i);
if (!p.isJoinPredicate()) continue;
selectivity = Math.min(selectivity, p.joinSelectivity(innerTable, innerCD, innerRowCount, outerRowCount, selectivityJoinType));
}
}
return selectivity;
};
public static double estimateScanSelectivity(Optimizable innerTable, OptimizablePredicateList predList) throws StandardException {
double selectivity = 1d;
if (innerTable == null) {
return selectivity;
}
for (int i = 0; i < predList.size(); i++) {
Predicate p = (Predicate) predList.getOptPredicate(i);
if (!p.isJoinPredicate()) continue;
selectivity *= p.scanSelectivity(innerTable);
}
return selectivity;
}
public static boolean isOneRowResultSet(Optimizable innerTable, ConglomerateDescriptor cd,
OptimizablePredicateList predList) throws StandardException{
if(predList==null || cd == null ){
return false;
}
assert predList instanceof PredicateList;
@SuppressWarnings("ConstantConditions") PredicateList restrictionList=(PredicateList)predList;
if(!cd.isIndex()){
IndexDescriptor indexDec=cd.getIndexDescriptor();
if(indexDec==null || indexDec.indexType()==null || !indexDec.indexType().contains("PRIMARY")){
return false;
}
}
IndexRowGenerator irg= cd.getIndexDescriptor();
if (irg == null)
return false;
// is this a unique index
if(!irg.isUnique()){
return false;
}
int[] baseColumnPositions=irg.baseColumnPositions();
// Do we have an exact match on the full key
for(int curCol : baseColumnPositions){
// get the column number at this position
/* Is there a pushable equality predicate on this key column?
* (IS NULL is also acceptable)
*/
List<Predicate> optimizableEqualityPredicateList =
restrictionList.getOptimizableEqualityPredicateList(innerTable, curCol, true);
// No equality predicate for this column, so this is not a one row result set
if (optimizableEqualityPredicateList == null)
return false;
// Look for equality predicate that is not a join predicate
boolean existsNonjoinPredicate = false;
for (int i = 0; i < optimizableEqualityPredicateList.size(); ++i) {
Predicate predicate = optimizableEqualityPredicateList.get(i);
if (!predicate.isJoinPredicate()) {
existsNonjoinPredicate = true;
break;
}
}
// If all equality predicates are join predicates, then this is NOT a one row result set
if (!existsNonjoinPredicate)
return false;
}
return true;
}
public static double existsFraction(ConglomerateDescriptor cd, OptimizablePredicateList predList) {
double fraction = 1.0d;
if (predList != null) {
for (int i = 0; i < predList.size(); i++) {
Predicate p = (Predicate) predList.getOptPredicate(i);
if (!p.isJoinPredicate()) continue;
}
}
return fraction;
}
public static double getTotalHeapSize(CostEstimate innerCostEstimate,
CostEstimate outerCostEstimate,
double totalOutputRows){
return getTotalHeapSize(outerCostEstimate.getEstimatedHeapSize(),innerCostEstimate.getEstimatedHeapSize(),
outerCostEstimate.rowCount(),innerCostEstimate.rowCount(),totalOutputRows);
}
public static double getTotalHeapSize(double outerHeapSize,
double innerHeapSize,
double outerRowCount,
double innerRowCount,
double totalOutputRows){
return totalOutputRows*(
(innerHeapSize/(innerRowCount<0?1.0d:innerRowCount)) +
(outerHeapSize/(outerRowCount<0?1.0d:outerRowCount)));
}
public static double getTotalRemoteCost(CostEstimate innerCostEstimate,
CostEstimate outerCostEstimate,
double totalOutputRows){
return getTotalRemoteCost(outerCostEstimate.remoteCost(),innerCostEstimate.remoteCost(),
outerCostEstimate.rowCount(),innerCostEstimate.rowCount(),totalOutputRows);
}
public static double getTotalRemoteCost(double outerRemoteCost,
double innerRemoteCost,
double outerRowCount,
double innerRowCount,
double totalOutputRows){
return totalOutputRows*(
(innerRemoteCost/(innerRowCount<0?1.0d:innerRowCount)) +
(outerRemoteCost/(outerRowCount<0?1.0d:outerRowCount)));
}
public static double getTotalRows(Double joinSelectivity, double outerRowCount, double innerRowCount) {
return joinSelectivity*
(outerRowCount<1.0d?1.0d:outerRowCount)*
(innerRowCount<1.0d?1.0d:innerRowCount);
}
/**
*
* Broadcast Join Local Cost Computation
*
* Total Cost = (Left Side Cost/Partition Count) + Right Side Cost + Right Side Transfer Cost + Open Cost + Close Cost + 0.1
*
* @param innerCost
* @param outerCost
* @return
*/
public static double broadcastJoinStrategyLocalCost(CostEstimate innerCost, CostEstimate outerCost) {
return (outerCost.localCost())/outerCost.partitionCount()+innerCost.localCost()+innerCost.remoteCost()+innerCost.getOpenCost()+innerCost.getCloseCost()+.01; // .01 Hash Cost
}
/**
*
* Merge Join Local Cost Computation
*
* Total Cost = (Left Side Cost + Right Side Cost + Right Side Remote Cost)/Left Side Partition Count) + Open Cost + Close Cost
*
* @param innerCost
* @param outerCost
* @return
*/
public static double mergeJoinStrategyLocalCost(CostEstimate innerCost, CostEstimate outerCost, boolean outerTableEmpty) {
if (outerTableEmpty) {
return (outerCost.localCost())/outerCost.partitionCount()+innerCost.getOpenCost()+innerCost.getCloseCost();
}
else
return (outerCost.localCost()+innerCost.localCost()+innerCost.remoteCost())/outerCost.partitionCount()+innerCost.getOpenCost()+innerCost.getCloseCost();
}
/**
*
* Merge Sort Join Local Cost Computation
*
* Total Cost = Max( (Left Side Cost+ReplicationFactor*Left Transfer Cost)/Left Number of Partitions),
* (Right Side Cost+ReplicationFactor*Right Transfer Cost)/Right Number of Partitions)
*
* Replication Factor Based
*
* @param innerCost
* @param outerCost
* @return
*/
public static double mergeSortJoinStrategyLocalCost(CostEstimate innerCost, CostEstimate outerCost, double replicationFactor) {
return Math.max( (outerCost.localCost()+replicationFactor*outerCost.getRemoteCost())/outerCost.partitionCount(),
(innerCost.localCost()+replicationFactor*innerCost.getRemoteCost())/innerCost.partitionCount());
}
/**
*
* Half Merge Sort Join Local Cost Computation
*
* Total Cost = (Left Side Cost + Right Side Cost + Right Side Remote Cost)/Left Side Partition Count) + Open Cost + Close Cost
*
* Replication Factor Based
*
* @param innerCost
* @param outerCost
* @return
*/
public static double halfMergeSortJoinStrategyLocalCost(CostEstimate innerCost, CostEstimate outerCost, double replicationFactor) {
return 1.1*((outerCost.localCost()+innerCost.localCost()+innerCost.remoteCost())/outerCost.partitionCount()+innerCost.getOpenCost()+innerCost.getCloseCost());
}
/**
*
* Nested Loop Join Local Cost Computation
*
* Total Cost = (Left Side Cost)/Left Side Partition Count) + (Left Side Row Count/Left Side Partition Count)*(Right Side Cost + Right Side Transfer Cost + Open Cost + Close Cost)
*
* @param innerCost
* @param outerCost
* @return
*/
public static double nestedLoopJoinStrategyLocalCost(CostEstimate innerCost, CostEstimate outerCost) {
return outerCost.localCost()/outerCost.partitionCount() + (outerCost.rowCount()/outerCost.partitionCount())*(innerCost.localCost()+innerCost.getRemoteCost()+innerCost.getOpenCost()+innerCost.getCloseCost());
}
}
|
DB-4102: prevent row count from being 0
|
db-engine/src/main/java/com/splicemachine/db/impl/sql/compile/SelectivityUtil.java
|
DB-4102: prevent row count from being 0
|
<ide><path>b-engine/src/main/java/com/splicemachine/db/impl/sql/compile/SelectivityUtil.java
<ide> double innerRowCount,
<ide> double totalOutputRows){
<ide> return totalOutputRows*(
<del> (innerHeapSize/(innerRowCount<0?1.0d:innerRowCount)) +
<del> (outerHeapSize/(outerRowCount<0?1.0d:outerRowCount)));
<add> (innerHeapSize/(innerRowCount<1.0d?1.0d:innerRowCount)) +
<add> (outerHeapSize/(outerRowCount<1.0d?1.0d:outerRowCount)));
<ide> }
<ide>
<ide> public static double getTotalRemoteCost(CostEstimate innerCostEstimate,
<ide> double innerRowCount,
<ide> double totalOutputRows){
<ide> return totalOutputRows*(
<del> (innerRemoteCost/(innerRowCount<0?1.0d:innerRowCount)) +
<del> (outerRemoteCost/(outerRowCount<0?1.0d:outerRowCount)));
<add> (innerRemoteCost/(innerRowCount<1.0d?1.0d:innerRowCount)) +
<add> (outerRemoteCost/(outerRowCount<1.0d?1.0d:outerRowCount)));
<ide> }
<ide>
<ide> public static double getTotalRows(Double joinSelectivity, double outerRowCount, double innerRowCount) {
|
|
Java
|
mpl-2.0
|
1d903798eeabd2e377feee95353408a980bbe421
| 0 |
etomica/etomica,etomica/etomica,etomica/etomica
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package etomica.mappedDensity.positionOrientation;
import etomica.action.activity.ActivityIntegrate;
import etomica.atom.AtomType;
import etomica.box.Box;
import etomica.config.ConfigurationLattice;
import etomica.config.ConformationChainLinear;
import etomica.data.*;
import etomica.data.meter.MeterPotentialEnergyFromIntegrator;
import etomica.data.types.DataDoubleArray;
import etomica.data.types.DataFunction;
import etomica.dcvgcmd.P1WCAWall;
import etomica.graphics.ColorSchemeRandomByMolecule;
import etomica.graphics.DisplayPlotXChart;
import etomica.graphics.DisplayTextBoxesCAE;
import etomica.graphics.SimulationGraphic;
import etomica.integrator.IntegratorMC;
import etomica.integrator.mcmove.MCMoveMolecule;
import etomica.integrator.mcmove.MCMoveMoleculeRotate;
import etomica.lattice.LatticeCubicFcc;
import etomica.lattice.LatticeOrthorhombicHexagonal;
import etomica.nbr.cell.PotentialMasterCell;
import etomica.potential.BondingInfo;
import etomica.potential.P2LennardJones;
import etomica.potential.P2SoftSphericalTruncatedForceShifted;
import etomica.potential.PotentialMaster;
import etomica.potential.compute.PotentialCompute;
import etomica.potential.compute.PotentialComputeAggregate;
import etomica.potential.compute.PotentialComputeField;
import etomica.simulation.Simulation;
import etomica.space.BoundaryRectangularSlit;
import etomica.space.Space;
import etomica.space.Vector;
import etomica.species.SpeciesBuilder;
import etomica.species.SpeciesGeneral;
import etomica.units.Degree;
import etomica.util.ParameterBase;
import etomica.util.ParseArgs;
import etomica.util.random.IRandom;
import java.util.Arrays;
/**
* Simple Lennard-Jones molecular dynamics simulation in 3D
*/
public class LJMCDimer extends Simulation {
public IntegratorMC integrator;
public SpeciesGeneral species;
public Box box;
public P2LennardJones potential;
public final PotentialMaster potentialMaster;
public final double Lz;
public LJMCDimer(int D, int numMolecules, double density, double Lz, double temperature) {
super(Space.getInstance(D));
this.Lz = Lz;
double a = Degree.UNIT.toSim(45);
double[] a2 = new double[D - 1];
Arrays.fill(a2, a);
species = new SpeciesBuilder(space)
.addCount(AtomType.simpleFromSim(this), 2)
.setDynamic(true)
.withConformation(new ConformationChainLinear(space, 1, a2))
.build();
addSpecies(species);
double sigma = 1.0;
box = this.makeBox(new BoundaryRectangularSlit(2, getSpace()));
potentialMaster = new PotentialMasterCell(this.getSpeciesManager(), box, 2, BondingInfo.noBonding());
P1WCAWall wall = new P1WCAWall(box, 1, 1);
PotentialComputeField pcField = new PotentialComputeField(getSpeciesManager(), box);
AtomType leafType = species.getLeafType();
pcField.setFieldPotential(leafType, wall);
PotentialComputeAggregate pcAgg = new PotentialComputeAggregate(potentialMaster, pcField);
integrator = new IntegratorMC(pcAgg, this.getRandom(), 1.0, box);
integrator.setTemperature(temperature);
integrator.getMoveManager().addMCMove(new MyMCMoveMolecule(this.getRandom(), pcAgg, box));
integrator.getMoveManager().addMCMove(new MCMoveMoleculeRotate(this.getRandom(), pcAgg, box));
box.setNMolecules(species, numMolecules);
if (D == 2) {
double Lxy = numMolecules / density / Lz;
box.getBoundary().setBoxSize(Vector.of(Lxy, Lz - 1));
} else {
double Lxy = Math.sqrt(numMolecules / density / Lz);
box.getBoundary().setBoxSize(Vector.of(Lxy, Lxy, Lz - 1));
}
potential = new P2LennardJones(sigma, 1.0);
P2SoftSphericalTruncatedForceShifted p2 = new P2SoftSphericalTruncatedForceShifted(potential, 3.0);
potentialMaster.setPairPotential(leafType, leafType, p2);
ConfigurationLattice configuration = new ConfigurationLattice(D == 3 ? new LatticeCubicFcc(space) : new LatticeOrthorhombicHexagonal(space), space);
configuration.initializeCoordinates(box);
Vector l = box.getBoundary().getBoxSize();
l.setX(2, Lz);
box.getBoundary().setBoxSize(l);
}
public static void main(String[] args) {
DimerParams params = new DimerParams();
if (args.length > 0) {
ParseArgs.doParseArgs(params, args);
} else {
// override defaults here
params.D = 2;
params.Lz = 4;
params.density = 0.01;
params.numMolecules = 10;
params.temperature = 1.0;
params.nZdata = 20;
params.nAngleData = 40;
// params.D = 2;
// params.Lz = 20;
// params.density = 0.35;
// params.numMolecules = 100;
// params.temperature = 1.0;
// params.nZdata = 10;
// params.nAngleData = 20;
}
if(params.D == 2) {
System.out.println("Estimated accessible density: "+params.density*params.Lz/(params.Lz-2)+", "+params.density*params.Lz/(params.Lz-2)/(2*Math.PI));
}
int numMolecules = params.numMolecules;
double temperature = params.temperature;
double density = params.density;
int D = params.D;
double Lz = params.Lz;
int nZdata = params.nZdata;
int nAngleData = params.nAngleData;
final LJMCDimer sim = new LJMCDimer(D, numMolecules, density, Lz, temperature);
boolean graphics = true;
MeterPotentialEnergyFromIntegrator energy = new MeterPotentialEnergyFromIntegrator(sim.integrator);
MeterHistogramOrientation meterOrientation = new MeterHistogramOrientation(sim.box, 2, nZdata, nAngleData);
MeterHistogramOrientationMA meterOrientationMA = new MeterHistogramOrientationMA(sim.potentialMaster, sim.box, params.temperature, 2, nZdata, nAngleData);
MeterDensityProfile meterDensity = new MeterDensityProfile(sim.box, 2, 20 * nZdata);
MeterDensityProfileMA meterDensityMA = new MeterDensityProfileMA(sim.potentialMaster, sim.box, params.temperature, 2, 20 * nZdata);
MeterDensityProfileForceSimple meterDensityForceSimple = new MeterDensityProfileForceSimple(sim.potentialMaster, sim.box, params.temperature, 2, 20*nZdata);
if (graphics) {
final String APP_NAME = "LJMDDimer";
sim.getController().addActivity(new ActivityIntegrate(sim.integrator));
final SimulationGraphic simGraphic = new SimulationGraphic(sim, SimulationGraphic.TABBED_PANE, APP_NAME, 3);
AccumulatorAverageCollapsing avgEnergy = new AccumulatorAverageCollapsing();
avgEnergy.setPushInterval(10);
DataPumpListener pump = new DataPumpListener(energy, avgEnergy, numMolecules);
sim.integrator.getEventManager().addListener(pump);
// Orientation-density mapped averaging
AccumulatorAverageFixed avgHistogramMA = new AccumulatorAverageFixed(1000);
DataPumpListener pumpHistogramMA = new DataPumpListener(meterOrientationMA, avgHistogramMA, numMolecules);
sim.integrator.getEventManager().addListener(pumpHistogramMA);
DataHistogramSplitter splitterMA = new DataHistogramSplitter();
avgHistogramMA.addDataSink(splitterMA, new AccumulatorAverageFixed.StatType[]{avgHistogramMA.AVERAGE});
DisplayPlotXChart plotHistogramMA = new DisplayPlotXChart();
DataDoubleArray zDataMA = meterOrientationMA.getIndependentData(0);
for (int i = nZdata - 1; i >= 0; i--) {
splitterMA.setDataSink(i, plotHistogramMA.getDataSet().makeDataSink());
plotHistogramMA.setLegend(new DataTag[]{splitterMA.getTag(i)}, "z=" + (0.5 * Lz - zDataMA.getValue(i)));
}
plotHistogramMA.setLabel("HistogramsMA");
simGraphic.add(plotHistogramMA);
// Orientation-density histogramming
AccumulatorAverageFixed avgHistogram = new AccumulatorAverageFixed(1000);
DataPumpListener pumpHistogram = new DataPumpListener(meterOrientation, avgHistogram, numMolecules);
sim.integrator.getEventManager().addListener(pumpHistogram);
DataHistogramSplitter splitter = new DataHistogramSplitter();
avgHistogram.addDataSink(splitter, new AccumulatorAverageFixed.StatType[]{avgHistogram.AVERAGE});
DisplayPlotXChart plotHistogram = new DisplayPlotXChart();
DataDoubleArray zData = meterOrientation.getIndependentData(0);
for (int i = nZdata - 1; i >= 0; i--) {
splitter.setDataSink(i, plotHistogram.getDataSet().makeDataSink());
plotHistogram.setLegend(new DataTag[]{splitter.getTag(i)}, "z=" + (0.5 * Lz - zData.getValue(i)));
}
plotHistogram.setLabel("Histograms");
simGraphic.add(plotHistogram);
// Density plot -- conventional
AccumulatorAverageFixed avgDensityProfile = new AccumulatorAverageFixed(1000);
DataPumpListener pumpDensityProfile = new DataPumpListener(meterDensity, avgDensityProfile, numMolecules);
sim.integrator.getEventManager().addListener(pumpDensityProfile);
DisplayPlotXChart plotDensityProfile = new DisplayPlotXChart();
avgDensityProfile.addDataSink(plotDensityProfile.getDataSet().makeDataSink(), new AccumulatorAverageFixed.StatType[]{avgHistogram.AVERAGE});
plotDensityProfile.setLabel("Density profile");
simGraphic.add(plotDensityProfile);
// Density plot -- mapped average
AccumulatorAverageFixed avgDensityProfileMA = new AccumulatorAverageFixed(1000);
DataPumpListener pumpDensityProfileMA = new DataPumpListener(meterDensityMA, avgDensityProfileMA, numMolecules);
sim.integrator.getEventManager().addListener(pumpDensityProfileMA);
DisplayPlotXChart plotDensityProfileMA = new DisplayPlotXChart();
avgDensityProfileMA.addDataSink(plotDensityProfileMA.getDataSet().makeDataSink(), new AccumulatorAverageFixed.StatType[]{avgHistogram.AVERAGE});
plotDensityProfileMA.setLabel("Density profile MA");
simGraphic.add(plotDensityProfileMA);
// Density plot -- simple force
AccumulatorAverageFixed avgDensityProfileF = new AccumulatorAverageFixed(1000);
DataPumpListener pumpDensityProfileF = new DataPumpListener(meterDensityForceSimple, avgDensityProfileF, numMolecules);
sim.integrator.getEventManager().addListener(pumpDensityProfileF);
DisplayPlotXChart plotDensityProfileF = new DisplayPlotXChart();
avgDensityProfileF.addDataSink(plotDensityProfileF.getDataSet().makeDataSink(), new AccumulatorAverageFixed.StatType[]{avgHistogram.AVERAGE});
plotDensityProfileF.setLabel("Density profile Force");
simGraphic.add(plotDensityProfileF);
DataProcessor dpDifficulty = new DataProcessorDifficulty(sim);
avgHistogram.addDataSink(dpDifficulty, new AccumulatorAverageFixed.StatType[]{avgHistogram.ERROR});
DataHistogramSplitter splitterErr = new DataHistogramSplitter();
dpDifficulty.setDataSink(splitterErr);
DisplayPlotXChart plotHistogramErr = new DisplayPlotXChart();
for (int i = nZdata - 1; i >= 0; i--) {
splitterErr.setDataSink(i, plotHistogramErr.getDataSet().makeDataSink());
plotHistogramErr.setLegend(new DataTag[]{splitterErr.getTag(i)}, "z=" + (0.5 * Lz - zData.getValue(i)));
}
plotHistogramErr.setLabel("Difficulty");
simGraphic.add(plotHistogramErr);
DataProcessor dpDifficultyMA = new DataProcessorDifficulty(sim);
avgHistogramMA.addDataSink(dpDifficultyMA, new AccumulatorAverageFixed.StatType[]{avgHistogramMA.ERROR});
DataHistogramSplitter splitterErrMA = new DataHistogramSplitter();
dpDifficultyMA.setDataSink(splitterErrMA);
DisplayPlotXChart plotHistogramErrMA = new DisplayPlotXChart();
for (int i = nZdata - 1; i >= 0; i--) {
splitterErrMA.setDataSink(i, plotHistogramErrMA.getDataSet().makeDataSink());
plotHistogramErrMA.setLegend(new DataTag[]{splitterErrMA.getTag(i)}, "z=" + (0.5 * Lz - zData.getValue(i)));
}
plotHistogramErrMA.setLabel("Difficulty MA");
simGraphic.add(plotHistogramErrMA);
simGraphic.getController().getReinitButton().setPostAction(simGraphic.getPaintAction(sim.box));
simGraphic.getController().getDataStreamPumps().add(pump);
simGraphic.getController().getDataStreamPumps().add(pumpHistogram);
simGraphic.getController().getDataStreamPumps().add(pumpHistogramMA);
simGraphic.getController().getDataStreamPumps().add(pumpDensityProfile);
simGraphic.getController().getDataStreamPumps().add(pumpDensityProfileMA);
simGraphic.getController().getDataStreamPumps().add(pumpDensityProfileF);
simGraphic.getDisplayBox(sim.box).setColorScheme(new ColorSchemeRandomByMolecule(sim.getSpeciesManager(), sim.box, sim.getRandom()));
simGraphic.makeAndDisplayFrame(APP_NAME);
DisplayTextBoxesCAE display = new DisplayTextBoxesCAE();
display.setAccumulator(avgEnergy);
simGraphic.add(display);
return;
}
}
public static class DimerParams extends ParameterBase {
public int numMolecules = 256;
public double temperature = 2;
public double density = 0.4;
public double Lz = 10;
public int D = 3;
public int nZdata = 10;
public int nAngleData = 10;
}
private static class DataProcessorDifficulty extends DataProcessor {
private final LJMCDimer sim;
DataFunction data;
public DataProcessorDifficulty(LJMCDimer sim) {
this.sim = sim;
}
@Override
protected IData processData(IData inputData) {
data.E(inputData);
data.TE(Math.sqrt(sim.integrator.getStepCount()));
return data;
}
@Override
protected IDataInfo processDataInfo(IDataInfo inputDataInfo) {
data = (DataFunction) inputDataInfo.makeData();
return inputDataInfo;
}
}
// checks that molecule is in box before attempting to compute energy
class MyMCMoveMolecule extends MCMoveMolecule {
public MyMCMoveMolecule(IRandom random, PotentialCompute potentialCompute, Box box) {
super(random, potentialCompute, box);
}
public double getChi(double temperature) {
int D = box.getSpace().D();
double r1z = Lz/2 + molecule.getChildList().get(0).getPosition().getX(D);
double r2z = Lz/2 + molecule.getChildList().get(1).getPosition().getX(D);
if (r1z < 0 || r1z > Lz || r2z < 0 || r2z > Lz) return 0.0;
return super.getChi(temperature);
}
}
}
|
etomica-apps/src/main/java/etomica/mappedDensity/positionOrientation/LJMCDimer.java
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package etomica.mappedDensity.positionOrientation;
import etomica.action.activity.ActivityIntegrate;
import etomica.atom.AtomType;
import etomica.box.Box;
import etomica.config.ConfigurationLattice;
import etomica.config.ConformationChainLinear;
import etomica.data.*;
import etomica.data.meter.MeterPotentialEnergyFromIntegrator;
import etomica.data.types.DataDoubleArray;
import etomica.data.types.DataFunction;
import etomica.dcvgcmd.P1WCAWall;
import etomica.graphics.ColorSchemeRandomByMolecule;
import etomica.graphics.DisplayPlotXChart;
import etomica.graphics.DisplayTextBoxesCAE;
import etomica.graphics.SimulationGraphic;
import etomica.integrator.IntegratorMC;
import etomica.integrator.mcmove.MCMoveMolecule;
import etomica.integrator.mcmove.MCMoveMoleculeRotate;
import etomica.lattice.LatticeCubicFcc;
import etomica.lattice.LatticeOrthorhombicHexagonal;
import etomica.nbr.cell.PotentialMasterCell;
import etomica.potential.BondingInfo;
import etomica.potential.P2LennardJones;
import etomica.potential.P2SoftSphericalTruncatedForceShifted;
import etomica.potential.PotentialMaster;
import etomica.potential.compute.PotentialCompute;
import etomica.potential.compute.PotentialComputeAggregate;
import etomica.potential.compute.PotentialComputeField;
import etomica.simulation.Simulation;
import etomica.space.BoundaryRectangularSlit;
import etomica.space.Space;
import etomica.space.Vector;
import etomica.species.SpeciesBuilder;
import etomica.species.SpeciesGeneral;
import etomica.units.Degree;
import etomica.util.ParameterBase;
import etomica.util.ParseArgs;
import etomica.util.random.IRandom;
import java.util.Arrays;
/**
* Simple Lennard-Jones molecular dynamics simulation in 3D
*/
public class LJMCDimer extends Simulation {
public IntegratorMC integrator;
public SpeciesGeneral species;
public Box box;
public P2LennardJones potential;
public final PotentialMaster potentialMaster;
public final double Lz;
public LJMCDimer(int D, int numMolecules, double density, double Lz, double temperature) {
super(Space.getInstance(D));
this.Lz = Lz;
double a = Degree.UNIT.toSim(45);
double[] a2 = new double[D - 1];
Arrays.fill(a2, a);
species = new SpeciesBuilder(space)
.addCount(AtomType.simpleFromSim(this), 2)
.setDynamic(true)
.withConformation(new ConformationChainLinear(space, 1, a2))
.build();
addSpecies(species);
double sigma = 1.0;
box = this.makeBox(new BoundaryRectangularSlit(2, getSpace()));
potentialMaster = new PotentialMasterCell(this.getSpeciesManager(), box, 2, BondingInfo.noBonding());
P1WCAWall wall = new P1WCAWall(box, 1, 1);
PotentialComputeField pcField = new PotentialComputeField(getSpeciesManager(), box);
AtomType leafType = species.getLeafType();
pcField.setFieldPotential(leafType, wall);
PotentialComputeAggregate pcAgg = new PotentialComputeAggregate(potentialMaster, pcField);
integrator = new IntegratorMC(pcAgg, this.getRandom(), 1.0, box);
integrator.setTemperature(temperature);
integrator.getMoveManager().addMCMove(new MyMCMoveMolecule(this.getRandom(), pcAgg, box));
integrator.getMoveManager().addMCMove(new MCMoveMoleculeRotate(this.getRandom(), pcAgg, box));
box.setNMolecules(species, numMolecules);
if (D == 2) {
double Lxy = numMolecules / density / Lz;
box.getBoundary().setBoxSize(Vector.of(Lxy, Lz - 1));
} else {
double Lxy = Math.sqrt(numMolecules / density / Lz);
box.getBoundary().setBoxSize(Vector.of(Lxy, Lxy, Lz - 1));
}
potential = new P2LennardJones(sigma, 1.0);
P2SoftSphericalTruncatedForceShifted p2 = new P2SoftSphericalTruncatedForceShifted(potential, 3.0);
potentialMaster.setPairPotential(leafType, leafType, p2);
ConfigurationLattice configuration = new ConfigurationLattice(D == 3 ? new LatticeCubicFcc(space) : new LatticeOrthorhombicHexagonal(space), space);
configuration.initializeCoordinates(box);
Vector l = box.getBoundary().getBoxSize();
l.setX(2, Lz);
box.getBoundary().setBoxSize(l);
}
public static void main(String[] args) {
DimerParams params = new DimerParams();
if (args.length > 0) {
ParseArgs.doParseArgs(params, args);
} else {
// override defaults here
params.D = 2;
params.Lz = 4;
params.density = 0.01;
params.numMolecules = 10;
params.temperature = 1.0;
params.nZdata = 20;
params.nAngleData = 40;
// params.D = 2;
// params.Lz = 20;
// params.density = 0.35;
// params.numMolecules = 100;
// params.temperature = 1.0;
// params.nZdata = 10;
// params.nAngleData = 20;
}
if(params.D == 2) {
System.out.println("Estimated accessible density: "+params.density*params.Lz/(params.Lz-2)+", "+params.density*params.Lz/(params.Lz-2)/(2*Math.PI));
}
int numMolecules = params.numMolecules;
double temperature = params.temperature;
double density = params.density;
int D = params.D;
double Lz = params.Lz;
int nZdata = params.nZdata;
int nAngleData = params.nAngleData;
final LJMCDimer sim = new LJMCDimer(D, numMolecules, density, Lz, temperature);
boolean graphics = true;
MeterPotentialEnergyFromIntegrator energy = new MeterPotentialEnergyFromIntegrator(sim.integrator);
MeterHistogramOrientation meterOrientation = new MeterHistogramOrientation(sim.box, 2, nZdata, nAngleData);
MeterHistogramOrientationMA meterOrientationMA = new MeterHistogramOrientationMA(sim.potentialMaster, sim.box, params.temperature, 2, nZdata, nAngleData);
MeterDensityProfile meterDensity = new MeterDensityProfile(sim.box, 2, 20 * nZdata);
MeterDensityProfileMA meterDensityMA = new MeterDensityProfileMA(sim.potentialMaster, sim.box, params.temperature, 2, 20 * nZdata);
MeterDensityProfileForceSimple meterDensityForceSimple = new MeterDensityProfileForceSimple(sim.potentialMaster, sim.box, params.temperature, 2, 20*nZdata);
if (graphics) {
final String APP_NAME = "LJMDDimer";
sim.getController().addActivity(new ActivityIntegrate(sim.integrator));
final SimulationGraphic simGraphic = new SimulationGraphic(sim, SimulationGraphic.TABBED_PANE, APP_NAME, 3);
AccumulatorAverageCollapsing avgEnergy = new AccumulatorAverageCollapsing();
avgEnergy.setPushInterval(10);
DataPumpListener pump = new DataPumpListener(energy, avgEnergy, numMolecules);
sim.integrator.getEventManager().addListener(pump);
// Orientation-density mapped averaging
AccumulatorAverageFixed avgHistogramMA = new AccumulatorAverageFixed(1000);
DataPumpListener pumpHistogramMA = new DataPumpListener(meterOrientationMA, avgHistogramMA, numMolecules);
sim.integrator.getEventManager().addListener(pumpHistogramMA);
DataHistogramSplitter splitterMA = new DataHistogramSplitter();
avgHistogramMA.addDataSink(splitterMA, new AccumulatorAverageFixed.StatType[]{avgHistogramMA.AVERAGE});
DisplayPlotXChart plotHistogramMA = new DisplayPlotXChart();
DataDoubleArray zDataMA = meterOrientationMA.getIndependentData(0);
for (int i = nZdata - 1; i >= 0; i--) {
splitterMA.setDataSink(i, plotHistogramMA.getDataSet().makeDataSink());
plotHistogramMA.setLegend(new DataTag[]{splitterMA.getTag(i)}, "z=" + (0.5 * Lz - zDataMA.getValue(i)));
}
plotHistogramMA.setLabel("HistogramsMA");
simGraphic.add(plotHistogramMA);
// Orientation-density histogramming
AccumulatorAverageFixed avgHistogram = new AccumulatorAverageFixed(1000);
DataPumpListener pumpHistogram = new DataPumpListener(meterOrientation, avgHistogram, numMolecules);
sim.integrator.getEventManager().addListener(pumpHistogram);
DataHistogramSplitter splitter = new DataHistogramSplitter();
avgHistogram.addDataSink(splitter, new AccumulatorAverageFixed.StatType[]{avgHistogram.AVERAGE});
DisplayPlotXChart plotHistogram = new DisplayPlotXChart();
DataDoubleArray zData = meterOrientation.getIndependentData(0);
for (int i = nZdata - 1; i >= 0; i--) {
splitter.setDataSink(i, plotHistogram.getDataSet().makeDataSink());
plotHistogram.setLegend(new DataTag[]{splitter.getTag(i)}, "z=" + (0.5 * Lz - zData.getValue(i)));
}
plotHistogram.setLabel("Histograms");
simGraphic.add(plotHistogram);
// Density plot -- conventional
AccumulatorAverageFixed avgDensityProfile = new AccumulatorAverageFixed(1000);
DataPumpListener pumpDensityProfile = new DataPumpListener(meterDensity, avgDensityProfile, numMolecules);
sim.integrator.getEventManager().addListener(pumpDensityProfile);
DisplayPlotXChart plotDensityProfile = new DisplayPlotXChart();
avgDensityProfile.addDataSink(plotDensityProfile.getDataSet().makeDataSink(), new AccumulatorAverageFixed.StatType[]{avgHistogram.AVERAGE});
plotDensityProfile.setLabel("Density profile");
simGraphic.add(plotDensityProfile);
// Density plot -- mapped average
AccumulatorAverageFixed avgDensityProfileMA = new AccumulatorAverageFixed(1000);
DataPumpListener pumpDensityProfileMA = new DataPumpListener(meterDensityMA, avgDensityProfileMA, numMolecules);
sim.integrator.getEventManager().addListener(pumpDensityProfileMA);
DisplayPlotXChart plotDensityProfileMA = new DisplayPlotXChart();
avgDensityProfileMA.addDataSink(plotDensityProfileMA.getDataSet().makeDataSink(), new AccumulatorAverageFixed.StatType[]{avgHistogram.AVERAGE});
plotDensityProfileMA.setLabel("Density profile MA");
simGraphic.add(plotDensityProfileMA);
// Density plot -- simple force
AccumulatorAverageFixed avgDensityProfileF = new AccumulatorAverageFixed(1000);
DataPumpListener pumpDensityProfileF = new DataPumpListener(meterDensityForceSimple, avgDensityProfileF, numMolecules);
sim.integrator.getEventManager().addListener(pumpDensityProfileF);
DisplayPlotXChart plotDensityProfileF = new DisplayPlotXChart();
avgDensityProfileF.addDataSink(plotDensityProfileF.getDataSet().makeDataSink(), new AccumulatorAverageFixed.StatType[]{avgHistogram.AVERAGE});
plotDensityProfileF.setLabel("Density profile Force");
simGraphic.add(plotDensityProfileF);
DataProcessor dpDifficulty = new DataProcessorDifficulty(sim);
avgHistogram.addDataSink(dpDifficulty, new AccumulatorAverageFixed.StatType[]{avgHistogram.ERROR});
DataHistogramSplitter splitterErr = new DataHistogramSplitter();
dpDifficulty.setDataSink(splitterErr);
DisplayPlotXChart plotHistogramErr = new DisplayPlotXChart();
for (int i = nZdata - 1; i >= 0; i--) {
splitterErr.setDataSink(i, plotHistogramErr.getDataSet().makeDataSink());
plotHistogramErr.setLegend(new DataTag[]{splitterErr.getTag(i)}, "z=" + (0.5 * Lz - zData.getValue(i)));
}
plotHistogramErr.setLabel("Difficulty");
simGraphic.add(plotHistogramErr);
DataProcessor dpDifficultyMA = new DataProcessorDifficulty(sim);
avgHistogramMA.addDataSink(dpDifficultyMA, new AccumulatorAverageFixed.StatType[]{avgHistogramMA.ERROR});
DataHistogramSplitter splitterErrMA = new DataHistogramSplitter();
dpDifficultyMA.setDataSink(splitterErrMA);
DisplayPlotXChart plotHistogramErrMA = new DisplayPlotXChart();
for (int i = nZdata - 1; i >= 0; i--) {
splitterErrMA.setDataSink(i, plotHistogramErrMA.getDataSet().makeDataSink());
plotHistogramErrMA.setLegend(new DataTag[]{splitterErrMA.getTag(i)}, "z=" + (0.5 * Lz - zData.getValue(i)));
}
plotHistogramErrMA.setLabel("Difficulty MA");
simGraphic.add(plotHistogramErrMA);
simGraphic.getController().getReinitButton().setPostAction(simGraphic.getPaintAction(sim.box));
simGraphic.getController().getDataStreamPumps().add(pump);
simGraphic.getController().getDataStreamPumps().add(pumpHistogram);
simGraphic.getDisplayBox(sim.box).setColorScheme(new ColorSchemeRandomByMolecule(sim.getSpeciesManager(), sim.box, sim.getRandom()));
simGraphic.makeAndDisplayFrame(APP_NAME);
DisplayTextBoxesCAE display = new DisplayTextBoxesCAE();
display.setAccumulator(avgEnergy);
simGraphic.add(display);
return;
}
}
public static class DimerParams extends ParameterBase {
public int numMolecules = 256;
public double temperature = 2;
public double density = 0.4;
public double Lz = 10;
public int D = 3;
public int nZdata = 10;
public int nAngleData = 10;
}
private static class DataProcessorDifficulty extends DataProcessor {
private final LJMCDimer sim;
DataFunction data;
public DataProcessorDifficulty(LJMCDimer sim) {
this.sim = sim;
}
@Override
protected IData processData(IData inputData) {
data.E(inputData);
data.TE(Math.sqrt(sim.integrator.getStepCount()));
return data;
}
@Override
protected IDataInfo processDataInfo(IDataInfo inputDataInfo) {
data = (DataFunction) inputDataInfo.makeData();
return inputDataInfo;
}
}
// checks that molecule is in box before attempting to compute energy
class MyMCMoveMolecule extends MCMoveMolecule {
public MyMCMoveMolecule(IRandom random, PotentialCompute potentialCompute, Box box) {
super(random, potentialCompute, box);
}
public double getChi(double temperature) {
int D = box.getSpace().D();
double r1z = Lz/2 + molecule.getChildList().get(0).getPosition().getX(D);
double r2z = Lz/2 + molecule.getChildList().get(1).getPosition().getX(D);
if (r1z < 0 || r1z > Lz || r2z < 0 || r2z > Lz) return 0.0;
return super.getChi(temperature);
}
}
}
|
hook up reset averages to all the pumps
|
etomica-apps/src/main/java/etomica/mappedDensity/positionOrientation/LJMCDimer.java
|
hook up reset averages to all the pumps
|
<ide><path>tomica-apps/src/main/java/etomica/mappedDensity/positionOrientation/LJMCDimer.java
<ide> simGraphic.getController().getReinitButton().setPostAction(simGraphic.getPaintAction(sim.box));
<ide> simGraphic.getController().getDataStreamPumps().add(pump);
<ide> simGraphic.getController().getDataStreamPumps().add(pumpHistogram);
<add> simGraphic.getController().getDataStreamPumps().add(pumpHistogramMA);
<add> simGraphic.getController().getDataStreamPumps().add(pumpDensityProfile);
<add> simGraphic.getController().getDataStreamPumps().add(pumpDensityProfileMA);
<add> simGraphic.getController().getDataStreamPumps().add(pumpDensityProfileF);
<ide> simGraphic.getDisplayBox(sim.box).setColorScheme(new ColorSchemeRandomByMolecule(sim.getSpeciesManager(), sim.box, sim.getRandom()));
<ide>
<ide> simGraphic.makeAndDisplayFrame(APP_NAME);
|
|
JavaScript
|
mit
|
e6630d563255f3902c15c0419368d115a8e59fc4
| 0 |
vweevers/bytespace,deanlandolt/bytespace
|
var EventEmitter = require('events').EventEmitter
var inherits = require('util').inherits
var merge = require('xtend')
var Transform = require('stream').Transform
var util = require('levelup/lib/util')
var Batch = require('./batch')
var Namespace = require('./namespace')
module.exports = Bytespace
function getCallback (opts, cb) {
return typeof opts == 'function' ? opts : cb
}
function getOptions(opts) {
return merge(util.getOptions(opts))
}
// create a bytespace within a remote levelup instance
function Bytespace(db, ns, opts) {
if (!(this instanceof Bytespace))
return new Bytespace(db, ns, opts)
if (!(ns instanceof Namespace)) {
// if db is a subspace mount as a nested subspace
if (db.namespace instanceof Namespace)
return db.sublevel(ns, opts)
// otherwise it's a root subspace
ns = new Namespace([ ns ], opts && opts.hexNamespace)
}
this.namespace = ns
opts = this.options = merge(Bytespace.options, db.options, opts)
ns.createCodec(opts)
// use provided methods manifest in options or get from db
this.methods = merge(opts.methods || db.methods)
// for sublevel api-compatibility
this.sublevel = function (ns_, opts_) {
var index = this.sublevels || (this.sublevels = {})
// memoize the sublevels we create
// TODO: memoize with bytewise-encoded hex string instead
if (index[ns_]) return index[ns_]
return index[ns_] = new Bytespace(db, ns.append(ns_), merge(opts, opts_))
}
this.clone = function () {
return new Bytespace(db, ns, opts)
}
function vOpts(initial) {
return merge({ valueEncoding: opts.valueEncoding }, initial)
}
function kvOpts(initial) {
return vOpts(kOpts(initial))
}
function addEncodings(op, db) {
if (db && db.options) {
op.keyEncoding || (op.keyEncoding = db.options.keyEncoding)
op.valueEncoding || (op.valueEncoding = db.options.valueEncoding)
}
return op
}
// method proxy implementations
if (typeof db.get === 'function') {
this.get = function (k, opts, cb) {
cb = getCallback(opts, cb)
opts = getOptions(opts)
db.get(ns.encode(k, opts), kvOpts(opts), cb)
}
}
if (typeof db.del === 'function') {
this.del = function (k, opts, cb) {
// redirect to batch if we have hooks
if (ns.hasHooks()) {
this.batch([{ type: 'del', key: k }], opts, cb)
}
else {
cb = getCallback(opts, cb)
opts = getOptions(opts)
db.del(ns.encode(k, opts), kOpts(opts), cb)
}
}
}
if (typeof db.put === 'function') {
this.put = function (k, v, opts, cb) {
// redirect to batch if we have hooks
if (ns.hasHooks()) {
this.batch([{ type: 'put', key: k, value: v }], opts, cb)
}
else {
cb = getCallback(opts, cb)
opts = getOptions(opts)
db.put(ns.encode(k, opts), v, kvOpts(opts), cb)
}
}
}
// helper to register pre and post commit hooks
function addHook(hooks, hook) {
hooks.push(hook)
return function () {
var i = hooks.indexOf(hook)
if (i >= 0)
return hooks.splice(i, 1)
}
}
if (typeof db.batch === 'function') {
this.batch = function (ops, opts, cb) {
if (!arguments.length)
return new Batch(this)
cb = getCallback(opts, cb)
opts = getOptions(opts)
// encode batch ops and apply precommit hooks
for (var i = 0, len = ops.length; i < len; i++) {
var op = ops[i]
function add(op) {
if (op === false)
return delete ops[i]
ops.push(op)
}
addEncodings(op, op.prefix)
op.prefix || (op.prefix = this)
var ns = op.prefix.namespace
if (!(ns instanceof Namespace))
return cb('Unknown prefix in batch commit')
if (ns.prehooks.length)
ns.trigger(ns.prehooks, op.prefix, [ op, add, ops ])
// encode op key, but keep a ref to initial value around for postcommit
op._initialKey = op.key
op._initialKeyEncoding = op.keyEncoding
}
var prefixes = []
ops.forEach(function (op) {
var pre = op.prefix
op.key = pre.namespace.encode(op.key, opts, op)
op.keyEncoding = ns.keyEncoding
// assign a unique id to each prefix used in batch to revive
op.prefix = null
var prefixId = prefixes.indexOf(pre)
if (prefixId >= 0) {
op._prefixId = prefixId
}
else {
op._prefixId = prefixes.length
prefixes.push(pre)
}
})
if (!ops.length)
return cb()
db.batch(ops, kvOpts(opts), function (err) {
if (err)
return cb(err)
// apply postcommit hooks for ops, setting encoded keys to initial state
ops.forEach(function (op) {
op.key = op._initialKey
op.keyEncoding = op._initialKeyEncoding
// revive prefix from index
var pre = op.prefix = prefixes[op._prefixId]
var ns = op.prefix.namespace
if (ns.posthooks.length)
ns.trigger(ns.posthooks, pre, [ op ])
})
cb()
})
}
this.pre = function (hook) {
return addHook(ns.prehooks, hook)
}
this.post = function (hook) {
return addHook(ns.posthooks, hook)
}
function kOpts(initial) {
return merge(initial, {
keyEncoding: ns.keyEncoding,
keyAsBuffer: !ns.hex
})
}
}
// transform stream to decode data keys
function decodeStream(opts) {
var stream = Transform({ objectMode: true })
stream._transform = function (data, _, cb) {
try {
if (opts.keys && opts.values) {
data.key = ns.decode(data.key, opts)
}
else if (opts.keys) {
data = ns.decode(data, opts)
}
}
catch (err) {
return cb(err)
}
cb(null, data)
}
return stream
}
function readStream(opts) {
return db.createReadStream(ns.encodeRange(opts)).pipe(decodeStream(opts))
}
// add read stream proxy methods if createReadStream is available
if (typeof db.createReadStream === 'function') {
this.createReadStream = this.readStream = function (opts) {
return readStream(merge({ keys: true, values: true }, vOpts(opts)))
}
this.createKeyStream = this.keyStream = function (opts) {
return readStream(merge(vOpts(opts), { keys: true, values: false }))
}
this.createValueStream = this.valueStream = function (opts) {
return readStream(merge(vOpts(opts), { keys: false, values: true }))
}
}
// add createLiveStream proxy if available
if (typeof db.createLiveStream === 'function') {
this.createLiveStream = this.liveStream = function (opts) {
var o = merge(vOpts(opts), ns.encodeRange(opts))
return db.createLiveStream(o).pipe(decodeStream(opts))
}
}
}
inherits(Bytespace, EventEmitter)
// used to define default options for root subspaces
Bytespace.options = {
keyEncoding: util.defaultOptions.keyEncoding,
valueEncoding: util.defaultOptions.valueEncoding
}
|
index.js
|
var EventEmitter = require('events').EventEmitter
var inherits = require('util').inherits
var merge = require('xtend')
var Transform = require('stream').Transform
var util = require('levelup/lib/util')
var Batch = require('./batch')
var Namespace = require('./namespace')
module.exports = Bytespace
function getCallback (opts, cb) {
return typeof opts == 'function' ? opts : cb
}
function getOptions(opts) {
return merge(util.getOptions(opts))
}
// create a bytespace within a remote levelup instance
function Bytespace(db, ns, opts) {
if (!(this instanceof Bytespace))
return new Bytespace(db, ns, opts)
if (!(ns instanceof Namespace)) {
// if db is a subspace mount as a nested subspace
if (db.namespace instanceof Namespace)
return db.sublevel(ns, opts)
// otherwise it's a root subspace
ns = new Namespace([ ns ], opts && opts.hexNamespace)
}
this.namespace = ns
opts = this.options = merge(Bytespace.options, db.options, opts)
ns.createCodec(opts)
// use provided methods manifest in options or get from db
this.methods = merge(opts.methods || db.methods)
// for sublevel api-compatibility
this.sublevel = function (ns_, opts_) {
var index = this.sublevels || (this.sublevels = {})
// memoize the sublevels we create
// TODO: memoize with bytewise-encoded hex string instead
if (index[ns_]) return index[ns_]
return index[ns_] = new Bytespace(db, ns.append(ns_), merge(opts, opts_))
}
this.clone = function () {
return new Bytespace(db, ns, opts)
}
function vOpts(initial) {
return merge({ valueEncoding: opts.valueEncoding }, initial)
}
function kvOpts(initial) {
return vOpts(kOpts(initial))
}
function addEncodings(op, db) {
if (db && db.options) {
op.keyEncoding || (op.keyEncoding = db.options.keyEncoding)
op.valueEncoding || (op.valueEncoding = db.options.valueEncoding)
}
return op
}
// method proxy implementations
if (typeof db.get === 'function') {
this.get = function (k, opts, cb) {
cb = getCallback(opts, cb)
opts = getOptions(opts)
db.get(ns.encode(k, opts), kvOpts(opts), cb)
}
}
if (typeof db.del === 'function') {
this.del = function (k, opts, cb) {
// redirect to batch if we have hooks
if (ns.hasHooks()) {
this.batch([{ type: 'del', key: k }], opts, cb)
}
else {
cb = getCallback(opts, cb)
opts = getOptions(opts)
db.del(ns.encode(k, opts), kOpts(opts), cb)
}
}
}
if (typeof db.put === 'function') {
this.put = function (k, v, opts, cb) {
// redirect to batch if we have hooks
if (ns.hasHooks()) {
this.batch([{ type: 'put', key: k, value: v }], opts, cb)
}
else {
cb = getCallback(opts, cb)
opts = getOptions(opts)
db.put(ns.encode(k, opts), v, kvOpts(opts), cb)
}
}
}
// helper to register pre and post commit hooks
function addHook(hooks, hook) {
hooks.push(hook)
return function () {
var i = hooks.indexOf(hook)
if (i >= 0)
return hooks.splice(i, 1)
}
}
if (typeof db.batch === 'function') {
this.batch = function (ops, opts, cb) {
if (!arguments.length)
return new Batch(this)
cb = getCallback(opts, cb)
opts = getOptions(opts)
// encode batch ops and apply precommit hooks
for (var i = 0, len = ops.length; i < len; i++) {
var op = ops[i]
function add(op) {
if (op === false)
return delete ops[i]
ops.push(op)
}
addEncodings(op, op.prefix)
op.prefix || (op.prefix = this)
var ns = op.prefix.namespace
if (!(ns instanceof Namespace))
return cb('Unknown prefix in batch commit')
if (ns.prehooks.length)
ns.trigger(ns.prehooks, op.prefix, [ op, add, ops ])
// encode op key, but keep a ref to initial value around for postcommit
op._initialKey = op.key
op._initialKeyEncoding = op.keyEncoding
}
ops.forEach(function (op) {
var pre = op.prefix
// op.key = pre.namespace.encode(pre._codec.encodeKey(op.key, opts, op))
op.key = pre.namespace.encode(op.key, opts, op)
op.keyEncoding = ns.keyEncoding
})
if (!ops.length)
return cb()
db.batch(ops, kvOpts(opts), function (err) {
if (err)
return cb(err)
// apply postcommit hooks for ops, setting encoded keys to initial state
ops.forEach(function (op) {
op.key = op._initialKey
op.keyEncoding = op._initialKeyEncoding
var ns = op.prefix.namespace
if (ns.posthooks.length)
ns.trigger(ns.posthooks, op.prefix, [ op ])
})
cb()
})
}
this.pre = function (hook) {
return addHook(ns.prehooks, hook)
}
this.post = function (hook) {
return addHook(ns.posthooks, hook)
}
function kOpts(initial) {
return merge(initial, {
keyEncoding: ns.keyEncoding,
keyAsBuffer: !ns.hex
})
}
}
// transform stream to decode data keys
function decodeStream(opts) {
var stream = Transform({ objectMode: true })
stream._transform = function (data, _, cb) {
try {
if (opts.keys && opts.values) {
data.key = ns.decode(data.key, opts)
}
else if (opts.keys) {
data = ns.decode(data, opts)
}
}
catch (err) {
return cb(err)
}
cb(null, data)
}
return stream
}
function readStream(opts) {
return db.createReadStream(ns.encodeRange(opts)).pipe(decodeStream(opts))
}
// add read stream proxy methods if createReadStream is available
if (typeof db.createReadStream === 'function') {
this.createReadStream = this.readStream = function (opts) {
return readStream(merge({ keys: true, values: true }, vOpts(opts)))
}
this.createKeyStream = this.keyStream = function (opts) {
return readStream(merge(vOpts(opts), { keys: true, values: false }))
}
this.createValueStream = this.valueStream = function (opts) {
return readStream(merge(vOpts(opts), { keys: false, values: true }))
}
}
// add createLiveStream proxy if available
if (typeof db.createLiveStream === 'function') {
this.createLiveStream = this.liveStream = function (opts) {
var o = merge(vOpts(opts), ns.encodeRange(opts))
return db.createLiveStream(o).pipe(decodeStream(opts))
}
}
}
inherits(Bytespace, EventEmitter)
// used to define default options for root subspaces
Bytespace.options = {
keyEncoding: util.defaultOptions.keyEncoding,
valueEncoding: util.defaultOptions.valueEncoding
}
|
Suppress prefix db refs in batch ops to prevent blowing up mulitlevel
|
index.js
|
Suppress prefix db refs in batch ops to prevent blowing up mulitlevel
|
<ide><path>ndex.js
<ide> op._initialKeyEncoding = op.keyEncoding
<ide> }
<ide>
<add> var prefixes = []
<ide> ops.forEach(function (op) {
<ide> var pre = op.prefix
<del> // op.key = pre.namespace.encode(pre._codec.encodeKey(op.key, opts, op))
<ide> op.key = pre.namespace.encode(op.key, opts, op)
<ide> op.keyEncoding = ns.keyEncoding
<add>
<add> // assign a unique id to each prefix used in batch to revive
<add> op.prefix = null
<add> var prefixId = prefixes.indexOf(pre)
<add> if (prefixId >= 0) {
<add> op._prefixId = prefixId
<add> }
<add> else {
<add> op._prefixId = prefixes.length
<add> prefixes.push(pre)
<add> }
<ide> })
<ide>
<ide> if (!ops.length)
<ide> ops.forEach(function (op) {
<ide> op.key = op._initialKey
<ide> op.keyEncoding = op._initialKeyEncoding
<add>
<add> // revive prefix from index
<add> var pre = op.prefix = prefixes[op._prefixId]
<ide> var ns = op.prefix.namespace
<ide> if (ns.posthooks.length)
<del> ns.trigger(ns.posthooks, op.prefix, [ op ])
<add> ns.trigger(ns.posthooks, pre, [ op ])
<ide> })
<ide>
<ide> cb()
|
|
Java
|
apache-2.0
|
8d65ce08f079769ca69752a6cee7c3dbc65118e7
| 0 |
boskoop/comet-pinball,boskoop/comet-pinball
|
package ch.m02.comet.pinball;
import javax.inject.Inject;
import org.picocontainer.Characteristics;
import org.picocontainer.MutablePicoContainer;
import org.picocontainer.PicoBuilder;
import org.picocontainer.behaviors.OptInCaching;
import org.picocontainer.gems.monitors.Slf4jComponentMonitor;
import org.picocontainer.injectors.AnnotatedFieldInjection;
import org.picocontainer.injectors.ProviderAdapter;
import org.picocontainer.parameters.ConstantParameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.m02.comet.pinball.core.ApplicationContext;
import ch.m02.comet.pinball.core.config.Configuration;
import ch.m02.comet.pinball.core.config.internal.ConfigurationImpl;
import ch.m02.comet.pinball.core.internal.ApplicationContextImpl;
import ch.m02.comet.pinball.game.ApplicationProvider;
import ch.m02.comet.pinball.game.PinballGame;
import ch.m02.comet.pinball.presentation.PinballScreenManager;
import com.badlogic.gdx.Game;
public class Pinball {
private static final Logger log = LoggerFactory.getLogger(Pinball.class);
private MainApplication application;
private MutablePicoContainer container;
public Pinball(MainApplication application) {
this.application = application;
container = new PicoBuilder()
.withMonitor(new Slf4jComponentMonitor())
.withBehaviors(new OptInCaching()) // Enable singletons
.withComponentFactory(new AnnotatedFieldInjection(Inject.class)) // use JSR-330
.withHiddenImplementations() // Hide concrete implementations when using an interface
.withJavaEE5Lifecycle() // use JSR-250 (@PostConstruct) annotations
.build();
registerSingletons();
registerPrototypes();
container.start();
}
private void registerSingletons() {
log.debug("Registering pico component singletons");
MutablePicoContainer singletonContainer = container.as(Characteristics.CACHE);
singletonContainer.addAdapter(new ProviderAdapter(new ApplicationProvider(application)));
singletonContainer.addComponent(Game.class, PinballGame.class);
singletonContainer.addComponent(Configuration.class, ConfigurationImpl.class);
singletonContainer.addComponent(ApplicationContext.class, ApplicationContextImpl.class,
new ConstantParameter(container));
singletonContainer.addComponent(PinballScreenManager.class);
}
private void registerPrototypes() {
log.debug("Registering pico component prototypes");
}
public Game getGame() {
return container.getComponent(Game.class);
}
public ApplicationContext getApplicationContext() {
return container.getComponent(ApplicationContext.class);
}
}
|
src/game/application/src/main/java/ch/m02/comet/pinball/Pinball.java
|
package ch.m02.comet.pinball;
import javax.inject.Inject;
import org.picocontainer.Characteristics;
import org.picocontainer.MutablePicoContainer;
import org.picocontainer.PicoBuilder;
import org.picocontainer.behaviors.OptInCaching;
import org.picocontainer.gems.monitors.Slf4jComponentMonitor;
import org.picocontainer.injectors.AnnotatedFieldInjection;
import org.picocontainer.injectors.ProviderAdapter;
import org.picocontainer.parameters.ConstantParameter;
import ch.m02.comet.pinball.core.ApplicationContext;
import ch.m02.comet.pinball.core.config.Configuration;
import ch.m02.comet.pinball.core.config.internal.ConfigurationImpl;
import ch.m02.comet.pinball.core.internal.ApplicationContextImpl;
import ch.m02.comet.pinball.game.ApplicationProvider;
import ch.m02.comet.pinball.game.PinballGame;
import ch.m02.comet.pinball.presentation.PinballScreenManager;
import com.badlogic.gdx.Game;
public class Pinball {
private MainApplication application;
private MutablePicoContainer container;
public Pinball(MainApplication application) {
this.application = application;
container = new PicoBuilder()
.withMonitor(new Slf4jComponentMonitor())
.withBehaviors(new OptInCaching()) // Enable singletons
.withComponentFactory(new AnnotatedFieldInjection(Inject.class)) // use JSR-330
.withHiddenImplementations() // Hide concrete implementations when using an interface
.withJavaEE5Lifecycle() // use JSR-250 (@PostConstruct) annotations
.build();
registerSingletons();
registerPrototypes();
container.start();
}
private void registerSingletons() {
MutablePicoContainer singletonContainer = container.as(Characteristics.CACHE);
singletonContainer.addAdapter(new ProviderAdapter(new ApplicationProvider(application)));
singletonContainer.addComponent(Game.class, PinballGame.class);
singletonContainer.addComponent(Configuration.class, ConfigurationImpl.class);
singletonContainer.addComponent(ApplicationContext.class, ApplicationContextImpl.class,
new ConstantParameter(container));
singletonContainer.addComponent(PinballScreenManager.class);
}
private void registerPrototypes() {
}
public Game getGame() {
return container.getComponent(Game.class);
}
public ApplicationContext getApplicationContext() {
return container.getComponent(ApplicationContext.class);
}
}
|
logging component registration
refs #44
|
src/game/application/src/main/java/ch/m02/comet/pinball/Pinball.java
|
logging component registration refs #44
|
<ide><path>rc/game/application/src/main/java/ch/m02/comet/pinball/Pinball.java
<ide> import org.picocontainer.injectors.AnnotatedFieldInjection;
<ide> import org.picocontainer.injectors.ProviderAdapter;
<ide> import org.picocontainer.parameters.ConstantParameter;
<add>import org.slf4j.Logger;
<add>import org.slf4j.LoggerFactory;
<ide>
<ide> import ch.m02.comet.pinball.core.ApplicationContext;
<ide> import ch.m02.comet.pinball.core.config.Configuration;
<ide> import com.badlogic.gdx.Game;
<ide>
<ide> public class Pinball {
<add>
<add> private static final Logger log = LoggerFactory.getLogger(Pinball.class);
<ide>
<ide> private MainApplication application;
<ide> private MutablePicoContainer container;
<ide> }
<ide>
<ide> private void registerSingletons() {
<add> log.debug("Registering pico component singletons");
<ide> MutablePicoContainer singletonContainer = container.as(Characteristics.CACHE);
<ide> singletonContainer.addAdapter(new ProviderAdapter(new ApplicationProvider(application)));
<ide> singletonContainer.addComponent(Game.class, PinballGame.class);
<ide> }
<ide>
<ide> private void registerPrototypes() {
<add> log.debug("Registering pico component prototypes");
<ide> }
<ide>
<ide> public Game getGame() {
|
|
Java
|
mit
|
ad6db9cf6f04d1a9b36835ae9465d9ac9a0ac759
| 0 |
domisum/AuxiliumLib
|
package de.domisum.lib.auxilium.util.time;
import de.domisum.lib.auxilium.util.java.annotations.API;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.time.DurationFormatUtils;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.Temporal;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class DurationUtil
{
// FORMAT
@API public static String format(Duration duration)
{
if(duration.isNegative())
return "-"+format(duration.abs());
String format = "";
if(duration.compareTo(Duration.ofHours(1)) < 0)
format = "s's'"+format;
if(duration.compareTo(Duration.ofMinutes(1)) >= 0)
format = "m'm':"+format;
if(duration.compareTo(Duration.ofHours(1)) >= 0)
format = "H'h':"+format;
String string = DurationFormatUtils.formatDuration(duration.toMillis(), format);
// done like this because "S" gives leading zeroes, don't want that
if(shouldDisplayMillis(duration))
string += ":"+(duration.toMillis()%1000)+"ms";
return string;
}
private static boolean shouldDisplayMillis(Duration duration)
{
boolean containsMillis = (duration.toMillis()%1000) != 0;
boolean isSmallEnough = duration.compareTo(Duration.ofSeconds(10)) < 0;
return containsMillis && isSmallEnough;
}
// MATH
@API public static Duration getDelta(Duration duration1, Duration duration2)
{
return duration1.minus(duration2).abs();
}
// NOW
@API public static Duration toNow(Temporal from)
{
return Duration.between(from, Instant.now());
}
}
|
src/main/java/de/domisum/lib/auxilium/util/time/DurationUtil.java
|
package de.domisum.lib.auxilium.util.time;
import de.domisum.lib.auxilium.util.java.annotations.API;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.time.DurationFormatUtils;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.Temporal;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class DurationUtil
{
// FORMAT
@API public static String format(Duration duration)
{
if(duration.isNegative())
return "-"+format(duration.abs());
String format = "s's'";
if(duration.compareTo(Duration.ofMinutes(1)) >= 0)
format = "m'm':"+format;
if(duration.compareTo(Duration.ofHours(1)) >= 0)
format = "H'h':"+format;
String string = DurationFormatUtils.formatDuration(duration.toMillis(), format);
// done like this because "S" gives leading zeroes, don't want that
if(shouldDisplayMillis(duration))
string += ":"+(duration.toMillis()%1000)+"ms";
return string;
}
private static boolean shouldDisplayMillis(Duration duration)
{
boolean containsMillis = (duration.toMillis()%1000) != 0;
boolean isSmallEnough = duration.compareTo(Duration.ofSeconds(10)) < 0;
return containsMillis && isSmallEnough;
}
// MATH
@API public static Duration getDelta(Duration duration1, Duration duration2)
{
return duration1.minus(duration2).abs();
}
// NOW
@API public static Duration toNow(Temporal from)
{
return Duration.between(from, Instant.now());
}
}
|
Only display seconds in durations less than an hour
|
src/main/java/de/domisum/lib/auxilium/util/time/DurationUtil.java
|
Only display seconds in durations less than an hour
|
<ide><path>rc/main/java/de/domisum/lib/auxilium/util/time/DurationUtil.java
<ide> return "-"+format(duration.abs());
<ide>
<ide>
<del> String format = "s's'";
<add> String format = "";
<add>
<add> if(duration.compareTo(Duration.ofHours(1)) < 0)
<add> format = "s's'"+format;
<ide>
<ide> if(duration.compareTo(Duration.ofMinutes(1)) >= 0)
<ide> format = "m'm':"+format;
|
|
JavaScript
|
mit
|
acb3eeb7b3ee1cb734e0a75e3dfdfbe7b02a305f
| 0 |
SimoNonnis/node,SimoNonnis/node
|
const express = require('express');
const router = express.Router();
const storeController = require('../controllers/storeController');
const userController = require('../controllers/userController');
const authController = require('../controllers/authController');
const { catchErrors } = require('../handlers/errorHandlers');
// Do work here
router.get('/', catchErrors(storeController.getStores));
router.get('/stores', catchErrors(storeController.getStores));
router.get('/add', storeController.addStore);
router.post('/add',
storeController.upload,
catchErrors(storeController.resize),
catchErrors(storeController.createStore)
);
router.post('/add/:id',
storeController.upload,
catchErrors(storeController.resize),
catchErrors(storeController.updateStore)
);
router.get('/stores/:id/edit', catchErrors(storeController.editStore))
router.get('/store/:slug', catchErrors(storeController.getStoreBySlug));
router.get('/tags', catchErrors(storeController.getStoreByTag));
router.get('/tags/:tag', catchErrors(storeController.getStoreByTag));
router.get('/login', userController.loginForm);
router.post('/login', authController.login);
router.get('/logout', authController.logout);
router.get('/register', userController.registerForm);
router.post('/register',
userController.validateRegister,
userController.register,
authController.login
);
module.exports = router;
|
routes/index.js
|
const express = require('express');
const router = express.Router();
const storeController = require('../controllers/storeController');
const userController = require('../controllers/userController');
const authController = require('../controllers/authController');
const { catchErrors } = require('../handlers/errorHandlers');
// Do work here
router.get('/', catchErrors(storeController.getStores));
router.get('/stores', catchErrors(storeController.getStores));
router.get('/add', storeController.addStore);
router.post('/add',
storeController.upload,
catchErrors(storeController.resize),
catchErrors(storeController.createStore)
);
router.post('/add/:id',
storeController.upload,
catchErrors(storeController.resize),
catchErrors(storeController.updateStore)
);
router.get('/stores/:id/edit', catchErrors(storeController.editStore))
router.get('/store/:slug', catchErrors(storeController.getStoreBySlug));
router.get('/tags', catchErrors(storeController.getStoreByTag));
router.get('/tags/:tag', catchErrors(storeController.getStoreByTag));
router.get('/login', userController.loginForm);
router.get('/register', userController.registerForm);
router.post('/register',
userController.validateRegister,
userController.register,
authController.login
);
router.get('/logout', authController.logout);
module.exports = router;
|
'Handle login'
|
routes/index.js
|
'Handle login'
|
<ide><path>outes/index.js
<ide> router.get('/tags/:tag', catchErrors(storeController.getStoreByTag));
<ide>
<ide> router.get('/login', userController.loginForm);
<add>router.post('/login', authController.login);
<add>router.get('/logout', authController.logout);
<add>
<ide> router.get('/register', userController.registerForm);
<ide> router.post('/register',
<ide> userController.validateRegister,
<ide> authController.login
<ide> );
<ide>
<del>router.get('/logout', authController.logout);
<del>
<ide>
<ide>
<ide>
|
|
Java
|
bsd-3-clause
|
a118fc814acfee95e2c2ecff33be79a5192f9ab0
| 0 |
rnathanday/dryad-repo,ojacobson/dryad-repo,jamie-dryad/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,mdiggory/dryad-repo,mdiggory/dryad-repo,jimallman/dryad-repo,jamie-dryad/dryad-repo,ojacobson/dryad-repo,mdiggory/dryad-repo,ojacobson/dryad-repo,rnathanday/dryad-repo,mdiggory/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,rnathanday/dryad-repo,jamie-dryad/dryad-repo,ojacobson/dryad-repo,rnathanday/dryad-repo,jamie-dryad/dryad-repo,mdiggory/dryad-repo,ojacobson/dryad-repo,jimallman/dryad-repo,ojacobson/dryad-repo,jimallman/dryad-repo,jamie-dryad/dryad-repo
|
/*
* ItemTag.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. 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 Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* 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
* 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.
*/
package org.dspace.app.webui.jsptag;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
import org.dspace.content.Collection;
import org.dspace.content.DCDate;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Utils;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.jstl.fmt.LocaleSupport;
import javax.servlet.jsp.tagext.TagSupport;
/**
* Tag for displaying an item
*
* @author Robert Tansley
* @version $Revision$
*/
public class ItemTag extends TagSupport
{
/** Item to display */
private Item item;
/** Collections this item appears in */
private Collection[] collections;
/** The style to use - "default" or "full" */
private String style;
/** Whether to show preview thumbs on the item page */
private boolean showThumbs;
public ItemTag()
{
super();
getThumbSettings();
}
public int doStartTag() throws JspException
{
try
{
if ((style != null) && style.equals("full"))
{
renderFull();
}
else
{
renderDefault();
}
}
catch (java.sql.SQLException e)
{
throw new JspException(e);
}
catch (IOException ie)
{
throw new JspException(ie);
}
return SKIP_BODY;
}
/**
* Get the item this tag should display
*
* @return the item
*/
public Item getItem()
{
return item;
}
/**
* Set the item this tag should display
*
* @param itemIn
* the item to display
*/
public void setItem(Item itemIn)
{
item = itemIn;
}
/**
* Get the collections this item is in
*
* @return the collections
*/
public Collection[] getCollections()
{
return collections;
}
/**
* Set the collections this item is in
*
* @param collectionsIn
* the collections
*/
public void setCollections(Collection[] collectionsIn)
{
collections = collectionsIn;
}
/**
* Get the style this tag should display
*
* @return the style
*/
public String getStyle()
{
return style;
}
/**
* Set the style this tag should display
*
* @param styleIn
* the Style to display
*/
public void setStyle(String styleIn)
{
style = styleIn;
}
public void release()
{
style = "default";
item = null;
collections = null;
}
/**
* Render an item in the default style
*/
private void renderDefault() throws IOException, java.sql.SQLException
{
JspWriter out = pageContext.getOut();
// Build up a list of things to display.
// To display a DC field from the item, do
// fields.add(new String[] {"Display Name", "element", "qualifier"});
// (or "qualifier" as null for unqualified)
// to display an actual value without getting it from the item, do
// fields.add(new String[] {"Display Name", "The value to display")
List fields = new LinkedList();
// Title - special case, if there is no title, use "Untitled"
DCValue[] titleDC = item.getDC("title", null, Item.ANY);
if (titleDC.length == 0)
{
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.title"),
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.title.untitled") });
}
else
{
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.title"),
"title", null });
}
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.title.other"),
"title", "alternative" });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.authors"),
"contributor", Item.ANY });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.keywords"),
"subject", null });
// Date issued
DCValue[] dateIssued = item.getDC("date", "issued", Item.ANY);
DCDate dd = null;
if (dateIssued.length > 0)
{
dd = new DCDate(dateIssued[0].value);
}
String displayDate = UIUtil.displayDate(dd, false, false);
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.issueDate"),
displayDate });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.publisher"),
"publisher", null });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.citation"),
"identifier", "citation" });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.series"),
"relation",
"ispartofseries" });
// Truncate abstract
DCValue[] abstrDC = item.getDC("description", "abstract", Item.ANY);
if (abstrDC.length > 0)
{
String abstr = abstrDC[0].value;
if (abstr.length() > 1000)
{
abstr = abstr.substring(0, 1000) + "...";
}
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.abstract"),
abstr });
}
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.description"),
"description", null });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.govdoc"),
"identifier", "govdoc" });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.uri"),
"identifier", "uri" });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.isbn"),
"identifier", "isbn" });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.issn"),
"identifier", "issn" });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.ismn"),
"identifier", "ismn" });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.otherIDs"),
"identifier", null });
HttpServletRequest request = (HttpServletRequest) pageContext
.getRequest();
out.println("<center><table class=\"itemDisplayTable\">");
Iterator fieldIterator = fields.iterator();
while (fieldIterator.hasNext())
{
String[] fieldData = (String[]) fieldIterator.next();
DCValue[] values;
if (fieldData.length == 2)
{
// Value direct from field data
DCValue v = new DCValue();
v.value = fieldData[1];
values = new DCValue[1];
values[0] = v;
}
else
{
// Grab the value from the item
values = item.getDC(fieldData[1], fieldData[2], Item.ANY);
}
// Only display the field if we have an actual value
if (values.length > 0)
{
out.print("<tr><td class=\"metadataFieldLabel\">");
out.print(fieldData[0]);
out.print(": </td><td class=\"metadataFieldValue\">");
out.print(Utils.addEntities(values[0].value));
for (int j = 1; j < values.length; j++)
{
out.print("<br>");
out.print(Utils.addEntities(values[j].value));
}
out.println("</td></tr>");
}
}
listCollections();
out.println("</table></center><br>");
listBitstreams();
out.println("<br><br>");
showLicence();
}
/**
* Render full item record
*/
private void renderFull() throws IOException, java.sql.SQLException
{
JspWriter out = pageContext.getOut();
// Get all the metadata
DCValue[] values = item.getDC(Item.ANY, Item.ANY, Item.ANY);
out.println("<P align=center>"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.full")
+"</P>");
HttpServletRequest request = (HttpServletRequest) pageContext
.getRequest();
// Three column table - DC field, value, language
out.println("<center><table class=\"itemDisplayTable\">");
out.println("<tr><th class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.dcfield")
+"</th><th class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.value")
+"</th><th class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.lang")
+"</th></tr>");
for (int i = 0; i < values.length; i++)
{
boolean hidden = false;
// Mask description.provenance
if (values[i].element.equals("description")
&& ((values[i].qualifier != null) && values[i].qualifier
.equals("provenance")))
{
hidden = true;
}
if (!hidden)
{
out.print("<tr><td class=\"metadataFieldLabel\">");
out.print(values[i].element);
if (values[i].qualifier != null)
{
out.print("." + values[i].qualifier);
}
out.print("</td><td class=\"metadataFieldValue\">");
out.print(Utils.addEntities(values[i].value));
out.print("</td><td class=\"metadataFieldValue\">");
if (values[i].language == null)
{
out.print("-");
}
else
{
out.print(values[i].language);
}
out.println("</td></tr>");
}
}
listCollections();
out.println("</table></center><br>");
listBitstreams();
out.println("<br><br>");
showLicence();
}
/**
* List links to collections if information is available
*/
private void listCollections() throws IOException
{
JspWriter out = pageContext.getOut();
HttpServletRequest request = (HttpServletRequest) pageContext
.getRequest();
if (collections != null)
{
out.print("<tr><td class=\"metadataFieldLabel\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.appears")
+ "</td><td class=\"metadataFieldValue\">");
for (int i = 0; i < collections.length; i++)
{
out.print("<A HREF=\"");
out.print(request.getContextPath());
out.print("/handle/");
out.print(collections[i].getHandle());
out.print("\">");
out.print(collections[i].getMetadata("name"));
out.print("</A><BR>");
}
out.println("</td></tr>");
}
}
/**
* List bitstreams in the item
*/
private void listBitstreams() throws IOException
{
JspWriter out = pageContext.getOut();
HttpServletRequest request = (HttpServletRequest) pageContext
.getRequest();
out.print("<table align=center class=\"miscTable\"><tr>");
out.println("<td class=evenRowEvenCol><P><strong>"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.files")
+ "</strong></P>");
Bundle[] bundles = item.getBundles("ORIGINAL");
if (bundles.length == 0)
{
out.println("<P>"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.files.no")
+ "</P>");
}
else
{
boolean html = false;
String handle = item.getHandle();
Bitstream primaryBitstream = null;
Bundle[] bunds = item.getBundles("ORIGINAL");
Bundle[] thumbs = item.getBundles("THUMBNAIL");
// if item contains multiple bitstreams, display bitstream
// description
boolean multiFile = false;
Bundle[] allBundles = item.getBundles();
for (int i = 0, filecount = 0; (i < allBundles.length)
&& !multiFile; i++)
{
filecount += allBundles[i].getBitstreams().length;
multiFile = (filecount > 1);
}
// check if primary bitstream is html
if (bunds[0] != null)
{
Bitstream[] bits = bunds[0].getBitstreams();
for (int i = 0; (i < bits.length) && !html; i++)
{
if (bits[i].getID() == bunds[0].getPrimaryBitstreamID())
{
html = bits[i].getFormat().getMIMEType().equals(
"text/html");
primaryBitstream = bits[i];
}
}
}
out.println("<table cellpadding=6><tr><th class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.file")
+ "</th>");
if (multiFile)
{
out.println("<th class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.description")
+ "</th>");
}
out.println("<th class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.filesize")
+ "</th><th class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.fileformat")
+ "</th></tr>");
// if primary bitstream is html, display a link for only that one to
// HTMLServlet
if (html)
{
// If no real Handle yet (e.g. because Item is in workflow)
// we use the 'fake' Handle db-id/1234 where 1234 is the
// database ID of the item.
if (handle == null)
{
handle = "db-id/" + item.getID();
}
out.print("<tr><td class=\"standard\">");
out.print(primaryBitstream.getName());
if (multiFile)
{
out.print("</td><td class=\"standard\">");
String desc = primaryBitstream.getDescription();
out.print((desc != null) ? desc : "");
}
out.print("</td><td class=\"standard\">");
out.print(primaryBitstream.getSize() / 1024);
out.print("Kb</td><td class=\"standard\">");
out.print(primaryBitstream.getFormatDescription());
out.print("</td><td class=\"standard\"><A TARGET=_blank HREF=\"");
out.print(request.getContextPath());
out.print("/html/");
out.print(handle + "/");
out.print(UIUtil.encodeBitstreamName(primaryBitstream.getName(),
Constants.DEFAULT_ENCODING));
out.print("\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.view")
+ "</A></td></tr>");
}
else
{
for (int i = 0; i < bundles.length; i++)
{
Bitstream[] bitstreams = bundles[i].getBitstreams();
for (int k = 0; k < bitstreams.length; k++)
{
// Skip internal types
if (!bitstreams[k].getFormat().isInternal())
{
out.print("<tr><td class=\"standard\">");
out.print(bitstreams[k].getName());
if (multiFile)
{
out.print("</td><td class=\"standard\">");
String desc = bitstreams[k].getDescription();
out.print((desc != null) ? desc : "");
}
out.print("</td><td class=\"standard\">");
out.print(bitstreams[k].getSize() / 1024);
out.print("Kb</td><td class=\"standard\">");
out.print(bitstreams[k].getFormatDescription());
out
.print("</td><td class=\"standard\" align=\"center\">");
// Work out what the bitstream link should be
// (persistent
// ID if item has Handle)
String bsLink = "<A TARGET=_blank HREF=\""
+ request.getContextPath();
if ((handle != null)
&& (bitstreams[k].getSequenceID() > 0))
{
bsLink = bsLink + "/bitstream/"
+ item.getHandle() + "/"
+ bitstreams[k].getSequenceID() + "/";
}
else
{
bsLink = bsLink + "/retrieve/"
+ bitstreams[k].getID() + "/";
}
bsLink = bsLink
+ UIUtil.encodeBitstreamName(
bitstreams[k].getName(),
Constants.DEFAULT_ENCODING) + "\">";
// is there a thumbnail bundle?
if ((thumbs.length > 0) && showThumbs)
{
String tName = bitstreams[k].getName() + ".jpg";
Bitstream tb = thumbs[0]
.getBitstreamByName(tName);
if (tb != null)
{
String myPath = request.getContextPath()
+ "/retrieve/"
+ tb.getID()
+ "/"
+ UIUtil.encodeBitstreamName(tb.getName(),
Constants.DEFAULT_ENCODING);
out.print(bsLink);
out.print("<img src=\"" + myPath + "\" ");
out.print("alt=\"" + tName + "\"></A><BR>");
}
}
out.print(bsLink
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.view")
+ "</A></td></tr>");
}
}
}
}
out.println("</table>");
}
out.println("</td></tr></table>");
}
private void getThumbSettings()
{
showThumbs = ConfigurationManager
.getBooleanProperty("webui.item.thumbnail.show");
}
/**
* Link to the item licence
*/
private void showLicence()
throws IOException
{
JspWriter out = pageContext.getOut();
HttpServletRequest request =
(HttpServletRequest) pageContext.getRequest();
Bundle[] bundles = item.getBundles("LICENSE");
out.println("<table align=\"center\" class=\"attentionTable\"><tr>");
out.println("<td class=\"attentionCell\"><P><strong>"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.itemprotected")
+ "</strong></P>");
for (int i = 0; i < bundles.length; i++)
{
Bitstream[] bitstreams = bundles[i].getBitstreams();
for (int k = 0; k < bitstreams.length ; k++)
{
out.print("<div align=\"center\" class=\"standard\">");
out.print("<strong><a target=_blank href=\"");
out.print(request.getContextPath());
out.print("/retrieve/");
out.print(bitstreams[k].getID() + "/");
out.print(UIUtil.encodeBitstreamName(bitstreams[k].getName(),
Constants.DEFAULT_ENCODING));
out.print("\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.viewlicence")
+ "</a></strong></div>");
}
}
out.println("</td></tr></table>");
}
}
|
dspace/src/org/dspace/app/webui/jsptag/ItemTag.java
|
/*
* ItemTag.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. 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 Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* 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
* 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.
*/
package org.dspace.app.webui.jsptag;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
import org.dspace.content.Collection;
import org.dspace.content.DCDate;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Utils;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.jstl.fmt.LocaleSupport;
import javax.servlet.jsp.tagext.TagSupport;
/**
* Tag for displaying an item
*
* @author Robert Tansley
* @version $Revision$
*/
public class ItemTag extends TagSupport
{
/** Item to display */
private Item item;
/** Collections this item appears in */
private Collection[] collections;
/** The style to use - "default" or "full" */
private String style;
/** Whether to show preview thumbs on the item page */
private boolean showThumbs;
public ItemTag()
{
super();
getThumbSettings();
}
public int doStartTag() throws JspException
{
try
{
if ((style != null) && style.equals("full"))
{
renderFull();
}
else
{
renderDefault();
}
}
catch (java.sql.SQLException e)
{
throw new JspException(e);
}
catch (IOException ie)
{
throw new JspException(ie);
}
return SKIP_BODY;
}
/**
* Get the item this tag should display
*
* @return the item
*/
public Item getItem()
{
return item;
}
/**
* Set the item this tag should display
*
* @param itemIn
* the item to display
*/
public void setItem(Item itemIn)
{
item = itemIn;
}
/**
* Get the collections this item is in
*
* @return the collections
*/
public Collection[] getCollections()
{
return collections;
}
/**
* Set the collections this item is in
*
* @param collectionsIn
* the collections
*/
public void setCollections(Collection[] collectionsIn)
{
collections = collectionsIn;
}
/**
* Get the style this tag should display
*
* @return the style
*/
public String getStyle()
{
return style;
}
/**
* Set the style this tag should display
*
* @param styleIn
* the Style to display
*/
public void setStyle(String styleIn)
{
style = styleIn;
}
public void release()
{
style = "default";
item = null;
collections = null;
}
/**
* Render an item in the default style
*/
private void renderDefault() throws IOException, java.sql.SQLException
{
JspWriter out = pageContext.getOut();
// Build up a list of things to display.
// To display a DC field from the item, do
// fields.add(new String[] {"Display Name", "element", "qualifier"});
// (or "qualifier" as null for unqualified)
// to display an actual value without getting it from the item, do
// fields.add(new String[] {"Display Name", "The value to display")
List fields = new LinkedList();
// Title - special case, if there is no title, use "Untitled"
DCValue[] titleDC = item.getDC("title", null, Item.ANY);
if (titleDC.length == 0)
{
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.title"),
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.title.untitled ") });
}
else
{
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.title"),
"title", null });
}
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.title.other"),
"title", "alternative" });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.authors"),
"contributor", Item.ANY });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.keywords"),
"subject", null });
// Date issued
DCValue[] dateIssued = item.getDC("date", "issued", Item.ANY);
DCDate dd = null;
if (dateIssued.length > 0)
{
dd = new DCDate(dateIssued[0].value);
}
String displayDate = UIUtil.displayDate(dd, false, false);
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.issueDate"),
displayDate });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.publisher"),
"publisher", null });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.citation"),
"identifier", "citation" });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.series"),
"relation",
"ispartofseries" });
// Truncate abstract
DCValue[] abstrDC = item.getDC("description", "abstract", Item.ANY);
if (abstrDC.length > 0)
{
String abstr = abstrDC[0].value;
if (abstr.length() > 1000)
{
abstr = abstr.substring(0, 1000) + "...";
}
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.abstract"),
abstr });
}
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.description"),
"description", null });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.govdoc"),
"identifier", "govdoc" });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.uri"),
"identifier", "uri" });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.isbn"),
"identifier", "isbn" });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.issn"),
"identifier", "issn" });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.ismn"),
"identifier", "ismn" });
fields.add(new String[] {
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.otherIDs"),
"identifier", null });
HttpServletRequest request = (HttpServletRequest) pageContext
.getRequest();
out.println("<center><table class=\"itemDisplayTable\">");
Iterator fieldIterator = fields.iterator();
while (fieldIterator.hasNext())
{
String[] fieldData = (String[]) fieldIterator.next();
DCValue[] values;
if (fieldData.length == 2)
{
// Value direct from field data
DCValue v = new DCValue();
v.value = fieldData[1];
values = new DCValue[1];
values[0] = v;
}
else
{
// Grab the value from the item
values = item.getDC(fieldData[1], fieldData[2], Item.ANY);
}
// Only display the field if we have an actual value
if (values.length > 0)
{
out.print("<tr><td class=\"metadataFieldLabel\">");
out.print(fieldData[0]);
out.print(": </td><td class=\"metadataFieldValue\">");
out.print(Utils.addEntities(values[0].value));
for (int j = 1; j < values.length; j++)
{
out.print("<br>");
out.print(Utils.addEntities(values[j].value));
}
out.println("</td></tr>");
}
}
listCollections();
out.println("</table></center><br>");
listBitstreams();
out.println("<br><br>");
showLicence();
}
/**
* Render full item record
*/
private void renderFull() throws IOException, java.sql.SQLException
{
JspWriter out = pageContext.getOut();
// Get all the metadata
DCValue[] values = item.getDC(Item.ANY, Item.ANY, Item.ANY);
out.println("<P align=center>"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.full")
+"</P>");
HttpServletRequest request = (HttpServletRequest) pageContext
.getRequest();
// Three column table - DC field, value, language
out.println("<center><table class=\"itemDisplayTable\">");
out.println("<tr><th class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.dcfield")
+"</th><th class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.value")
+"</th><th class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.lang")
+"</th></tr>");
for (int i = 0; i < values.length; i++)
{
boolean hidden = false;
// Mask description.provenance
if (values[i].element.equals("description")
&& ((values[i].qualifier != null) && values[i].qualifier
.equals("provenance")))
{
hidden = true;
}
if (!hidden)
{
out.print("<tr><td class=\"metadataFieldLabel\">");
out.print(values[i].element);
if (values[i].qualifier != null)
{
out.print("." + values[i].qualifier);
}
out.print("</td><td class=\"metadataFieldValue\">");
out.print(Utils.addEntities(values[i].value));
out.print("</td><td class=\"metadataFieldValue\">");
if (values[i].language == null)
{
out.print("-");
}
else
{
out.print(values[i].language);
}
out.println("</td></tr>");
}
}
listCollections();
out.println("</table></center><br>");
listBitstreams();
out.println("<br><br>");
showLicence();
}
/**
* List links to collections if information is available
*/
private void listCollections() throws IOException
{
JspWriter out = pageContext.getOut();
HttpServletRequest request = (HttpServletRequest) pageContext
.getRequest();
if (collections != null)
{
out.print("<tr><td class=\"metadataFieldLabel\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.appears")
+ "</td><td class=\"metadataFieldValue\">");
for (int i = 0; i < collections.length; i++)
{
out.print("<A HREF=\"");
out.print(request.getContextPath());
out.print("/handle/");
out.print(collections[i].getHandle());
out.print("\">");
out.print(collections[i].getMetadata("name"));
out.print("</A><BR>");
}
out.println("</td></tr>");
}
}
/**
* List bitstreams in the item
*/
private void listBitstreams() throws IOException
{
JspWriter out = pageContext.getOut();
HttpServletRequest request = (HttpServletRequest) pageContext
.getRequest();
out.print("<table align=center class=\"miscTable\"><tr>");
out.println("<td class=evenRowEvenCol><P><strong>"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.files")
+ "</strong></P>");
Bundle[] bundles = item.getBundles("ORIGINAL");
if (bundles.length == 0)
{
out.println("<P>"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.files.no")
+ "</P>");
}
else
{
boolean html = false;
String handle = item.getHandle();
Bitstream primaryBitstream = null;
Bundle[] bunds = item.getBundles("ORIGINAL");
Bundle[] thumbs = item.getBundles("THUMBNAIL");
// if item contains multiple bitstreams, display bitstream
// description
boolean multiFile = false;
Bundle[] allBundles = item.getBundles();
for (int i = 0, filecount = 0; (i < allBundles.length)
&& !multiFile; i++)
{
filecount += allBundles[i].getBitstreams().length;
multiFile = (filecount > 1);
}
// check if primary bitstream is html
if (bunds[0] != null)
{
Bitstream[] bits = bunds[0].getBitstreams();
for (int i = 0; (i < bits.length) && !html; i++)
{
if (bits[i].getID() == bunds[0].getPrimaryBitstreamID())
{
html = bits[i].getFormat().getMIMEType().equals(
"text/html");
primaryBitstream = bits[i];
}
}
}
out.println("<table cellpadding=6><tr><th class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.file")
+ "</th>");
if (multiFile)
{
out.println("<th class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.description")
+ "</th>");
}
out.println("<th class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.filesize")
+ "</th><th class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.fileformat")
+ "</th></tr>");
// if primary bitstream is html, display a link for only that one to
// HTMLServlet
if (html)
{
// If no real Handle yet (e.g. because Item is in workflow)
// we use the 'fake' Handle db-id/1234 where 1234 is the
// database ID of the item.
if (handle == null)
{
handle = "db-id/" + item.getID();
}
out.print("<tr><td class=\"standard\">");
out.print(primaryBitstream.getName());
if (multiFile)
{
out.print("</td><td class=\"standard\">");
String desc = primaryBitstream.getDescription();
out.print((desc != null) ? desc : "");
}
out.print("</td><td class=\"standard\">");
out.print(primaryBitstream.getSize() / 1024);
out.print("Kb</td><td class=\"standard\">");
out.print(primaryBitstream.getFormatDescription());
out.print("</td><td class=\"standard\"><A TARGET=_blank HREF=\"");
out.print(request.getContextPath());
out.print("/html/");
out.print(handle + "/");
out.print(UIUtil.encodeBitstreamName(primaryBitstream.getName(),
Constants.DEFAULT_ENCODING));
out.print("\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.view")
+ "</A></td></tr>");
}
else
{
for (int i = 0; i < bundles.length; i++)
{
Bitstream[] bitstreams = bundles[i].getBitstreams();
for (int k = 0; k < bitstreams.length; k++)
{
// Skip internal types
if (!bitstreams[k].getFormat().isInternal())
{
out.print("<tr><td class=\"standard\">");
out.print(bitstreams[k].getName());
if (multiFile)
{
out.print("</td><td class=\"standard\">");
String desc = bitstreams[k].getDescription();
out.print((desc != null) ? desc : "");
}
out.print("</td><td class=\"standard\">");
out.print(bitstreams[k].getSize() / 1024);
out.print("Kb</td><td class=\"standard\">");
out.print(bitstreams[k].getFormatDescription());
out
.print("</td><td class=\"standard\" align=\"center\">");
// Work out what the bitstream link should be
// (persistent
// ID if item has Handle)
String bsLink = "<A TARGET=_blank HREF=\""
+ request.getContextPath();
if ((handle != null)
&& (bitstreams[k].getSequenceID() > 0))
{
bsLink = bsLink + "/bitstream/"
+ item.getHandle() + "/"
+ bitstreams[k].getSequenceID() + "/";
}
else
{
bsLink = bsLink + "/retrieve/"
+ bitstreams[k].getID() + "/";
}
bsLink = bsLink
+ UIUtil.encodeBitstreamName(
bitstreams[k].getName(),
Constants.DEFAULT_ENCODING) + "\">";
// is there a thumbnail bundle?
if ((thumbs.length > 0) && showThumbs)
{
String tName = bitstreams[k].getName() + ".jpg";
Bitstream tb = thumbs[0]
.getBitstreamByName(tName);
if (tb != null)
{
String myPath = request.getContextPath()
+ "/retrieve/"
+ tb.getID()
+ "/"
+ UIUtil.encodeBitstreamName(tb.getName(),
Constants.DEFAULT_ENCODING);
out.print(bsLink);
out.print("<img src=\"" + myPath + "\" ");
out.print("alt=\"" + tName + "\"></A><BR>");
}
}
out.print(bsLink
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.view")
+ "</A></td></tr>");
}
}
}
}
out.println("</table>");
}
out.println("</td></tr></table>");
}
private void getThumbSettings()
{
showThumbs = ConfigurationManager
.getBooleanProperty("webui.item.thumbnail.show");
}
/**
* Link to the item licence
*/
private void showLicence()
throws IOException
{
JspWriter out = pageContext.getOut();
HttpServletRequest request =
(HttpServletRequest) pageContext.getRequest();
Bundle[] bundles = item.getBundles("LICENSE");
out.println("<table align=\"center\" class=\"attentionTable\"><tr>");
out.println("<td class=\"attentionCell\"><P><strong>"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.itemprotected")
+ "</strong></P>");
for (int i = 0; i < bundles.length; i++)
{
Bitstream[] bitstreams = bundles[i].getBitstreams();
for (int k = 0; k < bitstreams.length ; k++)
{
out.print("<div align=\"center\" class=\"standard\">");
out.print("<strong><a target=_blank href=\"");
out.print(request.getContextPath());
out.print("/retrieve/");
out.print(bitstreams[k].getID() + "/");
out.print(UIUtil.encodeBitstreamName(bitstreams[k].getName(),
Constants.DEFAULT_ENCODING));
out.print("\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.viewlicence")
+ "</a></strong></div>");
}
}
out.println("</td></tr></table>");
}
}
|
Fixed SF Bug #1244743 - Bad lookup key for special case of DC Title in ItemTag.java
git-svn-id: 39c64a9546defcc59b5f71fe8fe20b2d01c24c1f@1248 9c30dcfa-912a-0410-8fc2-9e0234be79fd
|
dspace/src/org/dspace/app/webui/jsptag/ItemTag.java
|
Fixed SF Bug #1244743 - Bad lookup key for special case of DC Title in ItemTag.java
|
<ide><path>space/src/org/dspace/app/webui/jsptag/ItemTag.java
<ide> LocaleSupport.getLocalizedMessage(pageContext,
<ide> "org.dspace.app.webui.jsptag.ItemTag.title"),
<ide> LocaleSupport.getLocalizedMessage(pageContext,
<del> "org.dspace.app.webui.jsptag.ItemTag.title.untitled ") });
<add> "org.dspace.app.webui.jsptag.ItemTag.title.untitled") });
<ide> }
<ide> else
<ide> {
|
|
Java
|
bsd-3-clause
|
7e17de9eb52c070c04ac4f030b335ff97fa64063
| 0 |
jtb-javacc/JTB
|
/**
* Copyright (c) 2004,2005 UCLA Compilers Group.
* 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 UCLA 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.
**/
/*
* All files in the distribution of JTB, The Java Tree Builder are
* Copyright 1997, 1998, 1999 by the Purdue Research Foundation of Purdue
* University. All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that this entire copyright notice is duplicated in all
* such copies, and that any documentation, announcements, and
* other materials related to such distribution and use acknowledge
* that the software was developed at Purdue University, West Lafayette,
* Indiana by Kevin Tao and Jens Palsberg. No charge may be made
* for copies, derivations, or distributions of this material
* without the express written consent of the copyright holder.
* Neither the name of the University nor the name of the author
* may be used to endorse or promote products derived from this
* material without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ANY PARTICULAR PURPOSE.
*/
package EDU.purdue.jtb.visitor;
import static EDU.purdue.jtb.misc.Globals.DEBUG_CLASS_COMMENTS;
import static EDU.purdue.jtb.misc.Globals.INDENT_AMT;
import static EDU.purdue.jtb.misc.Globals.getFixedName;
import static EDU.purdue.jtb.misc.Globals.keepSpecialTokens;
import static EDU.purdue.jtb.misc.Globals.noOverwrite;
import static EDU.purdue.jtb.visitor.GlobalDataBuilder.BNF_IND;
import static EDU.purdue.jtb.visitor.GlobalDataBuilder.JC_IND;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.regex.Pattern;
import EDU.purdue.jtb.misc.FileExistsException;
import EDU.purdue.jtb.misc.JavaBranchPrinter;
import EDU.purdue.jtb.misc.Messages;
import EDU.purdue.jtb.misc.Spacing;
import EDU.purdue.jtb.misc.UnicodeConverter;
import EDU.purdue.jtb.syntaxtree.*;
/**
* The {@link JavaCCPrinter} visitor reprints (with indentation) the JavaCC grammar JavaCC specific
* productions.<br>
* (The JavaCC grammar Java productions are handled by the {@link JavaPrinter} visitor.)
* <p>
* Implementation notes :
* <ul>
* <li>sb.append(spc.spc), sb.append(" ") and sb.append(LS) are done at the highest (calling) level
* (except for Modifiers which prints its last space as it can be empty)
* <li>sb.append(spc.spc) is normally done after sb.append(LS)
* <li>sb.append(" ") is not merged with printing punctuation / operators / keywords (to prepare
* evolutions for other formatting preferences)
* </ul>
* TODO : extract / refactor methods for custom formatting<br>
*
* @author Marc Mazas
* @version 1.4.0 : 05-08/2009 : MMa : adapted to JavaCC v4.2 grammar and JDK 1.5<br>
* 1.4.0 : 11/2009 : MMa : output commented JTB options
* @version 1.4.7 : 12/2011 : MMa : added comments in the JavaCodeProduction visit method<br>
* 1.4.7 : 07/2012 : MMa : followed changes in jtbgram.jtb (AccessModifier(),
* IndentifierAsString())<br>
* 1.4.7 : 09/2012 : MMa : added non node creation
* @version 1.4.8 : 10/2012 : MMa : updated for JavaCodeProduction class generation if requested
* 1.4.8 : 12/2014 : MMa : fixed commenting specials in JTB options ;<br>
* improved specials printing
*/
public class JavaCCPrinter extends DepthFirstVoidVisitor {
/** The {@link GlobalDataBuilder} visitor */
final GlobalDataBuilder gdbv;
/** The buffer to print into */
protected StringBuilder sb;
/** The indentation object */
protected Spacing spc;
/** True to not take the specials, false otherwise */
protected boolean withoutSpecials = false;
/** True to comment the specials, false otherwise */
boolean commentSpecials = false;
/** The {@link JavaBranchPrinter} printer to print a java node and its subtree */
protected JavaBranchPrinter jbp;
/** The generated variable assignment string to be inserted */
protected String gvaStr;
/**
* The BNF nesting level, starts at 0 (in {@link #visit(BNFProduction)}), incremented for each new
* level, except in an {@link ExpansionChoices} with no choice
*/
protected int bnfLvl = 0;
/** The OS line separator */
public static final String LS = System.getProperty("line.separator");
/** The OS line separator length */
public static final int LSLEN = LS.length();
/*
* Constructors
*/
/** The pattern to break the specials into lines */
public static final Pattern PATT_LS = Pattern.compile(LS);
/**
* Constructor with a global data builder visitor reference, a given buffer and indentation.
*
* @param aGdbv - the global data builder visitor
* @param aSb - the buffer to print into (will be allocated if null)
* @param aSPC - the Spacing indentation object (will be allocated and set to a default if null)
*/
public JavaCCPrinter(final GlobalDataBuilder aGdbv, final StringBuilder aSb, final Spacing aSPC) {
sb = aSb;
if (sb == null) {
sb = new StringBuilder(2048);
}
spc = aSPC;
if (spc == null) {
spc = new Spacing(INDENT_AMT);
}
jbp = new JavaBranchPrinter(spc);
gdbv = aGdbv;
}
/**
* Constructor which will allocate a default buffer and indentation.
*
* @param aGdbv - the global data builder visitor
*/
public JavaCCPrinter(final GlobalDataBuilder aGdbv) {
this(aGdbv, null, null);
}
/**
* Constructor with a global data builder visitor reference, a given buffer and which will
* allocate a default indentation.
*
* @param aGdbv - the global data builder visitor
* @param aSb - the buffer to print into (will be allocated if null)
*/
public JavaCCPrinter(final GlobalDataBuilder aGdbv, final StringBuilder aSb) {
this(aGdbv, aSb, null);
}
/**
* Constructor with a global data builder visitor reference, a given indentation which will
* allocate a default buffer.
*
* @param aGdbv - the global data builder visitor
* @param aSPC - the Spacing indentation object
*/
public JavaCCPrinter(final GlobalDataBuilder aGdbv, final Spacing aSPC) {
this(aGdbv, null, aSPC);
}
/**
* Saves the current buffer to an output file.
*
* @param outFile - the output file
* @throws FileExistsException - if the file exists and the noOverwrite flag is set
* @throws IOException if IO problem
*/
public void saveToFile(final String outFile) throws FileExistsException, IOException {
try {
final File file = new File(outFile);
if (noOverwrite && file.exists()) {
throw new FileExistsException(outFile);
} else {
final PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file),
sb.length()));
out.print(sb);
out.close();
}
}
catch (final IOException e) {
Messages.hardErr(e);
throw e;
}
}
/*
* Base classes visit methods
*/
/**
* Prints into the current buffer a NodeToken image and its specials before if global flag set.
*
* @param n - the node to visit
*/
@Override
public void visit(final NodeToken n) {
// sb.append(keepSpecialTokens ? n.withSpecials(spc.spc) : n.tokenImage);
final String str = keepSpecialTokens && !withoutSpecials ? n.withSpecials(spc.spc)
: n.tokenImage;
sb.append(str);
gvaStr = null;
}
/*
* Convenience methods
*/
/**
* Generates a java node and its subtree with a JavaPrinter.
*
* @param n - the node to process
* @return a buffer with the generated source
*/
protected StringBuilder genJavaBranch(final INode n) {
return jbp.genJavaBranch(n);
}
/**
* Generates a java node and its subtree with a JavaPrinter.
*
* @param n - the node to process
* @param noDebugComments - true to suppress debug comments, false otherwise
* @return a buffer with the generated source
*/
protected StringBuilder genJavaBranch(final INode n, final boolean noDebugComments) {
return jbp.genJavaBranch(n, noDebugComments);
}
/**
* Prints into the current buffer a node class comment and a new line.
*
* @param n - the node for the node class comment
*/
void oneNewLine(final INode n) {
sb.append(nodeClassComment(n)).append(LS);
}
/**
* Prints into the current buffer a node class comment, an extra given comment, and a new line.
*
* @param n - the node for the node class comment
* @param str - the extra comment
*/
void oneNewLine(final INode n, final String str) {
sb.append(nodeClassComment(n, str)).append(LS);
}
/**
* Prints into the current buffer a node class comment, extra given comments, and a new line.
*
* @param n - the node for the node class comment
* @param str - the extra comments
*/
void oneNewLine(final INode n, final Object... str) {
sb.append(nodeClassComment(n, str)).append(LS);
}
/**
* Prints twice into the current buffer a node class comment and a new line.
*
* @param n - the node for the node class comment
*/
void twoNewLines(final INode n) {
oneNewLine(n);
oneNewLine(n);
}
/**
* Prints three times into the current buffer a node class comment and a new line.
*
* @param n - the node for the node class comment
*/
void threeNewLines(final INode n) {
oneNewLine(n);
oneNewLine(n);
oneNewLine(n);
}
/**
* @param nt - the node token whose specials will be commented and appended to the buffer
*/
void appendSpecials(final NodeToken nt) {
String spe;
spe = nt.getSpecials("");
if (!commentSpecials) {
sb.append(spe);
} else {
// for each line in the specials, comment it if not starting with //
final String lines[] = PATT_LS.split(spe);
for (final String line : lines) {
final String stripped = line.trim();
if (stripped.startsWith("//")) {
sb.append(line);
} else {
sb.append(spc.spc).append("// ").append(line);
}
sb.append(LS);
}
sb.setLength(sb.length() - LSLEN);
}
}
/**
* Returns a node class comment (a //jcp followed by the node class short name if global flag set,
* nothing otherwise).
*
* @param n - the node for the node class comment
* @return the node class comment
*/
private static String nodeClassComment(final INode n) {
if (DEBUG_CLASS_COMMENTS) {
final String s = n.toString();
final int b = s.lastIndexOf('.') + 1;
final int e = s.indexOf('@');
if (b == -1 || e == -1) {
return " //jcp " + s;
} else {
return " //jcp " + s.substring(b, e);
}
} else {
return "";
}
}
/**
* Returns a node class comment with an extra comment (a //jcp followed by the node class short
* name plus the extra comment if global flag set, nothing otherwise).
*
* @param n - the node for the node class comment
* @param str - the extra comment
* @return the node class comment
*/
private static String nodeClassComment(final INode n, final String str) {
if (DEBUG_CLASS_COMMENTS) {
return nodeClassComment(n).concat(" ").concat(str);
} else {
return "";
}
}
/**
* Returns a node class comment with extra comments (a //jcp followed by the node class short name
* plus the extra comment if global flag set, nothing otherwise).
*
* @param n - the node for the node class comment
* @param obj - the extra comments
* @return the node class comment
*/
private static String nodeClassComment(final INode n, final Object... obj) {
if (DEBUG_CLASS_COMMENTS) {
int len = 0;
for (final Object o : obj) {
len += o.toString().length();
}
final StringBuilder buf = new StringBuilder(len);
for (final Object o : obj) {
buf.append(o.toString());
}
return nodeClassComment(n, buf.toString());
} else {
return "";
}
}
/*
* User grammar generated and overridden visit methods below
*/
/**
* Visits a {@link JavaCCInput} node, whose children are the following :
* <p>
* f0 -> JavaCCOptions()<br>
* f1 -> "PARSER_BEGIN"<br>
* f2 -> "("<br>
* f3 -> IdentifierAsString()<br>
* f4 -> ")"<br>
* f5 -> CompilationUnit()<br>
* f6 -> "PARSER_END"<br>
* f7 -> "("<br>
* f8 -> IdentifierAsString()<br>
* f9 -> ")"<br>
* f10 -> ( Production() )+<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final JavaCCInput n) {
// we do not use sb.append(spc.spc) as indent level should be 0 at this point
// f0 -> JavaCCOptions()
n.f0.accept(this);
oneNewLine(n);
oneNewLine(n);
oneNewLine(n);
// f1 -> "PARSER_BEGIN"
n.f1.accept(this);
// f2 -> "("
n.f2.accept(this);
// f3 -> IdentifierAsString()
n.f3.accept(this);
// f4 -> ")"
n.f4.accept(this);
oneNewLine(n);
// f5 -> CompilationUnit()
sb.append(genJavaBranch(n.f5));
// f6 -> "PARSER_END"
n.f6.accept(this);
// f7 -> "("
n.f7.accept(this);
// f8 -> IdentifierAsString()
n.f8.accept(this);
// f9 -> ")"
n.f9.accept(this);
oneNewLine(n);
oneNewLine(n);
oneNewLine(n);
// f10 -> ( Production() )+
for (final Iterator<INode> e = n.f10.elements(); e.hasNext();) {
e.next().accept(this);
if (e.hasNext()) {
oneNewLine(n);
oneNewLine(n);
}
}
oneNewLine(n);
}
/**
* Visits a {@link JavaCCOptions} node, whose children are the following :
* <p>
* f0 -> [ #0 "options" #1 "{"<br>
* .. .. . #2 ( OptionBinding() )*<br>
* .. .. . #3 "}" ]<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final JavaCCOptions n) {
if (n.f0.present()) {
final NodeSequence seq = (NodeSequence) n.f0.node;
// #0 "options"
seq.elementAt(0).accept(this);
oneNewLine(n);
// #1 "{"
seq.elementAt(1).accept(this);
withoutSpecials = true;
// #2 ( OptionBinding() )*
final NodeListOptional nlo = (NodeListOptional) seq.elementAt(2);
if (nlo.present()) {
spc.updateSpc(+1);
oneNewLine(n);
// sb.append(spc.spc);
for (final Iterator<INode> e = nlo.elements(); e.hasNext();) {
// OptionBinding()
commentSpecials = false;
e.next().accept(this);
if (e.hasNext()) {
oneNewLine(n);
sb.append(spc.spc);
}
}
spc.updateSpc(-1);
oneNewLine(n);
sb.append(spc.spc);
}
// #3 "}"
seq.elementAt(3).accept(this);
withoutSpecials = false;
}
}
/**
* Visits a {@link OptionBinding} node, whose children are the following :
* <p>
* f0 -> ( %0 < IDENTIFIER ><br>
* .. .. | %1 "LOOKAHEAD"<br>
* .. .. | %2 "IGNORE_CASE"<br>
* .. .. | %3 "static" )<br>
* f1 -> "="<br>
* f2 -> ( %0 IntegerLiteral()<br>
* .. .. | %1 BooleanLiteral()<br>
* .. .. | %2 StringLiteral() )<br>
* f3 -> ";"<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final OptionBinding n) {
// f0 -> ( %0 < IDENTIFIER > | %1 "LOOKAHEAD" | %2 "IGNORE_CASE" | %3 "static" )
if (n.f0.which == 0) {
// f0 -> %0 < IDENTIFIER
final NodeToken nt = (NodeToken) n.f0.choice;
if (nt.tokenImage.startsWith("JTB_")) {
// comment JTB options : need to comment not only one line but all the lines
if (keepSpecialTokens) {
appendSpecials(nt);
}
sb.append(spc.spc).append("// ").append(nt.tokenImage);
commentSpecials = true;
} else {
// not a JTB option
if (keepSpecialTokens) {
appendSpecials(nt);
}
n.f0.choice.accept(this);
}
} else {
// f0 -> %1 "LOOKAHEAD" | %2 "IGNORE_CASE" | %3 "static"
if (keepSpecialTokens) {
final NodeToken nt = (NodeToken) n.f0.choice;
appendSpecials(nt);
}
n.f0.choice.accept(this);
}
sb.append(" ");
// f1 -> "="
if (keepSpecialTokens) {
final NodeToken nt = n.f1;
appendSpecials(nt);
}
n.f1.accept(this);
sb.append(" ");
// f2 -> ( %0 IntegerLiteral() | %1 BooleanLiteral() | %2 StringLiteral() )
if (keepSpecialTokens) {
NodeToken nt = null;
final INode nd = n.f2.choice;
if (nd instanceof StringLiteral) {
nt = ((StringLiteral) nd).f0;
} else if (nd instanceof IntegerLiteral) {
nt = ((IntegerLiteral) nd).f0;
} else if (nd instanceof BooleanLiteral) {
nt = (NodeToken) ((BooleanLiteral) nd).f0.choice;
}
appendSpecials(nt);
}
n.f2.accept(this);
// f3 -> ";"
if (keepSpecialTokens) {
final NodeToken nt = n.f3;
appendSpecials(nt);
}
n.f3.accept(this);
}
/**
* Visits a {@link Production} node, whose children are the following :
* <p>
* f0 -> . %0 JavaCodeProduction()<br>
* .. .. | %1 RegularExprProduction()<br>
* .. .. | %2 TokenManagerDecls()<br>
* .. .. | %3 BNFProduction()<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final Production n) {
// no difference with super class
n.f0.accept(this);
}
/**
* Visits a {@link JavaCodeProduction} node, whose children are the following :
* <p>
* f0 -> "JAVACODE"<br>
* f1 -> AccessModifier()<br>
* f2 -> ResultType()<br>
* f3 -> IdentifierAsString()<br>
* f4 -> FormalParameters()<br>
* f5 -> [ #0 "throws" #1 Name()<br>
* .. .. . #2 ( $0 "," $1 Name() )* ]<br>
* f6 -> [ "%" ]<br>
* f7 -> Block()<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final JavaCodeProduction n) {
// f0 -> "JAVACODE"
n.f0.accept(this);
oneNewLine(n);
sb.append(spc.spc);
// f1 -> AccessModifier()
n.f1.accept(this);
// f2 -> ResultType()
sb.append(genJavaBranch(n.f2));
sb.append(" ");
// f3 -> IdentifierAsString()
n.f3.accept(this);
// f4 -> FormalParameters()
sb.append(genJavaBranch(n.f4));
// f5 -> [ #0 "throws" #1 Name() #2 ( $0 "," $1 Name() )* ]
if (n.f5.present()) {
final NodeSequence seq = (NodeSequence) n.f5.node;
sb.append(" ");
// #0 "throws"
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 Name()
sb.append(genJavaBranch(seq.elementAt(1)));
// #2 ( $0 "," $1 Name() )*
final NodeListOptional opt = (NodeListOptional) seq.elementAt(2);
if (opt.present()) {
for (final Iterator<INode> e = opt.elements(); e.hasNext();) {
final NodeSequence seq1 = (NodeSequence) e.next();
// $0 ","
sb.append(genJavaBranch(seq1.elementAt(0)));
sb.append(" ");
// $1 Name()
sb.append(genJavaBranch(seq1.elementAt(1)));
}
}
}
oneNewLine(n);
sb.append(spc.spc);
// f6 -> [ "%" ]
// print it in a block comment
if (n.f6.present()) {
sb.append(" /*%*/ ");
}
// f7 -> Block()
sb.append(genJavaBranch(n.f7));
}
/**
* Visits a {@link BNFProduction} node, whose children are the following :
* <p>
* f0 -> AccessModifier()<br>
* f1 -> ResultType()<br>
* f2 -> IdentifierAsString()<br>
* f3 -> FormalParameters()<br>
* f4 -> [ #0 "throws" #1 Name()<br>
* .. .. . #2 ( $0 "," $1 Name() )* ]<br>
* f5 -> [ "!" ]<br>
* f6 -> ":"<br>
* f7 -> Block()<br>
* f8 -> "{"<br>
* f9 -> ExpansionChoices()<br>
* f10 -> "}"<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final BNFProduction n) {
// note : it looks we never fall here
// throw new AssertionError("in JavaCCPrinter visiting BNFProduction");
bnfLvl = 0;
// f0 -> AccessModifier()
n.f0.accept(this);
// f1 -> ResultType()
sb.append(genJavaBranch(n.f1));
sb.append(" ");
// f2 -> IdentifierAsString()
n.f2.accept(this);
// f3 -> FormalParameters()
sb.append(genJavaBranch(n.f3));
// f4 -> [ #0 "throws" #1 Name() #2 ( $0 "," $1 Name() )* ]
if (n.f4.present()) {
final NodeSequence seq = (NodeSequence) n.f4.node;
sb.append(" ");
// #0 "throws"
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 Name()
sb.append(genJavaBranch(seq.elementAt(1)));
// #2 ( $0 "," $1 Name() )* ]
final NodeListOptional opt = (NodeListOptional) seq.elementAt(2);
if (opt.present()) {
for (final Iterator<INode> e = opt.elements(); e.hasNext();) {
final NodeSequence seq1 = (NodeSequence) e.next();
// $0 ","
seq1.elementAt(0).accept(this);
sb.append(" ");
// $1 Name()
sb.append(genJavaBranch(seq1.elementAt(1)));
}
}
}
// f5 -> [ "!" ]
// print it in a block comment
if (n.f5.present()) {
sb.append(" /*!*/ ");
}
// f6 -> ":"
n.f6.accept(this);
oneNewLine(n);
sb.append(spc.spc);
// f7 -> Block()
sb.append(genJavaBranch(n.f7));
oneNewLine(n);
sb.append(spc.spc);
// f8 -> "{"
n.f8.accept(this);
oneNewLine(n);
spc.updateSpc(+1);
sb.append(spc.spc);
// f9 -> ExpansionChoices()
n.f9.accept(this);
oneNewLine(n);
spc.updateSpc(-1);
sb.append(spc.spc);
// f10 -> "}"
n.f10.accept(this);
oneNewLine(n);
}
/**
* Visits a {@link AccessModifier} node, whose children are the following :
* <p>
* f0 -> ( %0 "public"<br>
* .. .. | %1 "protected"<br>
* .. .. | %2 "private"<br>
* .. .. | %3 "final" )*<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final AccessModifier n) {
if (n.f0.present()) {
for (final Iterator<INode> e = n.f0.elements(); e.hasNext();) {
((NodeChoice) e.next()).accept(this);
sb.append(" ");
}
}
}
/**
* Visits a {@link RegularExprProduction} node, whose children are the following :
* <p>
* f0 -> [ %0 #0 "<"<br>
* .. .. . .. #1 "*"<br>
* .. .. . .. #2 ">"<br>
* .. .. | %1 #0 "<"<br>
* .. .. . .. #1 < IDENTIFIER ><br>
* .. .. . .. #2 ( $0 ","<br>
* .. .. . .. .. . $1 < IDENTIFIER > )*<br>
* .. .. . .. #3 ">" ]<br>
* f1 -> RegExprKind()<br>
* f2 -> [ #0 "["<br>
* .. .. . #1 "IGNORE_CASE"<br>
* .. .. . #2 "]" ]<br>
* f3 -> ":"<br>
* f4 -> "{"<br>
* f5 -> RegExprSpec()<br>
* f6 -> ( #0 "|"<br>
* .. .. . #1 RegExprSpec() )*<br>
* f7 -> "}"<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final RegularExprProduction n) {
// f0 -> [ %0 #0 "<" #1 "*" #2 ">" | %1 #0 "<" #1 < IDENTIFIER > #2 ( $0 "," $1 < IDENTIFIER > )* #3 ">" ]
if (n.f0.present()) {
n.f0.node.accept(this);
oneNewLine(n);
}
// f1 -> RegExprKind()
n.f1.accept(this);
// f2 -> [ #0 "[" #1 "IGNORE_CASE" #2 "]" ]
if (n.f2.present()) {
sb.append(" ");
n.f2.node.accept(this);
}
sb.append(" ");
// f3 -> ":"
n.f3.accept(this);
oneNewLine(n);
// f4 -> "{"
n.f4.accept(this);
spc.updateSpc(+1);
oneNewLine(n);
sb.append(spc.spc);
// f5 -> RegExprSpec()
n.f5.accept(this);
// f6 -> ( #0 "|" #1 RegExprSpec() )*
if (n.f6.present()) {
for (final Iterator<INode> e = n.f6.elements(); e.hasNext();) {
final NodeSequence seq = (NodeSequence) e.next();
oneNewLine(n);
// #0 "|"
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 RegExprSpec()
seq.elementAt(1).accept(this);
}
}
spc.updateSpc(-1);
oneNewLine(n);
sb.append(spc.spc);
// f7 -> "}"
n.f7.accept(this);
}
/**
* Visits a {@link TokenManagerDecls} node, whose children are the following :
* <p>
* f0 -> "TOKEN_MGR_DECLS"<br>
* f1 -> ":"<br>
* f2 -> ClassOrInterfaceBody()<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final TokenManagerDecls n) {
// f0 -> "TOKEN_MGR_DECLS"
n.f0.accept(this);
sb.append(" ");
// f1 -> ":"
n.f1.accept(this);
sb.append(" ");
// f2 -> ClassOrInterfaceBody()
sb.append(genJavaBranch(n.f2));
}
/**
* Visits a {@link RegExprKind} node, whose children are the following :
* <p>
* f0 -> . %0 "TOKEN"<br>
* .. .. | %1 "SPECIAL_TOKEN"<br>
* .. .. | %2 "SKIP"<br>
* .. .. | %3 "MORE"<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final RegExprKind n) {
// no difference with superclass
n.f0.accept(this);
}
/**
* Visits a {@link RegExprSpec} node, whose children are the following :
* <p>
* f0 -> RegularExpression()<br>
* f1 -> [ "!" ]<br>
* f2 -> [ Block() ]<br>
* f3 -> [ #0 ":" #1 < IDENTIFIER > ]<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final RegExprSpec n) {
// f0 -> RegularExpression()
n.f0.accept(this);
// f1 -> [ "!" ]
// print it in a block comment
if (n.f1.present()) {
sb.append(" /*!*/");
}
// f2 -> [ Block() ]
if (n.f2.present()) {
oneNewLine(n);
spc.updateSpc(+1);
sb.append(spc.spc);
sb.append(genJavaBranch(n.f2.node));
spc.updateSpc(-1);
}
// f3 -> [ #0 ":" #1 < IDENTIFIER > ]
if (n.f3.present()) {
final NodeSequence seq = (NodeSequence) n.f3.node;
sb.append(" ");
// #0 ":"
sb.append(seq.elementAt(0));
sb.append(" ");
// #1 < IDENTIFIER >
sb.append(seq.elementAt(1));
}
}
/**
* Visits a {@link ExpansionChoices} node, whose children are the following :
* <p>
* f0 -> Expansion()<br>
* f1 -> ( #0 "|" #1 Expansion() )*<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final ExpansionChoices n) {
if (!n.f1.present()) {
// f0 -> Expansion()
n.f0.accept(this);
} else {
// f0 -> Expansion()
++bnfLvl;
n.f0.accept(this);
--bnfLvl;
// f1 -> ( #0 "|" #1 Expansion() )*
for (final Iterator<INode> e = n.f1.elements(); e.hasNext();) {
final NodeSequence seq = (NodeSequence) e.next();
if (bnfLvl != 0) {
sb.append(" ");
} else {
oneNewLine(n);
sb.append(spc.spc);
}
// #0 "|"
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 Expansion()
++bnfLvl;
seq.elementAt(1).accept(this);
--bnfLvl;
}
}
}
/**
* Visits a {@link Expansion} node, whose children are the following :
* <p>
* f0 -> ( #0 "LOOKAHEAD" #1 "(" #2 LocalLookahead() #3 ")" )?<br>
* f1 -> ( ExpansionUnit() )+<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final Expansion n) {
// f0 -> ( #0 "LOOKAHEAD" #1 "(" #2 LocalLookahead() #3 ")" )?
if (n.f0.present()) {
final NodeSequence seq = (NodeSequence) n.f0.node;
// #0 "LOOKAHEAD"
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 "("
seq.elementAt(1).accept(this);
sb.append(" ");
// #2 LocalLookahead()
seq.elementAt(2).accept(this);
sb.append(" ");
// #3 ")"
seq.elementAt(3).accept(this);
}
// f1 -> ( ExpansionUnit() )+
for (final Iterator<INode> e = n.f1.elements(); e.hasNext();) {
// ExpansionUnit()
e.next().accept(this);
if (e.hasNext()) {
if (bnfLvl == 0) {
oneNewLine(n);
sb.append(spc.spc);
} else {
sb.append(" ");
}
}
}
}
/**
* Visits a {@link LocalLookahead} node, whose children are the following :
* <p>
* f0 -> [ IntegerLiteral() ]<br>
* f1 -> [ "," ]<br>
* f2 -> [ ExpansionChoices() ]<br>
* f3 -> [ "," ]<br>
* f4 -> [ #0 "{" #1 Expression() #2 "}" ]<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final LocalLookahead n) {
// f0 -> [ IntegerLiteral() ]
if (n.f0.present()) {
n.f0.accept(this);
}
// f1 -> [ "," ]
if (n.f1.present()) {
n.f1.accept(this);
sb.append(" ");
}
// f2 -> [ ExpansionChoices() ]
if (n.f2.present()) {
++bnfLvl;
n.f2.node.accept(this);
--bnfLvl;
}
// f3 -> [ "," ]
if (n.f3.present()) {
n.f3.accept(this);
sb.append(" ");
}
// f4 -> [ #0 "{" #1 Expression() #2 "}" ]
if (n.f4.present()) {
final NodeSequence seq = (NodeSequence) n.f4.node;
// #0 "{"
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 Expression()
sb.append(genJavaBranch(seq.elementAt(1)));
sb.append(" ");
// #2 "}"
seq.elementAt(2).accept(this);
}
}
/**
* Visits a {@link ExpansionUnit} node, whose children are the following :
* <p>
* f0 -> . %0 #0 "LOOKAHEAD" #1 "(" #2 LocalLookahead() #3 ")"<br>
* .. .. | %1 Block()<br>
* .. .. | %2 #0 "[" #1 ExpansionChoices() #2 "]"<br>
* .. .. | %3 ExpansionUnitTCF()<br>
* .. .. | %4 #0 [ $0 PrimaryExpression() $1 "=" ]<br>
* .. .. . .. #1 ( &0 $0 IdentifierAsString() $1 Arguments()<br>
* .. .. . .. .. . .. $2 [ "!" ]<br>
* .. .. . .. .. | &1 $0 RegularExpression()<br>
* .. .. . .. .. . .. $1 [ ?0 "." ?1 <IDENTIFIER> ]<br>
* .. .. . .. .. . .. $2 [ "!" ] )<br>
* .. .. | %5 #0 "(" #1 ExpansionChoices() #2 ")"<br>
* .. .. . .. #3 ( &0 "+"<br>
* .. .. . .. .. | &1 "*"<br>
* .. .. . .. .. | &2 "?" )?<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final ExpansionUnit n) {
NodeSequence seq;
NodeOptional opt;
NodeChoice ch;
switch (n.f0.which) {
case 0:
// %0 #0 "LOOKAHEAD" #1 "(" #2 LocalLookahead() #3 ")"
// #0 "LOOKAHEAD"
seq = (NodeSequence) n.f0.choice;
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 "("
seq.elementAt(1).accept(this);
sb.append(" ");
// #2 LocalLookahead()
seq.elementAt(2).accept(this);
sb.append(" ");
// #3 ")"
seq.elementAt(3).accept(this);
break;
case 1:
// %1 Block()
sb.append(genJavaBranch(n.f0.choice));
break;
case 2:
// %2 #0 "[" #1 ExpansionChoices() #2 "]"
seq = (NodeSequence) n.f0.choice;
seq.elementAt(0).accept(this);
sb.append(" ");
++bnfLvl;
seq.elementAt(1).accept(this);
--bnfLvl;
sb.append(" ");
seq.elementAt(2).accept(this);
break;
case 3:
// %3 ExpansionUnitTCF()
n.f0.choice.accept(this);
break;
case 4:
// %4 #0 [ $0 PrimaryExpression() $1 "=" ]
// .. #1 ( &0 $0 IdentifierAsString() $1 Arguments()
// .. .. . .. $2 [ "!" ]
// .. .. | &1 $0 RegularExpression()
// .. .. . .. $1 [ ?0 "." ?1 < IDENTIFIER > ] )
// .. .. . .. $2 [ "!" ] )
seq = (NodeSequence) n.f0.choice;
// #0 [ $0 PrimaryExpression() $1 "=" ]
opt = (NodeOptional) seq.elementAt(0);
if (opt.present()) {
// $0 PrimaryExpression()
((NodeSequence) opt.node).elementAt(0).accept(this);
sb.append(" ");
// $1 "="
((NodeSequence) opt.node).elementAt(1).accept(this);
sb.append(" ");
}
// #1 ( &0 $0 IdentifierAsString() $1 Arguments()
// .. .. . $2 [ "!" ]
// .. | &1 $0 RegularExpression()
// .. . .. $1 [ ?0 "." ?1 < IDENTIFIER > ]
// .. . .. $2 [ "!" ] )
ch = (NodeChoice) seq.elementAt(1);
final NodeSequence seq1 = (NodeSequence) ch.choice;
if (ch.which == 0) {
// $0 IdentifierAsString()
// must be prefixed / suffixed if to be created
boolean creLocNode = true;
final String ias = ((IdentifierAsString) seq1.elementAt(0)).f0.tokenImage;
final String prod = gdbv.getProdHT().get(ias);
if (prod != null) {
final String indProd = prod.substring(0, 1);
if (BNF_IND.equals(indProd)) {
if (gdbv.getNsnHT().containsKey(ias)) {
creLocNode = false;
}
} else if (JC_IND.equals(indProd)) {
if (!gdbv.getNsnHT().containsKey(ias)) {
creLocNode = false;
}
}
}
if (((NodeOptional) seq1.elementAt(2)).present()) {
creLocNode = false;
}
sb.append(creLocNode ? getFixedName(ias) : ias);
//) $1 Arguments()
sb.append(genJavaBranch(seq1.elementAt(1)));
// $2 [ "!" ]
// print it in a block comment
if (((NodeOptional) seq1.elementAt(2)).present()) {
sb.append(" /*!*/ ");
}
} else {
// $0 RegularExpression()
seq1.elementAt(0).accept(this);
// $1 [ ?0 "." ?1 < IDENTIFIER > ]
final NodeOptional opt1 = (NodeOptional) seq1.elementAt(1);
if (opt1.present()) {
((NodeToken) ((NodeSequence) opt1.node).elementAt(0)).accept(this);
((NodeToken) ((NodeSequence) opt1.node).elementAt(1)).accept(this);
}
// $2 [ "!" ]
// print it in a block comment
if (((NodeOptional) seq1.elementAt(2)).present()) {
sb.append(" /*!*/ ");
}
}
break;
case 5:
// %5 #0 "(" #1 ExpansionChoices() #2 ")"
// .. #3 ( &0 "+" | &1 "*" | &2 "?" )?
seq = (NodeSequence) n.f0.choice;
// #0 "("
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 ExpansionChoices()
++bnfLvl;
seq.elementAt(1).accept(this);
--bnfLvl;
sb.append(" ");
// #2 ")"
seq.elementAt(2).accept(this);
// #3 ( &0 "+" | &1 "*" | &2 "?" )?
opt = (NodeOptional) seq.elementAt(3);
if (opt.present()) {
opt.node.accept(this);
}
break;
default:
final String msg = "Invalid n.f0.which = " + String.valueOf(n.f0.which);
Messages.hardErr(msg);
throw new InternalError(msg);
}
}
/**
* Visits a {@link ExpansionUnitTCF} node, whose children are the following :
* <p>
* f0 -> "try"<br>
* f1 -> "{"<br>
* f2 -> ExpansionChoices()<br>
* f3 -> "}"<br>
* f4 -> ( #0 "catch" #1 "(" #2 Name() #3 < IDENTIFIER > #4 ")" #5 Block() )*<br>
* f5 -> [ #0 "finally" #1 Block() ]<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final ExpansionUnitTCF n) {
// f0 -> "try"
n.f0.accept(this);
sb.append(" ");
//f1 -> "{"
n.f1.accept(this);
spc.updateSpc(+1);
oneNewLine(n);
sb.append(spc.spc);
// f2 -> ExpansionChoices()
n.f2.accept(this);
sb.append(" ");
spc.updateSpc(-1);
// f3 -> "}"
n.f3.accept(this);
oneNewLine(n);
sb.append(spc.spc);
// f4 -> ( #0 "catch" #1 "(" #2 Name() #3 < IDENTIFIER > #4 ")" #5 Block() )*
if (n.f4.present()) {
for (int i = 0; i < n.f4.size(); i++) {
final NodeSequence seq = (NodeSequence) n.f4.elementAt(i);
// #0 "catch"
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 "("
seq.elementAt(1).accept(this);
// #2 Name()
sb.append(genJavaBranch(seq.elementAt(2)));
sb.append(" ");
// #3 < IDENTIFIER >
sb.append(((NodeToken) seq.elementAt(3)).tokenImage);
// #4 ")"
seq.elementAt(3).accept(this);
// #5 Block()
sb.append(genJavaBranch(seq.elementAt(4)));
oneNewLine(n);
}
}
// f5 -> [ #0 "finally" #1 Block() ]
if (n.f5.present()) {
// #0 "finally"
((NodeSequence) n.f5.node).elementAt(0).accept(this);
sb.append(" ");
// #1 Block()
sb.append(genJavaBranch(((NodeSequence) n.f5.node).elementAt(1)));
oneNewLine(n);
}
}
/**
* Visits a {@link RegularExpression} node, whose children are the following :
* <p>
* f0 -> . %0 StringLiteral()<br>
* .. .. | %1 #0 "<"<br>
* .. .. . .. #1 [ $0 [ "#" ]<br>
* .. .. . .. .. . $1 IdentifierAsString() $2 ":" ]<br>
* .. .. . .. #2 ComplexRegularExpressionChoices() #3 ">"<br>
* .. .. | %2 #0 "<" #1 IdentifierAsString() #2 ">"<br>
* .. .. | %3 #0 "<" #1 "EOF" #2 ">"<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final RegularExpression n) {
if (n.f0.which == 0) {
// %0 StringLiteral()
n.f0.choice.accept(this);
} else if (n.f0.which == 1) {
// %1 #0 "<" #1 [ $0 [ "#" ] $1 IdentifierAsString() $2 ":" ] #2 ComplexRegularExpressionChoices() #3 ">"
final NodeSequence seq = (NodeSequence) n.f0.choice;
// #0 "<"
seq.elementAt(0).accept(this);
sb.append(" ");
final NodeOptional opt = (NodeOptional) seq.elementAt(1);
// #1 [ $0 [ "#" ] $1 IdentifierAsString() $2 ":" ]
if (opt.present()) {
final NodeSequence seq1 = (NodeSequence) opt.node;
if (((NodeOptional) seq1.elementAt(0)).present()) {
// $0 [ "#" ]
seq1.elementAt(0).accept(this);
}
// $1 IdentifierAsString()
seq1.elementAt(1).accept(this);
sb.append(" ");
// $2 ":"
seq1.elementAt(2).accept(this);
sb.append(" ");
}
// #2 ComplexRegularExpressionChoices(c)
seq.elementAt(2).accept(this);
sb.append(" ");
// #3 ">"
seq.elementAt(3).accept(this);
} else {
// %2 #0 "<" #1 IdentifierAsString() #2 ">" OR %3 #0 "<" #1 "EOF" #2 ">"
// #0 "<"
((NodeSequence) n.f0.choice).elementAt(0).accept(this);
sb.append(" ");
// #1 IdentifierAsString() OR #1 "EOF"
((NodeSequence) n.f0.choice).elementAt(1).accept(this);
sb.append(" ");
// #2 ">"
((NodeSequence) n.f0.choice).elementAt(2).accept(this);
}
}
/**
* Visits a {@link ComplexRegularExpressionChoices} node, whose children are the following :
* <p>
* f0 -> ComplexRegularExpression()<br>
* f1 -> ( #0 "|" #1 ComplexRegularExpression() )*<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final ComplexRegularExpressionChoices n) {
// f0 -> ComplexRegularExpression()
n.f0.accept(this);
// f1 -> ( #0 "|" #1 ComplexRegularExpression() )*
if (n.f1.present()) {
for (final Iterator<INode> e = n.f1.elements(); e.hasNext();) {
final NodeSequence seq = (NodeSequence) e.next();
// #0 "|"
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 ComplexRegularExpression()
seq.elementAt(1).accept(this);
}
}
}
/**
* Visits a {@link ComplexRegularExpression} node, whose children are the following :
* <p>
* f0 -> ( ComplexRegularExpressionUnit() )+<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final ComplexRegularExpression n) {
for (final Iterator<INode> e = n.f0.elements(); e.hasNext();) {
// ComplexRegularExpressionUnit()
e.next().accept(this);
if (e.hasNext()) {
sb.append(" ");
}
}
}
/**
* Visits a {@link ComplexRegularExpressionUnit} node, whose children are the following :
* <p>
* f0 -> . %0 StringLiteral()<br>
* .. .. | %1 #0 "<" #1 IdentifierAsString() #2 ">"<br>
* .. .. | %2 CharacterList()<br>
* .. .. | %3 #0 "(" #1 ComplexRegularExpressionChoices() #2 ")"<br>
* .. .. . .. #3 ( &0 "+"<br>
* .. .. . .. .. | &1 "*"<br>
* .. .. . .. .. | &2 "?"<br>
* .. .. . .. .. | &3 $0 "{" $1 IntegerLiteral()<br>
* .. .. . .. .. . .. $2 [ ?0 ","<br>
* .. .. . .. .. . .. .. . ?1 [ IntegerLiteral() ] ]<br>
* .. .. . .. .. . .. $3 "}" )?<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final ComplexRegularExpressionUnit n) {
if (n.f0.which == 0 || n.f0.which == 2) {
// %0 StringLiteral() OR %2 CharacterList(c)
n.f0.choice.accept(this);
} else if (n.f0.which == 1) {
// %1 #0 "<" #1 IdentifierAsString() #2 ">"
// #0 "<"
((NodeSequence) n.f0.choice).elementAt(0).accept(this);
// #1 IdentifierAsString()
((NodeSequence) n.f0.choice).elementAt(1).accept(this);
// #2 ">"
((NodeSequence) n.f0.choice).elementAt(2).accept(this);
} else {
// %3 #0 "(" #1 ComplexRegularExpressionChoices() #2 ")" #3 ( &0 "+" | &1 "*" | &2 "?" | &3 $0 "{" $1 IntegerLiteral() $2 [ ?0 "," ?1 [ IntegerLiteral() ] ] $3 "}" )?
final NodeSequence seq = (NodeSequence) n.f0.choice;
// #0 "("
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 ComplexRegularExpressionChoices()
seq.elementAt(1).accept(this);
sb.append(" ");
// #2 ")"
seq.elementAt(2).accept(this);
// #3 ( &0 "+" | &1 "*" | &2 "?" | &3 $0 "{" $1 IntegerLiteral() $2 [ ?0 "," ?1 [ IntegerLiteral() ] ] $3 "}" )?
final NodeOptional opt = (NodeOptional) seq.elementAt(3);
if (opt.present()) {
final NodeChoice ch = (NodeChoice) opt.node;
if (ch.which <= 2) {
// &0 "+" | &1 "*" | &2 "?"
ch.choice.accept(this);
} else {
// &3 $0 "{" $1 IntegerLiteral() $2 [ ?0 "," ?1 [ IntegerLiteral() ] ] $3 "}"
final NodeSequence seq1 = (NodeSequence) ch.choice;
// $0 "{"
seq1.elementAt(0).accept(this);
// $1 IntegerLiteral()
seq1.elementAt(1).accept(this);
// $2 [ ?0 "," ?1 [ IntegerLiteral() ] ]
final NodeOptional opt1 = (NodeOptional) seq1.elementAt(2);
if (opt1.present()) {
// ?0 ","
((NodeSequence) opt1.node).elementAt(0).accept(this);
sb.append(" ");
// ?1 IntegerLiteral()
((NodeSequence) opt1.node).elementAt(1).accept(this);
}
// $3 "}"
seq1.elementAt(3).accept(this);
}
}
}
}
/**
* Visits a {@link CharacterList} node, whose children are the following :
* <p>
* f0 -> [ "~" ]<br>
* f1 -> "["<br>
* f2 -> [ #0 CharacterDescriptor()<br>
* .. .. . #1 ( $0 "," $1 CharacterDescriptor() )* ]<br>
* f3 -> "]"<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final CharacterList n) {
// f0 -> [ "~" ]
if (n.f0.present()) {
n.f0.accept(this);
}
// f1 -> "["
n.f1.accept(this);
// f2 -> [ #0 CharacterDescriptor() #1 ( $0 "," $1 CharacterDescriptor() )* ]
if (n.f2.present()) {
final NodeSequence seq = (NodeSequence) n.f2.node;
// #0 CharacterDescriptor()
seq.elementAt(0).accept(this);
// #1 ( $0 "," $1 CharacterDescriptor() )* ]
final NodeListOptional nlo = (NodeListOptional) seq.elementAt(1);
for (final Iterator<INode> e = nlo.elements(); e.hasNext();) {
final NodeSequence seq1 = (NodeSequence) e.next();
// $0 ","
seq1.elementAt(0).accept(this);
sb.append(" ");
// $1 CharacterDescriptor()
seq1.elementAt(1).accept(this);
}
}
// f3 -> "]"
n.f3.accept(this);
}
/**
* Visits a {@link CharacterDescriptor} node, whose children are the following :
* <p>
* f0 -> StringLiteral()<br>
* f1 -> [ #0 "-" #1 StringLiteral() ]<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final CharacterDescriptor n) {
// f0 -> StringLiteral()
n.f0.accept(this);
// f1 -> [ #0 "-" #1 StringLiteral() ]
if (n.f1.present()) {
final NodeSequence seq = (NodeSequence) n.f1.node;
// #0 "-"
seq.elementAt(0).accept(this);
// #1 StringLiteral()
seq.elementAt(1).accept(this);
}
}
/**
* Visits a {@link IdentifierAsString} node, whose children are the following :
* <p>
* f0 -> < IDENTIFIER ><br>
*
* @param n - the node to visit
*/
@Override
public void visit(final IdentifierAsString n) {
final String str = keepSpecialTokens && !withoutSpecials ? n.f0.withSpecials(spc.spc)
: n.f0.tokenImage;
sb.append(UnicodeConverter.addUnicodeEscapes(str));
}
/**
* Visits a {@link IntegerLiteral} node, whose children are the following :
* <p>
* f0 -> < INTEGER_LITERAL ><br>
*
* @param n - the node to visit
*/
@Override
public void visit(final IntegerLiteral n) {
final String str = keepSpecialTokens && !withoutSpecials ? n.f0.withSpecials(spc.spc)
: n.f0.tokenImage;
sb.append(UnicodeConverter.addUnicodeEscapes(str));
}
/**
* Visits a {@link StringLiteral} node, whose children are the following :
* <p>
* f0 -> < STRING_LITERAL ><br>
*
* @param n - the node to visit
*/
@Override
public void visit(final StringLiteral n) {
final String str = keepSpecialTokens && !withoutSpecials ? n.f0.withSpecials(spc.spc)
: n.f0.tokenImage;
sb.append(UnicodeConverter.addUnicodeEscapes(str));
gvaStr = null;
}
}
|
src/EDU/purdue/jtb/visitor/JavaCCPrinter.java
|
/**
* Copyright (c) 2004,2005 UCLA Compilers Group.
* 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 UCLA 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.
**/
/*
* All files in the distribution of JTB, The Java Tree Builder are
* Copyright 1997, 1998, 1999 by the Purdue Research Foundation of Purdue
* University. All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that this entire copyright notice is duplicated in all
* such copies, and that any documentation, announcements, and
* other materials related to such distribution and use acknowledge
* that the software was developed at Purdue University, West Lafayette,
* Indiana by Kevin Tao and Jens Palsberg. No charge may be made
* for copies, derivations, or distributions of this material
* without the express written consent of the copyright holder.
* Neither the name of the University nor the name of the author
* may be used to endorse or promote products derived from this
* material without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ANY PARTICULAR PURPOSE.
*/
package EDU.purdue.jtb.visitor;
import static EDU.purdue.jtb.misc.Globals.DEBUG_CLASS_COMMENTS;
import static EDU.purdue.jtb.misc.Globals.INDENT_AMT;
import static EDU.purdue.jtb.misc.Globals.getFixedName;
import static EDU.purdue.jtb.misc.Globals.keepSpecialTokens;
import static EDU.purdue.jtb.misc.Globals.noOverwrite;
import static EDU.purdue.jtb.visitor.GlobalDataBuilder.BNF_IND;
import static EDU.purdue.jtb.visitor.GlobalDataBuilder.JC_IND;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.regex.Pattern;
import EDU.purdue.jtb.misc.FileExistsException;
import EDU.purdue.jtb.misc.JavaBranchPrinter;
import EDU.purdue.jtb.misc.Messages;
import EDU.purdue.jtb.misc.Spacing;
import EDU.purdue.jtb.misc.UnicodeConverter;
import EDU.purdue.jtb.syntaxtree.*;
/**
* The {@link JavaCCPrinter} visitor reprints (with indentation) the JavaCC grammar JavaCC specific
* productions.<br>
* (The JavaCC grammar Java productions are handled by the {@link JavaPrinter} visitor.)
* <p>
* Implementation notes :
* <ul>
* <li>sb.append(spc.spc), sb.append(" ") and sb.append(LS) are done at the highest (calling) level
* (except for Modifiers which prints its last space as it can be empty)
* <li>sb.append(spc.spc) is normally done after sb.append(LS)
* <li>sb.append(" ") is not merged with printing punctuation / operators / keywords (to prepare
* evolutions for other formatting preferences)
* </ul>
* TODO : extract / refactor methods for custom formatting<br>
*
* @author Marc Mazas
* @version 1.4.0 : 05-08/2009 : MMa : adapted to JavaCC v4.2 grammar and JDK 1.5<br>
* 1.4.0 : 11/2009 : MMa : output commented JTB options
* @version 1.4.7 : 12/2011 : MMa : added comments in the JavaCodeProduction visit method<br>
* 1.4.7 : 07/2012 : MMa : followed changes in jtbgram.jtb (AccessModifier(),
* IndentifierAsString())<br>
* 1.4.7 : 09/2012 : MMa : added non node creation
* @version 1.4.8 : 10/2012 : MMa : updated for JavaCodeProduction class generation if requested
* 1.4.8 : 12/2014 : MMa : fixed commenting specials in JTB options ;<br>
* improved specials printing
*/
public class JavaCCPrinter extends DepthFirstVoidVisitor {
/** The {@link GlobalDataBuilder} visitor */
final GlobalDataBuilder gdbv;
/** The buffer to print into */
protected StringBuilder sb;
/** The indentation object */
protected Spacing spc;
/** True to not take the specials, false otherwise */
protected boolean withoutSpecials = false;
/** True to comment the specials, false otherwise */
boolean commentSpecials = false;
/** The {@link JavaBranchPrinter} printer to print a java node and its subtree */
protected JavaBranchPrinter jbp;
/** The generated variable assignment string to be inserted */
protected String gvaStr;
/**
* The BNF nesting level, starts at 0 (in {@link #visit(BNFProduction)}), incremented for each new
* level, except in an {@link ExpansionChoices} with no choice
*/
protected int bnfLvl = 0;
/** The OS line separator */
public static final String LS = System.getProperty("line.separator");
/** The OS line separator length */
public static final int LSLEN = LS.length();
/*
* Constructors
*/
/** The pattern to break the specials into lines */
public static final Pattern PATT_LS = Pattern.compile(LS);
/**
* Constructor with a global data builder visitor reference, a given buffer and indentation.
*
* @param aGdbv - the global data builder visitor
* @param aSb - the buffer to print into (will be allocated if null)
* @param aSPC - the Spacing indentation object (will be allocated and set to a default if null)
*/
public JavaCCPrinter(final GlobalDataBuilder aGdbv, final StringBuilder aSb, final Spacing aSPC) {
sb = aSb;
if (sb == null) {
sb = new StringBuilder(2048);
}
spc = aSPC;
if (spc == null) {
spc = new Spacing(INDENT_AMT);
}
jbp = new JavaBranchPrinter(spc);
gdbv = aGdbv;
}
/**
* Constructor which will allocate a default buffer and indentation.
*
* @param aGdbv - the global data builder visitor
*/
public JavaCCPrinter(final GlobalDataBuilder aGdbv) {
this(aGdbv, null, null);
}
/**
* Constructor with a global data builder visitor reference, a given buffer and which will
* allocate a default indentation.
*
* @param aGdbv - the global data builder visitor
* @param aSb - the buffer to print into (will be allocated if null)
*/
public JavaCCPrinter(final GlobalDataBuilder aGdbv, final StringBuilder aSb) {
this(aGdbv, aSb, null);
}
/**
* Constructor with a global data builder visitor reference, a given indentation which will
* allocate a default buffer.
*
* @param aGdbv - the global data builder visitor
* @param aSPC - the Spacing indentation object
*/
public JavaCCPrinter(final GlobalDataBuilder aGdbv, final Spacing aSPC) {
this(aGdbv, null, aSPC);
}
/**
* Saves the current buffer to an output file.
*
* @param outFile - the output file
* @throws FileExistsException - if the file exists and the noOverwrite flag is set
* @throws IOException if IO problem
*/
public void saveToFile(final String outFile) throws FileExistsException, IOException {
try {
final File file = new File(outFile);
if (noOverwrite && file.exists()) {
throw new FileExistsException(outFile);
} else {
final PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file),
sb.length()));
out.print(sb);
out.close();
}
}
catch (final IOException e) {
Messages.hardErr(e);
throw e;
}
}
/*
* Base classes visit methods
*/
/**
* Prints into the current buffer a NodeToken image and its specials before if global flag set.
*
* @param n - the node to visit
*/
@Override
public void visit(final NodeToken n) {
// sb.append(keepSpecialTokens ? n.withSpecials(spc.spc) : n.tokenImage);
final String str = keepSpecialTokens && !withoutSpecials ? n.withSpecials(spc.spc, gvaStr)
: n.tokenImage;
sb.append(str);
gvaStr = null;
}
/*
* Convenience methods
*/
/**
* Generates a java node and its subtree with a JavaPrinter.
*
* @param n - the node to process
* @return a buffer with the generated source
*/
protected StringBuilder genJavaBranch(final INode n) {
return jbp.genJavaBranch(n);
}
/**
* Generates a java node and its subtree with a JavaPrinter.
*
* @param n - the node to process
* @param noDebugComments - true to suppress debug comments, false otherwise
* @return a buffer with the generated source
*/
protected StringBuilder genJavaBranch(final INode n, final boolean noDebugComments) {
return jbp.genJavaBranch(n, noDebugComments);
}
/**
* Prints into the current buffer a node class comment and a new line.
*
* @param n - the node for the node class comment
*/
void oneNewLine(final INode n) {
sb.append(nodeClassComment(n)).append(LS);
}
/**
* Prints into the current buffer a node class comment, an extra given comment, and a new line.
*
* @param n - the node for the node class comment
* @param str - the extra comment
*/
void oneNewLine(final INode n, final String str) {
sb.append(nodeClassComment(n, str)).append(LS);
}
/**
* Prints into the current buffer a node class comment, extra given comments, and a new line.
*
* @param n - the node for the node class comment
* @param str - the extra comments
*/
void oneNewLine(final INode n, final Object... str) {
sb.append(nodeClassComment(n, str)).append(LS);
}
/**
* Prints twice into the current buffer a node class comment and a new line.
*
* @param n - the node for the node class comment
*/
void twoNewLines(final INode n) {
oneNewLine(n);
oneNewLine(n);
}
/**
* Prints three times into the current buffer a node class comment and a new line.
*
* @param n - the node for the node class comment
*/
void threeNewLines(final INode n) {
oneNewLine(n);
oneNewLine(n);
oneNewLine(n);
}
/**
* @param nt - the node token whose specials will be commented and appended to the buffer
*/
void appendSpecials(final NodeToken nt) {
String spe;
spe = nt.getSpecials("");
if (!commentSpecials) {
sb.append(spe);
} else {
// for each line in the specials, comment it if not starting with //
final String lines[] = PATT_LS.split(spe);
for (final String line : lines) {
final String stripped = line.trim();
if (stripped.startsWith("//")) {
sb.append(line);
} else {
sb.append(spc.spc).append("// ").append(line);
}
sb.append(LS);
}
sb.setLength(sb.length() - LSLEN);
}
}
/**
* Returns a node class comment (a //jcp followed by the node class short name if global flag set,
* nothing otherwise).
*
* @param n - the node for the node class comment
* @return the node class comment
*/
private static String nodeClassComment(final INode n) {
if (DEBUG_CLASS_COMMENTS) {
final String s = n.toString();
final int b = s.lastIndexOf('.') + 1;
final int e = s.indexOf('@');
if (b == -1 || e == -1) {
return " //jcp " + s;
} else {
return " //jcp " + s.substring(b, e);
}
} else {
return "";
}
}
/**
* Returns a node class comment with an extra comment (a //jcp followed by the node class short
* name plus the extra comment if global flag set, nothing otherwise).
*
* @param n - the node for the node class comment
* @param str - the extra comment
* @return the node class comment
*/
private static String nodeClassComment(final INode n, final String str) {
if (DEBUG_CLASS_COMMENTS) {
return nodeClassComment(n).concat(" ").concat(str);
} else {
return "";
}
}
/**
* Returns a node class comment with extra comments (a //jcp followed by the node class short name
* plus the extra comment if global flag set, nothing otherwise).
*
* @param n - the node for the node class comment
* @param obj - the extra comments
* @return the node class comment
*/
private static String nodeClassComment(final INode n, final Object... obj) {
if (DEBUG_CLASS_COMMENTS) {
int len = 0;
for (final Object o : obj) {
len += o.toString().length();
}
final StringBuilder buf = new StringBuilder(len);
for (final Object o : obj) {
buf.append(o.toString());
}
return nodeClassComment(n, buf.toString());
} else {
return "";
}
}
/*
* User grammar generated and overridden visit methods below
*/
/**
* Visits a {@link JavaCCInput} node, whose children are the following :
* <p>
* f0 -> JavaCCOptions()<br>
* f1 -> "PARSER_BEGIN"<br>
* f2 -> "("<br>
* f3 -> IdentifierAsString()<br>
* f4 -> ")"<br>
* f5 -> CompilationUnit()<br>
* f6 -> "PARSER_END"<br>
* f7 -> "("<br>
* f8 -> IdentifierAsString()<br>
* f9 -> ")"<br>
* f10 -> ( Production() )+<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final JavaCCInput n) {
// we do not use sb.append(spc.spc) as indent level should be 0 at this point
// f0 -> JavaCCOptions()
n.f0.accept(this);
oneNewLine(n);
oneNewLine(n);
oneNewLine(n);
// f1 -> "PARSER_BEGIN"
n.f1.accept(this);
// f2 -> "("
n.f2.accept(this);
// f3 -> IdentifierAsString()
n.f3.accept(this);
// f4 -> ")"
n.f4.accept(this);
oneNewLine(n);
// f5 -> CompilationUnit()
sb.append(genJavaBranch(n.f5));
// f6 -> "PARSER_END"
n.f6.accept(this);
// f7 -> "("
n.f7.accept(this);
// f8 -> IdentifierAsString()
n.f8.accept(this);
// f9 -> ")"
n.f9.accept(this);
oneNewLine(n);
oneNewLine(n);
oneNewLine(n);
// f10 -> ( Production() )+
for (final Iterator<INode> e = n.f10.elements(); e.hasNext();) {
e.next().accept(this);
if (e.hasNext()) {
oneNewLine(n);
oneNewLine(n);
}
}
oneNewLine(n);
}
/**
* Visits a {@link JavaCCOptions} node, whose children are the following :
* <p>
* f0 -> [ #0 "options" #1 "{"<br>
* .. .. . #2 ( OptionBinding() )*<br>
* .. .. . #3 "}" ]<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final JavaCCOptions n) {
if (n.f0.present()) {
final NodeSequence seq = (NodeSequence) n.f0.node;
// #0 "options"
seq.elementAt(0).accept(this);
oneNewLine(n);
// #1 "{"
seq.elementAt(1).accept(this);
withoutSpecials = true;
// #2 ( OptionBinding() )*
final NodeListOptional nlo = (NodeListOptional) seq.elementAt(2);
if (nlo.present()) {
spc.updateSpc(+1);
oneNewLine(n);
// sb.append(spc.spc);
for (final Iterator<INode> e = nlo.elements(); e.hasNext();) {
// OptionBinding()
commentSpecials = false;
e.next().accept(this);
if (e.hasNext()) {
oneNewLine(n);
sb.append(spc.spc);
}
}
spc.updateSpc(-1);
oneNewLine(n);
sb.append(spc.spc);
}
// #3 "}"
seq.elementAt(3).accept(this);
withoutSpecials = false;
}
}
/**
* Visits a {@link OptionBinding} node, whose children are the following :
* <p>
* f0 -> ( %0 < IDENTIFIER ><br>
* .. .. | %1 "LOOKAHEAD"<br>
* .. .. | %2 "IGNORE_CASE"<br>
* .. .. | %3 "static" )<br>
* f1 -> "="<br>
* f2 -> ( %0 IntegerLiteral()<br>
* .. .. | %1 BooleanLiteral()<br>
* .. .. | %2 StringLiteral() )<br>
* f3 -> ";"<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final OptionBinding n) {
// f0 -> ( %0 < IDENTIFIER > | %1 "LOOKAHEAD" | %2 "IGNORE_CASE" | %3 "static" )
if (n.f0.which == 0) {
// f0 -> %0 < IDENTIFIER
final NodeToken nt = (NodeToken) n.f0.choice;
if (nt.tokenImage.startsWith("JTB_")) {
// comment JTB options : need to comment not only one line but all the lines
if (keepSpecialTokens) {
appendSpecials(nt);
}
sb.append(spc.spc).append("// ").append(nt.tokenImage);
commentSpecials = true;
} else {
// not a JTB option
if (keepSpecialTokens) {
appendSpecials(nt);
}
n.f0.choice.accept(this);
}
} else {
// f0 -> %1 "LOOKAHEAD" | %2 "IGNORE_CASE" | %3 "static"
if (keepSpecialTokens) {
final NodeToken nt = (NodeToken) n.f0.choice;
appendSpecials(nt);
}
n.f0.choice.accept(this);
}
sb.append(" ");
// f1 -> "="
if (keepSpecialTokens) {
final NodeToken nt = n.f1;
appendSpecials(nt);
}
n.f1.accept(this);
sb.append(" ");
// f2 -> ( %0 IntegerLiteral() | %1 BooleanLiteral() | %2 StringLiteral() )
if (keepSpecialTokens) {
NodeToken nt = null;
final INode nd = n.f2.choice;
if (nd instanceof StringLiteral) {
nt = ((StringLiteral) nd).f0;
} else if (nd instanceof IntegerLiteral) {
nt = ((IntegerLiteral) nd).f0;
} else if (nd instanceof BooleanLiteral) {
nt = (NodeToken) ((BooleanLiteral) nd).f0.choice;
}
appendSpecials(nt);
}
n.f2.accept(this);
// f3 -> ";"
if (keepSpecialTokens) {
final NodeToken nt = n.f3;
appendSpecials(nt);
}
n.f3.accept(this);
}
/**
* Visits a {@link Production} node, whose children are the following :
* <p>
* f0 -> . %0 JavaCodeProduction()<br>
* .. .. | %1 RegularExprProduction()<br>
* .. .. | %2 TokenManagerDecls()<br>
* .. .. | %3 BNFProduction()<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final Production n) {
// no difference with super class
n.f0.accept(this);
}
/**
* Visits a {@link JavaCodeProduction} node, whose children are the following :
* <p>
* f0 -> "JAVACODE"<br>
* f1 -> AccessModifier()<br>
* f2 -> ResultType()<br>
* f3 -> IdentifierAsString()<br>
* f4 -> FormalParameters()<br>
* f5 -> [ #0 "throws" #1 Name()<br>
* .. .. . #2 ( $0 "," $1 Name() )* ]<br>
* f6 -> [ "%" ]<br>
* f7 -> Block()<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final JavaCodeProduction n) {
// f0 -> "JAVACODE"
n.f0.accept(this);
oneNewLine(n);
sb.append(spc.spc);
// f1 -> AccessModifier()
n.f1.accept(this);
// f2 -> ResultType()
sb.append(genJavaBranch(n.f2));
sb.append(" ");
// f3 -> IdentifierAsString()
n.f3.accept(this);
// f4 -> FormalParameters()
sb.append(genJavaBranch(n.f4));
// f5 -> [ #0 "throws" #1 Name() #2 ( $0 "," $1 Name() )* ]
if (n.f5.present()) {
final NodeSequence seq = (NodeSequence) n.f5.node;
sb.append(" ");
// #0 "throws"
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 Name()
sb.append(genJavaBranch(seq.elementAt(1)));
// #2 ( $0 "," $1 Name() )*
final NodeListOptional opt = (NodeListOptional) seq.elementAt(2);
if (opt.present()) {
for (final Iterator<INode> e = opt.elements(); e.hasNext();) {
final NodeSequence seq1 = (NodeSequence) e.next();
// $0 ","
sb.append(genJavaBranch(seq1.elementAt(0)));
sb.append(" ");
// $1 Name()
sb.append(genJavaBranch(seq1.elementAt(1)));
}
}
}
oneNewLine(n);
sb.append(spc.spc);
// f6 -> [ "%" ]
// print it in a block comment
if (n.f6.present()) {
sb.append(" /*%*/ ");
}
// f7 -> Block()
sb.append(genJavaBranch(n.f7));
}
/**
* Visits a {@link BNFProduction} node, whose children are the following :
* <p>
* f0 -> AccessModifier()<br>
* f1 -> ResultType()<br>
* f2 -> IdentifierAsString()<br>
* f3 -> FormalParameters()<br>
* f4 -> [ #0 "throws" #1 Name()<br>
* .. .. . #2 ( $0 "," $1 Name() )* ]<br>
* f5 -> [ "!" ]<br>
* f6 -> ":"<br>
* f7 -> Block()<br>
* f8 -> "{"<br>
* f9 -> ExpansionChoices()<br>
* f10 -> "}"<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final BNFProduction n) {
// note : it looks we never fall here
// throw new AssertionError("in JavaCCPrinter visiting BNFProduction");
bnfLvl = 0;
// f0 -> AccessModifier()
n.f0.accept(this);
// f1 -> ResultType()
sb.append(genJavaBranch(n.f1));
sb.append(" ");
// f2 -> IdentifierAsString()
n.f2.accept(this);
// f3 -> FormalParameters()
sb.append(genJavaBranch(n.f3));
// f4 -> [ #0 "throws" #1 Name() #2 ( $0 "," $1 Name() )* ]
if (n.f4.present()) {
final NodeSequence seq = (NodeSequence) n.f4.node;
sb.append(" ");
// #0 "throws"
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 Name()
sb.append(genJavaBranch(seq.elementAt(1)));
// #2 ( $0 "," $1 Name() )* ]
final NodeListOptional opt = (NodeListOptional) seq.elementAt(2);
if (opt.present()) {
for (final Iterator<INode> e = opt.elements(); e.hasNext();) {
final NodeSequence seq1 = (NodeSequence) e.next();
// $0 ","
seq1.elementAt(0).accept(this);
sb.append(" ");
// $1 Name()
sb.append(genJavaBranch(seq1.elementAt(1)));
}
}
}
// f5 -> [ "!" ]
// print it in a block comment
if (n.f5.present()) {
sb.append(" /*!*/ ");
}
// f6 -> ":"
n.f6.accept(this);
oneNewLine(n);
sb.append(spc.spc);
// f7 -> Block()
sb.append(genJavaBranch(n.f7));
oneNewLine(n);
sb.append(spc.spc);
// f8 -> "{"
n.f8.accept(this);
oneNewLine(n);
spc.updateSpc(+1);
sb.append(spc.spc);
// f9 -> ExpansionChoices()
n.f9.accept(this);
oneNewLine(n);
spc.updateSpc(-1);
sb.append(spc.spc);
// f10 -> "}"
n.f10.accept(this);
oneNewLine(n);
}
/**
* Visits a {@link AccessModifier} node, whose children are the following :
* <p>
* f0 -> ( %0 "public"<br>
* .. .. | %1 "protected"<br>
* .. .. | %2 "private"<br>
* .. .. | %3 "final" )*<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final AccessModifier n) {
if (n.f0.present()) {
for (final Iterator<INode> e = n.f0.elements(); e.hasNext();) {
((NodeChoice) e.next()).accept(this);
sb.append(" ");
}
}
}
/**
* Visits a {@link RegularExprProduction} node, whose children are the following :
* <p>
* f0 -> [ %0 #0 "<"<br>
* .. .. . .. #1 "*"<br>
* .. .. . .. #2 ">"<br>
* .. .. | %1 #0 "<"<br>
* .. .. . .. #1 < IDENTIFIER ><br>
* .. .. . .. #2 ( $0 ","<br>
* .. .. . .. .. . $1 < IDENTIFIER > )*<br>
* .. .. . .. #3 ">" ]<br>
* f1 -> RegExprKind()<br>
* f2 -> [ #0 "["<br>
* .. .. . #1 "IGNORE_CASE"<br>
* .. .. . #2 "]" ]<br>
* f3 -> ":"<br>
* f4 -> "{"<br>
* f5 -> RegExprSpec()<br>
* f6 -> ( #0 "|"<br>
* .. .. . #1 RegExprSpec() )*<br>
* f7 -> "}"<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final RegularExprProduction n) {
// f0 -> [ %0 #0 "<" #1 "*" #2 ">" | %1 #0 "<" #1 < IDENTIFIER > #2 ( $0 "," $1 < IDENTIFIER > )* #3 ">" ]
if (n.f0.present()) {
n.f0.node.accept(this);
oneNewLine(n);
}
// f1 -> RegExprKind()
n.f1.accept(this);
// f2 -> [ #0 "[" #1 "IGNORE_CASE" #2 "]" ]
if (n.f2.present()) {
sb.append(" ");
n.f2.node.accept(this);
}
sb.append(" ");
// f3 -> ":"
n.f3.accept(this);
oneNewLine(n);
// f4 -> "{"
n.f4.accept(this);
spc.updateSpc(+1);
oneNewLine(n);
sb.append(spc.spc);
// f5 -> RegExprSpec()
n.f5.accept(this);
// f6 -> ( #0 "|" #1 RegExprSpec() )*
if (n.f6.present()) {
for (final Iterator<INode> e = n.f6.elements(); e.hasNext();) {
final NodeSequence seq = (NodeSequence) e.next();
oneNewLine(n);
// #0 "|"
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 RegExprSpec()
seq.elementAt(1).accept(this);
}
}
spc.updateSpc(-1);
oneNewLine(n);
sb.append(spc.spc);
// f7 -> "}"
n.f7.accept(this);
}
/**
* Visits a {@link TokenManagerDecls} node, whose children are the following :
* <p>
* f0 -> "TOKEN_MGR_DECLS"<br>
* f1 -> ":"<br>
* f2 -> ClassOrInterfaceBody()<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final TokenManagerDecls n) {
// f0 -> "TOKEN_MGR_DECLS"
n.f0.accept(this);
sb.append(" ");
// f1 -> ":"
n.f1.accept(this);
sb.append(" ");
// f2 -> ClassOrInterfaceBody()
sb.append(genJavaBranch(n.f2));
}
/**
* Visits a {@link RegExprKind} node, whose children are the following :
* <p>
* f0 -> . %0 "TOKEN"<br>
* .. .. | %1 "SPECIAL_TOKEN"<br>
* .. .. | %2 "SKIP"<br>
* .. .. | %3 "MORE"<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final RegExprKind n) {
// no difference with superclass
n.f0.accept(this);
}
/**
* Visits a {@link RegExprSpec} node, whose children are the following :
* <p>
* f0 -> RegularExpression()<br>
* f1 -> [ "!" ]<br>
* f2 -> [ Block() ]<br>
* f3 -> [ #0 ":" #1 < IDENTIFIER > ]<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final RegExprSpec n) {
// f0 -> RegularExpression()
n.f0.accept(this);
// f1 -> [ "!" ]
// print it in a block comment
if (n.f1.present()) {
sb.append(" /*!*/");
}
// f2 -> [ Block() ]
if (n.f2.present()) {
oneNewLine(n);
spc.updateSpc(+1);
sb.append(spc.spc);
sb.append(genJavaBranch(n.f2.node));
spc.updateSpc(-1);
}
// f3 -> [ #0 ":" #1 < IDENTIFIER > ]
if (n.f3.present()) {
final NodeSequence seq = (NodeSequence) n.f3.node;
sb.append(" ");
// #0 ":"
sb.append(seq.elementAt(0));
sb.append(" ");
// #1 < IDENTIFIER >
sb.append(seq.elementAt(1));
}
}
/**
* Visits a {@link ExpansionChoices} node, whose children are the following :
* <p>
* f0 -> Expansion()<br>
* f1 -> ( #0 "|" #1 Expansion() )*<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final ExpansionChoices n) {
if (!n.f1.present()) {
// f0 -> Expansion()
n.f0.accept(this);
} else {
// f0 -> Expansion()
++bnfLvl;
n.f0.accept(this);
--bnfLvl;
// f1 -> ( #0 "|" #1 Expansion() )*
for (final Iterator<INode> e = n.f1.elements(); e.hasNext();) {
final NodeSequence seq = (NodeSequence) e.next();
if (bnfLvl != 0) {
sb.append(" ");
} else {
oneNewLine(n);
sb.append(spc.spc);
}
// #0 "|"
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 Expansion()
++bnfLvl;
seq.elementAt(1).accept(this);
--bnfLvl;
}
}
}
/**
* Visits a {@link Expansion} node, whose children are the following :
* <p>
* f0 -> ( #0 "LOOKAHEAD" #1 "(" #2 LocalLookahead() #3 ")" )?<br>
* f1 -> ( ExpansionUnit() )+<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final Expansion n) {
// f0 -> ( #0 "LOOKAHEAD" #1 "(" #2 LocalLookahead() #3 ")" )?
if (n.f0.present()) {
final NodeSequence seq = (NodeSequence) n.f0.node;
// #0 "LOOKAHEAD"
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 "("
seq.elementAt(1).accept(this);
sb.append(" ");
// #2 LocalLookahead()
seq.elementAt(2).accept(this);
sb.append(" ");
// #3 ")"
seq.elementAt(3).accept(this);
}
// f1 -> ( ExpansionUnit() )+
for (final Iterator<INode> e = n.f1.elements(); e.hasNext();) {
// ExpansionUnit()
e.next().accept(this);
if (e.hasNext()) {
if (bnfLvl == 0) {
oneNewLine(n);
sb.append(spc.spc);
} else {
sb.append(" ");
}
}
}
}
/**
* Visits a {@link LocalLookahead} node, whose children are the following :
* <p>
* f0 -> [ IntegerLiteral() ]<br>
* f1 -> [ "," ]<br>
* f2 -> [ ExpansionChoices() ]<br>
* f3 -> [ "," ]<br>
* f4 -> [ #0 "{" #1 Expression() #2 "}" ]<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final LocalLookahead n) {
// f0 -> [ IntegerLiteral() ]
if (n.f0.present()) {
n.f0.accept(this);
}
// f1 -> [ "," ]
if (n.f1.present()) {
n.f1.accept(this);
sb.append(" ");
}
// f2 -> [ ExpansionChoices() ]
if (n.f2.present()) {
++bnfLvl;
n.f2.node.accept(this);
--bnfLvl;
}
// f3 -> [ "," ]
if (n.f3.present()) {
n.f3.accept(this);
sb.append(" ");
}
// f4 -> [ #0 "{" #1 Expression() #2 "}" ]
if (n.f4.present()) {
final NodeSequence seq = (NodeSequence) n.f4.node;
// #0 "{"
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 Expression()
sb.append(genJavaBranch(seq.elementAt(1)));
sb.append(" ");
// #2 "}"
seq.elementAt(2).accept(this);
}
}
/**
* Visits a {@link ExpansionUnit} node, whose children are the following :
* <p>
* f0 -> . %0 #0 "LOOKAHEAD" #1 "(" #2 LocalLookahead() #3 ")"<br>
* .. .. | %1 Block()<br>
* .. .. | %2 #0 "[" #1 ExpansionChoices() #2 "]"<br>
* .. .. | %3 ExpansionUnitTCF()<br>
* .. .. | %4 #0 [ $0 PrimaryExpression() $1 "=" ]<br>
* .. .. . .. #1 ( &0 $0 IdentifierAsString() $1 Arguments()<br>
* .. .. . .. .. . .. $2 [ "!" ]<br>
* .. .. . .. .. | &1 $0 RegularExpression()<br>
* .. .. . .. .. . .. $1 [ ?0 "." ?1 <IDENTIFIER> ]<br>
* .. .. . .. .. . .. $2 [ "!" ] )<br>
* .. .. | %5 #0 "(" #1 ExpansionChoices() #2 ")"<br>
* .. .. . .. #3 ( &0 "+"<br>
* .. .. . .. .. | &1 "*"<br>
* .. .. . .. .. | &2 "?" )?<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final ExpansionUnit n) {
NodeSequence seq;
NodeOptional opt;
NodeChoice ch;
switch (n.f0.which) {
case 0:
// %0 #0 "LOOKAHEAD" #1 "(" #2 LocalLookahead() #3 ")"
// #0 "LOOKAHEAD"
seq = (NodeSequence) n.f0.choice;
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 "("
seq.elementAt(1).accept(this);
sb.append(" ");
// #2 LocalLookahead()
seq.elementAt(2).accept(this);
sb.append(" ");
// #3 ")"
seq.elementAt(3).accept(this);
break;
case 1:
// %1 Block()
sb.append(genJavaBranch(n.f0.choice));
break;
case 2:
// %2 #0 "[" #1 ExpansionChoices() #2 "]"
seq = (NodeSequence) n.f0.choice;
seq.elementAt(0).accept(this);
sb.append(" ");
++bnfLvl;
seq.elementAt(1).accept(this);
--bnfLvl;
sb.append(" ");
seq.elementAt(2).accept(this);
break;
case 3:
// %3 ExpansionUnitTCF()
n.f0.choice.accept(this);
break;
case 4:
// %4 #0 [ $0 PrimaryExpression() $1 "=" ]
// .. #1 ( &0 $0 IdentifierAsString() $1 Arguments()
// .. .. . .. $2 [ "!" ]
// .. .. | &1 $0 RegularExpression()
// .. .. . .. $1 [ ?0 "." ?1 < IDENTIFIER > ] )
// .. .. . .. $2 [ "!" ] )
seq = (NodeSequence) n.f0.choice;
// #0 [ $0 PrimaryExpression() $1 "=" ]
opt = (NodeOptional) seq.elementAt(0);
if (opt.present()) {
// $0 PrimaryExpression()
((NodeSequence) opt.node).elementAt(0).accept(this);
sb.append(" ");
// $1 "="
((NodeSequence) opt.node).elementAt(1).accept(this);
sb.append(" ");
}
// #1 ( &0 $0 IdentifierAsString() $1 Arguments()
// .. .. . $2 [ "!" ]
// .. | &1 $0 RegularExpression()
// .. . .. $1 [ ?0 "." ?1 < IDENTIFIER > ]
// .. . .. $2 [ "!" ] )
ch = (NodeChoice) seq.elementAt(1);
final NodeSequence seq1 = (NodeSequence) ch.choice;
if (ch.which == 0) {
// $0 IdentifierAsString()
// must be prefixed / suffixed if to be created
boolean creLocNode = true;
final String ias = ((IdentifierAsString) seq1.elementAt(0)).f0.tokenImage;
final String prod = gdbv.getProdHT().get(ias);
if (prod != null) {
final String indProd = prod.substring(0, 1);
if (BNF_IND.equals(indProd)) {
if (gdbv.getNsnHT().containsKey(ias)) {
creLocNode = false;
}
} else if (JC_IND.equals(indProd)) {
if (!gdbv.getNsnHT().containsKey(ias)) {
creLocNode = false;
}
}
}
if (((NodeOptional) seq1.elementAt(2)).present()) {
creLocNode = false;
}
sb.append(creLocNode ? getFixedName(ias) : ias);
//) $1 Arguments()
sb.append(genJavaBranch(seq1.elementAt(1)));
// $2 [ "!" ]
// print it in a block comment
if (((NodeOptional) seq1.elementAt(2)).present()) {
sb.append(" /*!*/ ");
}
} else {
// $0 RegularExpression()
seq1.elementAt(0).accept(this);
// $1 [ ?0 "." ?1 < IDENTIFIER > ]
final NodeOptional opt1 = (NodeOptional) seq1.elementAt(1);
if (opt1.present()) {
((NodeToken) ((NodeSequence) opt1.node).elementAt(0)).accept(this);
((NodeToken) ((NodeSequence) opt1.node).elementAt(1)).accept(this);
}
// $2 [ "!" ]
// print it in a block comment
if (((NodeOptional) seq1.elementAt(2)).present()) {
sb.append(" /*!*/ ");
}
}
break;
case 5:
// %5 #0 "(" #1 ExpansionChoices() #2 ")"
// .. #3 ( &0 "+" | &1 "*" | &2 "?" )?
seq = (NodeSequence) n.f0.choice;
// #0 "("
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 ExpansionChoices()
++bnfLvl;
seq.elementAt(1).accept(this);
--bnfLvl;
sb.append(" ");
// #2 ")"
seq.elementAt(2).accept(this);
// #3 ( &0 "+" | &1 "*" | &2 "?" )?
opt = (NodeOptional) seq.elementAt(3);
if (opt.present()) {
opt.node.accept(this);
}
break;
default:
final String msg = "Invalid n.f0.which = " + String.valueOf(n.f0.which);
Messages.hardErr(msg);
throw new InternalError(msg);
}
}
/**
* Visits a {@link ExpansionUnitTCF} node, whose children are the following :
* <p>
* f0 -> "try"<br>
* f1 -> "{"<br>
* f2 -> ExpansionChoices()<br>
* f3 -> "}"<br>
* f4 -> ( #0 "catch" #1 "(" #2 Name() #3 < IDENTIFIER > #4 ")" #5 Block() )*<br>
* f5 -> [ #0 "finally" #1 Block() ]<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final ExpansionUnitTCF n) {
// f0 -> "try"
n.f0.accept(this);
sb.append(" ");
//f1 -> "{"
n.f1.accept(this);
spc.updateSpc(+1);
oneNewLine(n);
sb.append(spc.spc);
// f2 -> ExpansionChoices()
n.f2.accept(this);
sb.append(" ");
spc.updateSpc(-1);
// f3 -> "}"
n.f3.accept(this);
oneNewLine(n);
sb.append(spc.spc);
// f4 -> ( #0 "catch" #1 "(" #2 Name() #3 < IDENTIFIER > #4 ")" #5 Block() )*
if (n.f4.present()) {
for (int i = 0; i < n.f4.size(); i++) {
final NodeSequence seq = (NodeSequence) n.f4.elementAt(i);
// #0 "catch"
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 "("
seq.elementAt(1).accept(this);
// #2 Name()
sb.append(genJavaBranch(seq.elementAt(2)));
sb.append(" ");
// #3 < IDENTIFIER >
sb.append(((NodeToken) seq.elementAt(3)).tokenImage);
// #4 ")"
seq.elementAt(3).accept(this);
// #5 Block()
sb.append(genJavaBranch(seq.elementAt(4)));
oneNewLine(n);
}
}
// f5 -> [ #0 "finally" #1 Block() ]
if (n.f5.present()) {
// #0 "finally"
((NodeSequence) n.f5.node).elementAt(0).accept(this);
sb.append(" ");
// #1 Block()
sb.append(genJavaBranch(((NodeSequence) n.f5.node).elementAt(1)));
oneNewLine(n);
}
}
/**
* Visits a {@link RegularExpression} node, whose children are the following :
* <p>
* f0 -> . %0 StringLiteral()<br>
* .. .. | %1 #0 "<"<br>
* .. .. . .. #1 [ $0 [ "#" ]<br>
* .. .. . .. .. . $1 IdentifierAsString() $2 ":" ]<br>
* .. .. . .. #2 ComplexRegularExpressionChoices() #3 ">"<br>
* .. .. | %2 #0 "<" #1 IdentifierAsString() #2 ">"<br>
* .. .. | %3 #0 "<" #1 "EOF" #2 ">"<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final RegularExpression n) {
if (n.f0.which == 0) {
// %0 StringLiteral()
n.f0.choice.accept(this);
} else if (n.f0.which == 1) {
// %1 #0 "<" #1 [ $0 [ "#" ] $1 IdentifierAsString() $2 ":" ] #2 ComplexRegularExpressionChoices() #3 ">"
final NodeSequence seq = (NodeSequence) n.f0.choice;
// #0 "<"
seq.elementAt(0).accept(this);
sb.append(" ");
final NodeOptional opt = (NodeOptional) seq.elementAt(1);
// #1 [ $0 [ "#" ] $1 IdentifierAsString() $2 ":" ]
if (opt.present()) {
final NodeSequence seq1 = (NodeSequence) opt.node;
if (((NodeOptional) seq1.elementAt(0)).present()) {
// $0 [ "#" ]
seq1.elementAt(0).accept(this);
}
// $1 IdentifierAsString()
seq1.elementAt(1).accept(this);
sb.append(" ");
// $2 ":"
seq1.elementAt(2).accept(this);
sb.append(" ");
}
// #2 ComplexRegularExpressionChoices(c)
seq.elementAt(2).accept(this);
sb.append(" ");
// #3 ">"
seq.elementAt(3).accept(this);
} else {
// %2 #0 "<" #1 IdentifierAsString() #2 ">" OR %3 #0 "<" #1 "EOF" #2 ">"
// #0 "<"
((NodeSequence) n.f0.choice).elementAt(0).accept(this);
sb.append(" ");
// #1 IdentifierAsString() OR #1 "EOF"
((NodeSequence) n.f0.choice).elementAt(1).accept(this);
sb.append(" ");
// #2 ">"
((NodeSequence) n.f0.choice).elementAt(2).accept(this);
}
}
/**
* Visits a {@link ComplexRegularExpressionChoices} node, whose children are the following :
* <p>
* f0 -> ComplexRegularExpression()<br>
* f1 -> ( #0 "|" #1 ComplexRegularExpression() )*<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final ComplexRegularExpressionChoices n) {
// f0 -> ComplexRegularExpression()
n.f0.accept(this);
// f1 -> ( #0 "|" #1 ComplexRegularExpression() )*
if (n.f1.present()) {
for (final Iterator<INode> e = n.f1.elements(); e.hasNext();) {
final NodeSequence seq = (NodeSequence) e.next();
// #0 "|"
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 ComplexRegularExpression()
seq.elementAt(1).accept(this);
}
}
}
/**
* Visits a {@link ComplexRegularExpression} node, whose children are the following :
* <p>
* f0 -> ( ComplexRegularExpressionUnit() )+<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final ComplexRegularExpression n) {
for (final Iterator<INode> e = n.f0.elements(); e.hasNext();) {
// ComplexRegularExpressionUnit()
e.next().accept(this);
if (e.hasNext()) {
sb.append(" ");
}
}
}
/**
* Visits a {@link ComplexRegularExpressionUnit} node, whose children are the following :
* <p>
* f0 -> . %0 StringLiteral()<br>
* .. .. | %1 #0 "<" #1 IdentifierAsString() #2 ">"<br>
* .. .. | %2 CharacterList()<br>
* .. .. | %3 #0 "(" #1 ComplexRegularExpressionChoices() #2 ")"<br>
* .. .. . .. #3 ( &0 "+"<br>
* .. .. . .. .. | &1 "*"<br>
* .. .. . .. .. | &2 "?"<br>
* .. .. . .. .. | &3 $0 "{" $1 IntegerLiteral()<br>
* .. .. . .. .. . .. $2 [ ?0 ","<br>
* .. .. . .. .. . .. .. . ?1 [ IntegerLiteral() ] ]<br>
* .. .. . .. .. . .. $3 "}" )?<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final ComplexRegularExpressionUnit n) {
if (n.f0.which == 0 || n.f0.which == 2) {
// %0 StringLiteral() OR %2 CharacterList(c)
n.f0.choice.accept(this);
} else if (n.f0.which == 1) {
// %1 #0 "<" #1 IdentifierAsString() #2 ">"
// #0 "<"
((NodeSequence) n.f0.choice).elementAt(0).accept(this);
// #1 IdentifierAsString()
((NodeSequence) n.f0.choice).elementAt(1).accept(this);
// #2 ">"
((NodeSequence) n.f0.choice).elementAt(2).accept(this);
} else {
// %3 #0 "(" #1 ComplexRegularExpressionChoices() #2 ")" #3 ( &0 "+" | &1 "*" | &2 "?" | &3 $0 "{" $1 IntegerLiteral() $2 [ ?0 "," ?1 [ IntegerLiteral() ] ] $3 "}" )?
final NodeSequence seq = (NodeSequence) n.f0.choice;
// #0 "("
seq.elementAt(0).accept(this);
sb.append(" ");
// #1 ComplexRegularExpressionChoices()
seq.elementAt(1).accept(this);
sb.append(" ");
// #2 ")"
seq.elementAt(2).accept(this);
// #3 ( &0 "+" | &1 "*" | &2 "?" | &3 $0 "{" $1 IntegerLiteral() $2 [ ?0 "," ?1 [ IntegerLiteral() ] ] $3 "}" )?
final NodeOptional opt = (NodeOptional) seq.elementAt(3);
if (opt.present()) {
final NodeChoice ch = (NodeChoice) opt.node;
if (ch.which <= 2) {
// &0 "+" | &1 "*" | &2 "?"
ch.choice.accept(this);
} else {
// &3 $0 "{" $1 IntegerLiteral() $2 [ ?0 "," ?1 [ IntegerLiteral() ] ] $3 "}"
final NodeSequence seq1 = (NodeSequence) ch.choice;
// $0 "{"
seq1.elementAt(0).accept(this);
// $1 IntegerLiteral()
seq1.elementAt(1).accept(this);
// $2 [ ?0 "," ?1 [ IntegerLiteral() ] ]
final NodeOptional opt1 = (NodeOptional) seq1.elementAt(2);
if (opt1.present()) {
// ?0 ","
((NodeSequence) opt1.node).elementAt(0).accept(this);
sb.append(" ");
// ?1 IntegerLiteral()
((NodeSequence) opt1.node).elementAt(1).accept(this);
}
// $3 "}"
seq1.elementAt(3).accept(this);
}
}
}
}
/**
* Visits a {@link CharacterList} node, whose children are the following :
* <p>
* f0 -> [ "~" ]<br>
* f1 -> "["<br>
* f2 -> [ #0 CharacterDescriptor()<br>
* .. .. . #1 ( $0 "," $1 CharacterDescriptor() )* ]<br>
* f3 -> "]"<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final CharacterList n) {
// f0 -> [ "~" ]
if (n.f0.present()) {
n.f0.accept(this);
}
// f1 -> "["
n.f1.accept(this);
// f2 -> [ #0 CharacterDescriptor() #1 ( $0 "," $1 CharacterDescriptor() )* ]
if (n.f2.present()) {
final NodeSequence seq = (NodeSequence) n.f2.node;
// #0 CharacterDescriptor()
seq.elementAt(0).accept(this);
// #1 ( $0 "," $1 CharacterDescriptor() )* ]
final NodeListOptional nlo = (NodeListOptional) seq.elementAt(1);
for (final Iterator<INode> e = nlo.elements(); e.hasNext();) {
final NodeSequence seq1 = (NodeSequence) e.next();
// $0 ","
seq1.elementAt(0).accept(this);
sb.append(" ");
// $1 CharacterDescriptor()
seq1.elementAt(1).accept(this);
}
}
// f3 -> "]"
n.f3.accept(this);
}
/**
* Visits a {@link CharacterDescriptor} node, whose children are the following :
* <p>
* f0 -> StringLiteral()<br>
* f1 -> [ #0 "-" #1 StringLiteral() ]<br>
*
* @param n - the node to visit
*/
@Override
public void visit(final CharacterDescriptor n) {
// f0 -> StringLiteral()
n.f0.accept(this);
// f1 -> [ #0 "-" #1 StringLiteral() ]
if (n.f1.present()) {
final NodeSequence seq = (NodeSequence) n.f1.node;
// #0 "-"
seq.elementAt(0).accept(this);
// #1 StringLiteral()
seq.elementAt(1).accept(this);
}
}
/**
* Visits a {@link IdentifierAsString} node, whose children are the following :
* <p>
* f0 -> < IDENTIFIER ><br>
*
* @param n - the node to visit
*/
@Override
public void visit(final IdentifierAsString n) {
final String str = keepSpecialTokens && !withoutSpecials ? n.f0.withSpecials(spc.spc)
: n.f0.tokenImage;
sb.append(UnicodeConverter.addUnicodeEscapes(str));
}
/**
* Visits a {@link IntegerLiteral} node, whose children are the following :
* <p>
* f0 -> < INTEGER_LITERAL ><br>
*
* @param n - the node to visit
*/
@Override
public void visit(final IntegerLiteral n) {
final String str = keepSpecialTokens && !withoutSpecials ? n.f0.withSpecials(spc.spc)
: n.f0.tokenImage;
sb.append(UnicodeConverter.addUnicodeEscapes(str));
}
/**
* Visits a {@link StringLiteral} node, whose children are the following :
* <p>
* f0 -> < STRING_LITERAL ><br>
*
* @param n - the node to visit
*/
@Override
public void visit(final StringLiteral n) {
final String str = keepSpecialTokens && !withoutSpecials ? n.f0.withSpecials(spc.spc, gvaStr)
: n.f0.tokenImage;
sb.append(UnicodeConverter.addUnicodeEscapes(str));
gvaStr = null;
}
}
|
Fix function arity.
Signed-off-by: FrancisANDRE <[email protected]>
|
src/EDU/purdue/jtb/visitor/JavaCCPrinter.java
|
Fix function arity.
|
<ide><path>rc/EDU/purdue/jtb/visitor/JavaCCPrinter.java
<ide> @Override
<ide> public void visit(final NodeToken n) {
<ide> // sb.append(keepSpecialTokens ? n.withSpecials(spc.spc) : n.tokenImage);
<del> final String str = keepSpecialTokens && !withoutSpecials ? n.withSpecials(spc.spc, gvaStr)
<add> final String str = keepSpecialTokens && !withoutSpecials ? n.withSpecials(spc.spc)
<ide> : n.tokenImage;
<ide> sb.append(str);
<ide> gvaStr = null;
<ide> */
<ide> @Override
<ide> public void visit(final StringLiteral n) {
<del> final String str = keepSpecialTokens && !withoutSpecials ? n.f0.withSpecials(spc.spc, gvaStr)
<add> final String str = keepSpecialTokens && !withoutSpecials ? n.f0.withSpecials(spc.spc)
<ide> : n.f0.tokenImage;
<ide> sb.append(UnicodeConverter.addUnicodeEscapes(str));
<ide> gvaStr = null;
|
|
Java
|
apache-2.0
|
e7a0fb60034dc868944e58758bf78a98187033c9
| 0 |
anishek/hive,sankarh/hive,alanfgates/hive,lirui-apache/hive,anishek/hive,vergilchiu/hive,sankarh/hive,lirui-apache/hive,lirui-apache/hive,b-slim/hive,lirui-apache/hive,alanfgates/hive,lirui-apache/hive,nishantmonu51/hive,alanfgates/hive,anishek/hive,sankarh/hive,vineetgarg02/hive,alanfgates/hive,anishek/hive,jcamachor/hive,nishantmonu51/hive,vineetgarg02/hive,anishek/hive,lirui-apache/hive,b-slim/hive,vineetgarg02/hive,b-slim/hive,vergilchiu/hive,b-slim/hive,nishantmonu51/hive,jcamachor/hive,vergilchiu/hive,vergilchiu/hive,sankarh/hive,b-slim/hive,alanfgates/hive,anishek/hive,alanfgates/hive,jcamachor/hive,anishek/hive,b-slim/hive,b-slim/hive,nishantmonu51/hive,sankarh/hive,jcamachor/hive,sankarh/hive,vergilchiu/hive,nishantmonu51/hive,jcamachor/hive,nishantmonu51/hive,nishantmonu51/hive,jcamachor/hive,vergilchiu/hive,vineetgarg02/hive,anishek/hive,nishantmonu51/hive,sankarh/hive,b-slim/hive,alanfgates/hive,jcamachor/hive,lirui-apache/hive,alanfgates/hive,lirui-apache/hive,lirui-apache/hive,vineetgarg02/hive,vergilchiu/hive,vineetgarg02/hive,jcamachor/hive,vineetgarg02/hive,vergilchiu/hive,vineetgarg02/hive,jcamachor/hive,alanfgates/hive,sankarh/hive,sankarh/hive,b-slim/hive,nishantmonu51/hive,vineetgarg02/hive,anishek/hive,vergilchiu/hive
|
/**
* 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.hadoop.hive.shims;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.LoginException;
import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag;
import org.apache.hadoop.hive.thrift.DelegationTokenIdentifier;
import org.apache.hadoop.hive.thrift.DelegationTokenSelector;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authentication.util.KerberosUtil;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.hadoop.security.token.TokenSelector;
import org.apache.zookeeper.client.ZooKeeperSaslClient;
public class Utils {
private static final boolean IBM_JAVA = System.getProperty("java.vendor")
.contains("IBM");
public static UserGroupInformation getUGI() throws LoginException, IOException {
String doAs = System.getenv("HADOOP_USER_NAME");
if(doAs != null && doAs.length() > 0) {
/*
* this allows doAs (proxy user) to be passed along across process boundary where
* delegation tokens are not supported. For example, a DDL stmt via WebHCat with
* a doAs parameter, forks to 'hcat' which needs to start a Session that
* proxies the end user
*/
return UserGroupInformation.createProxyUser(doAs, UserGroupInformation.getLoginUser());
}
return UserGroupInformation.getCurrentUser();
}
/**
* Get the string form of the token given a token signature.
* The signature is used as the value of the "service" field in the token for lookup.
* Ref: AbstractDelegationTokenSelector in Hadoop. If there exists such a token
* in the token cache (credential store) of the job, the lookup returns that.
* This is relevant only when running against a "secure" hadoop release
* The method gets hold of the tokens if they are set up by hadoop - this should
* happen on the map/reduce tasks if the client added the tokens into hadoop's
* credential store in the front end during job submission. The method will
* select the hive delegation token among the set of tokens and return the string
* form of it
* @param tokenSignature
* @return the string form of the token found
* @throws IOException
*/
public static String getTokenStrForm(String tokenSignature) throws IOException {
UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
TokenSelector<? extends TokenIdentifier> tokenSelector = new DelegationTokenSelector();
Token<? extends TokenIdentifier> token = tokenSelector.selectToken(
tokenSignature == null ? new Text() : new Text(tokenSignature), ugi.getTokens());
return token != null ? token.encodeToUrlString() : null;
}
/**
* Create a delegation token object for the given token string and service.
* Add the token to given UGI
* @param ugi
* @param tokenStr
* @param tokenService
* @throws IOException
*/
public static void setTokenStr(UserGroupInformation ugi, String tokenStr, String tokenService)
throws IOException {
Token<DelegationTokenIdentifier> delegationToken = createToken(tokenStr, tokenService);
ugi.addToken(delegationToken);
}
/**
* Add a given service to delegation token string.
* @param tokenStr
* @param tokenService
* @return
* @throws IOException
*/
public static String addServiceToToken(String tokenStr, String tokenService)
throws IOException {
Token<DelegationTokenIdentifier> delegationToken = createToken(tokenStr, tokenService);
return delegationToken.encodeToUrlString();
}
/**
* Create a new token using the given string and service
* @param tokenStr
* @param tokenService
* @return
* @throws IOException
*/
private static Token<DelegationTokenIdentifier> createToken(String tokenStr, String tokenService)
throws IOException {
Token<DelegationTokenIdentifier> delegationToken = new Token<DelegationTokenIdentifier>();
delegationToken.decodeFromUrlString(tokenStr);
delegationToken.setService(new Text(tokenService));
return delegationToken;
}
/**
* Dynamically sets up the JAAS configuration that uses kerberos
* @param principal
* @param keyTabFile
* @throws IOException
*/
public static void setZookeeperClientKerberosJaasConfig(String principal, String keyTabFile) throws IOException {
// ZooKeeper property name to pick the correct JAAS conf section
final String SASL_LOGIN_CONTEXT_NAME = "HiveZooKeeperClient";
System.setProperty(ZooKeeperSaslClient.LOGIN_CONTEXT_NAME_KEY, SASL_LOGIN_CONTEXT_NAME);
principal = SecurityUtil.getServerPrincipal(principal, "0.0.0.0");
JaasConfiguration jaasConf = new JaasConfiguration(SASL_LOGIN_CONTEXT_NAME, principal, keyTabFile);
// Install the Configuration in the runtime.
javax.security.auth.login.Configuration.setConfiguration(jaasConf);
}
/**
* A JAAS configuration for ZooKeeper clients intended to use for SASL
* Kerberos.
*/
private static class JaasConfiguration extends javax.security.auth.login.Configuration {
// Current installed Configuration
private static final boolean IBM_JAVA = System.getProperty("java.vendor")
.contains("IBM");
private final javax.security.auth.login.Configuration baseConfig = javax.security.auth.login.Configuration
.getConfiguration();
private final String loginContextName;
private final String principal;
private final String keyTabFile;
public JaasConfiguration(String hiveLoginContextName, String principal, String keyTabFile) {
this.loginContextName = hiveLoginContextName;
this.principal = principal;
this.keyTabFile = keyTabFile;
}
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String appName) {
if (loginContextName.equals(appName)) {
Map<String, String> krbOptions = new HashMap<String, String>();
if (IBM_JAVA) {
krbOptions.put("credsType", "both");
krbOptions.put("useKeytab", keyTabFile);
} else {
krbOptions.put("doNotPrompt", "true");
krbOptions.put("storeKey", "true");
krbOptions.put("useKeyTab", "true");
krbOptions.put("keyTab", keyTabFile);
}
krbOptions.put("principal", principal);
krbOptions.put("refreshKrb5Config", "true");
AppConfigurationEntry hiveZooKeeperClientEntry = new AppConfigurationEntry(
KerberosUtil.getKrb5LoginModuleName(), LoginModuleControlFlag.REQUIRED, krbOptions);
return new AppConfigurationEntry[] { hiveZooKeeperClientEntry };
}
// Try the base config
if (baseConfig != null) {
return baseConfig.getAppConfigurationEntry(appName);
}
return null;
}
}
}
|
shims/common/src/main/java/org/apache/hadoop/hive/shims/Utils.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.hadoop.hive.shims;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.LoginException;
import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag;
import org.apache.hadoop.hive.thrift.DelegationTokenIdentifier;
import org.apache.hadoop.hive.thrift.DelegationTokenSelector;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authentication.util.KerberosUtil;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.hadoop.security.token.TokenSelector;
import org.apache.zookeeper.client.ZooKeeperSaslClient;
public class Utils {
public static UserGroupInformation getUGI() throws LoginException, IOException {
String doAs = System.getenv("HADOOP_USER_NAME");
if(doAs != null && doAs.length() > 0) {
/*
* this allows doAs (proxy user) to be passed along across process boundary where
* delegation tokens are not supported. For example, a DDL stmt via WebHCat with
* a doAs parameter, forks to 'hcat' which needs to start a Session that
* proxies the end user
*/
return UserGroupInformation.createProxyUser(doAs, UserGroupInformation.getLoginUser());
}
return UserGroupInformation.getCurrentUser();
}
/**
* Get the string form of the token given a token signature.
* The signature is used as the value of the "service" field in the token for lookup.
* Ref: AbstractDelegationTokenSelector in Hadoop. If there exists such a token
* in the token cache (credential store) of the job, the lookup returns that.
* This is relevant only when running against a "secure" hadoop release
* The method gets hold of the tokens if they are set up by hadoop - this should
* happen on the map/reduce tasks if the client added the tokens into hadoop's
* credential store in the front end during job submission. The method will
* select the hive delegation token among the set of tokens and return the string
* form of it
* @param tokenSignature
* @return the string form of the token found
* @throws IOException
*/
public static String getTokenStrForm(String tokenSignature) throws IOException {
UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
TokenSelector<? extends TokenIdentifier> tokenSelector = new DelegationTokenSelector();
Token<? extends TokenIdentifier> token = tokenSelector.selectToken(
tokenSignature == null ? new Text() : new Text(tokenSignature), ugi.getTokens());
return token != null ? token.encodeToUrlString() : null;
}
/**
* Create a delegation token object for the given token string and service.
* Add the token to given UGI
* @param ugi
* @param tokenStr
* @param tokenService
* @throws IOException
*/
public static void setTokenStr(UserGroupInformation ugi, String tokenStr, String tokenService)
throws IOException {
Token<DelegationTokenIdentifier> delegationToken = createToken(tokenStr, tokenService);
ugi.addToken(delegationToken);
}
/**
* Add a given service to delegation token string.
* @param tokenStr
* @param tokenService
* @return
* @throws IOException
*/
public static String addServiceToToken(String tokenStr, String tokenService)
throws IOException {
Token<DelegationTokenIdentifier> delegationToken = createToken(tokenStr, tokenService);
return delegationToken.encodeToUrlString();
}
/**
* Create a new token using the given string and service
* @param tokenStr
* @param tokenService
* @return
* @throws IOException
*/
private static Token<DelegationTokenIdentifier> createToken(String tokenStr, String tokenService)
throws IOException {
Token<DelegationTokenIdentifier> delegationToken = new Token<DelegationTokenIdentifier>();
delegationToken.decodeFromUrlString(tokenStr);
delegationToken.setService(new Text(tokenService));
return delegationToken;
}
/**
* Dynamically sets up the JAAS configuration that uses kerberos
* @param principal
* @param keyTabFile
* @throws IOException
*/
public static void setZookeeperClientKerberosJaasConfig(String principal, String keyTabFile) throws IOException {
// ZooKeeper property name to pick the correct JAAS conf section
final String SASL_LOGIN_CONTEXT_NAME = "HiveZooKeeperClient";
System.setProperty(ZooKeeperSaslClient.LOGIN_CONTEXT_NAME_KEY, SASL_LOGIN_CONTEXT_NAME);
principal = SecurityUtil.getServerPrincipal(principal, "0.0.0.0");
JaasConfiguration jaasConf = new JaasConfiguration(SASL_LOGIN_CONTEXT_NAME, principal, keyTabFile);
// Install the Configuration in the runtime.
javax.security.auth.login.Configuration.setConfiguration(jaasConf);
}
/**
* A JAAS configuration for ZooKeeper clients intended to use for SASL
* Kerberos.
*/
private static class JaasConfiguration extends javax.security.auth.login.Configuration {
// Current installed Configuration
private final javax.security.auth.login.Configuration baseConfig = javax.security.auth.login.Configuration
.getConfiguration();
private final String loginContextName;
private final String principal;
private final String keyTabFile;
public JaasConfiguration(String hiveLoginContextName, String principal, String keyTabFile) {
this.loginContextName = hiveLoginContextName;
this.principal = principal;
this.keyTabFile = keyTabFile;
}
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String appName) {
if (loginContextName.equals(appName)) {
Map<String, String> krbOptions = new HashMap<String, String>();
krbOptions.put("doNotPrompt", "true");
krbOptions.put("storeKey", "true");
krbOptions.put("useKeyTab", "true");
krbOptions.put("principal", principal);
krbOptions.put("keyTab", keyTabFile);
krbOptions.put("refreshKrb5Config", "true");
AppConfigurationEntry hiveZooKeeperClientEntry = new AppConfigurationEntry(
KerberosUtil.getKrb5LoginModuleName(), LoginModuleControlFlag.REQUIRED, krbOptions);
return new AppConfigurationEntry[] { hiveZooKeeperClientEntry };
}
// Try the base config
if (baseConfig != null) {
return baseConfig.getAppConfigurationEntry(appName);
}
return null;
}
}
}
|
HIVE-13020 : Hive Metastore and HiveServer2 to Zookeeper fails with IBM JDK (Greg Senia via Thejas Nair)
|
shims/common/src/main/java/org/apache/hadoop/hive/shims/Utils.java
|
HIVE-13020 : Hive Metastore and HiveServer2 to Zookeeper fails with IBM JDK (Greg Senia via Thejas Nair)
|
<ide><path>hims/common/src/main/java/org/apache/hadoop/hive/shims/Utils.java
<ide> import org.apache.zookeeper.client.ZooKeeperSaslClient;
<ide>
<ide> public class Utils {
<add>
<add> private static final boolean IBM_JAVA = System.getProperty("java.vendor")
<add> .contains("IBM");
<ide>
<ide> public static UserGroupInformation getUGI() throws LoginException, IOException {
<ide> String doAs = System.getenv("HADOOP_USER_NAME");
<ide> */
<ide> private static class JaasConfiguration extends javax.security.auth.login.Configuration {
<ide> // Current installed Configuration
<add> private static final boolean IBM_JAVA = System.getProperty("java.vendor")
<add> .contains("IBM");
<ide> private final javax.security.auth.login.Configuration baseConfig = javax.security.auth.login.Configuration
<ide> .getConfiguration();
<ide> private final String loginContextName;
<ide> public AppConfigurationEntry[] getAppConfigurationEntry(String appName) {
<ide> if (loginContextName.equals(appName)) {
<ide> Map<String, String> krbOptions = new HashMap<String, String>();
<del> krbOptions.put("doNotPrompt", "true");
<del> krbOptions.put("storeKey", "true");
<del> krbOptions.put("useKeyTab", "true");
<del> krbOptions.put("principal", principal);
<del> krbOptions.put("keyTab", keyTabFile);
<add> if (IBM_JAVA) {
<add> krbOptions.put("credsType", "both");
<add> krbOptions.put("useKeytab", keyTabFile);
<add> } else {
<add> krbOptions.put("doNotPrompt", "true");
<add> krbOptions.put("storeKey", "true");
<add> krbOptions.put("useKeyTab", "true");
<add> krbOptions.put("keyTab", keyTabFile);
<add> }
<add> krbOptions.put("principal", principal);
<ide> krbOptions.put("refreshKrb5Config", "true");
<ide> AppConfigurationEntry hiveZooKeeperClientEntry = new AppConfigurationEntry(
<ide> KerberosUtil.getKrb5LoginModuleName(), LoginModuleControlFlag.REQUIRED, krbOptions);
|
|
Java
|
apache-2.0
|
d3b97f15a75d40075c517ef6129a304fe1214bce
| 0 |
thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck
|
package org.ensembl.healthcheck.eg_gui;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import javax.swing.JOptionPane;
import org.ensembl.healthcheck.ConfigurableTestRunner;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.SystemPropertySetter;
import org.ensembl.healthcheck.configuration.ConfigurationUserParameters;
import org.ensembl.healthcheck.configuration.ConfigureHost;
import org.ensembl.healthcheck.configurationmanager.ConfigurationByProperties;
import org.ensembl.healthcheck.configurationmanager.ConfigurationFactory;
import org.ensembl.healthcheck.configurationmanager.ConfigurationFactory.ConfigurationType;
import org.ensembl.healthcheck.testcase.EnsTestCase;
import org.ensembl.healthcheck.testcase.PerlScriptConfig;
import org.ensembl.healthcheck.util.ActionAppendable;
import org.ensembl.healthcheck.util.DBUtils;
import org.ensembl.healthcheck.util.ProcessExec;
public class GuiTestRunnerFrameActionListener implements ActionListener {
protected final GuiTestRunnerFrame guiTestRunnerFrame;
protected boolean active;
// Holds a reference to the gui reporter. It is a component of the
// JPanel tabResults.
//
protected GuiReporterTab currentGuiReporter;
protected GuiLogHandler guiLogHandler;
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public GuiTestRunnerFrameActionListener(GuiTestRunnerFrame guiTestRunnerFrame) {
this.guiTestRunnerFrame = guiTestRunnerFrame;
this.active = true;
}
/**
* <p>
* Sets the primary and secondary host details in DBUtils.
* </p>
*
* @param primaryHostDetails
* @param secondaryHostDetails
*/
protected void setPrimaryAndSecondaryAndSystemPropertiesHost(
ConfigureHost primaryHostDetails,
ConfigureHost secondPrimaryHostDetails,
ConfigureHost secondaryHostDetails
) {
ConfigurationUserParameters combinedHostConfig = createConfigurationObject(
primaryHostDetails,
secondPrimaryHostDetails,
secondaryHostDetails
);
// And finally set the new configuration file in which the
// secondary host has been configured.
//
DBUtils.setHostConfiguration((ConfigureHost) combinedHostConfig);
SystemPropertySetter systemPropertySetter = new SystemPropertySetter(combinedHostConfig);
systemPropertySetter.setPropertiesForHealthchecks();
}
protected Properties writeToPrimaryServer(
Properties properties,
ConfigureHost hostDetails
) {
if (properties!=null) {
properties.setProperty("host", hostDetails.getHost());
properties.setProperty("port", hostDetails.getPort());
properties.setProperty("user", hostDetails.getUser());
properties.setProperty("password", hostDetails.getPassword());
properties.setProperty("driver", hostDetails.getDriver());
}
return properties;
}
protected Properties writeToSecondPrimaryServer(
Properties properties,
ConfigureHost hostDetails
) {
if (properties!=null) {
properties.setProperty("host1", hostDetails.getHost());
properties.setProperty("port1", hostDetails.getPort());
properties.setProperty("user1", hostDetails.getUser());
properties.setProperty("password1", hostDetails.getPassword());
properties.setProperty("driver1", hostDetails.getDriver());
}
return properties;
}
protected Properties writeToSecondaryServer(
Properties properties,
ConfigureHost hostDetails
) {
if (properties!=null) {
properties.setProperty("secondary.host", hostDetails.getHost());
properties.setProperty("secondary.port", hostDetails.getPort());
properties.setProperty("secondary.user", hostDetails.getUser());
properties.setProperty("secondary.password", hostDetails.getPassword());
properties.setProperty("secondary.driver", hostDetails.getDriver());
}
return properties;
}
protected ConfigurationUserParameters createConfigurationObject(
ConfigureHost primaryHostDetails,
ConfigureHost secondPrimaryHostDetails,
ConfigureHost secondaryHostDetails
) {
Properties hostProperties = new Properties();
hostProperties = writeToPrimaryServer (hostProperties, primaryHostDetails);
hostProperties = writeToSecondaryServer (hostProperties, secondaryHostDetails);
hostProperties = writeToSecondPrimaryServer (hostProperties, secondPrimaryHostDetails);
return createConfiguration(hostProperties);
}
/**
* @param hostProperties
* @return
*/
protected ConfigurationUserParameters createConfiguration(
Properties hostProperties) {
ConfigureHost hostConfiguration =
(ConfigureHost) ConfigurationByProperties.newInstance(
ConfigureHost.class,
hostProperties
);
List<File> propertyFileNames = new ArrayList<File>();
propertyFileNames.add(new File(ConfigurableTestRunner.getDefaultPropertiesFile()));
ConfigurationUserParameters ConfigurationByPropertyFiles =
new ConfigurationFactory<ConfigurationUserParameters>(
ConfigurationUserParameters.class,
propertyFileNames
).getConfiguration(ConfigurationType.Properties);
ConfigurationFactory<ConfigurationUserParameters> confFact =
new ConfigurationFactory<ConfigurationUserParameters>(
ConfigurationUserParameters.class,
hostConfiguration,
ConfigurationByPropertyFiles
);
ConfigurationUserParameters combinedHostConfig = confFact.getConfiguration(ConfigurationType.Cascading);
return combinedHostConfig;
}
@Override
public void actionPerformed(ActionEvent arg0) {
if (!active) {
return;
}
String cmd = arg0.getActionCommand();
// Not implemented yet
if (cmd.equals(Constants.Add_to_tests_to_be_run)) {
}
if (cmd.equals(Constants.REMOVE_SELECTED_TESTS)) {
GuiTestRunnerFrameActionPerformer.removeSelectedTests(guiTestRunnerFrame.setupTab.listOfTestsToBeRun);
}
if (cmd.equals(Constants.DB_SERVER_CHANGED) || cmd.equals(Constants.PAN_DB_SERVER_CHANGED)) {
ConfigureHost host = guiTestRunnerFrame.setupTab.dbDetails.get(guiTestRunnerFrame.setupTab.dbPrimaryServerSelector.getSelectedIndex());
ConfigureHost secondary_host = guiTestRunnerFrame.setupTab.dbDetails.get(guiTestRunnerFrame.setupTab.dbSecondaryServerSelector.getSelectedIndex());
ConfigureHost host1 = guiTestRunnerFrame.setupTab.dbDetails.get(guiTestRunnerFrame.setupTab.dbSecondPrimaryServerSelector.getSelectedIndex());
ConfigureHost combinedHostConfig = createConfigurationObject(
host,
host1,
secondary_host
);
GuiTestRunnerFrameActionPerformer.setupDatabasePane(
guiTestRunnerFrame.setupTab.databaseTabbedPaneWithSearchBox.getDatabasePane(),
combinedHostConfig
);
}
if (cmd.equals(Constants.RUN_ALL_TESTS) || cmd.equals(Constants.RUN_SELECTED_TESTS)) {
//
// Check, if basic conditions have been met so that tests can be
// run.
//
if (
(guiTestRunnerFrame.currentGuiTestRunnerThread != null)
&& (guiTestRunnerFrame.currentGuiTestRunnerThread.isAlive())
) {
JOptionPane.showMessageDialog(
guiTestRunnerFrame,
"A session of healthchecks is currently running already. "
+ "Please wait for it to terminate before starting another.",
"Error",
JOptionPane.ERROR_MESSAGE
);
return;
}
if (
cmd.equals(Constants.RUN_SELECTED_TESTS)
&& guiTestRunnerFrame.setupTab.listOfTestsToBeRun.getSelectedValues().length==0
) {
JOptionPane.showMessageDialog(
guiTestRunnerFrame,
"You have not selected any tests!",
"Error",
JOptionPane.ERROR_MESSAGE
);
return;
}
if (
cmd.equals(Constants.RUN_ALL_TESTS)
&& guiTestRunnerFrame.setupTab.listOfTestsToBeRun.getModel().getSize()==0
) {
JOptionPane.showMessageDialog(
guiTestRunnerFrame,
"No tests! Please drag tests from the tree in the left into the area above.",
"Error",
JOptionPane.ERROR_MESSAGE
);
return;
}
DatabaseRegistryEntry[] selectedDatabases
= guiTestRunnerFrame.setupTab.databaseTabbedPaneWithSearchBox.getDatabasePane().getSelectedDatabases();
if (selectedDatabases.length == 0) {
JOptionPane.showMessageDialog(
guiTestRunnerFrame,
"No databases selected!",
"Error",
JOptionPane.ERROR_MESSAGE
);
} else {
ReportManager.initialise();
// If currentGuiReporter has been initialised once, it has
// also been added to the tabResults. It has to be removed
// first, before a new one is created and put in its place.
//
if (currentGuiReporter!=null) {
guiTestRunnerFrame.resultTab.remove(currentGuiReporter);
}
currentGuiReporter = new GuiReporterTab();
guiLogHandler = new GuiLogHandler();
guiLogHandler.setReporter(currentGuiReporter);
// Set the formatter for EnsTestcases to what the user
// configured them to look like.
//
// Check, if a formatter was configured. If so, then use
// this formatter, otherwise create a new one.
//
Handler[] configuredHandler = Logger.getLogger(
EnsTestCase.class.getCanonicalName()
).getHandlers();
Formatter configuredFormatter;
if (configuredHandler.length == 0) {
configuredFormatter = new SimpleFormatter();
} else {
configuredFormatter = configuredHandler[0].getFormatter();
}
// Set the formatter.
guiLogHandler.setFormatter(configuredFormatter);
guiTestRunnerFrame.testProgressDialog = new TestProgressDialog("", 0, 100);
guiTestRunnerFrame.resultTab.setLayout(new BorderLayout());
guiTestRunnerFrame.resultTab.add(guiTestRunnerFrame.testProgressDialog, BorderLayout.SOUTH);
guiTestRunnerFrame.resultTab.add(currentGuiReporter, BorderLayout.CENTER);
guiTestRunnerFrame.tabbedPane.setEnabledAt(guiTestRunnerFrame.resultTabIndex, true);
guiTestRunnerFrame.tabbedPane.setEnabledAt(guiTestRunnerFrame.legacyResultTabIndex, true);
guiTestRunnerFrame.tabbedPane.setSelectedIndex(guiTestRunnerFrame.resultTabIndex);
guiTestRunnerFrame.legacyResultTab.setLayout(new BorderLayout());
ReportManager.setReporter(currentGuiReporter);
PerlScriptConfig psc = new PerlScriptConfig(
guiTestRunnerFrame.adminTab.getPerl5Binary(),
guiTestRunnerFrame.adminTab.getPerlOptions()
);
setPrimaryAndSecondaryAndSystemPropertiesHost(
guiTestRunnerFrame.setupTab.dbDetails.get(guiTestRunnerFrame.setupTab.dbPrimaryServerSelector.getSelectedIndex()),
guiTestRunnerFrame.setupTab.dbDetails.get(guiTestRunnerFrame.setupTab.dbSecondPrimaryServerSelector.getSelectedIndex()),
guiTestRunnerFrame.setupTab.dbDetails.get(guiTestRunnerFrame.setupTab.dbSecondaryServerSelector.getSelectedIndex())
);
if (cmd.equals(Constants.RUN_SELECTED_TESTS)) {
guiTestRunnerFrame.currentGuiTestRunnerThread = GuiTestRunnerFrameActionPerformer.runSelectedTests(
guiTestRunnerFrame.setupTab.listOfTestsToBeRun,
selectedDatabases,
guiTestRunnerFrame.testProgressDialog,
guiTestRunnerFrame.legacyResultTab,
guiTestRunnerFrame.adminTab.getPerl5Lib(),
psc,
guiLogHandler
);
}
if (cmd.equals(Constants.RUN_ALL_TESTS)) {
guiTestRunnerFrame.currentGuiTestRunnerThread = GuiTestRunnerFrameActionPerformer.runAllTests(
guiTestRunnerFrame.setupTab.listOfTestsToBeRun,
selectedDatabases,
guiTestRunnerFrame.testProgressDialog,
guiTestRunnerFrame.legacyResultTab,
guiTestRunnerFrame.adminTab.getPerl5Lib(),
psc,
guiLogHandler
);
}
}
}
}
}
|
src/org/ensembl/healthcheck/eg_gui/GuiTestRunnerFrameActionListener.java
|
package org.ensembl.healthcheck.eg_gui;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import javax.swing.JOptionPane;
import org.ensembl.healthcheck.ConfigurableTestRunner;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.SystemPropertySetter;
import org.ensembl.healthcheck.configuration.ConfigurationUserParameters;
import org.ensembl.healthcheck.configuration.ConfigureHost;
import org.ensembl.healthcheck.configurationmanager.ConfigurationByProperties;
import org.ensembl.healthcheck.configurationmanager.ConfigurationFactory;
import org.ensembl.healthcheck.configurationmanager.ConfigurationFactory.ConfigurationType;
import org.ensembl.healthcheck.testcase.EnsTestCase;
import org.ensembl.healthcheck.testcase.PerlScriptConfig;
import org.ensembl.healthcheck.util.ActionAppendable;
import org.ensembl.healthcheck.util.DBUtils;
import org.ensembl.healthcheck.util.ProcessExec;
public class GuiTestRunnerFrameActionListener implements ActionListener {
protected final GuiTestRunnerFrame guiTestRunnerFrame;
protected boolean active;
// Holds a reference to the gui reporter. It is a component of the
// JPanel tabResults.
//
protected GuiReporterTab currentGuiReporter;
protected GuiLogHandler guiLogHandler;
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public GuiTestRunnerFrameActionListener(GuiTestRunnerFrame guiTestRunnerFrame) {
this.guiTestRunnerFrame = guiTestRunnerFrame;
this.active = true;
}
/**
* <p>
* Sets the primary and secondary host details in DBUtils.
* </p>
*
* @param primaryHostDetails
* @param secondaryHostDetails
*/
protected void setPrimaryAndSecondaryAndSystemPropertiesHost(
ConfigureHost primaryHostDetails,
ConfigureHost secondPrimaryHostDetails,
ConfigureHost secondaryHostDetails
) {
ConfigurationUserParameters combinedHostConfig = createConfigurationObject(
primaryHostDetails,
secondPrimaryHostDetails,
secondaryHostDetails
);
System.out.println("Configuration is: " + combinedHostConfig);
// And finally set the new configuration file in which the
// secondary host has been configured.
//
DBUtils.setHostConfiguration((ConfigureHost) combinedHostConfig);
SystemPropertySetter systemPropertySetter = new SystemPropertySetter(combinedHostConfig);
systemPropertySetter.setPropertiesForHealthchecks();
}
protected Properties writeToPrimaryServer(
Properties properties,
ConfigureHost hostDetails
) {
if (properties!=null) {
properties.setProperty("host", hostDetails.getHost());
properties.setProperty("port", hostDetails.getPort());
properties.setProperty("user", hostDetails.getUser());
properties.setProperty("password", hostDetails.getPassword());
properties.setProperty("driver", hostDetails.getDriver());
}
return properties;
}
protected Properties writeToSecondPrimaryServer(
Properties properties,
ConfigureHost hostDetails
) {
if (properties!=null) {
properties.setProperty("host1", hostDetails.getHost());
properties.setProperty("port1", hostDetails.getPort());
properties.setProperty("user1", hostDetails.getUser());
properties.setProperty("password1", hostDetails.getPassword());
properties.setProperty("driver1", hostDetails.getDriver());
}
return properties;
}
protected Properties writeToSecondaryServer(
Properties properties,
ConfigureHost hostDetails
) {
if (properties!=null) {
properties.setProperty("secondary.host", hostDetails.getHost());
properties.setProperty("secondary.port", hostDetails.getPort());
properties.setProperty("secondary.user", hostDetails.getUser());
properties.setProperty("secondary.password", hostDetails.getPassword());
properties.setProperty("secondary.driver", hostDetails.getDriver());
}
return properties;
}
protected ConfigurationUserParameters createConfigurationObject(
ConfigureHost primaryHostDetails,
ConfigureHost secondPrimaryHostDetails,
ConfigureHost secondaryHostDetails
) {
Properties hostProperties = new Properties();
hostProperties = writeToPrimaryServer (hostProperties, primaryHostDetails);
hostProperties = writeToSecondaryServer (hostProperties, secondaryHostDetails);
hostProperties = writeToSecondPrimaryServer (hostProperties, secondPrimaryHostDetails);
return createConfiguration(hostProperties);
}
/**
* @param hostProperties
* @return
*/
protected ConfigurationUserParameters createConfiguration(
Properties hostProperties) {
ConfigureHost hostConfiguration =
(ConfigureHost) ConfigurationByProperties.newInstance(
ConfigureHost.class,
hostProperties
);
List<File> propertyFileNames = new ArrayList<File>();
propertyFileNames.add(new File(ConfigurableTestRunner.getDefaultPropertiesFile()));
ConfigurationUserParameters ConfigurationByPropertyFiles =
new ConfigurationFactory<ConfigurationUserParameters>(
ConfigurationUserParameters.class,
propertyFileNames
).getConfiguration(ConfigurationType.Properties);
ConfigurationFactory<ConfigurationUserParameters> confFact =
new ConfigurationFactory<ConfigurationUserParameters>(
ConfigurationUserParameters.class,
hostConfiguration,
ConfigurationByPropertyFiles
);
ConfigurationUserParameters combinedHostConfig = confFact.getConfiguration(ConfigurationType.Cascading);
return combinedHostConfig;
}
@Override
public void actionPerformed(ActionEvent arg0) {
if (!active) {
return;
}
String cmd = arg0.getActionCommand();
// Not implemented yet
if (cmd.equals(Constants.Add_to_tests_to_be_run)) {
}
if (cmd.equals(Constants.REMOVE_SELECTED_TESTS)) {
GuiTestRunnerFrameActionPerformer.removeSelectedTests(guiTestRunnerFrame.setupTab.listOfTestsToBeRun);
}
if (cmd.equals(Constants.DB_SERVER_CHANGED) || cmd.equals(Constants.PAN_DB_SERVER_CHANGED)) {
ConfigureHost host = guiTestRunnerFrame.setupTab.dbDetails.get(guiTestRunnerFrame.setupTab.dbPrimaryServerSelector.getSelectedIndex());
ConfigureHost secondary_host = guiTestRunnerFrame.setupTab.dbDetails.get(guiTestRunnerFrame.setupTab.dbSecondaryServerSelector.getSelectedIndex());
ConfigureHost host1 = guiTestRunnerFrame.setupTab.dbDetails.get(guiTestRunnerFrame.setupTab.dbSecondPrimaryServerSelector.getSelectedIndex());
ConfigureHost combinedHostConfig = createConfigurationObject(
host,
host1,
secondary_host
);
GuiTestRunnerFrameActionPerformer.setupDatabasePane(
guiTestRunnerFrame.setupTab.databaseTabbedPaneWithSearchBox.getDatabasePane(),
combinedHostConfig
);
}
if (cmd.equals(Constants.RUN_ALL_TESTS) || cmd.equals(Constants.RUN_SELECTED_TESTS)) {
//
// Check, if basic conditions have been met so that tests can be
// run.
//
if (
(guiTestRunnerFrame.currentGuiTestRunnerThread != null)
&& (guiTestRunnerFrame.currentGuiTestRunnerThread.isAlive())
) {
JOptionPane.showMessageDialog(
guiTestRunnerFrame,
"A session of healthchecks is currently running already. "
+ "Please wait for it to terminate before starting another.",
"Error",
JOptionPane.ERROR_MESSAGE
);
return;
}
if (
cmd.equals(Constants.RUN_SELECTED_TESTS)
&& guiTestRunnerFrame.setupTab.listOfTestsToBeRun.getSelectedValues().length==0
) {
JOptionPane.showMessageDialog(
guiTestRunnerFrame,
"You have not selected any tests!",
"Error",
JOptionPane.ERROR_MESSAGE
);
return;
}
if (
cmd.equals(Constants.RUN_ALL_TESTS)
&& guiTestRunnerFrame.setupTab.listOfTestsToBeRun.getModel().getSize()==0
) {
JOptionPane.showMessageDialog(
guiTestRunnerFrame,
"No tests! Please drag tests from the tree in the left into the area above.",
"Error",
JOptionPane.ERROR_MESSAGE
);
return;
}
DatabaseRegistryEntry[] selectedDatabases
= guiTestRunnerFrame.setupTab.databaseTabbedPaneWithSearchBox.getDatabasePane().getSelectedDatabases();
if (selectedDatabases.length == 0) {
JOptionPane.showMessageDialog(
guiTestRunnerFrame,
"No databases selected!",
"Error",
JOptionPane.ERROR_MESSAGE
);
} else {
ReportManager.initialise();
// If currentGuiReporter has been initialised once, it has
// also been added to the tabResults. It has to be removed
// first, before a new one is created and put in its place.
//
if (currentGuiReporter!=null) {
guiTestRunnerFrame.resultTab.remove(currentGuiReporter);
}
currentGuiReporter = new GuiReporterTab();
guiLogHandler = new GuiLogHandler();
guiLogHandler.setReporter(currentGuiReporter);
// Set the formatter for EnsTestcases to what the user
// configured them to look like.
//
// Check, if a formatter was configured. If so, then use
// this formatter, otherwise create a new one.
//
Handler[] configuredHandler = Logger.getLogger(
EnsTestCase.class.getCanonicalName()
).getHandlers();
Formatter configuredFormatter;
if (configuredHandler.length == 0) {
configuredFormatter = new SimpleFormatter();
} else {
configuredFormatter = configuredHandler[0].getFormatter();
}
// Set the formatter.
guiLogHandler.setFormatter(configuredFormatter);
guiTestRunnerFrame.testProgressDialog = new TestProgressDialog("", 0, 100);
guiTestRunnerFrame.resultTab.setLayout(new BorderLayout());
guiTestRunnerFrame.resultTab.add(guiTestRunnerFrame.testProgressDialog, BorderLayout.SOUTH);
guiTestRunnerFrame.resultTab.add(currentGuiReporter, BorderLayout.CENTER);
guiTestRunnerFrame.tabbedPane.setEnabledAt(guiTestRunnerFrame.resultTabIndex, true);
guiTestRunnerFrame.tabbedPane.setEnabledAt(guiTestRunnerFrame.legacyResultTabIndex, true);
guiTestRunnerFrame.tabbedPane.setSelectedIndex(guiTestRunnerFrame.resultTabIndex);
guiTestRunnerFrame.legacyResultTab.setLayout(new BorderLayout());
ReportManager.setReporter(currentGuiReporter);
PerlScriptConfig psc = new PerlScriptConfig(
guiTestRunnerFrame.adminTab.getPerl5Binary(),
guiTestRunnerFrame.adminTab.getPerlOptions()
);
setPrimaryAndSecondaryAndSystemPropertiesHost(
guiTestRunnerFrame.setupTab.dbDetails.get(guiTestRunnerFrame.setupTab.dbPrimaryServerSelector.getSelectedIndex()),
guiTestRunnerFrame.setupTab.dbDetails.get(guiTestRunnerFrame.setupTab.dbSecondPrimaryServerSelector.getSelectedIndex()),
guiTestRunnerFrame.setupTab.dbDetails.get(guiTestRunnerFrame.setupTab.dbSecondaryServerSelector.getSelectedIndex())
);
if (cmd.equals(Constants.RUN_SELECTED_TESTS)) {
guiTestRunnerFrame.currentGuiTestRunnerThread = GuiTestRunnerFrameActionPerformer.runSelectedTests(
guiTestRunnerFrame.setupTab.listOfTestsToBeRun,
selectedDatabases,
guiTestRunnerFrame.testProgressDialog,
guiTestRunnerFrame.legacyResultTab,
guiTestRunnerFrame.adminTab.getPerl5Lib(),
psc,
guiLogHandler
);
}
if (cmd.equals(Constants.RUN_ALL_TESTS)) {
guiTestRunnerFrame.currentGuiTestRunnerThread = GuiTestRunnerFrameActionPerformer.runAllTests(
guiTestRunnerFrame.setupTab.listOfTestsToBeRun,
selectedDatabases,
guiTestRunnerFrame.testProgressDialog,
guiTestRunnerFrame.legacyResultTab,
guiTestRunnerFrame.adminTab.getPerl5Lib(),
psc,
guiLogHandler
);
}
}
}
}
}
|
Removed superfluous output.
|
src/org/ensembl/healthcheck/eg_gui/GuiTestRunnerFrameActionListener.java
|
Removed superfluous output.
|
<ide><path>rc/org/ensembl/healthcheck/eg_gui/GuiTestRunnerFrameActionListener.java
<ide> secondPrimaryHostDetails,
<ide> secondaryHostDetails
<ide> );
<del>
<del> System.out.println("Configuration is: " + combinedHostConfig);
<ide>
<ide> // And finally set the new configuration file in which the
<ide> // secondary host has been configured.
|
|
Java
|
agpl-3.0
|
95b45d12fd0430be134be332b0ebe16ee027be25
| 0 |
Tanaguru/Tanaguru,medsob/Tanaguru,Tanaguru/Tanaguru,Asqatasun/Asqatasun,medsob/Tanaguru,medsob/Tanaguru,Asqatasun/Asqatasun,dzc34/Asqatasun,Asqatasun/Asqatasun,dzc34/Asqatasun,Asqatasun/Asqatasun,Tanaguru/Tanaguru,dzc34/Asqatasun,dzc34/Asqatasun,Asqatasun/Asqatasun,medsob/Tanaguru,dzc34/Asqatasun,Tanaguru/Tanaguru
|
package org.opens.tanaguru.client;
import java.util.ResourceBundle;
import org.opens.tanaguru.entity.audit.Audit;
import org.opens.tanaguru.entity.audit.AuditStatus;
import org.opens.tanaguru.entity.audit.Content;
import org.opens.tanaguru.entity.audit.ProcessResult;
import org.opens.tanaguru.entity.audit.SSP;
import org.opens.tanaguru.service.AuditService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
/**
*
* @author ADEX
*/
public class FullClientImpl {
private static final String APPLICATION_CONTEXT_FILE_PATH = "file:///etc/tanaguru/context/local-app/context-fullclient.xml";
public static void main(String[] args) {
if (args[0] != null && args[1] != null) {
run(args[0], args[1]);
} else {
run("opens-all", null);
}
}
private static void run(String bundleName, String url) throws BeansException {
ResourceBundle parametersBundle = ResourceBundle.getBundle(bundleName);
String siteUrl = parametersBundle.getString("siteUrl");
String[] pageUrlList = null;
if (url != null) {
pageUrlList = new String[]{url};
} else {
pageUrlList = parametersBundle.getString("pageUrlList").split(", ");
}
String[] testCodeList = parametersBundle.getString("testCodeList").split(", ");
ApplicationContext springApplicationContext = new FileSystemXmlApplicationContext(APPLICATION_CONTEXT_FILE_PATH);
BeanFactory springBeanFactory = springApplicationContext;
AuditService auditService = (AuditService) springBeanFactory.getBean("auditService");
Audit audit = null;
if (!siteUrl.isEmpty()) {
audit = auditService.auditSite(siteUrl, pageUrlList, testCodeList);
} else {
audit = auditService.auditPage(pageUrlList[0], testCodeList);
}
if (audit.getStatus().equals(AuditStatus.ERROR)) {
boolean hasContent = false;
for (Content content : audit.getContentList()) {
if (content instanceof SSP) {
//We check that some content has been downloaded and has to
//adapter. For the moment we ignore the return error code @TODO
if (!((SSP)content).getSource().isEmpty()) {
hasContent = true;
break;
}
}
}
if (!hasContent){
System.out.println("");
System.out.println("An error occured while loading " + audit.getSubject().getURL());
System.out.println("mark: 0");
return;
}
if (audit.getGrossResultList().isEmpty()) {
System.out.println("");
System.out.println("An error occured while testing " + audit.getSubject().getURL());
System.out.println("mark: 0");
return;
}
}
System.out.println("id: " + audit.getId());
for (ProcessResult netResult : audit.getNetResultList()) {
System.out.println(netResult.getTest().getCode() + ", " + netResult.getSubject().getURL() + ": " + netResult.getValue());
}
System.out.println("grossResultCount: " + audit.getGrossResultList().size());
System.out.println("netResultCount: " + audit.getNetResultList().size());
System.out.println("mark: " + audit.getMark());
}
}
|
tanaguru-client/src/main/java/org/opens/tanaguru/client/FullClientImpl.java
|
package org.opens.tanaguru.client;
import java.util.ResourceBundle;
import org.opens.tanaguru.entity.audit.Audit;
import org.opens.tanaguru.entity.audit.ProcessResult;
import org.opens.tanaguru.service.AuditService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
/**
*
* @author ADEX
*/
public class FullClientImpl {
private static final String APPLICATION_CONTEXT_FILE_PATH = "file:///etc/tanaguru/context/local-app/context-fullclient.xml";
public static void main(String[] args) {
if (args[0] != null && args[1] != null) {
run(args[0], args[1]);
} else {
run("opens-all", null);
}
}
private static void run(String bundleName, String url) throws BeansException {
ResourceBundle parametersBundle = ResourceBundle.getBundle(bundleName);
String siteUrl = parametersBundle.getString("siteUrl");
String[] pageUrlList = null;
if (url != null) {
pageUrlList = new String[]{url};
} else {
pageUrlList = parametersBundle.getString("pageUrlList").split(", ");
}
String[] testCodeList = parametersBundle.getString("testCodeList").split(", ");
ApplicationContext springApplicationContext = new FileSystemXmlApplicationContext(APPLICATION_CONTEXT_FILE_PATH);
BeanFactory springBeanFactory = springApplicationContext;
AuditService auditService = (AuditService) springBeanFactory.getBean("auditService");
Audit audit = null;
if (!siteUrl.isEmpty()) {
audit = auditService.auditSite(siteUrl, pageUrlList, testCodeList);
} else {
audit = auditService.auditPage(pageUrlList[0], testCodeList);
}
System.out.println("id: " + audit.getId());
for (ProcessResult netResult : audit.getNetResultList()) {
System.out.println(netResult.getTest().getCode() + ", " + netResult.getSubject().getURL() + ": " + netResult.getValue());
}
System.out.println("grossResultCount: " + audit.getGrossResultList().size());
System.out.println("netResultCount: " + audit.getNetResultList().size());
System.out.println("mark: " + audit.getMark());
}
}
|
Bug #36 correction
|
tanaguru-client/src/main/java/org/opens/tanaguru/client/FullClientImpl.java
|
Bug #36 correction
|
<ide><path>anaguru-client/src/main/java/org/opens/tanaguru/client/FullClientImpl.java
<ide>
<ide> import java.util.ResourceBundle;
<ide> import org.opens.tanaguru.entity.audit.Audit;
<add>import org.opens.tanaguru.entity.audit.AuditStatus;
<add>import org.opens.tanaguru.entity.audit.Content;
<ide> import org.opens.tanaguru.entity.audit.ProcessResult;
<add>import org.opens.tanaguru.entity.audit.SSP;
<ide> import org.opens.tanaguru.service.AuditService;
<ide> import org.springframework.beans.BeansException;
<ide> import org.springframework.beans.factory.BeanFactory;
<ide> audit = auditService.auditPage(pageUrlList[0], testCodeList);
<ide> }
<ide>
<add> if (audit.getStatus().equals(AuditStatus.ERROR)) {
<add> boolean hasContent = false;
<add> for (Content content : audit.getContentList()) {
<add> if (content instanceof SSP) {
<add> //We check that some content has been downloaded and has to
<add> //adapter. For the moment we ignore the return error code @TODO
<add> if (!((SSP)content).getSource().isEmpty()) {
<add> hasContent = true;
<add> break;
<add> }
<add> }
<add> }
<add> if (!hasContent){
<add> System.out.println("");
<add> System.out.println("An error occured while loading " + audit.getSubject().getURL());
<add> System.out.println("mark: 0");
<add> return;
<add> }
<add> if (audit.getGrossResultList().isEmpty()) {
<add> System.out.println("");
<add> System.out.println("An error occured while testing " + audit.getSubject().getURL());
<add> System.out.println("mark: 0");
<add> return;
<add> }
<add> }
<add>
<ide> System.out.println("id: " + audit.getId());
<ide> for (ProcessResult netResult : audit.getNetResultList()) {
<ide> System.out.println(netResult.getTest().getCode() + ", " + netResult.getSubject().getURL() + ": " + netResult.getValue());
|
|
Java
|
apache-2.0
|
43f93222a9dc26e148d762beb69a423c240f9bc4
| 0 |
TwoGuysFromKabul/xenqtt,codebeautiful/xenqtt,TwoGuysFromKabul/xenqtt,codebeautiful/xenqtt,codebeautiful/xenqtt,TwoGuysFromKabul/xenqtt
|
package net.sf.xenqtt.message;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import net.sf.xenqtt.MqttException;
import net.sf.xenqtt.MqttInterruptedException;
import net.sf.xenqtt.MqttTimeoutException;
/**
* Implementation of {@link BlockingCommand} that provides a simple extension point for command implementations.
*/
public abstract class AbstractBlockingCommand<T> implements BlockingCommand<T> {
private final CountDownLatch done = new CountDownLatch(1);
private T returnValue;
private Throwable failCause;
/**
* @see net.sf.xenqtt.message.BlockingCommand#await()
*/
@Override
public final T await() throws MqttInterruptedException {
return await(Long.MAX_VALUE, TimeUnit.DAYS);
}
/**
* @see net.sf.xenqtt.message.BlockingCommand#await(long, java.util.concurrent.TimeUnit)
*/
@Override
public final T await(long timeout, TimeUnit unit) throws MqttInterruptedException, MqttTimeoutException {
try {
if (timeout == Long.MAX_VALUE && unit == TimeUnit.DAYS) {
done.await();
} else {
if (!done.await(timeout, unit)) {
throw new MqttTimeoutException(String.format("Timed out waiting %d %s for command %s", timeout, unit, getClass().getSimpleName()));
}
}
} catch (InterruptedException e) {
throw new MqttInterruptedException(e);
}
if (failCause != null) {
if (failCause instanceof RuntimeException) {
throw (RuntimeException) failCause;
}
if (failCause instanceof Error) {
throw (Error) failCause;
}
throw new RuntimeException("Unexpected exception. This is a bug!", failCause);
}
return returnValue;
}
/**
* @see net.sf.xenqtt.message.BlockingCommand#execute()
*/
@Override
public final void execute() {
try {
returnValue = doExecute();
} catch (RuntimeException e) {
failCause = e;
} catch (Exception e) {
failCause = new MqttException(e);
} catch (Error e) {
failCause = e;
}
}
/**
* @see net.sf.xenqtt.message.BlockingCommand#complete(java.lang.Throwable)
*/
@Override
public final void complete(Throwable failCause) {
if (this.failCause == null && failCause != null) {
if (failCause instanceof RuntimeException) {
this.failCause = failCause;
} else if (failCause instanceof Exception) {
this.failCause = new MqttException(failCause);
} else {
this.failCause = failCause;
}
}
done.countDown();
}
/**
* Extensions implement this method to execute the command
*
* @return The value returned by the command
* @throws Exception
* Any exception thrown by the command
*/
protected abstract T doExecute() throws Exception;
}
|
src/main/java/net/sf/xenqtt/message/AbstractBlockingCommand.java
|
package net.sf.xenqtt.message;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import net.sf.xenqtt.MqttException;
import net.sf.xenqtt.MqttInterruptedException;
import net.sf.xenqtt.MqttTimeoutException;
/**
* Implementation of {@link BlockingCommand} that provides a simple extension point for command implementations.
*/
public abstract class AbstractBlockingCommand<T> implements BlockingCommand<T> {
private final CountDownLatch done = new CountDownLatch(1);
private T returnValue;
private Throwable failCause;
/**
* @see net.sf.xenqtt.message.BlockingCommand#await()
*/
@Override
public final T await() throws MqttInterruptedException {
return await(0, TimeUnit.DAYS);
}
/**
* @see net.sf.xenqtt.message.BlockingCommand#await(long, java.util.concurrent.TimeUnit)
*/
@Override
public final T await(long timeout, TimeUnit unit) throws MqttInterruptedException, MqttTimeoutException {
try {
if (timeout == Long.MAX_VALUE && unit == TimeUnit.DAYS) {
done.await();
} else {
if (!done.await(timeout, unit)) {
throw new MqttTimeoutException(String.format("Timed out waiting %d %s for command %s", timeout, unit, getClass().getSimpleName()));
}
}
} catch (InterruptedException e) {
throw new MqttInterruptedException(e);
}
if (failCause != null) {
if (failCause instanceof RuntimeException) {
throw (RuntimeException) failCause;
}
if (failCause instanceof Error) {
throw (Error) failCause;
}
throw new RuntimeException("Unexpected exception. This is a bug!", failCause);
}
return returnValue;
}
/**
* @see net.sf.xenqtt.message.BlockingCommand#execute()
*/
@Override
public final void execute() {
try {
returnValue = doExecute();
} catch (RuntimeException e) {
failCause = e;
} catch (Exception e) {
failCause = new MqttException(e);
} catch (Error e) {
failCause = e;
}
}
/**
* @see net.sf.xenqtt.message.BlockingCommand#complete(java.lang.Throwable)
*/
@Override
public final void complete(Throwable failCause) {
if (this.failCause == null && failCause != null) {
if (failCause instanceof RuntimeException) {
this.failCause = failCause;
} else if (failCause instanceof Exception) {
this.failCause = new MqttException(failCause);
} else {
this.failCause = failCause;
}
}
done.countDown();
}
/**
* Extensions implement this method to execute the command
*
* @return The value returned by the command
* @throws Exception
* Any exception thrown by the command
*/
protected abstract T doExecute() throws Exception;
}
|
fixed minor bug in AbstractBlockingChannel.await()
|
src/main/java/net/sf/xenqtt/message/AbstractBlockingCommand.java
|
fixed minor bug in AbstractBlockingChannel.await()
|
<ide><path>rc/main/java/net/sf/xenqtt/message/AbstractBlockingCommand.java
<ide> */
<ide> @Override
<ide> public final T await() throws MqttInterruptedException {
<del> return await(0, TimeUnit.DAYS);
<add> return await(Long.MAX_VALUE, TimeUnit.DAYS);
<ide> }
<ide>
<ide> /**
|
|
Java
|
apache-2.0
|
329ac65a94426ad795d6780c8b7b379e177be0ad
| 0 |
jpodeszwik/mifos,AArhin/head,jpodeszwik/mifos,AArhin/head,jpodeszwik/mifos,maduhu/head,maduhu/head,maduhu/head,jpodeszwik/mifos,AArhin/head,maduhu/head,AArhin/head,AArhin/head,maduhu/head
|
/*
* Copyright (c) 2005-2011 Grameen Foundation USA
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.test.acceptance.framework;
import com.thoughtworks.selenium.Selenium;
import com.thoughtworks.selenium.SeleniumException;
import org.testng.Assert;
/**
* Base class for all Page objects -
* There should be a Page object for each page referenced in an Selenium-based acceptance test.
* Page objects should be the place that all verification and navigation is done,
* to keep this activity in one place. If the web page changes, then only one class
* needs to change to make all the tests that reference it work.
*/
public class AbstractPage {
private static final String MAX_WAIT_FOR_PAGE_TO_LOAD_IN_MILLISECONDS = "30000";
protected Selenium selenium;
public AbstractPage() {
// do nothing
}
public AbstractPage(Selenium selenium) {
this.selenium = selenium;
}
protected void waitForPageToLoad() {
selenium.waitForPageToLoad(MAX_WAIT_FOR_PAGE_TO_LOAD_IN_MILLISECONDS);
}
final public void setSelenium(Selenium selenium) {
this.selenium = selenium;
}
public Selenium getSelenium() {
return this.selenium;
}
public void openUri(String uri) {
selenium.open(uri);
waitForPageToLoad();
}
public void verifyPage(String pageName) {
String pageId = selenium.getAttribute("page.id@title");
if("Exception".equals(pageId)){
String stackTrace = selenium.getText("css=div.stackTrace pre");
Assert.fail("Expected page <" +pageName +">, actual page <"+pageId+">!!! with error message > " + stackTrace);
}
else if(!pageId.equals(pageName)) {
String errors = getErrors();
Assert.fail("Expected page <" +pageName +">, actual page <"+pageId+">!!! with error message > " + errors);
}
}
public String getErrors() {
int totalErrorElements = selenium.getXpathCount("//*[contains(@id, \'error.message\')]").intValue();
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= totalErrorElements; i++) {
String text = selenium.getText("//*[contains(@id, \'error.message\')][" + i + "]");
if (text != null) {
sb.append(text);
}
}
return sb.toString();
}
public String getTextIfExists(String locator) {
String text = null;
try {
text = selenium.getText("error.messages");
} catch (SeleniumException se) { // NOPMD by ugupta on 15/3/11 10:16 PM
// do nothing
}
return text;
}
public void verifyPage(String pageName, String secondName) {
String pageID = selenium.getAttribute("page.id@title");
if(!pageID.equals(pageName)) {
Assert.assertEquals(pageID, secondName);
}
}
public void typeText(String locator, String text) {
selenium.focus(locator);
selenium.type(locator,text);
// selenium.keyDown(locator, tabKey);
// selenium.keyUp(locator, tabKey);
selenium.keyPressNative("9");
}
public void waitForElementToPresent(String locator){
selenium.waitForCondition("selenium.isElementPresent(\"" + locator + "\")",MAX_WAIT_FOR_PAGE_TO_LOAD_IN_MILLISECONDS);
}
public void navigateBack(){
selenium.goBack();
}
}
|
testFramework/src/main/java/org/mifos/test/acceptance/framework/AbstractPage.java
|
/*
* Copyright (c) 2005-2011 Grameen Foundation USA
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.test.acceptance.framework;
import com.thoughtworks.selenium.Selenium;
import com.thoughtworks.selenium.SeleniumException;
import org.testng.Assert;
/**
* Base class for all Page objects -
* There should be a Page object for each page referenced in an Selenium-based acceptance test.
* Page objects should be the place that all verification and navigation is done,
* to keep this activity in one place. If the web page changes, then only one class
* needs to change to make all the tests that reference it work.
*/
public class AbstractPage {
private static final String MAX_WAIT_FOR_PAGE_TO_LOAD_IN_MILLISECONDS = "30000";
protected Selenium selenium;
public AbstractPage() {
// do nothing
}
public AbstractPage(Selenium selenium) {
this.selenium = selenium;
}
protected void waitForPageToLoad() {
selenium.waitForPageToLoad(MAX_WAIT_FOR_PAGE_TO_LOAD_IN_MILLISECONDS);
}
final public void setSelenium(Selenium selenium) {
this.selenium = selenium;
}
public Selenium getSelenium() {
return this.selenium;
}
public void openUri(String uri) {
selenium.open(uri);
waitForPageToLoad();
}
public void verifyPage(String pageName) {
String pageId = selenium.getAttribute("page.id@title");
if(pageId.equals("Exception")){
String stackTrace = selenium.getText("css=div.stackTrace pre");
Assert.fail("Expected page <" +pageName +">, actual page <"+pageId+">!!! with error message > " + stackTrace);
}
else if(!pageId.equals(pageName)) {
String errors = getErrors();
Assert.fail("Expected page <" +pageName +">, actual page <"+pageId+">!!! with error message > " + errors);
}
}
public String getErrors() {
int totalErrorElements = selenium.getXpathCount("//*[contains(@id, \'error.message\')]").intValue();
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= totalErrorElements; i++) {
String text = selenium.getText("//*[contains(@id, \'error.message\')][" + i + "]");
if (text != null) {
sb.append(text);
}
}
return sb.toString();
}
public String getTextIfExists(String locator) {
String text = null;
try {
text = selenium.getText("error.messages");
} catch (SeleniumException se) { // NOPMD by ugupta on 15/3/11 10:16 PM
// do nothing
}
return text;
}
public void verifyPage(String pageName, String secondName) {
String pageID = selenium.getAttribute("page.id@title");
if(!pageID.equals(pageName)) {
Assert.assertEquals(pageID, secondName);
}
}
public void typeText(String locator, String text) {
selenium.focus(locator);
selenium.type(locator,text);
// selenium.keyDown(locator, tabKey);
// selenium.keyUp(locator, tabKey);
selenium.keyPressNative("9");
}
public void waitForElementToPresent(String locator){
selenium.waitForCondition("selenium.isElementPresent(\"" + locator + "\")",MAX_WAIT_FOR_PAGE_TO_LOAD_IN_MILLISECONDS);
}
public void navigateBack(){
selenium.goBack();
}
}
|
PMD error fix.
|
testFramework/src/main/java/org/mifos/test/acceptance/framework/AbstractPage.java
|
PMD error fix.
|
<ide><path>estFramework/src/main/java/org/mifos/test/acceptance/framework/AbstractPage.java
<ide>
<ide> public void verifyPage(String pageName) {
<ide> String pageId = selenium.getAttribute("page.id@title");
<del> if(pageId.equals("Exception")){
<add> if("Exception".equals(pageId)){
<ide> String stackTrace = selenium.getText("css=div.stackTrace pre");
<ide> Assert.fail("Expected page <" +pageName +">, actual page <"+pageId+">!!! with error message > " + stackTrace);
<ide> }
|
|
Java
|
lgpl-2.1
|
f2e26fdaf59e72f0638767bd7843b1a6700a9199
| 0 |
wesley1001/orbeon-forms,evlist/orbeon-forms,martinluther/orbeon-forms,ajw625/orbeon-forms,brunobuzzi/orbeon-forms,orbeon/orbeon-forms,joansmith/orbeon-forms,wesley1001/orbeon-forms,wesley1001/orbeon-forms,orbeon/orbeon-forms,martinluther/orbeon-forms,brunobuzzi/orbeon-forms,evlist/orbeon-forms,joansmith/orbeon-forms,evlist/orbeon-forms,ajw625/orbeon-forms,wesley1001/orbeon-forms,tanbo800/orbeon-forms,joansmith/orbeon-forms,joansmith/orbeon-forms,martinluther/orbeon-forms,orbeon/orbeon-forms,ajw625/orbeon-forms,tanbo800/orbeon-forms,martinluther/orbeon-forms,brunobuzzi/orbeon-forms,tanbo800/orbeon-forms,ajw625/orbeon-forms,tanbo800/orbeon-forms,evlist/orbeon-forms,orbeon/orbeon-forms,evlist/orbeon-forms,brunobuzzi/orbeon-forms
|
/**
* Copyright (C) 2004 Orbeon, Inc.
*
* This program 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 program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
*/
package org.orbeon.oxf.processor;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.orbeon.oxf.cache.InternalCacheKey;
import org.orbeon.oxf.cache.ObjectCache;
import org.orbeon.oxf.cache.OutputCacheKey;
import org.orbeon.oxf.common.OXFException;
import org.orbeon.oxf.common.ValidationException;
import org.orbeon.oxf.pipeline.api.ExternalContext;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.resources.ResourceManagerWrapper;
import org.orbeon.oxf.resources.URLFactory;
import org.orbeon.oxf.util.LoggerFactory;
import org.orbeon.oxf.util.SystemUtils;
import org.orbeon.oxf.xml.dom4j.LocationData;
import org.xml.sax.ContentHandler;
import java.io.*;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;
import java.util.*;
/**
* The Java processor dynamically creates processors by compiling Java files on the fly.
*/
public class JavaProcessor extends ProcessorImpl {
static private Logger logger = LoggerFactory.createLogger(JavaProcessor.class);
private final static String PATH_SEPARATOR = System.getProperty("path.separator");
public static final String JARPATH_PROPERTY = "jarpath";
public static final String CLASSPATH_PROPERTY = "classpath";
public static final String COMPILER_CLASS_PROPERTY = "compiler-class";
public static final String COMPILER_JAR_PROPERTY = "compiler-jar";
public static final String DEFAULT_COMPILER_MAIN = "com.sun.tools.javac.Main";
public static final String JAVA_CONFIG_NAMESPACE_URI = "http://www.orbeon.org/oxf/xml/java";
public JavaProcessor() {
addInputInfo(new ProcessorInputOutputInfo(INPUT_CONFIG, JAVA_CONFIG_NAMESPACE_URI));
}
public ProcessorOutput createOutput(final String name) {
ProcessorOutput output = new ProcessorImpl.ProcessorOutputImpl(getClass(), name) {
public void readImpl(PipelineContext context, ContentHandler contentHandler) {
getInput(context).getOutput().read(context, contentHandler);
}
public OutputCacheKey getKeyImpl(PipelineContext context) {
return isInputInCache(context, INPUT_CONFIG)
? getInputKey(context, getInput(context)) : null;
}
public Object getValidityImpl(PipelineContext context) {
return isInputInCache(context, INPUT_CONFIG)
? getInputValidity(context, getInput(context)) : null;
}
private ProcessorInput getInput(PipelineContext context) {
start(context);
State state = (State) getState(context);
return (ProcessorInput) state.bottomInputs.get(name);
}
};
addOutput(name, output);
return output;
}
public void start(PipelineContext context) {
State state = (State) getState(context);
if (!state.started) {
Processor processor = JavaProcessor.this.getProcessor(context);
// Check user processor does not have a config input
for (Iterator i = processor.getInputsInfo().iterator(); i.hasNext();) {
final ProcessorInputOutputInfo inputInfo = (ProcessorInputOutputInfo) i.next();
if (inputInfo.getName().equals(INPUT_CONFIG))
throw new OXFException("Processor used by Java processor cannot have a config input");
}
Map inputMap = getConnectedInputs();
for (Iterator i = inputMap.keySet().iterator(); i.hasNext();) {
String inputName = (String) i.next();
List inputsForName = (List) inputMap.get(inputName);
for (Iterator j = inputsForName.iterator(); j.hasNext();) {
final ProcessorInput javaProcessorInput = (ProcessorInput) j.next();
// Skip our own config input
if (inputName.equals(INPUT_CONFIG))
continue;
// Delegate
ProcessorInput userProcessorInput = processor.createInput(inputName);
ProcessorOutput topOutput = new ProcessorImpl.ProcessorOutputImpl(getClass(), inputName) {
protected void readImpl(PipelineContext context, ContentHandler contentHandler) {
javaProcessorInput.getOutput().read(context, contentHandler);
}
};
// Connect
userProcessorInput.setOutput(topOutput);
topOutput.setInput(userProcessorInput);
}
}
boolean hasOutputs = false;
Map outputMap = getConnectedOutputs();
// Connect processor outputs
for (Iterator i = outputMap.keySet().iterator(); i.hasNext();) {
hasOutputs = true;
String outputName = (String) i.next();
ProcessorOutput processorOutput = processor.createOutput(outputName);
ProcessorInput bottomInput = new ProcessorImpl.ProcessorInputImpl(getClass(), outputName);
processorOutput.setInput(bottomInput);
bottomInput.setOutput(processorOutput);
state.bottomInputs.put(outputName, bottomInput);
}
// Start processor if required
if (!hasOutputs) {
processor.start(context);
}
state.started = true;
}
}
private Processor getProcessor(PipelineContext context) {
try {
// Read config input into a String, cache if possible
ProcessorInput input = getInputByName(INPUT_CONFIG);
final Config config = (Config) readCacheInputAsObject(context, input, new CacheableInputReader() {
public Object read(PipelineContext context, ProcessorInput input) {
Document configDocument = readInputAsDOM4J(context, INPUT_CONFIG);
Element configElement = configDocument.getRootElement();
Config config = new Config();
config.clazz = configElement.attributeValue("class");
// Get source path
String sourcePathAttributeValue = configElement.attributeValue("sourcepath");
if (sourcePathAttributeValue == null)
sourcePathAttributeValue = ".";
File sourcePath = getFileFromURL(sourcePathAttributeValue, JavaProcessor.this.getLocationData());
if (!sourcePath.isDirectory())
throw new ValidationException("Invalid sourcepath attribute: cannot find directory for URL: " + sourcePathAttributeValue, (LocationData) configElement.getData());
try {
config.sourcepath = sourcePath.getCanonicalPath();
} catch (IOException e) {
throw new ValidationException("Invalid sourcepath attribute: cannot find directory for URL: " + sourcePathAttributeValue, (LocationData) configElement.getData());
}
return config;
}
});
// Check if need to compile
String sourceFile = config.sourcepath + "/" + config.clazz.replace('.', '/') + ".java";
String destinationDirectory = SystemUtils.getTemporaryDirectory().getAbsolutePath();
String destinationFile = destinationDirectory + "/" + config.clazz.replace('.', '/') + ".class";
boolean fileUpToDate = new File(sourceFile).lastModified() < new File(destinationFile).lastModified();
// Compile
if (!fileUpToDate) {
StringWriter javacOutput = new StringWriter();
final ArrayList argLst = new ArrayList();
final String[] cmdLine;
{
argLst.add("-g");
final String cp = buildClassPath(context);
if (cp != null) {
argLst.add("-classpath");
argLst.add(cp);
}
if (config.sourcepath != null && config.sourcepath.length() > 0) {
argLst.add("-sourcepath");
argLst.add(config.sourcepath);
}
argLst.add("-d");
final File tmp = SystemUtils.getTemporaryDirectory();
final String tmpPth = tmp.getAbsolutePath();
argLst.add(tmpPth);
final String fnam = config.sourcepath + "/"
+ config.clazz.replace('.', '/') + ".java";
argLst.add(fnam);
cmdLine = new String[argLst.size()];
argLst.toArray(cmdLine);
}
if (logger.isDebugEnabled()) {
logger.debug("Compiling class '" + config.clazz + "'");
logger.debug("javac " + argLst.toString());
}
Throwable thrown = null;
int exitCode = 1;
try {
// Get compiler class, either user-specified or default to Sun compiler
String compilerMain = getPropertySet().getString(COMPILER_CLASS_PROPERTY, DEFAULT_COMPILER_MAIN);
ClassLoader classLoader;
{
URL compilerJarURL = getPropertySet().getURL(COMPILER_JAR_PROPERTY);
if (compilerJarURL != null) {
// 1: Always honor user-specified compiler JAR if present
// Use special class loader pointing to this URL
classLoader = new URLClassLoader(new URL[]{compilerJarURL}, JavaProcessor.class.getClassLoader());
if (logger.isDebugEnabled())
logger.debug("Java processor using user-specified compiler JAR: " + compilerJarURL.toExternalForm());
} else {
// 2: Try to use the class loader that loaded this class
classLoader = JavaProcessor.class.getClassLoader();
try {
Class.forName(compilerMain, true, classLoader);
logger.debug("Java processor using current class loader");
} catch (ClassNotFoundException e) {
// Class not found
// 3: Try to get to Sun tools.jar
String javaHome = System.getProperty("java.home");
if (javaHome != null) {
File javaHomeFile = new File(javaHome);
if (javaHomeFile.getName().equals("jre")) {
File toolsFile = new File(javaHomeFile.getParentFile(), "lib" + File.separator + "tools.jar");
if (toolsFile.exists()) {
// JAR file exists, will use it to load compiler class
classLoader = new URLClassLoader(new URL[]{toolsFile.toURL()}, JavaProcessor.class.getClassLoader());
if (logger.isDebugEnabled())
logger.debug("Java processor using default tools.jar under " + toolsFile.toString());
}
}
}
}
}
}
// Load compiler class using class loader defined above
Class compilerClass = Class.forName(compilerMain, true, classLoader);
// Get method and run compiler
Method compileMethod = compilerClass.getMethod("compile", new Class[]{String[].class, PrintWriter.class});
Object result = compileMethod.invoke(null, new Object[]{cmdLine, new PrintWriter(javacOutput)});
exitCode = ((Integer) result).intValue();
} catch (final Throwable t) {
thrown = t;
}
if (exitCode != 0) {
String javacOutputString = "\n" + javacOutput.toString();
javacOutputString = StringUtils.replace(javacOutputString, "\n", "\n ");
throw new OXFException("Error compiling '" + argLst.toString() + "'" + javacOutputString, thrown);
}
}
// Try to get sourcepath info
InternalCacheKey sourcepathKey = new InternalCacheKey(JavaProcessor.this, "javaFile", config.sourcepath);
Object sourcepathValidity = new Long(0);
Sourcepath sourcepath = (Sourcepath) ObjectCache.instance()
.findValid(context, sourcepathKey, sourcepathValidity);
// Create classloader
if (sourcepath == null || (sourcepath.callNameToProcessorClass.containsKey(config.clazz) && !fileUpToDate)) {
if (logger.isDebugEnabled())
logger.debug("Creating classloader for sourcepath '" + config.sourcepath + "'");
sourcepath = new Sourcepath();
sourcepath.classLoader = new URLClassLoader
(new URL[]{SystemUtils.getTemporaryDirectory().toURL(), new File(config.sourcepath).toURL()},
this.getClass().getClassLoader());
ObjectCache.instance().add(context, sourcepathKey, sourcepathValidity, sourcepath);
}
// Get processor class
Class processorClass = (Class) sourcepath.callNameToProcessorClass.get(config.clazz);
if (processorClass == null) {
processorClass = sourcepath.classLoader.loadClass(config.clazz);
sourcepath.callNameToProcessorClass.put(config.clazz, processorClass);
}
// Create processor from class
Thread.currentThread().setContextClassLoader(processorClass.getClassLoader());
return (Processor) processorClass.newInstance();
} catch (final IOException e) {
throw new OXFException(e);
} catch (final IllegalAccessException e) {
throw new OXFException(e);
} catch (final InstantiationException e) {
throw new OXFException(e);
} catch (final ClassNotFoundException e) {
throw new OXFException(e);
}
}
/**
* Return a File object based on an URL string that can be relative to the specified
* LocationData. The protocols supported are "oxf:" and "file:". If the file doesn't exist, an
* exception is thrown.
*/
public static File getFileFromURL(String urlString, LocationData locationData) {
URL sourcePathURL;
{
try {
// Resolve relative URLs
sourcePathURL = (locationData != null && locationData.getSystemID() != null)
? URLFactory.createURL(locationData.getSystemID(), urlString)
: URLFactory.createURL(urlString);
} catch (MalformedURLException e) {
throw new ValidationException("Invalid sourcepath attribute: '" + urlString + "'", e, locationData);
}
}
// Make sure the protocol is oxf: or file:
if (sourcePathURL.getProtocol().equals("file")) {
String fileName = sourcePathURL.getFile();
File file = new File(fileName);
if (!file.exists()) {
// Try to decode only if we cannot find the file
try {
fileName = URLDecoder.decode(fileName, "utf-8");
} catch (UnsupportedEncodingException e) {
// Should not happen
throw new ValidationException(e, locationData);
}
file = new File(fileName);
if (!file.exists())
throw new ValidationException("Invalid sourcepath attribute: cannot find resource for URL: " + urlString, locationData);
}
return file;
} else if (sourcePathURL.getProtocol().equals("oxf")) {
// Get real path to source path
String path = sourcePathURL.getFile();
return new File(ResourceManagerWrapper.instance().getRealPath(path));
} else {
throw new ValidationException("Invalid sourcepath attribute: '" + urlString
+ "'. The Java processor only supports the oxf: and file: protocols for the sourcepath attribute.", locationData);
}
}
private String buildClassPath(PipelineContext context) throws UnsupportedEncodingException {
StringBuffer classpath = new StringBuffer();
StringBuffer jarpath = new StringBuffer();
String propJarpath = getPropertySet().getString(JARPATH_PROPERTY);
String propClasspath = getPropertySet().getString(CLASSPATH_PROPERTY);
// Add class path from properties if available
if (propClasspath != null)
classpath.append(propClasspath).append(PATH_SEPARATOR);
// Add JAR path from properties if available
if (propJarpath != null)
jarpath.append(propJarpath).append(PATH_SEPARATOR);
// Add JAR path and class path from webapp if available
ExternalContext externalContext = (ExternalContext) context.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
boolean gotLibDir = false;
if (externalContext != null) {
String webInfLibPath = externalContext.getRealPath("WEB-INF/lib");
if (webInfLibPath != null) {
jarpath.append(webInfLibPath).append(PATH_SEPARATOR);
gotLibDir = true;
}
String webInfClasses = externalContext.getRealPath("WEB-INF/classes");
if (webInfClasses != null)
classpath.append(webInfClasses).append(PATH_SEPARATOR);
}
// Get class path based on class loader hierarchy
{
final String pathFromLoaders = SystemUtils.pathFromLoaders(JavaProcessor.class);
classpath.append(pathFromLoaders);
if (!pathFromLoaders.endsWith(File.pathSeparator))
classpath.append(File.pathSeparatorChar);
}
if (!gotLibDir) {
// WEB-INF/lib was not found, this SHOULD mean we are running from the command-line or
// embedded rather than in a regular web app
// Try to add directory containing current JAR file
String pathToCurrentJarDir = SystemUtils.getJarPath(getClass());
if (pathToCurrentJarDir != null) {
if (logger.isDebugEnabled())
logger.debug("Found current JAR directory: " + pathToCurrentJarDir);
jarpath.append(pathToCurrentJarDir).append(PATH_SEPARATOR);
}
}
for (StringTokenizer tokenizer = new StringTokenizer(jarpath.toString(), PATH_SEPARATOR); tokenizer.hasMoreElements();) {
String path = tokenizer.nextToken();
// Find jars in path
File[] jars = new File(path).listFiles(new FileFilter() {
public boolean accept(File pathname) {
String absolutePath = pathname.getAbsolutePath();
return absolutePath.endsWith(".jar") || absolutePath.endsWith(".zip");
}
});
// Add them to string buffer
if (jars != null) {
for (int i = 0; i < jars.length; i++)
classpath.append(jars[i].getAbsolutePath()).append(PATH_SEPARATOR);
}
}
if (logger.isDebugEnabled())
logger.debug("Classpath: " + classpath.toString());
return classpath.length() == 0 ? null : classpath.toString();
}
public void reset(PipelineContext context) {
setState(context, new State());
}
private static class Config {
public String sourcepath;
public String clazz;
}
private static class State {
public boolean started = false;
public Map bottomInputs = new HashMap();
}
private static class Sourcepath {
public ClassLoader classLoader;
public Map callNameToProcessorClass = new HashMap();
}
}
|
src/java/org/orbeon/oxf/processor/JavaProcessor.java
|
/**
* Copyright (C) 2004 Orbeon, Inc.
*
* This program 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 program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
*/
package org.orbeon.oxf.processor;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.orbeon.oxf.cache.InternalCacheKey;
import org.orbeon.oxf.cache.ObjectCache;
import org.orbeon.oxf.cache.OutputCacheKey;
import org.orbeon.oxf.common.OXFException;
import org.orbeon.oxf.common.ValidationException;
import org.orbeon.oxf.pipeline.api.ExternalContext;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.resources.ResourceManagerWrapper;
import org.orbeon.oxf.resources.URLFactory;
import org.orbeon.oxf.util.LoggerFactory;
import org.orbeon.oxf.util.SystemUtils;
import org.orbeon.oxf.xml.dom4j.LocationData;
import org.xml.sax.ContentHandler;
import java.io.*;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;
import java.util.*;
/**
* The Java processor dynamically creates processors by compiling Java files on the fly.
*/
public class JavaProcessor extends ProcessorImpl {
static private Logger logger = LoggerFactory.createLogger(JavaProcessor.class);
private final static String PATH_SEPARATOR = System.getProperty("path.separator");
public static final String JARPATH_PROPERTY = "jarpath";
public static final String CLASSPATH_PROPERTY = "classpath";
public static final String COMPILER_CLASS_PROPERTY = "compiler-class";
public static final String COMPILER_JAR_PROPERTY = "compiler-jar";
public static final String DEFAULT_COMPILER_MAIN = "com.sun.tools.javac.Main";
public static final String JAVA_CONFIG_NAMESPACE_URI = "http://www.orbeon.org/oxf/xml/java";
public JavaProcessor() {
addInputInfo(new ProcessorInputOutputInfo(INPUT_CONFIG, JAVA_CONFIG_NAMESPACE_URI));
addOutputInfo(new ProcessorInputOutputInfo(OUTPUT_DATA)); // Why do we have this? Is this a mistake?
}
public ProcessorOutput createOutput(final String name) {
ProcessorOutput output = new ProcessorImpl.ProcessorOutputImpl(getClass(), name) {
public void readImpl(PipelineContext context, ContentHandler contentHandler) {
getInput(context).getOutput().read(context, contentHandler);
}
public OutputCacheKey getKeyImpl(PipelineContext context) {
return isInputInCache(context, INPUT_CONFIG)
? getInputKey(context, getInput(context)) : null;
}
public Object getValidityImpl(PipelineContext context) {
return isInputInCache(context, INPUT_CONFIG)
? getInputValidity(context, getInput(context)) : null;
}
private ProcessorInput getInput(PipelineContext context) {
start(context);
State state = (State) getState(context);
return (ProcessorInput) state.bottomInputs.get(name);
}
};
addOutput(name, output);
return output;
}
public void start(PipelineContext context) {
State state = (State) getState(context);
if (!state.started) {
Processor processor = JavaProcessor.this.getProcessor(context);
// Check user processor does not have a config input
for (Iterator i = processor.getInputsInfo().iterator(); i.hasNext();) {
final ProcessorInputOutputInfo inputInfo = (ProcessorInputOutputInfo) i.next();
if (inputInfo.getName().equals(INPUT_CONFIG))
throw new OXFException("Processor used by Java processor cannot have a config input");
}
Map inputMap = getConnectedInputs();
for (Iterator i = inputMap.keySet().iterator(); i.hasNext();) {
String inputName = (String) i.next();
List inputsForName = (List) inputMap.get(inputName);
for (Iterator j = inputsForName.iterator(); j.hasNext();) {
final ProcessorInput javaProcessorInput = (ProcessorInput) j.next();
// Skip our own config input
if (inputName.equals(INPUT_CONFIG))
continue;
// Delegate
ProcessorInput userProcessorInput = processor.createInput(inputName);
ProcessorOutput topOutput = new ProcessorImpl.ProcessorOutputImpl(getClass(), inputName) {
protected void readImpl(PipelineContext context, ContentHandler contentHandler) {
javaProcessorInput.getOutput().read(context, contentHandler);
}
};
// Connect
userProcessorInput.setOutput(topOutput);
topOutput.setInput(userProcessorInput);
}
}
boolean hasOutputs = false;
Map outputMap = getConnectedOutputs();
// Connect processor outputs
for (Iterator i = outputMap.keySet().iterator(); i.hasNext();) {
hasOutputs = true;
String outputName = (String) i.next();
ProcessorOutput processorOutput = processor.createOutput(outputName);
ProcessorInput bottomInput = new ProcessorImpl.ProcessorInputImpl(getClass(), outputName);
processorOutput.setInput(bottomInput);
bottomInput.setOutput(processorOutput);
state.bottomInputs.put(outputName, bottomInput);
}
// Start processor if required
if (!hasOutputs) {
processor.start(context);
}
state.started = true;
}
}
private Processor getProcessor(PipelineContext context) {
try {
// Read config input into a String, cache if possible
ProcessorInput input = getInputByName(INPUT_CONFIG);
final Config config = (Config) readCacheInputAsObject(context, input, new CacheableInputReader() {
public Object read(PipelineContext context, ProcessorInput input) {
Document configDocument = readInputAsDOM4J(context, INPUT_CONFIG);
Element configElement = configDocument.getRootElement();
Config config = new Config();
config.clazz = configElement.attributeValue("class");
// Get source path
String sourcePathAttributeValue = configElement.attributeValue("sourcepath");
if (sourcePathAttributeValue == null)
sourcePathAttributeValue = ".";
File sourcePath = getFileFromURL(sourcePathAttributeValue, JavaProcessor.this.getLocationData());
if (!sourcePath.isDirectory())
throw new ValidationException("Invalid sourcepath attribute: cannot find directory for URL: " + sourcePathAttributeValue, (LocationData) configElement.getData());
try {
config.sourcepath = sourcePath.getCanonicalPath();
} catch (IOException e) {
throw new ValidationException("Invalid sourcepath attribute: cannot find directory for URL: " + sourcePathAttributeValue, (LocationData) configElement.getData());
}
return config;
}
});
// Check if need to compile
String sourceFile = config.sourcepath + "/" + config.clazz.replace('.', '/') + ".java";
String destinationDirectory = SystemUtils.getTemporaryDirectory().getAbsolutePath();
String destinationFile = destinationDirectory + "/" + config.clazz.replace('.', '/') + ".class";
boolean fileUpToDate = new File(sourceFile).lastModified() < new File(destinationFile).lastModified();
// Compile
if (!fileUpToDate) {
StringWriter javacOutput = new StringWriter();
final ArrayList argLst = new ArrayList();
final String[] cmdLine;
{
argLst.add("-g");
final String cp = buildClassPath(context);
if (cp != null) {
argLst.add("-classpath");
argLst.add(cp);
}
if (config.sourcepath != null && config.sourcepath.length() > 0) {
argLst.add("-sourcepath");
argLst.add(config.sourcepath);
}
argLst.add("-d");
final File tmp = SystemUtils.getTemporaryDirectory();
final String tmpPth = tmp.getAbsolutePath();
argLst.add(tmpPth);
final String fnam = config.sourcepath + "/"
+ config.clazz.replace('.', '/') + ".java";
argLst.add(fnam);
cmdLine = new String[argLst.size()];
argLst.toArray(cmdLine);
}
if (logger.isDebugEnabled()) {
logger.debug("Compiling class '" + config.clazz + "'");
logger.debug("javac " + argLst.toString());
}
Throwable thrown = null;
int exitCode = 1;
try {
// Get compiler class, either user-specified or default to Sun compiler
String compilerMain = getPropertySet().getString(COMPILER_CLASS_PROPERTY, DEFAULT_COMPILER_MAIN);
ClassLoader classLoader;
{
URL compilerJarURL = getPropertySet().getURL(COMPILER_JAR_PROPERTY);
if (compilerJarURL != null) {
// 1: Always honor user-specified compiler JAR if present
// Use special class loader pointing to this URL
classLoader = new URLClassLoader(new URL[]{compilerJarURL}, JavaProcessor.class.getClassLoader());
if (logger.isDebugEnabled())
logger.debug("Java processor using user-specified compiler JAR: " + compilerJarURL.toExternalForm());
} else {
// 2: Try to use the class loader that loaded this class
classLoader = JavaProcessor.class.getClassLoader();
try {
Class.forName(compilerMain, true, classLoader);
logger.debug("Java processor using current class loader");
} catch (ClassNotFoundException e) {
// Class not found
// 3: Try to get to Sun tools.jar
String javaHome = System.getProperty("java.home");
if (javaHome != null) {
File javaHomeFile = new File(javaHome);
if (javaHomeFile.getName().equals("jre")) {
File toolsFile = new File(javaHomeFile.getParentFile(), "lib" + File.separator + "tools.jar");
if (toolsFile.exists()) {
// JAR file exists, will use it to load compiler class
classLoader = new URLClassLoader(new URL[]{toolsFile.toURL()}, JavaProcessor.class.getClassLoader());
if (logger.isDebugEnabled())
logger.debug("Java processor using default tools.jar under " + toolsFile.toString());
}
}
}
}
}
}
// Load compiler class using class loader defined above
Class compilerClass = Class.forName(compilerMain, true, classLoader);
// Get method and run compiler
Method compileMethod = compilerClass.getMethod("compile", new Class[]{String[].class, PrintWriter.class});
Object result = compileMethod.invoke(null, new Object[]{cmdLine, new PrintWriter(javacOutput)});
exitCode = ((Integer) result).intValue();
} catch (final Throwable t) {
thrown = t;
}
if (exitCode != 0) {
String javacOutputString = "\n" + javacOutput.toString();
javacOutputString = StringUtils.replace(javacOutputString, "\n", "\n ");
throw new OXFException("Error compiling '" + argLst.toString() + "'" + javacOutputString, thrown);
}
}
// Try to get sourcepath info
InternalCacheKey sourcepathKey = new InternalCacheKey(JavaProcessor.this, "javaFile", config.sourcepath);
Object sourcepathValidity = new Long(0);
Sourcepath sourcepath = (Sourcepath) ObjectCache.instance()
.findValid(context, sourcepathKey, sourcepathValidity);
// Create classloader
if (sourcepath == null || (sourcepath.callNameToProcessorClass.containsKey(config.clazz) && !fileUpToDate)) {
if (logger.isDebugEnabled())
logger.debug("Creating classloader for sourcepath '" + config.sourcepath + "'");
sourcepath = new Sourcepath();
sourcepath.classLoader = new URLClassLoader
(new URL[]{SystemUtils.getTemporaryDirectory().toURL(), new File(config.sourcepath).toURL()},
this.getClass().getClassLoader());
ObjectCache.instance().add(context, sourcepathKey, sourcepathValidity, sourcepath);
}
// Get processor class
Class processorClass = (Class) sourcepath.callNameToProcessorClass.get(config.clazz);
if (processorClass == null) {
processorClass = sourcepath.classLoader.loadClass(config.clazz);
sourcepath.callNameToProcessorClass.put(config.clazz, processorClass);
}
// Create processor from class
Thread.currentThread().setContextClassLoader(processorClass.getClassLoader());
return (Processor) processorClass.newInstance();
} catch (final IOException e) {
throw new OXFException(e);
} catch (final IllegalAccessException e) {
throw new OXFException(e);
} catch (final InstantiationException e) {
throw new OXFException(e);
} catch (final ClassNotFoundException e) {
throw new OXFException(e);
}
}
/**
* Return a File object based on an URL string that can be relative to the specified
* LocationData. The protocols supported are "oxf:" and "file:". If the file doesn't exist, an
* exception is thrown.
*/
public static File getFileFromURL(String urlString, LocationData locationData) {
URL sourcePathURL;
{
try {
// Resolve relative URLs
sourcePathURL = (locationData != null && locationData.getSystemID() != null)
? URLFactory.createURL(locationData.getSystemID(), urlString)
: URLFactory.createURL(urlString);
} catch (MalformedURLException e) {
throw new ValidationException("Invalid sourcepath attribute: '" + urlString + "'", e, locationData);
}
}
// Make sure the protocol is oxf: or file:
if (sourcePathURL.getProtocol().equals("file")) {
String fileName = sourcePathURL.getFile();
File file = new File(fileName);
if (!file.exists()) {
// Try to decode only if we cannot find the file
try {
fileName = URLDecoder.decode(fileName, "utf-8");
} catch (UnsupportedEncodingException e) {
// Should not happen
throw new ValidationException(e, locationData);
}
file = new File(fileName);
if (!file.exists())
throw new ValidationException("Invalid sourcepath attribute: cannot find resource for URL: " + urlString, locationData);
}
return file;
} else if (sourcePathURL.getProtocol().equals("oxf")) {
// Get real path to source path
String path = sourcePathURL.getFile();
return new File(ResourceManagerWrapper.instance().getRealPath(path));
} else {
throw new ValidationException("Invalid sourcepath attribute: '" + urlString
+ "'. The Java processor only supports the oxf: and file: protocols for the sourcepath attribute.", locationData);
}
}
private String buildClassPath(PipelineContext context) throws UnsupportedEncodingException {
StringBuffer classpath = new StringBuffer();
StringBuffer jarpath = new StringBuffer();
String propJarpath = getPropertySet().getString(JARPATH_PROPERTY);
String propClasspath = getPropertySet().getString(CLASSPATH_PROPERTY);
// Add class path from properties if available
if (propClasspath != null)
classpath.append(propClasspath).append(PATH_SEPARATOR);
// Add JAR path from properties if available
if (propJarpath != null)
jarpath.append(propJarpath).append(PATH_SEPARATOR);
// Add JAR path and class path from webapp if available
ExternalContext externalContext = (ExternalContext) context.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
boolean gotLibDir = false;
if (externalContext != null) {
String webInfLibPath = externalContext.getRealPath("WEB-INF/lib");
if (webInfLibPath != null) {
jarpath.append(webInfLibPath).append(PATH_SEPARATOR);
gotLibDir = true;
}
String webInfClasses = externalContext.getRealPath("WEB-INF/classes");
if (webInfClasses != null)
classpath.append(webInfClasses).append(PATH_SEPARATOR);
}
// Get class path based on class loader hierarchy
{
final String pathFromLoaders = SystemUtils.pathFromLoaders(JavaProcessor.class);
classpath.append(pathFromLoaders);
if (!pathFromLoaders.endsWith(File.pathSeparator))
classpath.append(File.pathSeparatorChar);
}
if (!gotLibDir) {
// WEB-INF/lib was not found, this SHOULD mean we are running from the command-line or
// embedded rather than in a regular web app
// Try to add directory containing current JAR file
String pathToCurrentJarDir = SystemUtils.getJarPath(getClass());
if (pathToCurrentJarDir != null) {
if (logger.isDebugEnabled())
logger.debug("Found current JAR directory: " + pathToCurrentJarDir);
jarpath.append(pathToCurrentJarDir).append(PATH_SEPARATOR);
}
}
for (StringTokenizer tokenizer = new StringTokenizer(jarpath.toString(), PATH_SEPARATOR); tokenizer.hasMoreElements();) {
String path = tokenizer.nextToken();
// Find jars in path
File[] jars = new File(path).listFiles(new FileFilter() {
public boolean accept(File pathname) {
String absolutePath = pathname.getAbsolutePath();
return absolutePath.endsWith(".jar") || absolutePath.endsWith(".zip");
}
});
// Add them to string buffer
if (jars != null) {
for (int i = 0; i < jars.length; i++)
classpath.append(jars[i].getAbsolutePath()).append(PATH_SEPARATOR);
}
}
if (logger.isDebugEnabled())
logger.debug("Classpath: " + classpath.toString());
return classpath.length() == 0 ? null : classpath.toString();
}
public void reset(PipelineContext context) {
setState(context, new State());
}
private static class Config {
public String sourcepath;
public String clazz;
}
private static class State {
public boolean started = false;
public Map bottomInputs = new HashMap();
}
private static class Sourcepath {
public ClassLoader classLoader;
public Map callNameToProcessorClass = new HashMap();
}
}
|
Fix [ #305038 ] Java processor cannot be used with not output
|
src/java/org/orbeon/oxf/processor/JavaProcessor.java
|
Fix [ #305038 ] Java processor cannot be used with not output
|
<ide><path>rc/java/org/orbeon/oxf/processor/JavaProcessor.java
<ide>
<ide> public JavaProcessor() {
<ide> addInputInfo(new ProcessorInputOutputInfo(INPUT_CONFIG, JAVA_CONFIG_NAMESPACE_URI));
<del> addOutputInfo(new ProcessorInputOutputInfo(OUTPUT_DATA)); // Why do we have this? Is this a mistake?
<ide> }
<ide>
<ide> public ProcessorOutput createOutput(final String name) {
|
|
JavaScript
|
mit
|
85014a4f6c7617b69f5b5b7449129b86f955fbf3
| 0 |
agusdiyansyah/mustache.js,jfmercer/mustache.js,AshWilliams/mustache.js,Ricardh522/mustache.js,laomu1988/mustache.js,aaron-goshine/mustache.js,Jeremy017/mustache.js,agusdiyansyah/mustache.js,xinliuruoxi/mustache.js,kamalbhatia/mustache.js,Jeremy017/mustache.js,AshWilliams/mustache.js,bengl/mustache.js,janl/mustache.js,xinliuruoxi/mustache.js,bengl/mustache.js,cgvarela/mustache.js,xiaowuzhu/mustache.js,emersion/mustache.js,carsonwright/mustache.js,Ricardh522/mustache.js,bengl/mustache.js,Jeremy017/mustache.js,xinliuruoxi/mustache.js,280455936/mustache.js,wjbryant/mustache.js,ivantcholakov/mustache.js,evdevgit/mustache.js,dasilvacontin/mustache.js,qweasd1/mustache.js,jfmercer/mustache.js,damyon/mustache.js,fbiz/mustache.js,janl/mustache.js,kamalbhatia/mustache.js,raine/mustache.js,laomu1988/mustache.js,fbiz/mustache.js,emersion/mustache.js,aaron-goshine/mustache.js,jlodijk/mustache.js,emersion/mustache.js,Ricardh522/mustache.js,damyon/mustache.js,djchie/mustache.js,ivantcholakov/mustache.js,carsonwright/mustache.js,mikekavouras/mustache.js,mikekavouras/mustache.js,xiaowuzhu/mustache.js,AshWilliams/mustache.js,cgvarela/mustache.js,dasilvacontin/mustache.js,dasilvacontin/mustache.js,evdevgit/mustache.js,jfmercer/mustache.js,cgvarela/mustache.js,raine/mustache.js,kamalbhatia/mustache.js,janl/mustache.js,damyon/mustache.js,srrvnn/mustache.js,bengl/mustache.js,wjbryant/mustache.js,agusdiyansyah/mustache.js,ivantcholakov/mustache.js,xinliuruoxi/mustache.js,srrvnn/mustache.js,qweasd1/mustache.js,jfmercer/mustache.js,wjbryant/mustache.js,xiaowuzhu/mustache.js,dasilvacontin/mustache.js,aaron-goshine/mustache.js,jlodijk/mustache.js,hahaguo/mustache.js,evdevgit/mustache.js,aaron-goshine/mustache.js,280455936/mustache.js,kamalbhatia/mustache.js,evdevgit/mustache.js,280455936/mustache.js,srrvnn/mustache.js,phillipj/mustache.js,ivantcholakov/mustache.js,mikekavouras/mustache.js,djchie/mustache.js,mikekavouras/mustache.js,damyon/mustache.js,raine/mustache.js,janl/mustache.js,djchie/mustache.js,wjbryant/mustache.js,phillipj/mustache.js,phillipj/mustache.js,Jeremy017/mustache.js,srrvnn/mustache.js,hahaguo/mustache.js,fbiz/mustache.js,280455936/mustache.js,AshWilliams/mustache.js,hahaguo/mustache.js,Ricardh522/mustache.js,cgvarela/mustache.js,qweasd1/mustache.js,hahaguo/mustache.js,carsonwright/mustache.js,djchie/mustache.js,raine/mustache.js,phillipj/mustache.js,phillipj/mustache.js,qweasd1/mustache.js,janl/mustache.js,laomu1988/mustache.js,agusdiyansyah/mustache.js,emersion/mustache.js,xiaowuzhu/mustache.js,fbiz/mustache.js,jlodijk/mustache.js,laomu1988/mustache.js,carsonwright/mustache.js,jlodijk/mustache.js
|
var assert = require("assert");
var vows = require("vows");
var Writer = require("./../mustache").Writer;
vows.describe("Mustache.Writer").addBatch({
"A Writer": {
topic: function () {
var writer = new Writer();
return writer;
},
"loads partials correctly": function (writer) {
var partial = "The content of the partial.";
var result = writer.render("{{>partial}}", {}, function (name) {
assert.equal(name, "partial");
return partial;
});
assert.equal(result, partial);
},
"caches partials by content, not by name": function (writer) {
var result = writer.render("{{>partial}}", {}, {
partial: "partial one"
});
assert.equal(result, "partial one");
result = writer.render("{{>partial}}", {}, {
partial: "partial two"
});
assert.equal(result, "partial two");
}
}
}).export(module);
|
test/writer_test.js
|
var assert = require("assert");
var vows = require("vows");
var Writer = require("./../mustache").Writer;
vows.describe("Mustache.Writer").addBatch({
"A Writer": {
topic: function () {
var writer = new Writer();
return writer;
},
"loads partials correctly": function (writer) {
var partial = "The content of the partial.";
var result = writer.render("{{>partial}}", {}, function (name) {
assert.equal(name, "partial");
return partial;
});
assert.equal(result, partial);
}
}
}).export(module);
|
Add spec for partial caching issue
|
test/writer_test.js
|
Add spec for partial caching issue
|
<ide><path>est/writer_test.js
<ide> });
<ide>
<ide> assert.equal(result, partial);
<add> },
<add> "caches partials by content, not by name": function (writer) {
<add> var result = writer.render("{{>partial}}", {}, {
<add> partial: "partial one"
<add> });
<add>
<add> assert.equal(result, "partial one");
<add>
<add> result = writer.render("{{>partial}}", {}, {
<add> partial: "partial two"
<add> });
<add>
<add> assert.equal(result, "partial two");
<ide> }
<ide> }
<ide> }).export(module);
|
|
Java
|
mit
|
0986d27f8ca519edf1d5d21ed6b4239921e8ed15
| 0 |
fredyw/leetcode,fredyw/leetcode,fredyw/leetcode,fredyw/leetcode
|
package leetcode;
import java.util.Arrays;
/**
* https://leetcode.com/problems/beautiful-arrangement-ii/
*/
public class Problem667 {
public int[] constructArray(int n, int k) {
int[] result = new int[n];
int idx = 0;
for (int i = 0; i < n; i++) {
if (i == 0) {
result[idx++] = i + 1;
continue;
}
if (k > 0) {
int a = result[i - 1] - k;
if (a <= 0) {
a = result[i - 1] + k;
}
result[idx++] = a;
k--;
} else {
result[idx++] = result[i - 1] + 1;
}
}
return result;
}
public static void main(String[] args) {
Problem667 prob = new Problem667();
System.out.println(Arrays.toString(prob.constructArray(3, 1))); // [1,2,3]
System.out.println(Arrays.toString(prob.constructArray(3, 2))); // [1,3,2]
System.out.println(Arrays.toString(prob.constructArray(10, 9))); // [1,10,2,9,3,8,4,7,5,6]
System.out.println(Arrays.toString(prob.constructArray(10, 5))); // [1,6,2,5,3,4,7,8,9,10]
}
}
|
src/main/java/leetcode/Problem667.java
|
package leetcode;
/**
* https://leetcode.com/problems/beautiful-arrangement-ii/
*/
public class Problem667 {
public int[] constructArray(int n, int k) {
// TODO
return null;
}
public static void main(String[] args) {
Problem667 prob = new Problem667();
System.out.println(prob.constructArray(3, 1)); // [1,2,3]
System.out.println(prob.constructArray(3, 2)); // [1,3,2]
System.out.println(prob.constructArray(10, 9)); // [1,10,2,9,3,8,4,7,5,6]
System.out.println(prob.constructArray(10, 5)); // [1,6,2,5,3,4,7,8,9,10]
}
}
|
Update problem 667
|
src/main/java/leetcode/Problem667.java
|
Update problem 667
|
<ide><path>rc/main/java/leetcode/Problem667.java
<ide> package leetcode;
<add>
<add>import java.util.Arrays;
<ide>
<ide> /**
<ide> * https://leetcode.com/problems/beautiful-arrangement-ii/
<ide> */
<ide> public class Problem667 {
<ide> public int[] constructArray(int n, int k) {
<del> // TODO
<del> return null;
<add> int[] result = new int[n];
<add> int idx = 0;
<add> for (int i = 0; i < n; i++) {
<add> if (i == 0) {
<add> result[idx++] = i + 1;
<add> continue;
<add> }
<add> if (k > 0) {
<add> int a = result[i - 1] - k;
<add> if (a <= 0) {
<add> a = result[i - 1] + k;
<add> }
<add> result[idx++] = a;
<add> k--;
<add> } else {
<add> result[idx++] = result[i - 1] + 1;
<add> }
<add> }
<add> return result;
<ide> }
<ide>
<ide> public static void main(String[] args) {
<ide> Problem667 prob = new Problem667();
<del> System.out.println(prob.constructArray(3, 1)); // [1,2,3]
<del> System.out.println(prob.constructArray(3, 2)); // [1,3,2]
<del> System.out.println(prob.constructArray(10, 9)); // [1,10,2,9,3,8,4,7,5,6]
<del> System.out.println(prob.constructArray(10, 5)); // [1,6,2,5,3,4,7,8,9,10]
<add> System.out.println(Arrays.toString(prob.constructArray(3, 1))); // [1,2,3]
<add> System.out.println(Arrays.toString(prob.constructArray(3, 2))); // [1,3,2]
<add> System.out.println(Arrays.toString(prob.constructArray(10, 9))); // [1,10,2,9,3,8,4,7,5,6]
<add> System.out.println(Arrays.toString(prob.constructArray(10, 5))); // [1,6,2,5,3,4,7,8,9,10]
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
error: pathspec 'PL2/PL2-core/src/main/java/nl/tudelft/pl2016gr2/core/algorithms/SplitGraphs.java' did not match any file(s) known to git
|
6ccb71a4a1bca4887ef1fe56be9d66c7689685b2
| 1 |
ProgrammingLife2016/PL2-2016
|
package nl.tudelft.pl2016gr2.core.algorithms;
import nl.tudelft.pl2016gr2.model.Node;
import nl.tudelft.pl2016gr2.model.OriginalGraph;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Provides functionality for extracting a subgraph of a sequence graph based on a subset of
* genomes.
* <p>
* The resulting subgraph will provide the following characteristics.
* <ul>
* <li>The nodes in the subgraph are a subset of the nodes in the original graph.</li>
* <li>The nodes in the subgraph will have an identical ID as their counterparts in the original
* graph.</li>
* <li>The nodes will be newly instantiated, meaning that the subgraph datastructure is not backed
* by the original graph.</li>
* </ul>
* </p>
*
* @author Wouter Smit
*/
public class SplitGraphs {
private OriginalGraph mainGraph;
/**
* Instantiates an algorithmic class on a <code>OriginalGraph</code>.
* <p>
* When {@link #getSubgraph(Collection)} is called, the class will construct a new instance of
* the
* graph containing only the specified genomes.
* </p>
*
* @param mainGraph The graph to split
*/
public SplitGraphs(OriginalGraph mainGraph) {
this.mainGraph = mainGraph;
}
/**
* Builds a subgraph of the {@link #mainGraph} containing only the nodes that contain (at least)
* one of the specified genomes.
*
* @param genomes The genomes that should be included in the resulting graph
* @return An <code>OriginalGraph</code> that is a subgraph of <code>mainGraph</code>
* @throws NoSuchElementException Iff the genome collection is not a
* subset of the main graph's genomes.
*/
public OriginalGraph getSubgraph(Collection<String> genomes) {
if (!mainGraph.getGenoms().containsAll(genomes)) {
throw new NoSuchElementException("All genomes must present in the main graph.");
}
OriginalGraph subGraph = buildSubgraph(genomes);
return prune(subGraph);
}
/**
* Creates a new graph containing only the nodes that will be part of the subGraph.
* <p>
* The nodes are not a deep copy, however the graph object is newly instantiated.
* </p>
*
* @param genomes The genomes that should be included in the subgraph
* @return The subgraph
*/
private OriginalGraph buildSubgraph(Collection<String> genomes) {
OriginalGraph subGraph = new OriginalGraph();
// Add all nodes for every genome
for (String genome : genomes) {
Iterator<Node> iterator = mainGraph.iterator(genome);
// add genome root
subGraph.addNode(iterator.next());
while (iterator.hasNext()) {
subGraph.addNode(iterator.next());
}
}
return subGraph;
}
/**
* Removes all redundant links from the nodes in the graph.
* <p>
* Redundant links are links that point to a {@link Node} that is not part of the subgraph.
* The method will return a new {@link OriginalGraph} object with new <code>Node</code>s.
* The Nodes will contain identical fields, except for the {@link Node#inLinks} and {@link
* Node#outLinks}.
* </p>
* <p>
* While this method is intended solely for subgraphs, it will provide the same behaviour when
* called with any graph.
* </p>
*
* @param graph The graph to prune.
* @return A new <code>OriginalGraph</code> with only the relevant links.
*/
private OriginalGraph prune(OriginalGraph graph) {
// TODO: Should be refactored to be accessible from the GraphInterface
HashMap<Integer, Node> nodeMap = graph.getNodes();
// Create new mirror graph
OriginalGraph pruned = new OriginalGraph();
for (Node node : nodeMap.values()) {
// Create mirror of original Node.
// TODO: Remove non-existent genomes from Node.genomes
Node mirrorNode = new Node(node.getId(), node.getSequenceLength(), node.getGenomes(),
node.getSnips());
// Add the correct in/out links
node.getInlinks().forEach((inLink) -> {
if (nodeMap.containsKey(inLink)) {
mirrorNode.addInlink(inLink);
}
});
node.getOutlinks().forEach((outLink) -> {
if (nodeMap.containsKey(outLink)) {
mirrorNode.addOutlink(outLink);
}
});
}
return pruned;
}
}
|
PL2/PL2-core/src/main/java/nl/tudelft/pl2016gr2/core/algorithms/SplitGraphs.java
|
Create SplitGraphs algorithm
Fixes: https://github.com/ProgrammingLife2016/PL2-2016/issues/24
|
PL2/PL2-core/src/main/java/nl/tudelft/pl2016gr2/core/algorithms/SplitGraphs.java
|
Create SplitGraphs algorithm
|
<ide><path>L2/PL2-core/src/main/java/nl/tudelft/pl2016gr2/core/algorithms/SplitGraphs.java
<add>package nl.tudelft.pl2016gr2.core.algorithms;
<add>
<add>import nl.tudelft.pl2016gr2.model.Node;
<add>import nl.tudelft.pl2016gr2.model.OriginalGraph;
<add>
<add>import java.util.Collection;
<add>import java.util.HashMap;
<add>import java.util.Iterator;
<add>import java.util.NoSuchElementException;
<add>
<add>/**
<add> * Provides functionality for extracting a subgraph of a sequence graph based on a subset of
<add> * genomes.
<add> * <p>
<add> * The resulting subgraph will provide the following characteristics.
<add> * <ul>
<add> * <li>The nodes in the subgraph are a subset of the nodes in the original graph.</li>
<add> * <li>The nodes in the subgraph will have an identical ID as their counterparts in the original
<add> * graph.</li>
<add> * <li>The nodes will be newly instantiated, meaning that the subgraph datastructure is not backed
<add> * by the original graph.</li>
<add> * </ul>
<add> * </p>
<add> *
<add> * @author Wouter Smit
<add> */
<add>public class SplitGraphs {
<add>
<add> private OriginalGraph mainGraph;
<add>
<add> /**
<add> * Instantiates an algorithmic class on a <code>OriginalGraph</code>.
<add> * <p>
<add> * When {@link #getSubgraph(Collection)} is called, the class will construct a new instance of
<add> * the
<add> * graph containing only the specified genomes.
<add> * </p>
<add> *
<add> * @param mainGraph The graph to split
<add> */
<add> public SplitGraphs(OriginalGraph mainGraph) {
<add> this.mainGraph = mainGraph;
<add> }
<add>
<add>
<add> /**
<add> * Builds a subgraph of the {@link #mainGraph} containing only the nodes that contain (at least)
<add> * one of the specified genomes.
<add> *
<add> * @param genomes The genomes that should be included in the resulting graph
<add> * @return An <code>OriginalGraph</code> that is a subgraph of <code>mainGraph</code>
<add> * @throws NoSuchElementException Iff the genome collection is not a
<add> * subset of the main graph's genomes.
<add> */
<add> public OriginalGraph getSubgraph(Collection<String> genomes) {
<add> if (!mainGraph.getGenoms().containsAll(genomes)) {
<add> throw new NoSuchElementException("All genomes must present in the main graph.");
<add> }
<add> OriginalGraph subGraph = buildSubgraph(genomes);
<add> return prune(subGraph);
<add> }
<add>
<add> /**
<add> * Creates a new graph containing only the nodes that will be part of the subGraph.
<add> * <p>
<add> * The nodes are not a deep copy, however the graph object is newly instantiated.
<add> * </p>
<add> *
<add> * @param genomes The genomes that should be included in the subgraph
<add> * @return The subgraph
<add> */
<add> private OriginalGraph buildSubgraph(Collection<String> genomes) {
<add> OriginalGraph subGraph = new OriginalGraph();
<add> // Add all nodes for every genome
<add> for (String genome : genomes) {
<add> Iterator<Node> iterator = mainGraph.iterator(genome);
<add> // add genome root
<add> subGraph.addNode(iterator.next());
<add>
<add> while (iterator.hasNext()) {
<add> subGraph.addNode(iterator.next());
<add> }
<add>
<add> }
<add> return subGraph;
<add> }
<add>
<add>
<add> /**
<add> * Removes all redundant links from the nodes in the graph.
<add> * <p>
<add> * Redundant links are links that point to a {@link Node} that is not part of the subgraph.
<add> * The method will return a new {@link OriginalGraph} object with new <code>Node</code>s.
<add> * The Nodes will contain identical fields, except for the {@link Node#inLinks} and {@link
<add> * Node#outLinks}.
<add> * </p>
<add> * <p>
<add> * While this method is intended solely for subgraphs, it will provide the same behaviour when
<add> * called with any graph.
<add> * </p>
<add> *
<add> * @param graph The graph to prune.
<add> * @return A new <code>OriginalGraph</code> with only the relevant links.
<add> */
<add> private OriginalGraph prune(OriginalGraph graph) {
<add> // TODO: Should be refactored to be accessible from the GraphInterface
<add> HashMap<Integer, Node> nodeMap = graph.getNodes();
<add> // Create new mirror graph
<add> OriginalGraph pruned = new OriginalGraph();
<add>
<add> for (Node node : nodeMap.values()) {
<add> // Create mirror of original Node.
<add> // TODO: Remove non-existent genomes from Node.genomes
<add> Node mirrorNode = new Node(node.getId(), node.getSequenceLength(), node.getGenomes(),
<add> node.getSnips());
<add> // Add the correct in/out links
<add> node.getInlinks().forEach((inLink) -> {
<add> if (nodeMap.containsKey(inLink)) {
<add> mirrorNode.addInlink(inLink);
<add> }
<add> });
<add> node.getOutlinks().forEach((outLink) -> {
<add> if (nodeMap.containsKey(outLink)) {
<add> mirrorNode.addOutlink(outLink);
<add> }
<add> });
<add> }
<add> return pruned;
<add> }
<add>}
|
|
JavaScript
|
mit
|
9496d08c9092e528c51e7f8c36259647fac17288
| 0 |
js-coder/cookie.js,js-coder/cookie.js,florian/cookie.js
|
module.exports = function(grunt) {
grunt.initConfig({
meta: {
banner: grunt.file.read('cookie.js').split('\n')[0]
},
lint: {
all: ['grunt.js', 'cookie.js']
},
jshint: {
options: {
browser: true,
evil: false,
expr: true,
supernew: true,
eqeqeq: true,
eqnull: true,
forin: true,
smarttabs: true
}
},
mocha: {
all: 'tests/index.html',
run: true
},
min: {
dist: {
src: ['<banner>', 'cookie.js'],
dest: 'cookie.min.js'
}
},
watch: {
files: ['cookie.js'],
tasks: 'development'
}
});
grunt.loadNpmTasks('grunt-mocha');
grunt.registerTask('default', 'lint min');
grunt.registerTask('development', 'lint');
};
|
grunt.js
|
module.exports = function(grunt) {
grunt.initConfig({
meta: {
banner: grunt.file.read('cookie.js').split('\n')[0]
},
lint: {
all: ['grunt.js', 'cookie.js']
},
jshint: {
options: {
browser: true,
evil: false,
expr: true,
supernew: true,
eqeqeq: true,
eqnull: true,
forin: true,
smarttabs: true
}
},
min: {
dist: {
src: ['<banner>', 'cookie.js'],
dest: 'cookie.min.js'
}
},
watch: {
files: ['cookie.js'],
tasks: 'development'
}
});
grunt.registerTask('default', 'lint min');
grunt.registerTask('development', 'lint');
};
|
add mocha task
|
grunt.js
|
add mocha task
|
<ide><path>runt.js
<ide> }
<ide> },
<ide>
<add> mocha: {
<add> all: 'tests/index.html',
<add> run: true
<add> },
<add>
<ide> min: {
<ide> dist: {
<ide> src: ['<banner>', 'cookie.js'],
<ide>
<ide> });
<ide>
<add> grunt.loadNpmTasks('grunt-mocha');
<add>
<ide> grunt.registerTask('default', 'lint min');
<ide> grunt.registerTask('development', 'lint');
<ide>
|
|
Java
|
apache-2.0
|
5c939641bf87f390c2ae2d8dbdf6f06f56b0215f
| 0 |
OpenHFT/Chronicle-Queue,OpenHFT/Chronicle-Queue
|
/*
* Copyright 2016 higherfrequencytrading.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 net.openhft.chronicle.queue.impl.single;
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.bytes.BytesStore;
import net.openhft.chronicle.bytes.MappedBytes;
import net.openhft.chronicle.bytes.WriteBytesMarshallable;
import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.Maths;
import net.openhft.chronicle.core.annotation.UsedViaReflection;
import net.openhft.chronicle.core.io.IORuntimeException;
import net.openhft.chronicle.core.util.StringUtils;
import net.openhft.chronicle.queue.*;
import net.openhft.chronicle.queue.impl.ExcerptContext;
import net.openhft.chronicle.queue.impl.RollingChronicleQueue;
import net.openhft.chronicle.queue.impl.WireStore;
import net.openhft.chronicle.wire.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.EOFException;
import java.io.IOException;
import java.io.StreamCorruptedException;
import java.nio.BufferOverflowException;
import java.text.ParseException;
import java.util.concurrent.TimeoutException;
import static net.openhft.chronicle.queue.TailerDirection.BACKWARD;
import static net.openhft.chronicle.queue.TailerDirection.FORWARD;
import static net.openhft.chronicle.queue.TailerState.*;
import static net.openhft.chronicle.queue.impl.single.ScanResult.FOUND;
import static net.openhft.chronicle.queue.impl.single.ScanResult.NOT_FOUND;
public class SingleChronicleQueueExcerpts {
private static final Logger LOG = LoggerFactory.getLogger(SingleChronicleQueueExcerpts.class);
@FunctionalInterface
interface WireWriter<T> {
void write(T message, WireOut wireOut);
}
// *************************************************************************
//
// APPENDERS
//
// *************************************************************************
public interface InternalAppender {
void writeBytes(long index, BytesStore bytes);
}
/**
* // StoreAppender
*/
static class StoreAppender implements ExcerptAppender, ExcerptContext, InternalAppender {
@NotNull
private final SingleChronicleQueue queue;
private final StoreAppenderContext context;
WireStore store;
private int cycle = Integer.MIN_VALUE;
private Wire wire;
private Wire bufferWire; // if you have a buffered write.
private Wire wireForIndex;
private long position = 0;
private volatile Thread appendingThread = null;
private long lastIndex = Long.MIN_VALUE;
private boolean lazyIndexing = false;
private long lastPosition;
private int lastCycle;
private PretoucherState pretoucher = null;
private Padding padToCacheLines = Padding.SMART;
StoreAppender(@NotNull SingleChronicleQueue queue) {
this.queue = queue;
queue.addCloseListener(this, StoreAppender::close);
context = new StoreAppenderContext();
}
public Padding padToCacheAlign() {
return padToCacheLines;
}
/**
* @param padToCacheLines the default for chronicle queue is Padding.SMART, which
* automatically pads all method calls other than {@link
* StoreAppender#writeBytes(net.openhft.chronicle.bytes.WriteBytesMarshallable)}
* and {@link StoreAppender#writeText(java.lang.CharSequence)}.
* Which can not be padded with out changing the message format, The
* reason we pad is to ensure that a message header does not straggle
* a cache line.
*/
public void padToCacheAlign(Padding padToCacheLines) {
this.padToCacheLines = padToCacheLines;
}
/**
* @param marshallable to write to excerpt.
*/
public void writeBytes(@NotNull WriteBytesMarshallable marshallable) throws UnrecoverableTimeoutException {
try (DocumentContext dc = writingDocument()) {
marshallable.writeMarshallable(dc.wire().bytes());
if (padToCacheAlign() != Padding.ALWAYS)
((StoreAppenderContext) dc).padToCacheAlign = false;
}
}
@Override
public void writeText(CharSequence text) throws UnrecoverableTimeoutException {
try (DocumentContext dc = writingDocument()) {
dc.wire().bytes()
.append8bit(text);
if (padToCacheAlign() != Padding.ALWAYS)
((StoreAppenderContext) dc).padToCacheAlign = false;
}
}
void close() {
Wire w0 = wireForIndex;
wireForIndex = null;
if (w0 != null)
w0.bytes().release();
Wire w = wire;
wire = null;
if (w != null)
w.bytes().release();
if (store != null)
queue.release(store);
store = null;
}
@Override
public void pretouch() {
setCycle(queue.cycle(), true);
if (pretoucher == null)
pretoucher = new PretoucherState(() -> this.store.writePosition());
Wire wire = this.wire;
if (wire != null)
pretoucher.pretouch((MappedBytes) wire.bytes());
}
@Override
public Wire wire() {
return wire;
}
@Override
public Wire wireForIndex() {
return wireForIndex;
}
@Override
public long timeoutMS() {
return queue.timeoutMS;
}
void lastIndex(long index) {
this.lastIndex = index;
}
@Override
public ExcerptAppender lazyIndexing(boolean lazyIndexing) {
this.lazyIndexing = lazyIndexing;
resetPosition();
return this;
}
@Override
public boolean lazyIndexing() {
return lazyIndexing;
}
@Override
public boolean recordHistory() {
return sourceId() != 0;
}
private void setCycle(int cycle, boolean createIfAbsent) {
if (cycle != this.cycle)
setCycle2(cycle, createIfAbsent);
}
private void setCycle2(int cycle, boolean createIfAbsent) {
if (cycle < 0)
throw new IllegalArgumentException("You can not have a cycle that starts " +
"before Epoch. cycle=" + cycle);
SingleChronicleQueue queue = this.queue;
if (this.store != null)
queue.release(this.store);
this.store = queue.storeForCycle(cycle, queue.epoch(), createIfAbsent);
resetWires(queue);
// only set the cycle after the wire is set.
this.cycle = cycle;
assert wire.startUse();
wire.parent(this);
wire.pauser(queue.pauserSupplier.get());
resetPosition();
queue.onRoll(cycle);
}
private void resetWires(SingleChronicleQueue queue) {
WireType wireType = queue.wireType();
{
Wire oldw = this.wire;
this.wire = wireType.apply(store.bytes());
if (oldw != null)
oldw.bytes().release();
}
{
Wire old = this.wireForIndex;
this.wireForIndex = wireType.apply(store.bytes());
if (old != null)
old.bytes().release();
}
}
private void resetPosition() throws UnrecoverableTimeoutException {
try {
if (store == null || wire == null)
return;
position(store.writePosition());
Bytes<?> bytes = wire.bytes();
int header = bytes.readVolatileInt(position);
assert position == 0 || Wires.isReadyData(header);
bytes.writePosition(position + 4 + Wires.lengthOf(header));
if (lazyIndexing) {
wire.headerNumber(Long.MIN_VALUE);
return;
}
final long headerNumber = store.sequenceForPosition(this, position, true);
wire.headerNumber(queue.rollCycle().toIndex(cycle, headerNumber + 1) - 1);
assert lazyIndexing || wire.headerNumber() != -1 || checkIndex(wire.headerNumber(), position);
} catch (BufferOverflowException | StreamCorruptedException e) {
throw new AssertionError(e);
}
assert checkWritePositionHeaderNumber();
}
@Override
public DocumentContext writingDocument(boolean metaData) throws UnrecoverableTimeoutException {
assert checkAppendingThread();
assert checkWritePositionHeaderNumber();
boolean ok = false;
try {
int cycle = queue.cycle();
if (this.cycle != cycle || wire == null)
rollCycleTo(cycle);
int safeLength = (int) queue.overlapSize();
for (int i = 0; i < 128; i++) {
try {
assert wire != null;
long pos = store.writeHeader(wire, Wires.UNKNOWN_LENGTH, safeLength, timeoutMS());
position(pos);
context.isClosed = false;
context.wire = wire;
context.padToCacheAlign = padToCacheAlign() != Padding.NEVER;
context.metaData(metaData);
ok = true;
return context;
} catch (EOFException theySeeMeRolling) {
cycle = handleRoll(cycle);
}
}
throw new IllegalStateException("Unable to roll to the current cycle");
} finally {
if (!ok)
assert resetAppendingThread();
}
}
private int handleRoll(int cycle) {
assert !((AbstractWire) wire).isInsideHeader();
int qCycle = queue.cycle();
if (cycle < queue.cycle()) {
setCycle2(cycle = qCycle, true);
} else if (cycle == qCycle) {
// for the rare case where the qCycle has just changed in the last
// few milliseconds since
setCycle2(++cycle, true);
} else
throw new IllegalStateException("Found an EOF on the next cycle file," +
" this next file, should not have an EOF as its cycle " +
"number is greater than the current cycle (based on the " +
"current time), this should only happen " +
"if it " +
"was written by a different appender set with a different " +
"EPOC or different roll cycle." +
"All your appenders ( that write to a given directory ) " +
"should have the same EPOCH and roll cycle" +
" qCycle=" + qCycle + ", cycle=" + cycle);
return cycle;
}
boolean checkWritePositionHeaderNumber() {
if (wire == null || wire.headerNumber() == Long.MIN_VALUE) return true;
try {
long pos1 = position;
/*
long posMax = store.writePosition();
if (pos1 > posMax+4) {
System.out.println(queue.dump());
String message = "########### " +
"thread: " + Thread.currentThread().getName() +
" pos1: " + pos1 +
" posMax: " + posMax;
System.err.println(message);
throw new AssertionError(message);
}*/
long seq1 = queue.rollCycle().toSequenceNumber(wire.headerNumber() + 1) - 1;
long seq2 = store.sequenceForPosition(this, pos1, true);
if (seq1 != seq2) {
// System.out.println(queue.dump());
String message = "~~~~~~~~~~~~~~ " +
"thread: " + Thread.currentThread().getName() +
" pos1: " + pos1 +
" seq1: " + seq1 +
" seq2: " + seq2;
System.err.println(message);
throw new AssertionError(message);
}
} catch (IOException e) {
Jvm.fatal().on(getClass(), e);
throw Jvm.rethrow(e);
}
return true;
}
@Override
public DocumentContext writingDocument(long index) {
context.isClosed = false;
assert checkAppendingThread();
context.wire = acquireBufferWire();
context.wire.headerNumber(index);
context.isClosed = false;
return context;
}
@Override
public int sourceId() {
return queue.sourceId;
}
@Override
public void writeBytes(@NotNull BytesStore bytes) throws UnrecoverableTimeoutException {
// still uses append as it has a known length.
append(Maths.toUInt31(bytes.readRemaining()), (m, w) -> w.bytes().write(m), bytes);
}
Wire acquireBufferWire() {
if (bufferWire == null) {
bufferWire = queue.wireType().apply(Bytes.elasticByteBuffer());
} else {
bufferWire.clear();
}
return bufferWire;
}
@Override
public void writeBytes(long index, BytesStore bytes) {
if (index < 0)
throw new IllegalArgumentException("index: " + index);
if (bytes.isEmpty())
throw new UnsupportedOperationException("Cannot append a zero length message");
assert checkAppendingThread();
try {
moveToIndexForWrite(index);
// only get the bytes after moveToIndex
Bytes<?> wireBytes = wire.bytes();
try {
// wire.bytes().writePosition(store.writePosition());
int length = bytes.length();
// sets the position
wire.headerNumber(index);
position(store.writeHeader(wire, length, length, timeoutMS()));
wireBytes.write(bytes);
wire.updateHeader(length, position, false);
writeIndexForPosition(index, position);
lastIndex(index);
lastPosition = position;
lastCycle = cycle;
store.writePosition(position);
} catch (EOFException theySeeMeRolling) {
if (wireBytes.compareAndSwapInt(wireBytes.writePosition(), Wires.END_OF_DATA, Wires.NOT_COMPLETE)) {
wireBytes.write(bytes);
wire.updateHeader(0, position, false);
}
}
} catch (IllegalStateException ise) {
if (!ise.getMessage().contains("index already exists")) {
Jvm.warn().on(getClass(), "Ignoring duplicate", ise);
throw ise;
}
} catch (StreamCorruptedException | EOFException e) {
throw Jvm.rethrow(e);
} finally {
if (wire != null) {
Bytes<?> wireBytes = wire.bytes();
assert resetAppendingThread();
}
}
}
private void position(long position) {
if (position > store.writePosition() + queue.blockSize())
throw new IllegalArgumentException("pos: " + position + ", store.writePosition()=" +
store.writePosition() + " queue.blockSize()=" + queue.blockSize());
// System.err.println("----- "+Thread.currentThread().getName()+" pos: "+position);
this.position = position;
}
// only called for writeBytes(long index, BytesStore)
private void moveToIndexForWrite(long index) throws EOFException {
if (wire != null && wire.headerNumber() == index)
return;
int cycle = queue.rollCycle().toCycle(index);
ScanResult scanResult = moveToIndex(cycle, queue.rollCycle().toSequenceNumber(index));
switch (scanResult) {
case FOUND:
throw new IllegalStateException("Unable to move to index " + Long.toHexString(index) + " as the index already exists");
case NOT_REACHED:
throw new IllegalStateException("Unable to move to index " + Long.toHexString(index) + " beyond the end of the queue");
case NOT_FOUND:
break;
}
}
ScanResult moveToIndex(int cycle, long sequenceNumber) throws UnrecoverableTimeoutException {
if (LOG.isDebugEnabled()) {
Jvm.debug().on(getClass(), "moveToIndex: " + Long.toHexString(cycle) + " " + Long.toHexString(sequenceNumber));
}
if (this.cycle != cycle) {
if (cycle > this.cycle)
rollCycleTo(cycle);
else
setCycle2(cycle, true);
}
ScanResult scanResult = this.store.moveToIndexForRead(this, sequenceNumber);
Bytes<?> bytes = wire.bytes();
if (scanResult == NOT_FOUND) {
// so you won't read any if it ran out of data.
bytes.writePosition(bytes.readPosition());
return scanResult;
}
bytes.readLimit(bytes.readPosition());
return scanResult;
}
@Override
public long lastIndexAppended() {
if (lastIndex != Long.MIN_VALUE)
return lastIndex;
if (lastPosition == Long.MIN_VALUE || wire == null) {
throw new IllegalStateException("nothing has been appended, so there is no last index");
}
try {
long sequenceNumber = store.sequenceForPosition(this, lastPosition, true);
long index = queue.rollCycle().toIndex(lastCycle, sequenceNumber);
lastIndex(index);
return index;
} catch (Exception e) {
throw Jvm.rethrow(e);
}
}
@Override
public int cycle() {
if (cycle == Integer.MIN_VALUE) {
int cycle = this.queue.lastCycle();
if (cycle < 0)
cycle = queue.cycle();
setCycle2(cycle, true);
}
return cycle;
}
public SingleChronicleQueue queue() {
return queue;
}
/**
* overwritten in delta wire
*
* @param wire
* @param index
*/
void beforeAppend(Wire wire, long index) {
}
private <T> void append(int length, WireWriter<T> wireWriter, T writer) throws
UnrecoverableTimeoutException {
assert checkAppendingThread();
try {
int cycle = queue.cycle();
if (this.cycle != cycle || wire == null)
rollCycleTo(cycle);
try {
position(store.writeHeader(wire, length, length, timeoutMS()));
assert ((AbstractWire) wire).isInsideHeader();
beforeAppend(wire, wire.headerNumber() + 1);
wireWriter.write(writer, wire);
wire.updateHeader(length, position, false);
lastIndex(wire.headerNumber());
lastPosition = position;
lastCycle = cycle;
store.writePosition(position);
writeIndexForPosition(lastIndex, position);
} catch (EOFException theySeeMeRolling) {
try {
append2(length, wireWriter, writer);
} catch (EOFException e) {
throw new AssertionError(e);
}
}
} catch (StreamCorruptedException e) {
throw new AssertionError(e);
} finally {
assert resetAppendingThread();
}
}
private void rollCycleTo(int cycle) throws UnrecoverableTimeoutException {
if (this.cycle == cycle)
throw new AssertionError();
if (wire != null) {
try {
store.writeEOF(wire, timeoutMS());
} catch (TimeoutException e) {
Jvm.warn().on(SingleChronicleQueueExcerpts.class, "Unable to terminate the previous cycle, continuing", e);
}
}
setCycle2(cycle, true);
}
/**
* Write an EOF marker on the current cycle if it is about to roll. It would do this any way
* if a new message was written, but this doesn't create a new cycle or add a message.
*/
public void writeEndOfCycleIfRequired() {
if (wire != null && queue.cycle() != cycle) {
try {
store.writeEOF(wire, timeoutMS());
} catch (TimeoutException e) {
Jvm.warn().on(SingleChronicleQueueExcerpts.class, "Unable to terminate the previous cycle, continuing", e);
}
}
}
<T> void append2(int length, WireWriter<T> wireWriter, T writer) throws
UnrecoverableTimeoutException, EOFException, StreamCorruptedException {
setCycle(Math.max(queue.cycle(), cycle + 1), true);
position(store.writeHeader(wire, length, length, timeoutMS()));
beforeAppend(wire, wire.headerNumber() + 1);
wireWriter.write(writer, wire);
wire.updateHeader(length, position, false);
}
private boolean checkAppendingThread() {
Thread appendingThread = this.appendingThread;
Thread currentThread = Thread.currentThread();
if (appendingThread != null) {
if (appendingThread == currentThread)
throw new IllegalStateException("Nested blocks of writingDocument() not supported");
throw new IllegalStateException("Attempting to use Appender in " + currentThread + " while used by " + appendingThread);
}
this.appendingThread = currentThread;
return true;
}
private boolean resetAppendingThread() {
if (this.appendingThread == null)
throw new IllegalStateException("Attempting to release Appender in " + Thread.currentThread() + " but already released");
this.appendingThread = null;
return true;
}
void writeIndexForPosition(long index, long position)
throws UnrecoverableTimeoutException, StreamCorruptedException {
if (!lazyIndexing) {
long sequenceNumber = queue.rollCycle().toSequenceNumber(index);
store.setPositionForSequenceNumber(this, sequenceNumber, position);
}
}
boolean checkIndex(long index, long position) {
try {
final long seq1 = queue.rollCycle().toSequenceNumber(index + 1) - 1;
final long seq2 = store.sequenceForPosition(this, position, true);
if (seq1 != seq2) {
final long seq3 = ((SingleChronicleQueueStore) store).indexing
.linearScanByPosition(wireForIndex(), position, 0, 0, true);
System.out.println("Thread=" + Thread.currentThread().getName() +
" pos: " + position +
" seq1: " + Long.toHexString(seq1) +
" seq2: " + Long.toHexString(seq2) +
" seq3: " + Long.toHexString(seq3));
System.out.println(store.dump());
assert seq1 == seq3 : "seq1=" + seq1 + ", seq3=" + seq3;
assert seq1 == seq2 : "seq1=" + seq1 + ", seq2=" + seq2;
} else {
/* System.out.println("checked Thread=" + Thread.currentThread().getName() +
" pos: " + position +
" seq1: " + seq1);*/
}
} catch (EOFException | UnrecoverableTimeoutException | StreamCorruptedException e) {
throw new AssertionError(e);
}
return true;
}
class StoreAppenderContext implements DocumentContext {
boolean isClosed;
boolean padToCacheAlign = true;
private boolean metaData = false;
private Wire wire;
@Override
public int sourceId() {
return StoreAppender.this.sourceId();
}
@Override
public boolean isPresent() {
return false;
}
@Override
public Wire wire() {
return wire;
}
@Override
public boolean isMetaData() {
return metaData;
}
@Override
public void metaData(boolean metaData) {
this.metaData = metaData;
}
@Override
public boolean isClosed() {
return isClosed;
}
@Override
public void close() {
if (isClosed) {
LOG.warn("Already Closed, close was called twice.");
return;
}
try {
if (wire == StoreAppender.this.wire) {
if (padToCacheAlign)
wire.padToCacheAlign();
wire.updateHeader(position, metaData);
lastPosition = position;
lastCycle = cycle;
if (!metaData) {
lastIndex(wire.headerNumber());
store.writePosition(position);
if (lastIndex != Long.MIN_VALUE)
writeIndexForPosition(lastIndex, position);
else
assert lazyIndexing || lastIndex == Long.MIN_VALUE || checkIndex(lastIndex, position);
}
assert checkWritePositionHeaderNumber();
} else if (wire != null) {
isClosed = true;
assert resetAppendingThread();
writeBytes(wire.headerNumber(), wire.bytes());
wire = StoreAppender.this.wire;
}
} catch (StreamCorruptedException | UnrecoverableTimeoutException e) {
throw new IllegalStateException(e);
} finally {
assert isClosed || resetAppendingThread();
}
}
@Override
public long index() throws IORuntimeException {
if (this.wire.headerNumber() == Long.MIN_VALUE) {
try {
long headerNumber0 = queue.rollCycle().toIndex(cycle, store
.sequenceForPosition(StoreAppender.this, position, false));
assert (((AbstractWire) this.wire).isInsideHeader());
return isMetaData() ? headerNumber0 : headerNumber0 + 1;
} catch (IOException e) {
throw new IORuntimeException(e);
}
}
return isMetaData() ? Long.MIN_VALUE : this.wire.headerNumber() + 1;
}
@Override
public boolean isNotComplete() {
throw new UnsupportedOperationException();
}
}
}
// *************************************************************************
//
// TAILERS
//
// *************************************************************************
/**
* Tailer
*/
public static class StoreTailer implements ExcerptTailer, SourceContext, ExcerptContext {
@NotNull
private final SingleChronicleQueue queue;
private final StoreTailerContext context = new StoreTailerContext();
private final int indexSpacingMask;
long index; // index of the next read.
WireStore store;
private int cycle;
private long timeForNextCycle = Long.MAX_VALUE;
private TailerDirection direction = TailerDirection.FORWARD;
private boolean lazyIndexing = false;
private Wire wireForIndex;
private boolean readAfterReplicaAcknowledged;
private TailerState state = UNINITIALISED;
public StoreTailer(@NotNull final SingleChronicleQueue queue) {
this.queue = queue;
this.setCycle(Integer.MIN_VALUE);
this.index = 0;
queue.addCloseListener(this, StoreTailer::close);
indexSpacingMask = queue.rollCycle().defaultIndexSpacing() - 1;
}
private static boolean isReadOnly(Bytes bytes) {
return bytes instanceof MappedBytes &&
!((MappedBytes) bytes).mappedFile().file().canWrite();
}
public boolean readDocument(@NotNull ReadMarshallable reader) {
try (@NotNull DocumentContext dc = readingDocument(false)) {
if (!dc.isPresent())
return false;
reader.readMarshallable(dc.wire());
}
return true;
}
@NotNull
public DocumentContext readingDocument() {
return readingDocument(false);
}
private void close() {
context.wire(null);
Wire w0 = wireForIndex;
if (w0 != null)
w0.bytes().release();
if (store != null)
queue.release(store);
store = null;
}
@Override
public Wire wire() {
return context.wire();
}
@Override
public Wire wireForIndex() {
return wireForIndex;
}
@Override
public long timeoutMS() {
return queue.timeoutMS;
}
@Override
public int sourceId() {
return queue.sourceId;
}
@Override
public String toString() {
return "StoreTailer{" +
"index sequence=" + queue.rollCycle().toSequenceNumber(index) +
", index cycle=" + queue.rollCycle().toCycle(index) +
", store=" + store + ", queue=" + queue + '}';
}
@Override
public DocumentContext readingDocument(boolean includeMetaData) {
try {
boolean next = false, tryAgain = true;
if (state == FOUND_CYCLE) {
try {
next = inACycle(includeMetaData);
tryAgain = false;
} catch (EOFException eof) {
state = TailerState.END_OF_CYCLE;
}
}
if (tryAgain)
next = next0(includeMetaData);
if (context.present(next)) {
assert wire().startUse();
return context;
}
RollCycle rollCycle = queue.rollCycle();
;
if (state == CYCLE_NOT_FOUND && direction == FORWARD) {
int firstCycle = queue.firstCycle();
if (rollCycle.toCycle(index) < firstCycle)
toStart();
}
} catch (StreamCorruptedException e) {
throw new IllegalStateException(e);
} catch (UnrecoverableTimeoutException notComplete) {
// so treat as empty.
}
return NoDocumentContext.INSTANCE;
}
private boolean next0(boolean includeMetaData) throws UnrecoverableTimeoutException, StreamCorruptedException {
for (int i = 0; i < 1000; i++) {
switch (state) {
case UNINITIALISED:
final long firstIndex = queue.firstIndex();
if (firstIndex == Long.MAX_VALUE)
return false;
if (!moveToIndex(firstIndex))
return false;
break;
case FOUND_CYCLE: {
try {
return inACycle(includeMetaData);
} catch (EOFException eof) {
state = TailerState.END_OF_CYCLE;
}
break;
}
case END_OF_CYCLE: {
long oldIndex = this.index;
int currentCycle = queue.rollCycle().toCycle(oldIndex);
long nextIndex = nextIndexWithNextAvailableCycle(currentCycle);
if (nextIndex != Long.MIN_VALUE) {
if (moveToIndex(nextIndex)) {
state = FOUND_CYCLE;
continue;
}
}
moveToIndex(oldIndex);
state = END_OF_CYCLE;
return false;
}
case BEYOND_START_OF_CYCLE: {
if (direction == FORWARD) {
state = UNINITIALISED;
continue;
}
if (direction == BACKWARD) {
// give the position of the last entry and
// flag we want to count it even though we don't know if it will be meta data or not.
boolean foundCycle = cycle(queue.rollCycle().toCycle(index), false);
if (foundCycle) {
long lastSequenceNumberInThisCycle = store.sequenceForPosition(this, Long.MAX_VALUE, false);
long nextIndex = queue.rollCycle().toIndex(this.cycle,
lastSequenceNumberInThisCycle);
moveToIndex(nextIndex);
state = FOUND_CYCLE;
continue;
}
int cycle = queue.rollCycle().toCycle(index);
long nextIndex = nextIndexWithNextAvailableCycle(cycle);
if (nextIndex != Long.MIN_VALUE) {
moveToIndex(nextIndex);
state = FOUND_CYCLE;
continue;
}
state = BEYOND_START_OF_CYCLE;
return false;
}
}
throw new AssertionError("direction not set, direction=" + direction);
case CYCLE_NOT_FOUND:
if (index == Long.MIN_VALUE) {
if (this.store != null)
queue.release(this.store);
this.store = null;
return false;
}
if (moveToIndex(index)) {
state = FOUND_CYCLE;
continue;
} else
return false;
default:
throw new AssertionError("state=" + state);
}
}
throw new IllegalStateException("Unable to progress to the next cycle, state=" + state);
}
private boolean inACycle(boolean includeMetaData) throws EOFException,
StreamCorruptedException {
Bytes<?> bytes = wire().bytes();
bytes.readLimit(bytes.capacity());
if (readAfterReplicaAcknowledged) {
long lastSequenceAck = store.lastAcknowledgedIndexReplicated();
long seq = queue.rollCycle().toSequenceNumber(index);
if (seq > lastSequenceAck)
return false;
}
if (direction != TailerDirection.FORWARD)
if (!moveToIndex(index))
return false;
switch (wire().readDataHeader(includeMetaData)) {
case NONE: {
// if current time is not the current cycle, then write an EOF marker and
// re-read from here, you may find that in the mean time an appender writes
// another message, however the EOF marker will always be at the end.
long now = queue.time().currentTimeMillis();
boolean cycleChange2 = now >= timeForNextCycle;
/* int qcycle = queue.cycle();
boolean cycleChange = this.cycle != qcycle;
if (cycleChange != cycleChange2)
System.out.println("error");*/
if (cycleChange2 && !isReadOnly(bytes))
return checkMoveToNextCycle(includeMetaData, bytes);
return false;
}
case META_DATA:
context.metaData(true);
break;
case DATA:
context.metaData(false);
break;
}
if ((index & indexSpacingMask) == 0)
indexEntry(bytes);
context.closeReadLimit(bytes.capacity());
wire().readAndSetLength(bytes.readPosition());
long end = bytes.readLimit();
context.closeReadPosition(end);
return true;
}
private void indexEntry(Bytes<?> bytes) throws StreamCorruptedException {
if (store.indexable(index)
&& !lazyIndexing
&& direction == TailerDirection.FORWARD
&& !context.isMetaData())
store.setPositionForSequenceNumber(this,
queue.rollCycle().toSequenceNumber(index), bytes
.readPosition());
}
private boolean checkMoveToNextCycle(boolean includeMetaData, Bytes<?> bytes)
throws EOFException, StreamCorruptedException {
long pos = bytes.readPosition();
long lim = bytes.readLimit();
long wlim = bytes.writeLimit();
try {
bytes.writePosition(pos);
store.writeEOF(wire(), timeoutMS());
} catch (TimeoutException e) {
Jvm.warn().on(getClass(), "Unable to append EOF, skipping", e);
} finally {
bytes.writeLimit(wlim);
bytes.readLimit(lim);
bytes.readPosition(pos);
}
return inACycle(includeMetaData);
}
private long nextIndexWithNextAvailableCycle(int cycle) {
if (cycle == Integer.MIN_VALUE)
throw new AssertionError("cycle == Integer.MIN_VALUE");
long nextIndex, doubleCheck;
// DON'T REMOVE THIS DOUBLE CHECK - ESPECIALLY WHEN USING SECONDLY THE
// FIRST RESULT CAN DIFFER FROM THE DOUBLE CHECK, AS THE APPENDER CAN RACE WITH THE
// TAILER
do {
nextIndex = nextIndexWithNextAvailableCycle0(cycle);
if (nextIndex != Long.MIN_VALUE) {
int nextCycle = queue.rollCycle().toCycle(nextIndex);
if (nextCycle == cycle + 1) {
// don't do the double check if the next cycle is adjacent to the current
return nextIndex;
}
}
doubleCheck = nextIndexWithNextAvailableCycle0(cycle);
} while (nextIndex != doubleCheck);
if (nextIndex != Long.MIN_VALUE && queue.rollCycle().toCycle(nextIndex) - 1 != cycle) {
/**
* lets say that you were using a roll cycle of TEST_SECONDLY
* and you wrote a message to the queue, if you created a tailer and read the first message,
* then waited around 22 seconds before writing the next message, when the tailer
* came to read the next message, there would be a gap of 22 cycle files
* that did not exist, that is what this is reporting. If you are using daily rolling,
* and writing every day, you should not see this message.
*/
LOG.debug("Rolled " + (queue
.rollCycle().toCycle(nextIndex) - cycle) + " " + "times to find the " +
"next cycle file. This can occur if your appenders have not written " +
"anything for a while, leaving the cycle files with a gap.");
}
return nextIndex;
}
private long nextIndexWithNextAvailableCycle0(int cycle) {
if (cycle > queue.lastCycle() || direction == TailerDirection.NONE) {
return Long.MIN_VALUE;
}
int nextCycle = cycle + direction.add();
boolean found = cycle(nextCycle, false);
if (found)
return nextIndexWithinFoundCycle(nextCycle);
try {
int nextCycle0 = queue.nextCycle(this.cycle, direction);
if (nextCycle0 == -1)
return Long.MIN_VALUE;
return nextIndexWithinFoundCycle(nextCycle0);
} catch (ParseException e) {
throw new IllegalStateException(e);
}
}
private long nextIndexWithinFoundCycle(int nextCycle) {
state = FOUND_CYCLE;
if (direction == FORWARD)
return queue.rollCycle().toIndex(nextCycle, 0);
if (direction == BACKWARD) {
try {
long lastSequenceNumber0 = store.lastSequenceNumber(this);
return queue.rollCycle().toIndex(nextCycle, lastSequenceNumber0);
} catch (Exception e) {
throw new AssertionError(e);
}
} else {
throw new IllegalStateException("direction=" + direction);
}
}
/**
* @return provides an index that includes the cycle number
*/
@Override
public long index() {
return this.index;
}
@Override
public int cycle() {
return this.cycle;
}
@Override
public boolean moveToIndex(final long index) {
final ScanResult scanResult = moveToIndexResult(index);
return scanResult == FOUND;
}
ScanResult moveToIndexResult(long index) {
final int cycle = queue.rollCycle().toCycle(index);
final long sequenceNumber = queue.rollCycle().toSequenceNumber(index);
if (LOG.isDebugEnabled()) {
Jvm.debug().on(getClass(), "moveToIndex: " + Long.toHexString(cycle) + " " + Long.toHexString(sequenceNumber));
}
if (cycle != this.cycle || state != FOUND_CYCLE) {
// moves to the expected cycle
if (!cycle(cycle, false))
return ScanResult.NOT_REACHED;
}
index(index);
ScanResult scanResult = this.store.moveToIndexForRead(this, sequenceNumber);
Bytes<?> bytes = wire().bytes();
if (scanResult == FOUND) {
state = FOUND_CYCLE;
return scanResult;
}
bytes.readLimit(bytes.readPosition());
return scanResult;
}
@NotNull
@Override
public final ExcerptTailer toStart() {
assert direction != BACKWARD;
final int firstCycle = queue.firstCycle();
if (firstCycle == Integer.MAX_VALUE) {
state = UNINITIALISED;
return this;
}
if (firstCycle != this.cycle) {
// moves to the expected cycle
boolean found = cycle(firstCycle, false);
assert found || store == null;
if (found)
state = FOUND_CYCLE;
}
index(queue.rollCycle().toIndex(cycle, 0));
state = FOUND_CYCLE;
if (wire() != null)
wire().bytes().readPosition(0);
return this;
}
/**
* gives approximately the last index, can not be relied on as the last index may have
* changed just after this was called. For this reason, this code is not in queue as it
* should only be an internal method
*
* @return the last index at the time this method was called, or Long.MIN_VALUE if none.
*/
private long approximateLastIndex() {
RollCycle rollCycle = queue.rollCycle();
final int lastCycle = queue.lastCycle();
try {
if (lastCycle == Integer.MIN_VALUE)
return Long.MIN_VALUE;
final WireStore wireStore = queue.storeForCycle(lastCycle, queue.epoch(), false);
this.setCycle(lastCycle);
assert wireStore != null;
if (store != null)
queue.release(store);
if (this.store != wireStore) {
this.store = wireStore;
resetWires();
}
// give the position of the last entry and
// flag we want to count it even though we don't know if it will be meta data or not.
long sequenceNumber = store.lastSequenceNumber(this);
return rollCycle.toIndex(lastCycle, sequenceNumber);
} catch (StreamCorruptedException | UnrecoverableTimeoutException e) {
throw new IllegalStateException(e);
}
}
private boolean headerNumberCheck(AbstractWire wire) {
wire.headNumberCheck((actual, position) -> {
try {
long expecting = store.sequenceForPosition(this, position, false);
if (actual == expecting)
return true;
LOG.error("", new AssertionError("header number check failed " +
"expecting=" + expecting +
" != actual=" + actual));
return false;
} catch (Exception e) {
LOG.error("", e);
return false;
}
});
return true;
}
private void resetWires() {
WireType wireType = queue.wireType();
final AbstractWire wire = (AbstractWire) readAnywhere(wireType.apply(store.bytes()));
assert headerNumberCheck(wire);
this.context.wire(wire);
Wire wireForIndexOld = wireForIndex;
wireForIndex = readAnywhere(wireType.apply(store.bytes()));
assert headerNumberCheck((AbstractWire) wireForIndex);
if (wireForIndexOld != null)
wireForIndexOld.bytes().release();
}
private Wire readAnywhere(Wire wire) {
Bytes<?> bytes = wire.bytes();
bytes.readLimit(bytes.capacity());
return wire;
}
@NotNull
@Override
public ExcerptTailer toEnd() {
long index = approximateLastIndex();
if (index == Long.MIN_VALUE) {
if (state() == TailerState.CYCLE_NOT_FOUND)
state = UNINITIALISED;
return this;
}
switch (moveToIndexResult(index)) {
case NOT_FOUND:
if (moveToIndexResult(index - 1) == FOUND)
state = FOUND_CYCLE;
break;
case FOUND:
if (direction == FORWARD) {
switch (moveToIndexResult(++index)) {
case FOUND:
// the end moved!!
state = FOUND_CYCLE;
break;
case NOT_REACHED:
throw new IllegalStateException("NOT_REACHED after FOUND");
case NOT_FOUND:
state = FOUND_CYCLE;
break;
}
}
break;
case NOT_REACHED:
approximateLastIndex();
throw new IllegalStateException("NOT_REACHED index: " + Long.toHexString(index));
}
return this;
}
@Override
public TailerDirection direction() {
return direction;
}
@Override
public ExcerptTailer direction(TailerDirection direction) {
final TailerDirection oldDirection = this.direction();
this.direction = direction;
if (oldDirection == TailerDirection.BACKWARD &&
direction == TailerDirection.FORWARD)
moveToIndex(index);
return this;
}
public RollingChronicleQueue queue() {
return queue;
}
private void incrementIndex() {
RollCycle rollCycle = queue.rollCycle();
long seq = rollCycle.toSequenceNumber(this.index);
int cycle = rollCycle.toCycle(this.index);
seq += direction.add();
switch (direction) {
case NONE:
break;
case FORWARD:
if (rollCycle.toSequenceNumber(seq) < seq) {
cycle(cycle + 1, false);
seq = 0;
}
break;
case BACKWARD:
if (seq < 0) {
windBackCycle(cycle);
return;
}
break;
}
this.index = rollCycle.toIndex(cycle, seq);
}
private void windBackCycle(int cycle) {
if (tryWindBack(cycle - 1))
return;
cycle--;
for (long first = queue.firstCycle(); cycle >= first; cycle--) {
if (tryWindBack(cycle))
return;
}
this.index(queue.rollCycle().toIndex(cycle, -1));
this.state = BEYOND_START_OF_CYCLE;
}
private boolean tryWindBack(int cycle) {
long count = queue.exceptsPerCycle(cycle);
if (count <= 0)
return false;
RollCycle rollCycle = queue.rollCycle();
moveToIndex(rollCycle.toIndex(cycle, count - 1));
this.state = FOUND_CYCLE;
return true;
}
// DON'T INLINE THIS METHOD, as it's used by enterprise chronicle queue
void index(long index) {
this.index = index;
}
private boolean cycle(final int cycle, boolean createIfAbsent) {
if (this.cycle == cycle && state == FOUND_CYCLE)
return true;
WireStore nextStore = this.queue.storeForCycle(cycle, queue.epoch(), createIfAbsent);
if (nextStore == null && this.store == null)
return false;
if (nextStore == null) {
if (direction == BACKWARD)
state = BEYOND_START_OF_CYCLE;
else
state = CYCLE_NOT_FOUND;
return false;
}
if (store != null)
queue.release(store);
if (nextStore == this.store)
return true;
context.wire(null);
this.store = nextStore;
this.state = FOUND_CYCLE;
this.setCycle(cycle);
resetWires();
final Wire wire = wire();
wire.parent(this);
wire.pauser(queue.pauserSupplier.get());
return true;
}
void release() {
if (store != null) {
store.release();
store = null;
}
state = UNINITIALISED;
}
@Override
public void readAfterReplicaAcknowledged(boolean readAfterReplicaAcknowledged) {
this.readAfterReplicaAcknowledged = readAfterReplicaAcknowledged;
}
@Override
public boolean readAfterReplicaAcknowledged() {
return readAfterReplicaAcknowledged;
}
@Override
public TailerState state() {
return state;
}
@Override
public ExcerptTailer afterLastWritten(ChronicleQueue queue) {
if (queue == this.queue)
throw new IllegalArgumentException("You must pass the queue written to, not the queue read");
ExcerptTailer tailer = queue.createTailer()
.direction(BACKWARD)
.toEnd();
StringBuilder sb = new StringBuilder();
VanillaMessageHistory veh = new VanillaMessageHistory();
veh.addSourceDetails(false);
while (true) {
try (DocumentContext context = tailer.readingDocument()) {
if (!context.isData()) {
toStart();
return this;
}
ValueIn valueIn = context.wire().readEventName(sb);
if (!StringUtils.isEqual("history", sb))
continue;
final Wire wire = context.wire();
Object parent = wire.parent();
try {
wire.parent(null);
valueIn.marshallable(veh);
} finally {
wire.parent(parent);
}
int i = veh.sources() - 1;
// skip the one we just added.
if (i < 0)
continue;
long sourceIndex = veh.sourceIndex(i);
if (!moveToIndex(sourceIndex))
throw new IORuntimeException("Unable to wind to index: " + sourceIndex);
try (DocumentContext content = readingDocument()) {
if (!content.isPresent())
throw new IORuntimeException("Unable to wind to index: " + (sourceIndex + 1));
// skip this message and go to the next.
}
return this;
}
}
}
@UsedViaReflection
public void lastAcknowledgedIndexReplicated(long acknowledgeIndex) {
Jvm.debug().on(getClass(), "received lastAcknowledgedIndexReplicated=" + Long.toHexString(acknowledgeIndex) + " ,file=" + queue().file().getAbsolutePath());
// the reason that we use the temp tailer is to prevent this tailer from having its cycle changed
StoreTailer temp = queue.acquireTailer();
try {
RollCycle rollCycle = queue.rollCycle();
int cycle0 = rollCycle.toCycle(acknowledgeIndex);
if (!temp.cycle(cycle0, false)) {
Jvm.warn().on(getClass(), "Got an acknowledge index " + Long.toHexString(acknowledgeIndex) + " for a cycle which could not found");
return;
}
if (temp.store == null) {
Jvm.warn().on(getClass(), "Got an acknowledge index " + Long.toHexString(acknowledgeIndex) + " discarded.");
return;
}
temp.store.lastAcknowledgedIndexReplicated(acknowledgeIndex);
} finally {
temp.release();
}
}
public long lastAcknowledgedIndexReplicated() throws EOFException {
// the reason that we use the temp tailer is to prevent this tailer from having its cycle changed
final StoreTailer temp = (StoreTailer) queue.acquireTailer().toEnd();
try {
return temp.store.lastAcknowledgedIndexReplicated();
} finally {
temp.release();
}
}
public void setCycle(int cycle) {
this.cycle = cycle;
timeForNextCycle = cycle == Integer.MIN_VALUE ? Long.MAX_VALUE :
(long) (cycle + 1) * queue.rollCycle().length() + queue.epoch();
}
class StoreTailerContext extends ReadDocumentContext {
StoreTailerContext() {
super(null);
}
@Override
public long index() {
return StoreTailer.this.index();
}
@Override
public int sourceId() {
return StoreTailer.this.sourceId();
}
@Override
public void close() {
if (isPresent())
incrementIndex();
super.close();
// assert wire == null || wire.endUse();
}
boolean present(boolean present) {
return this.present = present;
}
public void wire(@Nullable AbstractWire wire) {
AbstractWire oldWire = this.wire;
this.wire = wire;
if (oldWire != null)
oldWire.bytes().release();
}
}
}
}
|
src/main/java/net/openhft/chronicle/queue/impl/single/SingleChronicleQueueExcerpts.java
|
/*
* Copyright 2016 higherfrequencytrading.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 net.openhft.chronicle.queue.impl.single;
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.bytes.BytesStore;
import net.openhft.chronicle.bytes.MappedBytes;
import net.openhft.chronicle.bytes.WriteBytesMarshallable;
import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.Maths;
import net.openhft.chronicle.core.annotation.UsedViaReflection;
import net.openhft.chronicle.core.io.IORuntimeException;
import net.openhft.chronicle.core.util.StringUtils;
import net.openhft.chronicle.queue.*;
import net.openhft.chronicle.queue.impl.ExcerptContext;
import net.openhft.chronicle.queue.impl.RollingChronicleQueue;
import net.openhft.chronicle.queue.impl.WireStore;
import net.openhft.chronicle.wire.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.EOFException;
import java.io.IOException;
import java.io.StreamCorruptedException;
import java.nio.BufferOverflowException;
import java.text.ParseException;
import java.util.concurrent.TimeoutException;
import static net.openhft.chronicle.queue.TailerDirection.BACKWARD;
import static net.openhft.chronicle.queue.TailerDirection.FORWARD;
import static net.openhft.chronicle.queue.TailerState.*;
import static net.openhft.chronicle.queue.impl.single.ScanResult.FOUND;
import static net.openhft.chronicle.queue.impl.single.ScanResult.NOT_FOUND;
public class SingleChronicleQueueExcerpts {
private static final Logger LOG = LoggerFactory.getLogger(SingleChronicleQueueExcerpts.class);
@FunctionalInterface
interface WireWriter<T> {
void write(T message, WireOut wireOut);
}
// *************************************************************************
//
// APPENDERS
//
// *************************************************************************
public interface InternalAppender {
void writeBytes(long index, BytesStore bytes);
}
/**
* // StoreAppender
*/
static class StoreAppender implements ExcerptAppender, ExcerptContext, InternalAppender {
@NotNull
private final SingleChronicleQueue queue;
private final StoreAppenderContext context;
WireStore store;
private int cycle = Integer.MIN_VALUE;
private Wire wire;
private Wire bufferWire; // if you have a buffered write.
private Wire wireForIndex;
private long position = 0;
private volatile Thread appendingThread = null;
private long lastIndex = Long.MIN_VALUE;
private boolean lazyIndexing = false;
private long lastPosition;
private int lastCycle;
private PretoucherState pretoucher = null;
private Padding padToCacheLines = Padding.SMART;
StoreAppender(@NotNull SingleChronicleQueue queue) {
this.queue = queue;
queue.addCloseListener(this, StoreAppender::close);
context = new StoreAppenderContext();
}
public Padding padToCacheAlign() {
return padToCacheLines;
}
/**
* @param padToCacheLines the default for chronicle queue is Padding.SMART, which
* automatically pads all method calls other than {@link
* StoreAppender#writeBytes(net.openhft.chronicle.bytes.WriteBytesMarshallable)}
* and {@link StoreAppender#writeText(java.lang.CharSequence)}.
* Which can not be padded with out changing the message format, The
* reason we pad is to ensure that a message header does not straggle
* a cache line.
*/
public void padToCacheAlign(Padding padToCacheLines) {
this.padToCacheLines = padToCacheLines;
}
/**
* @param marshallable to write to excerpt.
*/
public void writeBytes(@NotNull WriteBytesMarshallable marshallable) throws UnrecoverableTimeoutException {
try (DocumentContext dc = writingDocument()) {
marshallable.writeMarshallable(dc.wire().bytes());
if (padToCacheAlign() != Padding.ALWAYS)
((StoreAppenderContext) dc).padToCacheAlign = false;
}
}
@Override
public void writeText(CharSequence text) throws UnrecoverableTimeoutException {
try (DocumentContext dc = writingDocument()) {
dc.wire().bytes()
.append8bit(text);
if (padToCacheAlign() != Padding.ALWAYS)
((StoreAppenderContext) dc).padToCacheAlign = false;
}
}
void close() {
Wire w0 = wireForIndex;
wireForIndex = null;
if (w0 != null)
w0.bytes().release();
Wire w = wire;
wire = null;
if (w != null)
w.bytes().release();
if (store != null)
queue.release(store);
store = null;
}
@Override
public void pretouch() {
setCycle(queue.cycle(), true);
if (pretoucher == null)
pretoucher = new PretoucherState(() -> this.store.writePosition());
Wire wire = this.wire;
if (wire != null)
pretoucher.pretouch((MappedBytes) wire.bytes());
}
@Override
public Wire wire() {
return wire;
}
@Override
public Wire wireForIndex() {
return wireForIndex;
}
@Override
public long timeoutMS() {
return queue.timeoutMS;
}
void lastIndex(long index) {
this.lastIndex = index;
}
@Override
public ExcerptAppender lazyIndexing(boolean lazyIndexing) {
this.lazyIndexing = lazyIndexing;
resetPosition();
return this;
}
@Override
public boolean lazyIndexing() {
return lazyIndexing;
}
@Override
public boolean recordHistory() {
return sourceId() != 0;
}
private void setCycle(int cycle, boolean createIfAbsent) {
if (cycle != this.cycle)
setCycle2(cycle, createIfAbsent);
}
private void setCycle2(int cycle, boolean createIfAbsent) {
if (cycle < 0)
throw new IllegalArgumentException("You can not have a cycle that starts " +
"before Epoch. cycle=" + cycle);
SingleChronicleQueue queue = this.queue;
if (this.store != null)
queue.release(this.store);
this.store = queue.storeForCycle(cycle, queue.epoch(), createIfAbsent);
resetWires(queue);
// only set the cycle after the wire is set.
this.cycle = cycle;
assert wire.startUse();
wire.parent(this);
wire.pauser(queue.pauserSupplier.get());
resetPosition();
queue.onRoll(cycle);
}
private void resetWires(SingleChronicleQueue queue) {
WireType wireType = queue.wireType();
{
Wire oldw = this.wire;
this.wire = wireType.apply(store.bytes());
if (oldw != null)
oldw.bytes().release();
}
{
Wire old = this.wireForIndex;
this.wireForIndex = wireType.apply(store.bytes());
if (old != null)
old.bytes().release();
}
}
private void resetPosition() throws UnrecoverableTimeoutException {
try {
if (store == null || wire == null)
return;
position(store.writePosition());
Bytes<?> bytes = wire.bytes();
int header = bytes.readVolatileInt(position);
assert position == 0 || Wires.isReadyData(header);
bytes.writePosition(position + 4 + Wires.lengthOf(header));
if (lazyIndexing) {
wire.headerNumber(Long.MIN_VALUE);
return;
}
final long headerNumber = store.sequenceForPosition(this, position, true);
wire.headerNumber(queue.rollCycle().toIndex(cycle, headerNumber + 1) - 1);
assert lazyIndexing || wire.headerNumber() != -1 || checkIndex(wire.headerNumber(), position);
} catch (BufferOverflowException | StreamCorruptedException e) {
throw new AssertionError(e);
}
assert checkWritePositionHeaderNumber();
}
@Override
public DocumentContext writingDocument(boolean metaData) throws UnrecoverableTimeoutException {
assert checkAppendingThread();
assert checkWritePositionHeaderNumber();
boolean ok = false;
try {
int cycle = queue.cycle();
if (this.cycle != cycle || wire == null)
rollCycleTo(cycle);
int safeLength = (int) queue.overlapSize();
for (int i = 0; i < 128; i++) {
try {
assert wire != null;
long pos = store.writeHeader(wire, Wires.UNKNOWN_LENGTH, safeLength, timeoutMS());
position(pos);
context.isClosed = false;
context.wire = wire;
context.padToCacheAlign = padToCacheAlign() != Padding.NEVER;
context.metaData(metaData);
ok = true;
return context;
} catch (EOFException theySeeMeRolling) {
cycle = handleRoll(cycle);
}
}
throw new IllegalStateException("Unable to roll to the current cycle");
} finally {
if (!ok)
assert resetAppendingThread();
}
}
private int handleRoll(int cycle) {
assert !((AbstractWire) wire).isInsideHeader();
int qCycle = queue.cycle();
if (cycle < queue.cycle()) {
setCycle2(cycle = qCycle, true);
} else if (cycle == qCycle) {
// for the rare case where the qCycle has just changed in the last
// few milliseconds since
setCycle2(++cycle, true);
} else
throw new IllegalStateException("Found an EOF on the next cycle file," +
" this next file, should not have an EOF as its cycle " +
"number is greater than the current cycle (based on the " +
"current time), this should only happen " +
"if it " +
"was written by a different appender set with a different " +
"EPOC or different roll cycle." +
"All your appenders ( that write to a given directory ) " +
"should have the same EPOCH and roll cycle" +
" qCycle=" + qCycle + ", cycle=" + cycle);
return cycle;
}
boolean checkWritePositionHeaderNumber() {
if (wire == null || wire.headerNumber() == Long.MIN_VALUE) return true;
try {
long pos1 = position;
/*
long posMax = store.writePosition();
if (pos1 > posMax+4) {
System.out.println(queue.dump());
String message = "########### " +
"thread: " + Thread.currentThread().getName() +
" pos1: " + pos1 +
" posMax: " + posMax;
System.err.println(message);
throw new AssertionError(message);
}*/
long seq1 = queue.rollCycle().toSequenceNumber(wire.headerNumber() + 1) - 1;
long seq2 = store.sequenceForPosition(this, pos1, true);
if (seq1 != seq2) {
// System.out.println(queue.dump());
String message = "~~~~~~~~~~~~~~ " +
"thread: " + Thread.currentThread().getName() +
" pos1: " + pos1 +
" seq1: " + seq1 +
" seq2: " + seq2;
System.err.println(message);
throw new AssertionError(message);
}
} catch (IOException e) {
Jvm.fatal().on(getClass(), e);
throw Jvm.rethrow(e);
}
return true;
}
@Override
public DocumentContext writingDocument(long index) {
context.isClosed = false;
assert checkAppendingThread();
context.wire = acquireBufferWire();
context.wire.headerNumber(index);
context.isClosed = false;
return context;
}
@Override
public int sourceId() {
return queue.sourceId;
}
@Override
public void writeBytes(@NotNull BytesStore bytes) throws UnrecoverableTimeoutException {
// still uses append as it has a known length.
append(Maths.toUInt31(bytes.readRemaining()), (m, w) -> w.bytes().write(m), bytes);
}
Wire acquireBufferWire() {
if (bufferWire == null) {
bufferWire = queue.wireType().apply(Bytes.elasticByteBuffer());
} else {
bufferWire.clear();
}
return bufferWire;
}
@Override
public void writeBytes(long index, BytesStore bytes) {
if (index < 0)
throw new IllegalArgumentException("index: " + index);
if (bytes.isEmpty())
throw new UnsupportedOperationException("Cannot append a zero length message");
assert checkAppendingThread();
try {
moveToIndexForWrite(index);
// only get the bytes after moveToIndex
Bytes<?> wireBytes = wire.bytes();
try {
// wire.bytes().writePosition(store.writePosition());
int length = bytes.length();
// sets the position
wire.headerNumber(index);
position(store.writeHeader(wire, length, length, timeoutMS()));
wireBytes.write(bytes);
wire.updateHeader(length, position, false);
writeIndexForPosition(index, position);
lastIndex(index);
lastPosition = position;
lastCycle = cycle;
store.writePosition(position);
} catch (EOFException theySeeMeRolling) {
if (wireBytes.compareAndSwapInt(wireBytes.writePosition(), Wires.END_OF_DATA, Wires.NOT_COMPLETE)) {
wireBytes.write(bytes);
wire.updateHeader(0, position, false);
}
}
} catch (IllegalStateException ise) {
if (!ise.getMessage().contains("index already exists")) {
Jvm.warn().on(getClass(), "Ignoring duplicate", ise);
throw ise;
}
} catch (StreamCorruptedException | EOFException e) {
throw Jvm.rethrow(e);
} finally {
if (wire != null) {
Bytes<?> wireBytes = wire.bytes();
assert resetAppendingThread();
}
}
}
private void position(long position) {
if (position > store.writePosition() + queue.blockSize())
throw new IllegalArgumentException("pos: " + position + ", store.writePosition()=" +
store.writePosition() + " queue.blockSize()=" + queue.blockSize());
// System.err.println("----- "+Thread.currentThread().getName()+" pos: "+position);
this.position = position;
}
// only called for writeBytes(long index, BytesStore)
private void moveToIndexForWrite(long index) throws EOFException {
if (wire != null && wire.headerNumber() == index)
return;
int cycle = queue.rollCycle().toCycle(index);
ScanResult scanResult = moveToIndex(cycle, queue.rollCycle().toSequenceNumber(index));
switch (scanResult) {
case FOUND:
throw new IllegalStateException("Unable to move to index " + Long.toHexString(index) + " as the index already exists");
case NOT_REACHED:
throw new IllegalStateException("Unable to move to index " + Long.toHexString(index) + " beyond the end of the queue");
case NOT_FOUND:
break;
}
}
ScanResult moveToIndex(int cycle, long sequenceNumber) throws UnrecoverableTimeoutException {
if (LOG.isDebugEnabled()) {
Jvm.debug().on(getClass(), "moveToIndex: " + Long.toHexString(cycle) + " " + Long.toHexString(sequenceNumber));
}
if (this.cycle != cycle) {
if (cycle > this.cycle)
rollCycleTo(cycle);
else
setCycle2(cycle, true);
}
ScanResult scanResult = this.store.moveToIndexForRead(this, sequenceNumber);
Bytes<?> bytes = wire.bytes();
if (scanResult == NOT_FOUND) {
// so you won't read any if it ran out of data.
bytes.writePosition(bytes.readPosition());
return scanResult;
}
bytes.readLimit(bytes.readPosition());
return scanResult;
}
@Override
public long lastIndexAppended() {
if (lastIndex != Long.MIN_VALUE)
return lastIndex;
if (lastPosition == Long.MIN_VALUE || wire == null) {
throw new IllegalStateException("nothing has been appended, so there is no last index");
}
try {
long sequenceNumber = store.sequenceForPosition(this, lastPosition, true);
long index = queue.rollCycle().toIndex(lastCycle, sequenceNumber);
lastIndex(index);
return index;
} catch (Exception e) {
throw Jvm.rethrow(e);
}
}
@Override
public int cycle() {
if (cycle == Integer.MIN_VALUE) {
int cycle = this.queue.lastCycle();
if (cycle < 0)
cycle = queue.cycle();
setCycle2(cycle, true);
}
return cycle;
}
public SingleChronicleQueue queue() {
return queue;
}
/**
* overwritten in delta wire
*
* @param wire
* @param index
*/
void beforeAppend(Wire wire, long index) {
}
private <T> void append(int length, WireWriter<T> wireWriter, T writer) throws
UnrecoverableTimeoutException {
assert checkAppendingThread();
try {
int cycle = queue.cycle();
if (this.cycle != cycle || wire == null)
rollCycleTo(cycle);
try {
position(store.writeHeader(wire, length, length, timeoutMS()));
assert ((AbstractWire) wire).isInsideHeader();
beforeAppend(wire, wire.headerNumber() + 1);
wireWriter.write(writer, wire);
wire.updateHeader(length, position, false);
lastIndex(wire.headerNumber());
lastPosition = position;
lastCycle = cycle;
store.writePosition(position);
writeIndexForPosition(lastIndex, position);
} catch (EOFException theySeeMeRolling) {
try {
append2(length, wireWriter, writer);
} catch (EOFException e) {
throw new AssertionError(e);
}
}
} catch (StreamCorruptedException e) {
throw new AssertionError(e);
} finally {
assert resetAppendingThread();
}
}
private void rollCycleTo(int cycle) throws UnrecoverableTimeoutException {
if (this.cycle == cycle)
throw new AssertionError();
if (wire != null) {
try {
store.writeEOF(wire, timeoutMS());
} catch (TimeoutException e) {
Jvm.warn().on(SingleChronicleQueueExcerpts.class, "Unable to terminate the previous cycle, continuing", e);
}
}
setCycle2(cycle, true);
}
/**
* Write an EOF marker on the current cycle if it is about to roll. It would do this any way
* if a new message was written, but this doesn't create a new cycle or add a message.
*/
public void writeEndOfCycleIfRequired() {
if (wire != null && queue.cycle() != cycle) {
try {
store.writeEOF(wire, timeoutMS());
} catch (TimeoutException e) {
Jvm.warn().on(SingleChronicleQueueExcerpts.class, "Unable to terminate the previous cycle, continuing", e);
}
}
}
<T> void append2(int length, WireWriter<T> wireWriter, T writer) throws
UnrecoverableTimeoutException, EOFException, StreamCorruptedException {
setCycle(Math.max(queue.cycle(), cycle + 1), true);
position(store.writeHeader(wire, length, length, timeoutMS()));
beforeAppend(wire, wire.headerNumber() + 1);
wireWriter.write(writer, wire);
wire.updateHeader(length, position, false);
}
private boolean checkAppendingThread() {
Thread appendingThread = this.appendingThread;
Thread currentThread = Thread.currentThread();
if (appendingThread != null) {
if (appendingThread == currentThread)
throw new IllegalStateException("Nested blocks of writingDocument() not supported");
throw new IllegalStateException("Attempting to use Appender in " + currentThread + " while used by " + appendingThread);
}
this.appendingThread = currentThread;
return true;
}
private boolean resetAppendingThread() {
if (this.appendingThread == null)
throw new IllegalStateException("Attempting to release Appender in " + Thread.currentThread() + " but already released");
this.appendingThread = null;
return true;
}
void writeIndexForPosition(long index, long position)
throws UnrecoverableTimeoutException, StreamCorruptedException {
if (!lazyIndexing) {
long sequenceNumber = queue.rollCycle().toSequenceNumber(index);
store.setPositionForSequenceNumber(this, sequenceNumber, position);
}
}
boolean checkIndex(long index, long position) {
try {
final long seq1 = queue.rollCycle().toSequenceNumber(index + 1) - 1;
final long seq2 = store.sequenceForPosition(this, position, true);
if (seq1 != seq2) {
final long seq3 = ((SingleChronicleQueueStore) store).indexing
.linearScanByPosition(wireForIndex(), position, 0, 0, true);
System.out.println("Thread=" + Thread.currentThread().getName() +
" pos: " + position +
" seq1: " + Long.toHexString(seq1) +
" seq2: " + Long.toHexString(seq2) +
" seq3: " + Long.toHexString(seq3));
System.out.println(store.dump());
assert seq1 == seq3 : "seq1=" + seq1 + ", seq3=" + seq3;
assert seq1 == seq2 : "seq1=" + seq1 + ", seq2=" + seq2;
} else {
/* System.out.println("checked Thread=" + Thread.currentThread().getName() +
" pos: " + position +
" seq1: " + seq1);*/
}
} catch (EOFException | UnrecoverableTimeoutException | StreamCorruptedException e) {
throw new AssertionError(e);
}
return true;
}
class StoreAppenderContext implements DocumentContext {
boolean isClosed;
boolean padToCacheAlign = true;
private boolean metaData = false;
private Wire wire;
@Override
public int sourceId() {
return StoreAppender.this.sourceId();
}
@Override
public boolean isPresent() {
return false;
}
@Override
public Wire wire() {
return wire;
}
@Override
public boolean isMetaData() {
return metaData;
}
@Override
public void metaData(boolean metaData) {
this.metaData = metaData;
}
@Override
public boolean isClosed() {
return isClosed;
}
@Override
public void close() {
if (isClosed) {
LOG.warn("Already Closed, close was called twice.");
return;
}
try {
if (wire == StoreAppender.this.wire) {
if (padToCacheAlign)
wire.padToCacheAlign();
wire.updateHeader(position, metaData);
lastPosition = position;
lastCycle = cycle;
if (!metaData) {
lastIndex(wire.headerNumber());
store.writePosition(position);
if (lastIndex != Long.MIN_VALUE)
writeIndexForPosition(lastIndex, position);
else
assert lazyIndexing || lastIndex == Long.MIN_VALUE || checkIndex(lastIndex, position);
}
assert checkWritePositionHeaderNumber();
} else if (wire != null) {
isClosed = true;
assert resetAppendingThread();
writeBytes(wire.headerNumber(), wire.bytes());
wire = StoreAppender.this.wire;
}
} catch (StreamCorruptedException | UnrecoverableTimeoutException e) {
throw new IllegalStateException(e);
} finally {
assert isClosed || resetAppendingThread();
}
}
@Override
public long index() throws IORuntimeException {
if (this.wire.headerNumber() == Long.MIN_VALUE) {
try {
long headerNumber0 = queue.rollCycle().toIndex(cycle, store
.sequenceForPosition(StoreAppender.this, position, false));
assert (((AbstractWire) this.wire).isInsideHeader());
return isMetaData() ? headerNumber0 : headerNumber0 + 1;
} catch (IOException e) {
throw new IORuntimeException(e);
}
}
return isMetaData() ? Long.MIN_VALUE : this.wire.headerNumber() + 1;
}
@Override
public boolean isNotComplete() {
throw new UnsupportedOperationException();
}
}
}
// *************************************************************************
//
// TAILERS
//
// *************************************************************************
/**
* Tailer
*/
public static class StoreTailer implements ExcerptTailer, SourceContext, ExcerptContext {
@NotNull
private final SingleChronicleQueue queue;
private final StoreTailerContext context = new StoreTailerContext();
private final int indexSpacingMask;
long index; // index of the next read.
WireStore store;
private int cycle;
private long timeForNextCycle = Long.MAX_VALUE;
private TailerDirection direction = TailerDirection.FORWARD;
private boolean lazyIndexing = false;
private Wire wireForIndex;
private boolean readAfterReplicaAcknowledged;
private TailerState state = UNINITIALISED;
public StoreTailer(@NotNull final SingleChronicleQueue queue) {
this.queue = queue;
this.setCycle(Integer.MIN_VALUE);
this.index = 0;
queue.addCloseListener(this, StoreTailer::close);
indexSpacingMask = queue.rollCycle().defaultIndexSpacing() - 1;
}
private static boolean isReadOnly(Bytes bytes) {
return bytes instanceof MappedBytes &&
!((MappedBytes) bytes).mappedFile().file().canWrite();
}
public boolean readDocument(@NotNull ReadMarshallable reader) {
try (@NotNull DocumentContext dc = readingDocument(false)) {
if (!dc.isPresent())
return false;
reader.readMarshallable(dc.wire());
}
return true;
}
@NotNull
public DocumentContext readingDocument() {
return readingDocument(false);
}
private void close() {
context.wire(null);
Wire w0 = wireForIndex;
if (w0 != null)
w0.bytes().release();
if (store != null)
queue.release(store);
store = null;
}
@Override
public Wire wire() {
return context.wire();
}
@Override
public Wire wireForIndex() {
return wireForIndex;
}
@Override
public long timeoutMS() {
return queue.timeoutMS;
}
@Override
public int sourceId() {
return queue.sourceId;
}
@Override
public String toString() {
return "StoreTailer{" +
"index sequence=" + queue.rollCycle().toSequenceNumber(index) +
", index cycle=" + queue.rollCycle().toCycle(index) +
", store=" + store + ", queue=" + queue + '}';
}
@Override
public DocumentContext readingDocument(boolean includeMetaData) {
try {
boolean next = false, tryAgain = true;
if (state == FOUND_CYCLE) {
try {
next = inACycle(includeMetaData);
tryAgain = false;
} catch (EOFException eof) {
state = TailerState.END_OF_CYCLE;
}
}
if (tryAgain)
next = next0(includeMetaData);
if (context.present(next)) {
assert wire().startUse();
return context;
}
RollCycle rollCycle = queue.rollCycle();
;
if (state == CYCLE_NOT_FOUND && direction == FORWARD) {
int firstCycle = queue.firstCycle();
if (rollCycle.toCycle(index) < firstCycle)
toStart();
}
} catch (StreamCorruptedException e) {
throw new IllegalStateException(e);
} catch (UnrecoverableTimeoutException notComplete) {
// so treat as empty.
}
return NoDocumentContext.INSTANCE;
}
private boolean next0(boolean includeMetaData) throws UnrecoverableTimeoutException, StreamCorruptedException {
for (int i = 0; i < 1000; i++) {
switch (state) {
case UNINITIALISED:
final long firstIndex = queue.firstIndex();
if (firstIndex == Long.MAX_VALUE)
return false;
if (!moveToIndex(firstIndex))
return false;
break;
case FOUND_CYCLE: {
try {
return inACycle(includeMetaData);
} catch (EOFException eof) {
state = TailerState.END_OF_CYCLE;
}
break;
}
case END_OF_CYCLE: {
long oldIndex = this.index;
int currentCycle = queue.rollCycle().toCycle(oldIndex);
long nextIndex = nextIndexWithNextAvailableCycle(currentCycle);
if (nextIndex != Long.MIN_VALUE) {
if (moveToIndex(nextIndex)) {
state = FOUND_CYCLE;
continue;
}
}
moveToIndex(oldIndex);
state = END_OF_CYCLE;
return false;
}
case BEYOND_START_OF_CYCLE: {
if (direction == FORWARD) {
state = UNINITIALISED;
continue;
}
if (direction == BACKWARD) {
// give the position of the last entry and
// flag we want to count it even though we don't know if it will be meta data or not.
boolean foundCycle = cycle(queue.rollCycle().toCycle(index), false);
if (foundCycle) {
long lastSequenceNumberInThisCycle = store.sequenceForPosition(this, Long.MAX_VALUE, false);
long nextIndex = queue.rollCycle().toIndex(this.cycle,
lastSequenceNumberInThisCycle);
moveToIndex(nextIndex);
state = FOUND_CYCLE;
continue;
}
int cycle = queue.rollCycle().toCycle(index);
long nextIndex = nextIndexWithNextAvailableCycle(cycle);
if (nextIndex != Long.MIN_VALUE) {
moveToIndex(nextIndex);
state = FOUND_CYCLE;
continue;
}
state = BEYOND_START_OF_CYCLE;
return false;
}
}
throw new AssertionError("direction not set, direction=" + direction);
case CYCLE_NOT_FOUND:
if (index == Long.MIN_VALUE) {
if (this.store != null)
queue.release(this.store);
this.store = null;
return false;
}
if (moveToIndex(index)) {
state = FOUND_CYCLE;
continue;
} else
return false;
default:
throw new AssertionError("state=" + state);
}
}
throw new IllegalStateException("Unable to progress to the next cycle, state=" + state);
}
private boolean inACycle(boolean includeMetaData) throws EOFException,
StreamCorruptedException {
Bytes<?> bytes = wire().bytes();
bytes.readLimit(bytes.capacity());
if (readAfterReplicaAcknowledged) {
long lastSequenceAck = store.lastAcknowledgedIndexReplicated();
long seq = queue.rollCycle().toSequenceNumber(index);
if (seq > lastSequenceAck)
return false;
}
if (direction != TailerDirection.FORWARD)
if (!moveToIndex(index))
return false;
switch (wire().readDataHeader(includeMetaData)) {
case NONE: {
// if current time is not the current cycle, then write an EOF marker and
// re-read from here, you may find that in the mean time an appender writes
// another message, however the EOF marker will always be at the end.
long now = queue.time().currentTimeMillis();
boolean cycleChange2 = now >= timeForNextCycle;
/* int qcycle = queue.cycle();
boolean cycleChange = this.cycle != qcycle;
if (cycleChange != cycleChange2)
System.out.println("error");*/
if (cycleChange2 && !isReadOnly(bytes))
return checkMoveToNextCycle(includeMetaData, bytes);
return false;
}
case META_DATA:
context.metaData(true);
break;
case DATA:
context.metaData(false);
break;
}
if ((index & indexSpacingMask) == 0)
indexEntry(bytes);
context.closeReadLimit(bytes.capacity());
wire().readAndSetLength(bytes.readPosition());
long end = bytes.readLimit();
context.closeReadPosition(end);
return true;
}
private void indexEntry(Bytes<?> bytes) throws StreamCorruptedException {
if (store.indexable(index)
&& !lazyIndexing
&& direction == TailerDirection.FORWARD
&& !context.isMetaData())
store.setPositionForSequenceNumber(this,
queue.rollCycle().toSequenceNumber(index), bytes
.readPosition());
}
private boolean checkMoveToNextCycle(boolean includeMetaData, Bytes<?> bytes)
throws EOFException, StreamCorruptedException {
long pos = bytes.readPosition();
long lim = bytes.readLimit();
long wlim = bytes.writeLimit();
try {
bytes.writePosition(pos);
store.writeEOF(wire(), timeoutMS());
} catch (TimeoutException e) {
Jvm.warn().on(getClass(), "Unable to append EOF, skipping", e);
} finally {
bytes.writeLimit(wlim);
bytes.readLimit(lim);
bytes.readPosition(pos);
}
return inACycle(includeMetaData);
}
private long nextIndexWithNextAvailableCycle(int cycle) {
if (cycle == Integer.MIN_VALUE)
throw new AssertionError("cycle == Integer.MIN_VALUE");
long nextIndex, doubleCheck;
// DON'T REMOVE THIS DOUBLE CHECK - ESPECIALLY WHEN USING SECONDLY THE
// FIRST RESULT CAN DIFFER FROM THE DOUBLE CHECK, AS THE APPENDER CAN RACE WITH THE
// TAILER
do {
nextIndex = nextIndexWithNextAvailableCycle0(cycle);
if (nextIndex != Long.MIN_VALUE) {
int nextCycle = queue.rollCycle().toCycle(nextIndex);
if (nextCycle == cycle + 1) {
// don't do the double check if the next cycle is adjacent to the current
return nextIndex;
}
}
doubleCheck = nextIndexWithNextAvailableCycle0(cycle);
} while (nextIndex != doubleCheck);
if (nextIndex != Long.MIN_VALUE && queue.rollCycle().toCycle(nextIndex) - 1 != cycle) {
/**
* lets say that you were using a roll cycle of TEST_SECONDLY
* and you wrote a message to the queue, if you created a tailer and read the first message,
* then waited around 22 seconds before writing the next message, when the tailer
* came to read the next message, there would be a gap of 22 cycle files
* that did not exist, that is what this is reporting. If you are using daily rolling,
* and writing every day, you should not see this message.
*/
LOG.debug("Rolled " + (queue
.rollCycle().toCycle(nextIndex) - cycle) + " " + "times to find the " +
"next cycle file. This can occur if your appenders have not written " +
"anything for a while, leaving the cycle files with a gap.");
}
return nextIndex;
}
private long nextIndexWithNextAvailableCycle0(int cycle) {
if (cycle > queue.lastCycle() || direction == TailerDirection.NONE) {
return Long.MIN_VALUE;
}
int nextCycle = cycle + direction.add();
boolean found = cycle(nextCycle, false);
if (found)
return nextIndexWithinFoundCycle(nextCycle);
try {
int nextCycle0 = queue.nextCycle(this.cycle, direction);
if (nextCycle0 == -1)
return Long.MIN_VALUE;
return nextIndexWithinFoundCycle(nextCycle0);
} catch (ParseException e) {
throw new IllegalStateException(e);
}
}
private long nextIndexWithinFoundCycle(int nextCycle) {
state = FOUND_CYCLE;
if (direction == FORWARD)
return queue.rollCycle().toIndex(nextCycle, 0);
if (direction == BACKWARD) {
try {
long lastSequenceNumber0 = store.lastSequenceNumber(this);
return queue.rollCycle().toIndex(nextCycle, lastSequenceNumber0);
} catch (Exception e) {
throw new AssertionError(e);
}
} else {
throw new IllegalStateException("direction=" + direction);
}
}
/**
* @return provides an index that includes the cycle number
*/
@Override
public long index() {
return this.index;
}
@Override
public int cycle() {
return this.cycle;
}
@Override
public boolean moveToIndex(final long index) {
final ScanResult scanResult = moveToIndexResult(index);
return scanResult == FOUND;
}
ScanResult moveToIndexResult(long index) {
final int cycle = queue.rollCycle().toCycle(index);
final long sequenceNumber = queue.rollCycle().toSequenceNumber(index);
if (LOG.isDebugEnabled()) {
Jvm.debug().on(getClass(), "moveToIndex: " + Long.toHexString(cycle) + " " + Long.toHexString(sequenceNumber));
}
if (cycle != this.cycle || state != FOUND_CYCLE) {
// moves to the expected cycle
if (!cycle(cycle, false))
return ScanResult.NOT_REACHED;
}
index(index);
ScanResult scanResult = this.store.moveToIndexForRead(this, sequenceNumber);
Bytes<?> bytes = wire().bytes();
if (scanResult == FOUND) {
state = FOUND_CYCLE;
return scanResult;
}
bytes.readLimit(bytes.readPosition());
return scanResult;
}
@NotNull
@Override
public final ExcerptTailer toStart() {
assert direction != BACKWARD;
final int firstCycle = queue.firstCycle();
if (firstCycle == Integer.MAX_VALUE) {
state = UNINITIALISED;
return this;
}
if (firstCycle != this.cycle) {
// moves to the expected cycle
boolean found = cycle(firstCycle, false);
assert found || store == null;
if (found)
state = FOUND_CYCLE;
}
index(queue.rollCycle().toIndex(cycle, 0));
state = FOUND_CYCLE;
if (wire() != null)
wire().bytes().readPosition(0);
return this;
}
/**
* gives approximately the last index, can not be relied on as the last index may have
* changed just after this was called. For this reason, this code is not in queue as it
* should only be an internal method
*
* @return the last index at the time this method was called, or Long.MIN_VALUE if none.
*/
private long approximateLastIndex() {
RollCycle rollCycle = queue.rollCycle();
final int lastCycle = queue.lastCycle();
try {
if (lastCycle == Integer.MIN_VALUE)
return Long.MIN_VALUE;
final WireStore wireStore = queue.storeForCycle(lastCycle, queue.epoch(), false);
this.setCycle(lastCycle);
assert wireStore != null;
if (store != null)
queue.release(store);
if (this.store != wireStore) {
this.store = wireStore;
resetWires();
}
// give the position of the last entry and
// flag we want to count it even though we don't know if it will be meta data or not.
long sequenceNumber = store.lastSequenceNumber(this);
return rollCycle.toIndex(lastCycle, sequenceNumber);
} catch (StreamCorruptedException | UnrecoverableTimeoutException e) {
throw new IllegalStateException(e);
}
}
private boolean headerNumberCheck(AbstractWire wire) {
wire.headNumberCheck((actual, position) -> {
try {
long expecting = store.sequenceForPosition(this, position, false);
if (actual == expecting)
return true;
LOG.error("", new AssertionError("header number check failed " +
"expecting=" + expecting +
" != actual=" + actual));
return false;
} catch (Exception e) {
LOG.error("", e);
return false;
}
});
return true;
}
private void resetWires() {
WireType wireType = queue.wireType();
final AbstractWire wire = (AbstractWire) readAnywhere(wireType.apply(store.bytes()));
assert headerNumberCheck(wire);
this.context.wire(wire);
Wire wireForIndexOld = wireForIndex;
wireForIndex = readAnywhere(wireType.apply(store.bytes()));
assert headerNumberCheck((AbstractWire) wireForIndex);
if (wireForIndexOld != null)
wireForIndexOld.bytes().release();
}
private Wire readAnywhere(Wire wire) {
Bytes<?> bytes = wire.bytes();
bytes.readLimit(bytes.capacity());
return wire;
}
@NotNull
@Override
public ExcerptTailer toEnd() {
long index = approximateLastIndex();
if (index == Long.MIN_VALUE) {
if (state() == TailerState.CYCLE_NOT_FOUND)
state = UNINITIALISED;
return this;
}
switch (moveToIndexResult(index)) {
case NOT_FOUND:
if (moveToIndexResult(index - 1) == FOUND)
state = FOUND_CYCLE;
break;
case FOUND:
if (direction == FORWARD) {
switch (moveToIndexResult(++index)) {
case FOUND:
// the end moved!!
state = FOUND_CYCLE;
break;
case NOT_REACHED:
throw new IllegalStateException("NOT_REACHED after FOUND");
case NOT_FOUND:
state = FOUND_CYCLE;
break;
}
}
break;
case NOT_REACHED:
approximateLastIndex();
throw new IllegalStateException("NOT_REACHED index: " + Long.toHexString(index));
}
return this;
}
@Override
public TailerDirection direction() {
return direction;
}
@Override
public ExcerptTailer direction(TailerDirection direction) {
final TailerDirection oldDirection = this.direction();
this.direction = direction;
if (oldDirection == TailerDirection.BACKWARD &&
direction == TailerDirection.FORWARD)
moveToIndex(index);
return this;
}
public RollingChronicleQueue queue() {
return queue;
}
private void incrementIndex() {
RollCycle rollCycle = queue.rollCycle();
long seq = rollCycle.toSequenceNumber(this.index);
int cycle = rollCycle.toCycle(this.index);
seq += direction.add();
switch (direction) {
case NONE:
break;
case FORWARD:
if (rollCycle.toSequenceNumber(seq) < seq) {
cycle(cycle + 1, false);
seq = 0;
}
break;
case BACKWARD:
if (seq < 0) {
windBackCycle(cycle);
return;
}
break;
}
this.index = rollCycle.toIndex(cycle, seq);
}
private void windBackCycle(int cycle) {
if (tryWindBack(cycle - 1))
return;
cycle--;
for (long first = queue.firstCycle(); cycle >= first; cycle--) {
if (tryWindBack(cycle))
return;
}
this.index(queue.rollCycle().toIndex(cycle, -1));
this.state = BEYOND_START_OF_CYCLE;
}
private boolean tryWindBack(int cycle) {
long count = queue.exceptsPerCycle(cycle);
if (count <= 0)
return false;
RollCycle rollCycle = queue.rollCycle();
moveToIndex(rollCycle.toIndex(cycle, count - 1));
this.state = FOUND_CYCLE;
return true;
}
// DON'T INLINE THIS METHOD, as it's used by enterprise chronicle queue
void index(long index) {
this.index = index;
}
private boolean cycle(final int cycle, boolean createIfAbsent) {
if (this.cycle == cycle && state == FOUND_CYCLE)
return true;
WireStore nextStore = this.queue.storeForCycle(cycle, queue.epoch(), createIfAbsent);
if (nextStore == null && this.store == null)
return false;
if (nextStore == null) {
if (direction == BACKWARD)
state = BEYOND_START_OF_CYCLE;
else
state = CYCLE_NOT_FOUND;
return false;
}
if (store != null)
queue.release(store);
if (nextStore == this.store)
return true;
context.wire(null);
this.store = nextStore;
this.state = FOUND_CYCLE;
this.setCycle(cycle);
resetWires();
final Wire wire = wire();
wire.parent(this);
wire.pauser(queue.pauserSupplier.get());
return true;
}
void release() {
if (store != null) {
store.release();
store = null;
}
state = UNINITIALISED;
}
@Override
public void readAfterReplicaAcknowledged(boolean readAfterReplicaAcknowledged) {
this.readAfterReplicaAcknowledged = readAfterReplicaAcknowledged;
}
@Override
public boolean readAfterReplicaAcknowledged() {
return readAfterReplicaAcknowledged;
}
@Override
public TailerState state() {
return state;
}
@Override
public ExcerptTailer afterLastWritten(ChronicleQueue queue) {
if (queue == this.queue)
throw new IllegalArgumentException("You must pass the queue written to, not the queue read");
ExcerptTailer tailer = queue.createTailer()
.direction(BACKWARD)
.toEnd();
StringBuilder sb = new StringBuilder();
VanillaMessageHistory veh = new VanillaMessageHistory();
veh.addSourceDetails(false);
while (true) {
try (DocumentContext context = tailer.readingDocument()) {
if (!context.isData()) {
toStart();
return this;
}
ValueIn valueIn = context.wire().readEventName(sb);
if (!StringUtils.isEqual("history", sb))
continue;
final Wire wire = context.wire();
Object parent = wire.parent();
try {
wire.parent(null);
valueIn.marshallable(veh);
} finally {
wire.parent(parent);
}
int i = veh.sources() - 1;
// skip the one we just added.
if (i < 0)
continue;
long sourceIndex = veh.sourceIndex(i);
if (!moveToIndex(sourceIndex))
throw new IORuntimeException("Unable to wind to index: " + sourceIndex);
try (DocumentContext content = readingDocument()) {
if (!content.isPresent())
throw new IORuntimeException("Unable to wind to index: " + (sourceIndex + 1));
// skip this message and go to the next.
}
return this;
}
}
}
@UsedViaReflection
public void lastAcknowledgedIndexReplicated(long acknowledgeIndex) {
Jvm.debug().on(getClass(), "received lastAcknowledgedIndexReplicated=" + Long.toHexString(acknowledgeIndex) + " ,file=" + queue().file().getAbsolutePath());
// the reason that we use the temp tailer is to prevent this tailer from having its cycle changed
StoreTailer temp = queue.acquireTailer();
try {
RollCycle rollCycle = queue.rollCycle();
int cycle0 = rollCycle.toCycle(acknowledgeIndex);
if (!temp.cycle(cycle0, false)) {
Jvm.warn().on(getClass(), "Got an acknowledge index " + Long.toHexString(acknowledgeIndex) + " for a cycle which could not found");
return;
}
if (temp.store == null) {
Jvm.warn().on(getClass(), "Got an acknowledge index " + Long.toHexString(acknowledgeIndex) + " discarded.");
return;
}
temp.store.lastAcknowledgedIndexReplicated(acknowledgeIndex);
} finally {
temp.release();
}
}
public long lastAcknowledgedIndexReplicated() throws EOFException {
// the reason that we use the temp tailer is to prevent this tailer from having its cycle changed
final StoreTailer temp = (StoreTailer) queue.acquireTailer().toEnd();
try {
return temp.store.lastAcknowledgedIndexReplicated();
} finally {
temp.release();
}
}
public void setCycle(int cycle) {
this.cycle = cycle;
timeForNextCycle = cycle == Integer.MIN_VALUE ? Long.MAX_VALUE :
(long) (cycle + 1) * queue.rollCycle().length() + queue.epoch();
}
class StoreTailerContext extends ReadDocumentContext {
StoreTailerContext() {
super(null);
}
@Override
public long index() {
return StoreTailer.this.index();
}
@Override
public int sourceId() {
return StoreTailer.this.sourceId();
}
@Override
public void close() {
if (isPresent())
incrementIndex();
super.close();
// assert wire == null || wire.endUse();
}
boolean present(boolean present) {
return this.present = present;
}
public void wire(@Nullable AbstractWire wire) {
AbstractWire oldWire = this.wire;
this.wire = wire;
if (oldWire != null)
oldWire.bytes().release();
}
}
}
}
|
improved software.chronicle.enterprise.queue.AcknowledgedIndexTest
|
src/main/java/net/openhft/chronicle/queue/impl/single/SingleChronicleQueueExcerpts.java
|
improved software.chronicle.enterprise.queue.AcknowledgedIndexTest
|
<ide><path>rc/main/java/net/openhft/chronicle/queue/impl/single/SingleChronicleQueueExcerpts.java
<ide> pretoucher = new PretoucherState(() -> this.store.writePosition());
<ide> Wire wire = this.wire;
<ide> if (wire != null)
<del> pretoucher.pretouch((MappedBytes) wire.bytes());
<add> pretoucher.pretouch((MappedBytes) wire.bytes());
<ide> }
<ide>
<ide> @Override
|
|
Java
|
bsd-3-clause
|
7abe1f1b4a390efb8b5d21ec3fbf7af0fa2b5a8b
| 0 |
QMXTech/MachineMusePowersuits,QMXTech/MachineMusePowersuits
|
package net.machinemuse.powersuits.common;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.IPowerModule;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.general.MuseStringUtils;
import net.machinemuse.powersuits.block.BlockTinkerTable;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.item.ItemPowerArmorBoots;
import net.machinemuse.powersuits.item.ItemPowerArmorChestplate;
import net.machinemuse.powersuits.item.ItemPowerArmorHelmet;
import net.machinemuse.powersuits.item.ItemPowerArmorLeggings;
import net.machinemuse.powersuits.item.ItemPowerGauntlet;
import net.machinemuse.powersuits.powermodule.armor.BasicPlatingModule;
import net.machinemuse.powersuits.powermodule.armor.DiamondPlatingModule;
import net.machinemuse.powersuits.powermodule.armor.EnergyShieldModule;
import net.machinemuse.powersuits.powermodule.energy.AdvancedBatteryModule;
import net.machinemuse.powersuits.powermodule.energy.BasicBatteryModule;
import net.machinemuse.powersuits.powermodule.energy.EliteBatteryModule;
import net.machinemuse.powersuits.powermodule.misc.CitizenJoeStyle;
import net.machinemuse.powersuits.powermodule.misc.InvisibilityModule;
import net.machinemuse.powersuits.powermodule.misc.NightVisionModule;
import net.machinemuse.powersuits.powermodule.misc.TintModule;
import net.machinemuse.powersuits.powermodule.misc.TransparentArmorModule;
import net.machinemuse.powersuits.powermodule.misc.WaterElectrolyzerModule;
import net.machinemuse.powersuits.powermodule.movement.BlinkDriveModule;
import net.machinemuse.powersuits.powermodule.movement.ClimbAssistModule;
import net.machinemuse.powersuits.powermodule.movement.FlightControlModule;
import net.machinemuse.powersuits.powermodule.movement.GliderModule;
import net.machinemuse.powersuits.powermodule.movement.JetBootsModule;
import net.machinemuse.powersuits.powermodule.movement.JetPackModule;
import net.machinemuse.powersuits.powermodule.movement.JumpAssistModule;
import net.machinemuse.powersuits.powermodule.movement.ParachuteModule;
import net.machinemuse.powersuits.powermodule.movement.ShockAbsorberModule;
import net.machinemuse.powersuits.powermodule.movement.SprintAssistModule;
import net.machinemuse.powersuits.powermodule.movement.SwimAssistModule;
import net.machinemuse.powersuits.powermodule.tool.AquaAffinityModule;
import net.machinemuse.powersuits.powermodule.tool.AxeModule;
import net.machinemuse.powersuits.powermodule.tool.DiamondPickUpgradeModule;
import net.machinemuse.powersuits.powermodule.tool.HoeModule;
import net.machinemuse.powersuits.powermodule.tool.PickaxeModule;
import net.machinemuse.powersuits.powermodule.tool.ShearsModule;
import net.machinemuse.powersuits.powermodule.tool.ShovelModule;
import net.machinemuse.powersuits.powermodule.weapon.BladeLauncherModule;
import net.machinemuse.powersuits.powermodule.weapon.MeleeAssistModule;
import net.machinemuse.powersuits.powermodule.weapon.PlasmaCannonModule;
import net.machinemuse.powersuits.powermodule.weapon.RailgunModule;
import net.machinemuse.powersuits.powermodule.weapon.SonicWeaponModule;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.Configuration;
import org.lwjgl.input.Keyboard;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
/**
* Initial attempt at storing all tweakable/configurable values in one class.
* This got really messy really fast so it's in the process of being
* reworked.
*
* @author MachineMuse
*
*/
public class Config {
public static final String RESOURCE_PREFIX = "/mods/mmmPowersuits/";
public static final String TEXTURE_PREFIX = RESOURCE_PREFIX + "textures/";
public static final String SOUND_PREFIX = RESOURCE_PREFIX + "sound/";
// public static final String SEBK_ICON_PATH =
// "/mods/mmmPowersuits//machinemuse/sebkicons.png";
public static final String SEBK_ARMOR_PATH = TEXTURE_PREFIX + "models/sebkarmor.png";
public static final String SEBK_ARMORPANTS_PATH = TEXTURE_PREFIX + "models/sebkarmorpants.png";
// public static final String WC_ICON_PATH =
// "/resources/machinemuse/watericons.png";
public static final String TINKERTABLE_TEXTURE_PATH = TEXTURE_PREFIX + "models/tinkertable_tx.png";
public static final String BLANK_ARMOR_MODEL_PATH = TEXTURE_PREFIX + "models/blankarmor.png";
// public static final String MUSE_ICON_PATH =
// "/resources/machinemuse/museicons.png";
public static final String SEBK_TOOL_TEXTURE = TEXTURE_PREFIX + "models/tool.png";
public static final String LIGHTNING_TEXTURE = TEXTURE_PREFIX + "gui/lightning-medium.png";
public static final String CITIZENJOE_ARMOR_PATH = TEXTURE_PREFIX + "models/joearmor.png";
public static final String CITIZENJOE_ARMORPANTS_PATH = TEXTURE_PREFIX + "models/joearmorpants.png";
private static Configuration config;
/**
* Called in the pre-init phase of initialization, informs Forge that we
* want the following blockIDs.
*
* @param config
* The Forge configuration object which will handle such
* requests.
*/
public static void init(Configuration config) {
Config.config = config;
config.load();
BlockTinkerTable.assignedBlockID = config.getBlock("Power Armor Tinker Table", 2477).getInt();
ItemComponent.assignedItemID = config.getItem("Power Armor Component", 24770).getInt();
ItemPowerArmorHelmet.assignedItemID = config.getItem("Power Armor Head", 24771).getInt();
ItemPowerArmorChestplate.assignedItemID = config.getItem("Power Armor Torso", 24772).getInt();
ItemPowerArmorLeggings.assignedItemID = config.getItem("Power Armor Legs", 24773).getInt();
ItemPowerArmorBoots.assignedItemID = config.getItem("Power Armor Feet", 24774).getInt();
ItemPowerGauntlet.assignedItemID = config.getItem("Power Tool", 24775).getInt();
config.save();
}
/**
* The packet channel for this mod. We will only listen for and send packets
* on this 'channel'. Max of 16 characters.
*
* @return
*/
public static String getNetworkChannelName() {
return "mmmPowerSuits";
}
/**
* The default creative tab to add all these items to. This behaviour may
* change if more items are added, but for now there are only 5 items and 1
* block, so misc is the most appropriate target.
*
* @return
*/
public static CreativeTabs getCreativeTab() {
return MuseCreativeTab.instance();
}
/**
* Chance of each item being returned when salvaged.
*
* @return percent chance, 0.0 to 1.0
*/
public static double getSalvageChance() {
return config.get(Configuration.CATEGORY_GENERAL, "Salvage Ratio", 0.9).getDouble(0.9);
}
/**
* The maximum amount of armor contribution allowed per armor piece. Total
* armor when the full set is worn can never exceed 4 times this amount.
*
* @return
*/
public static double getMaximumArmorPerPiece() {
// Clamp this value between 0 and 6 armor points.
// The default of 6 will allow 24% reduction per piece.
return Math.max(0.0, config.get(Configuration.CATEGORY_GENERAL, "Maximum Armor per Piece", 6.0).getDouble(6.0));
}
public static double getMaximumFlyingSpeedmps() {
return config.get(Configuration.CATEGORY_GENERAL, "Maximum flight speed (in m/s)", 25.0).getDouble(25.0);
}
/**
* Whether or not to print debugging info.
*
* @return
*/
public static boolean isDebugging() {
return config.get(Configuration.CATEGORY_GENERAL, "Debugging info", false).getBoolean(false);
}
/**
* Helper function for making recipes. Returns a copy of the itemstack with
* the specified stacksize.
*
* @param stack
* Itemstack to copy
* @param number
* New Stacksize
* @return A new itemstack with the specified properties
*/
public static ItemStack copyAndResize(ItemStack stack, int number) {
ItemStack copy = stack.copy();
copy.stackSize = number;
return copy;
}
public static void addModule(IPowerModule module) {
ModuleManager.addModule(module);
}
/**
* Load all the modules in the config file into memory. Eventually. For now,
* they are hardcoded.
*/
public static void loadPowerModules() {
// loadModularProperties();
List<IModularItem> ARMORONLY = Arrays.asList((IModularItem) ModularPowersuits.powerArmorHead, ModularPowersuits.powerArmorTorso,
ModularPowersuits.powerArmorLegs, ModularPowersuits.powerArmorFeet);
List<IModularItem> ALLITEMS = Arrays.asList((IModularItem) ModularPowersuits.powerArmorHead, ModularPowersuits.powerArmorTorso,
ModularPowersuits.powerArmorLegs, ModularPowersuits.powerArmorFeet, ModularPowersuits.powerTool);
List<IModularItem> HEADONLY = Collections.singletonList((IModularItem) ModularPowersuits.powerArmorHead);
List<IModularItem> TORSOONLY = Collections.singletonList((IModularItem) ModularPowersuits.powerArmorTorso);
List<IModularItem> LEGSONLY = Collections.singletonList((IModularItem) ModularPowersuits.powerArmorLegs);
List<IModularItem> FEETONLY = Collections.singletonList((IModularItem) ModularPowersuits.powerArmorFeet);
List<IModularItem> TOOLONLY = Collections.singletonList((IModularItem) ModularPowersuits.powerTool);
IPowerModule module;
// Armor
addModule(new BasicPlatingModule(ARMORONLY));
addModule(new DiamondPlatingModule(ARMORONLY));
addModule(new EnergyShieldModule(ARMORONLY));
// Tool
addModule(new AxeModule(TOOLONLY));
addModule(new PickaxeModule(TOOLONLY));
addModule(new ShovelModule(TOOLONLY));
addModule(new ShearsModule(TOOLONLY));
addModule(new HoeModule(TOOLONLY));
// Weapon
addModule(new MeleeAssistModule(TOOLONLY));
addModule(new PlasmaCannonModule(TOOLONLY));
addModule(new RailgunModule(TOOLONLY));
addModule(new SonicWeaponModule(TOOLONLY));
addModule(new BladeLauncherModule(TOOLONLY));
// Energy
addModule(new BasicBatteryModule(ALLITEMS));
addModule(new AdvancedBatteryModule(ALLITEMS));
addModule(new EliteBatteryModule(ALLITEMS));
// Movement
addModule(new ParachuteModule(TORSOONLY));
addModule(new GliderModule(TORSOONLY));
addModule(new JetPackModule(TORSOONLY));
addModule(new SprintAssistModule(LEGSONLY));
addModule(new JumpAssistModule(LEGSONLY));
addModule(new SwimAssistModule(LEGSONLY));
addModule(new ClimbAssistModule(LEGSONLY));
addModule(new JetBootsModule(FEETONLY));
addModule(new ShockAbsorberModule(FEETONLY));
addModule(new WaterElectrolyzerModule(HEADONLY));
// Special
addModule(new NightVisionModule(HEADONLY));
addModule(new FlightControlModule(HEADONLY));
addModule(new InvisibilityModule(TORSOONLY));
addModule(new BlinkDriveModule(TOOLONLY));
addModule(new DiamondPickUpgradeModule(TOOLONLY));
addModule(new AquaAffinityModule(TOOLONLY));
// Cosmetic
addModule(new TintModule(ALLITEMS));
addModule(new TransparentArmorModule(ARMORONLY));
addModule(new CitizenJoeStyle(ARMORONLY));
}
/**
* An enum to describe the various GUI windows which can appear. IDs are
* less important here since this data isn't saved or synced.
*
* @author MachineMuse
*
*/
public static enum Guis {
GuiTinkerTable,
GuiSuitManager,
GuiPortableCrafting;
}
public static Configuration getConfig() {
return config;
}
public static boolean doAdditionalInfo() {
if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) {
if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
return true;
}
}
return false;
}
public static Object additionalInfoInstructions() {
String message = "Press SHIFT for more information.";
message = MuseStringUtils.wrapMultipleFormatTags(message, MuseStringUtils.FormatCodes.Grey, MuseStringUtils.FormatCodes.Italic);
return message;
}
}
|
src/minecraft/net/machinemuse/powersuits/common/Config.java
|
package net.machinemuse.powersuits.common;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.IPowerModule;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.general.MuseStringUtils;
import net.machinemuse.powersuits.block.BlockTinkerTable;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.item.ItemPowerArmorBoots;
import net.machinemuse.powersuits.item.ItemPowerArmorChestplate;
import net.machinemuse.powersuits.item.ItemPowerArmorHelmet;
import net.machinemuse.powersuits.item.ItemPowerArmorLeggings;
import net.machinemuse.powersuits.item.ItemPowerGauntlet;
import net.machinemuse.powersuits.powermodule.armor.BasicPlatingModule;
import net.machinemuse.powersuits.powermodule.armor.DiamondPlatingModule;
import net.machinemuse.powersuits.powermodule.armor.EnergyShieldModule;
import net.machinemuse.powersuits.powermodule.energy.AdvancedBatteryModule;
import net.machinemuse.powersuits.powermodule.energy.BasicBatteryModule;
import net.machinemuse.powersuits.powermodule.energy.EliteBatteryModule;
import net.machinemuse.powersuits.powermodule.misc.CitizenJoeStyle;
import net.machinemuse.powersuits.powermodule.misc.InvisibilityModule;
import net.machinemuse.powersuits.powermodule.misc.NightVisionModule;
import net.machinemuse.powersuits.powermodule.misc.TintModule;
import net.machinemuse.powersuits.powermodule.misc.TransparentArmorModule;
import net.machinemuse.powersuits.powermodule.misc.WaterElectrolyzerModule;
import net.machinemuse.powersuits.powermodule.movement.BlinkDriveModule;
import net.machinemuse.powersuits.powermodule.movement.ClimbAssistModule;
import net.machinemuse.powersuits.powermodule.movement.FlightControlModule;
import net.machinemuse.powersuits.powermodule.movement.GliderModule;
import net.machinemuse.powersuits.powermodule.movement.JetBootsModule;
import net.machinemuse.powersuits.powermodule.movement.JetPackModule;
import net.machinemuse.powersuits.powermodule.movement.JumpAssistModule;
import net.machinemuse.powersuits.powermodule.movement.ParachuteModule;
import net.machinemuse.powersuits.powermodule.movement.ShockAbsorberModule;
import net.machinemuse.powersuits.powermodule.movement.SprintAssistModule;
import net.machinemuse.powersuits.powermodule.movement.SwimAssistModule;
import net.machinemuse.powersuits.powermodule.tool.AquaAffinityModule;
import net.machinemuse.powersuits.powermodule.tool.AxeModule;
import net.machinemuse.powersuits.powermodule.tool.DiamondPickUpgradeModule;
import net.machinemuse.powersuits.powermodule.tool.HoeModule;
import net.machinemuse.powersuits.powermodule.tool.PickaxeModule;
import net.machinemuse.powersuits.powermodule.tool.ShearsModule;
import net.machinemuse.powersuits.powermodule.tool.ShovelModule;
import net.machinemuse.powersuits.powermodule.weapon.MeleeAssistModule;
import net.machinemuse.powersuits.powermodule.weapon.PlasmaCannonModule;
import net.machinemuse.powersuits.powermodule.weapon.RailgunModule;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.Configuration;
import org.lwjgl.input.Keyboard;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
/**
* Initial attempt at storing all tweakable/configurable values in one class. This got really messy really fast so it's in the process of being
* reworked.
*
* @author MachineMuse
*
*/
public class Config {
public static final String RESOURCE_PREFIX = "/mods/mmmPowersuits/";
public static final String TEXTURE_PREFIX = RESOURCE_PREFIX + "textures/";
public static final String SOUND_PREFIX = RESOURCE_PREFIX + "sound/";
// public static final String SEBK_ICON_PATH = "/mods/mmmPowersuits//machinemuse/sebkicons.png";
public static final String SEBK_ARMOR_PATH = TEXTURE_PREFIX + "models/sebkarmor.png";
public static final String SEBK_ARMORPANTS_PATH = TEXTURE_PREFIX + "models/sebkarmorpants.png";
// public static final String WC_ICON_PATH = "/resources/machinemuse/watericons.png";
public static final String TINKERTABLE_TEXTURE_PATH = TEXTURE_PREFIX + "models/tinkertable_tx.png";
public static final String BLANK_ARMOR_MODEL_PATH = TEXTURE_PREFIX + "models/blankarmor.png";
// public static final String MUSE_ICON_PATH = "/resources/machinemuse/museicons.png";
public static final String SEBK_TOOL_TEXTURE = TEXTURE_PREFIX + "models/tool.png";
public static final String LIGHTNING_TEXTURE = TEXTURE_PREFIX + "gui/lightning-medium.png";
public static final String CITIZENJOE_ARMOR_PATH = TEXTURE_PREFIX + "models/joearmor.png";
public static final String CITIZENJOE_ARMORPANTS_PATH = TEXTURE_PREFIX + "models/joearmorpants.png";
private static Configuration config;
/**
* Called in the pre-init phase of initialization, informs Forge that we want the following blockIDs.
*
* @param config
* The Forge configuration object which will handle such requests.
*/
public static void init(Configuration config) {
Config.config = config;
config.load();
BlockTinkerTable.assignedBlockID = config.getBlock("Power Armor Tinker Table", 2477).getInt();
ItemComponent.assignedItemID = config.getItem("Power Armor Component", 24770).getInt();
ItemPowerArmorHelmet.assignedItemID = config.getItem("Power Armor Head", 24771).getInt();
ItemPowerArmorChestplate.assignedItemID = config.getItem("Power Armor Torso", 24772).getInt();
ItemPowerArmorLeggings.assignedItemID = config.getItem("Power Armor Legs", 24773).getInt();
ItemPowerArmorBoots.assignedItemID = config.getItem("Power Armor Feet", 24774).getInt();
ItemPowerGauntlet.assignedItemID = config.getItem("Power Tool", 24775).getInt();
config.save();
}
/**
* The packet channel for this mod. We will only listen for and send packets on this 'channel'. Max of 16 characters.
*
* @return
*/
public static String getNetworkChannelName() {
return "mmmPowerSuits";
}
/**
* The default creative tab to add all these items to. This behaviour may change if more items are added, but for now there are only 5 items and 1
* block, so misc is the most appropriate target.
*
* @return
*/
public static CreativeTabs getCreativeTab() {
return MuseCreativeTab.instance();
}
/**
* Chance of each item being returned when salvaged.
*
* @return percent chance, 0.0 to 1.0
*/
public static double getSalvageChance() {
return config.get(Configuration.CATEGORY_GENERAL, "Salvage Ratio", 0.9).getDouble(0.9);
}
/**
* The maximum amount of armor contribution allowed per armor piece. Total armor when the full set is worn can never exceed 4 times this amount.
*
* @return
*/
public static double getMaximumArmorPerPiece() {
// Clamp this value between 0 and 6 armor points.
// The default of 6 will allow 24% reduction per piece.
return Math.max(0.0, config.get(Configuration.CATEGORY_GENERAL, "Maximum Armor per Piece", 6.0).getDouble(6.0));
}
public static double getMaximumFlyingSpeedmps() {
return config.get(Configuration.CATEGORY_GENERAL, "Maximum flight speed (in m/s)", 25.0).getDouble(25.0);
}
/**
* Whether or not to print debugging info.
*
* @return
*/
public static boolean isDebugging() {
return config.get(Configuration.CATEGORY_GENERAL, "Debugging info", false).getBoolean(false);
}
/**
* Helper function for making recipes. Returns a copy of the itemstack with the specified stacksize.
*
* @param stack
* Itemstack to copy
* @param number
* New Stacksize
* @return A new itemstack with the specified properties
*/
public static ItemStack copyAndResize(ItemStack stack, int number) {
ItemStack copy = stack.copy();
copy.stackSize = number;
return copy;
}
public static void addModule(IPowerModule module) {
ModuleManager.addModule(module);
}
/**
* Load all the modules in the config file into memory. Eventually. For now, they are hardcoded.
*/
public static void loadPowerModules() {
// loadModularProperties();
List<IModularItem> ARMORONLY = Arrays.asList((IModularItem) ModularPowersuits.powerArmorHead, ModularPowersuits.powerArmorTorso,
ModularPowersuits.powerArmorLegs, ModularPowersuits.powerArmorFeet);
List<IModularItem> ALLITEMS = Arrays.asList((IModularItem) ModularPowersuits.powerArmorHead, ModularPowersuits.powerArmorTorso,
ModularPowersuits.powerArmorLegs, ModularPowersuits.powerArmorFeet, ModularPowersuits.powerTool);
List<IModularItem> HEADONLY = Collections.singletonList((IModularItem) ModularPowersuits.powerArmorHead);
List<IModularItem> TORSOONLY = Collections.singletonList((IModularItem) ModularPowersuits.powerArmorTorso);
List<IModularItem> LEGSONLY = Collections.singletonList((IModularItem) ModularPowersuits.powerArmorLegs);
List<IModularItem> FEETONLY = Collections.singletonList((IModularItem) ModularPowersuits.powerArmorFeet);
List<IModularItem> TOOLONLY = Collections.singletonList((IModularItem) ModularPowersuits.powerTool);
IPowerModule module;
// Armor
addModule(new BasicPlatingModule(ARMORONLY));
addModule(new DiamondPlatingModule(ARMORONLY));
addModule(new EnergyShieldModule(ARMORONLY));
// Tool
addModule(new AxeModule(TOOLONLY));
addModule(new PickaxeModule(TOOLONLY));
addModule(new ShovelModule(TOOLONLY));
addModule(new ShearsModule(TOOLONLY));
addModule(new HoeModule(TOOLONLY));
// Weapon
addModule(new MeleeAssistModule(TOOLONLY));
addModule(new PlasmaCannonModule(TOOLONLY));
addModule(new RailgunModule(TOOLONLY));
// Energy
addModule(new BasicBatteryModule(ALLITEMS));
addModule(new AdvancedBatteryModule(ALLITEMS));
addModule(new EliteBatteryModule(ALLITEMS));
// Movement
addModule(new ParachuteModule(TORSOONLY));
addModule(new GliderModule(TORSOONLY));
addModule(new JetPackModule(TORSOONLY));
addModule(new SprintAssistModule(LEGSONLY));
addModule(new JumpAssistModule(LEGSONLY));
addModule(new SwimAssistModule(LEGSONLY));
addModule(new ClimbAssistModule(LEGSONLY));
addModule(new JetBootsModule(FEETONLY));
addModule(new ShockAbsorberModule(FEETONLY));
addModule(new WaterElectrolyzerModule(HEADONLY));
// Special
addModule(new NightVisionModule(HEADONLY));
addModule(new FlightControlModule(HEADONLY));
addModule(new InvisibilityModule(TORSOONLY));
addModule(new BlinkDriveModule(TOOLONLY));
addModule(new DiamondPickUpgradeModule(TOOLONLY));
addModule(new AquaAffinityModule(TOOLONLY));
// Cosmetic
addModule(new TintModule(ALLITEMS));
addModule(new TransparentArmorModule(ARMORONLY));
addModule(new CitizenJoeStyle(ARMORONLY));
}
/**
* An enum to describe the various GUI windows which can appear. IDs are less important here since this data isn't saved or synced.
*
* @author MachineMuse
*
*/
public static enum Guis {
GuiTinkerTable, GuiSuitManager, GuiPortableCrafting;
}
public static Configuration getConfig() {
return config;
}
public static boolean doAdditionalInfo() {
if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) {
if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
return true;
}
}
return false;
}
public static Object additionalInfoInstructions() {
String message = "Press SHIFT for more information.";
message = MuseStringUtils.wrapMultipleFormatTags(message, MuseStringUtils.FormatCodes.Grey, MuseStringUtils.FormatCodes.Italic);
return message;
}
}
|
added incomplete modules to config
|
src/minecraft/net/machinemuse/powersuits/common/Config.java
|
added incomplete modules to config
|
<ide><path>rc/minecraft/net/machinemuse/powersuits/common/Config.java
<ide> import net.machinemuse.powersuits.powermodule.tool.PickaxeModule;
<ide> import net.machinemuse.powersuits.powermodule.tool.ShearsModule;
<ide> import net.machinemuse.powersuits.powermodule.tool.ShovelModule;
<add>import net.machinemuse.powersuits.powermodule.weapon.BladeLauncherModule;
<ide> import net.machinemuse.powersuits.powermodule.weapon.MeleeAssistModule;
<ide> import net.machinemuse.powersuits.powermodule.weapon.PlasmaCannonModule;
<ide> import net.machinemuse.powersuits.powermodule.weapon.RailgunModule;
<add>import net.machinemuse.powersuits.powermodule.weapon.SonicWeaponModule;
<ide> import net.minecraft.creativetab.CreativeTabs;
<ide> import net.minecraft.item.ItemStack;
<ide> import net.minecraftforge.common.Configuration;
<ide> import cpw.mods.fml.relauncher.Side;
<ide>
<ide> /**
<del> * Initial attempt at storing all tweakable/configurable values in one class. This got really messy really fast so it's in the process of being
<add> * Initial attempt at storing all tweakable/configurable values in one class.
<add> * This got really messy really fast so it's in the process of being
<ide> * reworked.
<ide> *
<ide> * @author MachineMuse
<ide> public static final String RESOURCE_PREFIX = "/mods/mmmPowersuits/";
<ide> public static final String TEXTURE_PREFIX = RESOURCE_PREFIX + "textures/";
<ide> public static final String SOUND_PREFIX = RESOURCE_PREFIX + "sound/";
<del> // public static final String SEBK_ICON_PATH = "/mods/mmmPowersuits//machinemuse/sebkicons.png";
<add> // public static final String SEBK_ICON_PATH =
<add> // "/mods/mmmPowersuits//machinemuse/sebkicons.png";
<ide> public static final String SEBK_ARMOR_PATH = TEXTURE_PREFIX + "models/sebkarmor.png";
<ide> public static final String SEBK_ARMORPANTS_PATH = TEXTURE_PREFIX + "models/sebkarmorpants.png";
<del> // public static final String WC_ICON_PATH = "/resources/machinemuse/watericons.png";
<add> // public static final String WC_ICON_PATH =
<add> // "/resources/machinemuse/watericons.png";
<ide> public static final String TINKERTABLE_TEXTURE_PATH = TEXTURE_PREFIX + "models/tinkertable_tx.png";
<ide> public static final String BLANK_ARMOR_MODEL_PATH = TEXTURE_PREFIX + "models/blankarmor.png";
<del> // public static final String MUSE_ICON_PATH = "/resources/machinemuse/museicons.png";
<add> // public static final String MUSE_ICON_PATH =
<add> // "/resources/machinemuse/museicons.png";
<ide> public static final String SEBK_TOOL_TEXTURE = TEXTURE_PREFIX + "models/tool.png";
<ide> public static final String LIGHTNING_TEXTURE = TEXTURE_PREFIX + "gui/lightning-medium.png";
<ide> public static final String CITIZENJOE_ARMOR_PATH = TEXTURE_PREFIX + "models/joearmor.png";
<ide> private static Configuration config;
<ide>
<ide> /**
<del> * Called in the pre-init phase of initialization, informs Forge that we want the following blockIDs.
<add> * Called in the pre-init phase of initialization, informs Forge that we
<add> * want the following blockIDs.
<ide> *
<ide> * @param config
<del> * The Forge configuration object which will handle such requests.
<add> * The Forge configuration object which will handle such
<add> * requests.
<ide> */
<ide> public static void init(Configuration config) {
<ide> Config.config = config;
<ide> }
<ide>
<ide> /**
<del> * The packet channel for this mod. We will only listen for and send packets on this 'channel'. Max of 16 characters.
<add> * The packet channel for this mod. We will only listen for and send packets
<add> * on this 'channel'. Max of 16 characters.
<ide> *
<ide> * @return
<ide> */
<ide> }
<ide>
<ide> /**
<del> * The default creative tab to add all these items to. This behaviour may change if more items are added, but for now there are only 5 items and 1
<add> * The default creative tab to add all these items to. This behaviour may
<add> * change if more items are added, but for now there are only 5 items and 1
<ide> * block, so misc is the most appropriate target.
<ide> *
<ide> * @return
<ide> }
<ide>
<ide> /**
<del> * The maximum amount of armor contribution allowed per armor piece. Total armor when the full set is worn can never exceed 4 times this amount.
<add> * The maximum amount of armor contribution allowed per armor piece. Total
<add> * armor when the full set is worn can never exceed 4 times this amount.
<ide> *
<ide> * @return
<ide> */
<ide> }
<ide>
<ide> /**
<del> * Helper function for making recipes. Returns a copy of the itemstack with the specified stacksize.
<add> * Helper function for making recipes. Returns a copy of the itemstack with
<add> * the specified stacksize.
<ide> *
<ide> * @param stack
<ide> * Itemstack to copy
<ide> }
<ide>
<ide> /**
<del> * Load all the modules in the config file into memory. Eventually. For now, they are hardcoded.
<add> * Load all the modules in the config file into memory. Eventually. For now,
<add> * they are hardcoded.
<ide> */
<ide> public static void loadPowerModules() {
<ide> // loadModularProperties();
<ide> addModule(new MeleeAssistModule(TOOLONLY));
<ide> addModule(new PlasmaCannonModule(TOOLONLY));
<ide> addModule(new RailgunModule(TOOLONLY));
<add> addModule(new SonicWeaponModule(TOOLONLY));
<add> addModule(new BladeLauncherModule(TOOLONLY));
<ide>
<ide> // Energy
<ide> addModule(new BasicBatteryModule(ALLITEMS));
<ide> }
<ide>
<ide> /**
<del> * An enum to describe the various GUI windows which can appear. IDs are less important here since this data isn't saved or synced.
<add> * An enum to describe the various GUI windows which can appear. IDs are
<add> * less important here since this data isn't saved or synced.
<ide> *
<ide> * @author MachineMuse
<ide> *
<ide> */
<ide> public static enum Guis {
<del> GuiTinkerTable, GuiSuitManager, GuiPortableCrafting;
<add> GuiTinkerTable,
<add> GuiSuitManager,
<add> GuiPortableCrafting;
<ide> }
<ide>
<ide> public static Configuration getConfig() {
|
|
Java
|
mit
|
df6483610011f5a1b602ea8ee1ae31c0c2b7c434
| 0 |
xiurobert/TowerWarZ,xiurobert/TowerWarZ
|
package net.towerwarz.towers.AncientPack;
/**
* Created by xiurobert on 3/5/2015
* Made with IntelliJ IDEA
*/
public class Swordsman {
public int /*You know what to put here! */
}
|
src/main/java/net/towerwarz/towers/AncientPack/Swordsman.java
|
/*
* Attention: This is an illegal file
*/
//lol my mom said stop. 2 bad...
|
Update Swordsman.java
|
src/main/java/net/towerwarz/towers/AncientPack/Swordsman.java
|
Update Swordsman.java
|
<ide><path>rc/main/java/net/towerwarz/towers/AncientPack/Swordsman.java
<del>/*
<del> * Attention: This is an illegal file
<add>package net.towerwarz.towers.AncientPack;
<add>
<add>/**
<add> * Created by xiurobert on 3/5/2015
<add> * Made with IntelliJ IDEA
<ide> */
<del>//lol my mom said stop. 2 bad...
<add>
<add>public class Swordsman {
<add> public int /*You know what to put here! */
<add>}
<add>
|
|
Java
|
apache-2.0
|
e4ef54e9985fc3632bfb14473ac5f9e5ced0a058
| 0 |
cushon/bazel,bazelbuild/bazel,katre/bazel,cushon/bazel,cushon/bazel,katre/bazel,katre/bazel,ButterflyNetwork/bazel,ButterflyNetwork/bazel,katre/bazel,cushon/bazel,cushon/bazel,ButterflyNetwork/bazel,bazelbuild/bazel,katre/bazel,ButterflyNetwork/bazel,katre/bazel,ButterflyNetwork/bazel,bazelbuild/bazel,bazelbuild/bazel,cushon/bazel,bazelbuild/bazel,ButterflyNetwork/bazel,bazelbuild/bazel
|
// Copyright 2021 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.analysis;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.devtools.build.lib.packages.ExecGroup.DEFAULT_EXEC_GROUP_NAME;
import static java.util.stream.Collectors.joining;
import com.google.auto.value.AutoValue;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableTable;
import com.google.common.collect.Table;
import com.google.devtools.build.lib.analysis.platform.PlatformInfo;
import com.google.devtools.build.lib.packages.ExecGroup;
import com.google.devtools.build.lib.server.FailureDetails.Analysis;
import com.google.devtools.build.lib.server.FailureDetails.Analysis.Code;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.skyframe.SaneAnalysisException;
import com.google.devtools.build.lib.util.DetailedExitCode;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A container class for groups of {@link ExecGroup} instances. This correctly handles exec group
* inheritance between rules and targets. See
* https://docs.bazel.build/versions/main/exec-groups.html for further details.
*/
@AutoValue
public abstract class ExecGroupCollection {
public static Builder emptyBuilder() {
return new AutoValue_ExecGroupCollection_Builder(ImmutableMap.of());
}
public static Builder builder(
ExecGroup defaultExecGroup, ImmutableMap<String, ExecGroup> execGroups) {
// Post-process the groups to handle inheritance.
Map<String, ExecGroup> processedGroups = new LinkedHashMap<>();
for (Map.Entry<String, ExecGroup> entry : execGroups.entrySet()) {
String name = entry.getKey();
ExecGroup execGroup = entry.getValue();
if (execGroup.copyFrom() != null) {
if (execGroup.copyFrom().equals(DEFAULT_EXEC_GROUP_NAME)) {
execGroup = execGroup.inheritFrom(defaultExecGroup);
} else {
execGroup = execGroup.inheritFrom(execGroups.get(execGroup.copyFrom()));
}
}
processedGroups.put(name, execGroup);
}
return new AutoValue_ExecGroupCollection_Builder(ImmutableMap.copyOf(processedGroups));
}
/** Builder class for correctly constructing ExecGroupCollection instances. */
// Note that this is _not_ an actual @AutoValue.Builder: it provides more logic and has different
// fields.
@AutoValue
public abstract static class Builder {
public abstract ImmutableMap<String, ExecGroup> execGroups();
public ImmutableSet<String> getExecGroupNames() {
return execGroups().keySet();
}
public ExecGroup getExecGroup(String name) {
return execGroups().get(name);
}
public ExecGroupCollection build(
@Nullable ToolchainCollection<ResolvedToolchainContext> toolchainContexts,
ImmutableMap<String, String> rawExecProperties)
throws InvalidExecGroupException {
// For each exec group, compute the combined execution properties.
ImmutableTable<String, String, String> combinedExecProperties =
computeCombinedExecProperties(toolchainContexts, rawExecProperties);
return new AutoValue_ExecGroupCollection(execGroups(), combinedExecProperties);
}
}
/**
* Gets the combined exec properties of the platform and the target's exec properties. If a
* property is set in both, the target properties take precedence.
*/
private static ImmutableTable<String, String, String> computeCombinedExecProperties(
@Nullable ToolchainCollection<ResolvedToolchainContext> toolchainContexts,
ImmutableMap<String, String> rawExecProperties)
throws InvalidExecGroupException {
ImmutableSet<String> execGroupNames;
if (toolchainContexts == null) {
execGroupNames = ImmutableSet.of(DEFAULT_EXEC_GROUP_NAME);
} else {
execGroupNames = toolchainContexts.getExecGroupNames();
}
// Parse the target-level exec properties.
ImmutableTable<String, String, String> parsedTargetProperties =
parseExecProperties(rawExecProperties);
// Validate the exec group names in the properties.
if (toolchainContexts != null) {
ImmutableSet<String> unknownTargetExecGroupNames =
parsedTargetProperties.rowKeySet().stream()
.filter(name -> !name.equals(DEFAULT_EXEC_GROUP_NAME))
.filter(name -> !execGroupNames.contains(name))
.collect(toImmutableSet());
if (!unknownTargetExecGroupNames.isEmpty()) {
throw new InvalidExecGroupException(unknownTargetExecGroupNames);
}
}
// Parse each execution platform's exec properties.
ImmutableSet<PlatformInfo> executionPlatforms;
if (toolchainContexts == null) {
executionPlatforms = ImmutableSet.of();
} else {
executionPlatforms =
execGroupNames.stream()
.map(name -> toolchainContexts.getToolchainContext(name).executionPlatform())
.distinct()
.collect(toImmutableSet());
}
Map<PlatformInfo, ImmutableTable<String, String, String>> parsedPlatformProperties =
new LinkedHashMap<>();
for (PlatformInfo executionPlatform : executionPlatforms) {
ImmutableTable<String, String, String> parsed =
parseExecProperties(executionPlatform.execProperties());
parsedPlatformProperties.put(executionPlatform, parsed);
}
// First, get the defaults.
ImmutableMap<String, String> defaultExecProperties =
parsedTargetProperties.row(DEFAULT_EXEC_GROUP_NAME);
Table<String, String, String> result = HashBasedTable.create();
putAll(result, DEFAULT_EXEC_GROUP_NAME, defaultExecProperties);
for (String execGroupName : execGroupNames) {
ImmutableMap<String, String> combined =
computeProperties(
execGroupName,
defaultExecProperties,
toolchainContexts,
parsedPlatformProperties,
parsedTargetProperties);
putAll(result, execGroupName, combined);
}
return ImmutableTable.copyOf(result);
}
private static <R, C, V> void putAll(Table<R, C, V> builder, R row, Map<C, V> values) {
for (Map.Entry<C, V> entry : values.entrySet()) {
builder.put(row, entry.getKey(), entry.getValue());
}
}
private static ImmutableMap<String, String> computeProperties(
String execGroupName,
ImmutableMap<String, String> defaultExecProperties,
@Nullable ToolchainCollection<ResolvedToolchainContext> toolchainContexts,
Map<PlatformInfo, ImmutableTable<String, String, String>> parsedPlatformProperties,
ImmutableTable<String, String, String> parsedTargetProperties) {
ImmutableMap<String, String> defaultExecGroupPlatformProperties;
ImmutableMap<String, String> platformProperties;
if (toolchainContexts == null) {
defaultExecGroupPlatformProperties = ImmutableMap.of();
platformProperties = ImmutableMap.of();
} else {
PlatformInfo executionPlatform =
toolchainContexts.getToolchainContext(execGroupName).executionPlatform();
defaultExecGroupPlatformProperties =
parsedPlatformProperties.get(executionPlatform).row(DEFAULT_EXEC_GROUP_NAME);
platformProperties = parsedPlatformProperties.get(executionPlatform).row(execGroupName);
}
Map<String, String> targetProperties =
new LinkedHashMap<>(parsedTargetProperties.row(execGroupName));
for (String propertyName : defaultExecProperties.keySet()) {
// If the property exists in the default and not in the target, copy it.
targetProperties.computeIfAbsent(propertyName, defaultExecProperties::get);
}
// Combine the target and exec platform properties. Target properties take precedence.
// Use a HashMap instead of an ImmutableMap.Builder because we expect duplicate keys.
Map<String, String> combined = new LinkedHashMap<>();
combined.putAll(defaultExecGroupPlatformProperties);
combined.putAll(defaultExecProperties);
combined.putAll(platformProperties);
combined.putAll(targetProperties);
return ImmutableMap.copyOf(combined);
}
protected abstract ImmutableMap<String, ExecGroup> execGroups();
protected abstract ImmutableTable<String, String, String> execProperties();
public ExecGroup getExecGroup(String execGroupName) {
return execGroups().get(execGroupName);
}
public ImmutableMap<String, String> getExecProperties(String execGroupName) {
return execProperties().row(execGroupName);
}
/**
* Parse raw exec properties attribute value into a map of exec group names to their properties.
* The raw map can have keys of two forms: (1) 'property' and (2) 'exec_group_name.property'. The
* former get parsed into the default exec group, the latter get parsed into their relevant exec
* groups.
*/
private static ImmutableTable<String, String, String> parseExecProperties(
Map<String, String> rawExecProperties) {
ImmutableTable.Builder<String, String, String> execProperties = ImmutableTable.builder();
for (Map.Entry<String, String> execProperty : rawExecProperties.entrySet()) {
String rawProperty = execProperty.getKey();
int delimiterIndex = rawProperty.indexOf('.');
if (delimiterIndex == -1) {
execProperties.put(DEFAULT_EXEC_GROUP_NAME, rawProperty, execProperty.getValue());
} else {
String execGroup = rawProperty.substring(0, delimiterIndex);
String property = rawProperty.substring(delimiterIndex + 1);
execProperties.put(execGroup, property, execProperty.getValue());
}
}
return execProperties.buildOrThrow();
}
/** An error for when the user tries to access a non-existent exec group. */
public static final class InvalidExecGroupException extends Exception
implements SaneAnalysisException {
public InvalidExecGroupException(Collection<String> invalidNames) {
super(
String.format(
"Tried to set properties for non-existent exec groups: %s.",
invalidNames.stream().collect(joining(","))));
}
@Override
public DetailedExitCode getDetailedExitCode() {
return DetailedExitCode.of(
FailureDetail.newBuilder()
.setMessage(getMessage())
.setAnalysis(Analysis.newBuilder().setCode(Code.EXEC_GROUP_MISSING))
.build());
}
}
}
|
src/main/java/com/google/devtools/build/lib/analysis/ExecGroupCollection.java
|
// Copyright 2021 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.analysis;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.devtools.build.lib.packages.ExecGroup.DEFAULT_EXEC_GROUP_NAME;
import static java.util.stream.Collectors.joining;
import com.google.auto.value.AutoValue;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableTable;
import com.google.common.collect.Table;
import com.google.devtools.build.lib.analysis.platform.PlatformInfo;
import com.google.devtools.build.lib.packages.ExecGroup;
import com.google.devtools.build.lib.server.FailureDetails.Analysis;
import com.google.devtools.build.lib.server.FailureDetails.Analysis.Code;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.skyframe.SaneAnalysisException;
import com.google.devtools.build.lib.util.DetailedExitCode;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A container class for groups of {@link ExecGroup} instances. This correctly handles exec group
* inheritance between rules and targets. See
* https://docs.bazel.build/versions/main/exec-groups.html for further details.
*/
@AutoValue
public abstract class ExecGroupCollection {
public static Builder emptyBuilder() {
return new AutoValue_ExecGroupCollection_Builder(ImmutableMap.of());
}
public static Builder builder(
ExecGroup defaultExecGroup, ImmutableMap<String, ExecGroup> execGroups) {
// Post-process the groups to handle inheritance.
Map<String, ExecGroup> processedGroups = new LinkedHashMap<>();
for (Map.Entry<String, ExecGroup> entry : execGroups.entrySet()) {
String name = entry.getKey();
ExecGroup execGroup = entry.getValue();
if (execGroup.copyFrom() != null) {
if (execGroup.copyFrom().equals(DEFAULT_EXEC_GROUP_NAME)) {
execGroup = execGroup.inheritFrom(defaultExecGroup);
} else {
execGroup = execGroup.inheritFrom(execGroups.get(execGroup.copyFrom()));
}
}
processedGroups.put(name, execGroup);
}
return new AutoValue_ExecGroupCollection_Builder(ImmutableMap.copyOf(processedGroups));
}
/** Builder class for correctly constructing ExecGroupCollection instances. */
// Note that this is _not_ an actual @AutoValue.Builder: it provides more logic and has different
// fields.
@AutoValue
public abstract static class Builder {
public abstract ImmutableMap<String, ExecGroup> execGroups();
public ImmutableSet<String> getExecGroupNames() {
return execGroups().keySet();
}
public ExecGroup getExecGroup(String name) {
return execGroups().get(name);
}
public ExecGroupCollection build(
@Nullable ToolchainCollection<ResolvedToolchainContext> toolchainContexts,
ImmutableMap<String, String> rawExecProperties)
throws InvalidExecGroupException {
// For each exec group, compute the combined execution properties.
ImmutableTable<String, String, String> combinedExecProperties =
computeCombinedExecProperties(toolchainContexts, rawExecProperties);
return new AutoValue_ExecGroupCollection(execGroups(), combinedExecProperties);
}
}
/**
* Gets the combined exec properties of the platform and the target's exec properties. If a
* property is set in both, the target properties take precedence.
*/
private static ImmutableTable<String, String, String> computeCombinedExecProperties(
@Nullable ToolchainCollection<ResolvedToolchainContext> toolchainContexts,
ImmutableMap<String, String> rawExecProperties)
throws InvalidExecGroupException {
ImmutableSet<String> execGroupNames;
if (toolchainContexts == null) {
execGroupNames = ImmutableSet.of(DEFAULT_EXEC_GROUP_NAME);
} else {
execGroupNames = toolchainContexts.getExecGroupNames();
}
// Parse the target-level exec properties.
ImmutableTable<String, String, String> parsedTargetProperties =
parseExecProperties(rawExecProperties);
// Validate the exec group names in the properties.
if (toolchainContexts != null) {
ImmutableSet<String> unknownTargetExecGroupNames =
parsedTargetProperties.rowKeySet().stream()
.filter(name -> !name.equals(DEFAULT_EXEC_GROUP_NAME))
.filter(name -> !execGroupNames.contains(name))
.collect(toImmutableSet());
if (!unknownTargetExecGroupNames.isEmpty()) {
throw new InvalidExecGroupException(unknownTargetExecGroupNames);
}
}
// Parse each execution platform's exec properties.
ImmutableSet<PlatformInfo> executionPlatforms;
if (toolchainContexts == null) {
executionPlatforms = ImmutableSet.of();
} else {
executionPlatforms =
execGroupNames.stream()
.map(name -> toolchainContexts.getToolchainContext(name).executionPlatform())
.distinct()
.collect(toImmutableSet());
}
Map<PlatformInfo, ImmutableTable<String, String, String>> parsedPlatformProperties =
new LinkedHashMap<>();
for (PlatformInfo executionPlatform : executionPlatforms) {
ImmutableTable<String, String, String> parsed =
parseExecProperties(executionPlatform.execProperties());
parsedPlatformProperties.put(executionPlatform, parsed);
}
// First, get the defaults.
ImmutableMap<String, String> defaultExecProperties =
parsedTargetProperties.row(DEFAULT_EXEC_GROUP_NAME);
Table<String, String, String> result = HashBasedTable.create();
putAll(result, DEFAULT_EXEC_GROUP_NAME, defaultExecProperties);
for (String execGroupName : execGroupNames) {
ImmutableMap<String, String> combined =
computeProperties(
execGroupName,
defaultExecProperties,
toolchainContexts,
parsedPlatformProperties,
parsedTargetProperties);
putAll(result, execGroupName, combined);
}
return ImmutableTable.copyOf(result);
}
private static <R, C, V> void putAll(Table<R, C, V> builder, R row, Map<C, V> values) {
for (Map.Entry<C, V> entry : values.entrySet()) {
builder.put(row, entry.getKey(), entry.getValue());
}
}
private static ImmutableMap<String, String> computeProperties(
String execGroupName,
ImmutableMap<String, String> defaultExecProperties,
@Nullable ToolchainCollection<ResolvedToolchainContext> toolchainContexts,
Map<PlatformInfo, ImmutableTable<String, String, String>> parsedPlatformProperties,
ImmutableTable<String, String, String> parsedTargetProperties) {
ImmutableMap<String, String> defaultExecGroupPlatformProperties;
ImmutableMap<String, String> platformProperties;
if (toolchainContexts == null) {
defaultExecGroupPlatformProperties = ImmutableMap.of();
platformProperties = ImmutableMap.of();
} else {
PlatformInfo executionPlatform =
toolchainContexts.getToolchainContext(execGroupName).executionPlatform();
defaultExecGroupPlatformProperties =
parsedPlatformProperties.get(executionPlatform).row(DEFAULT_EXEC_GROUP_NAME);
platformProperties = parsedPlatformProperties.get(executionPlatform).row(execGroupName);
}
Map<String, String> targetProperties =
new LinkedHashMap<>(parsedTargetProperties.row(execGroupName));
for (String propertyName : defaultExecProperties.keySet()) {
// If the property exists in the default and not in the target, copy it.
targetProperties.computeIfAbsent(propertyName, defaultExecProperties::get);
}
// Combine the target and exec platform properties. Target properties take precedence.
// Use a HashMap instead of an ImmutableMap.Builder because we expect duplicate keys.
Map<String, String> combined = new LinkedHashMap<>();
combined.putAll(defaultExecGroupPlatformProperties);
combined.putAll(defaultExecProperties);
combined.putAll(platformProperties);
combined.putAll(targetProperties);
return ImmutableMap.copyOf(combined);
}
protected abstract ImmutableMap<String, ExecGroup> execGroups();
protected abstract ImmutableTable<String, String, String> execProperties();
public ExecGroup getExecGroup(String execGroupName) {
return execGroups().get(execGroupName);
}
public ImmutableMap<String, String> getExecProperties(String execGroupName) {
return execProperties().row(execGroupName);
}
/**
* Parse raw exec properties attribute value into a map of exec group names to their properties.
* The raw map can have keys of two forms: (1) 'property' and (2) 'exec_group_name.property'. The
* former get parsed into the default exec group, the latter get parsed into their relevant exec
* groups.
*/
private static ImmutableTable<String, String, String> parseExecProperties(
Map<String, String> rawExecProperties) {
ImmutableTable.Builder<String, String, String> execProperties = ImmutableTable.builder();
for (Map.Entry<String, String> execProperty : rawExecProperties.entrySet()) {
String rawProperty = execProperty.getKey();
int delimiterIndex = rawProperty.indexOf('.');
if (delimiterIndex == -1) {
execProperties.put(DEFAULT_EXEC_GROUP_NAME, rawProperty, execProperty.getValue());
} else {
String execGroup = rawProperty.substring(0, delimiterIndex);
String property = rawProperty.substring(delimiterIndex + 1);
execProperties.put(execGroup, property, execProperty.getValue());
}
}
return execProperties.build();
}
/** An error for when the user tries to access a non-existent exec group. */
public static final class InvalidExecGroupException extends Exception
implements SaneAnalysisException {
public InvalidExecGroupException(Collection<String> invalidNames) {
super(
String.format(
"Tried to set properties for non-existent exec groups: %s.",
invalidNames.stream().collect(joining(","))));
}
@Override
public DetailedExitCode getDetailedExitCode() {
return DetailedExitCode.of(
FailureDetail.newBuilder()
.setMessage(getMessage())
.setAnalysis(Analysis.newBuilder().setCode(Code.EXEC_GROUP_MISSING))
.build());
}
}
}
|
Automatic code cleanup.
PiperOrigin-RevId: 421089618
|
src/main/java/com/google/devtools/build/lib/analysis/ExecGroupCollection.java
|
Automatic code cleanup.
|
<ide><path>rc/main/java/com/google/devtools/build/lib/analysis/ExecGroupCollection.java
<ide> execProperties.put(execGroup, property, execProperty.getValue());
<ide> }
<ide> }
<del> return execProperties.build();
<add> return execProperties.buildOrThrow();
<ide> }
<ide>
<ide> /** An error for when the user tries to access a non-existent exec group. */
|
|
JavaScript
|
mit
|
63e35c6185a5d26208f77c41fcc616d8084df4a4
| 0 |
rafalp/django-ember-gettext,rafalp/django-ember-gettext
|
import Ember from 'ember';
function gettextHelper(args, kwargs) {
var msgid = args[0];
if (Object.getOwnPropertyNames(kwargs).length > 0) {
return interpolate(gettext(msgid), kwargs, true);
} else {
return gettext(msgid);
}
}
function ngettextHelper(args, kwargs) {
var singular = args[0];
var plural = args[1];
var count = args[2];
kwargs.count = count;
return interpolate(ngettext(singular, plural, count), kwargs, true);
}
function pgettextHelper(args, kwargs) {
var context = args[0];
var msgid = args[1];
if (Object.getOwnPropertyNames(kwargs).length > 0) {
return interpolate(pgettext(context, msgid), kwargs, true);
} else {
return pgettext(context, msgid);
}
}
function npgettextHelper(args, kwargs) {
var context = args[0];
var singular = args[1];
var plural = args[2];
var count = args[3];
kwargs.count = count;
return interpolate(npgettext(context, singular, plural, count), kwargs, true);
}
export default function() {
var makeBoundHelper = Ember.HTMLBars.makeBoundHelper;
var registerHelper = Ember.HTMLBars.registerHelper;
registerHelper('gettext', makeBoundHelper(gettextHelper));
registerHelper('ngettext', makeBoundHelper(ngettextHelper));
registerHelper('pgettext', makeBoundHelper(pgettextHelper));
registerHelper('npgettext', makeBoundHelper(npgettextHelper));
}
|
addon/helpers/gettext.js
|
import Ember from 'ember';
export function gettextHelper(args, kwargs) {
var msgid = args[0];
if (Object.getOwnPropertyNames(kwargs).length > 0) {
return interpolate(gettext(msgid), kwargs, true);
} else {
return gettext(msgid);
}
}
export function ngettextHelper(args, kwargs) {
var singular = args[0];
var plural = args[1];
var count = args[2];
kwargs.count = count;
return interpolate(ngettext(singular, plural, count), kwargs, true);
}
export function pgettextHelper(args, kwargs) {
var context = args[0];
var msgid = args[1];
if (Object.getOwnPropertyNames(kwargs).length > 0) {
return interpolate(pgettext(context, msgid), kwargs, true);
} else {
return pgettext(context, msgid);
}
}
export function npgettextHelper(args, kwargs) {
var context = args[0];
var singular = args[1];
var plural = args[2];
var count = args[3];
kwargs.count = count;
return interpolate(npgettext(context, singular, plural, count), kwargs, true);
}
export function registerGettextHelpers() {
var makeBoundHelper = Ember.HTMLBars.makeBoundHelper;
var registerHelper = Ember.HTMLBars.registerHelper;
registerHelper('gettext', makeBoundHelper(gettextHelper));
registerHelper('ngettext', makeBoundHelper(ngettextHelper));
registerHelper('pgettext', makeBoundHelper(pgettextHelper));
registerHelper('npgettext', makeBoundHelper(npgettextHelper));
}
|
Updated exports
|
addon/helpers/gettext.js
|
Updated exports
|
<ide><path>ddon/helpers/gettext.js
<ide> import Ember from 'ember';
<ide>
<del>export function gettextHelper(args, kwargs) {
<add>function gettextHelper(args, kwargs) {
<ide> var msgid = args[0];
<ide>
<ide> if (Object.getOwnPropertyNames(kwargs).length > 0) {
<ide> }
<ide> }
<ide>
<del>export function ngettextHelper(args, kwargs) {
<add>function ngettextHelper(args, kwargs) {
<ide> var singular = args[0];
<ide> var plural = args[1];
<ide> var count = args[2];
<ide> return interpolate(ngettext(singular, plural, count), kwargs, true);
<ide> }
<ide>
<del>export function pgettextHelper(args, kwargs) {
<add>function pgettextHelper(args, kwargs) {
<ide> var context = args[0];
<ide> var msgid = args[1];
<ide>
<ide> }
<ide> }
<ide>
<del>export function npgettextHelper(args, kwargs) {
<add>function npgettextHelper(args, kwargs) {
<ide> var context = args[0];
<ide> var singular = args[1];
<ide> var plural = args[2];
<ide> return interpolate(npgettext(context, singular, plural, count), kwargs, true);
<ide> }
<ide>
<del>export function registerGettextHelpers() {
<add>export default function() {
<ide> var makeBoundHelper = Ember.HTMLBars.makeBoundHelper;
<ide> var registerHelper = Ember.HTMLBars.registerHelper;
<ide>
|
|
JavaScript
|
apache-2.0
|
78654196b4e7630a1263838136f2c81f02a98953
| 0 |
WFCD/genesis,Warframe-Community-Developers/genesis,WFCD/genesis
|
'use strict';
const mysql = require('mysql2/promise');
const SQL = require('sql-template-strings');
const Promise = require('bluebird');
const schema = require('./schema.js');
const CustomCommand = require('../CustomCommand.js');
/**
* Connection options for the database
* @typedef {Object} DbConnectionOptions
* @property {string} [host=localhost] - The hostname of the database
* @property {number} [port=3306] - The port number to connect to
* @property {string} user - The user to authenticate as
* @property {string} password - The password for that user
* @property {string} database - The database to use
*/
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const makeId = () => {
const tokens = [];
for (let i = 0; i < 8; i += 1) {
tokens.push(possible.charAt(Math.floor(Math.random() * possible.length)));
}
return tokens.join('');
};
/**
* Persistent storage for the bot
*/
class Database {
/**
* @param {DbConnectionOptions} dbOptions Connection options for the database
* @param {Genesis} bot Bot to load the settings for
*/
constructor(dbOptions, bot) {
const opts = {
supportBigNumbers: true,
bigNumberStrings: true,
Promise,
};
Object.assign(opts, dbOptions);
this.db = mysql.createPool(opts);
this.bot = bot;
this.logger = bot.logger;
this.defaults = {
prefix: '/',
respond_to_settings: true,
platform: 'pc',
language: 'en',
delete_after_respond: true,
delete_response: true,
createPrivateChannel: false,
deleteExpired: false,
allowCustom: false,
allowInline: false,
};
}
/**
* Creates the required tables in the database
* @returns {Promise}
*/
createSchema() {
return Promise.mapSeries(schema, q => this.db.query(q));
}
/**
* Initialize data for guilds in channels for existing guilds
* @param {Client} client for pulling guild information
*/
ensureData(client) {
const promises = [];
client.guilds.array().forEach((guild) => {
if (guild.channels.array().length) {
promises.push(this.addGuild(guild));
}
});
Promise.all(promises.map(x => x.reflect()))
.then((results) => {
results.forEach((result) => {
if (result && !result.isFulfilled()) {
this.logger.error(result.reason());
}
});
});
}
/**
* Adds a new guild to the database
* @param {Guild} guild A Discord guild (server)
* @returns {Promise}
*/
addGuild(guild) {
const channelIDs = guild.channels.filter(c => c.type === 'text').keyArray();
const query = SQL`INSERT IGNORE INTO channels (id, guild_id) VALUES `;
channelIDs.forEach((id, index) => {
query.append(SQL`(${id}, ${guild.id})`).append(index !== (channelIDs.length - 1) ? ',' : ';');
});
return this.db.query(query);
}
/**
* Deletes a guild from the database
* @param {Guild} guild A Discord guild (server)
* @returns {Promise}
*/
deleteGuild(guild) {
const query = SQL`DELETE FROM channels WHERE guild_id = ${guild.id};`;
return this.db.query(query);
}
/**
* Gets the current count of guilds and channels
* @returns {Promise}
*/
async getChannelAndGuildCounts() {
const query = 'select count(distinct guild_id) as countGuilds, count(distinct id) as countChannels from channels;';
const res = await this.db.query(query);
if (res[0]) {
return {
channels: res[0].countChannels,
guilds: res[0].countGuilds,
};
}
return {};
}
/**
* Adds a new guild text channel to the database
* @param {TextChannel} channel A discord guild text channel
* @returns {Promise}
*/
async addGuildTextChannel(channel) {
const query = SQL`INSERT IGNORE INTO channels (id, guild_id) VALUES (${channel.id}, ${channel.guild.id});`;
return this.db.query(query);
}
/**
* Adds a new DM or group DM channel to the database
* @param {DMChannel|GroupDMChannel} channel A discord DM or group DM channel
* @returns {Promise}
*/
async addDMChannel(channel) {
const query = SQL`INSERT IGNORE INTO channels (id) VALUES (${channel.id});`;
return this.db.query(query);
}
/**
* Deletes a channel from the database
* @param {Channel} channel The channel to delete
* @returns {Promise}
*/
async deleteChannel(channel) {
const query = SQL`DELETE FROM channels WHERE id = ${channel.id};`;
return this.db.query(query);
}
async checkWebhookAndReturn(channel, setting) {
if (!/webhook/.test(setting)) {
await this.setChannelSetting(channel, setting, this.defaults[`${setting}`]);
return this.defaults[`${setting}`];
}
return undefined;
}
/**
* Get a setting for a particular channel
* @param {Channel} channel channel to get the setting for
* @param {string} setting name of the setting to get
* @returns {Promise} setting
*/
async getChannelSetting(channel, setting) {
const query = SQL`SELECT val FROM settings WHERE channel_id=${channel.id} and setting=${setting};`;
const res = await this.db.query(query);
if (res[0].length === 0) {
if (channel.type === 'text') {
await this.addGuildTextChannel(channel);
return this.checkWebhookAndReturn(channel, setting);
}
await this.addDMChannel(channel);
return this.checkWebhookAndReturn(channel, setting);
}
return res[0][0].val;
}
async getChannelWebhook(channel) {
return {
avatar: await this.getChannelSetting(channel, 'webhookAvatar') || this.bot.client.user.avatarURL.replace('?size=2048', ''),
name: await this.getChannelSetting(channel, 'webhookName') || this.bot.client.user.username,
id: await this.getChannelSetting(channel, 'webhookId'),
token: await this.getChannelSetting(channel, 'webhookToken'),
};
}
/**
* Get a setting for a particular channel
* @param {Channel} channel channel to get the setting for
* @param {string} setting name of the setting to set
* @param {string|boolean} value value of the setting to be set
* @returns {Promise} setting
*/
async setChannelSetting(channel, setting, value) {
const query = SQL`INSERT IGNORE INTO settings (channel_id, setting, val) VALUE (${channel.id},${setting},${value}) ON DUPLICATE KEY UPDATE val=${value};`;
return this.db.query(query);
}
/**
* Resets the custom prefix for this guild to the bot's globally configured prefix
* @param {Guild} guild The Discord guild for which to set the response setting
* @param {string} setting Name of the setting to set
* @param {string|boolean} val value of the setting to be set
* @returns {Promise}
*/
async setGuildSetting(guild, setting, val) {
const promises = [];
guild.channels.array().forEach((channel) => {
promises.push(this.setChannelSetting(channel, setting, val));
});
return Promise.all(promises);
}
/**
* Enables notifications for an item in a channel
* @param {Channel} channel The channel where to enable notifications
* @param {string} item The item to track
* @returns {Promise}
*/
async trackItem(channel, item) {
const query = SQL`INSERT IGNORE INTO item_notifications (channel_id, item) VALUES (${channel.id},${item});`;
return this.db.query(query);
}
/**
* Disables notifications for an item in a channel
* @param {Channel} channel The channel where to enable notifications
* @param {string} item The item to track
* @returns {Promise}
*/
async untrackItem(channel, item) {
const query = SQL`DELETE FROM item_notifications WHERE channel_id = ${channel.id} AND item = ${item};`;
return this.db.query(query);
}
/**
* Enables notifications for an event type in a channel
* @param {Channel} channel The channel where to enable notifications
* @param {string} type The item to track
* @returns {Promise}
*/
async trackEventType(channel, type) {
const query = SQL`INSERT IGNORE INTO type_notifications (channel_id, type) VALUES (${channel.id},${type});`;
return this.db.query(query);
}
/**
* Disables notifications for an event type in a channel
* @param {Channel} channel The channel where to enable notifications
* @param {string} type The item to track
* @returns {Promise}
*/
async untrackEventType(channel, type) {
const query = SQL`DELETE FROM type_notifications WHERE channel_id = ${channel.id} AND type = ${type};`;
return this.db.query(query);
}
/**
* Enables or disables pings for an item in a channel
* @param {TextChannel} channel The channel where to enable notifications
* @param {string} item The item to set ping status for
* @param {boolean} enabled true to enable pinging, false to disable
* @returns {Promise}
*/
async setItemPing(channel, item, enabled) {
const query = SQL`UPDATE item_notifications SET ping = ${enabled} WHERE channel_id = ${channel.id}
AND item = ${item};`;
return this.db.query(query);
}
/**
* Enables or disables pings for an event type in a channel
* @param {TextChannel} channel The channel where to enable notifications
* @param {string} type The event type to set ping status for
* @param {boolean} enabled true to enable pinging, false to disable
* @returns {Promise}
*/
async setEventTypePing(channel, type, enabled) {
const query = SQL`UPDATE type_notifications SET ping = ${enabled} WHERE channel_id = ${channel.id}
AND type = ${type};`;
return this.db.query(query);
}
/**
* Sets a ping message for an item or event type in a guild
* @param {Guild} guild The guild
* @param {string} itemOrType The item or event type to set the ping message for
* @param {string} text The text of the ping message
* @returns {Promise}
*/
async setPing(guild, itemOrType, text) {
const query = SQL`INSERT INTO pings VALUES (${guild.id}, ${itemOrType}, ${text})
ON DUPLICATE KEY UPDATE text = ${text};`;
return this.db.query(query);
}
/**
* Get all pings for a guild for the provided event types and items
* @param {Guild} guild Guild to get pings for
* @param {Array.<string>} itemsOrTypes array of strings corresponding to event and reward types
* @returns {Promise.<string>} Promise of a string to prepend to a message
*/
async getPing(guild, itemsOrTypes) {
const query = SQL`SELECT text FROM pings WHERE guild_id=${guild.id} AND item_or_type in (${itemsOrTypes})`;
const res = await this.db.query(query);
if (res[0].length === 0) {
return '';
}
return res[0]
.map(result => result.text).join(', ');
}
/**
* Clear all pings for a guild
* @param {Guild} guild The guild
* @returns {Promise}
*/
async clearPingsForGuild(guild) {
const query = SQL`DELETE FROM pings WHERE guild_id=${guild.id}`;
return this.db.query(query);
}
async getPingsForGuild(guild) {
if (guild) {
const query = SQL`SELECT item_or_type, text FROM pings WHERE guild_id=${guild.id}`;
const res = await this.db.query(query);
if (res[0].length === 0) {
return [];
}
return res[0]
.map(result => ({ text: result.text, thing: result.item_or_type }));
}
return [];
}
/**
* Removes a ping message
* @param {Guild} guild The guild where the ping message is currently being sent
* @param {string} itemOrType The item or event type associated to the ping message
* @returns {Promise}
*/
async removePing(guild, itemOrType) {
if (guild) {
const query = SQL`DELETE FROM pings WHERE guild_id = ${guild.id} AND item_or_type = ${itemOrType};`;
return this.db.query(query);
}
return false;
}
/**
* Returns all the channels that should get a notification for the items in the list
* @param {string} type The type of the event
* @param {string} platform The platform of the event
* @param {Array.<string>} items The items in the reward that is being notified
* @returns {Promise.<Array.<{channel_id: string, webhook: string}>>}
*/
async getNotifications(type, platform, items) {
try {
const query = SQL`SELECT DISTINCT channels.id as channelId
FROM type_notifications`
.append(items && items.length > 0 ?
SQL` INNER JOIN item_notifications ON type_notifications.channel_id = item_notifications.channel_id` : SQL``)
.append(SQL` INNER JOIN channels ON channels.id = type_notifications.channel_id`)
.append(SQL` INNER JOIN settings ON channels.id = settings.channel_id`)
.append(SQL`
WHERE type_notifications.type = ${String(type)}
AND MOD(IFNULL(channels.guild_id, 0) >> 22, ${this.bot.shardCount}) = ${this.bot.shardId}
AND settings.setting = "platform" AND settings.val = ${platform || 'pc'} `)
.append(items && items.length > 0 ? SQL`AND item_notifications.item IN (${items})
AND item_notifications.channel_id = settings.channel_id;` : SQL`;`);
return this.db.query(query);
} catch (e) {
this.logger.error(e);
return [];
}
}
/**
* Returns the items that the channel is tracking
* @param {Channel} channel A Discord channel
* @returns {Promise.<Array.<string>>}
*/
async getTrackedItems(channel) {
const query = SQL`SELECT item FROM item_notifications WHERE channel_id = ${channel.id};`;
const res = await this.db.query(query);
return res[0].map(r => r.item);
}
/**
* Returns the event types that the channel is tracking
* @param {Channel} channel A Discord channel
* @returns {Promise.<Array.<string>>}
*/
async getTrackedEventTypes(channel) {
const query = SQL`SELECT type FROM type_notifications WHERE channel_id = ${channel.id};`;
const res = await this.db.query(query);
return res[0].map(r => r.type);
}
async deleteChannelPermissions(channel) {
const query = SQL`DELETE FROM channel_permissions WHERE channel_id = ${channel.id}`;
return this.db.query(query);
}
async deleteGuildPermissions(guild) {
const query = SQL`DELETE FROM guild_permissions WHERE guild_id = ${guild.id}`;
return this.db.query(query);
}
/**
* Enables or disables a command for an individual member in a channel
* @param {GuildChannel} channel - A discord guild channel
* @param {GuildMember} member - A discord guild member
* @param {string} commandId - The ID of the command to set the permission for
* @param {boolean} allowed - Whether this member should be allowed to use this command
* @returns {Promise}
*/
async setChannelPermissionForMember(channel, member, commandId, allowed) {
const query = SQL`INSERT INTO channel_permissions VALUES
(${channel.id}, ${member.id}, TRUE, ${commandId}, ${allowed})
ON DUPLICATE KEY UPDATE allowed = ${allowed};`;
return this.db.query(query);
}
/**
* Enables or disables a command for a role in a channel
* @param {GuildChannel} channel - A discord guild channel
* @param {Role} role - A discord role
* @param {string} commandId - The ID of the command to set the permission for
* @param {boolean} allowed - Whether this member should be allowed to use this command
* @returns {Promise}
*/
async setChannelPermissionForRole(channel, role, commandId, allowed) {
const query = SQL`INSERT INTO channel_permissions VALUES
(${channel.id}, ${role.id}, FALSE, ${commandId}, ${allowed})
ON DUPLICATE KEY UPDATE allowed = ${allowed};`;
return this.db.query(query);
}
/**
* Enables or disables a command for an individual member in a guild
* @param {Guild} guild - A discord guild
* @param {GuildMember} member - A discord guild member
* @param {string} commandId - The ID of the command to set the permission for
* @param {boolean} allowed - Whether this member should be allowed to use this command
* @returns {Promise}
*/
async setGuildPermissionForMember(guild, member, commandId, allowed) {
const query = SQL`INSERT INTO guild_permissions VALUES
(${guild.id}, ${member.id}, TRUE, ${commandId}, ${allowed})
ON DUPLICATE KEY UPDATE allowed = ${allowed};`;
return this.db.query(query);
}
/**
* Enables or disables a command for a role in a channel
* @param {Guild} guild - A discord guild
* @param {Role} role - A discord role
* @param {string} commandId - The ID of the command to set the permission for
* @param {boolean} allowed - Whether this member should be allowed to use this command
* @returns {Promise}
*/
async setGuildPermissionForRole(guild, role, commandId, allowed) {
const query = SQL`INSERT INTO guild_permissions VALUES
(${guild.id}, ${role.id}, FALSE, ${commandId}, ${allowed})
ON DUPLICATE KEY UPDATE allowed = ${allowed};`;
return this.db.query(query);
}
/**
* Stops tracking all event types in a channel (disables all notifications)
* @param {Channel} channel - A Discord channel
* @returns {Promise}
*/
async stopTracking(channel) {
const query = SQL`DELETE FROM type_notifications WHERE channel_id = ${channel.id};`;
return this.db.query(query);
}
/**
* Gets whether or not a user is allowed to use a particular command in a channel
* @param {Channel} channel - A Discord channel
* @param {string} memberId - String representing a user identifier
* @param {string} commandId - String representing a command identifier
* @returns {Promise}
*/
async getChannelPermissionForMember(channel, memberId, commandId) {
const query = SQL`SELECT allowed FROM channel_permissions
WHERE channel_id = ${channel.id} AND command_id = ${commandId}
AND is_user = true AND target_id = ${memberId}`;
const res = await this.db.query(query);
if (res[0].length === 0) {
return 'none';
}
return res.rows[0].allowed;
}
/**
* Gets whether or not a role is allowed to use a particular command in a channel
* @param {Channel} channel A Discord channel
* @param {string} role String representing a user identifier
* @param {string} commandId String representing a command identifier
* @returns {Promise}
*/
async getChannelPermissionForRole(channel, role, commandId) {
const query = SQL`SELECT allowed FROM channel_permissions
WHERE channel_id = ${channel.id} AND command_id = ${commandId}
AND is_user = false AND target_id = ${role.id}`;
const res = await this.db.query(query);
if (res[0].length === 0) {
return 'none';
}
return res.rows[0].allowed === 1;
}
/**
* Gets whether or not a role in the user's
* roles allows the user to use a particular command in a channel
* @param {Channel} channel - A Discord channel
* @param {User} user - A Discord user
* @param {string} commandId - A command id for designating
* a command to check permisions for
* @returns {Promise}
*/
async getChannelPermissionForUserRoles(channel, user, commandId) {
const userRoles = channel.type === 'text' ? channel.guild.member(user).roles : {};
const userRoleIds = userRoles.keyArray();
const query = SQL`SELECT target_id, is_user, allowed
FROM channel_permissions
WHERE channel_permissions.channel_id = ${channel.id}
AND channel_permissions.target_id IN (${userRoleIds})
AND command_id = ${commandId}
UNION SELECT guild_permissions.target_id AS target_id,
guild_permissions.is_user AS is_user,
guild_permissions.allowed AS allowed
FROM guild_permissions
INNER JOIN channels USING (guild_id)
LEFT JOIN channel_permissions ON
channel_permissions.channel_id = channels.id
AND guild_permissions.command_id = channel_permissions.command_id
AND guild_permissions.target_id = channel_permissions.target_id
WHERE channel_permissions.target_id IS NULL
AND channels.id = ${channel.id}
AND guild_permissions.target_id IN (${userRoleIds});`;
const res = await this.db.query(query);
if (res[0].length === 0) {
return 'none';
}
return res[0][0].allowed;
}
/**
* Gets whether or not a user is allowed to use a particular command in a guild
* @param {Guild} guild - A Discord guild
* @param {string} memberId - String representing a user identifier
* @param {string} commandId - String representing a command identifier
* @returns {Promise}
*/
async getGuildPermissionForMember(guild, memberId, commandId) {
const query = SQL`SELECT allowed FROM guild_permissions
WHERE channel_id = ${guild.id} AND command_id = ${commandId}
AND is_user = true AND target_id = ${memberId}`;
const res = await this.db.query(query);
if (res.rows.length === 0) {
throw new Error(`The guild permissions for the guild ${guild.id}
for member ${memberId} was not found in the database`);
}
return res.rows[0].allowed;
}
/**
* Gets whether or not a role is allowed to use a particular command in a guild
* @param {Guild} guild - A Discord guild
* @param {string} role String representing a user identifier
* @param {string} commandId String representing a command identifier
* @returns {Promise}
*/
async getGuildPermissionForRole(guild, role, commandId) {
const query = SQL`SELECT allowed FROM guild_permissions
WHERE channel_id = ${guild.id} AND command_id = ${commandId}
AND is_user = false AND target_id = ${role.id}`;
const res = await this.db.query(query);
if (res.rows.length === 0) {
throw new Error(`The guild permissions for the guild ${guild.id}
for member ${role.id} was not found in the database`);
}
return res.rows[0].allowed;
}
/**
* Remove guild from database
* @param {snowflake} guild Guild to be removed from database
* @returns {Promise.<string>} status of removal
*/
async removeGuild(guild) {
const channelIds = guild.channels.keyArray();
const results = [];
channelIds.forEach((channelId) => {
results.push(this.removeChannelPermissions(channelId));
results.push(this.removeItemNotifications(channelId));
});
results.push(this.removeGuildPermissions(guild.id));
results.push(this.removePings(guild.id));
await Promise.all(results);
const query = SQL`DELETE FROM channels WHERE guild_id = ${guild.id})`;
return this.db.query(query);
}
/**
* Remove permissions corresponding to the guild id
* @param {snowflake} guildId guild identifier for removal
* @returns {Promise.<string>} status of removal
*/
async removeGuildPermissions(guildId) {
const query = SQL`DELETE FROM guild_permissions WHERE guild_id = ${guildId}`;
return this.db.query(query);
}
/**
* Remove permissions corresponding to the guild id
* @param {snowflake} channelId channel identifier for removal
* @returns {Promise.<string>} status of removal
*/
async removeChannelPermissions(channelId) {
const query = SQL`DELETE FROM channel_permisions WHERE channel_id = ${channelId}`;
return this.db.query(query);
}
/**
* Remove permissions corresponding to the channel id
* @param {snowflake} channelId channel identifier for removal
* @returns {Promise.<string>} status of removal
*/
async removeItemNotifications(channelId) {
const query = SQL`DELETE FROM item_notifications WHERE channel_id = ${channelId}`;
return this.db.query(query);
}
/**
* Remove pings corresponding to the guild id
* @param {snowflake} guildId guild identifier for removal
* @returns {Promise.<string>} status of removal
*/
async removePings(guildId) {
const query = SQL`DELETE FROM pings WHERE guild_id = ${guildId}`;
return this.db.query(query);
}
/**
* Set the notified ids for a given platform and shard id
* @param {string} platform platform corresponding to notified ids
* @param {number} shardId shard id corresponding to notified ids
* @param {JSON} notifiedIds list of oids that have been notifiedIds
* @returns {Promise}
*/
async setNotifiedIds(platform, shardId, notifiedIds) {
const query = SQL`INSERT INTO notified_ids VALUES
(${shardId}, ${platform}, JSON_ARRAY(${notifiedIds}))
ON DUPLICATE KEY UPDATE id_list = JSON_ARRAY(${notifiedIds});`;
return this.db.query(query);
}
/**
* Get list of notified ids for the given platform and shard id
* @param {string} platform Platform
* @param {number} shardId Identifier of the corresponding shard
* @returns {Promise.<Array>} Array of notified oids
*/
async getNotifiedIds(platform, shardId) {
const query = SQL`SELECT id_list
FROM notified_ids
WHERE shard_id=${shardId} AND platform=${platform};`;
const res = await this.db.query(query);
if (res[0].length === 0) {
return [];
}
return res[0][0].id_list;
}
/**
* Set the joinable roles for a guild
* @param {Guild} guild Guild to set joinable roles for
* @param {Array.<string>} roles Array of role ids to set
* @returns {Promise}
*/
async setRolesForGuild(guild, roles) {
const query = SQL`INSERT INTO guild_joinable_roles VALUES
(${guild.id}, JSON_ARRAY(${roles}))
ON DUPLICATE KEY UPDATE id_list = JSON_ARRAY(${roles});`;
return this.db.query(query);
}
/**
* Get the roles that can be joined for a guild
* @param {Guild} guild [description]
* @returns {Promise.<Array.<Role>>} Promise of array of roles that are joinable
*/
async getRolesForGuild(guild) {
const query = SQL`SELECT id_list
FROM guild_joinable_roles
WHERE guild_id=${guild.id}`;
const res = await this.db.query(query);
if (res[0][0]) {
const validListIds = res[0][0].id_list
.filter(id => typeof this.bot.client.guilds.get(guild.id).roles.get(id) !== 'undefined');
const validList = validListIds
.map(id => this.bot.client.guilds.get(guild.id).roles.get(id));
return validList;
}
return [];
}
/**
* Get a dump of allowed and denied permissions
* @param {Guild} guild guild to fetch settings for
* @returns {Object} Data about allowed data
*/
async permissionsForGuild(guild) {
const query = SQL`SELECT * FROM guild_permissions WHERE guild_id = ${guild.id}`;
const res = await this.db.query(query);
if (res[0]) {
return res[0].map(value => ({
level: 'guild',
command: value.command_id,
isAllowed: value.allowed,
type: value.is_user ? 'user' : 'role',
appliesToId: value.target_id,
}));
}
return [];
}
/**
* Get a dump of allowed and denied permissions
* @param {Channel} channel channel to fetch settings for
* @returns {Object} Data about allowed data
*/
async permissionsForChannel(channel) {
const query = SQL`SELECT * FROM channel_permissions WHERE channel_id = ${channel.id}`;
const res = await this.db.query(query);
if (res[0]) {
return res[0].map(value => ({
level: 'channel',
command: value.command_id,
isAllowed: value.allowed,
type: value.is_user ? 'user' : 'role',
appliesToId: value.target_id,
}));
}
return [];
}
async addPrivateRoom(guild, textChannel, voiceChannel) {
const query = SQL`INSERT INTO private_channels (guild_id, text_id, voice_id) VALUES (${guild.id}, ${textChannel.id}, ${voiceChannel.id})`;
return this.db.query(query);
}
async deletePrivateRoom(guild, textChannel, voiceChannel) {
const query = SQL`DELETE FROM private_channels WHERE guild_id = ${guild.id} AND text_id = ${textChannel.id} AND voice_id = ${voiceChannel.id}`;
return this.db.query(query);
}
async getPrivateRooms() {
const query = SQL`SELECT guild_id, text_id, voice_id, created_at as crt_sec FROM private_channels WHERE MOD(IFNULL(guild_id, 0) >> 22, ${this.bot.shardCount}) = ${this.bot.shardId}`;
const res = await this.db.query(query);
if (res[0]) {
return res[0].map(value => ({
guild: this.bot.client.guilds.get(value.guild_id),
textChannel: this.bot.client.channels.get(value.text_id),
voiceChannel: this.bot.client.channels.get(value.voice_id),
createdAt: value.crt_sec,
}));
}
return [];
}
async getCommandContext(channel) {
const prefix = await this.getChannelSetting(channel, 'prefix');
const allowCustom = await this.getChannelSetting(channel, 'allowCustom') === '1';
const allowInline = await this.getChannelSetting(channel, 'allowInline') === '1';
const webhook = {
id: await this.getChannelSetting(channel, 'webhookId'),
token: await this.getChannelSetting(channel, 'webhookToken'),
name: await this.getChannelSetting(channel, 'webhookName'),
avatar: await this.getChannelSetting(channel, 'webhookAvatar'),
};
return {
prefix, allowCustom, allowInline, webhook, channel,
};
}
async getCustomCommands() {
const query = SQL`SELECT * FROM custom_commands WHERE MOD(IFNULL(guild_id, 0) >> 22, ${this.bot.shardCount}) = ${this.bot.shardId}`;
const res = await this.db.query(query);
if (res[0]) {
return res[0].map(value =>
new CustomCommand(this.bot, value.command, value.response, value.guild_id));
}
return [];
}
async addCustomCommand(message, call, response) {
const id = `${call}${message.guild.id}`;
const query = SQL`INSERT INTO custom_commands (command_id, guild_id, command, response, creator_id)
VALUES (${id}, ${message.guild.id}, ${call}, ${response}, ${message.author.id})`;
return this.db.query(query);
}
async deleteCustomCommand(message, call) {
const id = `${call}${message.guild.id}`;
const query = SQL`DELETE FROM custom_commands WHERE command_id = ${id}`;
return this.db.query(query);
}
/**
* Clear welcome messages for a guild
* @param {Guild} guild The guild
* @param {boolean} isDm whether or not the message to be cleared is the dm or in-chat message
* @returns {Promise}
*/
async clearWelcomeForGuild(guild, isDm) {
const query = SQL`DELETE FROM welcome_messages WHERE guild_id=${guild.id} && is_dm=${isDm}`;
return this.db.query(query);
}
/**
* Sets a ping message for an item or event type in a guild
* @param {Message} message Message to derive information for guild and channel
* @param {boolean} isDm whether or not this is for the dm welcome
* @param {string} text The text of the ping message
* @returns {Promise}
*/
async setWelcome(message, isDm, text) {
const query = SQL`INSERT INTO welcome_messages (guild_id, is_dm, channel_id, message) VALUES (${message.guild.id}, ${isDm}, ${message.channel.id}, ${text})
ON DUPLICATE KEY UPDATE message = ${text};`;
return this.db.query(query);
}
async getWelcomes(guild) {
if (guild) {
const query = SQL`SELECT * FROM welcome_messages WHERE guild_id=${guild.id}`;
const res = await this.db.query(query);
if (res[0]) {
return res[0].map(value =>
({
isDm: value.is_dm,
message: value.message,
channel: this.bot.client.channels.get(value.channel_id),
}));
}
return [];
}
return [];
}
async addNewBuild(title, body, image, owner) {
const buildId = makeId();
const query = SQL`INSERT INTO builds VALUES (${buildId}, ${title}, ${body}, ${image}, ${owner.id})
ON DUPLICATE KEY UPDATE title=${title}, body=${body}, image=${image};`;
await this.db.query(query);
return {
id: buildId, title, body, url: image, owner,
};
}
async getBuild(buildId) {
if (buildId) {
const query = SQL`SELECT * FROM builds WHERE build_id=${buildId};`;
const res = await this.db.query(query);
if (res[0] && res[0][0]) {
const result = res[0][0];
return {
title: result.title,
body: result.body,
url: result.image,
id: result.build_id,
owner: this.bot.client.users.get(result.owner_id) || result.owner_id,
owner_id: result.owner_id,
};
}
}
return {
id: '',
title: 'No Such Build',
body: '',
url: '',
owner: '',
};
}
async deleteBuild(buildId) {
const query = SQL`DELETE FROM builds WHERE build_id=${buildId};`;
return this.db.query(query);
}
async getBuilds(owner, author) {
const query = SQL`SELECT * FROM builds WHERE owner_id LIKE ${owner ? '%' : author.id};`;
const res = await this.db.query(query);
if (res[0]) {
return res[0].map(build => ({
id: build.build_id,
owner: this.bot.client.users.get(build.owner_id) || build.owner_id,
title: build.title,
}));
}
return [];
}
async setBuildFields(buildId, { title = undefined, body = undefined, image = undefined }) {
const setTokens = [];
if (title) {
setTokens.push(`title = '${title.trim().replace(/'/ig, '\\\'')}'`);
}
if (body) {
setTokens.push(`body = '${body.trim().replace(/'/ig, '\\\'')}'`);
}
if (image) {
setTokens.push(`image = '${image.trim().replace(/'/ig, '\\\'')}'`);
}
if (setTokens.length > 0) {
const query = `UPDATE builds SET ${setTokens.join(', ')} WHERE build_id='${buildId}';`;
return this.db.query(query);
}
return false;
}
async deleteWebhooksForChannel(channelId) {
const query = SQL`DELETE FROM settings WHERE channel_id=${channelId} and setting like "webhook%";`;
return this.db.query(query);
}
}
module.exports = Database;
|
src/settings/Database.js
|
'use strict';
const mysql = require('mysql2/promise');
const SQL = require('sql-template-strings');
const Promise = require('bluebird');
const schema = require('./schema.js');
const CustomCommand = require('../CustomCommand.js');
/**
* Connection options for the database
* @typedef {Object} DbConnectionOptions
* @property {string} [host=localhost] - The hostname of the database
* @property {number} [port=3306] - The port number to connect to
* @property {string} user - The user to authenticate as
* @property {string} password - The password for that user
* @property {string} database - The database to use
*/
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const makeId = () => {
const tokens = [];
for (let i = 0; i < 8; i += 1) {
tokens.push(possible.charAt(Math.floor(Math.random() * possible.length)));
}
return tokens.join('');
};
/**
* Persistent storage for the bot
*/
class Database {
/**
* @param {DbConnectionOptions} dbOptions Connection options for the database
* @param {Genesis} bot Bot to load the settings for
*/
constructor(dbOptions, bot) {
const opts = {
supportBigNumbers: true,
bigNumberStrings: true,
Promise,
};
Object.assign(opts, dbOptions);
this.db = mysql.createPool(opts);
this.bot = bot;
this.logger = bot.logger;
this.defaults = {
prefix: '/',
respond_to_settings: true,
platform: 'pc',
language: 'en',
delete_after_respond: true,
delete_response: true,
createPrivateChannel: false,
deleteExpired: false,
allowCustom: false,
allowInline: false,
};
}
/**
* Creates the required tables in the database
* @returns {Promise}
*/
createSchema() {
return Promise.mapSeries(schema, q => this.db.query(q));
}
/**
* Initialize data for guilds in channels for existing guilds
* @param {Client} client for pulling guild information
*/
ensureData(client) {
const promises = [];
client.guilds.array().forEach((guild) => {
if (guild.channels.array().length) {
promises.push(this.addGuild(guild));
}
});
Promise.all(promises.map(x => x.reflect()))
.then((results) => {
results.forEach((result) => {
if (result && !result.isFulfilled()) {
this.logger.error(result.reason());
}
});
});
}
/**
* Adds a new guild to the database
* @param {Guild} guild A Discord guild (server)
* @returns {Promise}
*/
addGuild(guild) {
const channelIDs = guild.channels.filter(c => c.type === 'text').keyArray();
const query = SQL`INSERT IGNORE INTO channels (id, guild_id) VALUES `;
channelIDs.forEach((id, index) => {
query.append(SQL`(${id}, ${guild.id})`).append(index !== (channelIDs.length - 1) ? ',' : ';');
});
return this.db.query(query);
}
/**
* Deletes a guild from the database
* @param {Guild} guild A Discord guild (server)
* @returns {Promise}
*/
deleteGuild(guild) {
const query = SQL`DELETE FROM channels WHERE guild_id = ${guild.id};`;
return this.db.query(query);
}
/**
* Gets the current count of guilds and channels
* @returns {Promise}
*/
async getChannelAndGuildCounts() {
const query = 'select count(distinct guild_id) as countGuilds, count(distinct id) as countChannels from channels;';
const res = await this.db.query(query);
if (res[0]) {
return {
channels: res[0].countChannels,
guilds: res[0].countGuilds,
};
}
return {};
}
/**
* Adds a new guild text channel to the database
* @param {TextChannel} channel A discord guild text channel
* @returns {Promise}
*/
async addGuildTextChannel(channel) {
const query = SQL`INSERT IGNORE INTO channels (id, guild_id) VALUES (${channel.id}, ${channel.guild.id});`;
return this.db.query(query);
}
/**
* Adds a new DM or group DM channel to the database
* @param {DMChannel|GroupDMChannel} channel A discord DM or group DM channel
* @returns {Promise}
*/
async addDMChannel(channel) {
const query = SQL`INSERT IGNORE INTO channels (id) VALUES (${channel.id});`;
return this.db.query(query);
}
/**
* Deletes a channel from the database
* @param {Channel} channel The channel to delete
* @returns {Promise}
*/
async deleteChannel(channel) {
const query = SQL`DELETE FROM channels WHERE id = ${channel.id};`;
return this.db.query(query);
}
async checkWebhookAndReturn(channel, setting) {
if (!/webhook/.test(setting)) {
await this.setChannelSetting(channel, setting, this.defaults[`${setting}`]);
return this.defaults[`${setting}`];
}
return undefined;
}
/**
* Get a setting for a particular channel
* @param {Channel} channel channel to get the setting for
* @param {string} setting name of the setting to get
* @returns {Promise} setting
*/
async getChannelSetting(channel, setting) {
const query = SQL`SELECT val FROM settings WHERE channel_id=${channel.id} and setting=${setting};`;
const res = await this.db.query(query);
if (res[0].length === 0) {
if (channel.type === 'text') {
await this.addGuildTextChannel(channel);
return this.checkWebhookAndReturn(channel, setting);
}
await this.addDMChannel(channel);
return this.checkWebhookAndReturn(channel, setting);
}
return res[0][0].val;
}
async getChannelWebhook(channel) {
return {
avatar: await this.getChannelSetting(channel, 'webhookAvatar') || this.bot.client.user.avatarURL.replace('?size=2048', ''),
name: await this.getChannelSetting(channel, 'webhookName') || this.bot.client.user.username,
id: await this.getChannelSetting(channel, 'webhookId'),
token: await this.getChannelSetting(channel, 'webhookToken'),
};
}
/**
* Get a setting for a particular channel
* @param {Channel} channel channel to get the setting for
* @param {string} setting name of the setting to set
* @param {string|boolean} value value of the setting to be set
* @returns {Promise} setting
*/
async setChannelSetting(channel, setting, value) {
const query = SQL`INSERT IGNORE INTO settings (channel_id, setting, val) VALUE (${channel.id},${setting},${value}) ON DUPLICATE KEY UPDATE val=${value};`;
return this.db.query(query);
}
/**
* Resets the custom prefix for this guild to the bot's globally configured prefix
* @param {Guild} guild The Discord guild for which to set the response setting
* @param {string} setting Name of the setting to set
* @param {string|boolean} val value of the setting to be set
* @returns {Promise}
*/
async setGuildSetting(guild, setting, val) {
const promises = [];
guild.channels.array().forEach((channel) => {
promises.push(this.setChannelSetting(channel, setting, val));
});
return Promise.all(promises);
}
/**
* Enables notifications for an item in a channel
* @param {Channel} channel The channel where to enable notifications
* @param {string} item The item to track
* @returns {Promise}
*/
async trackItem(channel, item) {
const query = SQL`INSERT IGNORE INTO item_notifications (channel_id, item) VALUES (${channel.id},${item});`;
return this.db.query(query);
}
/**
* Disables notifications for an item in a channel
* @param {Channel} channel The channel where to enable notifications
* @param {string} item The item to track
* @returns {Promise}
*/
async untrackItem(channel, item) {
const query = SQL`DELETE FROM item_notifications WHERE channel_id = ${channel.id} AND item = ${item};`;
return this.db.query(query);
}
/**
* Enables notifications for an event type in a channel
* @param {Channel} channel The channel where to enable notifications
* @param {string} type The item to track
* @returns {Promise}
*/
async trackEventType(channel, type) {
const query = SQL`INSERT IGNORE INTO type_notifications (channel_id, type) VALUES (${channel.id},${type});`;
return this.db.query(query);
}
/**
* Disables notifications for an event type in a channel
* @param {Channel} channel The channel where to enable notifications
* @param {string} type The item to track
* @returns {Promise}
*/
async untrackEventType(channel, type) {
const query = SQL`DELETE FROM type_notifications WHERE channel_id = ${channel.id} AND type = ${type};`;
return this.db.query(query);
}
/**
* Enables or disables pings for an item in a channel
* @param {TextChannel} channel The channel where to enable notifications
* @param {string} item The item to set ping status for
* @param {boolean} enabled true to enable pinging, false to disable
* @returns {Promise}
*/
async setItemPing(channel, item, enabled) {
const query = SQL`UPDATE item_notifications SET ping = ${enabled} WHERE channel_id = ${channel.id}
AND item = ${item};`;
return this.db.query(query);
}
/**
* Enables or disables pings for an event type in a channel
* @param {TextChannel} channel The channel where to enable notifications
* @param {string} type The event type to set ping status for
* @param {boolean} enabled true to enable pinging, false to disable
* @returns {Promise}
*/
async setEventTypePing(channel, type, enabled) {
const query = SQL`UPDATE type_notifications SET ping = ${enabled} WHERE channel_id = ${channel.id}
AND type = ${type};`;
return this.db.query(query);
}
/**
* Sets a ping message for an item or event type in a guild
* @param {Guild} guild The guild
* @param {string} itemOrType The item or event type to set the ping message for
* @param {string} text The text of the ping message
* @returns {Promise}
*/
async setPing(guild, itemOrType, text) {
const query = SQL`INSERT INTO pings VALUES (${guild.id}, ${itemOrType}, ${text})
ON DUPLICATE KEY UPDATE text = ${text};`;
return this.db.query(query);
}
/**
* Get all pings for a guild for the provided event types and items
* @param {Guild} guild Guild to get pings for
* @param {Array.<string>} itemsOrTypes array of strings corresponding to event and reward types
* @returns {Promise.<string>} Promise of a string to prepend to a message
*/
async getPing(guild, itemsOrTypes) {
const query = SQL`SELECT text FROM pings WHERE guild_id=${guild.id} AND item_or_type in (${itemsOrTypes})`;
const res = await this.db.query(query);
if (res[0].length === 0) {
return '';
}
return res[0]
.map(result => result.text).join(', ');
}
/**
* Clear all pings for a guild
* @param {Guild} guild The guild
* @returns {Promise}
*/
async clearPingsForGuild(guild) {
const query = SQL`DELETE FROM pings WHERE guild_id=${guild.id}`;
return this.db.query(query);
}
async getPingsForGuild(guild) {
if (guild) {
const query = SQL`SELECT item_or_type, text FROM pings WHERE guild_id=${guild.id}`;
const res = await this.db.query(query);
if (res[0].length === 0) {
return [];
}
return res[0]
.map(result => ({ text: result.text, thing: result.item_or_type }));
}
return [];
}
/**
* Removes a ping message
* @param {Guild} guild The guild where the ping message is currently being sent
* @param {string} itemOrType The item or event type associated to the ping message
* @returns {Promise}
*/
async removePing(guild, itemOrType) {
if (guild) {
const query = SQL`DELETE FROM pings WHERE guild_id = ${guild.id} AND item_or_type = ${itemOrType};`;
return this.db.query(query);
}
return false;
}
/**
* Returns all the channels that should get a notification for the items in the list
* @param {string} type The type of the event
* @param {string} platform The platform of the event
* @param {Array.<string>} items The items in the reward that is being notified
* @returns {Promise.<Array.<{channel_id: string, webhook: string}>>}
*/
async getNotifications(type, platform, items) {
try {
const query = SQL`SELECT DISTINCT channels.id as channelId
FROM type_notifications`
.append(items && items.length > 0 ?
SQL` INNER JOIN item_notifications ON type_notifications.channel_id = item_notifications.channel_id` : SQL``)
.append(SQL` INNER JOIN channels ON channels.id = type_notifications.channel_id`)
.append(SQL` INNER JOIN settings ON channels.id = settings.channel_id`)
.append(SQL`
WHERE type_notifications.type = ${String(type)}
AND MOD(IFNULL(channels.guild_id, 0) >> 22, ${this.bot.shardCount}) = ${this.bot.shardId}
AND settings.setting = "platform" AND settings.val = ${platform || 'pc'} `)
.append(items && items.length > 0 ? SQL`AND item_notifications.item IN (${items})
AND item_notifications.channel_id = settings.channel_id;` : SQL`;`);
return this.db.query(query);
} catch (e) {
this.logger.error(e);
return [];
}
}
/**
* Returns the items that the channel is tracking
* @param {Channel} channel A Discord channel
* @returns {Promise.<Array.<string>>}
*/
async getTrackedItems(channel) {
const query = SQL`SELECT item FROM item_notifications WHERE channel_id = ${channel.id};`;
const res = await this.db.query(query);
return res[0].map(r => r.item);
}
/**
* Returns the event types that the channel is tracking
* @param {Channel} channel A Discord channel
* @returns {Promise.<Array.<string>>}
*/
async getTrackedEventTypes(channel) {
const query = SQL`SELECT type FROM type_notifications WHERE channel_id = ${channel.id};`;
const res = await this.db.query(query);
return res[0].map(r => r.type);
}
async deleteChannelPermissions(channel) {
const query = SQL`DELETE FROM channel_permissions WHERE channel_id = ${channel.id}`;
return this.db.query(query);
}
async deleteGuildPermissions(guild) {
const query = SQL`DELETE FROM guild_permissions WHERE guild_id = ${guild.id}`;
return this.db.query(query);
}
/**
* Enables or disables a command for an individual member in a channel
* @param {GuildChannel} channel - A discord guild channel
* @param {GuildMember} member - A discord guild member
* @param {string} commandId - The ID of the command to set the permission for
* @param {boolean} allowed - Whether this member should be allowed to use this command
* @returns {Promise}
*/
async setChannelPermissionForMember(channel, member, commandId, allowed) {
const query = SQL`INSERT INTO channel_permissions VALUES
(${channel.id}, ${member.id}, TRUE, ${commandId}, ${allowed})
ON DUPLICATE KEY UPDATE allowed = ${allowed};`;
return this.db.query(query);
}
/**
* Enables or disables a command for a role in a channel
* @param {GuildChannel} channel - A discord guild channel
* @param {Role} role - A discord role
* @param {string} commandId - The ID of the command to set the permission for
* @param {boolean} allowed - Whether this member should be allowed to use this command
* @returns {Promise}
*/
async setChannelPermissionForRole(channel, role, commandId, allowed) {
const query = SQL`INSERT INTO channel_permissions VALUES
(${channel.id}, ${role.id}, FALSE, ${commandId}, ${allowed})
ON DUPLICATE KEY UPDATE allowed = ${allowed};`;
return this.db.query(query);
}
/**
* Enables or disables a command for an individual member in a guild
* @param {Guild} guild - A discord guild
* @param {GuildMember} member - A discord guild member
* @param {string} commandId - The ID of the command to set the permission for
* @param {boolean} allowed - Whether this member should be allowed to use this command
* @returns {Promise}
*/
async setGuildPermissionForMember(guild, member, commandId, allowed) {
const query = SQL`INSERT INTO guild_permissions VALUES
(${guild.id}, ${member.id}, TRUE, ${commandId}, ${allowed})
ON DUPLICATE KEY UPDATE allowed = ${allowed};`;
return this.db.query(query);
}
/**
* Enables or disables a command for a role in a channel
* @param {Guild} guild - A discord guild
* @param {Role} role - A discord role
* @param {string} commandId - The ID of the command to set the permission for
* @param {boolean} allowed - Whether this member should be allowed to use this command
* @returns {Promise}
*/
async setGuildPermissionForRole(guild, role, commandId, allowed) {
const query = SQL`INSERT INTO guild_permissions VALUES
(${guild.id}, ${role.id}, FALSE, ${commandId}, ${allowed})
ON DUPLICATE KEY UPDATE allowed = ${allowed};`;
return this.db.query(query);
}
/**
* Stops tracking all event types in a channel (disables all notifications)
* @param {Channel} channel - A Discord channel
* @returns {Promise}
*/
async stopTracking(channel) {
const query = SQL`DELETE FROM type_notifications WHERE channel_id = ${channel.id};`;
return this.db.query(query);
}
/**
* Gets whether or not a user is allowed to use a particular command in a channel
* @param {Channel} channel - A Discord channel
* @param {string} memberId - String representing a user identifier
* @param {string} commandId - String representing a command identifier
* @returns {Promise}
*/
async getChannelPermissionForMember(channel, memberId, commandId) {
const query = SQL`SELECT allowed FROM channel_permissions
WHERE channel_id = ${channel.id} AND command_id = ${commandId}
AND is_user = true AND target_id = ${memberId}`;
const res = await this.db.query(query);
if (!res || res[0].length === 0) {
return 'none';
}
return res.rows[0].allowed;
}
/**
* Gets whether or not a role is allowed to use a particular command in a channel
* @param {Channel} channel A Discord channel
* @param {string} role String representing a user identifier
* @param {string} commandId String representing a command identifier
* @returns {Promise}
*/
async getChannelPermissionForRole(channel, role, commandId) {
const query = SQL`SELECT allowed FROM channel_permissions
WHERE channel_id = ${channel.id} AND command_id = ${commandId}
AND is_user = false AND target_id = ${role.id}`;
const res = await this.db.query(query);
if (!res || res[0].length === 0) {
return 'none';
}
return res.rows[0].allowed === 1;
}
/**
* Gets whether or not a role in the user's
* roles allows the user to use a particular command in a channel
* @param {Channel} channel - A Discord channel
* @param {User} user - A Discord user
* @param {string} commandId - A command id for designating
* a command to check permisions for
* @returns {Promise}
*/
async getChannelPermissionForUserRoles(channel, user, commandId) {
const userRoles = channel.type === 'text' ? channel.guild.member(user).roles : {};
const userRoleIds = userRoles.keyArray();
const query = SQL`SELECT target_id, is_user, allowed
FROM channel_permissions
WHERE channel_permissions.channel_id = ${channel.id}
AND channel_permissions.target_id IN (${userRoleIds})
AND command_id = ${commandId}
UNION SELECT guild_permissions.target_id AS target_id,
guild_permissions.is_user AS is_user,
guild_permissions.allowed AS allowed
FROM guild_permissions
INNER JOIN channels USING (guild_id)
LEFT JOIN channel_permissions ON
channel_permissions.channel_id = channels.id
AND guild_permissions.command_id = channel_permissions.command_id
AND guild_permissions.target_id = channel_permissions.target_id
WHERE channel_permissions.target_id IS NULL
AND channels.id = ${channel.id}
AND guild_permissions.target_id IN (${userRoleIds});`;
const res = await this.db.query(query);
if (res[0].length === 0) {
return 'none';
}
return res[0][0].allowed;
}
/**
* Gets whether or not a user is allowed to use a particular command in a guild
* @param {Guild} guild - A Discord guild
* @param {string} memberId - String representing a user identifier
* @param {string} commandId - String representing a command identifier
* @returns {Promise}
*/
async getGuildPermissionForMember(guild, memberId, commandId) {
const query = SQL`SELECT allowed FROM guild_permissions
WHERE channel_id = ${guild.id} AND command_id = ${commandId}
AND is_user = true AND target_id = ${memberId}`;
const res = await this.db.query(query);
if (res.rows.length === 0) {
throw new Error(`The guild permissions for the guild ${guild.id}
for member ${memberId} was not found in the database`);
}
return res.rows[0].allowed;
}
/**
* Gets whether or not a role is allowed to use a particular command in a guild
* @param {Guild} guild - A Discord guild
* @param {string} role String representing a user identifier
* @param {string} commandId String representing a command identifier
* @returns {Promise}
*/
async getGuildPermissionForRole(guild, role, commandId) {
const query = SQL`SELECT allowed FROM guild_permissions
WHERE channel_id = ${guild.id} AND command_id = ${commandId}
AND is_user = false AND target_id = ${role.id}`;
const res = await this.db.query(query);
if (res.rows.length === 0) {
throw new Error(`The guild permissions for the guild ${guild.id}
for member ${role.id} was not found in the database`);
}
return res.rows[0].allowed;
}
/**
* Remove guild from database
* @param {snowflake} guild Guild to be removed from database
* @returns {Promise.<string>} status of removal
*/
async removeGuild(guild) {
const channelIds = guild.channels.keyArray();
const results = [];
channelIds.forEach((channelId) => {
results.push(this.removeChannelPermissions(channelId));
results.push(this.removeItemNotifications(channelId));
});
results.push(this.removeGuildPermissions(guild.id));
results.push(this.removePings(guild.id));
await Promise.all(results);
const query = SQL`DELETE FROM channels WHERE guild_id = ${guild.id})`;
return this.db.query(query);
}
/**
* Remove permissions corresponding to the guild id
* @param {snowflake} guildId guild identifier for removal
* @returns {Promise.<string>} status of removal
*/
async removeGuildPermissions(guildId) {
const query = SQL`DELETE FROM guild_permissions WHERE guild_id = ${guildId}`;
return this.db.query(query);
}
/**
* Remove permissions corresponding to the guild id
* @param {snowflake} channelId channel identifier for removal
* @returns {Promise.<string>} status of removal
*/
async removeChannelPermissions(channelId) {
const query = SQL`DELETE FROM channel_permisions WHERE channel_id = ${channelId}`;
return this.db.query(query);
}
/**
* Remove permissions corresponding to the channel id
* @param {snowflake} channelId channel identifier for removal
* @returns {Promise.<string>} status of removal
*/
async removeItemNotifications(channelId) {
const query = SQL`DELETE FROM item_notifications WHERE channel_id = ${channelId}`;
return this.db.query(query);
}
/**
* Remove pings corresponding to the guild id
* @param {snowflake} guildId guild identifier for removal
* @returns {Promise.<string>} status of removal
*/
async removePings(guildId) {
const query = SQL`DELETE FROM pings WHERE guild_id = ${guildId}`;
return this.db.query(query);
}
/**
* Set the notified ids for a given platform and shard id
* @param {string} platform platform corresponding to notified ids
* @param {number} shardId shard id corresponding to notified ids
* @param {JSON} notifiedIds list of oids that have been notifiedIds
* @returns {Promise}
*/
async setNotifiedIds(platform, shardId, notifiedIds) {
const query = SQL`INSERT INTO notified_ids VALUES
(${shardId}, ${platform}, JSON_ARRAY(${notifiedIds}))
ON DUPLICATE KEY UPDATE id_list = JSON_ARRAY(${notifiedIds});`;
return this.db.query(query);
}
/**
* Get list of notified ids for the given platform and shard id
* @param {string} platform Platform
* @param {number} shardId Identifier of the corresponding shard
* @returns {Promise.<Array>} Array of notified oids
*/
async getNotifiedIds(platform, shardId) {
const query = SQL`SELECT id_list
FROM notified_ids
WHERE shard_id=${shardId} AND platform=${platform};`;
const res = await this.db.query(query);
if (res[0].length === 0) {
return [];
}
return res[0][0].id_list;
}
/**
* Set the joinable roles for a guild
* @param {Guild} guild Guild to set joinable roles for
* @param {Array.<string>} roles Array of role ids to set
* @returns {Promise}
*/
async setRolesForGuild(guild, roles) {
const query = SQL`INSERT INTO guild_joinable_roles VALUES
(${guild.id}, JSON_ARRAY(${roles}))
ON DUPLICATE KEY UPDATE id_list = JSON_ARRAY(${roles});`;
return this.db.query(query);
}
/**
* Get the roles that can be joined for a guild
* @param {Guild} guild [description]
* @returns {Promise.<Array.<Role>>} Promise of array of roles that are joinable
*/
async getRolesForGuild(guild) {
const query = SQL`SELECT id_list
FROM guild_joinable_roles
WHERE guild_id=${guild.id}`;
const res = await this.db.query(query);
if (res[0][0]) {
const validListIds = res[0][0].id_list
.filter(id => typeof this.bot.client.guilds.get(guild.id).roles.get(id) !== 'undefined');
const validList = validListIds
.map(id => this.bot.client.guilds.get(guild.id).roles.get(id));
return validList;
}
return [];
}
/**
* Get a dump of allowed and denied permissions
* @param {Guild} guild guild to fetch settings for
* @returns {Object} Data about allowed data
*/
async permissionsForGuild(guild) {
const query = SQL`SELECT * FROM guild_permissions WHERE guild_id = ${guild.id}`;
const res = await this.db.query(query);
if (res[0]) {
return res[0].map(value => ({
level: 'guild',
command: value.command_id,
isAllowed: value.allowed,
type: value.is_user ? 'user' : 'role',
appliesToId: value.target_id,
}));
}
return [];
}
/**
* Get a dump of allowed and denied permissions
* @param {Channel} channel channel to fetch settings for
* @returns {Object} Data about allowed data
*/
async permissionsForChannel(channel) {
const query = SQL`SELECT * FROM channel_permissions WHERE channel_id = ${channel.id}`;
const res = await this.db.query(query);
if (res[0]) {
return res[0].map(value => ({
level: 'channel',
command: value.command_id,
isAllowed: value.allowed,
type: value.is_user ? 'user' : 'role',
appliesToId: value.target_id,
}));
}
return [];
}
async addPrivateRoom(guild, textChannel, voiceChannel) {
const query = SQL`INSERT INTO private_channels (guild_id, text_id, voice_id) VALUES (${guild.id}, ${textChannel.id}, ${voiceChannel.id})`;
return this.db.query(query);
}
async deletePrivateRoom(guild, textChannel, voiceChannel) {
const query = SQL`DELETE FROM private_channels WHERE guild_id = ${guild.id} AND text_id = ${textChannel.id} AND voice_id = ${voiceChannel.id}`;
return this.db.query(query);
}
async getPrivateRooms() {
const query = SQL`SELECT guild_id, text_id, voice_id, created_at as crt_sec FROM private_channels WHERE MOD(IFNULL(guild_id, 0) >> 22, ${this.bot.shardCount}) = ${this.bot.shardId}`;
const res = await this.db.query(query);
if (res[0]) {
return res[0].map(value => ({
guild: this.bot.client.guilds.get(value.guild_id),
textChannel: this.bot.client.channels.get(value.text_id),
voiceChannel: this.bot.client.channels.get(value.voice_id),
createdAt: value.crt_sec,
}));
}
return [];
}
async getCommandContext(channel) {
const prefix = await this.getChannelSetting(channel, 'prefix');
const allowCustom = await this.getChannelSetting(channel, 'allowCustom') === '1';
const allowInline = await this.getChannelSetting(channel, 'allowInline') === '1';
const webhook = {
id: await this.getChannelSetting(channel, 'webhookId'),
token: await this.getChannelSetting(channel, 'webhookToken'),
name: await this.getChannelSetting(channel, 'webhookName'),
avatar: await this.getChannelSetting(channel, 'webhookAvatar'),
};
return {
prefix, allowCustom, allowInline, webhook, channel,
};
}
async getCustomCommands() {
const query = SQL`SELECT * FROM custom_commands WHERE MOD(IFNULL(guild_id, 0) >> 22, ${this.bot.shardCount}) = ${this.bot.shardId}`;
const res = await this.db.query(query);
if (res[0]) {
return res[0].map(value =>
new CustomCommand(this.bot, value.command, value.response, value.guild_id));
}
return [];
}
async addCustomCommand(message, call, response) {
const id = `${call}${message.guild.id}`;
const query = SQL`INSERT INTO custom_commands (command_id, guild_id, command, response, creator_id)
VALUES (${id}, ${message.guild.id}, ${call}, ${response}, ${message.author.id})`;
return this.db.query(query);
}
async deleteCustomCommand(message, call) {
const id = `${call}${message.guild.id}`;
const query = SQL`DELETE FROM custom_commands WHERE command_id = ${id}`;
return this.db.query(query);
}
/**
* Clear welcome messages for a guild
* @param {Guild} guild The guild
* @param {boolean} isDm whether or not the message to be cleared is the dm or in-chat message
* @returns {Promise}
*/
async clearWelcomeForGuild(guild, isDm) {
const query = SQL`DELETE FROM welcome_messages WHERE guild_id=${guild.id} && is_dm=${isDm}`;
return this.db.query(query);
}
/**
* Sets a ping message for an item or event type in a guild
* @param {Message} message Message to derive information for guild and channel
* @param {boolean} isDm whether or not this is for the dm welcome
* @param {string} text The text of the ping message
* @returns {Promise}
*/
async setWelcome(message, isDm, text) {
const query = SQL`INSERT INTO welcome_messages (guild_id, is_dm, channel_id, message) VALUES (${message.guild.id}, ${isDm}, ${message.channel.id}, ${text})
ON DUPLICATE KEY UPDATE message = ${text};`;
return this.db.query(query);
}
async getWelcomes(guild) {
if (guild) {
const query = SQL`SELECT * FROM welcome_messages WHERE guild_id=${guild.id}`;
const res = await this.db.query(query);
if (res[0]) {
return res[0].map(value =>
({
isDm: value.is_dm,
message: value.message,
channel: this.bot.client.channels.get(value.channel_id),
}));
}
return [];
}
return [];
}
async addNewBuild(title, body, image, owner) {
const buildId = makeId();
const query = SQL`INSERT INTO builds VALUES (${buildId}, ${title}, ${body}, ${image}, ${owner.id})
ON DUPLICATE KEY UPDATE title=${title}, body=${body}, image=${image};`;
await this.db.query(query);
return {
id: buildId, title, body, url: image, owner,
};
}
async getBuild(buildId) {
if (buildId) {
const query = SQL`SELECT * FROM builds WHERE build_id=${buildId};`;
const res = await this.db.query(query);
if (res[0] && res[0][0]) {
const result = res[0][0];
return {
title: result.title,
body: result.body,
url: result.image,
id: result.build_id,
owner: this.bot.client.users.get(result.owner_id) || result.owner_id,
owner_id: result.owner_id,
};
}
}
return {
id: '',
title: 'No Such Build',
body: '',
url: '',
owner: '',
};
}
async deleteBuild(buildId) {
const query = SQL`DELETE FROM builds WHERE build_id=${buildId};`;
return this.db.query(query);
}
async getBuilds(owner, author) {
const query = SQL`SELECT * FROM builds WHERE owner_id LIKE ${owner ? '%' : author.id};`;
const res = await this.db.query(query);
if (res[0]) {
return res[0].map(build => ({
id: build.build_id,
owner: this.bot.client.users.get(build.owner_id) || build.owner_id,
title: build.title,
}));
}
return [];
}
async setBuildFields(buildId, { title = undefined, body = undefined, image = undefined }) {
const setTokens = [];
if (title) {
setTokens.push(`title = '${title.trim().replace(/'/ig, '\\\'')}'`);
}
if (body) {
setTokens.push(`body = '${body.trim().replace(/'/ig, '\\\'')}'`);
}
if (image) {
setTokens.push(`image = '${image.trim().replace(/'/ig, '\\\'')}'`);
}
if (setTokens.length > 0) {
const query = `UPDATE builds SET ${setTokens.join(', ')} WHERE build_id='${buildId}';`;
return this.db.query(query);
}
return false;
}
async deleteWebhooksForChannel(channelId) {
const query = SQL`DELETE FROM settings WHERE channel_id=${channelId} and setting like "webhook%";`;
return this.db.query(query);
}
}
module.exports = Database;
|
Revert "fix for undefined result"
This reverts commit 73660aaef3b539fc2ed5bf3400eb210c68ade67c.
|
src/settings/Database.js
|
Revert "fix for undefined result"
|
<ide><path>rc/settings/Database.js
<ide> WHERE channel_id = ${channel.id} AND command_id = ${commandId}
<ide> AND is_user = true AND target_id = ${memberId}`;
<ide> const res = await this.db.query(query);
<del> if (!res || res[0].length === 0) {
<add> if (res[0].length === 0) {
<ide> return 'none';
<ide> }
<ide> return res.rows[0].allowed;
<ide> WHERE channel_id = ${channel.id} AND command_id = ${commandId}
<ide> AND is_user = false AND target_id = ${role.id}`;
<ide> const res = await this.db.query(query);
<del> if (!res || res[0].length === 0) {
<add> if (res[0].length === 0) {
<ide> return 'none';
<ide> }
<ide> return res.rows[0].allowed === 1;
|
|
Java
|
apache-2.0
|
9949212b92de00609cb511d6f1b4599290240f73
| 0 |
MarkDacek/commons-lang,apache/commons-lang,MarkDacek/commons-lang,britter/commons-lang,britter/commons-lang,apache/commons-lang,MarkDacek/commons-lang,britter/commons-lang,apache/commons-lang
|
/*
* 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.commons.lang3;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.regex.Pattern;
/**
* <p>Operations on {@link java.lang.String} that are
* {@code null} safe.</p>
*
* <ul>
* <li><b>IsEmpty/IsBlank</b>
* - checks if a String contains text</li>
* <li><b>Trim/Strip</b>
* - removes leading and trailing whitespace</li>
* <li><b>Equals/Compare</b>
* - compares two strings in a null-safe manner</li>
* <li><b>startsWith</b>
* - check if a String starts with a prefix in a null-safe manner</li>
* <li><b>endsWith</b>
* - check if a String ends with a suffix in a null-safe manner</li>
* <li><b>IndexOf/LastIndexOf/Contains</b>
* - null-safe index-of checks
* <li><b>IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut</b>
* - index-of any of a set of Strings</li>
* <li><b>ContainsOnly/ContainsNone/ContainsAny</b>
* - checks if String contains only/none/any of these characters</li>
* <li><b>Substring/Left/Right/Mid</b>
* - null-safe substring extractions</li>
* <li><b>SubstringBefore/SubstringAfter/SubstringBetween</b>
* - substring extraction relative to other strings</li>
* <li><b>Split/Join</b>
* - splits a String into an array of substrings and vice versa</li>
* <li><b>Remove/Delete</b>
* - removes part of a String</li>
* <li><b>Replace/Overlay</b>
* - Searches a String and replaces one String with another</li>
* <li><b>Chomp/Chop</b>
* - removes the last part of a String</li>
* <li><b>AppendIfMissing</b>
* - appends a suffix to the end of the String if not present</li>
* <li><b>PrependIfMissing</b>
* - prepends a prefix to the start of the String if not present</li>
* <li><b>LeftPad/RightPad/Center/Repeat</b>
* - pads a String</li>
* <li><b>UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize</b>
* - changes the case of a String</li>
* <li><b>CountMatches</b>
* - counts the number of occurrences of one String in another</li>
* <li><b>IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable</b>
* - checks the characters in a String</li>
* <li><b>DefaultString</b>
* - protects against a null input String</li>
* <li><b>Rotate</b>
* - rotate (circular shift) a String</li>
* <li><b>Reverse/ReverseDelimited</b>
* - reverses a String</li>
* <li><b>Abbreviate</b>
* - abbreviates a string using ellipses or another given String</li>
* <li><b>Difference</b>
* - compares Strings and reports on their differences</li>
* <li><b>LevenshteinDistance</b>
* - the number of changes needed to change one String into another</li>
* </ul>
*
* <p>The {@code StringUtils} class defines certain words related to
* String handling.</p>
*
* <ul>
* <li>null - {@code null}</li>
* <li>empty - a zero-length string ({@code ""})</li>
* <li>space - the space character ({@code ' '}, char 32)</li>
* <li>whitespace - the characters defined by {@link Character#isWhitespace(char)}</li>
* <li>trim - the characters <= 32 as in {@link String#trim()}</li>
* </ul>
*
* <p>{@code StringUtils} handles {@code null} input Strings quietly.
* That is to say that a {@code null} input will return {@code null}.
* Where a {@code boolean} or {@code int} is being returned
* details vary by method.</p>
*
* <p>A side effect of the {@code null} handling is that a
* {@code NullPointerException} should be considered a bug in
* {@code StringUtils}.</p>
*
* <p>Methods in this class include sample code in their Javadoc comments to explain their operation.
* The symbol {@code *} is used to indicate any input including {@code null}.</p>
*
* <p>#ThreadSafe#</p>
* @see java.lang.String
* @since 1.0
*/
//@Immutable
public class StringUtils {
private static final int STRING_BUILDER_SIZE = 256;
// Performance testing notes (JDK 1.4, Jul03, scolebourne)
// Whitespace:
// Character.isWhitespace() is faster than WHITESPACE.indexOf()
// where WHITESPACE is a string of all whitespace characters
//
// Character access:
// String.charAt(n) versus toCharArray(), then array[n]
// String.charAt(n) is about 15% worse for a 10K string
// They are about equal for a length 50 string
// String.charAt(n) is about 4 times better for a length 3 string
// String.charAt(n) is best bet overall
//
// Append:
// String.concat about twice as fast as StringBuffer.append
// (not sure who tested this)
/**
* A String for a space character.
*
* @since 3.2
*/
public static final String SPACE = " ";
/**
* The empty String {@code ""}.
* @since 2.0
*/
public static final String EMPTY = "";
/**
* A String for linefeed LF ("\n").
*
* @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6">JLF: Escape Sequences
* for Character and String Literals</a>
* @since 3.2
*/
public static final String LF = "\n";
/**
* A String for carriage return CR ("\r").
*
* @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6">JLF: Escape Sequences
* for Character and String Literals</a>
* @since 3.2
*/
public static final String CR = "\r";
/**
* Represents a failed index search.
* @since 2.1
*/
public static final int INDEX_NOT_FOUND = -1;
/**
* <p>The maximum size to which the padding constant(s) can expand.</p>
*/
private static final int PAD_LIMIT = 8192;
// Abbreviating
//-----------------------------------------------------------------------
/**
* <p>Abbreviates a String using ellipses. This will turn
* "Now is the time for all good men" into "Now is the time for..."</p>
*
* <p>Specifically:</p>
* <ul>
* <li>If the number of characters in {@code str} is less than or equal to
* {@code maxWidth}, return {@code str}.</li>
* <li>Else abbreviate it to {@code (substring(str, 0, max-3) + "...")}.</li>
* <li>If {@code maxWidth} is less than {@code 4}, throw an
* {@code IllegalArgumentException}.</li>
* <li>In no case will it return a String of length greater than
* {@code maxWidth}.</li>
* </ul>
*
* <pre>
* StringUtils.abbreviate(null, *) = null
* StringUtils.abbreviate("", 4) = ""
* StringUtils.abbreviate("abcdefg", 6) = "abc..."
* StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
* StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
* StringUtils.abbreviate("abcdefg", 4) = "a..."
* StringUtils.abbreviate("abcdefg", 3) = IllegalArgumentException
* </pre>
*
* @param str the String to check, may be null
* @param maxWidth maximum length of result String, must be at least 4
* @return abbreviated String, {@code null} if null String input
* @throws IllegalArgumentException if the width is too small
* @since 2.0
*/
public static String abbreviate(final String str, final int maxWidth) {
return abbreviate(str, "...", 0, maxWidth);
}
/**
* <p>Abbreviates a String using ellipses. This will turn
* "Now is the time for all good men" into "...is the time for..."</p>
*
* <p>Works like {@code abbreviate(String, int)}, but allows you to specify
* a "left edge" offset. Note that this left edge is not necessarily going to
* be the leftmost character in the result, or the first character following the
* ellipses, but it will appear somewhere in the result.
*
* <p>In no case will it return a String of length greater than
* {@code maxWidth}.</p>
*
* <pre>
* StringUtils.abbreviate(null, *, *) = null
* StringUtils.abbreviate("", 0, 4) = ""
* StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 0, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 1, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 4, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 5, 10) = "...fghi..."
* StringUtils.abbreviate("abcdefghijklmno", 6, 10) = "...ghij..."
* StringUtils.abbreviate("abcdefghijklmno", 8, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghij", 0, 3) = IllegalArgumentException
* StringUtils.abbreviate("abcdefghij", 5, 6) = IllegalArgumentException
* </pre>
*
* @param str the String to check, may be null
* @param offset left edge of source String
* @param maxWidth maximum length of result String, must be at least 4
* @return abbreviated String, {@code null} if null String input
* @throws IllegalArgumentException if the width is too small
* @since 2.0
*/
public static String abbreviate(final String str, final int offset, final int maxWidth) {
return abbreviate(str, "...", offset, maxWidth);
}
/**
* <p>Abbreviates a String using another given String as replacement marker. This will turn
* "Now is the time for all good men" into "Now is the time for..." if "..." was defined
* as the replacement marker.</p>
*
* <p>Specifically:</p>
* <ul>
* <li>If the number of characters in {@code str} is less than or equal to
* {@code maxWidth}, return {@code str}.</li>
* <li>Else abbreviate it to {@code (substring(str, 0, max-abbrevMarker.length) + abbrevMarker)}.</li>
* <li>If {@code maxWidth} is less than {@code abbrevMarker.length + 1}, throw an
* {@code IllegalArgumentException}.</li>
* <li>In no case will it return a String of length greater than
* {@code maxWidth}.</li>
* </ul>
*
* <pre>
* StringUtils.abbreviate(null, "...", *) = null
* StringUtils.abbreviate("abcdefg", null, *) = "abcdefg"
* StringUtils.abbreviate("", "...", 4) = ""
* StringUtils.abbreviate("abcdefg", ".", 5) = "abcd."
* StringUtils.abbreviate("abcdefg", ".", 7) = "abcdefg"
* StringUtils.abbreviate("abcdefg", ".", 8) = "abcdefg"
* StringUtils.abbreviate("abcdefg", "..", 4) = "ab.."
* StringUtils.abbreviate("abcdefg", "..", 3) = "a.."
* StringUtils.abbreviate("abcdefg", "..", 2) = IllegalArgumentException
* StringUtils.abbreviate("abcdefg", "...", 3) = IllegalArgumentException
* </pre>
*
* @param str the String to check, may be null
* @param abbrevMarker the String used as replacement marker
* @param maxWidth maximum length of result String, must be at least {@code abbrevMarker.length + 1}
* @return abbreviated String, {@code null} if null String input
* @throws IllegalArgumentException if the width is too small
* @since 3.6
*/
public static String abbreviate(final String str, final String abbrevMarker, final int maxWidth) {
return abbreviate(str, abbrevMarker, 0, maxWidth);
}
/**
* <p>Abbreviates a String using a given replacement marker. This will turn
* "Now is the time for all good men" into "...is the time for..." if "..." was defined
* as the replacement marker.</p>
*
* <p>Works like {@code abbreviate(String, String, int)}, but allows you to specify
* a "left edge" offset. Note that this left edge is not necessarily going to
* be the leftmost character in the result, or the first character following the
* replacement marker, but it will appear somewhere in the result.
*
* <p>In no case will it return a String of length greater than {@code maxWidth}.</p>
*
* <pre>
* StringUtils.abbreviate(null, null, *, *) = null
* StringUtils.abbreviate("abcdefghijklmno", null, *, *) = "abcdefghijklmno"
* StringUtils.abbreviate("", "...", 0, 4) = ""
* StringUtils.abbreviate("abcdefghijklmno", "---", -1, 10) = "abcdefg---"
* StringUtils.abbreviate("abcdefghijklmno", ",", 0, 10) = "abcdefghi,"
* StringUtils.abbreviate("abcdefghijklmno", ",", 1, 10) = "abcdefghi,"
* StringUtils.abbreviate("abcdefghijklmno", ",", 2, 10) = "abcdefghi,"
* StringUtils.abbreviate("abcdefghijklmno", "::", 4, 10) = "::efghij::"
* StringUtils.abbreviate("abcdefghijklmno", "...", 6, 10) = "...ghij..."
* StringUtils.abbreviate("abcdefghijklmno", "*", 9, 10) = "*ghijklmno"
* StringUtils.abbreviate("abcdefghijklmno", "'", 10, 10) = "'ghijklmno"
* StringUtils.abbreviate("abcdefghijklmno", "!", 12, 10) = "!ghijklmno"
* StringUtils.abbreviate("abcdefghij", "abra", 0, 4) = IllegalArgumentException
* StringUtils.abbreviate("abcdefghij", "...", 5, 6) = IllegalArgumentException
* </pre>
*
* @param str the String to check, may be null
* @param abbrevMarker the String used as replacement marker
* @param offset left edge of source String
* @param maxWidth maximum length of result String, must be at least 4
* @return abbreviated String, {@code null} if null String input
* @throws IllegalArgumentException if the width is too small
* @since 3.6
*/
public static String abbreviate(final String str, final String abbrevMarker, int offset, final int maxWidth) {
if (isEmpty(str) && isEmpty(abbrevMarker)) {
return str;
} else if (isNotEmpty(str) && EMPTY.equals(abbrevMarker) && maxWidth > 0) {
return str.substring(0, maxWidth);
} else if (isEmpty(str) || isEmpty(abbrevMarker)) {
return str;
}
final int abbrevMarkerLength = abbrevMarker.length();
final int minAbbrevWidth = abbrevMarkerLength + 1;
final int minAbbrevWidthOffset = abbrevMarkerLength + abbrevMarkerLength + 1;
if (maxWidth < minAbbrevWidth) {
throw new IllegalArgumentException(String.format("Minimum abbreviation width is %d", minAbbrevWidth));
}
if (str.length() <= maxWidth) {
return str;
}
if (offset > str.length()) {
offset = str.length();
}
if (str.length() - offset < maxWidth - abbrevMarkerLength) {
offset = str.length() - (maxWidth - abbrevMarkerLength);
}
if (offset <= abbrevMarkerLength+1) {
return str.substring(0, maxWidth - abbrevMarkerLength) + abbrevMarker;
}
if (maxWidth < minAbbrevWidthOffset) {
throw new IllegalArgumentException(String.format("Minimum abbreviation width with offset is %d", minAbbrevWidthOffset));
}
if (offset + maxWidth - abbrevMarkerLength < str.length()) {
return abbrevMarker + abbreviate(str.substring(offset), abbrevMarker, maxWidth - abbrevMarkerLength);
}
return abbrevMarker + str.substring(str.length() - (maxWidth - abbrevMarkerLength));
}
/**
* <p>Abbreviates a String to the length passed, replacing the middle characters with the supplied
* replacement String.</p>
*
* <p>This abbreviation only occurs if the following criteria is met:</p>
* <ul>
* <li>Neither the String for abbreviation nor the replacement String are null or empty </li>
* <li>The length to truncate to is less than the length of the supplied String</li>
* <li>The length to truncate to is greater than 0</li>
* <li>The abbreviated String will have enough room for the length supplied replacement String
* and the first and last characters of the supplied String for abbreviation</li>
* </ul>
* <p>Otherwise, the returned String will be the same as the supplied String for abbreviation.
* </p>
*
* <pre>
* StringUtils.abbreviateMiddle(null, null, 0) = null
* StringUtils.abbreviateMiddle("abc", null, 0) = "abc"
* StringUtils.abbreviateMiddle("abc", ".", 0) = "abc"
* StringUtils.abbreviateMiddle("abc", ".", 3) = "abc"
* StringUtils.abbreviateMiddle("abcdef", ".", 4) = "ab.f"
* </pre>
*
* @param str the String to abbreviate, may be null
* @param middle the String to replace the middle characters with, may be null
* @param length the length to abbreviate {@code str} to.
* @return the abbreviated String if the above criteria is met, or the original String supplied for abbreviation.
* @since 2.5
*/
public static String abbreviateMiddle(final String str, final String middle, final int length) {
if (isEmpty(str) || isEmpty(middle)) {
return str;
}
if (length >= str.length() || length < middle.length()+2) {
return str;
}
final int targetSting = length-middle.length();
final int startOffset = targetSting/2+targetSting%2;
final int endOffset = str.length()-targetSting/2;
return str.substring(0, startOffset) +
middle +
str.substring(endOffset);
}
/**
* Appends the suffix to the end of the string if the string does not
* already end with the suffix.
*
* @param str The string.
* @param suffix The suffix to append to the end of the string.
* @param ignoreCase Indicates whether the compare should ignore case.
* @param suffixes Additional suffixes that are valid terminators (optional).
*
* @return A new String if suffix was appended, the same string otherwise.
*/
private static String appendIfMissing(final String str, final CharSequence suffix, final boolean ignoreCase, final CharSequence... suffixes) {
if (str == null || isEmpty(suffix) || endsWith(str, suffix, ignoreCase)) {
return str;
}
if (ArrayUtils.isNotEmpty(suffixes)) {
for (final CharSequence s : suffixes) {
if (endsWith(str, s, ignoreCase)) {
return str;
}
}
}
return str + suffix.toString();
}
/**
* Appends the suffix to the end of the string if the string does not
* already end with any of the suffixes.
*
* <pre>
* StringUtils.appendIfMissing(null, null) = null
* StringUtils.appendIfMissing("abc", null) = "abc"
* StringUtils.appendIfMissing("", "xyz") = "xyz"
* StringUtils.appendIfMissing("abc", "xyz") = "abcxyz"
* StringUtils.appendIfMissing("abcxyz", "xyz") = "abcxyz"
* StringUtils.appendIfMissing("abcXYZ", "xyz") = "abcXYZxyz"
* </pre>
* <p>With additional suffixes,</p>
* <pre>
* StringUtils.appendIfMissing(null, null, null) = null
* StringUtils.appendIfMissing("abc", null, null) = "abc"
* StringUtils.appendIfMissing("", "xyz", null) = "xyz"
* StringUtils.appendIfMissing("abc", "xyz", new CharSequence[]{null}) = "abcxyz"
* StringUtils.appendIfMissing("abc", "xyz", "") = "abc"
* StringUtils.appendIfMissing("abc", "xyz", "mno") = "abcxyz"
* StringUtils.appendIfMissing("abcxyz", "xyz", "mno") = "abcxyz"
* StringUtils.appendIfMissing("abcmno", "xyz", "mno") = "abcmno"
* StringUtils.appendIfMissing("abcXYZ", "xyz", "mno") = "abcXYZxyz"
* StringUtils.appendIfMissing("abcMNO", "xyz", "mno") = "abcMNOxyz"
* </pre>
*
* @param str The string.
* @param suffix The suffix to append to the end of the string.
* @param suffixes Additional suffixes that are valid terminators.
*
* @return A new String if suffix was appended, the same string otherwise.
*
* @since 3.2
*/
public static String appendIfMissing(final String str, final CharSequence suffix, final CharSequence... suffixes) {
return appendIfMissing(str, suffix, false, suffixes);
}
/**
* Appends the suffix to the end of the string if the string does not
* already end, case insensitive, with any of the suffixes.
*
* <pre>
* StringUtils.appendIfMissingIgnoreCase(null, null) = null
* StringUtils.appendIfMissingIgnoreCase("abc", null) = "abc"
* StringUtils.appendIfMissingIgnoreCase("", "xyz") = "xyz"
* StringUtils.appendIfMissingIgnoreCase("abc", "xyz") = "abcxyz"
* StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz") = "abcxyz"
* StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz") = "abcXYZ"
* </pre>
* <p>With additional suffixes,</p>
* <pre>
* StringUtils.appendIfMissingIgnoreCase(null, null, null) = null
* StringUtils.appendIfMissingIgnoreCase("abc", null, null) = "abc"
* StringUtils.appendIfMissingIgnoreCase("", "xyz", null) = "xyz"
* StringUtils.appendIfMissingIgnoreCase("abc", "xyz", new CharSequence[]{null}) = "abcxyz"
* StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "") = "abc"
* StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "mno") = "abcxyz"
* StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz", "mno") = "abcxyz"
* StringUtils.appendIfMissingIgnoreCase("abcmno", "xyz", "mno") = "abcmno"
* StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz", "mno") = "abcXYZ"
* StringUtils.appendIfMissingIgnoreCase("abcMNO", "xyz", "mno") = "abcMNO"
* </pre>
*
* @param str The string.
* @param suffix The suffix to append to the end of the string.
* @param suffixes Additional suffixes that are valid terminators.
*
* @return A new String if suffix was appended, the same string otherwise.
*
* @since 3.2
*/
public static String appendIfMissingIgnoreCase(final String str, final CharSequence suffix, final CharSequence... suffixes) {
return appendIfMissing(str, suffix, true, suffixes);
}
/**
* <p>Capitalizes a String changing the first character to title case as
* per {@link Character#toTitleCase(int)}. No other characters are changed.</p>
*
* <p>For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#capitalize(String)}.
* A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.capitalize(null) = null
* StringUtils.capitalize("") = ""
* StringUtils.capitalize("cat") = "Cat"
* StringUtils.capitalize("cAt") = "CAt"
* StringUtils.capitalize("'cat'") = "'cat'"
* </pre>
*
* @param str the String to capitalize, may be null
* @return the capitalized String, {@code null} if null String input
* @see org.apache.commons.lang3.text.WordUtils#capitalize(String)
* @see #uncapitalize(String)
* @since 2.0
*/
public static String capitalize(final String str) {
final int strLen = length(str);
if (strLen == 0) {
return str;
}
final int firstCodepoint = str.codePointAt(0);
final int newCodePoint = Character.toTitleCase(firstCodepoint);
if (firstCodepoint == newCodePoint) {
// already capitalized
return str;
}
final int newCodePoints[] = new int[strLen]; // cannot be longer than the char array
int outOffset = 0;
newCodePoints[outOffset++] = newCodePoint; // copy the first codepoint
for (int inOffset = Character.charCount(firstCodepoint); inOffset < strLen; ) {
final int codepoint = str.codePointAt(inOffset);
newCodePoints[outOffset++] = codepoint; // copy the remaining ones
inOffset += Character.charCount(codepoint);
}
return new String(newCodePoints, 0, outOffset);
}
// Centering
//-----------------------------------------------------------------------
/**
* <p>Centers a String in a larger String of size {@code size}
* using the space character (' ').</p>
*
* <p>If the size is less than the String length, the original String is returned.
* A {@code null} String returns {@code null}.
* A negative size is treated as zero.</p>
*
* <p>Equivalent to {@code center(str, size, " ")}.</p>
*
* <pre>
* StringUtils.center(null, *) = null
* StringUtils.center("", 4) = " "
* StringUtils.center("ab", -1) = "ab"
* StringUtils.center("ab", 4) = " ab "
* StringUtils.center("abcd", 2) = "abcd"
* StringUtils.center("a", 4) = " a "
* </pre>
*
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @return centered String, {@code null} if null String input
*/
public static String center(final String str, final int size) {
return center(str, size, ' ');
}
/**
* <p>Centers a String in a larger String of size {@code size}.
* Uses a supplied character as the value to pad the String with.</p>
*
* <p>If the size is less than the String length, the String is returned.
* A {@code null} String returns {@code null}.
* A negative size is treated as zero.</p>
*
* <pre>
* StringUtils.center(null, *, *) = null
* StringUtils.center("", 4, ' ') = " "
* StringUtils.center("ab", -1, ' ') = "ab"
* StringUtils.center("ab", 4, ' ') = " ab "
* StringUtils.center("abcd", 2, ' ') = "abcd"
* StringUtils.center("a", 4, ' ') = " a "
* StringUtils.center("a", 4, 'y') = "yayy"
* </pre>
*
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @param padChar the character to pad the new String with
* @return centered String, {@code null} if null String input
* @since 2.0
*/
public static String center(String str, final int size, final char padChar) {
if (str == null || size <= 0) {
return str;
}
final int strLen = str.length();
final int pads = size - strLen;
if (pads <= 0) {
return str;
}
str = leftPad(str, strLen + pads / 2, padChar);
str = rightPad(str, size, padChar);
return str;
}
/**
* <p>Centers a String in a larger String of size {@code size}.
* Uses a supplied String as the value to pad the String with.</p>
*
* <p>If the size is less than the String length, the String is returned.
* A {@code null} String returns {@code null}.
* A negative size is treated as zero.</p>
*
* <pre>
* StringUtils.center(null, *, *) = null
* StringUtils.center("", 4, " ") = " "
* StringUtils.center("ab", -1, " ") = "ab"
* StringUtils.center("ab", 4, " ") = " ab "
* StringUtils.center("abcd", 2, " ") = "abcd"
* StringUtils.center("a", 4, " ") = " a "
* StringUtils.center("a", 4, "yz") = "yayz"
* StringUtils.center("abc", 7, null) = " abc "
* StringUtils.center("abc", 7, "") = " abc "
* </pre>
*
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @param padStr the String to pad the new String with, must not be null or empty
* @return centered String, {@code null} if null String input
* @throws IllegalArgumentException if padStr is {@code null} or empty
*/
public static String center(String str, final int size, String padStr) {
if (str == null || size <= 0) {
return str;
}
if (isEmpty(padStr)) {
padStr = SPACE;
}
final int strLen = str.length();
final int pads = size - strLen;
if (pads <= 0) {
return str;
}
str = leftPad(str, strLen + pads / 2, padStr);
str = rightPad(str, size, padStr);
return str;
}
// Chomping
//-----------------------------------------------------------------------
/**
* <p>Removes one newline from end of a String if it's there,
* otherwise leave it alone. A newline is "{@code \n}",
* "{@code \r}", or "{@code \r\n}".</p>
*
* <p>NOTE: This method changed in 2.0.
* It now more closely matches Perl chomp.</p>
*
* <pre>
* StringUtils.chomp(null) = null
* StringUtils.chomp("") = ""
* StringUtils.chomp("abc \r") = "abc "
* StringUtils.chomp("abc\n") = "abc"
* StringUtils.chomp("abc\r\n") = "abc"
* StringUtils.chomp("abc\r\n\r\n") = "abc\r\n"
* StringUtils.chomp("abc\n\r") = "abc\n"
* StringUtils.chomp("abc\n\rabc") = "abc\n\rabc"
* StringUtils.chomp("\r") = ""
* StringUtils.chomp("\n") = ""
* StringUtils.chomp("\r\n") = ""
* </pre>
*
* @param str the String to chomp a newline from, may be null
* @return String without newline, {@code null} if null String input
*/
public static String chomp(final String str) {
if (isEmpty(str)) {
return str;
}
if (str.length() == 1) {
final char ch = str.charAt(0);
if (ch == CharUtils.CR || ch == CharUtils.LF) {
return EMPTY;
}
return str;
}
int lastIdx = str.length() - 1;
final char last = str.charAt(lastIdx);
if (last == CharUtils.LF) {
if (str.charAt(lastIdx - 1) == CharUtils.CR) {
lastIdx--;
}
} else if (last != CharUtils.CR) {
lastIdx++;
}
return str.substring(0, lastIdx);
}
/**
* <p>Removes {@code separator} from the end of
* {@code str} if it's there, otherwise leave it alone.</p>
*
* <p>NOTE: This method changed in version 2.0.
* It now more closely matches Perl chomp.
* For the previous behavior, use {@link #substringBeforeLast(String, String)}.
* This method uses {@link String#endsWith(String)}.</p>
*
* <pre>
* StringUtils.chomp(null, *) = null
* StringUtils.chomp("", *) = ""
* StringUtils.chomp("foobar", "bar") = "foo"
* StringUtils.chomp("foobar", "baz") = "foobar"
* StringUtils.chomp("foo", "foo") = ""
* StringUtils.chomp("foo ", "foo") = "foo "
* StringUtils.chomp(" foo", "foo") = " "
* StringUtils.chomp("foo", "foooo") = "foo"
* StringUtils.chomp("foo", "") = "foo"
* StringUtils.chomp("foo", null) = "foo"
* </pre>
*
* @param str the String to chomp from, may be null
* @param separator separator String, may be null
* @return String without trailing separator, {@code null} if null String input
* @deprecated This feature will be removed in Lang 4.0, use {@link StringUtils#removeEnd(String, String)} instead
*/
@Deprecated
public static String chomp(final String str, final String separator) {
return removeEnd(str, separator);
}
// Chopping
//-----------------------------------------------------------------------
/**
* <p>Remove the last character from a String.</p>
*
* <p>If the String ends in {@code \r\n}, then remove both
* of them.</p>
*
* <pre>
* StringUtils.chop(null) = null
* StringUtils.chop("") = ""
* StringUtils.chop("abc \r") = "abc "
* StringUtils.chop("abc\n") = "abc"
* StringUtils.chop("abc\r\n") = "abc"
* StringUtils.chop("abc") = "ab"
* StringUtils.chop("abc\nabc") = "abc\nab"
* StringUtils.chop("a") = ""
* StringUtils.chop("\r") = ""
* StringUtils.chop("\n") = ""
* StringUtils.chop("\r\n") = ""
* </pre>
*
* @param str the String to chop last character from, may be null
* @return String without last character, {@code null} if null String input
*/
public static String chop(final String str) {
if (str == null) {
return null;
}
final int strLen = str.length();
if (strLen < 2) {
return EMPTY;
}
final int lastIdx = strLen - 1;
final String ret = str.substring(0, lastIdx);
final char last = str.charAt(lastIdx);
if (last == CharUtils.LF && ret.charAt(lastIdx - 1) == CharUtils.CR) {
return ret.substring(0, lastIdx - 1);
}
return ret;
}
// Compare
//-----------------------------------------------------------------------
/**
* <p>Compare two Strings lexicographically, as per {@link String#compareTo(String)}, returning :</p>
* <ul>
* <li>{@code int = 0}, if {@code str1} is equal to {@code str2} (or both {@code null})</li>
* <li>{@code int < 0}, if {@code str1} is less than {@code str2}</li>
* <li>{@code int > 0}, if {@code str1} is greater than {@code str2}</li>
* </ul>
*
* <p>This is a {@code null} safe version of :</p>
* <blockquote><pre>str1.compareTo(str2)</pre></blockquote>
*
* <p>{@code null} value is considered less than non-{@code null} value.
* Two {@code null} references are considered equal.</p>
*
* <pre>
* StringUtils.compare(null, null) = 0
* StringUtils.compare(null , "a") < 0
* StringUtils.compare("a", null) > 0
* StringUtils.compare("abc", "abc") = 0
* StringUtils.compare("a", "b") < 0
* StringUtils.compare("b", "a") > 0
* StringUtils.compare("a", "B") > 0
* StringUtils.compare("ab", "abc") < 0
* </pre>
*
* @see #compare(String, String, boolean)
* @see String#compareTo(String)
* @param str1 the String to compare from
* @param str2 the String to compare to
* @return < 0, 0, > 0, if {@code str1} is respectively less, equal or greater than {@code str2}
* @since 3.5
*/
public static int compare(final String str1, final String str2) {
return compare(str1, str2, true);
}
/**
* <p>Compare two Strings lexicographically, as per {@link String#compareTo(String)}, returning :</p>
* <ul>
* <li>{@code int = 0}, if {@code str1} is equal to {@code str2} (or both {@code null})</li>
* <li>{@code int < 0}, if {@code str1} is less than {@code str2}</li>
* <li>{@code int > 0}, if {@code str1} is greater than {@code str2}</li>
* </ul>
*
* <p>This is a {@code null} safe version of :</p>
* <blockquote><pre>str1.compareTo(str2)</pre></blockquote>
*
* <p>{@code null} inputs are handled according to the {@code nullIsLess} parameter.
* Two {@code null} references are considered equal.</p>
*
* <pre>
* StringUtils.compare(null, null, *) = 0
* StringUtils.compare(null , "a", true) < 0
* StringUtils.compare(null , "a", false) > 0
* StringUtils.compare("a", null, true) > 0
* StringUtils.compare("a", null, false) < 0
* StringUtils.compare("abc", "abc", *) = 0
* StringUtils.compare("a", "b", *) < 0
* StringUtils.compare("b", "a", *) > 0
* StringUtils.compare("a", "B", *) > 0
* StringUtils.compare("ab", "abc", *) < 0
* </pre>
*
* @see String#compareTo(String)
* @param str1 the String to compare from
* @param str2 the String to compare to
* @param nullIsLess whether consider {@code null} value less than non-{@code null} value
* @return < 0, 0, > 0, if {@code str1} is respectively less, equal ou greater than {@code str2}
* @since 3.5
*/
public static int compare(final String str1, final String str2, final boolean nullIsLess) {
if (str1 == str2) {
return 0;
}
if (str1 == null) {
return nullIsLess ? -1 : 1;
}
if (str2 == null) {
return nullIsLess ? 1 : - 1;
}
return str1.compareTo(str2);
}
/**
* <p>Compare two Strings lexicographically, ignoring case differences,
* as per {@link String#compareToIgnoreCase(String)}, returning :</p>
* <ul>
* <li>{@code int = 0}, if {@code str1} is equal to {@code str2} (or both {@code null})</li>
* <li>{@code int < 0}, if {@code str1} is less than {@code str2}</li>
* <li>{@code int > 0}, if {@code str1} is greater than {@code str2}</li>
* </ul>
*
* <p>This is a {@code null} safe version of :</p>
* <blockquote><pre>str1.compareToIgnoreCase(str2)</pre></blockquote>
*
* <p>{@code null} value is considered less than non-{@code null} value.
* Two {@code null} references are considered equal.
* Comparison is case insensitive.</p>
*
* <pre>
* StringUtils.compareIgnoreCase(null, null) = 0
* StringUtils.compareIgnoreCase(null , "a") < 0
* StringUtils.compareIgnoreCase("a", null) > 0
* StringUtils.compareIgnoreCase("abc", "abc") = 0
* StringUtils.compareIgnoreCase("abc", "ABC") = 0
* StringUtils.compareIgnoreCase("a", "b") < 0
* StringUtils.compareIgnoreCase("b", "a") > 0
* StringUtils.compareIgnoreCase("a", "B") < 0
* StringUtils.compareIgnoreCase("A", "b") < 0
* StringUtils.compareIgnoreCase("ab", "ABC") < 0
* </pre>
*
* @see #compareIgnoreCase(String, String, boolean)
* @see String#compareToIgnoreCase(String)
* @param str1 the String to compare from
* @param str2 the String to compare to
* @return < 0, 0, > 0, if {@code str1} is respectively less, equal ou greater than {@code str2},
* ignoring case differences.
* @since 3.5
*/
public static int compareIgnoreCase(final String str1, final String str2) {
return compareIgnoreCase(str1, str2, true);
}
/**
* <p>Compare two Strings lexicographically, ignoring case differences,
* as per {@link String#compareToIgnoreCase(String)}, returning :</p>
* <ul>
* <li>{@code int = 0}, if {@code str1} is equal to {@code str2} (or both {@code null})</li>
* <li>{@code int < 0}, if {@code str1} is less than {@code str2}</li>
* <li>{@code int > 0}, if {@code str1} is greater than {@code str2}</li>
* </ul>
*
* <p>This is a {@code null} safe version of :</p>
* <blockquote><pre>str1.compareToIgnoreCase(str2)</pre></blockquote>
*
* <p>{@code null} inputs are handled according to the {@code nullIsLess} parameter.
* Two {@code null} references are considered equal.
* Comparison is case insensitive.</p>
*
* <pre>
* StringUtils.compareIgnoreCase(null, null, *) = 0
* StringUtils.compareIgnoreCase(null , "a", true) < 0
* StringUtils.compareIgnoreCase(null , "a", false) > 0
* StringUtils.compareIgnoreCase("a", null, true) > 0
* StringUtils.compareIgnoreCase("a", null, false) < 0
* StringUtils.compareIgnoreCase("abc", "abc", *) = 0
* StringUtils.compareIgnoreCase("abc", "ABC", *) = 0
* StringUtils.compareIgnoreCase("a", "b", *) < 0
* StringUtils.compareIgnoreCase("b", "a", *) > 0
* StringUtils.compareIgnoreCase("a", "B", *) < 0
* StringUtils.compareIgnoreCase("A", "b", *) < 0
* StringUtils.compareIgnoreCase("ab", "abc", *) < 0
* </pre>
*
* @see String#compareToIgnoreCase(String)
* @param str1 the String to compare from
* @param str2 the String to compare to
* @param nullIsLess whether consider {@code null} value less than non-{@code null} value
* @return < 0, 0, > 0, if {@code str1} is respectively less, equal ou greater than {@code str2},
* ignoring case differences.
* @since 3.5
*/
public static int compareIgnoreCase(final String str1, final String str2, final boolean nullIsLess) {
if (str1 == str2) {
return 0;
}
if (str1 == null) {
return nullIsLess ? -1 : 1;
}
if (str2 == null) {
return nullIsLess ? 1 : - 1;
}
return str1.compareToIgnoreCase(str2);
}
/**
* <p>Checks if CharSequence contains a search CharSequence, handling {@code null}.
* This method uses {@link String#indexOf(String)} if possible.</p>
*
* <p>A {@code null} CharSequence will return {@code false}.</p>
*
* <pre>
* StringUtils.contains(null, *) = false
* StringUtils.contains(*, null) = false
* StringUtils.contains("", "") = true
* StringUtils.contains("abc", "") = true
* StringUtils.contains("abc", "a") = true
* StringUtils.contains("abc", "z") = false
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchSeq the CharSequence to find, may be null
* @return true if the CharSequence contains the search CharSequence,
* false if not or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from contains(String, String) to contains(CharSequence, CharSequence)
*/
public static boolean contains(final CharSequence seq, final CharSequence searchSeq) {
if (seq == null || searchSeq == null) {
return false;
}
return CharSequenceUtils.indexOf(seq, searchSeq, 0) >= 0;
}
// Contains
//-----------------------------------------------------------------------
/**
* <p>Checks if CharSequence contains a search character, handling {@code null}.
* This method uses {@link String#indexOf(int)} if possible.</p>
*
* <p>A {@code null} or empty ("") CharSequence will return {@code false}.</p>
*
* <pre>
* StringUtils.contains(null, *) = false
* StringUtils.contains("", *) = false
* StringUtils.contains("abc", 'a') = true
* StringUtils.contains("abc", 'z') = false
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchChar the character to find
* @return true if the CharSequence contains the search character,
* false if not or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from contains(String, int) to contains(CharSequence, int)
*/
public static boolean contains(final CharSequence seq, final int searchChar) {
if (isEmpty(seq)) {
return false;
}
return CharSequenceUtils.indexOf(seq, searchChar, 0) >= 0;
}
// ContainsAny
//-----------------------------------------------------------------------
/**
* <p>Checks if the CharSequence contains any character in the given
* set of characters.</p>
*
* <p>A {@code null} CharSequence will return {@code false}.
* A {@code null} or zero length search array will return {@code false}.</p>
*
* <pre>
* StringUtils.containsAny(null, *) = false
* StringUtils.containsAny("", *) = false
* StringUtils.containsAny(*, null) = false
* StringUtils.containsAny(*, []) = false
* StringUtils.containsAny("zzabyycdxx", ['z', 'a']) = true
* StringUtils.containsAny("zzabyycdxx", ['b', 'y']) = true
* StringUtils.containsAny("zzabyycdxx", ['z', 'y']) = true
* StringUtils.containsAny("aba", ['z']) = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the {@code true} if any of the chars are found,
* {@code false} if no match or null input
* @since 2.4
* @since 3.0 Changed signature from containsAny(String, char[]) to containsAny(CharSequence, char...)
*/
public static boolean containsAny(final CharSequence cs, final char... searchChars) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
return false;
}
final int csLength = cs.length();
final int searchLength = searchChars.length;
final int csLast = csLength - 1;
final int searchLast = searchLength - 1;
for (int i = 0; i < csLength; i++) {
final char ch = cs.charAt(i);
for (int j = 0; j < searchLength; j++) {
if (searchChars[j] == ch) {
if (Character.isHighSurrogate(ch)) {
if (j == searchLast) {
// missing low surrogate, fine, like String.indexOf(String)
return true;
}
if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) {
return true;
}
} else {
// ch is in the Basic Multilingual Plane
return true;
}
}
}
}
return false;
}
/**
* <p>
* Checks if the CharSequence contains any character in the given set of characters.
* </p>
*
* <p>
* A {@code null} CharSequence will return {@code false}. A {@code null} search CharSequence will return
* {@code false}.
* </p>
*
* <pre>
* StringUtils.containsAny(null, *) = false
* StringUtils.containsAny("", *) = false
* StringUtils.containsAny(*, null) = false
* StringUtils.containsAny(*, "") = false
* StringUtils.containsAny("zzabyycdxx", "za") = true
* StringUtils.containsAny("zzabyycdxx", "by") = true
* StringUtils.containsAny("zzabyycdxx", "zy") = true
* StringUtils.containsAny("zzabyycdxx", "\tx") = true
* StringUtils.containsAny("zzabyycdxx", "$.#yF") = true
* StringUtils.containsAny("aba", "z") = false
* </pre>
*
* @param cs
* the CharSequence to check, may be null
* @param searchChars
* the chars to search for, may be null
* @return the {@code true} if any of the chars are found, {@code false} if no match or null input
* @since 2.4
* @since 3.0 Changed signature from containsAny(String, String) to containsAny(CharSequence, CharSequence)
*/
public static boolean containsAny(final CharSequence cs, final CharSequence searchChars) {
if (searchChars == null) {
return false;
}
return containsAny(cs, CharSequenceUtils.toCharArray(searchChars));
}
/**
* <p>Checks if the CharSequence contains any of the CharSequences in the given array.</p>
*
* <p>
* A {@code null} {@code cs} CharSequence will return {@code false}. A {@code null} or zero
* length search array will return {@code false}.
* </p>
*
* <pre>
* StringUtils.containsAny(null, *) = false
* StringUtils.containsAny("", *) = false
* StringUtils.containsAny(*, null) = false
* StringUtils.containsAny(*, []) = false
* StringUtils.containsAny("abcd", "ab", null) = true
* StringUtils.containsAny("abcd", "ab", "cd") = true
* StringUtils.containsAny("abc", "d", "abc") = true
* </pre>
*
*
* @param cs The CharSequence to check, may be null
* @param searchCharSequences The array of CharSequences to search for, may be null.
* Individual CharSequences may be null as well.
* @return {@code true} if any of the search CharSequences are found, {@code false} otherwise
* @since 3.4
*/
public static boolean containsAny(final CharSequence cs, final CharSequence... searchCharSequences) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchCharSequences)) {
return false;
}
for (final CharSequence searchCharSequence : searchCharSequences) {
if (contains(cs, searchCharSequence)) {
return true;
}
}
return false;
}
/**
* <p>Checks if CharSequence contains a search CharSequence irrespective of case,
* handling {@code null}. Case-insensitivity is defined as by
* {@link String#equalsIgnoreCase(String)}.
*
* <p>A {@code null} CharSequence will return {@code false}.</p>
*
* <pre>
* StringUtils.containsIgnoreCase(null, *) = false
* StringUtils.containsIgnoreCase(*, null) = false
* StringUtils.containsIgnoreCase("", "") = true
* StringUtils.containsIgnoreCase("abc", "") = true
* StringUtils.containsIgnoreCase("abc", "a") = true
* StringUtils.containsIgnoreCase("abc", "z") = false
* StringUtils.containsIgnoreCase("abc", "A") = true
* StringUtils.containsIgnoreCase("abc", "Z") = false
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @return true if the CharSequence contains the search CharSequence irrespective of
* case or false if not or {@code null} string input
* @since 3.0 Changed signature from containsIgnoreCase(String, String) to containsIgnoreCase(CharSequence, CharSequence)
*/
public static boolean containsIgnoreCase(final CharSequence str, final CharSequence searchStr) {
if (str == null || searchStr == null) {
return false;
}
final int len = searchStr.length();
final int max = str.length() - len;
for (int i = 0; i <= max; i++) {
if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, len)) {
return true;
}
}
return false;
}
// ContainsNone
//-----------------------------------------------------------------------
/**
* <p>Checks that the CharSequence does not contain certain characters.</p>
*
* <p>A {@code null} CharSequence will return {@code true}.
* A {@code null} invalid character array will return {@code true}.
* An empty CharSequence (length()=0) always returns true.</p>
*
* <pre>
* StringUtils.containsNone(null, *) = true
* StringUtils.containsNone(*, null) = true
* StringUtils.containsNone("", *) = true
* StringUtils.containsNone("ab", '') = true
* StringUtils.containsNone("abab", 'xyz') = true
* StringUtils.containsNone("ab1", 'xyz') = true
* StringUtils.containsNone("abz", 'xyz') = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars an array of invalid chars, may be null
* @return true if it contains none of the invalid chars, or is null
* @since 2.0
* @since 3.0 Changed signature from containsNone(String, char[]) to containsNone(CharSequence, char...)
*/
public static boolean containsNone(final CharSequence cs, final char... searchChars) {
if (cs == null || searchChars == null) {
return true;
}
final int csLen = cs.length();
final int csLast = csLen - 1;
final int searchLen = searchChars.length;
final int searchLast = searchLen - 1;
for (int i = 0; i < csLen; i++) {
final char ch = cs.charAt(i);
for (int j = 0; j < searchLen; j++) {
if (searchChars[j] == ch) {
if (Character.isHighSurrogate(ch)) {
if (j == searchLast) {
// missing low surrogate, fine, like String.indexOf(String)
return false;
}
if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) {
return false;
}
} else {
// ch is in the Basic Multilingual Plane
return false;
}
}
}
}
return true;
}
/**
* <p>Checks that the CharSequence does not contain certain characters.</p>
*
* <p>A {@code null} CharSequence will return {@code true}.
* A {@code null} invalid character array will return {@code true}.
* An empty String ("") always returns true.</p>
*
* <pre>
* StringUtils.containsNone(null, *) = true
* StringUtils.containsNone(*, null) = true
* StringUtils.containsNone("", *) = true
* StringUtils.containsNone("ab", "") = true
* StringUtils.containsNone("abab", "xyz") = true
* StringUtils.containsNone("ab1", "xyz") = true
* StringUtils.containsNone("abz", "xyz") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param invalidChars a String of invalid chars, may be null
* @return true if it contains none of the invalid chars, or is null
* @since 2.0
* @since 3.0 Changed signature from containsNone(String, String) to containsNone(CharSequence, String)
*/
public static boolean containsNone(final CharSequence cs, final String invalidChars) {
if (cs == null || invalidChars == null) {
return true;
}
return containsNone(cs, invalidChars.toCharArray());
}
// ContainsOnly
//-----------------------------------------------------------------------
/**
* <p>Checks if the CharSequence contains only certain characters.</p>
*
* <p>A {@code null} CharSequence will return {@code false}.
* A {@code null} valid character array will return {@code false}.
* An empty CharSequence (length()=0) always returns {@code true}.</p>
*
* <pre>
* StringUtils.containsOnly(null, *) = false
* StringUtils.containsOnly(*, null) = false
* StringUtils.containsOnly("", *) = true
* StringUtils.containsOnly("ab", '') = false
* StringUtils.containsOnly("abab", 'abc') = true
* StringUtils.containsOnly("ab1", 'abc') = false
* StringUtils.containsOnly("abz", 'abc') = false
* </pre>
*
* @param cs the String to check, may be null
* @param valid an array of valid chars, may be null
* @return true if it only contains valid chars and is non-null
* @since 3.0 Changed signature from containsOnly(String, char[]) to containsOnly(CharSequence, char...)
*/
public static boolean containsOnly(final CharSequence cs, final char... valid) {
// All these pre-checks are to maintain API with an older version
if (valid == null || cs == null) {
return false;
}
if (cs.length() == 0) {
return true;
}
if (valid.length == 0) {
return false;
}
return indexOfAnyBut(cs, valid) == INDEX_NOT_FOUND;
}
/**
* <p>Checks if the CharSequence contains only certain characters.</p>
*
* <p>A {@code null} CharSequence will return {@code false}.
* A {@code null} valid character String will return {@code false}.
* An empty String (length()=0) always returns {@code true}.</p>
*
* <pre>
* StringUtils.containsOnly(null, *) = false
* StringUtils.containsOnly(*, null) = false
* StringUtils.containsOnly("", *) = true
* StringUtils.containsOnly("ab", "") = false
* StringUtils.containsOnly("abab", "abc") = true
* StringUtils.containsOnly("ab1", "abc") = false
* StringUtils.containsOnly("abz", "abc") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param validChars a String of valid chars, may be null
* @return true if it only contains valid chars and is non-null
* @since 2.0
* @since 3.0 Changed signature from containsOnly(String, String) to containsOnly(CharSequence, String)
*/
public static boolean containsOnly(final CharSequence cs, final String validChars) {
if (cs == null || validChars == null) {
return false;
}
return containsOnly(cs, validChars.toCharArray());
}
/**
* <p>Check whether the given CharSequence contains any whitespace characters.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* @param seq the CharSequence to check (may be {@code null})
* @return {@code true} if the CharSequence is not empty and
* contains at least 1 (breaking) whitespace character
* @since 3.0
*/
// From org.springframework.util.StringUtils, under Apache License 2.0
public static boolean containsWhitespace(final CharSequence seq) {
if (isEmpty(seq)) {
return false;
}
final int strLen = seq.length();
for (int i = 0; i < strLen; i++) {
if (Character.isWhitespace(seq.charAt(i))) {
return true;
}
}
return false;
}
private static void convertRemainingAccentCharacters(final StringBuilder decomposed) {
for (int i = 0; i < decomposed.length(); i++) {
if (decomposed.charAt(i) == '\u0141') {
decomposed.deleteCharAt(i);
decomposed.insert(i, 'L');
} else if (decomposed.charAt(i) == '\u0142') {
decomposed.deleteCharAt(i);
decomposed.insert(i, 'l');
}
}
}
/**
* <p>Counts how many times the char appears in the given string.</p>
*
* <p>A {@code null} or empty ("") String input returns {@code 0}.</p>
*
* <pre>
* StringUtils.countMatches(null, *) = 0
* StringUtils.countMatches("", *) = 0
* StringUtils.countMatches("abba", 0) = 0
* StringUtils.countMatches("abba", 'a') = 2
* StringUtils.countMatches("abba", 'b') = 2
* StringUtils.countMatches("abba", 'x') = 0
* </pre>
*
* @param str the CharSequence to check, may be null
* @param ch the char to count
* @return the number of occurrences, 0 if the CharSequence is {@code null}
* @since 3.4
*/
public static int countMatches(final CharSequence str, final char ch) {
if (isEmpty(str)) {
return 0;
}
int count = 0;
// We could also call str.toCharArray() for faster look ups but that would generate more garbage.
for (int i = 0; i < str.length(); i++) {
if (ch == str.charAt(i)) {
count++;
}
}
return count;
}
// Count matches
//-----------------------------------------------------------------------
/**
* <p>Counts how many times the substring appears in the larger string.</p>
*
* <p>A {@code null} or empty ("") String input returns {@code 0}.</p>
*
* <pre>
* StringUtils.countMatches(null, *) = 0
* StringUtils.countMatches("", *) = 0
* StringUtils.countMatches("abba", null) = 0
* StringUtils.countMatches("abba", "") = 0
* StringUtils.countMatches("abba", "a") = 2
* StringUtils.countMatches("abba", "ab") = 1
* StringUtils.countMatches("abba", "xxx") = 0
* </pre>
*
* @param str the CharSequence to check, may be null
* @param sub the substring to count, may be null
* @return the number of occurrences, 0 if either CharSequence is {@code null}
* @since 3.0 Changed signature from countMatches(String, String) to countMatches(CharSequence, CharSequence)
*/
public static int countMatches(final CharSequence str, final CharSequence sub) {
if (isEmpty(str) || isEmpty(sub)) {
return 0;
}
int count = 0;
int idx = 0;
while ((idx = CharSequenceUtils.indexOf(str, sub, idx)) != INDEX_NOT_FOUND) {
count++;
idx += sub.length();
}
return count;
}
/**
* <p>Returns either the passed in CharSequence, or if the CharSequence is
* whitespace, empty ("") or {@code null}, the value of {@code defaultStr}.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.defaultIfBlank(null, "NULL") = "NULL"
* StringUtils.defaultIfBlank("", "NULL") = "NULL"
* StringUtils.defaultIfBlank(" ", "NULL") = "NULL"
* StringUtils.defaultIfBlank("bat", "NULL") = "bat"
* StringUtils.defaultIfBlank("", null) = null
* </pre>
* @param <T> the specific kind of CharSequence
* @param str the CharSequence to check, may be null
* @param defaultStr the default CharSequence to return
* if the input is whitespace, empty ("") or {@code null}, may be null
* @return the passed in CharSequence, or the default
* @see StringUtils#defaultString(String, String)
*/
public static <T extends CharSequence> T defaultIfBlank(final T str, final T defaultStr) {
return isBlank(str) ? defaultStr : str;
}
/**
* <p>Returns either the passed in CharSequence, or if the CharSequence is
* empty or {@code null}, the value of {@code defaultStr}.</p>
*
* <pre>
* StringUtils.defaultIfEmpty(null, "NULL") = "NULL"
* StringUtils.defaultIfEmpty("", "NULL") = "NULL"
* StringUtils.defaultIfEmpty(" ", "NULL") = " "
* StringUtils.defaultIfEmpty("bat", "NULL") = "bat"
* StringUtils.defaultIfEmpty("", null) = null
* </pre>
* @param <T> the specific kind of CharSequence
* @param str the CharSequence to check, may be null
* @param defaultStr the default CharSequence to return
* if the input is empty ("") or {@code null}, may be null
* @return the passed in CharSequence, or the default
* @see StringUtils#defaultString(String, String)
*/
public static <T extends CharSequence> T defaultIfEmpty(final T str, final T defaultStr) {
return isEmpty(str) ? defaultStr : str;
}
/**
* <p>Returns either the passed in String,
* or if the String is {@code null}, an empty String ("").</p>
*
* <pre>
* StringUtils.defaultString(null) = ""
* StringUtils.defaultString("") = ""
* StringUtils.defaultString("bat") = "bat"
* </pre>
*
* @see ObjectUtils#toString(Object)
* @see String#valueOf(Object)
* @param str the String to check, may be null
* @return the passed in String, or the empty String if it
* was {@code null}
*/
public static String defaultString(final String str) {
return defaultString(str, EMPTY);
}
/**
* <p>Returns either the passed in String, or if the String is
* {@code null}, the value of {@code defaultStr}.</p>
*
* <pre>
* StringUtils.defaultString(null, "NULL") = "NULL"
* StringUtils.defaultString("", "NULL") = ""
* StringUtils.defaultString("bat", "NULL") = "bat"
* </pre>
*
* @see ObjectUtils#toString(Object,String)
* @see String#valueOf(Object)
* @param str the String to check, may be null
* @param defaultStr the default String to return
* if the input is {@code null}, may be null
* @return the passed in String, or the default if it was {@code null}
*/
public static String defaultString(final String str, final String defaultStr) {
return str == null ? defaultStr : str;
}
// Delete
//-----------------------------------------------------------------------
/**
* <p>Deletes all whitespaces from a String as defined by
* {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.deleteWhitespace(null) = null
* StringUtils.deleteWhitespace("") = ""
* StringUtils.deleteWhitespace("abc") = "abc"
* StringUtils.deleteWhitespace(" ab c ") = "abc"
* </pre>
*
* @param str the String to delete whitespace from, may be null
* @return the String without whitespaces, {@code null} if null String input
*/
public static String deleteWhitespace(final String str) {
if (isEmpty(str)) {
return str;
}
final int sz = str.length();
final char[] chs = new char[sz];
int count = 0;
for (int i = 0; i < sz; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
chs[count++] = str.charAt(i);
}
}
if (count == sz) {
return str;
}
return new String(chs, 0, count);
}
// Difference
//-----------------------------------------------------------------------
/**
* <p>Compares two Strings, and returns the portion where they differ.
* More precisely, return the remainder of the second String,
* starting from where it's different from the first. This means that
* the difference between "abc" and "ab" is the empty String and not "c". </p>
*
* <p>For example,
* {@code difference("i am a machine", "i am a robot") -> "robot"}.</p>
*
* <pre>
* StringUtils.difference(null, null) = null
* StringUtils.difference("", "") = ""
* StringUtils.difference("", "abc") = "abc"
* StringUtils.difference("abc", "") = ""
* StringUtils.difference("abc", "abc") = ""
* StringUtils.difference("abc", "ab") = ""
* StringUtils.difference("ab", "abxyz") = "xyz"
* StringUtils.difference("abcde", "abxyz") = "xyz"
* StringUtils.difference("abcde", "xyz") = "xyz"
* </pre>
*
* @param str1 the first String, may be null
* @param str2 the second String, may be null
* @return the portion of str2 where it differs from str1; returns the
* empty String if they are equal
* @see #indexOfDifference(CharSequence,CharSequence)
* @since 2.0
*/
public static String difference(final String str1, final String str2) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
final int at = indexOfDifference(str1, str2);
if (at == INDEX_NOT_FOUND) {
return EMPTY;
}
return str2.substring(at);
}
/**
* <p>Check if a CharSequence ends with a specified suffix.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered to be equal. The comparison is case sensitive.</p>
*
* <pre>
* StringUtils.endsWith(null, null) = true
* StringUtils.endsWith(null, "def") = false
* StringUtils.endsWith("abcdef", null) = false
* StringUtils.endsWith("abcdef", "def") = true
* StringUtils.endsWith("ABCDEF", "def") = false
* StringUtils.endsWith("ABCDEF", "cde") = false
* StringUtils.endsWith("ABCDEF", "") = true
* </pre>
*
* @see java.lang.String#endsWith(String)
* @param str the CharSequence to check, may be null
* @param suffix the suffix to find, may be null
* @return {@code true} if the CharSequence ends with the suffix, case sensitive, or
* both {@code null}
* @since 2.4
* @since 3.0 Changed signature from endsWith(String, String) to endsWith(CharSequence, CharSequence)
*/
public static boolean endsWith(final CharSequence str, final CharSequence suffix) {
return endsWith(str, suffix, false);
}
/**
* <p>Check if a CharSequence ends with a specified suffix (optionally case insensitive).</p>
*
* @see java.lang.String#endsWith(String)
* @param str the CharSequence to check, may be null
* @param suffix the suffix to find, may be null
* @param ignoreCase indicates whether the compare should ignore case
* (case insensitive) or not.
* @return {@code true} if the CharSequence starts with the prefix or
* both {@code null}
*/
private static boolean endsWith(final CharSequence str, final CharSequence suffix, final boolean ignoreCase) {
if (str == null || suffix == null) {
return str == suffix;
}
if (suffix.length() > str.length()) {
return false;
}
final int strOffset = str.length() - suffix.length();
return CharSequenceUtils.regionMatches(str, ignoreCase, strOffset, suffix, 0, suffix.length());
}
/**
* <p>Check if a CharSequence ends with any of the provided case-sensitive suffixes.</p>
*
* <pre>
* StringUtils.endsWithAny(null, null) = false
* StringUtils.endsWithAny(null, new String[] {"abc"}) = false
* StringUtils.endsWithAny("abcxyz", null) = false
* StringUtils.endsWithAny("abcxyz", new String[] {""}) = true
* StringUtils.endsWithAny("abcxyz", new String[] {"xyz"}) = true
* StringUtils.endsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true
* StringUtils.endsWithAny("abcXYZ", "def", "XYZ") = true
* StringUtils.endsWithAny("abcXYZ", "def", "xyz") = false
* </pre>
*
* @param sequence the CharSequence to check, may be null
* @param searchStrings the case-sensitive CharSequences to find, may be empty or contain {@code null}
* @see StringUtils#endsWith(CharSequence, CharSequence)
* @return {@code true} if the input {@code sequence} is {@code null} AND no {@code searchStrings} are provided, or
* the input {@code sequence} ends in any of the provided case-sensitive {@code searchStrings}.
* @since 3.0
*/
public static boolean endsWithAny(final CharSequence sequence, final CharSequence... searchStrings) {
if (isEmpty(sequence) || ArrayUtils.isEmpty(searchStrings)) {
return false;
}
for (final CharSequence searchString : searchStrings) {
if (endsWith(sequence, searchString)) {
return true;
}
}
return false;
}
/**
* <p>Case insensitive check if a CharSequence ends with a specified suffix.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered to be equal. The comparison is case insensitive.</p>
*
* <pre>
* StringUtils.endsWithIgnoreCase(null, null) = true
* StringUtils.endsWithIgnoreCase(null, "def") = false
* StringUtils.endsWithIgnoreCase("abcdef", null) = false
* StringUtils.endsWithIgnoreCase("abcdef", "def") = true
* StringUtils.endsWithIgnoreCase("ABCDEF", "def") = true
* StringUtils.endsWithIgnoreCase("ABCDEF", "cde") = false
* </pre>
*
* @see java.lang.String#endsWith(String)
* @param str the CharSequence to check, may be null
* @param suffix the suffix to find, may be null
* @return {@code true} if the CharSequence ends with the suffix, case insensitive, or
* both {@code null}
* @since 2.4
* @since 3.0 Changed signature from endsWithIgnoreCase(String, String) to endsWithIgnoreCase(CharSequence, CharSequence)
*/
public static boolean endsWithIgnoreCase(final CharSequence str, final CharSequence suffix) {
return endsWith(str, suffix, true);
}
// Equals
//-----------------------------------------------------------------------
/**
* <p>Compares two CharSequences, returning {@code true} if they represent
* equal sequences of characters.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered to be equal. The comparison is <strong>case sensitive</strong>.</p>
*
* <pre>
* StringUtils.equals(null, null) = true
* StringUtils.equals(null, "abc") = false
* StringUtils.equals("abc", null) = false
* StringUtils.equals("abc", "abc") = true
* StringUtils.equals("abc", "ABC") = false
* </pre>
*
* @param cs1 the first CharSequence, may be {@code null}
* @param cs2 the second CharSequence, may be {@code null}
* @return {@code true} if the CharSequences are equal (case-sensitive), or both {@code null}
* @since 3.0 Changed signature from equals(String, String) to equals(CharSequence, CharSequence)
* @see Object#equals(Object)
* @see #equalsIgnoreCase(CharSequence, CharSequence)
*/
public static boolean equals(final CharSequence cs1, final CharSequence cs2) {
if (cs1 == cs2) {
return true;
}
if (cs1 == null || cs2 == null) {
return false;
}
if (cs1.length() != cs2.length()) {
return false;
}
if (cs1 instanceof String && cs2 instanceof String) {
return cs1.equals(cs2);
}
// Step-wise comparison
final int length = cs1.length();
for (int i = 0; i < length; i++) {
if (cs1.charAt(i) != cs2.charAt(i)) {
return false;
}
}
return true;
}
/**
* <p>Compares given {@code string} to a CharSequences vararg of {@code searchStrings},
* returning {@code true} if the {@code string} is equal to any of the {@code searchStrings}.</p>
*
* <pre>
* StringUtils.equalsAny(null, (CharSequence[]) null) = false
* StringUtils.equalsAny(null, null, null) = true
* StringUtils.equalsAny(null, "abc", "def") = false
* StringUtils.equalsAny("abc", null, "def") = false
* StringUtils.equalsAny("abc", "abc", "def") = true
* StringUtils.equalsAny("abc", "ABC", "DEF") = false
* </pre>
*
* @param string to compare, may be {@code null}.
* @param searchStrings a vararg of strings, may be {@code null}.
* @return {@code true} if the string is equal (case-sensitive) to any other element of {@code searchStrings};
* {@code false} if {@code searchStrings} is null or contains no matches.
* @since 3.5
*/
public static boolean equalsAny(final CharSequence string, final CharSequence... searchStrings) {
if (ArrayUtils.isNotEmpty(searchStrings)) {
for (final CharSequence next : searchStrings) {
if (equals(string, next)) {
return true;
}
}
}
return false;
}
/**
* <p>Compares given {@code string} to a CharSequences vararg of {@code searchStrings},
* returning {@code true} if the {@code string} is equal to any of the {@code searchStrings}, ignoring case.</p>
*
* <pre>
* StringUtils.equalsAnyIgnoreCase(null, (CharSequence[]) null) = false
* StringUtils.equalsAnyIgnoreCase(null, null, null) = true
* StringUtils.equalsAnyIgnoreCase(null, "abc", "def") = false
* StringUtils.equalsAnyIgnoreCase("abc", null, "def") = false
* StringUtils.equalsAnyIgnoreCase("abc", "abc", "def") = true
* StringUtils.equalsAnyIgnoreCase("abc", "ABC", "DEF") = true
* </pre>
*
* @param string to compare, may be {@code null}.
* @param searchStrings a vararg of strings, may be {@code null}.
* @return {@code true} if the string is equal (case-insensitive) to any other element of {@code searchStrings};
* {@code false} if {@code searchStrings} is null or contains no matches.
* @since 3.5
*/
public static boolean equalsAnyIgnoreCase(final CharSequence string, final CharSequence...searchStrings) {
if (ArrayUtils.isNotEmpty(searchStrings)) {
for (final CharSequence next : searchStrings) {
if (equalsIgnoreCase(string, next)) {
return true;
}
}
}
return false;
}
/**
* <p>Compares two CharSequences, returning {@code true} if they represent
* equal sequences of characters, ignoring case.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered equal. The comparison is <strong>case insensitive</strong>.</p>
*
* <pre>
* StringUtils.equalsIgnoreCase(null, null) = true
* StringUtils.equalsIgnoreCase(null, "abc") = false
* StringUtils.equalsIgnoreCase("abc", null) = false
* StringUtils.equalsIgnoreCase("abc", "abc") = true
* StringUtils.equalsIgnoreCase("abc", "ABC") = true
* </pre>
*
* @param cs1 the first CharSequence, may be {@code null}
* @param cs2 the second CharSequence, may be {@code null}
* @return {@code true} if the CharSequences are equal (case-insensitive), or both {@code null}
* @since 3.0 Changed signature from equalsIgnoreCase(String, String) to equalsIgnoreCase(CharSequence, CharSequence)
* @see #equals(CharSequence, CharSequence)
*/
public static boolean equalsIgnoreCase(final CharSequence cs1, final CharSequence cs2) {
if (cs1 == cs2) {
return true;
}
if (cs1 == null || cs2 == null) {
return false;
}
if (cs1.length() != cs2.length()) {
return false;
}
return CharSequenceUtils.regionMatches(cs1, true, 0, cs2, 0, cs1.length());
}
/**
* <p>Returns the first value in the array which is not empty (""),
* {@code null} or whitespace only.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>If all values are blank or the array is {@code null}
* or empty then {@code null} is returned.</p>
*
* <pre>
* StringUtils.firstNonBlank(null, null, null) = null
* StringUtils.firstNonBlank(null, "", " ") = null
* StringUtils.firstNonBlank("abc") = "abc"
* StringUtils.firstNonBlank(null, "xyz") = "xyz"
* StringUtils.firstNonBlank(null, "", " ", "xyz") = "xyz"
* StringUtils.firstNonBlank(null, "xyz", "abc") = "xyz"
* StringUtils.firstNonBlank() = null
* </pre>
*
* @param <T> the specific kind of CharSequence
* @param values the values to test, may be {@code null} or empty
* @return the first value from {@code values} which is not blank,
* or {@code null} if there are no non-blank values
* @since 3.8
*/
@SafeVarargs
public static <T extends CharSequence> T firstNonBlank(final T... values) {
if (values != null) {
for (final T val : values) {
if (isNotBlank(val)) {
return val;
}
}
}
return null;
}
/**
* <p>Returns the first value in the array which is not empty.</p>
*
* <p>If all values are empty or the array is {@code null}
* or empty then {@code null} is returned.</p>
*
* <pre>
* StringUtils.firstNonEmpty(null, null, null) = null
* StringUtils.firstNonEmpty(null, null, "") = null
* StringUtils.firstNonEmpty(null, "", " ") = " "
* StringUtils.firstNonEmpty("abc") = "abc"
* StringUtils.firstNonEmpty(null, "xyz") = "xyz"
* StringUtils.firstNonEmpty("", "xyz") = "xyz"
* StringUtils.firstNonEmpty(null, "xyz", "abc") = "xyz"
* StringUtils.firstNonEmpty() = null
* </pre>
*
* @param <T> the specific kind of CharSequence
* @param values the values to test, may be {@code null} or empty
* @return the first value from {@code values} which is not empty,
* or {@code null} if there are no non-empty values
* @since 3.8
*/
@SafeVarargs
public static <T extends CharSequence> T firstNonEmpty(final T... values) {
if (values != null) {
for (final T val : values) {
if (isNotEmpty(val)) {
return val;
}
}
}
return null;
}
/**
* Calls {@link String#getBytes(Charset)} in a null-safe manner.
*
* @param string input string
* @param charset The {@link Charset} to encode the {@code String}. If null, then use the default Charset.
* @return The empty byte[] if {@code string} is null, the result of {@link String#getBytes(Charset)} otherwise.
* @see String#getBytes(Charset)
* @since 3.10
*/
public static byte[] getBytes(final String string, final Charset charset) {
return string == null ? ArrayUtils.EMPTY_BYTE_ARRAY : string.getBytes(Charsets.toCharset(charset));
}
/**
* Calls {@link String#getBytes(String)} in a null-safe manner.
*
* @param string input string
* @param charset The {@link Charset} name to encode the {@code String}. If null, then use the default Charset.
* @return The empty byte[] if {@code string} is null, the result of {@link String#getBytes(String)} otherwise.
* @throws UnsupportedEncodingException Thrown when the named charset is not supported.
* @see String#getBytes(String)
* @since 3.10
*/
public static byte[] getBytes(final String string, final String charset) throws UnsupportedEncodingException {
return string == null ? ArrayUtils.EMPTY_BYTE_ARRAY : string.getBytes(Charsets.toCharsetName(charset));
}
/**
* <p>Compares all Strings in an array and returns the initial sequence of
* characters that is common to all of them.</p>
*
* <p>For example,
* {@code getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) -> "i am a "}</p>
*
* <pre>
* StringUtils.getCommonPrefix(null) = ""
* StringUtils.getCommonPrefix(new String[] {}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc"}) = "abc"
* StringUtils.getCommonPrefix(new String[] {null, null}) = ""
* StringUtils.getCommonPrefix(new String[] {"", ""}) = ""
* StringUtils.getCommonPrefix(new String[] {"", null}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc", null, null}) = ""
* StringUtils.getCommonPrefix(new String[] {null, null, "abc"}) = ""
* StringUtils.getCommonPrefix(new String[] {"", "abc"}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc", ""}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc", "abc"}) = "abc"
* StringUtils.getCommonPrefix(new String[] {"abc", "a"}) = "a"
* StringUtils.getCommonPrefix(new String[] {"ab", "abxyz"}) = "ab"
* StringUtils.getCommonPrefix(new String[] {"abcde", "abxyz"}) = "ab"
* StringUtils.getCommonPrefix(new String[] {"abcde", "xyz"}) = ""
* StringUtils.getCommonPrefix(new String[] {"xyz", "abcde"}) = ""
* StringUtils.getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) = "i am a "
* </pre>
*
* @param strs array of String objects, entries may be null
* @return the initial sequence of characters that are common to all Strings
* in the array; empty String if the array is null, the elements are all null
* or if there is no common prefix.
* @since 2.4
*/
public static String getCommonPrefix(final String... strs) {
if (ArrayUtils.isEmpty(strs)) {
return EMPTY;
}
final int smallestIndexOfDiff = indexOfDifference(strs);
if (smallestIndexOfDiff == INDEX_NOT_FOUND) {
// all strings were identical
if (strs[0] == null) {
return EMPTY;
}
return strs[0];
} else if (smallestIndexOfDiff == 0) {
// there were no common initial characters
return EMPTY;
} else {
// we found a common initial character sequence
return strs[0].substring(0, smallestIndexOfDiff);
}
}
/**
* <p>Checks if a String {@code str} contains Unicode digits,
* if yes then concatenate all the digits in {@code str} and return it as a String.</p>
*
* <p>An empty ("") String will be returned if no digits found in {@code str}.</p>
*
* <pre>
* StringUtils.getDigits(null) = null
* StringUtils.getDigits("") = ""
* StringUtils.getDigits("abc") = ""
* StringUtils.getDigits("1000$") = "1000"
* StringUtils.getDigits("1123~45") = "112345"
* StringUtils.getDigits("(541) 754-3010") = "5417543010"
* StringUtils.getDigits("\u0967\u0968\u0969") = "\u0967\u0968\u0969"
* </pre>
*
* @param str the String to extract digits from, may be null
* @return String with only digits,
* or an empty ("") String if no digits found,
* or {@code null} String if {@code str} is null
* @since 3.6
*/
public static String getDigits(final String str) {
if (isEmpty(str)) {
return str;
}
final int sz = str.length();
final StringBuilder strDigits = new StringBuilder(sz);
for (int i = 0; i < sz; i++) {
final char tempChar = str.charAt(i);
if (Character.isDigit(tempChar)) {
strDigits.append(tempChar);
}
}
return strDigits.toString();
}
/**
* <p>Find the Fuzzy Distance which indicates the similarity score between two Strings.</p>
*
* <p>This string matching algorithm is similar to the algorithms of editors such as Sublime Text,
* TextMate, Atom and others. One point is given for every matched character. Subsequent
* matches yield two bonus points. A higher score indicates a higher similarity.</p>
*
* <pre>
* StringUtils.getFuzzyDistance(null, null, null) = IllegalArgumentException
* StringUtils.getFuzzyDistance("", "", Locale.ENGLISH) = 0
* StringUtils.getFuzzyDistance("Workshop", "b", Locale.ENGLISH) = 0
* StringUtils.getFuzzyDistance("Room", "o", Locale.ENGLISH) = 1
* StringUtils.getFuzzyDistance("Workshop", "w", Locale.ENGLISH) = 1
* StringUtils.getFuzzyDistance("Workshop", "ws", Locale.ENGLISH) = 2
* StringUtils.getFuzzyDistance("Workshop", "wo", Locale.ENGLISH) = 4
* StringUtils.getFuzzyDistance("Apache Software Foundation", "asf", Locale.ENGLISH) = 3
* </pre>
*
* @param term a full term that should be matched against, must not be null
* @param query the query that will be matched against a term, must not be null
* @param locale This string matching logic is case insensitive. A locale is necessary to normalize
* both Strings to lower case.
* @return result score
* @throws IllegalArgumentException if either String input {@code null} or Locale input {@code null}
* @since 3.4
* @deprecated as of 3.6, use commons-text
* <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/similarity/FuzzyScore.html">
* FuzzyScore</a> instead
*/
@Deprecated
public static int getFuzzyDistance(final CharSequence term, final CharSequence query, final Locale locale) {
if (term == null || query == null) {
throw new IllegalArgumentException("Strings must not be null");
} else if (locale == null) {
throw new IllegalArgumentException("Locale must not be null");
}
// fuzzy logic is case insensitive. We normalize the Strings to lower
// case right from the start. Turning characters to lower case
// via Character.toLowerCase(char) is unfortunately insufficient
// as it does not accept a locale.
final String termLowerCase = term.toString().toLowerCase(locale);
final String queryLowerCase = query.toString().toLowerCase(locale);
// the resulting score
int score = 0;
// the position in the term which will be scanned next for potential
// query character matches
int termIndex = 0;
// index of the previously matched character in the term
int previousMatchingCharacterIndex = Integer.MIN_VALUE;
for (int queryIndex = 0; queryIndex < queryLowerCase.length(); queryIndex++) {
final char queryChar = queryLowerCase.charAt(queryIndex);
boolean termCharacterMatchFound = false;
for (; termIndex < termLowerCase.length() && !termCharacterMatchFound; termIndex++) {
final char termChar = termLowerCase.charAt(termIndex);
if (queryChar == termChar) {
// simple character matches result in one point
score++;
// subsequent character matches further improve
// the score.
if (previousMatchingCharacterIndex + 1 == termIndex) {
score += 2;
}
previousMatchingCharacterIndex = termIndex;
// we can leave the nested loop. Every character in the
// query can match at most one character in the term.
termCharacterMatchFound = true;
}
}
}
return score;
}
/**
* <p>Returns either the passed in CharSequence, or if the CharSequence is
* whitespace, empty ("") or {@code null}, the value supplied by {@code defaultStrSupplier}.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>Caller responsible for thread-safety and exception handling of default value supplier</p>
*
* <pre>
* {@code
* StringUtils.getIfBlank(null, () -> "NULL") = "NULL"
* StringUtils.getIfBlank("", () -> "NULL") = "NULL"
* StringUtils.getIfBlank(" ", () -> "NULL") = "NULL"
* StringUtils.getIfBlank("bat", () -> "NULL") = "bat"
* StringUtils.getIfBlank("", () -> null) = null
* StringUtils.getIfBlank("", null) = null
* }</pre>
* @param <T> the specific kind of CharSequence
* @param str the CharSequence to check, may be null
* @param defaultSupplier the supplier of default CharSequence to return
* if the input is whitespace, empty ("") or {@code null}, may be null
* @return the passed in CharSequence, or the default
* @see StringUtils#defaultString(String, String)
* @since 3.10
*/
public static <T extends CharSequence> T getIfBlank(final T str, final Supplier<T> defaultSupplier) {
return isBlank(str) ? defaultSupplier == null ? null : defaultSupplier.get() : str;
}
/**
* <p>Returns either the passed in CharSequence, or if the CharSequence is
* empty or {@code null}, the value supplied by {@code defaultStrSupplier}.</p>
*
* <p>Caller responsible for thread-safety and exception handling of default value supplier</p>
*
* <pre>
* {@code
* StringUtils.getIfEmpty(null, () -> "NULL") = "NULL"
* StringUtils.getIfEmpty("", () -> "NULL") = "NULL"
* StringUtils.getIfEmpty(" ", () -> "NULL") = " "
* StringUtils.getIfEmpty("bat", () -> "NULL") = "bat"
* StringUtils.getIfEmpty("", () -> null) = null
* StringUtils.getIfEmpty("", null) = null
* }
* </pre>
* @param <T> the specific kind of CharSequence
* @param str the CharSequence to check, may be null
* @param defaultSupplier the supplier of default CharSequence to return
* if the input is empty ("") or {@code null}, may be null
* @return the passed in CharSequence, or the default
* @see StringUtils#defaultString(String, String)
* @since 3.10
*/
public static <T extends CharSequence> T getIfEmpty(final T str, final Supplier<T> defaultSupplier) {
return isEmpty(str) ? defaultSupplier == null ? null : defaultSupplier.get() : str;
}
/**
* <p>Find the Jaro Winkler Distance which indicates the similarity score between two Strings.</p>
*
* <p>The Jaro measure is the weighted sum of percentage of matched characters from each file and transposed characters.
* Winkler increased this measure for matching initial characters.</p>
*
* <p>This implementation is based on the Jaro Winkler similarity algorithm
* from <a href="http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance">http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance</a>.</p>
*
* <pre>
* StringUtils.getJaroWinklerDistance(null, null) = IllegalArgumentException
* StringUtils.getJaroWinklerDistance("", "") = 0.0
* StringUtils.getJaroWinklerDistance("", "a") = 0.0
* StringUtils.getJaroWinklerDistance("aaapppp", "") = 0.0
* StringUtils.getJaroWinklerDistance("frog", "fog") = 0.93
* StringUtils.getJaroWinklerDistance("fly", "ant") = 0.0
* StringUtils.getJaroWinklerDistance("elephant", "hippo") = 0.44
* StringUtils.getJaroWinklerDistance("hippo", "elephant") = 0.44
* StringUtils.getJaroWinklerDistance("hippo", "zzzzzzzz") = 0.0
* StringUtils.getJaroWinklerDistance("hello", "hallo") = 0.88
* StringUtils.getJaroWinklerDistance("ABC Corporation", "ABC Corp") = 0.93
* StringUtils.getJaroWinklerDistance("D N H Enterprises Inc", "D & H Enterprises, Inc.") = 0.95
* StringUtils.getJaroWinklerDistance("My Gym Children's Fitness Center", "My Gym. Childrens Fitness") = 0.92
* StringUtils.getJaroWinklerDistance("PENNSYLVANIA", "PENNCISYLVNIA") = 0.88
* </pre>
*
* @param first the first String, must not be null
* @param second the second String, must not be null
* @return result distance
* @throws IllegalArgumentException if either String input {@code null}
* @since 3.3
* @deprecated as of 3.6, use commons-text
* <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/similarity/JaroWinklerDistance.html">
* JaroWinklerDistance</a> instead
*/
@Deprecated
public static double getJaroWinklerDistance(final CharSequence first, final CharSequence second) {
final double DEFAULT_SCALING_FACTOR = 0.1;
if (first == null || second == null) {
throw new IllegalArgumentException("Strings must not be null");
}
final int[] mtp = matches(first, second);
final double m = mtp[0];
if (m == 0) {
return 0D;
}
final double j = ((m / first.length() + m / second.length() + (m - mtp[1]) / m)) / 3;
final double jw = j < 0.7D ? j : j + Math.min(DEFAULT_SCALING_FACTOR, 1D / mtp[3]) * mtp[2] * (1D - j);
return Math.round(jw * 100.0D) / 100.0D;
}
// Misc
//-----------------------------------------------------------------------
/**
* <p>Find the Levenshtein distance between two Strings.</p>
*
* <p>This is the number of changes needed to change one String into
* another, where each change is a single character modification (deletion,
* insertion or substitution).</p>
*
* <p>The implementation uses a single-dimensional array of length s.length() + 1. See
* <a href="http://blog.softwx.net/2014/12/optimizing-levenshtein-algorithm-in-c.html">
* http://blog.softwx.net/2014/12/optimizing-levenshtein-algorithm-in-c.html</a> for details.</p>
*
* <pre>
* StringUtils.getLevenshteinDistance(null, *) = IllegalArgumentException
* StringUtils.getLevenshteinDistance(*, null) = IllegalArgumentException
* StringUtils.getLevenshteinDistance("", "") = 0
* StringUtils.getLevenshteinDistance("", "a") = 1
* StringUtils.getLevenshteinDistance("aaapppp", "") = 7
* StringUtils.getLevenshteinDistance("frog", "fog") = 1
* StringUtils.getLevenshteinDistance("fly", "ant") = 3
* StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
* StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
* StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
* StringUtils.getLevenshteinDistance("hello", "hallo") = 1
* </pre>
*
* @param s the first String, must not be null
* @param t the second String, must not be null
* @return result distance
* @throws IllegalArgumentException if either String input {@code null}
* @since 3.0 Changed signature from getLevenshteinDistance(String, String) to
* getLevenshteinDistance(CharSequence, CharSequence)
* @deprecated as of 3.6, use commons-text
* <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/similarity/LevenshteinDistance.html">
* LevenshteinDistance</a> instead
*/
@Deprecated
public static int getLevenshteinDistance(CharSequence s, CharSequence t) {
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
int n = s.length();
int m = t.length();
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
if (n > m) {
// swap the input strings to consume less memory
final CharSequence tmp = s;
s = t;
t = tmp;
n = m;
m = t.length();
}
final int p[] = new int[n + 1];
// indexes into strings s and t
int i; // iterates through s
int j; // iterates through t
int upper_left;
int upper;
char t_j; // jth character of t
int cost;
for (i = 0; i <= n; i++) {
p[i] = i;
}
for (j = 1; j <= m; j++) {
upper_left = p[0];
t_j = t.charAt(j - 1);
p[0] = j;
for (i = 1; i <= n; i++) {
upper = p[i];
cost = s.charAt(i - 1) == t_j ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left and up +cost
p[i] = Math.min(Math.min(p[i - 1] + 1, p[i] + 1), upper_left + cost);
upper_left = upper;
}
}
return p[n];
}
/**
* <p>Find the Levenshtein distance between two Strings if it's less than or equal to a given
* threshold.</p>
*
* <p>This is the number of changes needed to change one String into
* another, where each change is a single character modification (deletion,
* insertion or substitution).</p>
*
* <p>This implementation follows from Algorithms on Strings, Trees and Sequences by Dan Gusfield
* and Chas Emerick's implementation of the Levenshtein distance algorithm from
* <a href="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a></p>
*
* <pre>
* StringUtils.getLevenshteinDistance(null, *, *) = IllegalArgumentException
* StringUtils.getLevenshteinDistance(*, null, *) = IllegalArgumentException
* StringUtils.getLevenshteinDistance(*, *, -1) = IllegalArgumentException
* StringUtils.getLevenshteinDistance("", "", 0) = 0
* StringUtils.getLevenshteinDistance("aaapppp", "", 8) = 7
* StringUtils.getLevenshteinDistance("aaapppp", "", 7) = 7
* StringUtils.getLevenshteinDistance("aaapppp", "", 6)) = -1
* StringUtils.getLevenshteinDistance("elephant", "hippo", 7) = 7
* StringUtils.getLevenshteinDistance("elephant", "hippo", 6) = -1
* StringUtils.getLevenshteinDistance("hippo", "elephant", 7) = 7
* StringUtils.getLevenshteinDistance("hippo", "elephant", 6) = -1
* </pre>
*
* @param s the first String, must not be null
* @param t the second String, must not be null
* @param threshold the target threshold, must not be negative
* @return result distance, or {@code -1} if the distance would be greater than the threshold
* @throws IllegalArgumentException if either String input {@code null} or negative threshold
* @deprecated as of 3.6, use commons-text
* <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/similarity/LevenshteinDistance.html">
* LevenshteinDistance</a> instead
*/
@Deprecated
public static int getLevenshteinDistance(CharSequence s, CharSequence t, final int threshold) {
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
if (threshold < 0) {
throw new IllegalArgumentException("Threshold must not be negative");
}
/*
This implementation only computes the distance if it's less than or equal to the
threshold value, returning -1 if it's greater. The advantage is performance: unbounded
distance is O(nm), but a bound of k allows us to reduce it to O(km) time by only
computing a diagonal stripe of width 2k + 1 of the cost table.
It is also possible to use this to compute the unbounded Levenshtein distance by starting
the threshold at 1 and doubling each time until the distance is found; this is O(dm), where
d is the distance.
One subtlety comes from needing to ignore entries on the border of our stripe
eg.
p[] = |#|#|#|*
d[] = *|#|#|#|
We must ignore the entry to the left of the leftmost member
We must ignore the entry above the rightmost member
Another subtlety comes from our stripe running off the matrix if the strings aren't
of the same size. Since string s is always swapped to be the shorter of the two,
the stripe will always run off to the upper right instead of the lower left of the matrix.
As a concrete example, suppose s is of length 5, t is of length 7, and our threshold is 1.
In this case we're going to walk a stripe of length 3. The matrix would look like so:
1 2 3 4 5
1 |#|#| | | |
2 |#|#|#| | |
3 | |#|#|#| |
4 | | |#|#|#|
5 | | | |#|#|
6 | | | | |#|
7 | | | | | |
Note how the stripe leads off the table as there is no possible way to turn a string of length 5
into one of length 7 in edit distance of 1.
Additionally, this implementation decreases memory usage by using two
single-dimensional arrays and swapping them back and forth instead of allocating
an entire n by m matrix. This requires a few minor changes, such as immediately returning
when it's detected that the stripe has run off the matrix and initially filling the arrays with
large values so that entries we don't compute are ignored.
See Algorithms on Strings, Trees and Sequences by Dan Gusfield for some discussion.
*/
int n = s.length(); // length of s
int m = t.length(); // length of t
// if one string is empty, the edit distance is necessarily the length of the other
if (n == 0) {
return m <= threshold ? m : -1;
} else if (m == 0) {
return n <= threshold ? n : -1;
} else if (Math.abs(n - m) > threshold) {
// no need to calculate the distance if the length difference is greater than the threshold
return -1;
}
if (n > m) {
// swap the two strings to consume less memory
final CharSequence tmp = s;
s = t;
t = tmp;
n = m;
m = t.length();
}
int p[] = new int[n + 1]; // 'previous' cost array, horizontally
int d[] = new int[n + 1]; // cost array, horizontally
int _d[]; // placeholder to assist in swapping p and d
// fill in starting table values
final int boundary = Math.min(n, threshold) + 1;
for (int i = 0; i < boundary; i++) {
p[i] = i;
}
// these fills ensure that the value above the rightmost entry of our
// stripe will be ignored in following loop iterations
Arrays.fill(p, boundary, p.length, Integer.MAX_VALUE);
Arrays.fill(d, Integer.MAX_VALUE);
// iterates through t
for (int j = 1; j <= m; j++) {
final char t_j = t.charAt(j - 1); // jth character of t
d[0] = j;
// compute stripe indices, constrain to array size
final int min = Math.max(1, j - threshold);
final int max = j > Integer.MAX_VALUE - threshold ? n : Math.min(n, j + threshold);
// the stripe may lead off of the table if s and t are of different sizes
if (min > max) {
return -1;
}
// ignore entry left of leftmost
if (min > 1) {
d[min - 1] = Integer.MAX_VALUE;
}
// iterates through [min, max] in s
for (int i = min; i <= max; i++) {
if (s.charAt(i - 1) == t_j) {
// diagonally left and up
d[i] = p[i - 1];
} else {
// 1 + minimum of cell to the left, to the top, diagonally left and up
d[i] = 1 + Math.min(Math.min(d[i - 1], p[i]), p[i - 1]);
}
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// if p[n] is greater than the threshold, there's no guarantee on it being the correct
// distance
if (p[n] <= threshold) {
return p[n];
}
return -1;
}
/**
* <p>Finds the first index within a CharSequence, handling {@code null}.
* This method uses {@link String#indexOf(String, int)} if possible.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.</p>
*
* <pre>
* StringUtils.indexOf(null, *) = -1
* StringUtils.indexOf(*, null) = -1
* StringUtils.indexOf("", "") = 0
* StringUtils.indexOf("", *) = -1 (except when * = "")
* StringUtils.indexOf("aabaabaa", "a") = 0
* StringUtils.indexOf("aabaabaa", "b") = 2
* StringUtils.indexOf("aabaabaa", "ab") = 1
* StringUtils.indexOf("aabaabaa", "") = 0
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchSeq the CharSequence to find, may be null
* @return the first index of the search CharSequence,
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from indexOf(String, String) to indexOf(CharSequence, CharSequence)
*/
public static int indexOf(final CharSequence seq, final CharSequence searchSeq) {
if (seq == null || searchSeq == null) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.indexOf(seq, searchSeq, 0);
}
/**
* <p>Finds the first index within a CharSequence, handling {@code null}.
* This method uses {@link String#indexOf(String, int)} if possible.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A negative start position is treated as zero.
* An empty ("") search CharSequence always matches.
* A start position greater than the string length only matches
* an empty search CharSequence.</p>
*
* <pre>
* StringUtils.indexOf(null, *, *) = -1
* StringUtils.indexOf(*, null, *) = -1
* StringUtils.indexOf("", "", 0) = 0
* StringUtils.indexOf("", *, 0) = -1 (except when * = "")
* StringUtils.indexOf("aabaabaa", "a", 0) = 0
* StringUtils.indexOf("aabaabaa", "b", 0) = 2
* StringUtils.indexOf("aabaabaa", "ab", 0) = 1
* StringUtils.indexOf("aabaabaa", "b", 3) = 5
* StringUtils.indexOf("aabaabaa", "b", 9) = -1
* StringUtils.indexOf("aabaabaa", "b", -1) = 2
* StringUtils.indexOf("aabaabaa", "", 2) = 2
* StringUtils.indexOf("abc", "", 9) = 3
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchSeq the CharSequence to find, may be null
* @param startPos the start position, negative treated as zero
* @return the first index of the search CharSequence (always ≥ startPos),
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from indexOf(String, String, int) to indexOf(CharSequence, CharSequence, int)
*/
public static int indexOf(final CharSequence seq, final CharSequence searchSeq, final int startPos) {
if (seq == null || searchSeq == null) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.indexOf(seq, searchSeq, startPos);
}
// IndexOf
//-----------------------------------------------------------------------
/**
* Returns the index within {@code seq} of the first occurrence of
* the specified character. If a character with value
* {@code searchChar} occurs in the character sequence represented by
* {@code seq} {@code CharSequence} object, then the index (in Unicode
* code units) of the first such occurrence is returned. For
* values of {@code searchChar} in the range from 0 to 0xFFFF
* (inclusive), this is the smallest value <i>k</i> such that:
* <blockquote><pre>
* this.charAt(<i>k</i>) == searchChar
* </pre></blockquote>
* is true. For other values of {@code searchChar}, it is the
* smallest value <i>k</i> such that:
* <blockquote><pre>
* this.codePointAt(<i>k</i>) == searchChar
* </pre></blockquote>
* is true. In either case, if no such character occurs in {@code seq},
* then {@code INDEX_NOT_FOUND (-1)} is returned.
*
* <p>Furthermore, a {@code null} or empty ("") CharSequence will
* return {@code INDEX_NOT_FOUND (-1)}.</p>
*
* <pre>
* StringUtils.indexOf(null, *) = -1
* StringUtils.indexOf("", *) = -1
* StringUtils.indexOf("aabaabaa", 'a') = 0
* StringUtils.indexOf("aabaabaa", 'b') = 2
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchChar the character to find
* @return the first index of the search character,
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from indexOf(String, int) to indexOf(CharSequence, int)
* @since 3.6 Updated {@link CharSequenceUtils} call to behave more like {@code String}
*/
public static int indexOf(final CharSequence seq, final int searchChar) {
if (isEmpty(seq)) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.indexOf(seq, searchChar, 0);
}
/**
*
* Returns the index within {@code seq} of the first occurrence of the
* specified character, starting the search at the specified index.
* <p>
* If a character with value {@code searchChar} occurs in the
* character sequence represented by the {@code seq} {@code CharSequence}
* object at an index no smaller than {@code startPos}, then
* the index of the first such occurrence is returned. For values
* of {@code searchChar} in the range from 0 to 0xFFFF (inclusive),
* this is the smallest value <i>k</i> such that:
* <blockquote><pre>
* (this.charAt(<i>k</i>) == searchChar) && (<i>k</i> >= startPos)
* </pre></blockquote>
* is true. For other values of {@code searchChar}, it is the
* smallest value <i>k</i> such that:
* <blockquote><pre>
* (this.codePointAt(<i>k</i>) == searchChar) && (<i>k</i> >= startPos)
* </pre></blockquote>
* is true. In either case, if no such character occurs in {@code seq}
* at or after position {@code startPos}, then
* {@code -1} is returned.
*
* <p>
* There is no restriction on the value of {@code startPos}. If it
* is negative, it has the same effect as if it were zero: this entire
* string may be searched. If it is greater than the length of this
* string, it has the same effect as if it were equal to the length of
* this string: {@code (INDEX_NOT_FOUND) -1} is returned. Furthermore, a
* {@code null} or empty ("") CharSequence will
* return {@code (INDEX_NOT_FOUND) -1}.
*
* <p>All indices are specified in {@code char} values
* (Unicode code units).
*
* <pre>
* StringUtils.indexOf(null, *, *) = -1
* StringUtils.indexOf("", *, *) = -1
* StringUtils.indexOf("aabaabaa", 'b', 0) = 2
* StringUtils.indexOf("aabaabaa", 'b', 3) = 5
* StringUtils.indexOf("aabaabaa", 'b', 9) = -1
* StringUtils.indexOf("aabaabaa", 'b', -1) = 2
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchChar the character to find
* @param startPos the start position, negative treated as zero
* @return the first index of the search character (always ≥ startPos),
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from indexOf(String, int, int) to indexOf(CharSequence, int, int)
* @since 3.6 Updated {@link CharSequenceUtils} call to behave more like {@code String}
*/
public static int indexOf(final CharSequence seq, final int searchChar, final int startPos) {
if (isEmpty(seq)) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.indexOf(seq, searchChar, startPos);
}
// IndexOfAny chars
//-----------------------------------------------------------------------
/**
* <p>Search a CharSequence to find the first index of any
* character in the given set of characters.</p>
*
* <p>A {@code null} String will return {@code -1}.
* A {@code null} or zero length search array will return {@code -1}.</p>
*
* <pre>
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny("", *) = -1
* StringUtils.indexOfAny(*, null) = -1
* StringUtils.indexOfAny(*, []) = -1
* StringUtils.indexOfAny("zzabyycdxx", ['z', 'a']) = 0
* StringUtils.indexOfAny("zzabyycdxx", ['b', 'y']) = 3
* StringUtils.indexOfAny("aba", ['z']) = -1
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
* @since 3.0 Changed signature from indexOfAny(String, char[]) to indexOfAny(CharSequence, char...)
*/
public static int indexOfAny(final CharSequence cs, final char... searchChars) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
final int csLen = cs.length();
final int csLast = csLen - 1;
final int searchLen = searchChars.length;
final int searchLast = searchLen - 1;
for (int i = 0; i < csLen; i++) {
final char ch = cs.charAt(i);
for (int j = 0; j < searchLen; j++) {
if (searchChars[j] == ch) {
if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) {
// ch is a supplementary character
if (searchChars[j + 1] == cs.charAt(i + 1)) {
return i;
}
} else {
return i;
}
}
}
}
return INDEX_NOT_FOUND;
}
// IndexOfAny strings
//-----------------------------------------------------------------------
/**
* <p>Find the first index of any of a set of potential substrings.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A {@code null} or zero length search array will return {@code -1}.
* A {@code null} search array entry will be ignored, but a search
* array containing "" will return {@code 0} if {@code str} is not
* null. This method uses {@link String#indexOf(String)} if possible.</p>
*
* <pre>
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny(*, null) = -1
* StringUtils.indexOfAny(*, []) = -1
* StringUtils.indexOfAny("zzabyycdxx", ["ab", "cd"]) = 2
* StringUtils.indexOfAny("zzabyycdxx", ["cd", "ab"]) = 2
* StringUtils.indexOfAny("zzabyycdxx", ["mn", "op"]) = -1
* StringUtils.indexOfAny("zzabyycdxx", ["zab", "aby"]) = 1
* StringUtils.indexOfAny("zzabyycdxx", [""]) = 0
* StringUtils.indexOfAny("", [""]) = 0
* StringUtils.indexOfAny("", ["a"]) = -1
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStrs the CharSequences to search for, may be null
* @return the first index of any of the searchStrs in str, -1 if no match
* @since 3.0 Changed signature from indexOfAny(String, String[]) to indexOfAny(CharSequence, CharSequence...)
*/
public static int indexOfAny(final CharSequence str, final CharSequence... searchStrs) {
if (str == null || searchStrs == null) {
return INDEX_NOT_FOUND;
}
// String's can't have a MAX_VALUEth index.
int ret = Integer.MAX_VALUE;
int tmp = 0;
for (final CharSequence search : searchStrs) {
if (search == null) {
continue;
}
tmp = CharSequenceUtils.indexOf(str, search, 0);
if (tmp == INDEX_NOT_FOUND) {
continue;
}
if (tmp < ret) {
ret = tmp;
}
}
return ret == Integer.MAX_VALUE ? INDEX_NOT_FOUND : ret;
}
/**
* <p>Search a CharSequence to find the first index of any
* character in the given set of characters.</p>
*
* <p>A {@code null} String will return {@code -1}.
* A {@code null} search string will return {@code -1}.</p>
*
* <pre>
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny("", *) = -1
* StringUtils.indexOfAny(*, null) = -1
* StringUtils.indexOfAny(*, "") = -1
* StringUtils.indexOfAny("zzabyycdxx", "za") = 0
* StringUtils.indexOfAny("zzabyycdxx", "by") = 3
* StringUtils.indexOfAny("aba", "z") = -1
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
* @since 3.0 Changed signature from indexOfAny(String, String) to indexOfAny(CharSequence, String)
*/
public static int indexOfAny(final CharSequence cs, final String searchChars) {
if (isEmpty(cs) || isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
return indexOfAny(cs, searchChars.toCharArray());
}
// IndexOfAnyBut chars
//-----------------------------------------------------------------------
/**
* <p>Searches a CharSequence to find the first index of any
* character not in the given set of characters.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A {@code null} or zero length search array will return {@code -1}.</p>
*
* <pre>
* StringUtils.indexOfAnyBut(null, *) = -1
* StringUtils.indexOfAnyBut("", *) = -1
* StringUtils.indexOfAnyBut(*, null) = -1
* StringUtils.indexOfAnyBut(*, []) = -1
* StringUtils.indexOfAnyBut("zzabyycdxx", new char[] {'z', 'a'} ) = 3
* StringUtils.indexOfAnyBut("aba", new char[] {'z'} ) = 0
* StringUtils.indexOfAnyBut("aba", new char[] {'a', 'b'} ) = -1
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
* @since 3.0 Changed signature from indexOfAnyBut(String, char[]) to indexOfAnyBut(CharSequence, char...)
*/
public static int indexOfAnyBut(final CharSequence cs, final char... searchChars) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
final int csLen = cs.length();
final int csLast = csLen - 1;
final int searchLen = searchChars.length;
final int searchLast = searchLen - 1;
outer:
for (int i = 0; i < csLen; i++) {
final char ch = cs.charAt(i);
for (int j = 0; j < searchLen; j++) {
if (searchChars[j] == ch) {
if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) {
if (searchChars[j + 1] == cs.charAt(i + 1)) {
continue outer;
}
} else {
continue outer;
}
}
}
return i;
}
return INDEX_NOT_FOUND;
}
/**
* <p>Search a CharSequence to find the first index of any
* character not in the given set of characters.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A {@code null} or empty search string will return {@code -1}.</p>
*
* <pre>
* StringUtils.indexOfAnyBut(null, *) = -1
* StringUtils.indexOfAnyBut("", *) = -1
* StringUtils.indexOfAnyBut(*, null) = -1
* StringUtils.indexOfAnyBut(*, "") = -1
* StringUtils.indexOfAnyBut("zzabyycdxx", "za") = 3
* StringUtils.indexOfAnyBut("zzabyycdxx", "") = -1
* StringUtils.indexOfAnyBut("aba", "ab") = -1
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
* @since 3.0 Changed signature from indexOfAnyBut(String, String) to indexOfAnyBut(CharSequence, CharSequence)
*/
public static int indexOfAnyBut(final CharSequence seq, final CharSequence searchChars) {
if (isEmpty(seq) || isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
final int strLen = seq.length();
for (int i = 0; i < strLen; i++) {
final char ch = seq.charAt(i);
final boolean chFound = CharSequenceUtils.indexOf(searchChars, ch, 0) >= 0;
if (i + 1 < strLen && Character.isHighSurrogate(ch)) {
final char ch2 = seq.charAt(i + 1);
if (chFound && CharSequenceUtils.indexOf(searchChars, ch2, 0) < 0) {
return i;
}
} else {
if (!chFound) {
return i;
}
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Compares all CharSequences in an array and returns the index at which the
* CharSequences begin to differ.</p>
*
* <p>For example,
* {@code indexOfDifference(new String[] {"i am a machine", "i am a robot"}) -> 7}</p>
*
* <pre>
* StringUtils.indexOfDifference(null) = -1
* StringUtils.indexOfDifference(new String[] {}) = -1
* StringUtils.indexOfDifference(new String[] {"abc"}) = -1
* StringUtils.indexOfDifference(new String[] {null, null}) = -1
* StringUtils.indexOfDifference(new String[] {"", ""}) = -1
* StringUtils.indexOfDifference(new String[] {"", null}) = 0
* StringUtils.indexOfDifference(new String[] {"abc", null, null}) = 0
* StringUtils.indexOfDifference(new String[] {null, null, "abc"}) = 0
* StringUtils.indexOfDifference(new String[] {"", "abc"}) = 0
* StringUtils.indexOfDifference(new String[] {"abc", ""}) = 0
* StringUtils.indexOfDifference(new String[] {"abc", "abc"}) = -1
* StringUtils.indexOfDifference(new String[] {"abc", "a"}) = 1
* StringUtils.indexOfDifference(new String[] {"ab", "abxyz"}) = 2
* StringUtils.indexOfDifference(new String[] {"abcde", "abxyz"}) = 2
* StringUtils.indexOfDifference(new String[] {"abcde", "xyz"}) = 0
* StringUtils.indexOfDifference(new String[] {"xyz", "abcde"}) = 0
* StringUtils.indexOfDifference(new String[] {"i am a machine", "i am a robot"}) = 7
* </pre>
*
* @param css array of CharSequences, entries may be null
* @return the index where the strings begin to differ; -1 if they are all equal
* @since 2.4
* @since 3.0 Changed signature from indexOfDifference(String...) to indexOfDifference(CharSequence...)
*/
public static int indexOfDifference(final CharSequence... css) {
if (ArrayUtils.getLength(css) <= 1) {
return INDEX_NOT_FOUND;
}
boolean anyStringNull = false;
boolean allStringsNull = true;
final int arrayLen = css.length;
int shortestStrLen = Integer.MAX_VALUE;
int longestStrLen = 0;
// find the min and max string lengths; this avoids checking to make
// sure we are not exceeding the length of the string each time through
// the bottom loop.
for (final CharSequence cs : css) {
if (cs == null) {
anyStringNull = true;
shortestStrLen = 0;
} else {
allStringsNull = false;
shortestStrLen = Math.min(cs.length(), shortestStrLen);
longestStrLen = Math.max(cs.length(), longestStrLen);
}
}
// handle lists containing all nulls or all empty strings
if (allStringsNull || longestStrLen == 0 && !anyStringNull) {
return INDEX_NOT_FOUND;
}
// handle lists containing some nulls or some empty strings
if (shortestStrLen == 0) {
return 0;
}
// find the position with the first difference across all strings
int firstDiff = -1;
for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) {
final char comparisonChar = css[0].charAt(stringPos);
for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) {
if (css[arrayPos].charAt(stringPos) != comparisonChar) {
firstDiff = stringPos;
break;
}
}
if (firstDiff != -1) {
break;
}
}
if (firstDiff == -1 && shortestStrLen != longestStrLen) {
// we compared all of the characters up to the length of the
// shortest string and didn't find a match, but the string lengths
// vary, so return the length of the shortest string.
return shortestStrLen;
}
return firstDiff;
}
/**
* <p>Compares two CharSequences, and returns the index at which the
* CharSequences begin to differ.</p>
*
* <p>For example,
* {@code indexOfDifference("i am a machine", "i am a robot") -> 7}</p>
*
* <pre>
* StringUtils.indexOfDifference(null, null) = -1
* StringUtils.indexOfDifference("", "") = -1
* StringUtils.indexOfDifference("", "abc") = 0
* StringUtils.indexOfDifference("abc", "") = 0
* StringUtils.indexOfDifference("abc", "abc") = -1
* StringUtils.indexOfDifference("ab", "abxyz") = 2
* StringUtils.indexOfDifference("abcde", "abxyz") = 2
* StringUtils.indexOfDifference("abcde", "xyz") = 0
* </pre>
*
* @param cs1 the first CharSequence, may be null
* @param cs2 the second CharSequence, may be null
* @return the index where cs1 and cs2 begin to differ; -1 if they are equal
* @since 2.0
* @since 3.0 Changed signature from indexOfDifference(String, String) to
* indexOfDifference(CharSequence, CharSequence)
*/
public static int indexOfDifference(final CharSequence cs1, final CharSequence cs2) {
if (cs1 == cs2) {
return INDEX_NOT_FOUND;
}
if (cs1 == null || cs2 == null) {
return 0;
}
int i;
for (i = 0; i < cs1.length() && i < cs2.length(); ++i) {
if (cs1.charAt(i) != cs2.charAt(i)) {
break;
}
}
if (i < cs2.length() || i < cs1.length()) {
return i;
}
return INDEX_NOT_FOUND;
}
/**
* <p>Case in-sensitive find of the first index within a CharSequence.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A negative start position is treated as zero.
* An empty ("") search CharSequence always matches.
* A start position greater than the string length only matches
* an empty search CharSequence.</p>
*
* <pre>
* StringUtils.indexOfIgnoreCase(null, *) = -1
* StringUtils.indexOfIgnoreCase(*, null) = -1
* StringUtils.indexOfIgnoreCase("", "") = 0
* StringUtils.indexOfIgnoreCase("aabaabaa", "a") = 0
* StringUtils.indexOfIgnoreCase("aabaabaa", "b") = 2
* StringUtils.indexOfIgnoreCase("aabaabaa", "ab") = 1
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @return the first index of the search CharSequence,
* -1 if no match or {@code null} string input
* @since 2.5
* @since 3.0 Changed signature from indexOfIgnoreCase(String, String) to indexOfIgnoreCase(CharSequence, CharSequence)
*/
public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr) {
return indexOfIgnoreCase(str, searchStr, 0);
}
/**
* <p>Case in-sensitive find of the first index within a CharSequence
* from the specified position.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A negative start position is treated as zero.
* An empty ("") search CharSequence always matches.
* A start position greater than the string length only matches
* an empty search CharSequence.</p>
*
* <pre>
* StringUtils.indexOfIgnoreCase(null, *, *) = -1
* StringUtils.indexOfIgnoreCase(*, null, *) = -1
* StringUtils.indexOfIgnoreCase("", "", 0) = 0
* StringUtils.indexOfIgnoreCase("aabaabaa", "A", 0) = 0
* StringUtils.indexOfIgnoreCase("aabaabaa", "B", 0) = 2
* StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1
* StringUtils.indexOfIgnoreCase("aabaabaa", "B", 3) = 5
* StringUtils.indexOfIgnoreCase("aabaabaa", "B", 9) = -1
* StringUtils.indexOfIgnoreCase("aabaabaa", "B", -1) = 2
* StringUtils.indexOfIgnoreCase("aabaabaa", "", 2) = 2
* StringUtils.indexOfIgnoreCase("abc", "", 9) = -1
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @param startPos the start position, negative treated as zero
* @return the first index of the search CharSequence (always ≥ startPos),
* -1 if no match or {@code null} string input
* @since 2.5
* @since 3.0 Changed signature from indexOfIgnoreCase(String, String, int) to indexOfIgnoreCase(CharSequence, CharSequence, int)
*/
public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int startPos) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
if (startPos < 0) {
startPos = 0;
}
final int endLimit = str.length() - searchStr.length() + 1;
if (startPos > endLimit) {
return INDEX_NOT_FOUND;
}
if (searchStr.length() == 0) {
return startPos;
}
for (int i = startPos; i < endLimit; i++) {
if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, searchStr.length())) {
return i;
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Checks if all of the CharSequences are empty (""), null or whitespace only.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.isAllBlank(null) = true
* StringUtils.isAllBlank(null, "foo") = false
* StringUtils.isAllBlank(null, null) = true
* StringUtils.isAllBlank("", "bar") = false
* StringUtils.isAllBlank("bob", "") = false
* StringUtils.isAllBlank(" bob ", null) = false
* StringUtils.isAllBlank(" ", "bar") = false
* StringUtils.isAllBlank("foo", "bar") = false
* StringUtils.isAllBlank(new String[] {}) = true
* </pre>
*
* @param css the CharSequences to check, may be null or empty
* @return {@code true} if all of the CharSequences are empty or null or whitespace only
* @since 3.6
*/
public static boolean isAllBlank(final CharSequence... css) {
if (ArrayUtils.isEmpty(css)) {
return true;
}
for (final CharSequence cs : css) {
if (isNotBlank(cs)) {
return false;
}
}
return true;
}
/**
* <p>Checks if all of the CharSequences are empty ("") or null.</p>
*
* <pre>
* StringUtils.isAllEmpty(null) = true
* StringUtils.isAllEmpty(null, "") = true
* StringUtils.isAllEmpty(new String[] {}) = true
* StringUtils.isAllEmpty(null, "foo") = false
* StringUtils.isAllEmpty("", "bar") = false
* StringUtils.isAllEmpty("bob", "") = false
* StringUtils.isAllEmpty(" bob ", null) = false
* StringUtils.isAllEmpty(" ", "bar") = false
* StringUtils.isAllEmpty("foo", "bar") = false
* </pre>
*
* @param css the CharSequences to check, may be null or empty
* @return {@code true} if all of the CharSequences are empty or null
* @since 3.6
*/
public static boolean isAllEmpty(final CharSequence... css) {
if (ArrayUtils.isEmpty(css)) {
return true;
}
for (final CharSequence cs : css) {
if (isNotEmpty(cs)) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only lowercase characters.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code false}.</p>
*
* <pre>
* StringUtils.isAllLowerCase(null) = false
* StringUtils.isAllLowerCase("") = false
* StringUtils.isAllLowerCase(" ") = false
* StringUtils.isAllLowerCase("abc") = true
* StringUtils.isAllLowerCase("abC") = false
* StringUtils.isAllLowerCase("ab c") = false
* StringUtils.isAllLowerCase("ab1c") = false
* StringUtils.isAllLowerCase("ab/c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains lowercase characters, and is non-null
* @since 2.5
* @since 3.0 Changed signature from isAllLowerCase(String) to isAllLowerCase(CharSequence)
*/
public static boolean isAllLowerCase(final CharSequence cs) {
if (isEmpty(cs)) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isLowerCase(cs.charAt(i))) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only uppercase characters.</p>
*
* <p>{@code null} will return {@code false}.
* An empty String (length()=0) will return {@code false}.</p>
*
* <pre>
* StringUtils.isAllUpperCase(null) = false
* StringUtils.isAllUpperCase("") = false
* StringUtils.isAllUpperCase(" ") = false
* StringUtils.isAllUpperCase("ABC") = true
* StringUtils.isAllUpperCase("aBC") = false
* StringUtils.isAllUpperCase("A C") = false
* StringUtils.isAllUpperCase("A1C") = false
* StringUtils.isAllUpperCase("A/C") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains uppercase characters, and is non-null
* @since 2.5
* @since 3.0 Changed signature from isAllUpperCase(String) to isAllUpperCase(CharSequence)
*/
public static boolean isAllUpperCase(final CharSequence cs) {
if (isEmpty(cs)) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isUpperCase(cs.charAt(i))) {
return false;
}
}
return true;
}
// Character Tests
//-----------------------------------------------------------------------
/**
* <p>Checks if the CharSequence contains only Unicode letters.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code false}.</p>
*
* <pre>
* StringUtils.isAlpha(null) = false
* StringUtils.isAlpha("") = false
* StringUtils.isAlpha(" ") = false
* StringUtils.isAlpha("abc") = true
* StringUtils.isAlpha("ab2c") = false
* StringUtils.isAlpha("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains letters, and is non-null
* @since 3.0 Changed signature from isAlpha(String) to isAlpha(CharSequence)
* @since 3.0 Changed "" to return false and not true
*/
public static boolean isAlpha(final CharSequence cs) {
if (isEmpty(cs)) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isLetter(cs.charAt(i))) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only Unicode letters or digits.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code false}.</p>
*
* <pre>
* StringUtils.isAlphanumeric(null) = false
* StringUtils.isAlphanumeric("") = false
* StringUtils.isAlphanumeric(" ") = false
* StringUtils.isAlphanumeric("abc") = true
* StringUtils.isAlphanumeric("ab c") = false
* StringUtils.isAlphanumeric("ab2c") = true
* StringUtils.isAlphanumeric("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains letters or digits,
* and is non-null
* @since 3.0 Changed signature from isAlphanumeric(String) to isAlphanumeric(CharSequence)
* @since 3.0 Changed "" to return false and not true
*/
public static boolean isAlphanumeric(final CharSequence cs) {
if (isEmpty(cs)) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isLetterOrDigit(cs.charAt(i))) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only Unicode letters, digits
* or space ({@code ' '}).</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code true}.</p>
*
* <pre>
* StringUtils.isAlphanumericSpace(null) = false
* StringUtils.isAlphanumericSpace("") = true
* StringUtils.isAlphanumericSpace(" ") = true
* StringUtils.isAlphanumericSpace("abc") = true
* StringUtils.isAlphanumericSpace("ab c") = true
* StringUtils.isAlphanumericSpace("ab2c") = true
* StringUtils.isAlphanumericSpace("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains letters, digits or space,
* and is non-null
* @since 3.0 Changed signature from isAlphanumericSpace(String) to isAlphanumericSpace(CharSequence)
*/
public static boolean isAlphanumericSpace(final CharSequence cs) {
if (cs == null) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isLetterOrDigit(cs.charAt(i)) && cs.charAt(i) != ' ') {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only Unicode letters and
* space (' ').</p>
*
* <p>{@code null} will return {@code false}
* An empty CharSequence (length()=0) will return {@code true}.</p>
*
* <pre>
* StringUtils.isAlphaSpace(null) = false
* StringUtils.isAlphaSpace("") = true
* StringUtils.isAlphaSpace(" ") = true
* StringUtils.isAlphaSpace("abc") = true
* StringUtils.isAlphaSpace("ab c") = true
* StringUtils.isAlphaSpace("ab2c") = false
* StringUtils.isAlphaSpace("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains letters and space,
* and is non-null
* @since 3.0 Changed signature from isAlphaSpace(String) to isAlphaSpace(CharSequence)
*/
public static boolean isAlphaSpace(final CharSequence cs) {
if (cs == null) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isLetter(cs.charAt(i)) && cs.charAt(i) != ' ') {
return false;
}
}
return true;
}
/**
* <p>Checks if any of the CharSequences are empty ("") or null or whitespace only.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.isAnyBlank((String) null) = true
* StringUtils.isAnyBlank((String[]) null) = false
* StringUtils.isAnyBlank(null, "foo") = true
* StringUtils.isAnyBlank(null, null) = true
* StringUtils.isAnyBlank("", "bar") = true
* StringUtils.isAnyBlank("bob", "") = true
* StringUtils.isAnyBlank(" bob ", null) = true
* StringUtils.isAnyBlank(" ", "bar") = true
* StringUtils.isAnyBlank(new String[] {}) = false
* StringUtils.isAnyBlank(new String[]{""}) = true
* StringUtils.isAnyBlank("foo", "bar") = false
* </pre>
*
* @param css the CharSequences to check, may be null or empty
* @return {@code true} if any of the CharSequences are empty or null or whitespace only
* @since 3.2
*/
public static boolean isAnyBlank(final CharSequence... css) {
if (ArrayUtils.isEmpty(css)) {
return false;
}
for (final CharSequence cs : css) {
if (isBlank(cs)) {
return true;
}
}
return false;
}
/**
* <p>Checks if any of the CharSequences are empty ("") or null.</p>
*
* <pre>
* StringUtils.isAnyEmpty((String) null) = true
* StringUtils.isAnyEmpty((String[]) null) = false
* StringUtils.isAnyEmpty(null, "foo") = true
* StringUtils.isAnyEmpty("", "bar") = true
* StringUtils.isAnyEmpty("bob", "") = true
* StringUtils.isAnyEmpty(" bob ", null) = true
* StringUtils.isAnyEmpty(" ", "bar") = false
* StringUtils.isAnyEmpty("foo", "bar") = false
* StringUtils.isAnyEmpty(new String[]{}) = false
* StringUtils.isAnyEmpty(new String[]{""}) = true
* </pre>
*
* @param css the CharSequences to check, may be null or empty
* @return {@code true} if any of the CharSequences are empty or null
* @since 3.2
*/
public static boolean isAnyEmpty(final CharSequence... css) {
if (ArrayUtils.isEmpty(css)) {
return false;
}
for (final CharSequence cs : css) {
if (isEmpty(cs)) {
return true;
}
}
return false;
}
/**
* <p>Checks if the CharSequence contains only ASCII printable characters.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code true}.</p>
*
* <pre>
* StringUtils.isAsciiPrintable(null) = false
* StringUtils.isAsciiPrintable("") = true
* StringUtils.isAsciiPrintable(" ") = true
* StringUtils.isAsciiPrintable("Ceki") = true
* StringUtils.isAsciiPrintable("ab2c") = true
* StringUtils.isAsciiPrintable("!ab-c~") = true
* StringUtils.isAsciiPrintable("\u0020") = true
* StringUtils.isAsciiPrintable("\u0021") = true
* StringUtils.isAsciiPrintable("\u007e") = true
* StringUtils.isAsciiPrintable("\u007f") = false
* StringUtils.isAsciiPrintable("Ceki G\u00fclc\u00fc") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if every character is in the range
* 32 thru 126
* @since 2.1
* @since 3.0 Changed signature from isAsciiPrintable(String) to isAsciiPrintable(CharSequence)
*/
public static boolean isAsciiPrintable(final CharSequence cs) {
if (cs == null) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!CharUtils.isAsciiPrintable(cs.charAt(i))) {
return false;
}
}
return true;
}
// Nested extraction
//-----------------------------------------------------------------------
/**
* <p>Checks if a CharSequence is empty (""), null or whitespace only.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is null, empty or whitespace only
* @since 2.0
* @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)
*/
public static boolean isBlank(final CharSequence cs) {
final int strLen = length(cs);
if (strLen == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
// Empty checks
//-----------------------------------------------------------------------
/**
* <p>Checks if a CharSequence is empty ("") or null.</p>
*
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer trims the CharSequence.
* That functionality is available in isBlank().</p>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is empty or null
* @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence)
*/
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
/**
* <p>Checks if the CharSequence contains mixed casing of both uppercase and lowercase characters.</p>
*
* <p>{@code null} will return {@code false}. An empty CharSequence ({@code length()=0}) will return
* {@code false}.</p>
*
* <pre>
* StringUtils.isMixedCase(null) = false
* StringUtils.isMixedCase("") = false
* StringUtils.isMixedCase("ABC") = false
* StringUtils.isMixedCase("abc") = false
* StringUtils.isMixedCase("aBc") = true
* StringUtils.isMixedCase("A c") = true
* StringUtils.isMixedCase("A1c") = true
* StringUtils.isMixedCase("a/C") = true
* StringUtils.isMixedCase("aC\t") = true
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence contains both uppercase and lowercase characters
* @since 3.5
*/
public static boolean isMixedCase(final CharSequence cs) {
if (isEmpty(cs) || cs.length() == 1) {
return false;
}
boolean containsUppercase = false;
boolean containsLowercase = false;
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (containsUppercase && containsLowercase) {
return true;
} else if (Character.isUpperCase(cs.charAt(i))) {
containsUppercase = true;
} else if (Character.isLowerCase(cs.charAt(i))) {
containsLowercase = true;
}
}
return containsUppercase && containsLowercase;
}
/**
* <p>Checks if none of the CharSequences are empty (""), null or whitespace only.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.isNoneBlank((String) null) = false
* StringUtils.isNoneBlank((String[]) null) = true
* StringUtils.isNoneBlank(null, "foo") = false
* StringUtils.isNoneBlank(null, null) = false
* StringUtils.isNoneBlank("", "bar") = false
* StringUtils.isNoneBlank("bob", "") = false
* StringUtils.isNoneBlank(" bob ", null) = false
* StringUtils.isNoneBlank(" ", "bar") = false
* StringUtils.isNoneBlank(new String[] {}) = true
* StringUtils.isNoneBlank(new String[]{""}) = false
* StringUtils.isNoneBlank("foo", "bar") = true
* </pre>
*
* @param css the CharSequences to check, may be null or empty
* @return {@code true} if none of the CharSequences are empty or null or whitespace only
* @since 3.2
*/
public static boolean isNoneBlank(final CharSequence... css) {
return !isAnyBlank(css);
}
/**
* <p>Checks if none of the CharSequences are empty ("") or null.</p>
*
* <pre>
* StringUtils.isNoneEmpty((String) null) = false
* StringUtils.isNoneEmpty((String[]) null) = true
* StringUtils.isNoneEmpty(null, "foo") = false
* StringUtils.isNoneEmpty("", "bar") = false
* StringUtils.isNoneEmpty("bob", "") = false
* StringUtils.isNoneEmpty(" bob ", null) = false
* StringUtils.isNoneEmpty(new String[] {}) = true
* StringUtils.isNoneEmpty(new String[]{""}) = false
* StringUtils.isNoneEmpty(" ", "bar") = true
* StringUtils.isNoneEmpty("foo", "bar") = true
* </pre>
*
* @param css the CharSequences to check, may be null or empty
* @return {@code true} if none of the CharSequences are empty or null
* @since 3.2
*/
public static boolean isNoneEmpty(final CharSequence... css) {
return !isAnyEmpty(css);
}
/**
* <p>Checks if a CharSequence is not empty (""), not null and not whitespace only.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.isNotBlank(null) = false
* StringUtils.isNotBlank("") = false
* StringUtils.isNotBlank(" ") = false
* StringUtils.isNotBlank("bob") = true
* StringUtils.isNotBlank(" bob ") = true
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is
* not empty and not null and not whitespace only
* @since 2.0
* @since 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence)
*/
public static boolean isNotBlank(final CharSequence cs) {
return !isBlank(cs);
}
/**
* <p>Checks if a CharSequence is not empty ("") and not null.</p>
*
* <pre>
* StringUtils.isNotEmpty(null) = false
* StringUtils.isNotEmpty("") = false
* StringUtils.isNotEmpty(" ") = true
* StringUtils.isNotEmpty("bob") = true
* StringUtils.isNotEmpty(" bob ") = true
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is not empty and not null
* @since 3.0 Changed signature from isNotEmpty(String) to isNotEmpty(CharSequence)
*/
public static boolean isNotEmpty(final CharSequence cs) {
return !isEmpty(cs);
}
/**
* <p>Checks if the CharSequence contains only Unicode digits.
* A decimal point is not a Unicode digit and returns false.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code false}.</p>
*
* <p>Note that the method does not allow for a leading sign, either positive or negative.
* Also, if a String passes the numeric test, it may still generate a NumberFormatException
* when parsed by Integer.parseInt or Long.parseLong, e.g. if the value is outside the range
* for int or long respectively.</p>
*
* <pre>
* StringUtils.isNumeric(null) = false
* StringUtils.isNumeric("") = false
* StringUtils.isNumeric(" ") = false
* StringUtils.isNumeric("123") = true
* StringUtils.isNumeric("\u0967\u0968\u0969") = true
* StringUtils.isNumeric("12 3") = false
* StringUtils.isNumeric("ab2c") = false
* StringUtils.isNumeric("12-3") = false
* StringUtils.isNumeric("12.3") = false
* StringUtils.isNumeric("-123") = false
* StringUtils.isNumeric("+123") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains digits, and is non-null
* @since 3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence)
* @since 3.0 Changed "" to return false and not true
*/
public static boolean isNumeric(final CharSequence cs) {
if (isEmpty(cs)) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isDigit(cs.charAt(i))) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only Unicode digits or space
* ({@code ' '}).
* A decimal point is not a Unicode digit and returns false.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code true}.</p>
*
* <pre>
* StringUtils.isNumericSpace(null) = false
* StringUtils.isNumericSpace("") = true
* StringUtils.isNumericSpace(" ") = true
* StringUtils.isNumericSpace("123") = true
* StringUtils.isNumericSpace("12 3") = true
* StringUtils.isNumeric("\u0967\u0968\u0969") = true
* StringUtils.isNumeric("\u0967\u0968 \u0969") = true
* StringUtils.isNumericSpace("ab2c") = false
* StringUtils.isNumericSpace("12-3") = false
* StringUtils.isNumericSpace("12.3") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains digits or space,
* and is non-null
* @since 3.0 Changed signature from isNumericSpace(String) to isNumericSpace(CharSequence)
*/
public static boolean isNumericSpace(final CharSequence cs) {
if (cs == null) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isDigit(cs.charAt(i)) && cs.charAt(i) != ' ') {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only whitespace.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code true}.</p>
*
* <pre>
* StringUtils.isWhitespace(null) = false
* StringUtils.isWhitespace("") = true
* StringUtils.isWhitespace(" ") = true
* StringUtils.isWhitespace("abc") = false
* StringUtils.isWhitespace("ab2c") = false
* StringUtils.isWhitespace("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains whitespace, and is non-null
* @since 2.0
* @since 3.0 Changed signature from isWhitespace(String) to isWhitespace(CharSequence)
*/
public static boolean isWhitespace(final CharSequence cs) {
if (cs == null) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final byte[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in a start index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final byte[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = newStringBuilder(noOfItems);
buf.append(array[startIndex]);
for (int i = startIndex + 1; i < endIndex; i++) {
buf.append(separator);
buf.append(array[i]);
}
return buf.toString();
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final char[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in a start index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final char[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = newStringBuilder(noOfItems);
buf.append(array[startIndex]);
for (int i = startIndex + 1; i < endIndex; i++) {
buf.append(separator);
buf.append(array[i]);
}
return buf.toString();
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final double[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in a start index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final double[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = newStringBuilder(noOfItems);
buf.append(array[startIndex]);
for (int i = startIndex + 1; i < endIndex; i++) {
buf.append(separator);
buf.append(array[i]);
}
return buf.toString();
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final float[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in a start index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final float[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = newStringBuilder(noOfItems);
buf.append(array[startIndex]);
for (int i = startIndex + 1; i < endIndex; i++) {
buf.append(separator);
buf.append(array[i]);
}
return buf.toString();
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final int[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in a start index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final int[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = newStringBuilder(noOfItems);
buf.append(array[startIndex]);
for (int i = startIndex + 1; i < endIndex; i++) {
buf.append(separator);
buf.append(array[i]);
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided {@code Iterable} into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list. Null objects or empty
* strings within the iteration are represented by empty strings.</p>
*
* <p>See the examples here: {@link #join(Object[],char)}. </p>
*
* @param iterable the {@code Iterable} providing the values to join together, may be null
* @param separator the separator character to use
* @return the joined String, {@code null} if null iterator input
* @since 2.3
*/
public static String join(final Iterable<?> iterable, final char separator) {
if (iterable == null) {
return null;
}
return join(iterable.iterator(), separator);
}
/**
* <p>Joins the elements of the provided {@code Iterable} into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list.
* A {@code null} separator is the same as an empty String ("").</p>
*
* <p>See the examples here: {@link #join(Object[],String)}. </p>
*
* @param iterable the {@code Iterable} providing the values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, {@code null} if null iterator input
* @since 2.3
*/
public static String join(final Iterable<?> iterable, final String separator) {
if (iterable == null) {
return null;
}
return join(iterable.iterator(), separator);
}
/**
* <p>Joins the elements of the provided {@code Iterator} into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list. Null objects or empty
* strings within the iteration are represented by empty strings.</p>
*
* <p>See the examples here: {@link #join(Object[],char)}. </p>
*
* @param iterator the {@code Iterator} of values to join together, may be null
* @param separator the separator character to use
* @return the joined String, {@code null} if null iterator input
* @since 2.0
*/
public static String join(final Iterator<?> iterator, final char separator) {
// handle null, zero and one elements before building a buffer
if (iterator == null) {
return null;
}
if (!iterator.hasNext()) {
return EMPTY;
}
final Object first = iterator.next();
if (!iterator.hasNext()) {
return Objects.toString(first, EMPTY);
}
// two or more elements
final StringBuilder buf = new StringBuilder(STRING_BUILDER_SIZE); // Java default is 16, probably too small
if (first != null) {
buf.append(first);
}
while (iterator.hasNext()) {
buf.append(separator);
final Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided {@code Iterator} into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list.
* A {@code null} separator is the same as an empty String ("").</p>
*
* <p>See the examples here: {@link #join(Object[],String)}. </p>
*
* @param iterator the {@code Iterator} of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, {@code null} if null iterator input
*/
public static String join(final Iterator<?> iterator, final String separator) {
// handle null, zero and one elements before building a buffer
if (iterator == null) {
return null;
}
if (!iterator.hasNext()) {
return EMPTY;
}
final Object first = iterator.next();
if (!iterator.hasNext()) {
return Objects.toString(first, "");
}
// two or more elements
final StringBuilder buf = new StringBuilder(STRING_BUILDER_SIZE); // Java default is 16, probably too small
if (first != null) {
buf.append(first);
}
while (iterator.hasNext()) {
if (separator != null) {
buf.append(separator);
}
final Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided {@code List} into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join([null, "", "a"], ';') = ";;a"
* </pre>
*
* @param list the {@code List} of values to join together, may be null
* @param separator the separator character to use
* @param startIndex the first index to start joining from. It is
* an error to pass in a start index past the end of the list
* @param endIndex the index to stop joining from (exclusive). It is
* an error to pass in an end index past the end of the list
* @return the joined String, {@code null} if null list input
* @since 3.8
*/
public static String join(final List<?> list, final char separator, final int startIndex, final int endIndex) {
if (list == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final List<?> subList = list.subList(startIndex, endIndex);
return join(subList.iterator(), separator);
}
/**
* <p>Joins the elements of the provided {@code List} into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join([null, "", "a"], ';') = ";;a"
* </pre>
*
* @param list the {@code List} of values to join together, may be null
* @param separator the separator character to use
* @param startIndex the first index to start joining from. It is
* an error to pass in a start index past the end of the list
* @param endIndex the index to stop joining from (exclusive). It is
* an error to pass in an end index past the end of the list
* @return the joined String, {@code null} if null list input
* @since 3.8
*/
public static String join(final List<?> list, final String separator, final int startIndex, final int endIndex) {
if (list == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final List<?> subList = list.subList(startIndex, endIndex);
return join(subList.iterator(), separator);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final long[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in a start index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final long[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = newStringBuilder(noOfItems);
buf.append(array[startIndex]);
for (int i = startIndex + 1; i < endIndex; i++) {
buf.append(separator);
buf.append(array[i]);
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join([null, "", "a"], ';') = ";;a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use
* @return the joined String, {@code null} if null array input
* @since 2.0
*/
public static String join(final Object[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join([null, "", "a"], ';') = ";;a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use
* @param startIndex the first index to start joining from. It is
* an error to pass in a start index past the end of the array
* @param endIndex the index to stop joining from (exclusive). It is
* an error to pass in an end index past the end of the array
* @return the joined String, {@code null} if null array input
* @since 2.0
*/
public static String join(final Object[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = newStringBuilder(noOfItems);
if (array[startIndex] != null) {
buf.append(array[startIndex]);
}
for (int i = startIndex + 1; i < endIndex; i++) {
buf.append(separator);
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* A {@code null} separator is the same as an empty String ("").
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join(["a", "b", "c"], "") = "abc"
* StringUtils.join([null, "", "a"], ',') = ",,a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, {@code null} if null array input
*/
public static String join(final Object[] array, final String separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* A {@code null} separator is the same as an empty String ("").
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *, *, *) = null
* StringUtils.join([], *, *, *) = ""
* StringUtils.join([null], *, *, *) = ""
* StringUtils.join(["a", "b", "c"], "--", 0, 3) = "a--b--c"
* StringUtils.join(["a", "b", "c"], "--", 1, 3) = "b--c"
* StringUtils.join(["a", "b", "c"], "--", 2, 3) = "c"
* StringUtils.join(["a", "b", "c"], "--", 2, 2) = ""
* StringUtils.join(["a", "b", "c"], null, 0, 3) = "abc"
* StringUtils.join(["a", "b", "c"], "", 0, 3) = "abc"
* StringUtils.join([null, "", "a"], ',', 0, 3) = ",,a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @param startIndex the first index to start joining from.
* @param endIndex the index to stop joining from (exclusive).
* @return the joined String, {@code null} if null array input; or the empty string
* if {@code endIndex - startIndex <= 0}. The number of joined entries is given by
* {@code endIndex - startIndex}
* @throws ArrayIndexOutOfBoundsException ife<br>
* {@code startIndex < 0} or <br>
* {@code startIndex >= array.length()} or <br>
* {@code endIndex < 0} or <br>
* {@code endIndex > array.length()}
*/
public static String join(final Object[] array, String separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
if (separator == null) {
separator = EMPTY;
}
// endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator))
// (Assuming that all Strings are roughly equally long)
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = newStringBuilder(noOfItems);
if (array[startIndex] != null) {
buf.append(array[startIndex]);
}
for (int i = startIndex + 1; i < endIndex; i++) {
buf.append(separator);
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final short[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in a start index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final short[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = newStringBuilder(noOfItems);
buf.append(array[startIndex]);
for (int i = startIndex + 1; i < endIndex; i++) {
buf.append(separator);
buf.append(array[i]);
}
return buf.toString();
}
// Joining
//-----------------------------------------------------------------------
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No separator is added to the joined String.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null) = null
* StringUtils.join([]) = ""
* StringUtils.join([null]) = ""
* StringUtils.join(["a", "b", "c"]) = "abc"
* StringUtils.join([null, "", "a"]) = "a"
* </pre>
*
* @param <T> the specific type of values to join together
* @param elements the values to join together, may be null
* @return the joined String, {@code null} if null array input
* @since 2.0
* @since 3.0 Changed signature to use varargs
*/
@SafeVarargs
public static <T> String join(final T... elements) {
return join(elements, null);
}
/**
* <p>Joins the elements of the provided varargs into a
* single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list.
* {@code null} elements and separator are treated as empty Strings ("").</p>
*
* <pre>
* StringUtils.joinWith(",", {"a", "b"}) = "a,b"
* StringUtils.joinWith(",", {"a", "b",""}) = "a,b,"
* StringUtils.joinWith(",", {"a", null, "b"}) = "a,,b"
* StringUtils.joinWith(null, {"a", "b"}) = "ab"
* </pre>
*
* @param separator the separator character to use, null treated as ""
* @param objects the varargs providing the values to join together. {@code null} elements are treated as ""
* @return the joined String.
* @throws java.lang.IllegalArgumentException if a null varargs is provided
* @since 3.5
*/
public static String joinWith(final String separator, final Object... objects) {
if (objects == null) {
throw new IllegalArgumentException("Object varargs must not be null");
}
final String sanitizedSeparator = defaultString(separator);
final StringBuilder result = new StringBuilder();
final Iterator<Object> iterator = Arrays.asList(objects).iterator();
while (iterator.hasNext()) {
final String value = Objects.toString(iterator.next(), "");
result.append(value);
if (iterator.hasNext()) {
result.append(sanitizedSeparator);
}
}
return result.toString();
}
/**
* <p>Finds the last index within a CharSequence, handling {@code null}.
* This method uses {@link String#lastIndexOf(String)} if possible.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.</p>
*
* <pre>
* StringUtils.lastIndexOf(null, *) = -1
* StringUtils.lastIndexOf(*, null) = -1
* StringUtils.lastIndexOf("", "") = 0
* StringUtils.lastIndexOf("aabaabaa", "a") = 7
* StringUtils.lastIndexOf("aabaabaa", "b") = 5
* StringUtils.lastIndexOf("aabaabaa", "ab") = 4
* StringUtils.lastIndexOf("aabaabaa", "") = 8
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchSeq the CharSequence to find, may be null
* @return the last index of the search String,
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from lastIndexOf(String, String) to lastIndexOf(CharSequence, CharSequence)
*/
public static int lastIndexOf(final CharSequence seq, final CharSequence searchSeq) {
if (seq == null || searchSeq == null) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.lastIndexOf(seq, searchSeq, seq.length());
}
/**
* <p>Finds the last index within a CharSequence, handling {@code null}.
* This method uses {@link String#lastIndexOf(String, int)} if possible.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A negative start position returns {@code -1}.
* An empty ("") search CharSequence always matches unless the start position is negative.
* A start position greater than the string length searches the whole string.
* The search starts at the startPos and works backwards; matches starting after the start
* position are ignored.
* </p>
*
* <pre>
* StringUtils.lastIndexOf(null, *, *) = -1
* StringUtils.lastIndexOf(*, null, *) = -1
* StringUtils.lastIndexOf("aabaabaa", "a", 8) = 7
* StringUtils.lastIndexOf("aabaabaa", "b", 8) = 5
* StringUtils.lastIndexOf("aabaabaa", "ab", 8) = 4
* StringUtils.lastIndexOf("aabaabaa", "b", 9) = 5
* StringUtils.lastIndexOf("aabaabaa", "b", -1) = -1
* StringUtils.lastIndexOf("aabaabaa", "a", 0) = 0
* StringUtils.lastIndexOf("aabaabaa", "b", 0) = -1
* StringUtils.lastIndexOf("aabaabaa", "b", 1) = -1
* StringUtils.lastIndexOf("aabaabaa", "b", 2) = 2
* StringUtils.lastIndexOf("aabaabaa", "ba", 2) = 2
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchSeq the CharSequence to find, may be null
* @param startPos the start position, negative treated as zero
* @return the last index of the search CharSequence (always ≤ startPos),
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from lastIndexOf(String, String, int) to lastIndexOf(CharSequence, CharSequence, int)
*/
public static int lastIndexOf(final CharSequence seq, final CharSequence searchSeq, final int startPos) {
if (seq == null || searchSeq == null) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.lastIndexOf(seq, searchSeq, startPos);
}
// LastIndexOf
//-----------------------------------------------------------------------
/**
* Returns the index within {@code seq} of the last occurrence of
* the specified character. For values of {@code searchChar} in the
* range from 0 to 0xFFFF (inclusive), the index (in Unicode code
* units) returned is the largest value <i>k</i> such that:
* <blockquote><pre>
* this.charAt(<i>k</i>) == searchChar
* </pre></blockquote>
* is true. For other values of {@code searchChar}, it is the
* largest value <i>k</i> such that:
* <blockquote><pre>
* this.codePointAt(<i>k</i>) == searchChar
* </pre></blockquote>
* is true. In either case, if no such character occurs in this
* string, then {@code -1} is returned. Furthermore, a {@code null} or empty ("")
* {@code CharSequence} will return {@code -1}. The
* {@code seq} {@code CharSequence} object is searched backwards
* starting at the last character.
*
* <pre>
* StringUtils.lastIndexOf(null, *) = -1
* StringUtils.lastIndexOf("", *) = -1
* StringUtils.lastIndexOf("aabaabaa", 'a') = 7
* StringUtils.lastIndexOf("aabaabaa", 'b') = 5
* </pre>
*
* @param seq the {@code CharSequence} to check, may be null
* @param searchChar the character to find
* @return the last index of the search character,
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from lastIndexOf(String, int) to lastIndexOf(CharSequence, int)
* @since 3.6 Updated {@link CharSequenceUtils} call to behave more like {@code String}
*/
public static int lastIndexOf(final CharSequence seq, final int searchChar) {
if (isEmpty(seq)) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.lastIndexOf(seq, searchChar, seq.length());
}
/**
* Returns the index within {@code seq} of the last occurrence of
* the specified character, searching backward starting at the
* specified index. For values of {@code searchChar} in the range
* from 0 to 0xFFFF (inclusive), the index returned is the largest
* value <i>k</i> such that:
* <blockquote><pre>
* (this.charAt(<i>k</i>) == searchChar) && (<i>k</i> <= startPos)
* </pre></blockquote>
* is true. For other values of {@code searchChar}, it is the
* largest value <i>k</i> such that:
* <blockquote><pre>
* (this.codePointAt(<i>k</i>) == searchChar) && (<i>k</i> <= startPos)
* </pre></blockquote>
* is true. In either case, if no such character occurs in {@code seq}
* at or before position {@code startPos}, then
* {@code -1} is returned. Furthermore, a {@code null} or empty ("")
* {@code CharSequence} will return {@code -1}. A start position greater
* than the string length searches the whole string.
* The search starts at the {@code startPos} and works backwards;
* matches starting after the start position are ignored.
*
* <p>All indices are specified in {@code char} values
* (Unicode code units).
*
* <pre>
* StringUtils.lastIndexOf(null, *, *) = -1
* StringUtils.lastIndexOf("", *, *) = -1
* StringUtils.lastIndexOf("aabaabaa", 'b', 8) = 5
* StringUtils.lastIndexOf("aabaabaa", 'b', 4) = 2
* StringUtils.lastIndexOf("aabaabaa", 'b', 0) = -1
* StringUtils.lastIndexOf("aabaabaa", 'b', 9) = 5
* StringUtils.lastIndexOf("aabaabaa", 'b', -1) = -1
* StringUtils.lastIndexOf("aabaabaa", 'a', 0) = 0
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchChar the character to find
* @param startPos the start position
* @return the last index of the search character (always ≤ startPos),
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from lastIndexOf(String, int, int) to lastIndexOf(CharSequence, int, int)
*/
public static int lastIndexOf(final CharSequence seq, final int searchChar, final int startPos) {
if (isEmpty(seq)) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.lastIndexOf(seq, searchChar, startPos);
}
/**
* <p>Find the latest index of any substring in a set of potential substrings.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A {@code null} search array will return {@code -1}.
* A {@code null} or zero length search array entry will be ignored,
* but a search array containing "" will return the length of {@code str}
* if {@code str} is not null. This method uses {@link String#indexOf(String)} if possible</p>
*
* <pre>
* StringUtils.lastIndexOfAny(null, *) = -1
* StringUtils.lastIndexOfAny(*, null) = -1
* StringUtils.lastIndexOfAny(*, []) = -1
* StringUtils.lastIndexOfAny(*, [null]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["ab", "cd"]) = 6
* StringUtils.lastIndexOfAny("zzabyycdxx", ["cd", "ab"]) = 6
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn", "op"]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn", "op"]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn", ""]) = 10
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStrs the CharSequences to search for, may be null
* @return the last index of any of the CharSequences, -1 if no match
* @since 3.0 Changed signature from lastIndexOfAny(String, String[]) to lastIndexOfAny(CharSequence, CharSequence)
*/
public static int lastIndexOfAny(final CharSequence str, final CharSequence... searchStrs) {
if (str == null || searchStrs == null) {
return INDEX_NOT_FOUND;
}
int ret = INDEX_NOT_FOUND;
int tmp = 0;
for (final CharSequence search : searchStrs) {
if (search == null) {
continue;
}
tmp = CharSequenceUtils.lastIndexOf(str, search, str.length());
if (tmp > ret) {
ret = tmp;
}
}
return ret;
}
/**
* <p>Case in-sensitive find of the last index within a CharSequence.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A negative start position returns {@code -1}.
* An empty ("") search CharSequence always matches unless the start position is negative.
* A start position greater than the string length searches the whole string.</p>
*
* <pre>
* StringUtils.lastIndexOfIgnoreCase(null, *) = -1
* StringUtils.lastIndexOfIgnoreCase(*, null) = -1
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A") = 7
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B") = 5
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB") = 4
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @return the first index of the search CharSequence,
* -1 if no match or {@code null} string input
* @since 2.5
* @since 3.0 Changed signature from lastIndexOfIgnoreCase(String, String) to lastIndexOfIgnoreCase(CharSequence, CharSequence)
*/
public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
return lastIndexOfIgnoreCase(str, searchStr, str.length());
}
/**
* <p>Case in-sensitive find of the last index within a CharSequence
* from the specified position.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A negative start position returns {@code -1}.
* An empty ("") search CharSequence always matches unless the start position is negative.
* A start position greater than the string length searches the whole string.
* The search starts at the startPos and works backwards; matches starting after the start
* position are ignored.
* </p>
*
* <pre>
* StringUtils.lastIndexOfIgnoreCase(null, *, *) = -1
* StringUtils.lastIndexOfIgnoreCase(*, null, *) = -1
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 8) = 7
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 8) = 5
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB", 8) = 4
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 9) = 5
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", -1) = -1
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 0) = 0
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 0) = -1
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @param startPos the start position
* @return the last index of the search CharSequence (always ≤ startPos),
* -1 if no match or {@code null} input
* @since 2.5
* @since 3.0 Changed signature from lastIndexOfIgnoreCase(String, String, int) to lastIndexOfIgnoreCase(CharSequence, CharSequence, int)
*/
public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int startPos) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
if (startPos > str.length() - searchStr.length()) {
startPos = str.length() - searchStr.length();
}
if (startPos < 0) {
return INDEX_NOT_FOUND;
}
if (searchStr.length() == 0) {
return startPos;
}
for (int i = startPos; i >= 0; i--) {
if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, searchStr.length())) {
return i;
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Finds the n-th last index within a String, handling {@code null}.
* This method uses {@link String#lastIndexOf(String)}.</p>
*
* <p>A {@code null} String will return {@code -1}.</p>
*
* <pre>
* StringUtils.lastOrdinalIndexOf(null, *, *) = -1
* StringUtils.lastOrdinalIndexOf(*, null, *) = -1
* StringUtils.lastOrdinalIndexOf("", "", *) = 0
* StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 1) = 7
* StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 2) = 6
* StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 1) = 5
* StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 2) = 2
* StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 1) = 4
* StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2) = 1
* StringUtils.lastOrdinalIndexOf("aabaabaa", "", 1) = 8
* StringUtils.lastOrdinalIndexOf("aabaabaa", "", 2) = 8
* </pre>
*
* <p>Note that 'tail(CharSequence str, int n)' may be implemented as: </p>
*
* <pre>
* str.substring(lastOrdinalIndexOf(str, "\n", n) + 1)
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @param ordinal the n-th last {@code searchStr} to find
* @return the n-th last index of the search CharSequence,
* {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input
* @since 2.5
* @since 3.0 Changed signature from lastOrdinalIndexOf(String, String, int) to lastOrdinalIndexOf(CharSequence, CharSequence, int)
*/
public static int lastOrdinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal) {
return ordinalIndexOf(str, searchStr, ordinal, true);
}
// Left/Right/Mid
//-----------------------------------------------------------------------
/**
* <p>Gets the leftmost {@code len} characters of a String.</p>
*
* <p>If {@code len} characters are not available, or the
* String is {@code null}, the String will be returned without
* an exception. An empty String is returned if len is negative.</p>
*
* <pre>
* StringUtils.left(null, *) = null
* StringUtils.left(*, -ve) = ""
* StringUtils.left("", *) = ""
* StringUtils.left("abc", 0) = ""
* StringUtils.left("abc", 2) = "ab"
* StringUtils.left("abc", 4) = "abc"
* </pre>
*
* @param str the String to get the leftmost characters from, may be null
* @param len the length of the required String
* @return the leftmost characters, {@code null} if null String input
*/
public static String left(final String str, final int len) {
if (str == null) {
return null;
}
if (len < 0) {
return EMPTY;
}
if (str.length() <= len) {
return str;
}
return str.substring(0, len);
}
/**
* <p>Left pad a String with spaces (' ').</p>
*
* <p>The String is padded to the size of {@code size}.</p>
*
* <pre>
* StringUtils.leftPad(null, *) = null
* StringUtils.leftPad("", 3) = " "
* StringUtils.leftPad("bat", 3) = "bat"
* StringUtils.leftPad("bat", 5) = " bat"
* StringUtils.leftPad("bat", 1) = "bat"
* StringUtils.leftPad("bat", -1) = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @return left padded String or original String if no padding is necessary,
* {@code null} if null String input
*/
public static String leftPad(final String str, final int size) {
return leftPad(str, size, ' ');
}
/**
* <p>Left pad a String with a specified character.</p>
*
* <p>Pad to a size of {@code size}.</p>
*
* <pre>
* StringUtils.leftPad(null, *, *) = null
* StringUtils.leftPad("", 3, 'z') = "zzz"
* StringUtils.leftPad("bat", 3, 'z') = "bat"
* StringUtils.leftPad("bat", 5, 'z') = "zzbat"
* StringUtils.leftPad("bat", 1, 'z') = "bat"
* StringUtils.leftPad("bat", -1, 'z') = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padChar the character to pad with
* @return left padded String or original String if no padding is necessary,
* {@code null} if null String input
* @since 2.0
*/
public static String leftPad(final String str, final int size, final char padChar) {
if (str == null) {
return null;
}
final int pads = size - str.length();
if (pads <= 0) {
return str; // returns original String when possible
}
if (pads > PAD_LIMIT) {
return leftPad(str, size, String.valueOf(padChar));
}
return repeat(padChar, pads).concat(str);
}
/**
* <p>Left pad a String with a specified String.</p>
*
* <p>Pad to a size of {@code size}.</p>
*
* <pre>
* StringUtils.leftPad(null, *, *) = null
* StringUtils.leftPad("", 3, "z") = "zzz"
* StringUtils.leftPad("bat", 3, "yz") = "bat"
* StringUtils.leftPad("bat", 5, "yz") = "yzbat"
* StringUtils.leftPad("bat", 8, "yz") = "yzyzybat"
* StringUtils.leftPad("bat", 1, "yz") = "bat"
* StringUtils.leftPad("bat", -1, "yz") = "bat"
* StringUtils.leftPad("bat", 5, null) = " bat"
* StringUtils.leftPad("bat", 5, "") = " bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padStr the String to pad with, null or empty treated as single space
* @return left padded String or original String if no padding is necessary,
* {@code null} if null String input
*/
public static String leftPad(final String str, final int size, String padStr) {
if (str == null) {
return null;
}
if (isEmpty(padStr)) {
padStr = SPACE;
}
final int padLen = padStr.length();
final int strLen = str.length();
final int pads = size - strLen;
if (pads <= 0) {
return str; // returns original String when possible
}
if (padLen == 1 && pads <= PAD_LIMIT) {
return leftPad(str, size, padStr.charAt(0));
}
if (pads == padLen) {
return padStr.concat(str);
} else if (pads < padLen) {
return padStr.substring(0, pads).concat(str);
} else {
final char[] padding = new char[pads];
final char[] padChars = padStr.toCharArray();
for (int i = 0; i < pads; i++) {
padding[i] = padChars[i % padLen];
}
return new String(padding).concat(str);
}
}
/**
* Gets a CharSequence length or {@code 0} if the CharSequence is
* {@code null}.
*
* @param cs
* a CharSequence or {@code null}
* @return CharSequence length or {@code 0} if the CharSequence is
* {@code null}.
* @since 2.4
* @since 3.0 Changed signature from length(String) to length(CharSequence)
*/
public static int length(final CharSequence cs) {
return cs == null ? 0 : cs.length();
}
/**
* <p>Converts a String to lower case as per {@link String#toLowerCase()}.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.lowerCase(null) = null
* StringUtils.lowerCase("") = ""
* StringUtils.lowerCase("aBc") = "abc"
* </pre>
*
* <p><strong>Note:</strong> As described in the documentation for {@link String#toLowerCase()},
* the result of this method is affected by the current locale.
* For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}
* should be used with a specific locale (e.g. {@link Locale#ENGLISH}).</p>
*
* @param str the String to lower case, may be null
* @return the lower cased String, {@code null} if null String input
*/
public static String lowerCase(final String str) {
if (str == null) {
return null;
}
return str.toLowerCase();
}
/**
* <p>Converts a String to lower case as per {@link String#toLowerCase(Locale)}.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.lowerCase(null, Locale.ENGLISH) = null
* StringUtils.lowerCase("", Locale.ENGLISH) = ""
* StringUtils.lowerCase("aBc", Locale.ENGLISH) = "abc"
* </pre>
*
* @param str the String to lower case, may be null
* @param locale the locale that defines the case transformation rules, must not be null
* @return the lower cased String, {@code null} if null String input
* @since 2.5
*/
public static String lowerCase(final String str, final Locale locale) {
if (str == null) {
return null;
}
return str.toLowerCase(locale);
}
private static int[] matches(final CharSequence first, final CharSequence second) {
CharSequence max, min;
if (first.length() > second.length()) {
max = first;
min = second;
} else {
max = second;
min = first;
}
final int range = Math.max(max.length() / 2 - 1, 0);
final int[] matchIndexes = new int[min.length()];
Arrays.fill(matchIndexes, -1);
final boolean[] matchFlags = new boolean[max.length()];
int matches = 0;
for (int mi = 0; mi < min.length(); mi++) {
final char c1 = min.charAt(mi);
for (int xi = Math.max(mi - range, 0), xn = Math.min(mi + range + 1, max.length()); xi < xn; xi++) {
if (!matchFlags[xi] && c1 == max.charAt(xi)) {
matchIndexes[mi] = xi;
matchFlags[xi] = true;
matches++;
break;
}
}
}
final char[] ms1 = new char[matches];
final char[] ms2 = new char[matches];
for (int i = 0, si = 0; i < min.length(); i++) {
if (matchIndexes[i] != -1) {
ms1[si] = min.charAt(i);
si++;
}
}
for (int i = 0, si = 0; i < max.length(); i++) {
if (matchFlags[i]) {
ms2[si] = max.charAt(i);
si++;
}
}
int transpositions = 0;
for (int mi = 0; mi < ms1.length; mi++) {
if (ms1[mi] != ms2[mi]) {
transpositions++;
}
}
int prefix = 0;
for (int mi = 0; mi < min.length(); mi++) {
if (first.charAt(mi) == second.charAt(mi)) {
prefix++;
} else {
break;
}
}
return new int[] { matches, transpositions / 2, prefix, max.length() };
}
/**
* <p>Gets {@code len} characters from the middle of a String.</p>
*
* <p>If {@code len} characters are not available, the remainder
* of the String will be returned without an exception. If the
* String is {@code null}, {@code null} will be returned.
* An empty String is returned if len is negative or exceeds the
* length of {@code str}.</p>
*
* <pre>
* StringUtils.mid(null, *, *) = null
* StringUtils.mid(*, *, -ve) = ""
* StringUtils.mid("", 0, *) = ""
* StringUtils.mid("abc", 0, 2) = "ab"
* StringUtils.mid("abc", 0, 4) = "abc"
* StringUtils.mid("abc", 2, 4) = "c"
* StringUtils.mid("abc", 4, 2) = ""
* StringUtils.mid("abc", -2, 2) = "ab"
* </pre>
*
* @param str the String to get the characters from, may be null
* @param pos the position to start from, negative treated as zero
* @param len the length of the required String
* @return the middle characters, {@code null} if null String input
*/
public static String mid(final String str, int pos, final int len) {
if (str == null) {
return null;
}
if (len < 0 || pos > str.length()) {
return EMPTY;
}
if (pos < 0) {
pos = 0;
}
if (str.length() <= pos + len) {
return str.substring(pos);
}
return str.substring(pos, pos + len);
}
private static StringBuilder newStringBuilder(final int noOfItems) {
return new StringBuilder(noOfItems * 16);
}
/**
* <p>
* Similar to <a
* href="http://www.w3.org/TR/xpath/#function-normalize-space">http://www.w3.org/TR/xpath/#function-normalize
* -space</a>
* </p>
* <p>
* The function returns the argument string with whitespace normalized by using
* {@code {@link #trim(String)}} to remove leading and trailing whitespace
* and then replacing sequences of whitespace characters by a single space.
* </p>
* In XML Whitespace characters are the same as those allowed by the <a
* href="http://www.w3.org/TR/REC-xml/#NT-S">S</a> production, which is S ::= (#x20 | #x9 | #xD | #xA)+
* <p>
* Java's regexp pattern \s defines whitespace as [ \t\n\x0B\f\r]
*
* <p>For reference:</p>
* <ul>
* <li>\x0B = vertical tab</li>
* <li>\f = #xC = form feed</li>
* <li>#x20 = space</li>
* <li>#x9 = \t</li>
* <li>#xA = \n</li>
* <li>#xD = \r</li>
* </ul>
*
* <p>
* The difference is that Java's whitespace includes vertical tab and form feed, which this functional will also
* normalize. Additionally {@code {@link #trim(String)}} removes control characters (char <= 32) from both
* ends of this String.
* </p>
*
* @see Pattern
* @see #trim(String)
* @see <a
* href="http://www.w3.org/TR/xpath/#function-normalize-space">http://www.w3.org/TR/xpath/#function-normalize-space</a>
* @param str the source String to normalize whitespaces from, may be null
* @return the modified string with whitespace normalized, {@code null} if null String input
*
* @since 3.0
*/
public static String normalizeSpace(final String str) {
// LANG-1020: Improved performance significantly by normalizing manually instead of using regex
// See https://github.com/librucha/commons-lang-normalizespaces-benchmark for performance test
if (isEmpty(str)) {
return str;
}
final int size = str.length();
final char[] newChars = new char[size];
int count = 0;
int whitespacesCount = 0;
boolean startWhitespaces = true;
for (int i = 0; i < size; i++) {
final char actualChar = str.charAt(i);
final boolean isWhitespace = Character.isWhitespace(actualChar);
if (isWhitespace) {
if (whitespacesCount == 0 && !startWhitespaces) {
newChars[count++] = SPACE.charAt(0);
}
whitespacesCount++;
} else {
startWhitespaces = false;
newChars[count++] = (actualChar == 160 ? 32 : actualChar);
whitespacesCount = 0;
}
}
if (startWhitespaces) {
return EMPTY;
}
return new String(newChars, 0, count - (whitespacesCount > 0 ? 1 : 0)).trim();
}
/**
* <p>Finds the n-th index within a CharSequence, handling {@code null}.
* This method uses {@link String#indexOf(String)} if possible.</p>
* <p><b>Note:</b> The code starts looking for a match at the start of the target,
* incrementing the starting index by one after each successful match
* (unless {@code searchStr} is an empty string in which case the position
* is never incremented and {@code 0} is returned immediately).
* This means that matches may overlap.</p>
* <p>A {@code null} CharSequence will return {@code -1}.</p>
*
* <pre>
* StringUtils.ordinalIndexOf(null, *, *) = -1
* StringUtils.ordinalIndexOf(*, null, *) = -1
* StringUtils.ordinalIndexOf("", "", *) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "a", 1) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "a", 2) = 1
* StringUtils.ordinalIndexOf("aabaabaa", "b", 1) = 2
* StringUtils.ordinalIndexOf("aabaabaa", "b", 2) = 5
* StringUtils.ordinalIndexOf("aabaabaa", "ab", 1) = 1
* StringUtils.ordinalIndexOf("aabaabaa", "ab", 2) = 4
* StringUtils.ordinalIndexOf("aabaabaa", "", 1) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "", 2) = 0
* </pre>
*
* <p>Matches may overlap:</p>
* <pre>
* StringUtils.ordinalIndexOf("ababab", "aba", 1) = 0
* StringUtils.ordinalIndexOf("ababab", "aba", 2) = 2
* StringUtils.ordinalIndexOf("ababab", "aba", 3) = -1
*
* StringUtils.ordinalIndexOf("abababab", "abab", 1) = 0
* StringUtils.ordinalIndexOf("abababab", "abab", 2) = 2
* StringUtils.ordinalIndexOf("abababab", "abab", 3) = 4
* StringUtils.ordinalIndexOf("abababab", "abab", 4) = -1
* </pre>
*
* <p>Note that 'head(CharSequence str, int n)' may be implemented as: </p>
*
* <pre>
* str.substring(0, lastOrdinalIndexOf(str, "\n", n))
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @param ordinal the n-th {@code searchStr} to find
* @return the n-th index of the search CharSequence,
* {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input
* @since 2.1
* @since 3.0 Changed signature from ordinalIndexOf(String, String, int) to ordinalIndexOf(CharSequence, CharSequence, int)
*/
public static int ordinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal) {
return ordinalIndexOf(str, searchStr, ordinal, false);
}
/**
* <p>Finds the n-th index within a String, handling {@code null}.
* This method uses {@link String#indexOf(String)} if possible.</p>
* <p>Note that matches may overlap<p>
*
* <p>A {@code null} CharSequence will return {@code -1}.</p>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @param ordinal the n-th {@code searchStr} to find, overlapping matches are allowed.
* @param lastIndex true if lastOrdinalIndexOf() otherwise false if ordinalIndexOf()
* @return the n-th index of the search CharSequence,
* {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input
*/
// Shared code between ordinalIndexOf(String, String, int) and lastOrdinalIndexOf(String, String, int)
private static int ordinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal, final boolean lastIndex) {
if (str == null || searchStr == null || ordinal <= 0) {
return INDEX_NOT_FOUND;
}
if (searchStr.length() == 0) {
return lastIndex ? str.length() : 0;
}
int found = 0;
// set the initial index beyond the end of the string
// this is to allow for the initial index decrement/increment
int index = lastIndex ? str.length() : INDEX_NOT_FOUND;
do {
if (lastIndex) {
index = CharSequenceUtils.lastIndexOf(str, searchStr, index - 1); // step backwards thru string
} else {
index = CharSequenceUtils.indexOf(str, searchStr, index + 1); // step forwards through string
}
if (index < 0) {
return index;
}
found++;
} while (found < ordinal);
return index;
}
// Overlay
//-----------------------------------------------------------------------
/**
* <p>Overlays part of a String with another String.</p>
*
* <p>A {@code null} string input returns {@code null}.
* A negative index is treated as zero.
* An index greater than the string length is treated as the string length.
* The start index is always the smaller of the two indices.</p>
*
* <pre>
* StringUtils.overlay(null, *, *, *) = null
* StringUtils.overlay("", "abc", 0, 0) = "abc"
* StringUtils.overlay("abcdef", null, 2, 4) = "abef"
* StringUtils.overlay("abcdef", "", 2, 4) = "abef"
* StringUtils.overlay("abcdef", "", 4, 2) = "abef"
* StringUtils.overlay("abcdef", "zzzz", 2, 4) = "abzzzzef"
* StringUtils.overlay("abcdef", "zzzz", 4, 2) = "abzzzzef"
* StringUtils.overlay("abcdef", "zzzz", -1, 4) = "zzzzef"
* StringUtils.overlay("abcdef", "zzzz", 2, 8) = "abzzzz"
* StringUtils.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef"
* StringUtils.overlay("abcdef", "zzzz", 8, 10) = "abcdefzzzz"
* </pre>
*
* @param str the String to do overlaying in, may be null
* @param overlay the String to overlay, may be null
* @param start the position to start overlaying at
* @param end the position to stop overlaying before
* @return overlayed String, {@code null} if null String input
* @since 2.0
*/
public static String overlay(final String str, String overlay, int start, int end) {
if (str == null) {
return null;
}
if (overlay == null) {
overlay = EMPTY;
}
final int len = str.length();
if (start < 0) {
start = 0;
}
if (start > len) {
start = len;
}
if (end < 0) {
end = 0;
}
if (end > len) {
end = len;
}
if (start > end) {
final int temp = start;
start = end;
end = temp;
}
return str.substring(0, start) +
overlay +
str.substring(end);
}
/**
* Prepends the prefix to the start of the string if the string does not
* already start with any of the prefixes.
*
* @param str The string.
* @param prefix The prefix to prepend to the start of the string.
* @param ignoreCase Indicates whether the compare should ignore case.
* @param prefixes Additional prefixes that are valid (optional).
*
* @return A new String if prefix was prepended, the same string otherwise.
*/
private static String prependIfMissing(final String str, final CharSequence prefix, final boolean ignoreCase, final CharSequence... prefixes) {
if (str == null || isEmpty(prefix) || startsWith(str, prefix, ignoreCase)) {
return str;
}
if (ArrayUtils.isNotEmpty(prefixes)) {
for (final CharSequence p : prefixes) {
if (startsWith(str, p, ignoreCase)) {
return str;
}
}
}
return prefix.toString() + str;
}
/**
* Prepends the prefix to the start of the string if the string does not
* already start with any of the prefixes.
*
* <pre>
* StringUtils.prependIfMissing(null, null) = null
* StringUtils.prependIfMissing("abc", null) = "abc"
* StringUtils.prependIfMissing("", "xyz") = "xyz"
* StringUtils.prependIfMissing("abc", "xyz") = "xyzabc"
* StringUtils.prependIfMissing("xyzabc", "xyz") = "xyzabc"
* StringUtils.prependIfMissing("XYZabc", "xyz") = "xyzXYZabc"
* </pre>
* <p>With additional prefixes,</p>
* <pre>
* StringUtils.prependIfMissing(null, null, null) = null
* StringUtils.prependIfMissing("abc", null, null) = "abc"
* StringUtils.prependIfMissing("", "xyz", null) = "xyz"
* StringUtils.prependIfMissing("abc", "xyz", new CharSequence[]{null}) = "xyzabc"
* StringUtils.prependIfMissing("abc", "xyz", "") = "abc"
* StringUtils.prependIfMissing("abc", "xyz", "mno") = "xyzabc"
* StringUtils.prependIfMissing("xyzabc", "xyz", "mno") = "xyzabc"
* StringUtils.prependIfMissing("mnoabc", "xyz", "mno") = "mnoabc"
* StringUtils.prependIfMissing("XYZabc", "xyz", "mno") = "xyzXYZabc"
* StringUtils.prependIfMissing("MNOabc", "xyz", "mno") = "xyzMNOabc"
* </pre>
*
* @param str The string.
* @param prefix The prefix to prepend to the start of the string.
* @param prefixes Additional prefixes that are valid.
*
* @return A new String if prefix was prepended, the same string otherwise.
*
* @since 3.2
*/
public static String prependIfMissing(final String str, final CharSequence prefix, final CharSequence... prefixes) {
return prependIfMissing(str, prefix, false, prefixes);
}
/**
* Prepends the prefix to the start of the string if the string does not
* already start, case insensitive, with any of the prefixes.
*
* <pre>
* StringUtils.prependIfMissingIgnoreCase(null, null) = null
* StringUtils.prependIfMissingIgnoreCase("abc", null) = "abc"
* StringUtils.prependIfMissingIgnoreCase("", "xyz") = "xyz"
* StringUtils.prependIfMissingIgnoreCase("abc", "xyz") = "xyzabc"
* StringUtils.prependIfMissingIgnoreCase("xyzabc", "xyz") = "xyzabc"
* StringUtils.prependIfMissingIgnoreCase("XYZabc", "xyz") = "XYZabc"
* </pre>
* <p>With additional prefixes,</p>
* <pre>
* StringUtils.prependIfMissingIgnoreCase(null, null, null) = null
* StringUtils.prependIfMissingIgnoreCase("abc", null, null) = "abc"
* StringUtils.prependIfMissingIgnoreCase("", "xyz", null) = "xyz"
* StringUtils.prependIfMissingIgnoreCase("abc", "xyz", new CharSequence[]{null}) = "xyzabc"
* StringUtils.prependIfMissingIgnoreCase("abc", "xyz", "") = "abc"
* StringUtils.prependIfMissingIgnoreCase("abc", "xyz", "mno") = "xyzabc"
* StringUtils.prependIfMissingIgnoreCase("xyzabc", "xyz", "mno") = "xyzabc"
* StringUtils.prependIfMissingIgnoreCase("mnoabc", "xyz", "mno") = "mnoabc"
* StringUtils.prependIfMissingIgnoreCase("XYZabc", "xyz", "mno") = "XYZabc"
* StringUtils.prependIfMissingIgnoreCase("MNOabc", "xyz", "mno") = "MNOabc"
* </pre>
*
* @param str The string.
* @param prefix The prefix to prepend to the start of the string.
* @param prefixes Additional prefixes that are valid (optional).
*
* @return A new String if prefix was prepended, the same string otherwise.
*
* @since 3.2
*/
public static String prependIfMissingIgnoreCase(final String str, final CharSequence prefix, final CharSequence... prefixes) {
return prependIfMissing(str, prefix, true, prefixes);
}
/**
* <p>Removes all occurrences of a character from within the source string.</p>
*
* <p>A {@code null} source string will return {@code null}.
* An empty ("") source string will return the empty string.</p>
*
* <pre>
* StringUtils.remove(null, *) = null
* StringUtils.remove("", *) = ""
* StringUtils.remove("queued", 'u') = "qeed"
* StringUtils.remove("queued", 'z') = "queued"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the char to search for and remove, may be null
* @return the substring with the char removed if found,
* {@code null} if null String input
* @since 2.1
*/
public static String remove(final String str, final char remove) {
if (isEmpty(str) || str.indexOf(remove) == INDEX_NOT_FOUND) {
return str;
}
final char[] chars = str.toCharArray();
int pos = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] != remove) {
chars[pos++] = chars[i];
}
}
return new String(chars, 0, pos);
}
/**
* <p>Removes all occurrences of a substring from within the source string.</p>
*
* <p>A {@code null} source string will return {@code null}.
* An empty ("") source string will return the empty string.
* A {@code null} remove string will return the source string.
* An empty ("") remove string will return the source string.</p>
*
* <pre>
* StringUtils.remove(null, *) = null
* StringUtils.remove("", *) = ""
* StringUtils.remove(*, null) = *
* StringUtils.remove(*, "") = *
* StringUtils.remove("queued", "ue") = "qd"
* StringUtils.remove("queued", "zz") = "queued"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for and remove, may be null
* @return the substring with the string removed if found,
* {@code null} if null String input
* @since 2.1
*/
public static String remove(final String str, final String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
return replace(str, remove, EMPTY, -1);
}
/**
* <p>Removes each substring of the text String that matches the given regular expression.</p>
*
* This method is a {@code null} safe equivalent to:
* <ul>
* <li>{@code text.replaceAll(regex, StringUtils.EMPTY)}</li>
* <li>{@code Pattern.compile(regex).matcher(text).replaceAll(StringUtils.EMPTY)}</li>
* </ul>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <p>Unlike in the {@link #removePattern(String, String)} method, the {@link Pattern#DOTALL} option
* is NOT automatically added.
* To use the DOTALL option prepend {@code "(?s)"} to the regex.
* DOTALL is also known as single-line mode in Perl.</p>
*
* <pre>
* StringUtils.removeAll(null, *) = null
* StringUtils.removeAll("any", (String) null) = "any"
* StringUtils.removeAll("any", "") = "any"
* StringUtils.removeAll("any", ".*") = ""
* StringUtils.removeAll("any", ".+") = ""
* StringUtils.removeAll("abc", ".?") = ""
* StringUtils.removeAll("A<__>\n<__>B", "<.*>") = "A\nB"
* StringUtils.removeAll("A<__>\n<__>B", "(?s)<.*>") = "AB"
* StringUtils.removeAll("ABCabc123abc", "[a-z]") = "ABC123"
* </pre>
*
* @param text text to remove from, may be null
* @param regex the regular expression to which this string is to be matched
* @return the text with any removes processed,
* {@code null} if null String input
*
* @throws java.util.regex.PatternSyntaxException
* if the regular expression's syntax is invalid
*
* @see #replaceAll(String, String, String)
* @see #removePattern(String, String)
* @see String#replaceAll(String, String)
* @see java.util.regex.Pattern
* @see java.util.regex.Pattern#DOTALL
* @since 3.5
*
* @deprecated Moved to RegExUtils.
*/
@Deprecated
public static String removeAll(final String text, final String regex) {
return RegExUtils.removeAll(text, regex);
}
/**
* <p>Removes a substring only if it is at the end of a source string,
* otherwise returns the source string.</p>
*
* <p>A {@code null} source string will return {@code null}.
* An empty ("") source string will return the empty string.
* A {@code null} search string will return the source string.</p>
*
* <pre>
* StringUtils.removeEnd(null, *) = null
* StringUtils.removeEnd("", *) = ""
* StringUtils.removeEnd(*, null) = *
* StringUtils.removeEnd("www.domain.com", ".com.") = "www.domain.com"
* StringUtils.removeEnd("www.domain.com", ".com") = "www.domain"
* StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeEnd("abc", "") = "abc"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for and remove, may be null
* @return the substring with the string removed if found,
* {@code null} if null String input
* @since 2.1
*/
public static String removeEnd(final String str, final String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (str.endsWith(remove)) {
return str.substring(0, str.length() - remove.length());
}
return str;
}
/**
* <p>Case insensitive removal of a substring if it is at the end of a source string,
* otherwise returns the source string.</p>
*
* <p>A {@code null} source string will return {@code null}.
* An empty ("") source string will return the empty string.
* A {@code null} search string will return the source string.</p>
*
* <pre>
* StringUtils.removeEndIgnoreCase(null, *) = null
* StringUtils.removeEndIgnoreCase("", *) = ""
* StringUtils.removeEndIgnoreCase(*, null) = *
* StringUtils.removeEndIgnoreCase("www.domain.com", ".com.") = "www.domain.com"
* StringUtils.removeEndIgnoreCase("www.domain.com", ".com") = "www.domain"
* StringUtils.removeEndIgnoreCase("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeEndIgnoreCase("abc", "") = "abc"
* StringUtils.removeEndIgnoreCase("www.domain.com", ".COM") = "www.domain")
* StringUtils.removeEndIgnoreCase("www.domain.COM", ".com") = "www.domain")
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for (case insensitive) and remove, may be null
* @return the substring with the string removed if found,
* {@code null} if null String input
* @since 2.4
*/
public static String removeEndIgnoreCase(final String str, final String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (endsWithIgnoreCase(str, remove)) {
return str.substring(0, str.length() - remove.length());
}
return str;
}
/**
* <p>Removes the first substring of the text string that matches the given regular expression.</p>
*
* This method is a {@code null} safe equivalent to:
* <ul>
* <li>{@code text.replaceFirst(regex, StringUtils.EMPTY)}</li>
* <li>{@code Pattern.compile(regex).matcher(text).replaceFirst(StringUtils.EMPTY)}</li>
* </ul>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <p>The {@link Pattern#DOTALL} option is NOT automatically added.
* To use the DOTALL option prepend {@code "(?s)"} to the regex.
* DOTALL is also known as single-line mode in Perl.</p>
*
* <pre>
* StringUtils.removeFirst(null, *) = null
* StringUtils.removeFirst("any", (String) null) = "any"
* StringUtils.removeFirst("any", "") = "any"
* StringUtils.removeFirst("any", ".*") = ""
* StringUtils.removeFirst("any", ".+") = ""
* StringUtils.removeFirst("abc", ".?") = "bc"
* StringUtils.removeFirst("A<__>\n<__>B", "<.*>") = "A\n<__>B"
* StringUtils.removeFirst("A<__>\n<__>B", "(?s)<.*>") = "AB"
* StringUtils.removeFirst("ABCabc123", "[a-z]") = "ABCbc123"
* StringUtils.removeFirst("ABCabc123abc", "[a-z]+") = "ABC123abc"
* </pre>
*
* @param text text to remove from, may be null
* @param regex the regular expression to which this string is to be matched
* @return the text with the first replacement processed,
* {@code null} if null String input
*
* @throws java.util.regex.PatternSyntaxException
* if the regular expression's syntax is invalid
*
* @see #replaceFirst(String, String, String)
* @see String#replaceFirst(String, String)
* @see java.util.regex.Pattern
* @see java.util.regex.Pattern#DOTALL
* @since 3.5
*
* @deprecated Moved to RegExUtils.
*/
@Deprecated
public static String removeFirst(final String text, final String regex) {
return replaceFirst(text, regex, EMPTY);
}
/**
* <p>
* Case insensitive removal of all occurrences of a substring from within
* the source string.
* </p>
*
* <p>
* A {@code null} source string will return {@code null}. An empty ("")
* source string will return the empty string. A {@code null} remove string
* will return the source string. An empty ("") remove string will return
* the source string.
* </p>
*
* <pre>
* StringUtils.removeIgnoreCase(null, *) = null
* StringUtils.removeIgnoreCase("", *) = ""
* StringUtils.removeIgnoreCase(*, null) = *
* StringUtils.removeIgnoreCase(*, "") = *
* StringUtils.removeIgnoreCase("queued", "ue") = "qd"
* StringUtils.removeIgnoreCase("queued", "zz") = "queued"
* StringUtils.removeIgnoreCase("quEUed", "UE") = "qd"
* StringUtils.removeIgnoreCase("queued", "zZ") = "queued"
* </pre>
*
* @param str
* the source String to search, may be null
* @param remove
* the String to search for (case insensitive) and remove, may be
* null
* @return the substring with the string removed if found, {@code null} if
* null String input
* @since 3.5
*/
public static String removeIgnoreCase(final String str, final String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
return replaceIgnoreCase(str, remove, EMPTY, -1);
}
/**
* <p>Removes each substring of the source String that matches the given regular expression using the DOTALL option.
* </p>
*
* This call is a {@code null} safe equivalent to:
* <ul>
* <li>{@code source.replaceAll("(?s)" + regex, StringUtils.EMPTY)}</li>
* <li>{@code Pattern.compile(regex, Pattern.DOTALL).matcher(source).replaceAll(StringUtils.EMPTY)}</li>
* </ul>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.removePattern(null, *) = null
* StringUtils.removePattern("any", (String) null) = "any"
* StringUtils.removePattern("A<__>\n<__>B", "<.*>") = "AB"
* StringUtils.removePattern("ABCabc123", "[a-z]") = "ABC123"
* </pre>
*
* @param source
* the source string
* @param regex
* the regular expression to which this string is to be matched
* @return The resulting {@code String}
* @see #replacePattern(String, String, String)
* @see String#replaceAll(String, String)
* @see Pattern#DOTALL
* @since 3.2
* @since 3.5 Changed {@code null} reference passed to this method is a no-op.
*
* @deprecated Moved to RegExUtils.
*/
@Deprecated
public static String removePattern(final String source, final String regex) {
return RegExUtils.removePattern(source, regex);
}
// Remove
//-----------------------------------------------------------------------
/**
* <p>Removes a substring only if it is at the beginning of a source string,
* otherwise returns the source string.</p>
*
* <p>A {@code null} source string will return {@code null}.
* An empty ("") source string will return the empty string.
* A {@code null} search string will return the source string.</p>
*
* <pre>
* StringUtils.removeStart(null, *) = null
* StringUtils.removeStart("", *) = ""
* StringUtils.removeStart(*, null) = *
* StringUtils.removeStart("www.domain.com", "www.") = "domain.com"
* StringUtils.removeStart("domain.com", "www.") = "domain.com"
* StringUtils.removeStart("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeStart("abc", "") = "abc"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for and remove, may be null
* @return the substring with the string removed if found,
* {@code null} if null String input
* @since 2.1
*/
public static String removeStart(final String str, final String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (str.startsWith(remove)) {
return str.substring(remove.length());
}
return str;
}
/**
* <p>Case insensitive removal of a substring if it is at the beginning of a source string,
* otherwise returns the source string.</p>
*
* <p>A {@code null} source string will return {@code null}.
* An empty ("") source string will return the empty string.
* A {@code null} search string will return the source string.</p>
*
* <pre>
* StringUtils.removeStartIgnoreCase(null, *) = null
* StringUtils.removeStartIgnoreCase("", *) = ""
* StringUtils.removeStartIgnoreCase(*, null) = *
* StringUtils.removeStartIgnoreCase("www.domain.com", "www.") = "domain.com"
* StringUtils.removeStartIgnoreCase("www.domain.com", "WWW.") = "domain.com"
* StringUtils.removeStartIgnoreCase("domain.com", "www.") = "domain.com"
* StringUtils.removeStartIgnoreCase("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeStartIgnoreCase("abc", "") = "abc"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for (case insensitive) and remove, may be null
* @return the substring with the string removed if found,
* {@code null} if null String input
* @since 2.4
*/
public static String removeStartIgnoreCase(final String str, final String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (startsWithIgnoreCase(str, remove)) {
return str.substring(remove.length());
}
return str;
}
/**
* <p>Returns padding using the specified delimiter repeated
* to a given length.</p>
*
* <pre>
* StringUtils.repeat('e', 0) = ""
* StringUtils.repeat('e', 3) = "eee"
* StringUtils.repeat('e', -2) = ""
* </pre>
*
* <p>Note: this method does not support padding with
* <a href="http://www.unicode.org/glossary/#supplementary_character">Unicode Supplementary Characters</a>
* as they require a pair of {@code char}s to be represented.
* If you are needing to support full I18N of your applications
* consider using {@link #repeat(String, int)} instead.
* </p>
*
* @param ch character to repeat
* @param repeat number of times to repeat char, negative treated as zero
* @return String with repeated character
* @see #repeat(String, int)
*/
public static String repeat(final char ch, final int repeat) {
if (repeat <= 0) {
return EMPTY;
}
final char[] buf = new char[repeat];
for (int i = repeat - 1; i >= 0; i--) {
buf[i] = ch;
}
return new String(buf);
}
// Padding
//-----------------------------------------------------------------------
/**
* <p>Repeat a String {@code repeat} times to form a
* new String.</p>
*
* <pre>
* StringUtils.repeat(null, 2) = null
* StringUtils.repeat("", 0) = ""
* StringUtils.repeat("", 2) = ""
* StringUtils.repeat("a", 3) = "aaa"
* StringUtils.repeat("ab", 2) = "abab"
* StringUtils.repeat("a", -2) = ""
* </pre>
*
* @param str the String to repeat, may be null
* @param repeat number of times to repeat str, negative treated as zero
* @return a new String consisting of the original String repeated,
* {@code null} if null String input
*/
public static String repeat(final String str, final int repeat) {
// Performance tuned for 2.0 (JDK1.4)
if (str == null) {
return null;
}
if (repeat <= 0) {
return EMPTY;
}
final int inputLength = str.length();
if (repeat == 1 || inputLength == 0) {
return str;
}
if (inputLength == 1 && repeat <= PAD_LIMIT) {
return repeat(str.charAt(0), repeat);
}
final int outputLength = inputLength * repeat;
switch (inputLength) {
case 1 :
return repeat(str.charAt(0), repeat);
case 2 :
final char ch0 = str.charAt(0);
final char ch1 = str.charAt(1);
final char[] output2 = new char[outputLength];
for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
output2[i] = ch0;
output2[i + 1] = ch1;
}
return new String(output2);
default :
final StringBuilder buf = new StringBuilder(outputLength);
for (int i = 0; i < repeat; i++) {
buf.append(str);
}
return buf.toString();
}
}
// Conversion
//-----------------------------------------------------------------------
/**
* <p>Repeat a String {@code repeat} times to form a
* new String, with a String separator injected each time. </p>
*
* <pre>
* StringUtils.repeat(null, null, 2) = null
* StringUtils.repeat(null, "x", 2) = null
* StringUtils.repeat("", null, 0) = ""
* StringUtils.repeat("", "", 2) = ""
* StringUtils.repeat("", "x", 3) = "xxx"
* StringUtils.repeat("?", ", ", 3) = "?, ?, ?"
* </pre>
*
* @param str the String to repeat, may be null
* @param separator the String to inject, may be null
* @param repeat number of times to repeat str, negative treated as zero
* @return a new String consisting of the original String repeated,
* {@code null} if null String input
* @since 2.5
*/
public static String repeat(final String str, final String separator, final int repeat) {
if (str == null || separator == null) {
return repeat(str, repeat);
}
// given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it
final String result = repeat(str + separator, repeat);
return removeEnd(result, separator);
}
/**
* <p>Replaces all occurrences of a String within another String.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replace(null, *, *) = null
* StringUtils.replace("", *, *) = ""
* StringUtils.replace("any", null, *) = "any"
* StringUtils.replace("any", *, null) = "any"
* StringUtils.replace("any", "", *) = "any"
* StringUtils.replace("aba", "a", null) = "aba"
* StringUtils.replace("aba", "a", "") = "b"
* StringUtils.replace("aba", "a", "z") = "zbz"
* </pre>
*
* @see #replace(String text, String searchString, String replacement, int max)
* @param text text to search and replace in, may be null
* @param searchString the String to search for, may be null
* @param replacement the String to replace it with, may be null
* @return the text with any replacements processed,
* {@code null} if null String input
*/
public static String replace(final String text, final String searchString, final String replacement) {
return replace(text, searchString, replacement, -1);
}
/**
* <p>Replaces a String with another String inside a larger String,
* for the first {@code max} values of the search String.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replace(null, *, *, *) = null
* StringUtils.replace("", *, *, *) = ""
* StringUtils.replace("any", null, *, *) = "any"
* StringUtils.replace("any", *, null, *) = "any"
* StringUtils.replace("any", "", *, *) = "any"
* StringUtils.replace("any", *, *, 0) = "any"
* StringUtils.replace("abaa", "a", null, -1) = "abaa"
* StringUtils.replace("abaa", "a", "", -1) = "b"
* StringUtils.replace("abaa", "a", "z", 0) = "abaa"
* StringUtils.replace("abaa", "a", "z", 1) = "zbaa"
* StringUtils.replace("abaa", "a", "z", 2) = "zbza"
* StringUtils.replace("abaa", "a", "z", -1) = "zbzz"
* </pre>
*
* @param text text to search and replace in, may be null
* @param searchString the String to search for, may be null
* @param replacement the String to replace it with, may be null
* @param max maximum number of values to replace, or {@code -1} if no maximum
* @return the text with any replacements processed,
* {@code null} if null String input
*/
public static String replace(final String text, final String searchString, final String replacement, final int max) {
return replace(text, searchString, replacement, max, false);
}
/**
* <p>Replaces a String with another String inside a larger String,
* for the first {@code max} values of the search String,
* case sensitively/insensitively based on {@code ignoreCase} value.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replace(null, *, *, *, false) = null
* StringUtils.replace("", *, *, *, false) = ""
* StringUtils.replace("any", null, *, *, false) = "any"
* StringUtils.replace("any", *, null, *, false) = "any"
* StringUtils.replace("any", "", *, *, false) = "any"
* StringUtils.replace("any", *, *, 0, false) = "any"
* StringUtils.replace("abaa", "a", null, -1, false) = "abaa"
* StringUtils.replace("abaa", "a", "", -1, false) = "b"
* StringUtils.replace("abaa", "a", "z", 0, false) = "abaa"
* StringUtils.replace("abaa", "A", "z", 1, false) = "abaa"
* StringUtils.replace("abaa", "A", "z", 1, true) = "zbaa"
* StringUtils.replace("abAa", "a", "z", 2, true) = "zbza"
* StringUtils.replace("abAa", "a", "z", -1, true) = "zbzz"
* </pre>
*
* @param text text to search and replace in, may be null
* @param searchString the String to search for (case insensitive), may be null
* @param replacement the String to replace it with, may be null
* @param max maximum number of values to replace, or {@code -1} if no maximum
* @param ignoreCase if true replace is case insensitive, otherwise case sensitive
* @return the text with any replacements processed,
* {@code null} if null String input
*/
private static String replace(final String text, String searchString, final String replacement, int max, final boolean ignoreCase) {
if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) {
return text;
}
if (ignoreCase) {
searchString = searchString.toLowerCase();
}
int start = 0;
int end = ignoreCase ? indexOfIgnoreCase(text, searchString, start) : indexOf(text, searchString, start);
if (end == INDEX_NOT_FOUND) {
return text;
}
final int replLength = searchString.length();
int increase = replacement.length() - replLength;
increase = increase < 0 ? 0 : increase;
increase *= max < 0 ? 16 : max > 64 ? 64 : max;
final StringBuilder buf = new StringBuilder(text.length() + increase);
while (end != INDEX_NOT_FOUND) {
buf.append(text, start, end).append(replacement);
start = end + replLength;
if (--max == 0) {
break;
}
end = ignoreCase ? indexOfIgnoreCase(text, searchString, start) : indexOf(text, searchString, start);
}
buf.append(text, start, text.length());
return buf.toString();
}
/**
* <p>Replaces each substring of the text String that matches the given regular expression
* with the given replacement.</p>
*
* This method is a {@code null} safe equivalent to:
* <ul>
* <li>{@code text.replaceAll(regex, replacement)}</li>
* <li>{@code Pattern.compile(regex).matcher(text).replaceAll(replacement)}</li>
* </ul>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <p>Unlike in the {@link #replacePattern(String, String, String)} method, the {@link Pattern#DOTALL} option
* is NOT automatically added.
* To use the DOTALL option prepend {@code "(?s)"} to the regex.
* DOTALL is also known as single-line mode in Perl.</p>
*
* <pre>
* StringUtils.replaceAll(null, *, *) = null
* StringUtils.replaceAll("any", (String) null, *) = "any"
* StringUtils.replaceAll("any", *, null) = "any"
* StringUtils.replaceAll("", "", "zzz") = "zzz"
* StringUtils.replaceAll("", ".*", "zzz") = "zzz"
* StringUtils.replaceAll("", ".+", "zzz") = ""
* StringUtils.replaceAll("abc", "", "ZZ") = "ZZaZZbZZcZZ"
* StringUtils.replaceAll("<__>\n<__>", "<.*>", "z") = "z\nz"
* StringUtils.replaceAll("<__>\n<__>", "(?s)<.*>", "z") = "z"
* StringUtils.replaceAll("ABCabc123", "[a-z]", "_") = "ABC___123"
* StringUtils.replaceAll("ABCabc123", "[^A-Z0-9]+", "_") = "ABC_123"
* StringUtils.replaceAll("ABCabc123", "[^A-Z0-9]+", "") = "ABC123"
* StringUtils.replaceAll("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2") = "Lorem_ipsum_dolor_sit"
* </pre>
*
* @param text text to search and replace in, may be null
* @param regex the regular expression to which this string is to be matched
* @param replacement the string to be substituted for each match
* @return the text with any replacements processed,
* {@code null} if null String input
*
* @throws java.util.regex.PatternSyntaxException
* if the regular expression's syntax is invalid
*
* @see #replacePattern(String, String, String)
* @see String#replaceAll(String, String)
* @see java.util.regex.Pattern
* @see java.util.regex.Pattern#DOTALL
* @since 3.5
*
* @deprecated Moved to RegExUtils.
*/
@Deprecated
public static String replaceAll(final String text, final String regex, final String replacement) {
return RegExUtils.replaceAll(text, regex, replacement);
}
// Replace, character based
//-----------------------------------------------------------------------
/**
* <p>Replaces all occurrences of a character in a String with another.
* This is a null-safe version of {@link String#replace(char, char)}.</p>
*
* <p>A {@code null} string input returns {@code null}.
* An empty ("") string input returns an empty string.</p>
*
* <pre>
* StringUtils.replaceChars(null, *, *) = null
* StringUtils.replaceChars("", *, *) = ""
* StringUtils.replaceChars("abcba", 'b', 'y') = "aycya"
* StringUtils.replaceChars("abcba", 'z', 'y') = "abcba"
* </pre>
*
* @param str String to replace characters in, may be null
* @param searchChar the character to search for, may be null
* @param replaceChar the character to replace, may be null
* @return modified String, {@code null} if null string input
* @since 2.0
*/
public static String replaceChars(final String str, final char searchChar, final char replaceChar) {
if (str == null) {
return null;
}
return str.replace(searchChar, replaceChar);
}
/**
* <p>Replaces multiple characters in a String in one go.
* This method can also be used to delete characters.</p>
*
* <p>For example:<br>
* {@code replaceChars("hello", "ho", "jy") = jelly}.</p>
*
* <p>A {@code null} string input returns {@code null}.
* An empty ("") string input returns an empty string.
* A null or empty set of search characters returns the input string.</p>
*
* <p>The length of the search characters should normally equal the length
* of the replace characters.
* If the search characters is longer, then the extra search characters
* are deleted.
* If the search characters is shorter, then the extra replace characters
* are ignored.</p>
*
* <pre>
* StringUtils.replaceChars(null, *, *) = null
* StringUtils.replaceChars("", *, *) = ""
* StringUtils.replaceChars("abc", null, *) = "abc"
* StringUtils.replaceChars("abc", "", *) = "abc"
* StringUtils.replaceChars("abc", "b", null) = "ac"
* StringUtils.replaceChars("abc", "b", "") = "ac"
* StringUtils.replaceChars("abcba", "bc", "yz") = "ayzya"
* StringUtils.replaceChars("abcba", "bc", "y") = "ayya"
* StringUtils.replaceChars("abcba", "bc", "yzx") = "ayzya"
* </pre>
*
* @param str String to replace characters in, may be null
* @param searchChars a set of characters to search for, may be null
* @param replaceChars a set of characters to replace, may be null
* @return modified String, {@code null} if null string input
* @since 2.0
*/
public static String replaceChars(final String str, final String searchChars, String replaceChars) {
if (isEmpty(str) || isEmpty(searchChars)) {
return str;
}
if (replaceChars == null) {
replaceChars = EMPTY;
}
boolean modified = false;
final int replaceCharsLength = replaceChars.length();
final int strLength = str.length();
final StringBuilder buf = new StringBuilder(strLength);
for (int i = 0; i < strLength; i++) {
final char ch = str.charAt(i);
final int index = searchChars.indexOf(ch);
if (index >= 0) {
modified = true;
if (index < replaceCharsLength) {
buf.append(replaceChars.charAt(index));
}
} else {
buf.append(ch);
}
}
if (modified) {
return buf.toString();
}
return str;
}
/**
* <p>
* Replaces all occurrences of Strings within another String.
* </p>
*
* <p>
* A {@code null} reference passed to this method is a no-op, or if
* any "search string" or "string to replace" is null, that replace will be
* ignored. This will not repeat. For repeating replaces, call the
* overloaded method.
* </p>
*
* <pre>
* StringUtils.replaceEach(null, *, *) = null
* StringUtils.replaceEach("", *, *) = ""
* StringUtils.replaceEach("aba", null, null) = "aba"
* StringUtils.replaceEach("aba", new String[0], null) = "aba"
* StringUtils.replaceEach("aba", null, new String[0]) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, null) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}) = "b"
* StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}) = "aba"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte"
* (example of how it does not repeat)
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "dcte"
* </pre>
*
* @param text
* text to search and replace in, no-op if null
* @param searchList
* the Strings to search for, no-op if null
* @param replacementList
* the Strings to replace them with, no-op if null
* @return the text with any replacements processed, {@code null} if
* null String input
* @throws IllegalArgumentException
* if the lengths of the arrays are not the same (null is ok,
* and/or size 0)
* @since 2.4
*/
public static String replaceEach(final String text, final String[] searchList, final String[] replacementList) {
return replaceEach(text, searchList, replacementList, false, 0);
}
/**
* <p>
* Replace all occurrences of Strings within another String.
* This is a private recursive helper method for {@link #replaceEachRepeatedly(String, String[], String[])} and
* {@link #replaceEach(String, String[], String[])}
* </p>
*
* <p>
* A {@code null} reference passed to this method is a no-op, or if
* any "search string" or "string to replace" is null, that replace will be
* ignored.
* </p>
*
* <pre>
* StringUtils.replaceEach(null, *, *, *, *) = null
* StringUtils.replaceEach("", *, *, *, *) = ""
* StringUtils.replaceEach("aba", null, null, *, *) = "aba"
* StringUtils.replaceEach("aba", new String[0], null, *, *) = "aba"
* StringUtils.replaceEach("aba", null, new String[0], *, *) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, null, *, *) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}, *, >=0) = "b"
* StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}, *, >=0) = "aba"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}, *, >=0) = "wcte"
* (example of how it repeats)
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, false, >=0) = "dcte"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, true, >=2) = "tcte"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, *, *) = IllegalStateException
* </pre>
*
* @param text
* text to search and replace in, no-op if null
* @param searchList
* the Strings to search for, no-op if null
* @param replacementList
* the Strings to replace them with, no-op if null
* @param repeat if true, then replace repeatedly
* until there are no more possible replacements or timeToLive < 0
* @param timeToLive
* if less than 0 then there is a circular reference and endless
* loop
* @return the text with any replacements processed, {@code null} if
* null String input
* @throws IllegalStateException
* if the search is repeating and there is an endless loop due
* to outputs of one being inputs to another
* @throws IllegalArgumentException
* if the lengths of the arrays are not the same (null is ok,
* and/or size 0)
* @since 2.4
*/
private static String replaceEach(
final String text, final String[] searchList, final String[] replacementList, final boolean repeat, final int timeToLive) {
// mchyzer Performance note: This creates very few new objects (one major goal)
// let me know if there are performance requests, we can create a harness to measure
if (isEmpty(text) || ArrayUtils.isEmpty(searchList) || ArrayUtils.isEmpty(replacementList)) {
return text;
}
// if recursing, this shouldn't be less than 0
if (timeToLive < 0) {
throw new IllegalStateException("Aborting to protect against StackOverflowError - " +
"output of one loop is the input of another");
}
final int searchLength = searchList.length;
final int replacementLength = replacementList.length;
// make sure lengths are ok, these need to be equal
if (searchLength != replacementLength) {
throw new IllegalArgumentException("Search and Replace array lengths don't match: "
+ searchLength
+ " vs "
+ replacementLength);
}
// keep track of which still have matches
final boolean[] noMoreMatchesForReplIndex = new boolean[searchLength];
// index on index that the match was found
int textIndex = -1;
int replaceIndex = -1;
int tempIndex = -1;
// index of replace array that will replace the search string found
// NOTE: logic duplicated below START
for (int i = 0; i < searchLength; i++) {
if (noMoreMatchesForReplIndex[i] || searchList[i] == null ||
searchList[i].isEmpty() || replacementList[i] == null) {
continue;
}
tempIndex = text.indexOf(searchList[i]);
// see if we need to keep searching for this
if (tempIndex == -1) {
noMoreMatchesForReplIndex[i] = true;
} else {
if (textIndex == -1 || tempIndex < textIndex) {
textIndex = tempIndex;
replaceIndex = i;
}
}
}
// NOTE: logic mostly below END
// no search strings found, we are done
if (textIndex == -1) {
return text;
}
int start = 0;
// get a good guess on the size of the result buffer so it doesn't have to double if it goes over a bit
int increase = 0;
// count the replacement text elements that are larger than their corresponding text being replaced
for (int i = 0; i < searchList.length; i++) {
if (searchList[i] == null || replacementList[i] == null) {
continue;
}
final int greater = replacementList[i].length() - searchList[i].length();
if (greater > 0) {
increase += 3 * greater; // assume 3 matches
}
}
// have upper-bound at 20% increase, then let Java take over
increase = Math.min(increase, text.length() / 5);
final StringBuilder buf = new StringBuilder(text.length() + increase);
while (textIndex != -1) {
for (int i = start; i < textIndex; i++) {
buf.append(text.charAt(i));
}
buf.append(replacementList[replaceIndex]);
start = textIndex + searchList[replaceIndex].length();
textIndex = -1;
replaceIndex = -1;
tempIndex = -1;
// find the next earliest match
// NOTE: logic mostly duplicated above START
for (int i = 0; i < searchLength; i++) {
if (noMoreMatchesForReplIndex[i] || searchList[i] == null ||
searchList[i].isEmpty() || replacementList[i] == null) {
continue;
}
tempIndex = text.indexOf(searchList[i], start);
// see if we need to keep searching for this
if (tempIndex == -1) {
noMoreMatchesForReplIndex[i] = true;
} else {
if (textIndex == -1 || tempIndex < textIndex) {
textIndex = tempIndex;
replaceIndex = i;
}
}
}
// NOTE: logic duplicated above END
}
final int textLength = text.length();
for (int i = start; i < textLength; i++) {
buf.append(text.charAt(i));
}
final String result = buf.toString();
if (!repeat) {
return result;
}
return replaceEach(result, searchList, replacementList, repeat, timeToLive - 1);
}
/**
* <p>
* Replaces all occurrences of Strings within another String.
* </p>
*
* <p>
* A {@code null} reference passed to this method is a no-op, or if
* any "search string" or "string to replace" is null, that replace will be
* ignored.
* </p>
*
* <pre>
* StringUtils.replaceEachRepeatedly(null, *, *) = null
* StringUtils.replaceEachRepeatedly("", *, *) = ""
* StringUtils.replaceEachRepeatedly("aba", null, null) = "aba"
* StringUtils.replaceEachRepeatedly("aba", new String[0], null) = "aba"
* StringUtils.replaceEachRepeatedly("aba", null, new String[0]) = "aba"
* StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, null) = "aba"
* StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, new String[]{""}) = "b"
* StringUtils.replaceEachRepeatedly("aba", new String[]{null}, new String[]{"a"}) = "aba"
* StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte"
* (example of how it repeats)
* StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "tcte"
* StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}) = IllegalStateException
* </pre>
*
* @param text
* text to search and replace in, no-op if null
* @param searchList
* the Strings to search for, no-op if null
* @param replacementList
* the Strings to replace them with, no-op if null
* @return the text with any replacements processed, {@code null} if
* null String input
* @throws IllegalStateException
* if the search is repeating and there is an endless loop due
* to outputs of one being inputs to another
* @throws IllegalArgumentException
* if the lengths of the arrays are not the same (null is ok,
* and/or size 0)
* @since 2.4
*/
public static String replaceEachRepeatedly(final String text, final String[] searchList, final String[] replacementList) {
// timeToLive should be 0 if not used or nothing to replace, else it's
// the length of the replace array
final int timeToLive = searchList == null ? 0 : searchList.length;
return replaceEach(text, searchList, replacementList, true, timeToLive);
}
/**
* <p>Replaces the first substring of the text string that matches the given regular expression
* with the given replacement.</p>
*
* This method is a {@code null} safe equivalent to:
* <ul>
* <li>{@code text.replaceFirst(regex, replacement)}</li>
* <li>{@code Pattern.compile(regex).matcher(text).replaceFirst(replacement)}</li>
* </ul>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <p>The {@link Pattern#DOTALL} option is NOT automatically added.
* To use the DOTALL option prepend {@code "(?s)"} to the regex.
* DOTALL is also known as single-line mode in Perl.</p>
*
* <pre>
* StringUtils.replaceFirst(null, *, *) = null
* StringUtils.replaceFirst("any", (String) null, *) = "any"
* StringUtils.replaceFirst("any", *, null) = "any"
* StringUtils.replaceFirst("", "", "zzz") = "zzz"
* StringUtils.replaceFirst("", ".*", "zzz") = "zzz"
* StringUtils.replaceFirst("", ".+", "zzz") = ""
* StringUtils.replaceFirst("abc", "", "ZZ") = "ZZabc"
* StringUtils.replaceFirst("<__>\n<__>", "<.*>", "z") = "z\n<__>"
* StringUtils.replaceFirst("<__>\n<__>", "(?s)<.*>", "z") = "z"
* StringUtils.replaceFirst("ABCabc123", "[a-z]", "_") = "ABC_bc123"
* StringUtils.replaceFirst("ABCabc123abc", "[^A-Z0-9]+", "_") = "ABC_123abc"
* StringUtils.replaceFirst("ABCabc123abc", "[^A-Z0-9]+", "") = "ABC123abc"
* StringUtils.replaceFirst("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2") = "Lorem_ipsum dolor sit"
* </pre>
*
* @param text text to search and replace in, may be null
* @param regex the regular expression to which this string is to be matched
* @param replacement the string to be substituted for the first match
* @return the text with the first replacement processed,
* {@code null} if null String input
*
* @throws java.util.regex.PatternSyntaxException
* if the regular expression's syntax is invalid
*
* @see String#replaceFirst(String, String)
* @see java.util.regex.Pattern
* @see java.util.regex.Pattern#DOTALL
* @since 3.5
*
* @deprecated Moved to RegExUtils.
*/
@Deprecated
public static String replaceFirst(final String text, final String regex, final String replacement) {
return RegExUtils.replaceFirst(text, regex, replacement);
}
/**
* <p>Case insensitively replaces all occurrences of a String within another String.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replaceIgnoreCase(null, *, *) = null
* StringUtils.replaceIgnoreCase("", *, *) = ""
* StringUtils.replaceIgnoreCase("any", null, *) = "any"
* StringUtils.replaceIgnoreCase("any", *, null) = "any"
* StringUtils.replaceIgnoreCase("any", "", *) = "any"
* StringUtils.replaceIgnoreCase("aba", "a", null) = "aba"
* StringUtils.replaceIgnoreCase("abA", "A", "") = "b"
* StringUtils.replaceIgnoreCase("aba", "A", "z") = "zbz"
* </pre>
*
* @see #replaceIgnoreCase(String text, String searchString, String replacement, int max)
* @param text text to search and replace in, may be null
* @param searchString the String to search for (case insensitive), may be null
* @param replacement the String to replace it with, may be null
* @return the text with any replacements processed,
* {@code null} if null String input
* @since 3.5
*/
public static String replaceIgnoreCase(final String text, final String searchString, final String replacement) {
return replaceIgnoreCase(text, searchString, replacement, -1);
}
/**
* <p>Case insensitively replaces a String with another String inside a larger String,
* for the first {@code max} values of the search String.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replaceIgnoreCase(null, *, *, *) = null
* StringUtils.replaceIgnoreCase("", *, *, *) = ""
* StringUtils.replaceIgnoreCase("any", null, *, *) = "any"
* StringUtils.replaceIgnoreCase("any", *, null, *) = "any"
* StringUtils.replaceIgnoreCase("any", "", *, *) = "any"
* StringUtils.replaceIgnoreCase("any", *, *, 0) = "any"
* StringUtils.replaceIgnoreCase("abaa", "a", null, -1) = "abaa"
* StringUtils.replaceIgnoreCase("abaa", "a", "", -1) = "b"
* StringUtils.replaceIgnoreCase("abaa", "a", "z", 0) = "abaa"
* StringUtils.replaceIgnoreCase("abaa", "A", "z", 1) = "zbaa"
* StringUtils.replaceIgnoreCase("abAa", "a", "z", 2) = "zbza"
* StringUtils.replaceIgnoreCase("abAa", "a", "z", -1) = "zbzz"
* </pre>
*
* @param text text to search and replace in, may be null
* @param searchString the String to search for (case insensitive), may be null
* @param replacement the String to replace it with, may be null
* @param max maximum number of values to replace, or {@code -1} if no maximum
* @return the text with any replacements processed,
* {@code null} if null String input
* @since 3.5
*/
public static String replaceIgnoreCase(final String text, final String searchString, final String replacement, final int max) {
return replace(text, searchString, replacement, max, true);
}
// Replacing
//-----------------------------------------------------------------------
/**
* <p>Replaces a String with another String inside a larger String, once.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replaceOnce(null, *, *) = null
* StringUtils.replaceOnce("", *, *) = ""
* StringUtils.replaceOnce("any", null, *) = "any"
* StringUtils.replaceOnce("any", *, null) = "any"
* StringUtils.replaceOnce("any", "", *) = "any"
* StringUtils.replaceOnce("aba", "a", null) = "aba"
* StringUtils.replaceOnce("aba", "a", "") = "ba"
* StringUtils.replaceOnce("aba", "a", "z") = "zba"
* </pre>
*
* @see #replace(String text, String searchString, String replacement, int max)
* @param text text to search and replace in, may be null
* @param searchString the String to search for, may be null
* @param replacement the String to replace with, may be null
* @return the text with any replacements processed,
* {@code null} if null String input
*/
public static String replaceOnce(final String text, final String searchString, final String replacement) {
return replace(text, searchString, replacement, 1);
}
/**
* <p>Case insensitively replaces a String with another String inside a larger String, once.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replaceOnceIgnoreCase(null, *, *) = null
* StringUtils.replaceOnceIgnoreCase("", *, *) = ""
* StringUtils.replaceOnceIgnoreCase("any", null, *) = "any"
* StringUtils.replaceOnceIgnoreCase("any", *, null) = "any"
* StringUtils.replaceOnceIgnoreCase("any", "", *) = "any"
* StringUtils.replaceOnceIgnoreCase("aba", "a", null) = "aba"
* StringUtils.replaceOnceIgnoreCase("aba", "a", "") = "ba"
* StringUtils.replaceOnceIgnoreCase("aba", "a", "z") = "zba"
* StringUtils.replaceOnceIgnoreCase("FoOFoofoo", "foo", "") = "Foofoo"
* </pre>
*
* @see #replaceIgnoreCase(String text, String searchString, String replacement, int max)
* @param text text to search and replace in, may be null
* @param searchString the String to search for (case insensitive), may be null
* @param replacement the String to replace with, may be null
* @return the text with any replacements processed,
* {@code null} if null String input
* @since 3.5
*/
public static String replaceOnceIgnoreCase(final String text, final String searchString, final String replacement) {
return replaceIgnoreCase(text, searchString, replacement, 1);
}
/**
* <p>Replaces each substring of the source String that matches the given regular expression with the given
* replacement using the {@link Pattern#DOTALL} option. DOTALL is also known as single-line mode in Perl.</p>
*
* This call is a {@code null} safe equivalent to:
* <ul>
* <li>{@code source.replaceAll("(?s)" + regex, replacement)}</li>
* <li>{@code Pattern.compile(regex, Pattern.DOTALL).matcher(source).replaceAll(replacement)}</li>
* </ul>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replacePattern(null, *, *) = null
* StringUtils.replacePattern("any", (String) null, *) = "any"
* StringUtils.replacePattern("any", *, null) = "any"
* StringUtils.replacePattern("", "", "zzz") = "zzz"
* StringUtils.replacePattern("", ".*", "zzz") = "zzz"
* StringUtils.replacePattern("", ".+", "zzz") = ""
* StringUtils.replacePattern("<__>\n<__>", "<.*>", "z") = "z"
* StringUtils.replacePattern("ABCabc123", "[a-z]", "_") = "ABC___123"
* StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "_") = "ABC_123"
* StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "") = "ABC123"
* StringUtils.replacePattern("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2") = "Lorem_ipsum_dolor_sit"
* </pre>
*
* @param source
* the source string
* @param regex
* the regular expression to which this string is to be matched
* @param replacement
* the string to be substituted for each match
* @return The resulting {@code String}
* @see #replaceAll(String, String, String)
* @see String#replaceAll(String, String)
* @see Pattern#DOTALL
* @since 3.2
* @since 3.5 Changed {@code null} reference passed to this method is a no-op.
*
* @deprecated Moved to RegExUtils.
*/
@Deprecated
public static String replacePattern(final String source, final String regex, final String replacement) {
return RegExUtils.replacePattern(source, regex, replacement);
}
// Reversing
//-----------------------------------------------------------------------
/**
* <p>Reverses a String as per {@link StringBuilder#reverse()}.</p>
*
* <p>A {@code null} String returns {@code null}.</p>
*
* <pre>
* StringUtils.reverse(null) = null
* StringUtils.reverse("") = ""
* StringUtils.reverse("bat") = "tab"
* </pre>
*
* @param str the String to reverse, may be null
* @return the reversed String, {@code null} if null String input
*/
public static String reverse(final String str) {
if (str == null) {
return null;
}
return new StringBuilder(str).reverse().toString();
}
/**
* <p>Reverses a String that is delimited by a specific character.</p>
*
* <p>The Strings between the delimiters are not reversed.
* Thus java.lang.String becomes String.lang.java (if the delimiter
* is {@code '.'}).</p>
*
* <pre>
* StringUtils.reverseDelimited(null, *) = null
* StringUtils.reverseDelimited("", *) = ""
* StringUtils.reverseDelimited("a.b.c", 'x') = "a.b.c"
* StringUtils.reverseDelimited("a.b.c", ".") = "c.b.a"
* </pre>
*
* @param str the String to reverse, may be null
* @param separatorChar the separator character to use
* @return the reversed String, {@code null} if null String input
* @since 2.0
*/
public static String reverseDelimited(final String str, final char separatorChar) {
if (str == null) {
return null;
}
// could implement manually, but simple way is to reuse other,
// probably slower, methods.
final String[] strs = split(str, separatorChar);
ArrayUtils.reverse(strs);
return join(strs, separatorChar);
}
/**
* <p>Gets the rightmost {@code len} characters of a String.</p>
*
* <p>If {@code len} characters are not available, or the String
* is {@code null}, the String will be returned without an
* an exception. An empty String is returned if len is negative.</p>
*
* <pre>
* StringUtils.right(null, *) = null
* StringUtils.right(*, -ve) = ""
* StringUtils.right("", *) = ""
* StringUtils.right("abc", 0) = ""
* StringUtils.right("abc", 2) = "bc"
* StringUtils.right("abc", 4) = "abc"
* </pre>
*
* @param str the String to get the rightmost characters from, may be null
* @param len the length of the required String
* @return the rightmost characters, {@code null} if null String input
*/
public static String right(final String str, final int len) {
if (str == null) {
return null;
}
if (len < 0) {
return EMPTY;
}
if (str.length() <= len) {
return str;
}
return str.substring(str.length() - len);
}
/**
* <p>Right pad a String with spaces (' ').</p>
*
* <p>The String is padded to the size of {@code size}.</p>
*
* <pre>
* StringUtils.rightPad(null, *) = null
* StringUtils.rightPad("", 3) = " "
* StringUtils.rightPad("bat", 3) = "bat"
* StringUtils.rightPad("bat", 5) = "bat "
* StringUtils.rightPad("bat", 1) = "bat"
* StringUtils.rightPad("bat", -1) = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @return right padded String or original String if no padding is necessary,
* {@code null} if null String input
*/
public static String rightPad(final String str, final int size) {
return rightPad(str, size, ' ');
}
/**
* <p>Right pad a String with a specified character.</p>
*
* <p>The String is padded to the size of {@code size}.</p>
*
* <pre>
* StringUtils.rightPad(null, *, *) = null
* StringUtils.rightPad("", 3, 'z') = "zzz"
* StringUtils.rightPad("bat", 3, 'z') = "bat"
* StringUtils.rightPad("bat", 5, 'z') = "batzz"
* StringUtils.rightPad("bat", 1, 'z') = "bat"
* StringUtils.rightPad("bat", -1, 'z') = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padChar the character to pad with
* @return right padded String or original String if no padding is necessary,
* {@code null} if null String input
* @since 2.0
*/
public static String rightPad(final String str, final int size, final char padChar) {
if (str == null) {
return null;
}
final int pads = size - str.length();
if (pads <= 0) {
return str; // returns original String when possible
}
if (pads > PAD_LIMIT) {
return rightPad(str, size, String.valueOf(padChar));
}
return str.concat(repeat(padChar, pads));
}
/**
* <p>Right pad a String with a specified String.</p>
*
* <p>The String is padded to the size of {@code size}.</p>
*
* <pre>
* StringUtils.rightPad(null, *, *) = null
* StringUtils.rightPad("", 3, "z") = "zzz"
* StringUtils.rightPad("bat", 3, "yz") = "bat"
* StringUtils.rightPad("bat", 5, "yz") = "batyz"
* StringUtils.rightPad("bat", 8, "yz") = "batyzyzy"
* StringUtils.rightPad("bat", 1, "yz") = "bat"
* StringUtils.rightPad("bat", -1, "yz") = "bat"
* StringUtils.rightPad("bat", 5, null) = "bat "
* StringUtils.rightPad("bat", 5, "") = "bat "
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padStr the String to pad with, null or empty treated as single space
* @return right padded String or original String if no padding is necessary,
* {@code null} if null String input
*/
public static String rightPad(final String str, final int size, String padStr) {
if (str == null) {
return null;
}
if (isEmpty(padStr)) {
padStr = SPACE;
}
final int padLen = padStr.length();
final int strLen = str.length();
final int pads = size - strLen;
if (pads <= 0) {
return str; // returns original String when possible
}
if (padLen == 1 && pads <= PAD_LIMIT) {
return rightPad(str, size, padStr.charAt(0));
}
if (pads == padLen) {
return str.concat(padStr);
} else if (pads < padLen) {
return str.concat(padStr.substring(0, pads));
} else {
final char[] padding = new char[pads];
final char[] padChars = padStr.toCharArray();
for (int i = 0; i < pads; i++) {
padding[i] = padChars[i % padLen];
}
return str.concat(new String(padding));
}
}
// Rotating (circular shift)
//-----------------------------------------------------------------------
/**
* <p>Rotate (circular shift) a String of {@code shift} characters.</p>
* <ul>
* <li>If {@code shift > 0}, right circular shift (ex : ABCDEF => FABCDE)</li>
* <li>If {@code shift < 0}, left circular shift (ex : ABCDEF => BCDEFA)</li>
* </ul>
*
* <pre>
* StringUtils.rotate(null, *) = null
* StringUtils.rotate("", *) = ""
* StringUtils.rotate("abcdefg", 0) = "abcdefg"
* StringUtils.rotate("abcdefg", 2) = "fgabcde"
* StringUtils.rotate("abcdefg", -2) = "cdefgab"
* StringUtils.rotate("abcdefg", 7) = "abcdefg"
* StringUtils.rotate("abcdefg", -7) = "abcdefg"
* StringUtils.rotate("abcdefg", 9) = "fgabcde"
* StringUtils.rotate("abcdefg", -9) = "cdefgab"
* </pre>
*
* @param str the String to rotate, may be null
* @param shift number of time to shift (positive : right shift, negative : left shift)
* @return the rotated String,
* or the original String if {@code shift == 0},
* or {@code null} if null String input
* @since 3.5
*/
public static String rotate(final String str, final int shift) {
if (str == null) {
return null;
}
final int strLen = str.length();
if (shift == 0 || strLen == 0 || shift % strLen == 0) {
return str;
}
final StringBuilder builder = new StringBuilder(strLen);
final int offset = - (shift % strLen);
builder.append(substring(str, offset));
builder.append(substring(str, 0, offset));
return builder.toString();
}
// Splitting
//-----------------------------------------------------------------------
/**
* <p>Splits the provided text into an array, using whitespace as the
* separator.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.split(null) = null
* StringUtils.split("") = []
* StringUtils.split("abc def") = ["abc", "def"]
* StringUtils.split("abc def") = ["abc", "def"]
* StringUtils.split(" abc ") = ["abc"]
* </pre>
*
* @param str the String to parse, may be null
* @return an array of parsed Strings, {@code null} if null String input
*/
public static String[] split(final String str) {
return split(str, null, -1);
}
/**
* <p>Splits the provided text into an array, separator specified.
* This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.split(null, *) = null
* StringUtils.split("", *) = []
* StringUtils.split("a.b.c", '.') = ["a", "b", "c"]
* StringUtils.split("a..b.c", '.') = ["a", "b", "c"]
* StringUtils.split("a:b:c", '.') = ["a:b:c"]
* StringUtils.split("a b c", ' ') = ["a", "b", "c"]
* </pre>
*
* @param str the String to parse, may be null
* @param separatorChar the character used as the delimiter
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.0
*/
public static String[] split(final String str, final char separatorChar) {
return splitWorker(str, separatorChar, false);
}
/**
* <p>Splits the provided text into an array, separators specified.
* This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separatorChars splits on whitespace.</p>
*
* <pre>
* StringUtils.split(null, *) = null
* StringUtils.split("", *) = []
* StringUtils.split("abc def", null) = ["abc", "def"]
* StringUtils.split("abc def", " ") = ["abc", "def"]
* StringUtils.split("abc def", " ") = ["abc", "def"]
* StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separatorChars the characters used as the delimiters,
* {@code null} splits on whitespace
* @return an array of parsed Strings, {@code null} if null String input
*/
public static String[] split(final String str, final String separatorChars) {
return splitWorker(str, separatorChars, -1, false);
}
/**
* <p>Splits the provided text into an array with a maximum length,
* separators specified.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separatorChars splits on whitespace.</p>
*
* <p>If more than {@code max} delimited substrings are found, the last
* returned string includes all characters after the first {@code max - 1}
* returned strings (including separator characters).</p>
*
* <pre>
* StringUtils.split(null, *, *) = null
* StringUtils.split("", *, *) = []
* StringUtils.split("ab cd ef", null, 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab cd ef", null, 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separatorChars the characters used as the delimiters,
* {@code null} splits on whitespace
* @param max the maximum number of elements to include in the
* array. A zero or negative value implies no limit
* @return an array of parsed Strings, {@code null} if null String input
*/
public static String[] split(final String str, final String separatorChars, final int max) {
return splitWorker(str, separatorChars, max, false);
}
/**
* <p>Splits a String by Character type as returned by
* {@code java.lang.Character.getType(char)}. Groups of contiguous
* characters of the same type are returned as complete tokens.
* <pre>
* StringUtils.splitByCharacterType(null) = null
* StringUtils.splitByCharacterType("") = []
* StringUtils.splitByCharacterType("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterType("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterType("ab:cd:ef") = ["ab", ":", "cd", ":", "ef"]
* StringUtils.splitByCharacterType("number5") = ["number", "5"]
* StringUtils.splitByCharacterType("fooBar") = ["foo", "B", "ar"]
* StringUtils.splitByCharacterType("foo200Bar") = ["foo", "200", "B", "ar"]
* StringUtils.splitByCharacterType("ASFRules") = ["ASFR", "ules"]
* </pre>
* @param str the String to split, may be {@code null}
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.4
*/
public static String[] splitByCharacterType(final String str) {
return splitByCharacterType(str, false);
}
/**
* <p>Splits a String by Character type as returned by
* {@code java.lang.Character.getType(char)}. Groups of contiguous
* characters of the same type are returned as complete tokens, with the
* following exception: if {@code camelCase} is {@code true},
* the character of type {@code Character.UPPERCASE_LETTER}, if any,
* immediately preceding a token of type {@code Character.LOWERCASE_LETTER}
* will belong to the following token rather than to the preceding, if any,
* {@code Character.UPPERCASE_LETTER} token.
* @param str the String to split, may be {@code null}
* @param camelCase whether to use so-called "camel-case" for letter types
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.4
*/
private static String[] splitByCharacterType(final String str, final boolean camelCase) {
if (str == null) {
return null;
}
if (str.isEmpty()) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
final char[] c = str.toCharArray();
final List<String> list = new ArrayList<>();
int tokenStart = 0;
int currentType = Character.getType(c[tokenStart]);
for (int pos = tokenStart + 1; pos < c.length; pos++) {
final int type = Character.getType(c[pos]);
if (type == currentType) {
continue;
}
if (camelCase && type == Character.LOWERCASE_LETTER && currentType == Character.UPPERCASE_LETTER) {
final int newTokenStart = pos - 1;
if (newTokenStart != tokenStart) {
list.add(new String(c, tokenStart, newTokenStart - tokenStart));
tokenStart = newTokenStart;
}
} else {
list.add(new String(c, tokenStart, pos - tokenStart));
tokenStart = pos;
}
currentType = type;
}
list.add(new String(c, tokenStart, c.length - tokenStart));
return list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
/**
* <p>Splits a String by Character type as returned by
* {@code java.lang.Character.getType(char)}. Groups of contiguous
* characters of the same type are returned as complete tokens, with the
* following exception: the character of type
* {@code Character.UPPERCASE_LETTER}, if any, immediately
* preceding a token of type {@code Character.LOWERCASE_LETTER}
* will belong to the following token rather than to the preceding, if any,
* {@code Character.UPPERCASE_LETTER} token.
* <pre>
* StringUtils.splitByCharacterTypeCamelCase(null) = null
* StringUtils.splitByCharacterTypeCamelCase("") = []
* StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterTypeCamelCase("ab:cd:ef") = ["ab", ":", "cd", ":", "ef"]
* StringUtils.splitByCharacterTypeCamelCase("number5") = ["number", "5"]
* StringUtils.splitByCharacterTypeCamelCase("fooBar") = ["foo", "Bar"]
* StringUtils.splitByCharacterTypeCamelCase("foo200Bar") = ["foo", "200", "Bar"]
* StringUtils.splitByCharacterTypeCamelCase("ASFRules") = ["ASF", "Rules"]
* </pre>
* @param str the String to split, may be {@code null}
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.4
*/
public static String[] splitByCharacterTypeCamelCase(final String str) {
return splitByCharacterType(str, true);
}
/**
* <p>Splits the provided text into an array, separator string specified.</p>
*
* <p>The separator(s) will not be included in the returned String array.
* Adjacent separators are treated as one separator.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separator splits on whitespace.</p>
*
* <pre>
* StringUtils.splitByWholeSeparator(null, *) = null
* StringUtils.splitByWholeSeparator("", *) = []
* StringUtils.splitByWholeSeparator("ab de fg", null) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab de fg", null) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separator String containing the String to be used as a delimiter,
* {@code null} splits on whitespace
* @return an array of parsed Strings, {@code null} if null String was input
*/
public static String[] splitByWholeSeparator(final String str, final String separator) {
return splitByWholeSeparatorWorker(str, separator, -1, false);
}
/**
* <p>Splits the provided text into an array, separator string specified.
* Returns a maximum of {@code max} substrings.</p>
*
* <p>The separator(s) will not be included in the returned String array.
* Adjacent separators are treated as one separator.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separator splits on whitespace.</p>
*
* <pre>
* StringUtils.splitByWholeSeparator(null, *, *) = null
* StringUtils.splitByWholeSeparator("", *, *) = []
* StringUtils.splitByWholeSeparator("ab de fg", null, 0) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab de fg", null, 0) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separator String containing the String to be used as a delimiter,
* {@code null} splits on whitespace
* @param max the maximum number of elements to include in the returned
* array. A zero or negative value implies no limit.
* @return an array of parsed Strings, {@code null} if null String was input
*/
public static String[] splitByWholeSeparator( final String str, final String separator, final int max) {
return splitByWholeSeparatorWorker(str, separator, max, false);
}
/**
* <p>Splits the provided text into an array, separator string specified. </p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separator splits on whitespace.</p>
*
* <pre>
* StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *) = null
* StringUtils.splitByWholeSeparatorPreserveAllTokens("", *) = []
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null) = ["ab", "", "", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separator String containing the String to be used as a delimiter,
* {@code null} splits on whitespace
* @return an array of parsed Strings, {@code null} if null String was input
* @since 2.4
*/
public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator) {
return splitByWholeSeparatorWorker(str, separator, -1, true);
}
/**
* <p>Splits the provided text into an array, separator string specified.
* Returns a maximum of {@code max} substrings.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separator splits on whitespace.</p>
*
* <pre>
* StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *, *) = null
* StringUtils.splitByWholeSeparatorPreserveAllTokens("", *, *) = []
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null, 0) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null, 0) = ["ab", "", "", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separator String containing the String to be used as a delimiter,
* {@code null} splits on whitespace
* @param max the maximum number of elements to include in the returned
* array. A zero or negative value implies no limit.
* @return an array of parsed Strings, {@code null} if null String was input
* @since 2.4
*/
public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator, final int max) {
return splitByWholeSeparatorWorker(str, separator, max, true);
}
/**
* Performs the logic for the {@code splitByWholeSeparatorPreserveAllTokens} methods.
*
* @param str the String to parse, may be {@code null}
* @param separator String containing the String to be used as a delimiter,
* {@code null} splits on whitespace
* @param max the maximum number of elements to include in the returned
* array. A zero or negative value implies no limit.
* @param preserveAllTokens if {@code true}, adjacent separators are
* treated as empty token separators; if {@code false}, adjacent
* separators are treated as one separator.
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.4
*/
private static String[] splitByWholeSeparatorWorker(
final String str, final String separator, final int max, final boolean preserveAllTokens) {
if (str == null) {
return null;
}
final int len = str.length();
if (len == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
if (separator == null || EMPTY.equals(separator)) {
// Split on whitespace.
return splitWorker(str, null, max, preserveAllTokens);
}
final int separatorLength = separator.length();
final ArrayList<String> substrings = new ArrayList<>();
int numberOfSubstrings = 0;
int beg = 0;
int end = 0;
while (end < len) {
end = str.indexOf(separator, beg);
if (end > -1) {
if (end > beg) {
numberOfSubstrings += 1;
if (numberOfSubstrings == max) {
end = len;
substrings.add(str.substring(beg));
} else {
// The following is OK, because String.substring( beg, end ) excludes
// the character at the position 'end'.
substrings.add(str.substring(beg, end));
// Set the starting point for the next search.
// The following is equivalent to beg = end + (separatorLength - 1) + 1,
// which is the right calculation:
beg = end + separatorLength;
}
} else {
// We found a consecutive occurrence of the separator, so skip it.
if (preserveAllTokens) {
numberOfSubstrings += 1;
if (numberOfSubstrings == max) {
end = len;
substrings.add(str.substring(beg));
} else {
substrings.add(EMPTY);
}
}
beg = end + separatorLength;
}
} else {
// String.substring( beg ) goes from 'beg' to the end of the String.
substrings.add(str.substring(beg));
end = len;
}
}
return substrings.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
// -----------------------------------------------------------------------
/**
* <p>Splits the provided text into an array, using whitespace as the
* separator, preserving all tokens, including empty tokens created by
* adjacent separators. This is an alternative to using StringTokenizer.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.splitPreserveAllTokens(null) = null
* StringUtils.splitPreserveAllTokens("") = []
* StringUtils.splitPreserveAllTokens("abc def") = ["abc", "def"]
* StringUtils.splitPreserveAllTokens("abc def") = ["abc", "", "def"]
* StringUtils.splitPreserveAllTokens(" abc ") = ["", "abc", ""]
* </pre>
*
* @param str the String to parse, may be {@code null}
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.1
*/
public static String[] splitPreserveAllTokens(final String str) {
return splitWorker(str, null, -1, true);
}
/**
* <p>Splits the provided text into an array, separator specified,
* preserving all tokens, including empty tokens created by adjacent
* separators. This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.splitPreserveAllTokens(null, *) = null
* StringUtils.splitPreserveAllTokens("", *) = []
* StringUtils.splitPreserveAllTokens("a.b.c", '.') = ["a", "b", "c"]
* StringUtils.splitPreserveAllTokens("a..b.c", '.') = ["a", "", "b", "c"]
* StringUtils.splitPreserveAllTokens("a:b:c", '.') = ["a:b:c"]
* StringUtils.splitPreserveAllTokens("a\tb\nc", null) = ["a", "b", "c"]
* StringUtils.splitPreserveAllTokens("a b c", ' ') = ["a", "b", "c"]
* StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", ""]
* StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", "", ""]
* StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", a", "b", "c"]
* StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", "", a", "b", "c"]
* StringUtils.splitPreserveAllTokens(" a b c ", ' ') = ["", a", "b", "c", ""]
* </pre>
*
* @param str the String to parse, may be {@code null}
* @param separatorChar the character used as the delimiter,
* {@code null} splits on whitespace
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.1
*/
public static String[] splitPreserveAllTokens(final String str, final char separatorChar) {
return splitWorker(str, separatorChar, true);
}
/**
* <p>Splits the provided text into an array, separators specified,
* preserving all tokens, including empty tokens created by adjacent
* separators. This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separatorChars splits on whitespace.</p>
*
* <pre>
* StringUtils.splitPreserveAllTokens(null, *) = null
* StringUtils.splitPreserveAllTokens("", *) = []
* StringUtils.splitPreserveAllTokens("abc def", null) = ["abc", "def"]
* StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "def"]
* StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "", def"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef:", ":") = ["ab", "cd", "ef", ""]
* StringUtils.splitPreserveAllTokens("ab:cd:ef::", ":") = ["ab", "cd", "ef", "", ""]
* StringUtils.splitPreserveAllTokens("ab::cd:ef", ":") = ["ab", "", cd", "ef"]
* StringUtils.splitPreserveAllTokens(":cd:ef", ":") = ["", cd", "ef"]
* StringUtils.splitPreserveAllTokens("::cd:ef", ":") = ["", "", cd", "ef"]
* StringUtils.splitPreserveAllTokens(":cd:ef:", ":") = ["", cd", "ef", ""]
* </pre>
*
* @param str the String to parse, may be {@code null}
* @param separatorChars the characters used as the delimiters,
* {@code null} splits on whitespace
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.1
*/
public static String[] splitPreserveAllTokens(final String str, final String separatorChars) {
return splitWorker(str, separatorChars, -1, true);
}
/**
* <p>Splits the provided text into an array with a maximum length,
* separators specified, preserving all tokens, including empty tokens
* created by adjacent separators.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* Adjacent separators are treated as one separator.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separatorChars splits on whitespace.</p>
*
* <p>If more than {@code max} delimited substrings are found, the last
* returned string includes all characters after the first {@code max - 1}
* returned strings (including separator characters).</p>
*
* <pre>
* StringUtils.splitPreserveAllTokens(null, *, *) = null
* StringUtils.splitPreserveAllTokens("", *, *) = []
* StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "de", "fg"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "", "", "de", "fg"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 2) = ["ab", " de fg"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 3) = ["ab", "", " de fg"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 4) = ["ab", "", "", "de fg"]
* </pre>
*
* @param str the String to parse, may be {@code null}
* @param separatorChars the characters used as the delimiters,
* {@code null} splits on whitespace
* @param max the maximum number of elements to include in the
* array. A zero or negative value implies no limit
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.1
*/
public static String[] splitPreserveAllTokens(final String str, final String separatorChars, final int max) {
return splitWorker(str, separatorChars, max, true);
}
/**
* Performs the logic for the {@code split} and
* {@code splitPreserveAllTokens} methods that do not return a
* maximum array length.
*
* @param str the String to parse, may be {@code null}
* @param separatorChar the separate character
* @param preserveAllTokens if {@code true}, adjacent separators are
* treated as empty token separators; if {@code false}, adjacent
* separators are treated as one separator.
* @return an array of parsed Strings, {@code null} if null String input
*/
private static String[] splitWorker(final String str, final char separatorChar, final boolean preserveAllTokens) {
// Performance tuned for 2.0 (JDK1.4)
if (str == null) {
return null;
}
final int len = str.length();
if (len == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
final List<String> list = new ArrayList<>();
int i = 0, start = 0;
boolean match = false;
boolean lastMatch = false;
while (i < len) {
if (str.charAt(i) == separatorChar) {
if (match || preserveAllTokens) {
list.add(str.substring(start, i));
match = false;
lastMatch = true;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
if (match || preserveAllTokens && lastMatch) {
list.add(str.substring(start, i));
}
return list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
/**
* Performs the logic for the {@code split} and
* {@code splitPreserveAllTokens} methods that return a maximum array
* length.
*
* @param str the String to parse, may be {@code null}
* @param separatorChars the separate character
* @param max the maximum number of elements to include in the
* array. A zero or negative value implies no limit.
* @param preserveAllTokens if {@code true}, adjacent separators are
* treated as empty token separators; if {@code false}, adjacent
* separators are treated as one separator.
* @return an array of parsed Strings, {@code null} if null String input
*/
private static String[] splitWorker(final String str, final String separatorChars, final int max, final boolean preserveAllTokens) {
// Performance tuned for 2.0 (JDK1.4)
// Direct code is quicker than StringTokenizer.
// Also, StringTokenizer uses isSpace() not isWhitespace()
if (str == null) {
return null;
}
final int len = str.length();
if (len == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
final List<String> list = new ArrayList<>();
int sizePlus1 = 1;
int i = 0, start = 0;
boolean match = false;
boolean lastMatch = false;
if (separatorChars == null) {
// Null separator means use whitespace
while (i < len) {
if (Character.isWhitespace(str.charAt(i))) {
if (match || preserveAllTokens) {
lastMatch = true;
if (sizePlus1++ == max) {
i = len;
lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
} else if (separatorChars.length() == 1) {
// Optimise 1 character case
final char sep = separatorChars.charAt(0);
while (i < len) {
if (str.charAt(i) == sep) {
if (match || preserveAllTokens) {
lastMatch = true;
if (sizePlus1++ == max) {
i = len;
lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
} else {
// standard case
while (i < len) {
if (separatorChars.indexOf(str.charAt(i)) >= 0) {
if (match || preserveAllTokens) {
lastMatch = true;
if (sizePlus1++ == max) {
i = len;
lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
}
if (match || preserveAllTokens && lastMatch) {
list.add(str.substring(start, i));
}
return list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
/**
* <p>Check if a CharSequence starts with a specified prefix.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered to be equal. The comparison is case sensitive.</p>
*
* <pre>
* StringUtils.startsWith(null, null) = true
* StringUtils.startsWith(null, "abc") = false
* StringUtils.startsWith("abcdef", null) = false
* StringUtils.startsWith("abcdef", "abc") = true
* StringUtils.startsWith("ABCDEF", "abc") = false
* </pre>
*
* @see java.lang.String#startsWith(String)
* @param str the CharSequence to check, may be null
* @param prefix the prefix to find, may be null
* @return {@code true} if the CharSequence starts with the prefix, case sensitive, or
* both {@code null}
* @since 2.4
* @since 3.0 Changed signature from startsWith(String, String) to startsWith(CharSequence, CharSequence)
*/
public static boolean startsWith(final CharSequence str, final CharSequence prefix) {
return startsWith(str, prefix, false);
}
/**
* <p>Check if a CharSequence starts with a specified prefix (optionally case insensitive).</p>
*
* @see java.lang.String#startsWith(String)
* @param str the CharSequence to check, may be null
* @param prefix the prefix to find, may be null
* @param ignoreCase indicates whether the compare should ignore case
* (case insensitive) or not.
* @return {@code true} if the CharSequence starts with the prefix or
* both {@code null}
*/
private static boolean startsWith(final CharSequence str, final CharSequence prefix, final boolean ignoreCase) {
if (str == null || prefix == null) {
return str == prefix;
}
if (prefix.length() > str.length()) {
return false;
}
return CharSequenceUtils.regionMatches(str, ignoreCase, 0, prefix, 0, prefix.length());
}
/**
* <p>Check if a CharSequence starts with any of the provided case-sensitive prefixes.</p>
*
* <pre>
* StringUtils.startsWithAny(null, null) = false
* StringUtils.startsWithAny(null, new String[] {"abc"}) = false
* StringUtils.startsWithAny("abcxyz", null) = false
* StringUtils.startsWithAny("abcxyz", new String[] {""}) = true
* StringUtils.startsWithAny("abcxyz", new String[] {"abc"}) = true
* StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true
* StringUtils.startsWithAny("abcxyz", null, "xyz", "ABCX") = false
* StringUtils.startsWithAny("ABCXYZ", null, "xyz", "abc") = false
* </pre>
*
* @param sequence the CharSequence to check, may be null
* @param searchStrings the case-sensitive CharSequence prefixes, may be empty or contain {@code null}
* @see StringUtils#startsWith(CharSequence, CharSequence)
* @return {@code true} if the input {@code sequence} is {@code null} AND no {@code searchStrings} are provided, or
* the input {@code sequence} begins with any of the provided case-sensitive {@code searchStrings}.
* @since 2.5
* @since 3.0 Changed signature from startsWithAny(String, String[]) to startsWithAny(CharSequence, CharSequence...)
*/
public static boolean startsWithAny(final CharSequence sequence, final CharSequence... searchStrings) {
if (isEmpty(sequence) || ArrayUtils.isEmpty(searchStrings)) {
return false;
}
for (final CharSequence searchString : searchStrings) {
if (startsWith(sequence, searchString)) {
return true;
}
}
return false;
}
/**
* <p>Case insensitive check if a CharSequence starts with a specified prefix.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered to be equal. The comparison is case insensitive.</p>
*
* <pre>
* StringUtils.startsWithIgnoreCase(null, null) = true
* StringUtils.startsWithIgnoreCase(null, "abc") = false
* StringUtils.startsWithIgnoreCase("abcdef", null) = false
* StringUtils.startsWithIgnoreCase("abcdef", "abc") = true
* StringUtils.startsWithIgnoreCase("ABCDEF", "abc") = true
* </pre>
*
* @see java.lang.String#startsWith(String)
* @param str the CharSequence to check, may be null
* @param prefix the prefix to find, may be null
* @return {@code true} if the CharSequence starts with the prefix, case insensitive, or
* both {@code null}
* @since 2.4
* @since 3.0 Changed signature from startsWithIgnoreCase(String, String) to startsWithIgnoreCase(CharSequence, CharSequence)
*/
public static boolean startsWithIgnoreCase(final CharSequence str, final CharSequence prefix) {
return startsWith(str, prefix, true);
}
// Stripping
//-----------------------------------------------------------------------
/**
* <p>Strips whitespace from the start and end of a String.</p>
*
* <p>This is similar to {@link #trim(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.strip(null) = null
* StringUtils.strip("") = ""
* StringUtils.strip(" ") = ""
* StringUtils.strip("abc") = "abc"
* StringUtils.strip(" abc") = "abc"
* StringUtils.strip("abc ") = "abc"
* StringUtils.strip(" abc ") = "abc"
* StringUtils.strip(" ab c ") = "ab c"
* </pre>
*
* @param str the String to remove whitespace from, may be null
* @return the stripped String, {@code null} if null String input
*/
public static String strip(final String str) {
return strip(str, null);
}
/**
* <p>Strips any of a set of characters from the start and end of a String.
* This is similar to {@link String#trim()} but allows the characters
* to be stripped to be controlled.</p>
*
* <p>A {@code null} input String returns {@code null}.
* An empty string ("") input returns the empty string.</p>
*
* <p>If the stripChars String is {@code null}, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.
* Alternatively use {@link #strip(String)}.</p>
*
* <pre>
* StringUtils.strip(null, *) = null
* StringUtils.strip("", *) = ""
* StringUtils.strip("abc", null) = "abc"
* StringUtils.strip(" abc", null) = "abc"
* StringUtils.strip("abc ", null) = "abc"
* StringUtils.strip(" abc ", null) = "abc"
* StringUtils.strip(" abcyx", "xyz") = " abc"
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped String, {@code null} if null String input
*/
public static String strip(String str, final String stripChars) {
if (isEmpty(str)) {
return str;
}
str = stripStart(str, stripChars);
return stripEnd(str, stripChars);
}
/**
* <p>Removes diacritics (~= accents) from a string. The case will not be altered.</p>
* <p>For instance, 'à' will be replaced by 'a'.</p>
* <p>Note that ligatures will be left as is.</p>
*
* <pre>
* StringUtils.stripAccents(null) = null
* StringUtils.stripAccents("") = ""
* StringUtils.stripAccents("control") = "control"
* StringUtils.stripAccents("éclair") = "eclair"
* </pre>
*
* @param input String to be stripped
* @return input text with diacritics removed
*
* @since 3.0
*/
// See also Lucene's ASCIIFoldingFilter (Lucene 2.9) that replaces accented characters by their unaccented equivalent (and uncommitted bug fix: https://issues.apache.org/jira/browse/LUCENE-1343?focusedCommentId=12858907&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#action_12858907).
public static String stripAccents(final String input) {
if (input == null) {
return null;
}
final Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); //$NON-NLS-1$
final StringBuilder decomposed = new StringBuilder(Normalizer.normalize(input, Normalizer.Form.NFD));
convertRemainingAccentCharacters(decomposed);
// Note that this doesn't correctly remove ligatures...
return pattern.matcher(decomposed).replaceAll(EMPTY);
}
// StripAll
//-----------------------------------------------------------------------
/**
* <p>Strips whitespace from the start and end of every String in an array.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>A new array is returned each time, except for length zero.
* A {@code null} array will return {@code null}.
* An empty array will return itself.
* A {@code null} array entry will be ignored.</p>
*
* <pre>
* StringUtils.stripAll(null) = null
* StringUtils.stripAll([]) = []
* StringUtils.stripAll(["abc", " abc"]) = ["abc", "abc"]
* StringUtils.stripAll(["abc ", null]) = ["abc", null]
* </pre>
*
* @param strs the array to remove whitespace from, may be null
* @return the stripped Strings, {@code null} if null array input
*/
public static String[] stripAll(final String... strs) {
return stripAll(strs, null);
}
/**
* <p>Strips any of a set of characters from the start and end of every
* String in an array.</p>
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>A new array is returned each time, except for length zero.
* A {@code null} array will return {@code null}.
* An empty array will return itself.
* A {@code null} array entry will be ignored.
* A {@code null} stripChars will strip whitespace as defined by
* {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripAll(null, *) = null
* StringUtils.stripAll([], *) = []
* StringUtils.stripAll(["abc", " abc"], null) = ["abc", "abc"]
* StringUtils.stripAll(["abc ", null], null) = ["abc", null]
* StringUtils.stripAll(["abc ", null], "yz") = ["abc ", null]
* StringUtils.stripAll(["yabcz", null], "yz") = ["abc", null]
* </pre>
*
* @param strs the array to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped Strings, {@code null} if null array input
*/
public static String[] stripAll(final String[] strs, final String stripChars) {
int strsLen;
if (strs == null || (strsLen = strs.length) == 0) {
return strs;
}
final String[] newArr = new String[strsLen];
for (int i = 0; i < strsLen; i++) {
newArr[i] = strip(strs[i], stripChars);
}
return newArr;
}
/**
* <p>Strips any of a set of characters from the end of a String.</p>
*
* <p>A {@code null} input String returns {@code null}.
* An empty string ("") input returns the empty string.</p>
*
* <p>If the stripChars String is {@code null}, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripEnd(null, *) = null
* StringUtils.stripEnd("", *) = ""
* StringUtils.stripEnd("abc", "") = "abc"
* StringUtils.stripEnd("abc", null) = "abc"
* StringUtils.stripEnd(" abc", null) = " abc"
* StringUtils.stripEnd("abc ", null) = "abc"
* StringUtils.stripEnd(" abc ", null) = " abc"
* StringUtils.stripEnd(" abcyx", "xyz") = " abc"
* StringUtils.stripEnd("120.00", ".0") = "12"
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the set of characters to remove, null treated as whitespace
* @return the stripped String, {@code null} if null String input
*/
public static String stripEnd(final String str, final String stripChars) {
int end = length(str);
if (end == 0) {
return str;
}
if (stripChars == null) {
while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) {
end--;
}
} else if (stripChars.isEmpty()) {
return str;
} else {
while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != INDEX_NOT_FOUND) {
end--;
}
}
return str.substring(0, end);
}
/**
* <p>Strips any of a set of characters from the start of a String.</p>
*
* <p>A {@code null} input String returns {@code null}.
* An empty string ("") input returns the empty string.</p>
*
* <p>If the stripChars String is {@code null}, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripStart(null, *) = null
* StringUtils.stripStart("", *) = ""
* StringUtils.stripStart("abc", "") = "abc"
* StringUtils.stripStart("abc", null) = "abc"
* StringUtils.stripStart(" abc", null) = "abc"
* StringUtils.stripStart("abc ", null) = "abc "
* StringUtils.stripStart(" abc ", null) = "abc "
* StringUtils.stripStart("yxabc ", "xyz") = "abc "
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped String, {@code null} if null String input
*/
public static String stripStart(final String str, final String stripChars) {
final int strLen = length(str);
if (strLen == 0) {
return str;
}
int start = 0;
if (stripChars == null) {
while (start != strLen && Character.isWhitespace(str.charAt(start))) {
start++;
}
} else if (stripChars.isEmpty()) {
return str;
} else {
while (start != strLen && stripChars.indexOf(str.charAt(start)) != INDEX_NOT_FOUND) {
start++;
}
}
return str.substring(start);
}
/**
* <p>Strips whitespace from the start and end of a String returning
* an empty String if {@code null} input.</p>
*
* <p>This is similar to {@link #trimToEmpty(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripToEmpty(null) = ""
* StringUtils.stripToEmpty("") = ""
* StringUtils.stripToEmpty(" ") = ""
* StringUtils.stripToEmpty("abc") = "abc"
* StringUtils.stripToEmpty(" abc") = "abc"
* StringUtils.stripToEmpty("abc ") = "abc"
* StringUtils.stripToEmpty(" abc ") = "abc"
* StringUtils.stripToEmpty(" ab c ") = "ab c"
* </pre>
*
* @param str the String to be stripped, may be null
* @return the trimmed String, or an empty String if {@code null} input
* @since 2.0
*/
public static String stripToEmpty(final String str) {
return str == null ? EMPTY : strip(str, null);
}
/**
* <p>Strips whitespace from the start and end of a String returning
* {@code null} if the String is empty ("") after the strip.</p>
*
* <p>This is similar to {@link #trimToNull(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripToNull(null) = null
* StringUtils.stripToNull("") = null
* StringUtils.stripToNull(" ") = null
* StringUtils.stripToNull("abc") = "abc"
* StringUtils.stripToNull(" abc") = "abc"
* StringUtils.stripToNull("abc ") = "abc"
* StringUtils.stripToNull(" abc ") = "abc"
* StringUtils.stripToNull(" ab c ") = "ab c"
* </pre>
*
* @param str the String to be stripped, may be null
* @return the stripped String,
* {@code null} if whitespace, empty or null String input
* @since 2.0
*/
public static String stripToNull(String str) {
if (str == null) {
return null;
}
str = strip(str, null);
return str.isEmpty() ? null : str;
}
// Substring
//-----------------------------------------------------------------------
/**
* <p>Gets a substring from the specified String avoiding exceptions.</p>
*
* <p>A negative start position can be used to start {@code n}
* characters from the end of the String.</p>
*
* <p>A {@code null} String will return {@code null}.
* An empty ("") String will return "".</p>
*
* <pre>
* StringUtils.substring(null, *) = null
* StringUtils.substring("", *) = ""
* StringUtils.substring("abc", 0) = "abc"
* StringUtils.substring("abc", 2) = "c"
* StringUtils.substring("abc", 4) = ""
* StringUtils.substring("abc", -2) = "bc"
* StringUtils.substring("abc", -4) = "abc"
* </pre>
*
* @param str the String to get the substring from, may be null
* @param start the position to start from, negative means
* count back from the end of the String by this many characters
* @return substring from start position, {@code null} if null String input
*/
public static String substring(final String str, int start) {
if (str == null) {
return null;
}
// handle negatives, which means last n characters
if (start < 0) {
start = str.length() + start; // remember start is negative
}
if (start < 0) {
start = 0;
}
if (start > str.length()) {
return EMPTY;
}
return str.substring(start);
}
/**
* <p>Gets a substring from the specified String avoiding exceptions.</p>
*
* <p>A negative start position can be used to start/end {@code n}
* characters from the end of the String.</p>
*
* <p>The returned substring starts with the character in the {@code start}
* position and ends before the {@code end} position. All position counting is
* zero-based -- i.e., to start at the beginning of the string use
* {@code start = 0}. Negative start and end positions can be used to
* specify offsets relative to the end of the String.</p>
*
* <p>If {@code start} is not strictly to the left of {@code end}, ""
* is returned.</p>
*
* <pre>
* StringUtils.substring(null, *, *) = null
* StringUtils.substring("", * , *) = "";
* StringUtils.substring("abc", 0, 2) = "ab"
* StringUtils.substring("abc", 2, 0) = ""
* StringUtils.substring("abc", 2, 4) = "c"
* StringUtils.substring("abc", 4, 6) = ""
* StringUtils.substring("abc", 2, 2) = ""
* StringUtils.substring("abc", -2, -1) = "b"
* StringUtils.substring("abc", -4, 2) = "ab"
* </pre>
*
* @param str the String to get the substring from, may be null
* @param start the position to start from, negative means
* count back from the end of the String by this many characters
* @param end the position to end at (exclusive), negative means
* count back from the end of the String by this many characters
* @return substring from start position to end position,
* {@code null} if null String input
*/
public static String substring(final String str, int start, int end) {
if (str == null) {
return null;
}
// handle negatives
if (end < 0) {
end = str.length() + end; // remember end is negative
}
if (start < 0) {
start = str.length() + start; // remember start is negative
}
// check length next
if (end > str.length()) {
end = str.length();
}
// if start is greater than end, return ""
if (start > end) {
return EMPTY;
}
if (start < 0) {
start = 0;
}
if (end < 0) {
end = 0;
}
return str.substring(start, end);
}
/**
* <p>Gets the substring after the first occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A {@code null} string input will return {@code null}.
* An empty ("") string input will return the empty string.
* A {@code null} separator will return the empty string if the
* input string is not {@code null}.</p>
*
* <p>If nothing is found, the empty string is returned.</p>
*
* <pre>
* StringUtils.substringAfter(null, *) = null
* StringUtils.substringAfter("", *) = ""
* StringUtils.substringAfter(*, null) = ""
* StringUtils.substringAfter("abc", "a") = "bc"
* StringUtils.substringAfter("abcba", "b") = "cba"
* StringUtils.substringAfter("abc", "c") = ""
* StringUtils.substringAfter("abc", "d") = ""
* StringUtils.substringAfter("abc", "") = "abc"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring after the first occurrence of the separator,
* {@code null} if null String input
* @since 2.0
*/
public static String substringAfter(final String str, final String separator) {
if (isEmpty(str)) {
return str;
}
if (separator == null) {
return EMPTY;
}
final int pos = str.indexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return EMPTY;
}
return str.substring(pos + separator.length());
}
// startsWith
//-----------------------------------------------------------------------
/**
* <p>Gets the substring after the last occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A {@code null} string input will return {@code null}.
* An empty ("") string input will return the empty string.
* An empty or {@code null} separator will return the empty string if
* the input string is not {@code null}.</p>
*
* <p>If nothing is found, the empty string is returned.</p>
*
* <pre>
* StringUtils.substringAfterLast(null, *) = null
* StringUtils.substringAfterLast("", *) = ""
* StringUtils.substringAfterLast(*, "") = ""
* StringUtils.substringAfterLast(*, null) = ""
* StringUtils.substringAfterLast("abc", "a") = "bc"
* StringUtils.substringAfterLast("abcba", "b") = "a"
* StringUtils.substringAfterLast("abc", "c") = ""
* StringUtils.substringAfterLast("a", "a") = ""
* StringUtils.substringAfterLast("a", "z") = ""
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring after the last occurrence of the separator,
* {@code null} if null String input
* @since 2.0
*/
public static String substringAfterLast(final String str, final String separator) {
if (isEmpty(str)) {
return str;
}
if (isEmpty(separator)) {
return EMPTY;
}
final int pos = str.lastIndexOf(separator);
if (pos == INDEX_NOT_FOUND || pos == str.length() - separator.length()) {
return EMPTY;
}
return str.substring(pos + separator.length());
}
// SubStringAfter/SubStringBefore
//-----------------------------------------------------------------------
/**
* <p>Gets the substring before the first occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A {@code null} string input will return {@code null}.
* An empty ("") string input will return the empty string.
* A {@code null} separator will return the input string.</p>
*
* <p>If nothing is found, the string input is returned.</p>
*
* <pre>
* StringUtils.substringBefore(null, *) = null
* StringUtils.substringBefore("", *) = ""
* StringUtils.substringBefore("abc", "a") = ""
* StringUtils.substringBefore("abcba", "b") = "a"
* StringUtils.substringBefore("abc", "c") = "ab"
* StringUtils.substringBefore("abc", "d") = "abc"
* StringUtils.substringBefore("abc", "") = ""
* StringUtils.substringBefore("abc", null) = "abc"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring before the first occurrence of the separator,
* {@code null} if null String input
* @since 2.0
*/
public static String substringBefore(final String str, final String separator) {
if (isEmpty(str) || separator == null) {
return str;
}
if (separator.isEmpty()) {
return EMPTY;
}
final int pos = str.indexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return str;
}
return str.substring(0, pos);
}
/**
* <p>Gets the substring before the last occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A {@code null} string input will return {@code null}.
* An empty ("") string input will return the empty string.
* An empty or {@code null} separator will return the input string.</p>
*
* <p>If nothing is found, the string input is returned.</p>
*
* <pre>
* StringUtils.substringBeforeLast(null, *) = null
* StringUtils.substringBeforeLast("", *) = ""
* StringUtils.substringBeforeLast("abcba", "b") = "abc"
* StringUtils.substringBeforeLast("abc", "c") = "ab"
* StringUtils.substringBeforeLast("a", "a") = ""
* StringUtils.substringBeforeLast("a", "z") = "a"
* StringUtils.substringBeforeLast("a", null) = "a"
* StringUtils.substringBeforeLast("a", "") = "a"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring before the last occurrence of the separator,
* {@code null} if null String input
* @since 2.0
*/
public static String substringBeforeLast(final String str, final String separator) {
if (isEmpty(str) || isEmpty(separator)) {
return str;
}
final int pos = str.lastIndexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return str;
}
return str.substring(0, pos);
}
// Substring between
//-----------------------------------------------------------------------
/**
* <p>Gets the String that is nested in between two instances of the
* same String.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} tag returns {@code null}.</p>
*
* <pre>
* StringUtils.substringBetween(null, *) = null
* StringUtils.substringBetween("", "") = ""
* StringUtils.substringBetween("", "tag") = null
* StringUtils.substringBetween("tagabctag", null) = null
* StringUtils.substringBetween("tagabctag", "") = ""
* StringUtils.substringBetween("tagabctag", "tag") = "abc"
* </pre>
*
* @param str the String containing the substring, may be null
* @param tag the String before and after the substring, may be null
* @return the substring, {@code null} if no match
* @since 2.0
*/
public static String substringBetween(final String str, final String tag) {
return substringBetween(str, tag, tag);
}
// endsWith
//-----------------------------------------------------------------------
/**
* <p>Gets the String that is nested in between two Strings.
* Only the first match is returned.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} open/close returns {@code null} (no match).
* An empty ("") open and close returns an empty string.</p>
*
* <pre>
* StringUtils.substringBetween("wx[b]yz", "[", "]") = "b"
* StringUtils.substringBetween(null, *, *) = null
* StringUtils.substringBetween(*, null, *) = null
* StringUtils.substringBetween(*, *, null) = null
* StringUtils.substringBetween("", "", "") = ""
* StringUtils.substringBetween("", "", "]") = null
* StringUtils.substringBetween("", "[", "]") = null
* StringUtils.substringBetween("yabcz", "", "") = ""
* StringUtils.substringBetween("yabcz", "y", "z") = "abc"
* StringUtils.substringBetween("yabczyabcz", "y", "z") = "abc"
* </pre>
*
* @param str the String containing the substring, may be null
* @param open the String before the substring, may be null
* @param close the String after the substring, may be null
* @return the substring, {@code null} if no match
* @since 2.0
*/
public static String substringBetween(final String str, final String open, final String close) {
if (str == null || open == null || close == null) {
return null;
}
final int start = str.indexOf(open);
if (start != INDEX_NOT_FOUND) {
final int end = str.indexOf(close, start + open.length());
if (end != INDEX_NOT_FOUND) {
return str.substring(start + open.length(), end);
}
}
return null;
}
/**
* <p>Searches a String for substrings delimited by a start and end tag,
* returning all matching substrings in an array.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} open/close returns {@code null} (no match).
* An empty ("") open/close returns {@code null} (no match).</p>
*
* <pre>
* StringUtils.substringsBetween("[a][b][c]", "[", "]") = ["a","b","c"]
* StringUtils.substringsBetween(null, *, *) = null
* StringUtils.substringsBetween(*, null, *) = null
* StringUtils.substringsBetween(*, *, null) = null
* StringUtils.substringsBetween("", "[", "]") = []
* </pre>
*
* @param str the String containing the substrings, null returns null, empty returns empty
* @param open the String identifying the start of the substring, empty returns null
* @param close the String identifying the end of the substring, empty returns null
* @return a String Array of substrings, or {@code null} if no match
* @since 2.3
*/
public static String[] substringsBetween(final String str, final String open, final String close) {
if (str == null || isEmpty(open) || isEmpty(close)) {
return null;
}
final int strLen = str.length();
if (strLen == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
final int closeLen = close.length();
final int openLen = open.length();
final List<String> list = new ArrayList<>();
int pos = 0;
while (pos < strLen - closeLen) {
int start = str.indexOf(open, pos);
if (start < 0) {
break;
}
start += openLen;
final int end = str.indexOf(close, start);
if (end < 0) {
break;
}
list.add(str.substring(start, end));
pos = end + closeLen;
}
if (list.isEmpty()) {
return null;
}
return list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
/**
* <p>Swaps the case of a String changing upper and title case to
* lower case, and lower case to upper case.</p>
*
* <ul>
* <li>Upper case character converts to Lower case</li>
* <li>Title case character converts to Lower case</li>
* <li>Lower case character converts to Upper case</li>
* </ul>
*
* <p>For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#swapCase(String)}.
* A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.swapCase(null) = null
* StringUtils.swapCase("") = ""
* StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer performs a word based algorithm.
* If you only use ASCII, you will notice no change.
* That functionality is available in org.apache.commons.lang3.text.WordUtils.</p>
*
* @param str the String to swap case, may be null
* @return the changed String, {@code null} if null String input
*/
public static String swapCase(final String str) {
if (isEmpty(str)) {
return str;
}
final int strLen = str.length();
final int newCodePoints[] = new int[strLen]; // cannot be longer than the char array
int outOffset = 0;
for (int i = 0; i < strLen; ) {
final int oldCodepoint = str.codePointAt(i);
final int newCodePoint;
if (Character.isUpperCase(oldCodepoint)) {
newCodePoint = Character.toLowerCase(oldCodepoint);
} else if (Character.isTitleCase(oldCodepoint)) {
newCodePoint = Character.toLowerCase(oldCodepoint);
} else if (Character.isLowerCase(oldCodepoint)) {
newCodePoint = Character.toUpperCase(oldCodepoint);
} else {
newCodePoint = oldCodepoint;
}
newCodePoints[outOffset++] = newCodePoint;
i += Character.charCount(newCodePoint);
}
return new String(newCodePoints, 0, outOffset);
}
/**
* <p>Converts a {@code CharSequence} into an array of code points.</p>
*
* <p>Valid pairs of surrogate code units will be converted into a single supplementary
* code point. Isolated surrogate code units (i.e. a high surrogate not followed by a low surrogate or
* a low surrogate not preceded by a high surrogate) will be returned as-is.</p>
*
* <pre>
* StringUtils.toCodePoints(null) = null
* StringUtils.toCodePoints("") = [] // empty array
* </pre>
*
* @param str the character sequence to convert
* @return an array of code points
* @since 3.6
*/
public static int[] toCodePoints(final CharSequence str) {
if (str == null) {
return null;
}
if (str.length() == 0) {
return ArrayUtils.EMPTY_INT_ARRAY;
}
final String s = str.toString();
final int[] result = new int[s.codePointCount(0, s.length())];
int index = 0;
for (int i = 0; i < result.length; i++) {
result[i] = s.codePointAt(index);
index += Character.charCount(result[i]);
}
return result;
}
/**
* Converts a {@code byte[]} to a String using the specified character encoding.
*
* @param bytes
* the byte array to read from
* @param charset
* the encoding to use, if null then use the platform default
* @return a new String
* @throws NullPointerException
* if {@code bytes} is null
* @since 3.2
* @since 3.3 No longer throws {@link UnsupportedEncodingException}.
*/
public static String toEncodedString(final byte[] bytes, final Charset charset) {
return new String(bytes, Charsets.toCharset(charset));
}
/**
* Converts the given source String as a lower-case using the {@link Locale#ROOT} locale in a null-safe manner.
*
* @param source A source String or null.
* @return the given source String as a lower-case using the {@link Locale#ROOT} locale or null.
* @since 3.10
*/
public static String toRootLowerCase(final String source) {
return source == null ? null : source.toLowerCase(Locale.ROOT);
}
/**
* Converts the given source String as a upper-case using the {@link Locale#ROOT} locale in a null-safe manner.
*
* @param source A source String or null.
* @return the given source String as a upper-case using the {@link Locale#ROOT} locale or null.
* @since 3.10
*/
public static String toRootUpperCase(final String source) {
return source == null ? null : source.toUpperCase(Locale.ROOT);
}
/**
* Converts a {@code byte[]} to a String using the specified character encoding.
*
* @param bytes
* the byte array to read from
* @param charsetName
* the encoding to use, if null then use the platform default
* @return a new String
* @throws UnsupportedEncodingException
* If the named charset is not supported
* @throws NullPointerException
* if the input is null
* @deprecated use {@link StringUtils#toEncodedString(byte[], Charset)} instead of String constants in your code
* @since 3.1
*/
@Deprecated
public static String toString(final byte[] bytes, final String charsetName) throws UnsupportedEncodingException {
return charsetName != null ? new String(bytes, charsetName) : new String(bytes, Charset.defaultCharset());
}
// Trim
//-----------------------------------------------------------------------
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String, handling {@code null} by returning
* {@code null}.</p>
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #strip(String)}.</p>
*
* <p>To trim your choice of characters, use the
* {@link #strip(String, String)} methods.</p>
*
* <pre>
* StringUtils.trim(null) = null
* StringUtils.trim("") = ""
* StringUtils.trim(" ") = ""
* StringUtils.trim("abc") = "abc"
* StringUtils.trim(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed string, {@code null} if null String input
*/
public static String trim(final String str) {
return str == null ? null : str.trim();
}
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String returning an empty String ("") if the String
* is empty ("") after the trim or if it is {@code null}.
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #stripToEmpty(String)}.</p>
*
* <pre>
* StringUtils.trimToEmpty(null) = ""
* StringUtils.trimToEmpty("") = ""
* StringUtils.trimToEmpty(" ") = ""
* StringUtils.trimToEmpty("abc") = "abc"
* StringUtils.trimToEmpty(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed String, or an empty String if {@code null} input
* @since 2.0
*/
public static String trimToEmpty(final String str) {
return str == null ? EMPTY : str.trim();
}
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String returning {@code null} if the String is
* empty ("") after the trim or if it is {@code null}.
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #stripToNull(String)}.</p>
*
* <pre>
* StringUtils.trimToNull(null) = null
* StringUtils.trimToNull("") = null
* StringUtils.trimToNull(" ") = null
* StringUtils.trimToNull("abc") = "abc"
* StringUtils.trimToNull(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed String,
* {@code null} if only chars <= 32, empty or null String input
* @since 2.0
*/
public static String trimToNull(final String str) {
final String ts = trim(str);
return isEmpty(ts) ? null : ts;
}
/**
* <p>Truncates a String. This will turn
* "Now is the time for all good men" into "Now is the time for".</p>
*
* <p>Specifically:</p>
* <ul>
* <li>If {@code str} is less than {@code maxWidth} characters
* long, return it.</li>
* <li>Else truncate it to {@code substring(str, 0, maxWidth)}.</li>
* <li>If {@code maxWidth} is less than {@code 0}, throw an
* {@code IllegalArgumentException}.</li>
* <li>In no case will it return a String of length greater than
* {@code maxWidth}.</li>
* </ul>
*
* <pre>
* StringUtils.truncate(null, 0) = null
* StringUtils.truncate(null, 2) = null
* StringUtils.truncate("", 4) = ""
* StringUtils.truncate("abcdefg", 4) = "abcd"
* StringUtils.truncate("abcdefg", 6) = "abcdef"
* StringUtils.truncate("abcdefg", 7) = "abcdefg"
* StringUtils.truncate("abcdefg", 8) = "abcdefg"
* StringUtils.truncate("abcdefg", -1) = throws an IllegalArgumentException
* </pre>
*
* @param str the String to truncate, may be null
* @param maxWidth maximum length of result String, must be positive
* @return truncated String, {@code null} if null String input
* @throws IllegalArgumentException If {@code maxWidth} is less than {@code 0}
* @since 3.5
*/
public static String truncate(final String str, final int maxWidth) {
return truncate(str, 0, maxWidth);
}
/**
* <p>Truncates a String. This will turn
* "Now is the time for all good men" into "is the time for all".</p>
*
* <p>Works like {@code truncate(String, int)}, but allows you to specify
* a "left edge" offset.
*
* <p>Specifically:</p>
* <ul>
* <li>If {@code str} is less than {@code maxWidth} characters
* long, return it.</li>
* <li>Else truncate it to {@code substring(str, offset, maxWidth)}.</li>
* <li>If {@code maxWidth} is less than {@code 0}, throw an
* {@code IllegalArgumentException}.</li>
* <li>If {@code offset} is less than {@code 0}, throw an
* {@code IllegalArgumentException}.</li>
* <li>In no case will it return a String of length greater than
* {@code maxWidth}.</li>
* </ul>
*
* <pre>
* StringUtils.truncate(null, 0, 0) = null
* StringUtils.truncate(null, 2, 4) = null
* StringUtils.truncate("", 0, 10) = ""
* StringUtils.truncate("", 2, 10) = ""
* StringUtils.truncate("abcdefghij", 0, 3) = "abc"
* StringUtils.truncate("abcdefghij", 5, 6) = "fghij"
* StringUtils.truncate("raspberry peach", 10, 15) = "peach"
* StringUtils.truncate("abcdefghijklmno", 0, 10) = "abcdefghij"
* StringUtils.truncate("abcdefghijklmno", -1, 10) = throws an IllegalArgumentException
* StringUtils.truncate("abcdefghijklmno", Integer.MIN_VALUE, 10) = throws an IllegalArgumentException
* StringUtils.truncate("abcdefghijklmno", Integer.MIN_VALUE, Integer.MAX_VALUE) = throws an IllegalArgumentException
* StringUtils.truncate("abcdefghijklmno", 0, Integer.MAX_VALUE) = "abcdefghijklmno"
* StringUtils.truncate("abcdefghijklmno", 1, 10) = "bcdefghijk"
* StringUtils.truncate("abcdefghijklmno", 2, 10) = "cdefghijkl"
* StringUtils.truncate("abcdefghijklmno", 3, 10) = "defghijklm"
* StringUtils.truncate("abcdefghijklmno", 4, 10) = "efghijklmn"
* StringUtils.truncate("abcdefghijklmno", 5, 10) = "fghijklmno"
* StringUtils.truncate("abcdefghijklmno", 5, 5) = "fghij"
* StringUtils.truncate("abcdefghijklmno", 5, 3) = "fgh"
* StringUtils.truncate("abcdefghijklmno", 10, 3) = "klm"
* StringUtils.truncate("abcdefghijklmno", 10, Integer.MAX_VALUE) = "klmno"
* StringUtils.truncate("abcdefghijklmno", 13, 1) = "n"
* StringUtils.truncate("abcdefghijklmno", 13, Integer.MAX_VALUE) = "no"
* StringUtils.truncate("abcdefghijklmno", 14, 1) = "o"
* StringUtils.truncate("abcdefghijklmno", 14, Integer.MAX_VALUE) = "o"
* StringUtils.truncate("abcdefghijklmno", 15, 1) = ""
* StringUtils.truncate("abcdefghijklmno", 15, Integer.MAX_VALUE) = ""
* StringUtils.truncate("abcdefghijklmno", Integer.MAX_VALUE, Integer.MAX_VALUE) = ""
* StringUtils.truncate("abcdefghij", 3, -1) = throws an IllegalArgumentException
* StringUtils.truncate("abcdefghij", -2, 4) = throws an IllegalArgumentException
* </pre>
*
* @param str the String to truncate, may be null
* @param offset left edge of source String
* @param maxWidth maximum length of result String, must be positive
* @return truncated String, {@code null} if null String input
* @throws IllegalArgumentException If {@code offset} or {@code maxWidth} is less than {@code 0}
* @since 3.5
*/
public static String truncate(final String str, final int offset, final int maxWidth) {
if (offset < 0) {
throw new IllegalArgumentException("offset cannot be negative");
}
if (maxWidth < 0) {
throw new IllegalArgumentException("maxWith cannot be negative");
}
if (str == null) {
return null;
}
if (offset > str.length()) {
return EMPTY;
}
if (str.length() > maxWidth) {
final int ix = offset + maxWidth > str.length() ? str.length() : offset + maxWidth;
return str.substring(offset, ix);
}
return str.substring(offset);
}
/**
* <p>Uncapitalizes a String, changing the first character to lower case as
* per {@link Character#toLowerCase(int)}. No other characters are changed.</p>
*
* <p>For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#uncapitalize(String)}.
* A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.uncapitalize(null) = null
* StringUtils.uncapitalize("") = ""
* StringUtils.uncapitalize("cat") = "cat"
* StringUtils.uncapitalize("Cat") = "cat"
* StringUtils.uncapitalize("CAT") = "cAT"
* </pre>
*
* @param str the String to uncapitalize, may be null
* @return the uncapitalized String, {@code null} if null String input
* @see org.apache.commons.lang3.text.WordUtils#uncapitalize(String)
* @see #capitalize(String)
* @since 2.0
*/
public static String uncapitalize(final String str) {
final int strLen = length(str);
if (strLen == 0) {
return str;
}
final int firstCodepoint = str.codePointAt(0);
final int newCodePoint = Character.toLowerCase(firstCodepoint);
if (firstCodepoint == newCodePoint) {
// already capitalized
return str;
}
final int newCodePoints[] = new int[strLen]; // cannot be longer than the char array
int outOffset = 0;
newCodePoints[outOffset++] = newCodePoint; // copy the first codepoint
for (int inOffset = Character.charCount(firstCodepoint); inOffset < strLen; ) {
final int codepoint = str.codePointAt(inOffset);
newCodePoints[outOffset++] = codepoint; // copy the remaining ones
inOffset += Character.charCount(codepoint);
}
return new String(newCodePoints, 0, outOffset);
}
/**
* <p>
* Unwraps a given string from a character.
* </p>
*
* <pre>
* StringUtils.unwrap(null, null) = null
* StringUtils.unwrap(null, '\0') = null
* StringUtils.unwrap(null, '1') = null
* StringUtils.unwrap("a", 'a') = "a"
* StringUtils.unwrap("aa", 'a') = ""
* StringUtils.unwrap("\'abc\'", '\'') = "abc"
* StringUtils.unwrap("AABabcBAA", 'A') = "ABabcBA"
* StringUtils.unwrap("A", '#') = "A"
* StringUtils.unwrap("#A", '#') = "#A"
* StringUtils.unwrap("A#", '#') = "A#"
* </pre>
*
* @param str
* the String to be unwrapped, can be null
* @param wrapChar
* the character used to unwrap
* @return unwrapped String or the original string
* if it is not quoted properly with the wrapChar
* @since 3.6
*/
public static String unwrap(final String str, final char wrapChar) {
if (isEmpty(str) || wrapChar == CharUtils.NUL || str.length() == 1) {
return str;
}
if (str.charAt(0) == wrapChar && str.charAt(str.length() - 1) == wrapChar) {
final int startIndex = 0;
final int endIndex = str.length() - 1;
return str.substring(startIndex + 1, endIndex);
}
return str;
}
/**
* <p>
* Unwraps a given string from anther string.
* </p>
*
* <pre>
* StringUtils.unwrap(null, null) = null
* StringUtils.unwrap(null, "") = null
* StringUtils.unwrap(null, "1") = null
* StringUtils.unwrap("a", "a") = "a"
* StringUtils.unwrap("aa", "a") = ""
* StringUtils.unwrap("\'abc\'", "\'") = "abc"
* StringUtils.unwrap("\"abc\"", "\"") = "abc"
* StringUtils.unwrap("AABabcBAA", "AA") = "BabcB"
* StringUtils.unwrap("A", "#") = "A"
* StringUtils.unwrap("#A", "#") = "#A"
* StringUtils.unwrap("A#", "#") = "A#"
* </pre>
*
* @param str
* the String to be unwrapped, can be null
* @param wrapToken
* the String used to unwrap
* @return unwrapped String or the original string
* if it is not quoted properly with the wrapToken
* @since 3.6
*/
public static String unwrap(final String str, final String wrapToken) {
if (isEmpty(str) || isEmpty(wrapToken) || str.length() == 1) {
return str;
}
if (startsWith(str, wrapToken) && endsWith(str, wrapToken)) {
final int startIndex = str.indexOf(wrapToken);
final int endIndex = str.lastIndexOf(wrapToken);
final int wrapLength = wrapToken.length();
if (startIndex != -1 && endIndex != -1) {
return str.substring(startIndex + wrapLength, endIndex);
}
}
return str;
}
// Case conversion
//-----------------------------------------------------------------------
/**
* <p>Converts a String to upper case as per {@link String#toUpperCase()}.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.upperCase(null) = null
* StringUtils.upperCase("") = ""
* StringUtils.upperCase("aBc") = "ABC"
* </pre>
*
* <p><strong>Note:</strong> As described in the documentation for {@link String#toUpperCase()},
* the result of this method is affected by the current locale.
* For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}
* should be used with a specific locale (e.g. {@link Locale#ENGLISH}).</p>
*
* @param str the String to upper case, may be null
* @return the upper cased String, {@code null} if null String input
*/
public static String upperCase(final String str) {
if (str == null) {
return null;
}
return str.toUpperCase();
}
/**
* <p>Converts a String to upper case as per {@link String#toUpperCase(Locale)}.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.upperCase(null, Locale.ENGLISH) = null
* StringUtils.upperCase("", Locale.ENGLISH) = ""
* StringUtils.upperCase("aBc", Locale.ENGLISH) = "ABC"
* </pre>
*
* @param str the String to upper case, may be null
* @param locale the locale that defines the case transformation rules, must not be null
* @return the upper cased String, {@code null} if null String input
* @since 2.5
*/
public static String upperCase(final String str, final Locale locale) {
if (str == null) {
return null;
}
return str.toUpperCase(locale);
}
/**
* Returns the string representation of the {@code char} array or null.
*
* @param value the character array.
* @return a String or null
* @see String#valueOf(char[])
* @since 3.9
*/
public static String valueOf(final char[] value) {
return value == null ? null : String.valueOf(value);
}
/**
* <p>
* Wraps a string with a char.
* </p>
*
* <pre>
* StringUtils.wrap(null, *) = null
* StringUtils.wrap("", *) = ""
* StringUtils.wrap("ab", '\0') = "ab"
* StringUtils.wrap("ab", 'x') = "xabx"
* StringUtils.wrap("ab", '\'') = "'ab'"
* StringUtils.wrap("\"ab\"", '\"') = "\"\"ab\"\""
* </pre>
*
* @param str
* the string to be wrapped, may be {@code null}
* @param wrapWith
* the char that will wrap {@code str}
* @return the wrapped string, or {@code null} if {@code str==null}
* @since 3.4
*/
public static String wrap(final String str, final char wrapWith) {
if (isEmpty(str) || wrapWith == CharUtils.NUL) {
return str;
}
return wrapWith + str + wrapWith;
}
/**
* <p>
* Wraps a String with another String.
* </p>
*
* <p>
* A {@code null} input String returns {@code null}.
* </p>
*
* <pre>
* StringUtils.wrap(null, *) = null
* StringUtils.wrap("", *) = ""
* StringUtils.wrap("ab", null) = "ab"
* StringUtils.wrap("ab", "x") = "xabx"
* StringUtils.wrap("ab", "\"") = "\"ab\""
* StringUtils.wrap("\"ab\"", "\"") = "\"\"ab\"\""
* StringUtils.wrap("ab", "'") = "'ab'"
* StringUtils.wrap("'abcd'", "'") = "''abcd''"
* StringUtils.wrap("\"abcd\"", "'") = "'\"abcd\"'"
* StringUtils.wrap("'abcd'", "\"") = "\"'abcd'\""
* </pre>
*
* @param str
* the String to be wrapper, may be null
* @param wrapWith
* the String that will wrap str
* @return wrapped String, {@code null} if null String input
* @since 3.4
*/
public static String wrap(final String str, final String wrapWith) {
if (isEmpty(str) || isEmpty(wrapWith)) {
return str;
}
return wrapWith.concat(str).concat(wrapWith);
}
/**
* <p>
* Wraps a string with a char if that char is missing from the start or end of the given string.
* </p>
*
* <p>A new {@code String} will not be created if {@code str} is already wrapped.</p>
*
* <pre>
* StringUtils.wrapIfMissing(null, *) = null
* StringUtils.wrapIfMissing("", *) = ""
* StringUtils.wrapIfMissing("ab", '\0') = "ab"
* StringUtils.wrapIfMissing("ab", 'x') = "xabx"
* StringUtils.wrapIfMissing("ab", '\'') = "'ab'"
* StringUtils.wrapIfMissing("\"ab\"", '\"') = "\"ab\""
* StringUtils.wrapIfMissing("/", '/') = "/"
* StringUtils.wrapIfMissing("a/b/c", '/') = "/a/b/c/"
* StringUtils.wrapIfMissing("/a/b/c", '/') = "/a/b/c/"
* StringUtils.wrapIfMissing("a/b/c/", '/') = "/a/b/c/"
* </pre>
*
* @param str
* the string to be wrapped, may be {@code null}
* @param wrapWith
* the char that will wrap {@code str}
* @return the wrapped string, or {@code null} if {@code str==null}
* @since 3.5
*/
public static String wrapIfMissing(final String str, final char wrapWith) {
if (isEmpty(str) || wrapWith == CharUtils.NUL) {
return str;
}
final boolean wrapStart = str.charAt(0) != wrapWith;
final boolean wrapEnd = str.charAt(str.length() - 1) != wrapWith;
if (!wrapStart && !wrapEnd) {
return str;
}
final StringBuilder builder = new StringBuilder(str.length() + 2);
if (wrapStart) {
builder.append(wrapWith);
}
builder.append(str);
if (wrapEnd) {
builder.append(wrapWith);
}
return builder.toString();
}
/**
* <p>
* Wraps a string with a string if that string is missing from the start or end of the given string.
* </p>
*
* <p>A new {@code String} will not be created if {@code str} is already wrapped.</p>
*
* <pre>
* StringUtils.wrapIfMissing(null, *) = null
* StringUtils.wrapIfMissing("", *) = ""
* StringUtils.wrapIfMissing("ab", null) = "ab"
* StringUtils.wrapIfMissing("ab", "x") = "xabx"
* StringUtils.wrapIfMissing("ab", "\"") = "\"ab\""
* StringUtils.wrapIfMissing("\"ab\"", "\"") = "\"ab\""
* StringUtils.wrapIfMissing("ab", "'") = "'ab'"
* StringUtils.wrapIfMissing("'abcd'", "'") = "'abcd'"
* StringUtils.wrapIfMissing("\"abcd\"", "'") = "'\"abcd\"'"
* StringUtils.wrapIfMissing("'abcd'", "\"") = "\"'abcd'\""
* StringUtils.wrapIfMissing("/", "/") = "/"
* StringUtils.wrapIfMissing("a/b/c", "/") = "/a/b/c/"
* StringUtils.wrapIfMissing("/a/b/c", "/") = "/a/b/c/"
* StringUtils.wrapIfMissing("a/b/c/", "/") = "/a/b/c/"
* </pre>
*
* @param str
* the string to be wrapped, may be {@code null}
* @param wrapWith
* the string that will wrap {@code str}
* @return the wrapped string, or {@code null} if {@code str==null}
* @since 3.5
*/
public static String wrapIfMissing(final String str, final String wrapWith) {
if (isEmpty(str) || isEmpty(wrapWith)) {
return str;
}
final boolean wrapStart = !str.startsWith(wrapWith);
final boolean wrapEnd = !str.endsWith(wrapWith);
if (!wrapStart && !wrapEnd) {
return str;
}
final StringBuilder builder = new StringBuilder(str.length() + wrapWith.length() + wrapWith.length());
if (wrapStart) {
builder.append(wrapWith);
}
builder.append(str);
if (wrapEnd) {
builder.append(wrapWith);
}
return builder.toString();
}
/**
* <p>{@code StringUtils} instances should NOT be constructed in
* standard programming. Instead, the class should be used as
* {@code StringUtils.trim(" foo ");}.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean
* instance to operate.</p>
*/
public StringUtils() {
super();
}
}
|
src/main/java/org/apache/commons/lang3/StringUtils.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.commons.lang3;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.regex.Pattern;
/**
* <p>Operations on {@link java.lang.String} that are
* {@code null} safe.</p>
*
* <ul>
* <li><b>IsEmpty/IsBlank</b>
* - checks if a String contains text</li>
* <li><b>Trim/Strip</b>
* - removes leading and trailing whitespace</li>
* <li><b>Equals/Compare</b>
* - compares two strings null-safe</li>
* <li><b>startsWith</b>
* - check if a String starts with a prefix null-safe</li>
* <li><b>endsWith</b>
* - check if a String ends with a suffix null-safe</li>
* <li><b>IndexOf/LastIndexOf/Contains</b>
* - null-safe index-of checks
* <li><b>IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut</b>
* - index-of any of a set of Strings</li>
* <li><b>ContainsOnly/ContainsNone/ContainsAny</b>
* - does String contains only/none/any of these characters</li>
* <li><b>Substring/Left/Right/Mid</b>
* - null-safe substring extractions</li>
* <li><b>SubstringBefore/SubstringAfter/SubstringBetween</b>
* - substring extraction relative to other strings</li>
* <li><b>Split/Join</b>
* - splits a String into an array of substrings and vice versa</li>
* <li><b>Remove/Delete</b>
* - removes part of a String</li>
* <li><b>Replace/Overlay</b>
* - Searches a String and replaces one String with another</li>
* <li><b>Chomp/Chop</b>
* - removes the last part of a String</li>
* <li><b>AppendIfMissing</b>
* - appends a suffix to the end of the String if not present</li>
* <li><b>PrependIfMissing</b>
* - prepends a prefix to the start of the String if not present</li>
* <li><b>LeftPad/RightPad/Center/Repeat</b>
* - pads a String</li>
* <li><b>UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize</b>
* - changes the case of a String</li>
* <li><b>CountMatches</b>
* - counts the number of occurrences of one String in another</li>
* <li><b>IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable</b>
* - checks the characters in a String</li>
* <li><b>DefaultString</b>
* - protects against a null input String</li>
* <li><b>Rotate</b>
* - rotate (circular shift) a String</li>
* <li><b>Reverse/ReverseDelimited</b>
* - reverses a String</li>
* <li><b>Abbreviate</b>
* - abbreviates a string using ellipsis or another given String</li>
* <li><b>Difference</b>
* - compares Strings and reports on their differences</li>
* <li><b>LevenshteinDistance</b>
* - the number of changes needed to change one String into another</li>
* </ul>
*
* <p>The {@code StringUtils} class defines certain words related to
* String handling.</p>
*
* <ul>
* <li>null - {@code null}</li>
* <li>empty - a zero-length string ({@code ""})</li>
* <li>space - the space character ({@code ' '}, char 32)</li>
* <li>whitespace - the characters defined by {@link Character#isWhitespace(char)}</li>
* <li>trim - the characters <= 32 as in {@link String#trim()}</li>
* </ul>
*
* <p>{@code StringUtils} handles {@code null} input Strings quietly.
* That is to say that a {@code null} input will return {@code null}.
* Where a {@code boolean} or {@code int} is being returned
* details vary by method.</p>
*
* <p>A side effect of the {@code null} handling is that a
* {@code NullPointerException} should be considered a bug in
* {@code StringUtils}.</p>
*
* <p>Methods in this class give sample code to explain their operation.
* The symbol {@code *} is used to indicate any input including {@code null}.</p>
*
* <p>#ThreadSafe#</p>
* @see java.lang.String
* @since 1.0
*/
//@Immutable
public class StringUtils {
private static final int STRING_BUILDER_SIZE = 256;
// Performance testing notes (JDK 1.4, Jul03, scolebourne)
// Whitespace:
// Character.isWhitespace() is faster than WHITESPACE.indexOf()
// where WHITESPACE is a string of all whitespace characters
//
// Character access:
// String.charAt(n) versus toCharArray(), then array[n]
// String.charAt(n) is about 15% worse for a 10K string
// They are about equal for a length 50 string
// String.charAt(n) is about 4 times better for a length 3 string
// String.charAt(n) is best bet overall
//
// Append:
// String.concat about twice as fast as StringBuffer.append
// (not sure who tested this)
/**
* A String for a space character.
*
* @since 3.2
*/
public static final String SPACE = " ";
/**
* The empty String {@code ""}.
* @since 2.0
*/
public static final String EMPTY = "";
/**
* A String for linefeed LF ("\n").
*
* @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6">JLF: Escape Sequences
* for Character and String Literals</a>
* @since 3.2
*/
public static final String LF = "\n";
/**
* A String for carriage return CR ("\r").
*
* @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6">JLF: Escape Sequences
* for Character and String Literals</a>
* @since 3.2
*/
public static final String CR = "\r";
/**
* Represents a failed index search.
* @since 2.1
*/
public static final int INDEX_NOT_FOUND = -1;
/**
* <p>The maximum size to which the padding constant(s) can expand.</p>
*/
private static final int PAD_LIMIT = 8192;
// Abbreviating
//-----------------------------------------------------------------------
/**
* <p>Abbreviates a String using ellipses. This will turn
* "Now is the time for all good men" into "Now is the time for..."</p>
*
* <p>Specifically:</p>
* <ul>
* <li>If the number of characters in {@code str} is less than or equal to
* {@code maxWidth}, return {@code str}.</li>
* <li>Else abbreviate it to {@code (substring(str, 0, max-3) + "...")}.</li>
* <li>If {@code maxWidth} is less than {@code 4}, throw an
* {@code IllegalArgumentException}.</li>
* <li>In no case will it return a String of length greater than
* {@code maxWidth}.</li>
* </ul>
*
* <pre>
* StringUtils.abbreviate(null, *) = null
* StringUtils.abbreviate("", 4) = ""
* StringUtils.abbreviate("abcdefg", 6) = "abc..."
* StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
* StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
* StringUtils.abbreviate("abcdefg", 4) = "a..."
* StringUtils.abbreviate("abcdefg", 3) = IllegalArgumentException
* </pre>
*
* @param str the String to check, may be null
* @param maxWidth maximum length of result String, must be at least 4
* @return abbreviated String, {@code null} if null String input
* @throws IllegalArgumentException if the width is too small
* @since 2.0
*/
public static String abbreviate(final String str, final int maxWidth) {
return abbreviate(str, "...", 0, maxWidth);
}
/**
* <p>Abbreviates a String using ellipses. This will turn
* "Now is the time for all good men" into "...is the time for..."</p>
*
* <p>Works like {@code abbreviate(String, int)}, but allows you to specify
* a "left edge" offset. Note that this left edge is not necessarily going to
* be the leftmost character in the result, or the first character following the
* ellipses, but it will appear somewhere in the result.
*
* <p>In no case will it return a String of length greater than
* {@code maxWidth}.</p>
*
* <pre>
* StringUtils.abbreviate(null, *, *) = null
* StringUtils.abbreviate("", 0, 4) = ""
* StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 0, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 1, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 4, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 5, 10) = "...fghi..."
* StringUtils.abbreviate("abcdefghijklmno", 6, 10) = "...ghij..."
* StringUtils.abbreviate("abcdefghijklmno", 8, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghij", 0, 3) = IllegalArgumentException
* StringUtils.abbreviate("abcdefghij", 5, 6) = IllegalArgumentException
* </pre>
*
* @param str the String to check, may be null
* @param offset left edge of source String
* @param maxWidth maximum length of result String, must be at least 4
* @return abbreviated String, {@code null} if null String input
* @throws IllegalArgumentException if the width is too small
* @since 2.0
*/
public static String abbreviate(final String str, final int offset, final int maxWidth) {
return abbreviate(str, "...", offset, maxWidth);
}
/**
* <p>Abbreviates a String using another given String as replacement marker. This will turn
* "Now is the time for all good men" into "Now is the time for..." if "..." was defined
* as the replacement marker.</p>
*
* <p>Specifically:</p>
* <ul>
* <li>If the number of characters in {@code str} is less than or equal to
* {@code maxWidth}, return {@code str}.</li>
* <li>Else abbreviate it to {@code (substring(str, 0, max-abbrevMarker.length) + abbrevMarker)}.</li>
* <li>If {@code maxWidth} is less than {@code abbrevMarker.length + 1}, throw an
* {@code IllegalArgumentException}.</li>
* <li>In no case will it return a String of length greater than
* {@code maxWidth}.</li>
* </ul>
*
* <pre>
* StringUtils.abbreviate(null, "...", *) = null
* StringUtils.abbreviate("abcdefg", null, *) = "abcdefg"
* StringUtils.abbreviate("", "...", 4) = ""
* StringUtils.abbreviate("abcdefg", ".", 5) = "abcd."
* StringUtils.abbreviate("abcdefg", ".", 7) = "abcdefg"
* StringUtils.abbreviate("abcdefg", ".", 8) = "abcdefg"
* StringUtils.abbreviate("abcdefg", "..", 4) = "ab.."
* StringUtils.abbreviate("abcdefg", "..", 3) = "a.."
* StringUtils.abbreviate("abcdefg", "..", 2) = IllegalArgumentException
* StringUtils.abbreviate("abcdefg", "...", 3) = IllegalArgumentException
* </pre>
*
* @param str the String to check, may be null
* @param abbrevMarker the String used as replacement marker
* @param maxWidth maximum length of result String, must be at least {@code abbrevMarker.length + 1}
* @return abbreviated String, {@code null} if null String input
* @throws IllegalArgumentException if the width is too small
* @since 3.6
*/
public static String abbreviate(final String str, final String abbrevMarker, final int maxWidth) {
return abbreviate(str, abbrevMarker, 0, maxWidth);
}
/**
* <p>Abbreviates a String using a given replacement marker. This will turn
* "Now is the time for all good men" into "...is the time for..." if "..." was defined
* as the replacement marker.</p>
*
* <p>Works like {@code abbreviate(String, String, int)}, but allows you to specify
* a "left edge" offset. Note that this left edge is not necessarily going to
* be the leftmost character in the result, or the first character following the
* replacement marker, but it will appear somewhere in the result.
*
* <p>In no case will it return a String of length greater than {@code maxWidth}.</p>
*
* <pre>
* StringUtils.abbreviate(null, null, *, *) = null
* StringUtils.abbreviate("abcdefghijklmno", null, *, *) = "abcdefghijklmno"
* StringUtils.abbreviate("", "...", 0, 4) = ""
* StringUtils.abbreviate("abcdefghijklmno", "---", -1, 10) = "abcdefg---"
* StringUtils.abbreviate("abcdefghijklmno", ",", 0, 10) = "abcdefghi,"
* StringUtils.abbreviate("abcdefghijklmno", ",", 1, 10) = "abcdefghi,"
* StringUtils.abbreviate("abcdefghijklmno", ",", 2, 10) = "abcdefghi,"
* StringUtils.abbreviate("abcdefghijklmno", "::", 4, 10) = "::efghij::"
* StringUtils.abbreviate("abcdefghijklmno", "...", 6, 10) = "...ghij..."
* StringUtils.abbreviate("abcdefghijklmno", "*", 9, 10) = "*ghijklmno"
* StringUtils.abbreviate("abcdefghijklmno", "'", 10, 10) = "'ghijklmno"
* StringUtils.abbreviate("abcdefghijklmno", "!", 12, 10) = "!ghijklmno"
* StringUtils.abbreviate("abcdefghij", "abra", 0, 4) = IllegalArgumentException
* StringUtils.abbreviate("abcdefghij", "...", 5, 6) = IllegalArgumentException
* </pre>
*
* @param str the String to check, may be null
* @param abbrevMarker the String used as replacement marker
* @param offset left edge of source String
* @param maxWidth maximum length of result String, must be at least 4
* @return abbreviated String, {@code null} if null String input
* @throws IllegalArgumentException if the width is too small
* @since 3.6
*/
public static String abbreviate(final String str, final String abbrevMarker, int offset, final int maxWidth) {
if (isEmpty(str) && isEmpty(abbrevMarker)) {
return str;
} else if (isNotEmpty(str) && EMPTY.equals(abbrevMarker) && maxWidth > 0) {
return str.substring(0, maxWidth);
} else if (isEmpty(str) || isEmpty(abbrevMarker)) {
return str;
}
final int abbrevMarkerLength = abbrevMarker.length();
final int minAbbrevWidth = abbrevMarkerLength + 1;
final int minAbbrevWidthOffset = abbrevMarkerLength + abbrevMarkerLength + 1;
if (maxWidth < minAbbrevWidth) {
throw new IllegalArgumentException(String.format("Minimum abbreviation width is %d", minAbbrevWidth));
}
if (str.length() <= maxWidth) {
return str;
}
if (offset > str.length()) {
offset = str.length();
}
if (str.length() - offset < maxWidth - abbrevMarkerLength) {
offset = str.length() - (maxWidth - abbrevMarkerLength);
}
if (offset <= abbrevMarkerLength+1) {
return str.substring(0, maxWidth - abbrevMarkerLength) + abbrevMarker;
}
if (maxWidth < minAbbrevWidthOffset) {
throw new IllegalArgumentException(String.format("Minimum abbreviation width with offset is %d", minAbbrevWidthOffset));
}
if (offset + maxWidth - abbrevMarkerLength < str.length()) {
return abbrevMarker + abbreviate(str.substring(offset), abbrevMarker, maxWidth - abbrevMarkerLength);
}
return abbrevMarker + str.substring(str.length() - (maxWidth - abbrevMarkerLength));
}
/**
* <p>Abbreviates a String to the length passed, replacing the middle characters with the supplied
* replacement String.</p>
*
* <p>This abbreviation only occurs if the following criteria is met:</p>
* <ul>
* <li>Neither the String for abbreviation nor the replacement String are null or empty </li>
* <li>The length to truncate to is less than the length of the supplied String</li>
* <li>The length to truncate to is greater than 0</li>
* <li>The abbreviated String will have enough room for the length supplied replacement String
* and the first and last characters of the supplied String for abbreviation</li>
* </ul>
* <p>Otherwise, the returned String will be the same as the supplied String for abbreviation.
* </p>
*
* <pre>
* StringUtils.abbreviateMiddle(null, null, 0) = null
* StringUtils.abbreviateMiddle("abc", null, 0) = "abc"
* StringUtils.abbreviateMiddle("abc", ".", 0) = "abc"
* StringUtils.abbreviateMiddle("abc", ".", 3) = "abc"
* StringUtils.abbreviateMiddle("abcdef", ".", 4) = "ab.f"
* </pre>
*
* @param str the String to abbreviate, may be null
* @param middle the String to replace the middle characters with, may be null
* @param length the length to abbreviate {@code str} to.
* @return the abbreviated String if the above criteria is met, or the original String supplied for abbreviation.
* @since 2.5
*/
public static String abbreviateMiddle(final String str, final String middle, final int length) {
if (isEmpty(str) || isEmpty(middle)) {
return str;
}
if (length >= str.length() || length < middle.length()+2) {
return str;
}
final int targetSting = length-middle.length();
final int startOffset = targetSting/2+targetSting%2;
final int endOffset = str.length()-targetSting/2;
return str.substring(0, startOffset) +
middle +
str.substring(endOffset);
}
/**
* Appends the suffix to the end of the string if the string does not
* already end with the suffix.
*
* @param str The string.
* @param suffix The suffix to append to the end of the string.
* @param ignoreCase Indicates whether the compare should ignore case.
* @param suffixes Additional suffixes that are valid terminators (optional).
*
* @return A new String if suffix was appended, the same string otherwise.
*/
private static String appendIfMissing(final String str, final CharSequence suffix, final boolean ignoreCase, final CharSequence... suffixes) {
if (str == null || isEmpty(suffix) || endsWith(str, suffix, ignoreCase)) {
return str;
}
if (ArrayUtils.isNotEmpty(suffixes)) {
for (final CharSequence s : suffixes) {
if (endsWith(str, s, ignoreCase)) {
return str;
}
}
}
return str + suffix.toString();
}
/**
* Appends the suffix to the end of the string if the string does not
* already end with any of the suffixes.
*
* <pre>
* StringUtils.appendIfMissing(null, null) = null
* StringUtils.appendIfMissing("abc", null) = "abc"
* StringUtils.appendIfMissing("", "xyz") = "xyz"
* StringUtils.appendIfMissing("abc", "xyz") = "abcxyz"
* StringUtils.appendIfMissing("abcxyz", "xyz") = "abcxyz"
* StringUtils.appendIfMissing("abcXYZ", "xyz") = "abcXYZxyz"
* </pre>
* <p>With additional suffixes,</p>
* <pre>
* StringUtils.appendIfMissing(null, null, null) = null
* StringUtils.appendIfMissing("abc", null, null) = "abc"
* StringUtils.appendIfMissing("", "xyz", null) = "xyz"
* StringUtils.appendIfMissing("abc", "xyz", new CharSequence[]{null}) = "abcxyz"
* StringUtils.appendIfMissing("abc", "xyz", "") = "abc"
* StringUtils.appendIfMissing("abc", "xyz", "mno") = "abcxyz"
* StringUtils.appendIfMissing("abcxyz", "xyz", "mno") = "abcxyz"
* StringUtils.appendIfMissing("abcmno", "xyz", "mno") = "abcmno"
* StringUtils.appendIfMissing("abcXYZ", "xyz", "mno") = "abcXYZxyz"
* StringUtils.appendIfMissing("abcMNO", "xyz", "mno") = "abcMNOxyz"
* </pre>
*
* @param str The string.
* @param suffix The suffix to append to the end of the string.
* @param suffixes Additional suffixes that are valid terminators.
*
* @return A new String if suffix was appended, the same string otherwise.
*
* @since 3.2
*/
public static String appendIfMissing(final String str, final CharSequence suffix, final CharSequence... suffixes) {
return appendIfMissing(str, suffix, false, suffixes);
}
/**
* Appends the suffix to the end of the string if the string does not
* already end, case insensitive, with any of the suffixes.
*
* <pre>
* StringUtils.appendIfMissingIgnoreCase(null, null) = null
* StringUtils.appendIfMissingIgnoreCase("abc", null) = "abc"
* StringUtils.appendIfMissingIgnoreCase("", "xyz") = "xyz"
* StringUtils.appendIfMissingIgnoreCase("abc", "xyz") = "abcxyz"
* StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz") = "abcxyz"
* StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz") = "abcXYZ"
* </pre>
* <p>With additional suffixes,</p>
* <pre>
* StringUtils.appendIfMissingIgnoreCase(null, null, null) = null
* StringUtils.appendIfMissingIgnoreCase("abc", null, null) = "abc"
* StringUtils.appendIfMissingIgnoreCase("", "xyz", null) = "xyz"
* StringUtils.appendIfMissingIgnoreCase("abc", "xyz", new CharSequence[]{null}) = "abcxyz"
* StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "") = "abc"
* StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "mno") = "abcxyz"
* StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz", "mno") = "abcxyz"
* StringUtils.appendIfMissingIgnoreCase("abcmno", "xyz", "mno") = "abcmno"
* StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz", "mno") = "abcXYZ"
* StringUtils.appendIfMissingIgnoreCase("abcMNO", "xyz", "mno") = "abcMNO"
* </pre>
*
* @param str The string.
* @param suffix The suffix to append to the end of the string.
* @param suffixes Additional suffixes that are valid terminators.
*
* @return A new String if suffix was appended, the same string otherwise.
*
* @since 3.2
*/
public static String appendIfMissingIgnoreCase(final String str, final CharSequence suffix, final CharSequence... suffixes) {
return appendIfMissing(str, suffix, true, suffixes);
}
/**
* <p>Capitalizes a String changing the first character to title case as
* per {@link Character#toTitleCase(int)}. No other characters are changed.</p>
*
* <p>For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#capitalize(String)}.
* A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.capitalize(null) = null
* StringUtils.capitalize("") = ""
* StringUtils.capitalize("cat") = "Cat"
* StringUtils.capitalize("cAt") = "CAt"
* StringUtils.capitalize("'cat'") = "'cat'"
* </pre>
*
* @param str the String to capitalize, may be null
* @return the capitalized String, {@code null} if null String input
* @see org.apache.commons.lang3.text.WordUtils#capitalize(String)
* @see #uncapitalize(String)
* @since 2.0
*/
public static String capitalize(final String str) {
final int strLen = length(str);
if (strLen == 0) {
return str;
}
final int firstCodepoint = str.codePointAt(0);
final int newCodePoint = Character.toTitleCase(firstCodepoint);
if (firstCodepoint == newCodePoint) {
// already capitalized
return str;
}
final int newCodePoints[] = new int[strLen]; // cannot be longer than the char array
int outOffset = 0;
newCodePoints[outOffset++] = newCodePoint; // copy the first codepoint
for (int inOffset = Character.charCount(firstCodepoint); inOffset < strLen; ) {
final int codepoint = str.codePointAt(inOffset);
newCodePoints[outOffset++] = codepoint; // copy the remaining ones
inOffset += Character.charCount(codepoint);
}
return new String(newCodePoints, 0, outOffset);
}
// Centering
//-----------------------------------------------------------------------
/**
* <p>Centers a String in a larger String of size {@code size}
* using the space character (' ').</p>
*
* <p>If the size is less than the String length, the String is returned.
* A {@code null} String returns {@code null}.
* A negative size is treated as zero.</p>
*
* <p>Equivalent to {@code center(str, size, " ")}.</p>
*
* <pre>
* StringUtils.center(null, *) = null
* StringUtils.center("", 4) = " "
* StringUtils.center("ab", -1) = "ab"
* StringUtils.center("ab", 4) = " ab "
* StringUtils.center("abcd", 2) = "abcd"
* StringUtils.center("a", 4) = " a "
* </pre>
*
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @return centered String, {@code null} if null String input
*/
public static String center(final String str, final int size) {
return center(str, size, ' ');
}
/**
* <p>Centers a String in a larger String of size {@code size}.
* Uses a supplied character as the value to pad the String with.</p>
*
* <p>If the size is less than the String length, the String is returned.
* A {@code null} String returns {@code null}.
* A negative size is treated as zero.</p>
*
* <pre>
* StringUtils.center(null, *, *) = null
* StringUtils.center("", 4, ' ') = " "
* StringUtils.center("ab", -1, ' ') = "ab"
* StringUtils.center("ab", 4, ' ') = " ab "
* StringUtils.center("abcd", 2, ' ') = "abcd"
* StringUtils.center("a", 4, ' ') = " a "
* StringUtils.center("a", 4, 'y') = "yayy"
* </pre>
*
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @param padChar the character to pad the new String with
* @return centered String, {@code null} if null String input
* @since 2.0
*/
public static String center(String str, final int size, final char padChar) {
if (str == null || size <= 0) {
return str;
}
final int strLen = str.length();
final int pads = size - strLen;
if (pads <= 0) {
return str;
}
str = leftPad(str, strLen + pads / 2, padChar);
str = rightPad(str, size, padChar);
return str;
}
/**
* <p>Centers a String in a larger String of size {@code size}.
* Uses a supplied String as the value to pad the String with.</p>
*
* <p>If the size is less than the String length, the String is returned.
* A {@code null} String returns {@code null}.
* A negative size is treated as zero.</p>
*
* <pre>
* StringUtils.center(null, *, *) = null
* StringUtils.center("", 4, " ") = " "
* StringUtils.center("ab", -1, " ") = "ab"
* StringUtils.center("ab", 4, " ") = " ab "
* StringUtils.center("abcd", 2, " ") = "abcd"
* StringUtils.center("a", 4, " ") = " a "
* StringUtils.center("a", 4, "yz") = "yayz"
* StringUtils.center("abc", 7, null) = " abc "
* StringUtils.center("abc", 7, "") = " abc "
* </pre>
*
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @param padStr the String to pad the new String with, must not be null or empty
* @return centered String, {@code null} if null String input
* @throws IllegalArgumentException if padStr is {@code null} or empty
*/
public static String center(String str, final int size, String padStr) {
if (str == null || size <= 0) {
return str;
}
if (isEmpty(padStr)) {
padStr = SPACE;
}
final int strLen = str.length();
final int pads = size - strLen;
if (pads <= 0) {
return str;
}
str = leftPad(str, strLen + pads / 2, padStr);
str = rightPad(str, size, padStr);
return str;
}
// Chomping
//-----------------------------------------------------------------------
/**
* <p>Removes one newline from end of a String if it's there,
* otherwise leave it alone. A newline is "{@code \n}",
* "{@code \r}", or "{@code \r\n}".</p>
*
* <p>NOTE: This method changed in 2.0.
* It now more closely matches Perl chomp.</p>
*
* <pre>
* StringUtils.chomp(null) = null
* StringUtils.chomp("") = ""
* StringUtils.chomp("abc \r") = "abc "
* StringUtils.chomp("abc\n") = "abc"
* StringUtils.chomp("abc\r\n") = "abc"
* StringUtils.chomp("abc\r\n\r\n") = "abc\r\n"
* StringUtils.chomp("abc\n\r") = "abc\n"
* StringUtils.chomp("abc\n\rabc") = "abc\n\rabc"
* StringUtils.chomp("\r") = ""
* StringUtils.chomp("\n") = ""
* StringUtils.chomp("\r\n") = ""
* </pre>
*
* @param str the String to chomp a newline from, may be null
* @return String without newline, {@code null} if null String input
*/
public static String chomp(final String str) {
if (isEmpty(str)) {
return str;
}
if (str.length() == 1) {
final char ch = str.charAt(0);
if (ch == CharUtils.CR || ch == CharUtils.LF) {
return EMPTY;
}
return str;
}
int lastIdx = str.length() - 1;
final char last = str.charAt(lastIdx);
if (last == CharUtils.LF) {
if (str.charAt(lastIdx - 1) == CharUtils.CR) {
lastIdx--;
}
} else if (last != CharUtils.CR) {
lastIdx++;
}
return str.substring(0, lastIdx);
}
/**
* <p>Removes {@code separator} from the end of
* {@code str} if it's there, otherwise leave it alone.</p>
*
* <p>NOTE: This method changed in version 2.0.
* It now more closely matches Perl chomp.
* For the previous behavior, use {@link #substringBeforeLast(String, String)}.
* This method uses {@link String#endsWith(String)}.</p>
*
* <pre>
* StringUtils.chomp(null, *) = null
* StringUtils.chomp("", *) = ""
* StringUtils.chomp("foobar", "bar") = "foo"
* StringUtils.chomp("foobar", "baz") = "foobar"
* StringUtils.chomp("foo", "foo") = ""
* StringUtils.chomp("foo ", "foo") = "foo "
* StringUtils.chomp(" foo", "foo") = " "
* StringUtils.chomp("foo", "foooo") = "foo"
* StringUtils.chomp("foo", "") = "foo"
* StringUtils.chomp("foo", null) = "foo"
* </pre>
*
* @param str the String to chomp from, may be null
* @param separator separator String, may be null
* @return String without trailing separator, {@code null} if null String input
* @deprecated This feature will be removed in Lang 4.0, use {@link StringUtils#removeEnd(String, String)} instead
*/
@Deprecated
public static String chomp(final String str, final String separator) {
return removeEnd(str, separator);
}
// Chopping
//-----------------------------------------------------------------------
/**
* <p>Remove the last character from a String.</p>
*
* <p>If the String ends in {@code \r\n}, then remove both
* of them.</p>
*
* <pre>
* StringUtils.chop(null) = null
* StringUtils.chop("") = ""
* StringUtils.chop("abc \r") = "abc "
* StringUtils.chop("abc\n") = "abc"
* StringUtils.chop("abc\r\n") = "abc"
* StringUtils.chop("abc") = "ab"
* StringUtils.chop("abc\nabc") = "abc\nab"
* StringUtils.chop("a") = ""
* StringUtils.chop("\r") = ""
* StringUtils.chop("\n") = ""
* StringUtils.chop("\r\n") = ""
* </pre>
*
* @param str the String to chop last character from, may be null
* @return String without last character, {@code null} if null String input
*/
public static String chop(final String str) {
if (str == null) {
return null;
}
final int strLen = str.length();
if (strLen < 2) {
return EMPTY;
}
final int lastIdx = strLen - 1;
final String ret = str.substring(0, lastIdx);
final char last = str.charAt(lastIdx);
if (last == CharUtils.LF && ret.charAt(lastIdx - 1) == CharUtils.CR) {
return ret.substring(0, lastIdx - 1);
}
return ret;
}
// Compare
//-----------------------------------------------------------------------
/**
* <p>Compare two Strings lexicographically, as per {@link String#compareTo(String)}, returning :</p>
* <ul>
* <li>{@code int = 0}, if {@code str1} is equal to {@code str2} (or both {@code null})</li>
* <li>{@code int < 0}, if {@code str1} is less than {@code str2}</li>
* <li>{@code int > 0}, if {@code str1} is greater than {@code str2}</li>
* </ul>
*
* <p>This is a {@code null} safe version of :</p>
* <blockquote><pre>str1.compareTo(str2)</pre></blockquote>
*
* <p>{@code null} value is considered less than non-{@code null} value.
* Two {@code null} references are considered equal.</p>
*
* <pre>
* StringUtils.compare(null, null) = 0
* StringUtils.compare(null , "a") < 0
* StringUtils.compare("a", null) > 0
* StringUtils.compare("abc", "abc") = 0
* StringUtils.compare("a", "b") < 0
* StringUtils.compare("b", "a") > 0
* StringUtils.compare("a", "B") > 0
* StringUtils.compare("ab", "abc") < 0
* </pre>
*
* @see #compare(String, String, boolean)
* @see String#compareTo(String)
* @param str1 the String to compare from
* @param str2 the String to compare to
* @return < 0, 0, > 0, if {@code str1} is respectively less, equal or greater than {@code str2}
* @since 3.5
*/
public static int compare(final String str1, final String str2) {
return compare(str1, str2, true);
}
/**
* <p>Compare two Strings lexicographically, as per {@link String#compareTo(String)}, returning :</p>
* <ul>
* <li>{@code int = 0}, if {@code str1} is equal to {@code str2} (or both {@code null})</li>
* <li>{@code int < 0}, if {@code str1} is less than {@code str2}</li>
* <li>{@code int > 0}, if {@code str1} is greater than {@code str2}</li>
* </ul>
*
* <p>This is a {@code null} safe version of :</p>
* <blockquote><pre>str1.compareTo(str2)</pre></blockquote>
*
* <p>{@code null} inputs are handled according to the {@code nullIsLess} parameter.
* Two {@code null} references are considered equal.</p>
*
* <pre>
* StringUtils.compare(null, null, *) = 0
* StringUtils.compare(null , "a", true) < 0
* StringUtils.compare(null , "a", false) > 0
* StringUtils.compare("a", null, true) > 0
* StringUtils.compare("a", null, false) < 0
* StringUtils.compare("abc", "abc", *) = 0
* StringUtils.compare("a", "b", *) < 0
* StringUtils.compare("b", "a", *) > 0
* StringUtils.compare("a", "B", *) > 0
* StringUtils.compare("ab", "abc", *) < 0
* </pre>
*
* @see String#compareTo(String)
* @param str1 the String to compare from
* @param str2 the String to compare to
* @param nullIsLess whether consider {@code null} value less than non-{@code null} value
* @return < 0, 0, > 0, if {@code str1} is respectively less, equal ou greater than {@code str2}
* @since 3.5
*/
public static int compare(final String str1, final String str2, final boolean nullIsLess) {
if (str1 == str2) {
return 0;
}
if (str1 == null) {
return nullIsLess ? -1 : 1;
}
if (str2 == null) {
return nullIsLess ? 1 : - 1;
}
return str1.compareTo(str2);
}
/**
* <p>Compare two Strings lexicographically, ignoring case differences,
* as per {@link String#compareToIgnoreCase(String)}, returning :</p>
* <ul>
* <li>{@code int = 0}, if {@code str1} is equal to {@code str2} (or both {@code null})</li>
* <li>{@code int < 0}, if {@code str1} is less than {@code str2}</li>
* <li>{@code int > 0}, if {@code str1} is greater than {@code str2}</li>
* </ul>
*
* <p>This is a {@code null} safe version of :</p>
* <blockquote><pre>str1.compareToIgnoreCase(str2)</pre></blockquote>
*
* <p>{@code null} value is considered less than non-{@code null} value.
* Two {@code null} references are considered equal.
* Comparison is case insensitive.</p>
*
* <pre>
* StringUtils.compareIgnoreCase(null, null) = 0
* StringUtils.compareIgnoreCase(null , "a") < 0
* StringUtils.compareIgnoreCase("a", null) > 0
* StringUtils.compareIgnoreCase("abc", "abc") = 0
* StringUtils.compareIgnoreCase("abc", "ABC") = 0
* StringUtils.compareIgnoreCase("a", "b") < 0
* StringUtils.compareIgnoreCase("b", "a") > 0
* StringUtils.compareIgnoreCase("a", "B") < 0
* StringUtils.compareIgnoreCase("A", "b") < 0
* StringUtils.compareIgnoreCase("ab", "ABC") < 0
* </pre>
*
* @see #compareIgnoreCase(String, String, boolean)
* @see String#compareToIgnoreCase(String)
* @param str1 the String to compare from
* @param str2 the String to compare to
* @return < 0, 0, > 0, if {@code str1} is respectively less, equal ou greater than {@code str2},
* ignoring case differences.
* @since 3.5
*/
public static int compareIgnoreCase(final String str1, final String str2) {
return compareIgnoreCase(str1, str2, true);
}
/**
* <p>Compare two Strings lexicographically, ignoring case differences,
* as per {@link String#compareToIgnoreCase(String)}, returning :</p>
* <ul>
* <li>{@code int = 0}, if {@code str1} is equal to {@code str2} (or both {@code null})</li>
* <li>{@code int < 0}, if {@code str1} is less than {@code str2}</li>
* <li>{@code int > 0}, if {@code str1} is greater than {@code str2}</li>
* </ul>
*
* <p>This is a {@code null} safe version of :</p>
* <blockquote><pre>str1.compareToIgnoreCase(str2)</pre></blockquote>
*
* <p>{@code null} inputs are handled according to the {@code nullIsLess} parameter.
* Two {@code null} references are considered equal.
* Comparison is case insensitive.</p>
*
* <pre>
* StringUtils.compareIgnoreCase(null, null, *) = 0
* StringUtils.compareIgnoreCase(null , "a", true) < 0
* StringUtils.compareIgnoreCase(null , "a", false) > 0
* StringUtils.compareIgnoreCase("a", null, true) > 0
* StringUtils.compareIgnoreCase("a", null, false) < 0
* StringUtils.compareIgnoreCase("abc", "abc", *) = 0
* StringUtils.compareIgnoreCase("abc", "ABC", *) = 0
* StringUtils.compareIgnoreCase("a", "b", *) < 0
* StringUtils.compareIgnoreCase("b", "a", *) > 0
* StringUtils.compareIgnoreCase("a", "B", *) < 0
* StringUtils.compareIgnoreCase("A", "b", *) < 0
* StringUtils.compareIgnoreCase("ab", "abc", *) < 0
* </pre>
*
* @see String#compareToIgnoreCase(String)
* @param str1 the String to compare from
* @param str2 the String to compare to
* @param nullIsLess whether consider {@code null} value less than non-{@code null} value
* @return < 0, 0, > 0, if {@code str1} is respectively less, equal ou greater than {@code str2},
* ignoring case differences.
* @since 3.5
*/
public static int compareIgnoreCase(final String str1, final String str2, final boolean nullIsLess) {
if (str1 == str2) {
return 0;
}
if (str1 == null) {
return nullIsLess ? -1 : 1;
}
if (str2 == null) {
return nullIsLess ? 1 : - 1;
}
return str1.compareToIgnoreCase(str2);
}
/**
* <p>Checks if CharSequence contains a search CharSequence, handling {@code null}.
* This method uses {@link String#indexOf(String)} if possible.</p>
*
* <p>A {@code null} CharSequence will return {@code false}.</p>
*
* <pre>
* StringUtils.contains(null, *) = false
* StringUtils.contains(*, null) = false
* StringUtils.contains("", "") = true
* StringUtils.contains("abc", "") = true
* StringUtils.contains("abc", "a") = true
* StringUtils.contains("abc", "z") = false
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchSeq the CharSequence to find, may be null
* @return true if the CharSequence contains the search CharSequence,
* false if not or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from contains(String, String) to contains(CharSequence, CharSequence)
*/
public static boolean contains(final CharSequence seq, final CharSequence searchSeq) {
if (seq == null || searchSeq == null) {
return false;
}
return CharSequenceUtils.indexOf(seq, searchSeq, 0) >= 0;
}
// Contains
//-----------------------------------------------------------------------
/**
* <p>Checks if CharSequence contains a search character, handling {@code null}.
* This method uses {@link String#indexOf(int)} if possible.</p>
*
* <p>A {@code null} or empty ("") CharSequence will return {@code false}.</p>
*
* <pre>
* StringUtils.contains(null, *) = false
* StringUtils.contains("", *) = false
* StringUtils.contains("abc", 'a') = true
* StringUtils.contains("abc", 'z') = false
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchChar the character to find
* @return true if the CharSequence contains the search character,
* false if not or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from contains(String, int) to contains(CharSequence, int)
*/
public static boolean contains(final CharSequence seq, final int searchChar) {
if (isEmpty(seq)) {
return false;
}
return CharSequenceUtils.indexOf(seq, searchChar, 0) >= 0;
}
// ContainsAny
//-----------------------------------------------------------------------
/**
* <p>Checks if the CharSequence contains any character in the given
* set of characters.</p>
*
* <p>A {@code null} CharSequence will return {@code false}.
* A {@code null} or zero length search array will return {@code false}.</p>
*
* <pre>
* StringUtils.containsAny(null, *) = false
* StringUtils.containsAny("", *) = false
* StringUtils.containsAny(*, null) = false
* StringUtils.containsAny(*, []) = false
* StringUtils.containsAny("zzabyycdxx", ['z', 'a']) = true
* StringUtils.containsAny("zzabyycdxx", ['b', 'y']) = true
* StringUtils.containsAny("zzabyycdxx", ['z', 'y']) = true
* StringUtils.containsAny("aba", ['z']) = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the {@code true} if any of the chars are found,
* {@code false} if no match or null input
* @since 2.4
* @since 3.0 Changed signature from containsAny(String, char[]) to containsAny(CharSequence, char...)
*/
public static boolean containsAny(final CharSequence cs, final char... searchChars) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
return false;
}
final int csLength = cs.length();
final int searchLength = searchChars.length;
final int csLast = csLength - 1;
final int searchLast = searchLength - 1;
for (int i = 0; i < csLength; i++) {
final char ch = cs.charAt(i);
for (int j = 0; j < searchLength; j++) {
if (searchChars[j] == ch) {
if (Character.isHighSurrogate(ch)) {
if (j == searchLast) {
// missing low surrogate, fine, like String.indexOf(String)
return true;
}
if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) {
return true;
}
} else {
// ch is in the Basic Multilingual Plane
return true;
}
}
}
}
return false;
}
/**
* <p>
* Checks if the CharSequence contains any character in the given set of characters.
* </p>
*
* <p>
* A {@code null} CharSequence will return {@code false}. A {@code null} search CharSequence will return
* {@code false}.
* </p>
*
* <pre>
* StringUtils.containsAny(null, *) = false
* StringUtils.containsAny("", *) = false
* StringUtils.containsAny(*, null) = false
* StringUtils.containsAny(*, "") = false
* StringUtils.containsAny("zzabyycdxx", "za") = true
* StringUtils.containsAny("zzabyycdxx", "by") = true
* StringUtils.containsAny("zzabyycdxx", "zy") = true
* StringUtils.containsAny("zzabyycdxx", "\tx") = true
* StringUtils.containsAny("zzabyycdxx", "$.#yF") = true
* StringUtils.containsAny("aba", "z") = false
* </pre>
*
* @param cs
* the CharSequence to check, may be null
* @param searchChars
* the chars to search for, may be null
* @return the {@code true} if any of the chars are found, {@code false} if no match or null input
* @since 2.4
* @since 3.0 Changed signature from containsAny(String, String) to containsAny(CharSequence, CharSequence)
*/
public static boolean containsAny(final CharSequence cs, final CharSequence searchChars) {
if (searchChars == null) {
return false;
}
return containsAny(cs, CharSequenceUtils.toCharArray(searchChars));
}
/**
* <p>Checks if the CharSequence contains any of the CharSequences in the given array.</p>
*
* <p>
* A {@code null} {@code cs} CharSequence will return {@code false}. A {@code null} or zero
* length search array will return {@code false}.
* </p>
*
* <pre>
* StringUtils.containsAny(null, *) = false
* StringUtils.containsAny("", *) = false
* StringUtils.containsAny(*, null) = false
* StringUtils.containsAny(*, []) = false
* StringUtils.containsAny("abcd", "ab", null) = true
* StringUtils.containsAny("abcd", "ab", "cd") = true
* StringUtils.containsAny("abc", "d", "abc") = true
* </pre>
*
*
* @param cs The CharSequence to check, may be null
* @param searchCharSequences The array of CharSequences to search for, may be null.
* Individual CharSequences may be null as well.
* @return {@code true} if any of the search CharSequences are found, {@code false} otherwise
* @since 3.4
*/
public static boolean containsAny(final CharSequence cs, final CharSequence... searchCharSequences) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchCharSequences)) {
return false;
}
for (final CharSequence searchCharSequence : searchCharSequences) {
if (contains(cs, searchCharSequence)) {
return true;
}
}
return false;
}
/**
* <p>Checks if CharSequence contains a search CharSequence irrespective of case,
* handling {@code null}. Case-insensitivity is defined as by
* {@link String#equalsIgnoreCase(String)}.
*
* <p>A {@code null} CharSequence will return {@code false}.</p>
*
* <pre>
* StringUtils.containsIgnoreCase(null, *) = false
* StringUtils.containsIgnoreCase(*, null) = false
* StringUtils.containsIgnoreCase("", "") = true
* StringUtils.containsIgnoreCase("abc", "") = true
* StringUtils.containsIgnoreCase("abc", "a") = true
* StringUtils.containsIgnoreCase("abc", "z") = false
* StringUtils.containsIgnoreCase("abc", "A") = true
* StringUtils.containsIgnoreCase("abc", "Z") = false
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @return true if the CharSequence contains the search CharSequence irrespective of
* case or false if not or {@code null} string input
* @since 3.0 Changed signature from containsIgnoreCase(String, String) to containsIgnoreCase(CharSequence, CharSequence)
*/
public static boolean containsIgnoreCase(final CharSequence str, final CharSequence searchStr) {
if (str == null || searchStr == null) {
return false;
}
final int len = searchStr.length();
final int max = str.length() - len;
for (int i = 0; i <= max; i++) {
if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, len)) {
return true;
}
}
return false;
}
// ContainsNone
//-----------------------------------------------------------------------
/**
* <p>Checks that the CharSequence does not contain certain characters.</p>
*
* <p>A {@code null} CharSequence will return {@code true}.
* A {@code null} invalid character array will return {@code true}.
* An empty CharSequence (length()=0) always returns true.</p>
*
* <pre>
* StringUtils.containsNone(null, *) = true
* StringUtils.containsNone(*, null) = true
* StringUtils.containsNone("", *) = true
* StringUtils.containsNone("ab", '') = true
* StringUtils.containsNone("abab", 'xyz') = true
* StringUtils.containsNone("ab1", 'xyz') = true
* StringUtils.containsNone("abz", 'xyz') = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars an array of invalid chars, may be null
* @return true if it contains none of the invalid chars, or is null
* @since 2.0
* @since 3.0 Changed signature from containsNone(String, char[]) to containsNone(CharSequence, char...)
*/
public static boolean containsNone(final CharSequence cs, final char... searchChars) {
if (cs == null || searchChars == null) {
return true;
}
final int csLen = cs.length();
final int csLast = csLen - 1;
final int searchLen = searchChars.length;
final int searchLast = searchLen - 1;
for (int i = 0; i < csLen; i++) {
final char ch = cs.charAt(i);
for (int j = 0; j < searchLen; j++) {
if (searchChars[j] == ch) {
if (Character.isHighSurrogate(ch)) {
if (j == searchLast) {
// missing low surrogate, fine, like String.indexOf(String)
return false;
}
if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) {
return false;
}
} else {
// ch is in the Basic Multilingual Plane
return false;
}
}
}
}
return true;
}
/**
* <p>Checks that the CharSequence does not contain certain characters.</p>
*
* <p>A {@code null} CharSequence will return {@code true}.
* A {@code null} invalid character array will return {@code true}.
* An empty String ("") always returns true.</p>
*
* <pre>
* StringUtils.containsNone(null, *) = true
* StringUtils.containsNone(*, null) = true
* StringUtils.containsNone("", *) = true
* StringUtils.containsNone("ab", "") = true
* StringUtils.containsNone("abab", "xyz") = true
* StringUtils.containsNone("ab1", "xyz") = true
* StringUtils.containsNone("abz", "xyz") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param invalidChars a String of invalid chars, may be null
* @return true if it contains none of the invalid chars, or is null
* @since 2.0
* @since 3.0 Changed signature from containsNone(String, String) to containsNone(CharSequence, String)
*/
public static boolean containsNone(final CharSequence cs, final String invalidChars) {
if (cs == null || invalidChars == null) {
return true;
}
return containsNone(cs, invalidChars.toCharArray());
}
// ContainsOnly
//-----------------------------------------------------------------------
/**
* <p>Checks if the CharSequence contains only certain characters.</p>
*
* <p>A {@code null} CharSequence will return {@code false}.
* A {@code null} valid character array will return {@code false}.
* An empty CharSequence (length()=0) always returns {@code true}.</p>
*
* <pre>
* StringUtils.containsOnly(null, *) = false
* StringUtils.containsOnly(*, null) = false
* StringUtils.containsOnly("", *) = true
* StringUtils.containsOnly("ab", '') = false
* StringUtils.containsOnly("abab", 'abc') = true
* StringUtils.containsOnly("ab1", 'abc') = false
* StringUtils.containsOnly("abz", 'abc') = false
* </pre>
*
* @param cs the String to check, may be null
* @param valid an array of valid chars, may be null
* @return true if it only contains valid chars and is non-null
* @since 3.0 Changed signature from containsOnly(String, char[]) to containsOnly(CharSequence, char...)
*/
public static boolean containsOnly(final CharSequence cs, final char... valid) {
// All these pre-checks are to maintain API with an older version
if (valid == null || cs == null) {
return false;
}
if (cs.length() == 0) {
return true;
}
if (valid.length == 0) {
return false;
}
return indexOfAnyBut(cs, valid) == INDEX_NOT_FOUND;
}
/**
* <p>Checks if the CharSequence contains only certain characters.</p>
*
* <p>A {@code null} CharSequence will return {@code false}.
* A {@code null} valid character String will return {@code false}.
* An empty String (length()=0) always returns {@code true}.</p>
*
* <pre>
* StringUtils.containsOnly(null, *) = false
* StringUtils.containsOnly(*, null) = false
* StringUtils.containsOnly("", *) = true
* StringUtils.containsOnly("ab", "") = false
* StringUtils.containsOnly("abab", "abc") = true
* StringUtils.containsOnly("ab1", "abc") = false
* StringUtils.containsOnly("abz", "abc") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param validChars a String of valid chars, may be null
* @return true if it only contains valid chars and is non-null
* @since 2.0
* @since 3.0 Changed signature from containsOnly(String, String) to containsOnly(CharSequence, String)
*/
public static boolean containsOnly(final CharSequence cs, final String validChars) {
if (cs == null || validChars == null) {
return false;
}
return containsOnly(cs, validChars.toCharArray());
}
/**
* <p>Check whether the given CharSequence contains any whitespace characters.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* @param seq the CharSequence to check (may be {@code null})
* @return {@code true} if the CharSequence is not empty and
* contains at least 1 (breaking) whitespace character
* @since 3.0
*/
// From org.springframework.util.StringUtils, under Apache License 2.0
public static boolean containsWhitespace(final CharSequence seq) {
if (isEmpty(seq)) {
return false;
}
final int strLen = seq.length();
for (int i = 0; i < strLen; i++) {
if (Character.isWhitespace(seq.charAt(i))) {
return true;
}
}
return false;
}
private static void convertRemainingAccentCharacters(final StringBuilder decomposed) {
for (int i = 0; i < decomposed.length(); i++) {
if (decomposed.charAt(i) == '\u0141') {
decomposed.deleteCharAt(i);
decomposed.insert(i, 'L');
} else if (decomposed.charAt(i) == '\u0142') {
decomposed.deleteCharAt(i);
decomposed.insert(i, 'l');
}
}
}
/**
* <p>Counts how many times the char appears in the given string.</p>
*
* <p>A {@code null} or empty ("") String input returns {@code 0}.</p>
*
* <pre>
* StringUtils.countMatches(null, *) = 0
* StringUtils.countMatches("", *) = 0
* StringUtils.countMatches("abba", 0) = 0
* StringUtils.countMatches("abba", 'a') = 2
* StringUtils.countMatches("abba", 'b') = 2
* StringUtils.countMatches("abba", 'x') = 0
* </pre>
*
* @param str the CharSequence to check, may be null
* @param ch the char to count
* @return the number of occurrences, 0 if the CharSequence is {@code null}
* @since 3.4
*/
public static int countMatches(final CharSequence str, final char ch) {
if (isEmpty(str)) {
return 0;
}
int count = 0;
// We could also call str.toCharArray() for faster look ups but that would generate more garbage.
for (int i = 0; i < str.length(); i++) {
if (ch == str.charAt(i)) {
count++;
}
}
return count;
}
// Count matches
//-----------------------------------------------------------------------
/**
* <p>Counts how many times the substring appears in the larger string.</p>
*
* <p>A {@code null} or empty ("") String input returns {@code 0}.</p>
*
* <pre>
* StringUtils.countMatches(null, *) = 0
* StringUtils.countMatches("", *) = 0
* StringUtils.countMatches("abba", null) = 0
* StringUtils.countMatches("abba", "") = 0
* StringUtils.countMatches("abba", "a") = 2
* StringUtils.countMatches("abba", "ab") = 1
* StringUtils.countMatches("abba", "xxx") = 0
* </pre>
*
* @param str the CharSequence to check, may be null
* @param sub the substring to count, may be null
* @return the number of occurrences, 0 if either CharSequence is {@code null}
* @since 3.0 Changed signature from countMatches(String, String) to countMatches(CharSequence, CharSequence)
*/
public static int countMatches(final CharSequence str, final CharSequence sub) {
if (isEmpty(str) || isEmpty(sub)) {
return 0;
}
int count = 0;
int idx = 0;
while ((idx = CharSequenceUtils.indexOf(str, sub, idx)) != INDEX_NOT_FOUND) {
count++;
idx += sub.length();
}
return count;
}
/**
* <p>Returns either the passed in CharSequence, or if the CharSequence is
* whitespace, empty ("") or {@code null}, the value of {@code defaultStr}.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.defaultIfBlank(null, "NULL") = "NULL"
* StringUtils.defaultIfBlank("", "NULL") = "NULL"
* StringUtils.defaultIfBlank(" ", "NULL") = "NULL"
* StringUtils.defaultIfBlank("bat", "NULL") = "bat"
* StringUtils.defaultIfBlank("", null) = null
* </pre>
* @param <T> the specific kind of CharSequence
* @param str the CharSequence to check, may be null
* @param defaultStr the default CharSequence to return
* if the input is whitespace, empty ("") or {@code null}, may be null
* @return the passed in CharSequence, or the default
* @see StringUtils#defaultString(String, String)
*/
public static <T extends CharSequence> T defaultIfBlank(final T str, final T defaultStr) {
return isBlank(str) ? defaultStr : str;
}
/**
* <p>Returns either the passed in CharSequence, or if the CharSequence is
* empty or {@code null}, the value of {@code defaultStr}.</p>
*
* <pre>
* StringUtils.defaultIfEmpty(null, "NULL") = "NULL"
* StringUtils.defaultIfEmpty("", "NULL") = "NULL"
* StringUtils.defaultIfEmpty(" ", "NULL") = " "
* StringUtils.defaultIfEmpty("bat", "NULL") = "bat"
* StringUtils.defaultIfEmpty("", null) = null
* </pre>
* @param <T> the specific kind of CharSequence
* @param str the CharSequence to check, may be null
* @param defaultStr the default CharSequence to return
* if the input is empty ("") or {@code null}, may be null
* @return the passed in CharSequence, or the default
* @see StringUtils#defaultString(String, String)
*/
public static <T extends CharSequence> T defaultIfEmpty(final T str, final T defaultStr) {
return isEmpty(str) ? defaultStr : str;
}
/**
* <p>Returns either the passed in String,
* or if the String is {@code null}, an empty String ("").</p>
*
* <pre>
* StringUtils.defaultString(null) = ""
* StringUtils.defaultString("") = ""
* StringUtils.defaultString("bat") = "bat"
* </pre>
*
* @see ObjectUtils#toString(Object)
* @see String#valueOf(Object)
* @param str the String to check, may be null
* @return the passed in String, or the empty String if it
* was {@code null}
*/
public static String defaultString(final String str) {
return defaultString(str, EMPTY);
}
/**
* <p>Returns either the passed in String, or if the String is
* {@code null}, the value of {@code defaultStr}.</p>
*
* <pre>
* StringUtils.defaultString(null, "NULL") = "NULL"
* StringUtils.defaultString("", "NULL") = ""
* StringUtils.defaultString("bat", "NULL") = "bat"
* </pre>
*
* @see ObjectUtils#toString(Object,String)
* @see String#valueOf(Object)
* @param str the String to check, may be null
* @param defaultStr the default String to return
* if the input is {@code null}, may be null
* @return the passed in String, or the default if it was {@code null}
*/
public static String defaultString(final String str, final String defaultStr) {
return str == null ? defaultStr : str;
}
// Delete
//-----------------------------------------------------------------------
/**
* <p>Deletes all whitespaces from a String as defined by
* {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.deleteWhitespace(null) = null
* StringUtils.deleteWhitespace("") = ""
* StringUtils.deleteWhitespace("abc") = "abc"
* StringUtils.deleteWhitespace(" ab c ") = "abc"
* </pre>
*
* @param str the String to delete whitespace from, may be null
* @return the String without whitespaces, {@code null} if null String input
*/
public static String deleteWhitespace(final String str) {
if (isEmpty(str)) {
return str;
}
final int sz = str.length();
final char[] chs = new char[sz];
int count = 0;
for (int i = 0; i < sz; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
chs[count++] = str.charAt(i);
}
}
if (count == sz) {
return str;
}
return new String(chs, 0, count);
}
// Difference
//-----------------------------------------------------------------------
/**
* <p>Compares two Strings, and returns the portion where they differ.
* More precisely, return the remainder of the second String,
* starting from where it's different from the first. This means that
* the difference between "abc" and "ab" is the empty String and not "c". </p>
*
* <p>For example,
* {@code difference("i am a machine", "i am a robot") -> "robot"}.</p>
*
* <pre>
* StringUtils.difference(null, null) = null
* StringUtils.difference("", "") = ""
* StringUtils.difference("", "abc") = "abc"
* StringUtils.difference("abc", "") = ""
* StringUtils.difference("abc", "abc") = ""
* StringUtils.difference("abc", "ab") = ""
* StringUtils.difference("ab", "abxyz") = "xyz"
* StringUtils.difference("abcde", "abxyz") = "xyz"
* StringUtils.difference("abcde", "xyz") = "xyz"
* </pre>
*
* @param str1 the first String, may be null
* @param str2 the second String, may be null
* @return the portion of str2 where it differs from str1; returns the
* empty String if they are equal
* @see #indexOfDifference(CharSequence,CharSequence)
* @since 2.0
*/
public static String difference(final String str1, final String str2) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
final int at = indexOfDifference(str1, str2);
if (at == INDEX_NOT_FOUND) {
return EMPTY;
}
return str2.substring(at);
}
/**
* <p>Check if a CharSequence ends with a specified suffix.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered to be equal. The comparison is case sensitive.</p>
*
* <pre>
* StringUtils.endsWith(null, null) = true
* StringUtils.endsWith(null, "def") = false
* StringUtils.endsWith("abcdef", null) = false
* StringUtils.endsWith("abcdef", "def") = true
* StringUtils.endsWith("ABCDEF", "def") = false
* StringUtils.endsWith("ABCDEF", "cde") = false
* StringUtils.endsWith("ABCDEF", "") = true
* </pre>
*
* @see java.lang.String#endsWith(String)
* @param str the CharSequence to check, may be null
* @param suffix the suffix to find, may be null
* @return {@code true} if the CharSequence ends with the suffix, case sensitive, or
* both {@code null}
* @since 2.4
* @since 3.0 Changed signature from endsWith(String, String) to endsWith(CharSequence, CharSequence)
*/
public static boolean endsWith(final CharSequence str, final CharSequence suffix) {
return endsWith(str, suffix, false);
}
/**
* <p>Check if a CharSequence ends with a specified suffix (optionally case insensitive).</p>
*
* @see java.lang.String#endsWith(String)
* @param str the CharSequence to check, may be null
* @param suffix the suffix to find, may be null
* @param ignoreCase indicates whether the compare should ignore case
* (case insensitive) or not.
* @return {@code true} if the CharSequence starts with the prefix or
* both {@code null}
*/
private static boolean endsWith(final CharSequence str, final CharSequence suffix, final boolean ignoreCase) {
if (str == null || suffix == null) {
return str == suffix;
}
if (suffix.length() > str.length()) {
return false;
}
final int strOffset = str.length() - suffix.length();
return CharSequenceUtils.regionMatches(str, ignoreCase, strOffset, suffix, 0, suffix.length());
}
/**
* <p>Check if a CharSequence ends with any of the provided case-sensitive suffixes.</p>
*
* <pre>
* StringUtils.endsWithAny(null, null) = false
* StringUtils.endsWithAny(null, new String[] {"abc"}) = false
* StringUtils.endsWithAny("abcxyz", null) = false
* StringUtils.endsWithAny("abcxyz", new String[] {""}) = true
* StringUtils.endsWithAny("abcxyz", new String[] {"xyz"}) = true
* StringUtils.endsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true
* StringUtils.endsWithAny("abcXYZ", "def", "XYZ") = true
* StringUtils.endsWithAny("abcXYZ", "def", "xyz") = false
* </pre>
*
* @param sequence the CharSequence to check, may be null
* @param searchStrings the case-sensitive CharSequences to find, may be empty or contain {@code null}
* @see StringUtils#endsWith(CharSequence, CharSequence)
* @return {@code true} if the input {@code sequence} is {@code null} AND no {@code searchStrings} are provided, or
* the input {@code sequence} ends in any of the provided case-sensitive {@code searchStrings}.
* @since 3.0
*/
public static boolean endsWithAny(final CharSequence sequence, final CharSequence... searchStrings) {
if (isEmpty(sequence) || ArrayUtils.isEmpty(searchStrings)) {
return false;
}
for (final CharSequence searchString : searchStrings) {
if (endsWith(sequence, searchString)) {
return true;
}
}
return false;
}
/**
* <p>Case insensitive check if a CharSequence ends with a specified suffix.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered to be equal. The comparison is case insensitive.</p>
*
* <pre>
* StringUtils.endsWithIgnoreCase(null, null) = true
* StringUtils.endsWithIgnoreCase(null, "def") = false
* StringUtils.endsWithIgnoreCase("abcdef", null) = false
* StringUtils.endsWithIgnoreCase("abcdef", "def") = true
* StringUtils.endsWithIgnoreCase("ABCDEF", "def") = true
* StringUtils.endsWithIgnoreCase("ABCDEF", "cde") = false
* </pre>
*
* @see java.lang.String#endsWith(String)
* @param str the CharSequence to check, may be null
* @param suffix the suffix to find, may be null
* @return {@code true} if the CharSequence ends with the suffix, case insensitive, or
* both {@code null}
* @since 2.4
* @since 3.0 Changed signature from endsWithIgnoreCase(String, String) to endsWithIgnoreCase(CharSequence, CharSequence)
*/
public static boolean endsWithIgnoreCase(final CharSequence str, final CharSequence suffix) {
return endsWith(str, suffix, true);
}
// Equals
//-----------------------------------------------------------------------
/**
* <p>Compares two CharSequences, returning {@code true} if they represent
* equal sequences of characters.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered to be equal. The comparison is <strong>case sensitive</strong>.</p>
*
* <pre>
* StringUtils.equals(null, null) = true
* StringUtils.equals(null, "abc") = false
* StringUtils.equals("abc", null) = false
* StringUtils.equals("abc", "abc") = true
* StringUtils.equals("abc", "ABC") = false
* </pre>
*
* @param cs1 the first CharSequence, may be {@code null}
* @param cs2 the second CharSequence, may be {@code null}
* @return {@code true} if the CharSequences are equal (case-sensitive), or both {@code null}
* @since 3.0 Changed signature from equals(String, String) to equals(CharSequence, CharSequence)
* @see Object#equals(Object)
* @see #equalsIgnoreCase(CharSequence, CharSequence)
*/
public static boolean equals(final CharSequence cs1, final CharSequence cs2) {
if (cs1 == cs2) {
return true;
}
if (cs1 == null || cs2 == null) {
return false;
}
if (cs1.length() != cs2.length()) {
return false;
}
if (cs1 instanceof String && cs2 instanceof String) {
return cs1.equals(cs2);
}
// Step-wise comparison
final int length = cs1.length();
for (int i = 0; i < length; i++) {
if (cs1.charAt(i) != cs2.charAt(i)) {
return false;
}
}
return true;
}
/**
* <p>Compares given {@code string} to a CharSequences vararg of {@code searchStrings},
* returning {@code true} if the {@code string} is equal to any of the {@code searchStrings}.</p>
*
* <pre>
* StringUtils.equalsAny(null, (CharSequence[]) null) = false
* StringUtils.equalsAny(null, null, null) = true
* StringUtils.equalsAny(null, "abc", "def") = false
* StringUtils.equalsAny("abc", null, "def") = false
* StringUtils.equalsAny("abc", "abc", "def") = true
* StringUtils.equalsAny("abc", "ABC", "DEF") = false
* </pre>
*
* @param string to compare, may be {@code null}.
* @param searchStrings a vararg of strings, may be {@code null}.
* @return {@code true} if the string is equal (case-sensitive) to any other element of {@code searchStrings};
* {@code false} if {@code searchStrings} is null or contains no matches.
* @since 3.5
*/
public static boolean equalsAny(final CharSequence string, final CharSequence... searchStrings) {
if (ArrayUtils.isNotEmpty(searchStrings)) {
for (final CharSequence next : searchStrings) {
if (equals(string, next)) {
return true;
}
}
}
return false;
}
/**
* <p>Compares given {@code string} to a CharSequences vararg of {@code searchStrings},
* returning {@code true} if the {@code string} is equal to any of the {@code searchStrings}, ignoring case.</p>
*
* <pre>
* StringUtils.equalsAnyIgnoreCase(null, (CharSequence[]) null) = false
* StringUtils.equalsAnyIgnoreCase(null, null, null) = true
* StringUtils.equalsAnyIgnoreCase(null, "abc", "def") = false
* StringUtils.equalsAnyIgnoreCase("abc", null, "def") = false
* StringUtils.equalsAnyIgnoreCase("abc", "abc", "def") = true
* StringUtils.equalsAnyIgnoreCase("abc", "ABC", "DEF") = true
* </pre>
*
* @param string to compare, may be {@code null}.
* @param searchStrings a vararg of strings, may be {@code null}.
* @return {@code true} if the string is equal (case-insensitive) to any other element of {@code searchStrings};
* {@code false} if {@code searchStrings} is null or contains no matches.
* @since 3.5
*/
public static boolean equalsAnyIgnoreCase(final CharSequence string, final CharSequence...searchStrings) {
if (ArrayUtils.isNotEmpty(searchStrings)) {
for (final CharSequence next : searchStrings) {
if (equalsIgnoreCase(string, next)) {
return true;
}
}
}
return false;
}
/**
* <p>Compares two CharSequences, returning {@code true} if they represent
* equal sequences of characters, ignoring case.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered equal. The comparison is <strong>case insensitive</strong>.</p>
*
* <pre>
* StringUtils.equalsIgnoreCase(null, null) = true
* StringUtils.equalsIgnoreCase(null, "abc") = false
* StringUtils.equalsIgnoreCase("abc", null) = false
* StringUtils.equalsIgnoreCase("abc", "abc") = true
* StringUtils.equalsIgnoreCase("abc", "ABC") = true
* </pre>
*
* @param cs1 the first CharSequence, may be {@code null}
* @param cs2 the second CharSequence, may be {@code null}
* @return {@code true} if the CharSequences are equal (case-insensitive), or both {@code null}
* @since 3.0 Changed signature from equalsIgnoreCase(String, String) to equalsIgnoreCase(CharSequence, CharSequence)
* @see #equals(CharSequence, CharSequence)
*/
public static boolean equalsIgnoreCase(final CharSequence cs1, final CharSequence cs2) {
if (cs1 == cs2) {
return true;
}
if (cs1 == null || cs2 == null) {
return false;
}
if (cs1.length() != cs2.length()) {
return false;
}
return CharSequenceUtils.regionMatches(cs1, true, 0, cs2, 0, cs1.length());
}
/**
* <p>Returns the first value in the array which is not empty (""),
* {@code null} or whitespace only.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>If all values are blank or the array is {@code null}
* or empty then {@code null} is returned.</p>
*
* <pre>
* StringUtils.firstNonBlank(null, null, null) = null
* StringUtils.firstNonBlank(null, "", " ") = null
* StringUtils.firstNonBlank("abc") = "abc"
* StringUtils.firstNonBlank(null, "xyz") = "xyz"
* StringUtils.firstNonBlank(null, "", " ", "xyz") = "xyz"
* StringUtils.firstNonBlank(null, "xyz", "abc") = "xyz"
* StringUtils.firstNonBlank() = null
* </pre>
*
* @param <T> the specific kind of CharSequence
* @param values the values to test, may be {@code null} or empty
* @return the first value from {@code values} which is not blank,
* or {@code null} if there are no non-blank values
* @since 3.8
*/
@SafeVarargs
public static <T extends CharSequence> T firstNonBlank(final T... values) {
if (values != null) {
for (final T val : values) {
if (isNotBlank(val)) {
return val;
}
}
}
return null;
}
/**
* <p>Returns the first value in the array which is not empty.</p>
*
* <p>If all values are empty or the array is {@code null}
* or empty then {@code null} is returned.</p>
*
* <pre>
* StringUtils.firstNonEmpty(null, null, null) = null
* StringUtils.firstNonEmpty(null, null, "") = null
* StringUtils.firstNonEmpty(null, "", " ") = " "
* StringUtils.firstNonEmpty("abc") = "abc"
* StringUtils.firstNonEmpty(null, "xyz") = "xyz"
* StringUtils.firstNonEmpty("", "xyz") = "xyz"
* StringUtils.firstNonEmpty(null, "xyz", "abc") = "xyz"
* StringUtils.firstNonEmpty() = null
* </pre>
*
* @param <T> the specific kind of CharSequence
* @param values the values to test, may be {@code null} or empty
* @return the first value from {@code values} which is not empty,
* or {@code null} if there are no non-empty values
* @since 3.8
*/
@SafeVarargs
public static <T extends CharSequence> T firstNonEmpty(final T... values) {
if (values != null) {
for (final T val : values) {
if (isNotEmpty(val)) {
return val;
}
}
}
return null;
}
/**
* Calls {@link String#getBytes(Charset)} in a null-safe manner.
*
* @param string input string
* @param charset The {@link Charset} to encode the {@code String}. If null, then use the default Charset.
* @return The empty byte[] if {@code string} is null, the result of {@link String#getBytes(Charset)} otherwise.
* @see String#getBytes(Charset)
* @since 3.10
*/
public static byte[] getBytes(final String string, final Charset charset) {
return string == null ? ArrayUtils.EMPTY_BYTE_ARRAY : string.getBytes(Charsets.toCharset(charset));
}
/**
* Calls {@link String#getBytes(String)} in a null-safe manner.
*
* @param string input string
* @param charset The {@link Charset} name to encode the {@code String}. If null, then use the default Charset.
* @return The empty byte[] if {@code string} is null, the result of {@link String#getBytes(String)} otherwise.
* @throws UnsupportedEncodingException Thrown when the named charset is not supported.
* @see String#getBytes(String)
* @since 3.10
*/
public static byte[] getBytes(final String string, final String charset) throws UnsupportedEncodingException {
return string == null ? ArrayUtils.EMPTY_BYTE_ARRAY : string.getBytes(Charsets.toCharsetName(charset));
}
/**
* <p>Compares all Strings in an array and returns the initial sequence of
* characters that is common to all of them.</p>
*
* <p>For example,
* {@code getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) -> "i am a "}</p>
*
* <pre>
* StringUtils.getCommonPrefix(null) = ""
* StringUtils.getCommonPrefix(new String[] {}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc"}) = "abc"
* StringUtils.getCommonPrefix(new String[] {null, null}) = ""
* StringUtils.getCommonPrefix(new String[] {"", ""}) = ""
* StringUtils.getCommonPrefix(new String[] {"", null}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc", null, null}) = ""
* StringUtils.getCommonPrefix(new String[] {null, null, "abc"}) = ""
* StringUtils.getCommonPrefix(new String[] {"", "abc"}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc", ""}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc", "abc"}) = "abc"
* StringUtils.getCommonPrefix(new String[] {"abc", "a"}) = "a"
* StringUtils.getCommonPrefix(new String[] {"ab", "abxyz"}) = "ab"
* StringUtils.getCommonPrefix(new String[] {"abcde", "abxyz"}) = "ab"
* StringUtils.getCommonPrefix(new String[] {"abcde", "xyz"}) = ""
* StringUtils.getCommonPrefix(new String[] {"xyz", "abcde"}) = ""
* StringUtils.getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) = "i am a "
* </pre>
*
* @param strs array of String objects, entries may be null
* @return the initial sequence of characters that are common to all Strings
* in the array; empty String if the array is null, the elements are all null
* or if there is no common prefix.
* @since 2.4
*/
public static String getCommonPrefix(final String... strs) {
if (ArrayUtils.isEmpty(strs)) {
return EMPTY;
}
final int smallestIndexOfDiff = indexOfDifference(strs);
if (smallestIndexOfDiff == INDEX_NOT_FOUND) {
// all strings were identical
if (strs[0] == null) {
return EMPTY;
}
return strs[0];
} else if (smallestIndexOfDiff == 0) {
// there were no common initial characters
return EMPTY;
} else {
// we found a common initial character sequence
return strs[0].substring(0, smallestIndexOfDiff);
}
}
/**
* <p>Checks if a String {@code str} contains Unicode digits,
* if yes then concatenate all the digits in {@code str} and return it as a String.</p>
*
* <p>An empty ("") String will be returned if no digits found in {@code str}.</p>
*
* <pre>
* StringUtils.getDigits(null) = null
* StringUtils.getDigits("") = ""
* StringUtils.getDigits("abc") = ""
* StringUtils.getDigits("1000$") = "1000"
* StringUtils.getDigits("1123~45") = "112345"
* StringUtils.getDigits("(541) 754-3010") = "5417543010"
* StringUtils.getDigits("\u0967\u0968\u0969") = "\u0967\u0968\u0969"
* </pre>
*
* @param str the String to extract digits from, may be null
* @return String with only digits,
* or an empty ("") String if no digits found,
* or {@code null} String if {@code str} is null
* @since 3.6
*/
public static String getDigits(final String str) {
if (isEmpty(str)) {
return str;
}
final int sz = str.length();
final StringBuilder strDigits = new StringBuilder(sz);
for (int i = 0; i < sz; i++) {
final char tempChar = str.charAt(i);
if (Character.isDigit(tempChar)) {
strDigits.append(tempChar);
}
}
return strDigits.toString();
}
/**
* <p>Find the Fuzzy Distance which indicates the similarity score between two Strings.</p>
*
* <p>This string matching algorithm is similar to the algorithms of editors such as Sublime Text,
* TextMate, Atom and others. One point is given for every matched character. Subsequent
* matches yield two bonus points. A higher score indicates a higher similarity.</p>
*
* <pre>
* StringUtils.getFuzzyDistance(null, null, null) = IllegalArgumentException
* StringUtils.getFuzzyDistance("", "", Locale.ENGLISH) = 0
* StringUtils.getFuzzyDistance("Workshop", "b", Locale.ENGLISH) = 0
* StringUtils.getFuzzyDistance("Room", "o", Locale.ENGLISH) = 1
* StringUtils.getFuzzyDistance("Workshop", "w", Locale.ENGLISH) = 1
* StringUtils.getFuzzyDistance("Workshop", "ws", Locale.ENGLISH) = 2
* StringUtils.getFuzzyDistance("Workshop", "wo", Locale.ENGLISH) = 4
* StringUtils.getFuzzyDistance("Apache Software Foundation", "asf", Locale.ENGLISH) = 3
* </pre>
*
* @param term a full term that should be matched against, must not be null
* @param query the query that will be matched against a term, must not be null
* @param locale This string matching logic is case insensitive. A locale is necessary to normalize
* both Strings to lower case.
* @return result score
* @throws IllegalArgumentException if either String input {@code null} or Locale input {@code null}
* @since 3.4
* @deprecated as of 3.6, use commons-text
* <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/similarity/FuzzyScore.html">
* FuzzyScore</a> instead
*/
@Deprecated
public static int getFuzzyDistance(final CharSequence term, final CharSequence query, final Locale locale) {
if (term == null || query == null) {
throw new IllegalArgumentException("Strings must not be null");
} else if (locale == null) {
throw new IllegalArgumentException("Locale must not be null");
}
// fuzzy logic is case insensitive. We normalize the Strings to lower
// case right from the start. Turning characters to lower case
// via Character.toLowerCase(char) is unfortunately insufficient
// as it does not accept a locale.
final String termLowerCase = term.toString().toLowerCase(locale);
final String queryLowerCase = query.toString().toLowerCase(locale);
// the resulting score
int score = 0;
// the position in the term which will be scanned next for potential
// query character matches
int termIndex = 0;
// index of the previously matched character in the term
int previousMatchingCharacterIndex = Integer.MIN_VALUE;
for (int queryIndex = 0; queryIndex < queryLowerCase.length(); queryIndex++) {
final char queryChar = queryLowerCase.charAt(queryIndex);
boolean termCharacterMatchFound = false;
for (; termIndex < termLowerCase.length() && !termCharacterMatchFound; termIndex++) {
final char termChar = termLowerCase.charAt(termIndex);
if (queryChar == termChar) {
// simple character matches result in one point
score++;
// subsequent character matches further improve
// the score.
if (previousMatchingCharacterIndex + 1 == termIndex) {
score += 2;
}
previousMatchingCharacterIndex = termIndex;
// we can leave the nested loop. Every character in the
// query can match at most one character in the term.
termCharacterMatchFound = true;
}
}
}
return score;
}
/**
* <p>Returns either the passed in CharSequence, or if the CharSequence is
* whitespace, empty ("") or {@code null}, the value supplied by {@code defaultStrSupplier}.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>Caller responsible for thread-safety and exception handling of default value supplier</p>
*
* <pre>
* {@code
* StringUtils.getIfBlank(null, () -> "NULL") = "NULL"
* StringUtils.getIfBlank("", () -> "NULL") = "NULL"
* StringUtils.getIfBlank(" ", () -> "NULL") = "NULL"
* StringUtils.getIfBlank("bat", () -> "NULL") = "bat"
* StringUtils.getIfBlank("", () -> null) = null
* StringUtils.getIfBlank("", null) = null
* }</pre>
* @param <T> the specific kind of CharSequence
* @param str the CharSequence to check, may be null
* @param defaultSupplier the supplier of default CharSequence to return
* if the input is whitespace, empty ("") or {@code null}, may be null
* @return the passed in CharSequence, or the default
* @see StringUtils#defaultString(String, String)
* @since 3.10
*/
public static <T extends CharSequence> T getIfBlank(final T str, final Supplier<T> defaultSupplier) {
return isBlank(str) ? defaultSupplier == null ? null : defaultSupplier.get() : str;
}
/**
* <p>Returns either the passed in CharSequence, or if the CharSequence is
* empty or {@code null}, the value supplied by {@code defaultStrSupplier}.</p>
*
* <p>Caller responsible for thread-safety and exception handling of default value supplier</p>
*
* <pre>
* {@code
* StringUtils.getIfEmpty(null, () -> "NULL") = "NULL"
* StringUtils.getIfEmpty("", () -> "NULL") = "NULL"
* StringUtils.getIfEmpty(" ", () -> "NULL") = " "
* StringUtils.getIfEmpty("bat", () -> "NULL") = "bat"
* StringUtils.getIfEmpty("", () -> null) = null
* StringUtils.getIfEmpty("", null) = null
* }
* </pre>
* @param <T> the specific kind of CharSequence
* @param str the CharSequence to check, may be null
* @param defaultSupplier the supplier of default CharSequence to return
* if the input is empty ("") or {@code null}, may be null
* @return the passed in CharSequence, or the default
* @see StringUtils#defaultString(String, String)
* @since 3.10
*/
public static <T extends CharSequence> T getIfEmpty(final T str, final Supplier<T> defaultSupplier) {
return isEmpty(str) ? defaultSupplier == null ? null : defaultSupplier.get() : str;
}
/**
* <p>Find the Jaro Winkler Distance which indicates the similarity score between two Strings.</p>
*
* <p>The Jaro measure is the weighted sum of percentage of matched characters from each file and transposed characters.
* Winkler increased this measure for matching initial characters.</p>
*
* <p>This implementation is based on the Jaro Winkler similarity algorithm
* from <a href="http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance">http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance</a>.</p>
*
* <pre>
* StringUtils.getJaroWinklerDistance(null, null) = IllegalArgumentException
* StringUtils.getJaroWinklerDistance("", "") = 0.0
* StringUtils.getJaroWinklerDistance("", "a") = 0.0
* StringUtils.getJaroWinklerDistance("aaapppp", "") = 0.0
* StringUtils.getJaroWinklerDistance("frog", "fog") = 0.93
* StringUtils.getJaroWinklerDistance("fly", "ant") = 0.0
* StringUtils.getJaroWinklerDistance("elephant", "hippo") = 0.44
* StringUtils.getJaroWinklerDistance("hippo", "elephant") = 0.44
* StringUtils.getJaroWinklerDistance("hippo", "zzzzzzzz") = 0.0
* StringUtils.getJaroWinklerDistance("hello", "hallo") = 0.88
* StringUtils.getJaroWinklerDistance("ABC Corporation", "ABC Corp") = 0.93
* StringUtils.getJaroWinklerDistance("D N H Enterprises Inc", "D & H Enterprises, Inc.") = 0.95
* StringUtils.getJaroWinklerDistance("My Gym Children's Fitness Center", "My Gym. Childrens Fitness") = 0.92
* StringUtils.getJaroWinklerDistance("PENNSYLVANIA", "PENNCISYLVNIA") = 0.88
* </pre>
*
* @param first the first String, must not be null
* @param second the second String, must not be null
* @return result distance
* @throws IllegalArgumentException if either String input {@code null}
* @since 3.3
* @deprecated as of 3.6, use commons-text
* <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/similarity/JaroWinklerDistance.html">
* JaroWinklerDistance</a> instead
*/
@Deprecated
public static double getJaroWinklerDistance(final CharSequence first, final CharSequence second) {
final double DEFAULT_SCALING_FACTOR = 0.1;
if (first == null || second == null) {
throw new IllegalArgumentException("Strings must not be null");
}
final int[] mtp = matches(first, second);
final double m = mtp[0];
if (m == 0) {
return 0D;
}
final double j = ((m / first.length() + m / second.length() + (m - mtp[1]) / m)) / 3;
final double jw = j < 0.7D ? j : j + Math.min(DEFAULT_SCALING_FACTOR, 1D / mtp[3]) * mtp[2] * (1D - j);
return Math.round(jw * 100.0D) / 100.0D;
}
// Misc
//-----------------------------------------------------------------------
/**
* <p>Find the Levenshtein distance between two Strings.</p>
*
* <p>This is the number of changes needed to change one String into
* another, where each change is a single character modification (deletion,
* insertion or substitution).</p>
*
* <p>The implementation uses a single-dimensional array of length s.length() + 1. See
* <a href="http://blog.softwx.net/2014/12/optimizing-levenshtein-algorithm-in-c.html">
* http://blog.softwx.net/2014/12/optimizing-levenshtein-algorithm-in-c.html</a> for details.</p>
*
* <pre>
* StringUtils.getLevenshteinDistance(null, *) = IllegalArgumentException
* StringUtils.getLevenshteinDistance(*, null) = IllegalArgumentException
* StringUtils.getLevenshteinDistance("", "") = 0
* StringUtils.getLevenshteinDistance("", "a") = 1
* StringUtils.getLevenshteinDistance("aaapppp", "") = 7
* StringUtils.getLevenshteinDistance("frog", "fog") = 1
* StringUtils.getLevenshteinDistance("fly", "ant") = 3
* StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
* StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
* StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
* StringUtils.getLevenshteinDistance("hello", "hallo") = 1
* </pre>
*
* @param s the first String, must not be null
* @param t the second String, must not be null
* @return result distance
* @throws IllegalArgumentException if either String input {@code null}
* @since 3.0 Changed signature from getLevenshteinDistance(String, String) to
* getLevenshteinDistance(CharSequence, CharSequence)
* @deprecated as of 3.6, use commons-text
* <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/similarity/LevenshteinDistance.html">
* LevenshteinDistance</a> instead
*/
@Deprecated
public static int getLevenshteinDistance(CharSequence s, CharSequence t) {
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
int n = s.length();
int m = t.length();
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
if (n > m) {
// swap the input strings to consume less memory
final CharSequence tmp = s;
s = t;
t = tmp;
n = m;
m = t.length();
}
final int p[] = new int[n + 1];
// indexes into strings s and t
int i; // iterates through s
int j; // iterates through t
int upper_left;
int upper;
char t_j; // jth character of t
int cost;
for (i = 0; i <= n; i++) {
p[i] = i;
}
for (j = 1; j <= m; j++) {
upper_left = p[0];
t_j = t.charAt(j - 1);
p[0] = j;
for (i = 1; i <= n; i++) {
upper = p[i];
cost = s.charAt(i - 1) == t_j ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left and up +cost
p[i] = Math.min(Math.min(p[i - 1] + 1, p[i] + 1), upper_left + cost);
upper_left = upper;
}
}
return p[n];
}
/**
* <p>Find the Levenshtein distance between two Strings if it's less than or equal to a given
* threshold.</p>
*
* <p>This is the number of changes needed to change one String into
* another, where each change is a single character modification (deletion,
* insertion or substitution).</p>
*
* <p>This implementation follows from Algorithms on Strings, Trees and Sequences by Dan Gusfield
* and Chas Emerick's implementation of the Levenshtein distance algorithm from
* <a href="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a></p>
*
* <pre>
* StringUtils.getLevenshteinDistance(null, *, *) = IllegalArgumentException
* StringUtils.getLevenshteinDistance(*, null, *) = IllegalArgumentException
* StringUtils.getLevenshteinDistance(*, *, -1) = IllegalArgumentException
* StringUtils.getLevenshteinDistance("", "", 0) = 0
* StringUtils.getLevenshteinDistance("aaapppp", "", 8) = 7
* StringUtils.getLevenshteinDistance("aaapppp", "", 7) = 7
* StringUtils.getLevenshteinDistance("aaapppp", "", 6)) = -1
* StringUtils.getLevenshteinDistance("elephant", "hippo", 7) = 7
* StringUtils.getLevenshteinDistance("elephant", "hippo", 6) = -1
* StringUtils.getLevenshteinDistance("hippo", "elephant", 7) = 7
* StringUtils.getLevenshteinDistance("hippo", "elephant", 6) = -1
* </pre>
*
* @param s the first String, must not be null
* @param t the second String, must not be null
* @param threshold the target threshold, must not be negative
* @return result distance, or {@code -1} if the distance would be greater than the threshold
* @throws IllegalArgumentException if either String input {@code null} or negative threshold
* @deprecated as of 3.6, use commons-text
* <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/similarity/LevenshteinDistance.html">
* LevenshteinDistance</a> instead
*/
@Deprecated
public static int getLevenshteinDistance(CharSequence s, CharSequence t, final int threshold) {
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
if (threshold < 0) {
throw new IllegalArgumentException("Threshold must not be negative");
}
/*
This implementation only computes the distance if it's less than or equal to the
threshold value, returning -1 if it's greater. The advantage is performance: unbounded
distance is O(nm), but a bound of k allows us to reduce it to O(km) time by only
computing a diagonal stripe of width 2k + 1 of the cost table.
It is also possible to use this to compute the unbounded Levenshtein distance by starting
the threshold at 1 and doubling each time until the distance is found; this is O(dm), where
d is the distance.
One subtlety comes from needing to ignore entries on the border of our stripe
eg.
p[] = |#|#|#|*
d[] = *|#|#|#|
We must ignore the entry to the left of the leftmost member
We must ignore the entry above the rightmost member
Another subtlety comes from our stripe running off the matrix if the strings aren't
of the same size. Since string s is always swapped to be the shorter of the two,
the stripe will always run off to the upper right instead of the lower left of the matrix.
As a concrete example, suppose s is of length 5, t is of length 7, and our threshold is 1.
In this case we're going to walk a stripe of length 3. The matrix would look like so:
1 2 3 4 5
1 |#|#| | | |
2 |#|#|#| | |
3 | |#|#|#| |
4 | | |#|#|#|
5 | | | |#|#|
6 | | | | |#|
7 | | | | | |
Note how the stripe leads off the table as there is no possible way to turn a string of length 5
into one of length 7 in edit distance of 1.
Additionally, this implementation decreases memory usage by using two
single-dimensional arrays and swapping them back and forth instead of allocating
an entire n by m matrix. This requires a few minor changes, such as immediately returning
when it's detected that the stripe has run off the matrix and initially filling the arrays with
large values so that entries we don't compute are ignored.
See Algorithms on Strings, Trees and Sequences by Dan Gusfield for some discussion.
*/
int n = s.length(); // length of s
int m = t.length(); // length of t
// if one string is empty, the edit distance is necessarily the length of the other
if (n == 0) {
return m <= threshold ? m : -1;
} else if (m == 0) {
return n <= threshold ? n : -1;
} else if (Math.abs(n - m) > threshold) {
// no need to calculate the distance if the length difference is greater than the threshold
return -1;
}
if (n > m) {
// swap the two strings to consume less memory
final CharSequence tmp = s;
s = t;
t = tmp;
n = m;
m = t.length();
}
int p[] = new int[n + 1]; // 'previous' cost array, horizontally
int d[] = new int[n + 1]; // cost array, horizontally
int _d[]; // placeholder to assist in swapping p and d
// fill in starting table values
final int boundary = Math.min(n, threshold) + 1;
for (int i = 0; i < boundary; i++) {
p[i] = i;
}
// these fills ensure that the value above the rightmost entry of our
// stripe will be ignored in following loop iterations
Arrays.fill(p, boundary, p.length, Integer.MAX_VALUE);
Arrays.fill(d, Integer.MAX_VALUE);
// iterates through t
for (int j = 1; j <= m; j++) {
final char t_j = t.charAt(j - 1); // jth character of t
d[0] = j;
// compute stripe indices, constrain to array size
final int min = Math.max(1, j - threshold);
final int max = j > Integer.MAX_VALUE - threshold ? n : Math.min(n, j + threshold);
// the stripe may lead off of the table if s and t are of different sizes
if (min > max) {
return -1;
}
// ignore entry left of leftmost
if (min > 1) {
d[min - 1] = Integer.MAX_VALUE;
}
// iterates through [min, max] in s
for (int i = min; i <= max; i++) {
if (s.charAt(i - 1) == t_j) {
// diagonally left and up
d[i] = p[i - 1];
} else {
// 1 + minimum of cell to the left, to the top, diagonally left and up
d[i] = 1 + Math.min(Math.min(d[i - 1], p[i]), p[i - 1]);
}
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// if p[n] is greater than the threshold, there's no guarantee on it being the correct
// distance
if (p[n] <= threshold) {
return p[n];
}
return -1;
}
/**
* <p>Finds the first index within a CharSequence, handling {@code null}.
* This method uses {@link String#indexOf(String, int)} if possible.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.</p>
*
* <pre>
* StringUtils.indexOf(null, *) = -1
* StringUtils.indexOf(*, null) = -1
* StringUtils.indexOf("", "") = 0
* StringUtils.indexOf("", *) = -1 (except when * = "")
* StringUtils.indexOf("aabaabaa", "a") = 0
* StringUtils.indexOf("aabaabaa", "b") = 2
* StringUtils.indexOf("aabaabaa", "ab") = 1
* StringUtils.indexOf("aabaabaa", "") = 0
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchSeq the CharSequence to find, may be null
* @return the first index of the search CharSequence,
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from indexOf(String, String) to indexOf(CharSequence, CharSequence)
*/
public static int indexOf(final CharSequence seq, final CharSequence searchSeq) {
if (seq == null || searchSeq == null) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.indexOf(seq, searchSeq, 0);
}
/**
* <p>Finds the first index within a CharSequence, handling {@code null}.
* This method uses {@link String#indexOf(String, int)} if possible.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A negative start position is treated as zero.
* An empty ("") search CharSequence always matches.
* A start position greater than the string length only matches
* an empty search CharSequence.</p>
*
* <pre>
* StringUtils.indexOf(null, *, *) = -1
* StringUtils.indexOf(*, null, *) = -1
* StringUtils.indexOf("", "", 0) = 0
* StringUtils.indexOf("", *, 0) = -1 (except when * = "")
* StringUtils.indexOf("aabaabaa", "a", 0) = 0
* StringUtils.indexOf("aabaabaa", "b", 0) = 2
* StringUtils.indexOf("aabaabaa", "ab", 0) = 1
* StringUtils.indexOf("aabaabaa", "b", 3) = 5
* StringUtils.indexOf("aabaabaa", "b", 9) = -1
* StringUtils.indexOf("aabaabaa", "b", -1) = 2
* StringUtils.indexOf("aabaabaa", "", 2) = 2
* StringUtils.indexOf("abc", "", 9) = 3
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchSeq the CharSequence to find, may be null
* @param startPos the start position, negative treated as zero
* @return the first index of the search CharSequence (always ≥ startPos),
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from indexOf(String, String, int) to indexOf(CharSequence, CharSequence, int)
*/
public static int indexOf(final CharSequence seq, final CharSequence searchSeq, final int startPos) {
if (seq == null || searchSeq == null) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.indexOf(seq, searchSeq, startPos);
}
// IndexOf
//-----------------------------------------------------------------------
/**
* Returns the index within {@code seq} of the first occurrence of
* the specified character. If a character with value
* {@code searchChar} occurs in the character sequence represented by
* {@code seq} {@code CharSequence} object, then the index (in Unicode
* code units) of the first such occurrence is returned. For
* values of {@code searchChar} in the range from 0 to 0xFFFF
* (inclusive), this is the smallest value <i>k</i> such that:
* <blockquote><pre>
* this.charAt(<i>k</i>) == searchChar
* </pre></blockquote>
* is true. For other values of {@code searchChar}, it is the
* smallest value <i>k</i> such that:
* <blockquote><pre>
* this.codePointAt(<i>k</i>) == searchChar
* </pre></blockquote>
* is true. In either case, if no such character occurs in {@code seq},
* then {@code INDEX_NOT_FOUND (-1)} is returned.
*
* <p>Furthermore, a {@code null} or empty ("") CharSequence will
* return {@code INDEX_NOT_FOUND (-1)}.</p>
*
* <pre>
* StringUtils.indexOf(null, *) = -1
* StringUtils.indexOf("", *) = -1
* StringUtils.indexOf("aabaabaa", 'a') = 0
* StringUtils.indexOf("aabaabaa", 'b') = 2
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchChar the character to find
* @return the first index of the search character,
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from indexOf(String, int) to indexOf(CharSequence, int)
* @since 3.6 Updated {@link CharSequenceUtils} call to behave more like {@code String}
*/
public static int indexOf(final CharSequence seq, final int searchChar) {
if (isEmpty(seq)) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.indexOf(seq, searchChar, 0);
}
/**
*
* Returns the index within {@code seq} of the first occurrence of the
* specified character, starting the search at the specified index.
* <p>
* If a character with value {@code searchChar} occurs in the
* character sequence represented by the {@code seq} {@code CharSequence}
* object at an index no smaller than {@code startPos}, then
* the index of the first such occurrence is returned. For values
* of {@code searchChar} in the range from 0 to 0xFFFF (inclusive),
* this is the smallest value <i>k</i> such that:
* <blockquote><pre>
* (this.charAt(<i>k</i>) == searchChar) && (<i>k</i> >= startPos)
* </pre></blockquote>
* is true. For other values of {@code searchChar}, it is the
* smallest value <i>k</i> such that:
* <blockquote><pre>
* (this.codePointAt(<i>k</i>) == searchChar) && (<i>k</i> >= startPos)
* </pre></blockquote>
* is true. In either case, if no such character occurs in {@code seq}
* at or after position {@code startPos}, then
* {@code -1} is returned.
*
* <p>
* There is no restriction on the value of {@code startPos}. If it
* is negative, it has the same effect as if it were zero: this entire
* string may be searched. If it is greater than the length of this
* string, it has the same effect as if it were equal to the length of
* this string: {@code (INDEX_NOT_FOUND) -1} is returned. Furthermore, a
* {@code null} or empty ("") CharSequence will
* return {@code (INDEX_NOT_FOUND) -1}.
*
* <p>All indices are specified in {@code char} values
* (Unicode code units).
*
* <pre>
* StringUtils.indexOf(null, *, *) = -1
* StringUtils.indexOf("", *, *) = -1
* StringUtils.indexOf("aabaabaa", 'b', 0) = 2
* StringUtils.indexOf("aabaabaa", 'b', 3) = 5
* StringUtils.indexOf("aabaabaa", 'b', 9) = -1
* StringUtils.indexOf("aabaabaa", 'b', -1) = 2
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchChar the character to find
* @param startPos the start position, negative treated as zero
* @return the first index of the search character (always ≥ startPos),
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from indexOf(String, int, int) to indexOf(CharSequence, int, int)
* @since 3.6 Updated {@link CharSequenceUtils} call to behave more like {@code String}
*/
public static int indexOf(final CharSequence seq, final int searchChar, final int startPos) {
if (isEmpty(seq)) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.indexOf(seq, searchChar, startPos);
}
// IndexOfAny chars
//-----------------------------------------------------------------------
/**
* <p>Search a CharSequence to find the first index of any
* character in the given set of characters.</p>
*
* <p>A {@code null} String will return {@code -1}.
* A {@code null} or zero length search array will return {@code -1}.</p>
*
* <pre>
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny("", *) = -1
* StringUtils.indexOfAny(*, null) = -1
* StringUtils.indexOfAny(*, []) = -1
* StringUtils.indexOfAny("zzabyycdxx", ['z', 'a']) = 0
* StringUtils.indexOfAny("zzabyycdxx", ['b', 'y']) = 3
* StringUtils.indexOfAny("aba", ['z']) = -1
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
* @since 3.0 Changed signature from indexOfAny(String, char[]) to indexOfAny(CharSequence, char...)
*/
public static int indexOfAny(final CharSequence cs, final char... searchChars) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
final int csLen = cs.length();
final int csLast = csLen - 1;
final int searchLen = searchChars.length;
final int searchLast = searchLen - 1;
for (int i = 0; i < csLen; i++) {
final char ch = cs.charAt(i);
for (int j = 0; j < searchLen; j++) {
if (searchChars[j] == ch) {
if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) {
// ch is a supplementary character
if (searchChars[j + 1] == cs.charAt(i + 1)) {
return i;
}
} else {
return i;
}
}
}
}
return INDEX_NOT_FOUND;
}
// IndexOfAny strings
//-----------------------------------------------------------------------
/**
* <p>Find the first index of any of a set of potential substrings.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A {@code null} or zero length search array will return {@code -1}.
* A {@code null} search array entry will be ignored, but a search
* array containing "" will return {@code 0} if {@code str} is not
* null. This method uses {@link String#indexOf(String)} if possible.</p>
*
* <pre>
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny(*, null) = -1
* StringUtils.indexOfAny(*, []) = -1
* StringUtils.indexOfAny("zzabyycdxx", ["ab", "cd"]) = 2
* StringUtils.indexOfAny("zzabyycdxx", ["cd", "ab"]) = 2
* StringUtils.indexOfAny("zzabyycdxx", ["mn", "op"]) = -1
* StringUtils.indexOfAny("zzabyycdxx", ["zab", "aby"]) = 1
* StringUtils.indexOfAny("zzabyycdxx", [""]) = 0
* StringUtils.indexOfAny("", [""]) = 0
* StringUtils.indexOfAny("", ["a"]) = -1
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStrs the CharSequences to search for, may be null
* @return the first index of any of the searchStrs in str, -1 if no match
* @since 3.0 Changed signature from indexOfAny(String, String[]) to indexOfAny(CharSequence, CharSequence...)
*/
public static int indexOfAny(final CharSequence str, final CharSequence... searchStrs) {
if (str == null || searchStrs == null) {
return INDEX_NOT_FOUND;
}
// String's can't have a MAX_VALUEth index.
int ret = Integer.MAX_VALUE;
int tmp = 0;
for (final CharSequence search : searchStrs) {
if (search == null) {
continue;
}
tmp = CharSequenceUtils.indexOf(str, search, 0);
if (tmp == INDEX_NOT_FOUND) {
continue;
}
if (tmp < ret) {
ret = tmp;
}
}
return ret == Integer.MAX_VALUE ? INDEX_NOT_FOUND : ret;
}
/**
* <p>Search a CharSequence to find the first index of any
* character in the given set of characters.</p>
*
* <p>A {@code null} String will return {@code -1}.
* A {@code null} search string will return {@code -1}.</p>
*
* <pre>
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny("", *) = -1
* StringUtils.indexOfAny(*, null) = -1
* StringUtils.indexOfAny(*, "") = -1
* StringUtils.indexOfAny("zzabyycdxx", "za") = 0
* StringUtils.indexOfAny("zzabyycdxx", "by") = 3
* StringUtils.indexOfAny("aba", "z") = -1
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
* @since 3.0 Changed signature from indexOfAny(String, String) to indexOfAny(CharSequence, String)
*/
public static int indexOfAny(final CharSequence cs, final String searchChars) {
if (isEmpty(cs) || isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
return indexOfAny(cs, searchChars.toCharArray());
}
// IndexOfAnyBut chars
//-----------------------------------------------------------------------
/**
* <p>Searches a CharSequence to find the first index of any
* character not in the given set of characters.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A {@code null} or zero length search array will return {@code -1}.</p>
*
* <pre>
* StringUtils.indexOfAnyBut(null, *) = -1
* StringUtils.indexOfAnyBut("", *) = -1
* StringUtils.indexOfAnyBut(*, null) = -1
* StringUtils.indexOfAnyBut(*, []) = -1
* StringUtils.indexOfAnyBut("zzabyycdxx", new char[] {'z', 'a'} ) = 3
* StringUtils.indexOfAnyBut("aba", new char[] {'z'} ) = 0
* StringUtils.indexOfAnyBut("aba", new char[] {'a', 'b'} ) = -1
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
* @since 3.0 Changed signature from indexOfAnyBut(String, char[]) to indexOfAnyBut(CharSequence, char...)
*/
public static int indexOfAnyBut(final CharSequence cs, final char... searchChars) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
final int csLen = cs.length();
final int csLast = csLen - 1;
final int searchLen = searchChars.length;
final int searchLast = searchLen - 1;
outer:
for (int i = 0; i < csLen; i++) {
final char ch = cs.charAt(i);
for (int j = 0; j < searchLen; j++) {
if (searchChars[j] == ch) {
if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) {
if (searchChars[j + 1] == cs.charAt(i + 1)) {
continue outer;
}
} else {
continue outer;
}
}
}
return i;
}
return INDEX_NOT_FOUND;
}
/**
* <p>Search a CharSequence to find the first index of any
* character not in the given set of characters.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A {@code null} or empty search string will return {@code -1}.</p>
*
* <pre>
* StringUtils.indexOfAnyBut(null, *) = -1
* StringUtils.indexOfAnyBut("", *) = -1
* StringUtils.indexOfAnyBut(*, null) = -1
* StringUtils.indexOfAnyBut(*, "") = -1
* StringUtils.indexOfAnyBut("zzabyycdxx", "za") = 3
* StringUtils.indexOfAnyBut("zzabyycdxx", "") = -1
* StringUtils.indexOfAnyBut("aba", "ab") = -1
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
* @since 3.0 Changed signature from indexOfAnyBut(String, String) to indexOfAnyBut(CharSequence, CharSequence)
*/
public static int indexOfAnyBut(final CharSequence seq, final CharSequence searchChars) {
if (isEmpty(seq) || isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
final int strLen = seq.length();
for (int i = 0; i < strLen; i++) {
final char ch = seq.charAt(i);
final boolean chFound = CharSequenceUtils.indexOf(searchChars, ch, 0) >= 0;
if (i + 1 < strLen && Character.isHighSurrogate(ch)) {
final char ch2 = seq.charAt(i + 1);
if (chFound && CharSequenceUtils.indexOf(searchChars, ch2, 0) < 0) {
return i;
}
} else {
if (!chFound) {
return i;
}
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Compares all CharSequences in an array and returns the index at which the
* CharSequences begin to differ.</p>
*
* <p>For example,
* {@code indexOfDifference(new String[] {"i am a machine", "i am a robot"}) -> 7}</p>
*
* <pre>
* StringUtils.indexOfDifference(null) = -1
* StringUtils.indexOfDifference(new String[] {}) = -1
* StringUtils.indexOfDifference(new String[] {"abc"}) = -1
* StringUtils.indexOfDifference(new String[] {null, null}) = -1
* StringUtils.indexOfDifference(new String[] {"", ""}) = -1
* StringUtils.indexOfDifference(new String[] {"", null}) = 0
* StringUtils.indexOfDifference(new String[] {"abc", null, null}) = 0
* StringUtils.indexOfDifference(new String[] {null, null, "abc"}) = 0
* StringUtils.indexOfDifference(new String[] {"", "abc"}) = 0
* StringUtils.indexOfDifference(new String[] {"abc", ""}) = 0
* StringUtils.indexOfDifference(new String[] {"abc", "abc"}) = -1
* StringUtils.indexOfDifference(new String[] {"abc", "a"}) = 1
* StringUtils.indexOfDifference(new String[] {"ab", "abxyz"}) = 2
* StringUtils.indexOfDifference(new String[] {"abcde", "abxyz"}) = 2
* StringUtils.indexOfDifference(new String[] {"abcde", "xyz"}) = 0
* StringUtils.indexOfDifference(new String[] {"xyz", "abcde"}) = 0
* StringUtils.indexOfDifference(new String[] {"i am a machine", "i am a robot"}) = 7
* </pre>
*
* @param css array of CharSequences, entries may be null
* @return the index where the strings begin to differ; -1 if they are all equal
* @since 2.4
* @since 3.0 Changed signature from indexOfDifference(String...) to indexOfDifference(CharSequence...)
*/
public static int indexOfDifference(final CharSequence... css) {
if (ArrayUtils.getLength(css) <= 1) {
return INDEX_NOT_FOUND;
}
boolean anyStringNull = false;
boolean allStringsNull = true;
final int arrayLen = css.length;
int shortestStrLen = Integer.MAX_VALUE;
int longestStrLen = 0;
// find the min and max string lengths; this avoids checking to make
// sure we are not exceeding the length of the string each time through
// the bottom loop.
for (final CharSequence cs : css) {
if (cs == null) {
anyStringNull = true;
shortestStrLen = 0;
} else {
allStringsNull = false;
shortestStrLen = Math.min(cs.length(), shortestStrLen);
longestStrLen = Math.max(cs.length(), longestStrLen);
}
}
// handle lists containing all nulls or all empty strings
if (allStringsNull || longestStrLen == 0 && !anyStringNull) {
return INDEX_NOT_FOUND;
}
// handle lists containing some nulls or some empty strings
if (shortestStrLen == 0) {
return 0;
}
// find the position with the first difference across all strings
int firstDiff = -1;
for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) {
final char comparisonChar = css[0].charAt(stringPos);
for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) {
if (css[arrayPos].charAt(stringPos) != comparisonChar) {
firstDiff = stringPos;
break;
}
}
if (firstDiff != -1) {
break;
}
}
if (firstDiff == -1 && shortestStrLen != longestStrLen) {
// we compared all of the characters up to the length of the
// shortest string and didn't find a match, but the string lengths
// vary, so return the length of the shortest string.
return shortestStrLen;
}
return firstDiff;
}
/**
* <p>Compares two CharSequences, and returns the index at which the
* CharSequences begin to differ.</p>
*
* <p>For example,
* {@code indexOfDifference("i am a machine", "i am a robot") -> 7}</p>
*
* <pre>
* StringUtils.indexOfDifference(null, null) = -1
* StringUtils.indexOfDifference("", "") = -1
* StringUtils.indexOfDifference("", "abc") = 0
* StringUtils.indexOfDifference("abc", "") = 0
* StringUtils.indexOfDifference("abc", "abc") = -1
* StringUtils.indexOfDifference("ab", "abxyz") = 2
* StringUtils.indexOfDifference("abcde", "abxyz") = 2
* StringUtils.indexOfDifference("abcde", "xyz") = 0
* </pre>
*
* @param cs1 the first CharSequence, may be null
* @param cs2 the second CharSequence, may be null
* @return the index where cs1 and cs2 begin to differ; -1 if they are equal
* @since 2.0
* @since 3.0 Changed signature from indexOfDifference(String, String) to
* indexOfDifference(CharSequence, CharSequence)
*/
public static int indexOfDifference(final CharSequence cs1, final CharSequence cs2) {
if (cs1 == cs2) {
return INDEX_NOT_FOUND;
}
if (cs1 == null || cs2 == null) {
return 0;
}
int i;
for (i = 0; i < cs1.length() && i < cs2.length(); ++i) {
if (cs1.charAt(i) != cs2.charAt(i)) {
break;
}
}
if (i < cs2.length() || i < cs1.length()) {
return i;
}
return INDEX_NOT_FOUND;
}
/**
* <p>Case in-sensitive find of the first index within a CharSequence.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A negative start position is treated as zero.
* An empty ("") search CharSequence always matches.
* A start position greater than the string length only matches
* an empty search CharSequence.</p>
*
* <pre>
* StringUtils.indexOfIgnoreCase(null, *) = -1
* StringUtils.indexOfIgnoreCase(*, null) = -1
* StringUtils.indexOfIgnoreCase("", "") = 0
* StringUtils.indexOfIgnoreCase("aabaabaa", "a") = 0
* StringUtils.indexOfIgnoreCase("aabaabaa", "b") = 2
* StringUtils.indexOfIgnoreCase("aabaabaa", "ab") = 1
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @return the first index of the search CharSequence,
* -1 if no match or {@code null} string input
* @since 2.5
* @since 3.0 Changed signature from indexOfIgnoreCase(String, String) to indexOfIgnoreCase(CharSequence, CharSequence)
*/
public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr) {
return indexOfIgnoreCase(str, searchStr, 0);
}
/**
* <p>Case in-sensitive find of the first index within a CharSequence
* from the specified position.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A negative start position is treated as zero.
* An empty ("") search CharSequence always matches.
* A start position greater than the string length only matches
* an empty search CharSequence.</p>
*
* <pre>
* StringUtils.indexOfIgnoreCase(null, *, *) = -1
* StringUtils.indexOfIgnoreCase(*, null, *) = -1
* StringUtils.indexOfIgnoreCase("", "", 0) = 0
* StringUtils.indexOfIgnoreCase("aabaabaa", "A", 0) = 0
* StringUtils.indexOfIgnoreCase("aabaabaa", "B", 0) = 2
* StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1
* StringUtils.indexOfIgnoreCase("aabaabaa", "B", 3) = 5
* StringUtils.indexOfIgnoreCase("aabaabaa", "B", 9) = -1
* StringUtils.indexOfIgnoreCase("aabaabaa", "B", -1) = 2
* StringUtils.indexOfIgnoreCase("aabaabaa", "", 2) = 2
* StringUtils.indexOfIgnoreCase("abc", "", 9) = -1
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @param startPos the start position, negative treated as zero
* @return the first index of the search CharSequence (always ≥ startPos),
* -1 if no match or {@code null} string input
* @since 2.5
* @since 3.0 Changed signature from indexOfIgnoreCase(String, String, int) to indexOfIgnoreCase(CharSequence, CharSequence, int)
*/
public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int startPos) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
if (startPos < 0) {
startPos = 0;
}
final int endLimit = str.length() - searchStr.length() + 1;
if (startPos > endLimit) {
return INDEX_NOT_FOUND;
}
if (searchStr.length() == 0) {
return startPos;
}
for (int i = startPos; i < endLimit; i++) {
if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, searchStr.length())) {
return i;
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Checks if all of the CharSequences are empty (""), null or whitespace only.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.isAllBlank(null) = true
* StringUtils.isAllBlank(null, "foo") = false
* StringUtils.isAllBlank(null, null) = true
* StringUtils.isAllBlank("", "bar") = false
* StringUtils.isAllBlank("bob", "") = false
* StringUtils.isAllBlank(" bob ", null) = false
* StringUtils.isAllBlank(" ", "bar") = false
* StringUtils.isAllBlank("foo", "bar") = false
* StringUtils.isAllBlank(new String[] {}) = true
* </pre>
*
* @param css the CharSequences to check, may be null or empty
* @return {@code true} if all of the CharSequences are empty or null or whitespace only
* @since 3.6
*/
public static boolean isAllBlank(final CharSequence... css) {
if (ArrayUtils.isEmpty(css)) {
return true;
}
for (final CharSequence cs : css) {
if (isNotBlank(cs)) {
return false;
}
}
return true;
}
/**
* <p>Checks if all of the CharSequences are empty ("") or null.</p>
*
* <pre>
* StringUtils.isAllEmpty(null) = true
* StringUtils.isAllEmpty(null, "") = true
* StringUtils.isAllEmpty(new String[] {}) = true
* StringUtils.isAllEmpty(null, "foo") = false
* StringUtils.isAllEmpty("", "bar") = false
* StringUtils.isAllEmpty("bob", "") = false
* StringUtils.isAllEmpty(" bob ", null) = false
* StringUtils.isAllEmpty(" ", "bar") = false
* StringUtils.isAllEmpty("foo", "bar") = false
* </pre>
*
* @param css the CharSequences to check, may be null or empty
* @return {@code true} if all of the CharSequences are empty or null
* @since 3.6
*/
public static boolean isAllEmpty(final CharSequence... css) {
if (ArrayUtils.isEmpty(css)) {
return true;
}
for (final CharSequence cs : css) {
if (isNotEmpty(cs)) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only lowercase characters.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code false}.</p>
*
* <pre>
* StringUtils.isAllLowerCase(null) = false
* StringUtils.isAllLowerCase("") = false
* StringUtils.isAllLowerCase(" ") = false
* StringUtils.isAllLowerCase("abc") = true
* StringUtils.isAllLowerCase("abC") = false
* StringUtils.isAllLowerCase("ab c") = false
* StringUtils.isAllLowerCase("ab1c") = false
* StringUtils.isAllLowerCase("ab/c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains lowercase characters, and is non-null
* @since 2.5
* @since 3.0 Changed signature from isAllLowerCase(String) to isAllLowerCase(CharSequence)
*/
public static boolean isAllLowerCase(final CharSequence cs) {
if (isEmpty(cs)) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isLowerCase(cs.charAt(i))) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only uppercase characters.</p>
*
* <p>{@code null} will return {@code false}.
* An empty String (length()=0) will return {@code false}.</p>
*
* <pre>
* StringUtils.isAllUpperCase(null) = false
* StringUtils.isAllUpperCase("") = false
* StringUtils.isAllUpperCase(" ") = false
* StringUtils.isAllUpperCase("ABC") = true
* StringUtils.isAllUpperCase("aBC") = false
* StringUtils.isAllUpperCase("A C") = false
* StringUtils.isAllUpperCase("A1C") = false
* StringUtils.isAllUpperCase("A/C") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains uppercase characters, and is non-null
* @since 2.5
* @since 3.0 Changed signature from isAllUpperCase(String) to isAllUpperCase(CharSequence)
*/
public static boolean isAllUpperCase(final CharSequence cs) {
if (isEmpty(cs)) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isUpperCase(cs.charAt(i))) {
return false;
}
}
return true;
}
// Character Tests
//-----------------------------------------------------------------------
/**
* <p>Checks if the CharSequence contains only Unicode letters.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code false}.</p>
*
* <pre>
* StringUtils.isAlpha(null) = false
* StringUtils.isAlpha("") = false
* StringUtils.isAlpha(" ") = false
* StringUtils.isAlpha("abc") = true
* StringUtils.isAlpha("ab2c") = false
* StringUtils.isAlpha("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains letters, and is non-null
* @since 3.0 Changed signature from isAlpha(String) to isAlpha(CharSequence)
* @since 3.0 Changed "" to return false and not true
*/
public static boolean isAlpha(final CharSequence cs) {
if (isEmpty(cs)) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isLetter(cs.charAt(i))) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only Unicode letters or digits.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code false}.</p>
*
* <pre>
* StringUtils.isAlphanumeric(null) = false
* StringUtils.isAlphanumeric("") = false
* StringUtils.isAlphanumeric(" ") = false
* StringUtils.isAlphanumeric("abc") = true
* StringUtils.isAlphanumeric("ab c") = false
* StringUtils.isAlphanumeric("ab2c") = true
* StringUtils.isAlphanumeric("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains letters or digits,
* and is non-null
* @since 3.0 Changed signature from isAlphanumeric(String) to isAlphanumeric(CharSequence)
* @since 3.0 Changed "" to return false and not true
*/
public static boolean isAlphanumeric(final CharSequence cs) {
if (isEmpty(cs)) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isLetterOrDigit(cs.charAt(i))) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only Unicode letters, digits
* or space ({@code ' '}).</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code true}.</p>
*
* <pre>
* StringUtils.isAlphanumericSpace(null) = false
* StringUtils.isAlphanumericSpace("") = true
* StringUtils.isAlphanumericSpace(" ") = true
* StringUtils.isAlphanumericSpace("abc") = true
* StringUtils.isAlphanumericSpace("ab c") = true
* StringUtils.isAlphanumericSpace("ab2c") = true
* StringUtils.isAlphanumericSpace("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains letters, digits or space,
* and is non-null
* @since 3.0 Changed signature from isAlphanumericSpace(String) to isAlphanumericSpace(CharSequence)
*/
public static boolean isAlphanumericSpace(final CharSequence cs) {
if (cs == null) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isLetterOrDigit(cs.charAt(i)) && cs.charAt(i) != ' ') {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only Unicode letters and
* space (' ').</p>
*
* <p>{@code null} will return {@code false}
* An empty CharSequence (length()=0) will return {@code true}.</p>
*
* <pre>
* StringUtils.isAlphaSpace(null) = false
* StringUtils.isAlphaSpace("") = true
* StringUtils.isAlphaSpace(" ") = true
* StringUtils.isAlphaSpace("abc") = true
* StringUtils.isAlphaSpace("ab c") = true
* StringUtils.isAlphaSpace("ab2c") = false
* StringUtils.isAlphaSpace("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains letters and space,
* and is non-null
* @since 3.0 Changed signature from isAlphaSpace(String) to isAlphaSpace(CharSequence)
*/
public static boolean isAlphaSpace(final CharSequence cs) {
if (cs == null) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isLetter(cs.charAt(i)) && cs.charAt(i) != ' ') {
return false;
}
}
return true;
}
/**
* <p>Checks if any of the CharSequences are empty ("") or null or whitespace only.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.isAnyBlank((String) null) = true
* StringUtils.isAnyBlank((String[]) null) = false
* StringUtils.isAnyBlank(null, "foo") = true
* StringUtils.isAnyBlank(null, null) = true
* StringUtils.isAnyBlank("", "bar") = true
* StringUtils.isAnyBlank("bob", "") = true
* StringUtils.isAnyBlank(" bob ", null) = true
* StringUtils.isAnyBlank(" ", "bar") = true
* StringUtils.isAnyBlank(new String[] {}) = false
* StringUtils.isAnyBlank(new String[]{""}) = true
* StringUtils.isAnyBlank("foo", "bar") = false
* </pre>
*
* @param css the CharSequences to check, may be null or empty
* @return {@code true} if any of the CharSequences are empty or null or whitespace only
* @since 3.2
*/
public static boolean isAnyBlank(final CharSequence... css) {
if (ArrayUtils.isEmpty(css)) {
return false;
}
for (final CharSequence cs : css) {
if (isBlank(cs)) {
return true;
}
}
return false;
}
/**
* <p>Checks if any of the CharSequences are empty ("") or null.</p>
*
* <pre>
* StringUtils.isAnyEmpty((String) null) = true
* StringUtils.isAnyEmpty((String[]) null) = false
* StringUtils.isAnyEmpty(null, "foo") = true
* StringUtils.isAnyEmpty("", "bar") = true
* StringUtils.isAnyEmpty("bob", "") = true
* StringUtils.isAnyEmpty(" bob ", null) = true
* StringUtils.isAnyEmpty(" ", "bar") = false
* StringUtils.isAnyEmpty("foo", "bar") = false
* StringUtils.isAnyEmpty(new String[]{}) = false
* StringUtils.isAnyEmpty(new String[]{""}) = true
* </pre>
*
* @param css the CharSequences to check, may be null or empty
* @return {@code true} if any of the CharSequences are empty or null
* @since 3.2
*/
public static boolean isAnyEmpty(final CharSequence... css) {
if (ArrayUtils.isEmpty(css)) {
return false;
}
for (final CharSequence cs : css) {
if (isEmpty(cs)) {
return true;
}
}
return false;
}
/**
* <p>Checks if the CharSequence contains only ASCII printable characters.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code true}.</p>
*
* <pre>
* StringUtils.isAsciiPrintable(null) = false
* StringUtils.isAsciiPrintable("") = true
* StringUtils.isAsciiPrintable(" ") = true
* StringUtils.isAsciiPrintable("Ceki") = true
* StringUtils.isAsciiPrintable("ab2c") = true
* StringUtils.isAsciiPrintable("!ab-c~") = true
* StringUtils.isAsciiPrintable("\u0020") = true
* StringUtils.isAsciiPrintable("\u0021") = true
* StringUtils.isAsciiPrintable("\u007e") = true
* StringUtils.isAsciiPrintable("\u007f") = false
* StringUtils.isAsciiPrintable("Ceki G\u00fclc\u00fc") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if every character is in the range
* 32 thru 126
* @since 2.1
* @since 3.0 Changed signature from isAsciiPrintable(String) to isAsciiPrintable(CharSequence)
*/
public static boolean isAsciiPrintable(final CharSequence cs) {
if (cs == null) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!CharUtils.isAsciiPrintable(cs.charAt(i))) {
return false;
}
}
return true;
}
// Nested extraction
//-----------------------------------------------------------------------
/**
* <p>Checks if a CharSequence is empty (""), null or whitespace only.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is null, empty or whitespace only
* @since 2.0
* @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)
*/
public static boolean isBlank(final CharSequence cs) {
final int strLen = length(cs);
if (strLen == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
// Empty checks
//-----------------------------------------------------------------------
/**
* <p>Checks if a CharSequence is empty ("") or null.</p>
*
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer trims the CharSequence.
* That functionality is available in isBlank().</p>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is empty or null
* @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence)
*/
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
/**
* <p>Checks if the CharSequence contains mixed casing of both uppercase and lowercase characters.</p>
*
* <p>{@code null} will return {@code false}. An empty CharSequence ({@code length()=0}) will return
* {@code false}.</p>
*
* <pre>
* StringUtils.isMixedCase(null) = false
* StringUtils.isMixedCase("") = false
* StringUtils.isMixedCase("ABC") = false
* StringUtils.isMixedCase("abc") = false
* StringUtils.isMixedCase("aBc") = true
* StringUtils.isMixedCase("A c") = true
* StringUtils.isMixedCase("A1c") = true
* StringUtils.isMixedCase("a/C") = true
* StringUtils.isMixedCase("aC\t") = true
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence contains both uppercase and lowercase characters
* @since 3.5
*/
public static boolean isMixedCase(final CharSequence cs) {
if (isEmpty(cs) || cs.length() == 1) {
return false;
}
boolean containsUppercase = false;
boolean containsLowercase = false;
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (containsUppercase && containsLowercase) {
return true;
} else if (Character.isUpperCase(cs.charAt(i))) {
containsUppercase = true;
} else if (Character.isLowerCase(cs.charAt(i))) {
containsLowercase = true;
}
}
return containsUppercase && containsLowercase;
}
/**
* <p>Checks if none of the CharSequences are empty (""), null or whitespace only.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.isNoneBlank((String) null) = false
* StringUtils.isNoneBlank((String[]) null) = true
* StringUtils.isNoneBlank(null, "foo") = false
* StringUtils.isNoneBlank(null, null) = false
* StringUtils.isNoneBlank("", "bar") = false
* StringUtils.isNoneBlank("bob", "") = false
* StringUtils.isNoneBlank(" bob ", null) = false
* StringUtils.isNoneBlank(" ", "bar") = false
* StringUtils.isNoneBlank(new String[] {}) = true
* StringUtils.isNoneBlank(new String[]{""}) = false
* StringUtils.isNoneBlank("foo", "bar") = true
* </pre>
*
* @param css the CharSequences to check, may be null or empty
* @return {@code true} if none of the CharSequences are empty or null or whitespace only
* @since 3.2
*/
public static boolean isNoneBlank(final CharSequence... css) {
return !isAnyBlank(css);
}
/**
* <p>Checks if none of the CharSequences are empty ("") or null.</p>
*
* <pre>
* StringUtils.isNoneEmpty((String) null) = false
* StringUtils.isNoneEmpty((String[]) null) = true
* StringUtils.isNoneEmpty(null, "foo") = false
* StringUtils.isNoneEmpty("", "bar") = false
* StringUtils.isNoneEmpty("bob", "") = false
* StringUtils.isNoneEmpty(" bob ", null) = false
* StringUtils.isNoneEmpty(new String[] {}) = true
* StringUtils.isNoneEmpty(new String[]{""}) = false
* StringUtils.isNoneEmpty(" ", "bar") = true
* StringUtils.isNoneEmpty("foo", "bar") = true
* </pre>
*
* @param css the CharSequences to check, may be null or empty
* @return {@code true} if none of the CharSequences are empty or null
* @since 3.2
*/
public static boolean isNoneEmpty(final CharSequence... css) {
return !isAnyEmpty(css);
}
/**
* <p>Checks if a CharSequence is not empty (""), not null and not whitespace only.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.isNotBlank(null) = false
* StringUtils.isNotBlank("") = false
* StringUtils.isNotBlank(" ") = false
* StringUtils.isNotBlank("bob") = true
* StringUtils.isNotBlank(" bob ") = true
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is
* not empty and not null and not whitespace only
* @since 2.0
* @since 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence)
*/
public static boolean isNotBlank(final CharSequence cs) {
return !isBlank(cs);
}
/**
* <p>Checks if a CharSequence is not empty ("") and not null.</p>
*
* <pre>
* StringUtils.isNotEmpty(null) = false
* StringUtils.isNotEmpty("") = false
* StringUtils.isNotEmpty(" ") = true
* StringUtils.isNotEmpty("bob") = true
* StringUtils.isNotEmpty(" bob ") = true
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is not empty and not null
* @since 3.0 Changed signature from isNotEmpty(String) to isNotEmpty(CharSequence)
*/
public static boolean isNotEmpty(final CharSequence cs) {
return !isEmpty(cs);
}
/**
* <p>Checks if the CharSequence contains only Unicode digits.
* A decimal point is not a Unicode digit and returns false.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code false}.</p>
*
* <p>Note that the method does not allow for a leading sign, either positive or negative.
* Also, if a String passes the numeric test, it may still generate a NumberFormatException
* when parsed by Integer.parseInt or Long.parseLong, e.g. if the value is outside the range
* for int or long respectively.</p>
*
* <pre>
* StringUtils.isNumeric(null) = false
* StringUtils.isNumeric("") = false
* StringUtils.isNumeric(" ") = false
* StringUtils.isNumeric("123") = true
* StringUtils.isNumeric("\u0967\u0968\u0969") = true
* StringUtils.isNumeric("12 3") = false
* StringUtils.isNumeric("ab2c") = false
* StringUtils.isNumeric("12-3") = false
* StringUtils.isNumeric("12.3") = false
* StringUtils.isNumeric("-123") = false
* StringUtils.isNumeric("+123") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains digits, and is non-null
* @since 3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence)
* @since 3.0 Changed "" to return false and not true
*/
public static boolean isNumeric(final CharSequence cs) {
if (isEmpty(cs)) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isDigit(cs.charAt(i))) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only Unicode digits or space
* ({@code ' '}).
* A decimal point is not a Unicode digit and returns false.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code true}.</p>
*
* <pre>
* StringUtils.isNumericSpace(null) = false
* StringUtils.isNumericSpace("") = true
* StringUtils.isNumericSpace(" ") = true
* StringUtils.isNumericSpace("123") = true
* StringUtils.isNumericSpace("12 3") = true
* StringUtils.isNumeric("\u0967\u0968\u0969") = true
* StringUtils.isNumeric("\u0967\u0968 \u0969") = true
* StringUtils.isNumericSpace("ab2c") = false
* StringUtils.isNumericSpace("12-3") = false
* StringUtils.isNumericSpace("12.3") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains digits or space,
* and is non-null
* @since 3.0 Changed signature from isNumericSpace(String) to isNumericSpace(CharSequence)
*/
public static boolean isNumericSpace(final CharSequence cs) {
if (cs == null) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isDigit(cs.charAt(i)) && cs.charAt(i) != ' ') {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only whitespace.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code true}.</p>
*
* <pre>
* StringUtils.isWhitespace(null) = false
* StringUtils.isWhitespace("") = true
* StringUtils.isWhitespace(" ") = true
* StringUtils.isWhitespace("abc") = false
* StringUtils.isWhitespace("ab2c") = false
* StringUtils.isWhitespace("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains whitespace, and is non-null
* @since 2.0
* @since 3.0 Changed signature from isWhitespace(String) to isWhitespace(CharSequence)
*/
public static boolean isWhitespace(final CharSequence cs) {
if (cs == null) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final byte[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in a start index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final byte[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = newStringBuilder(noOfItems);
buf.append(array[startIndex]);
for (int i = startIndex + 1; i < endIndex; i++) {
buf.append(separator);
buf.append(array[i]);
}
return buf.toString();
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final char[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in a start index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final char[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = newStringBuilder(noOfItems);
buf.append(array[startIndex]);
for (int i = startIndex + 1; i < endIndex; i++) {
buf.append(separator);
buf.append(array[i]);
}
return buf.toString();
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final double[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in a start index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final double[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = newStringBuilder(noOfItems);
buf.append(array[startIndex]);
for (int i = startIndex + 1; i < endIndex; i++) {
buf.append(separator);
buf.append(array[i]);
}
return buf.toString();
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final float[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in a start index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final float[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = newStringBuilder(noOfItems);
buf.append(array[startIndex]);
for (int i = startIndex + 1; i < endIndex; i++) {
buf.append(separator);
buf.append(array[i]);
}
return buf.toString();
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final int[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in a start index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final int[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = newStringBuilder(noOfItems);
buf.append(array[startIndex]);
for (int i = startIndex + 1; i < endIndex; i++) {
buf.append(separator);
buf.append(array[i]);
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided {@code Iterable} into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list. Null objects or empty
* strings within the iteration are represented by empty strings.</p>
*
* <p>See the examples here: {@link #join(Object[],char)}. </p>
*
* @param iterable the {@code Iterable} providing the values to join together, may be null
* @param separator the separator character to use
* @return the joined String, {@code null} if null iterator input
* @since 2.3
*/
public static String join(final Iterable<?> iterable, final char separator) {
if (iterable == null) {
return null;
}
return join(iterable.iterator(), separator);
}
/**
* <p>Joins the elements of the provided {@code Iterable} into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list.
* A {@code null} separator is the same as an empty String ("").</p>
*
* <p>See the examples here: {@link #join(Object[],String)}. </p>
*
* @param iterable the {@code Iterable} providing the values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, {@code null} if null iterator input
* @since 2.3
*/
public static String join(final Iterable<?> iterable, final String separator) {
if (iterable == null) {
return null;
}
return join(iterable.iterator(), separator);
}
/**
* <p>Joins the elements of the provided {@code Iterator} into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list. Null objects or empty
* strings within the iteration are represented by empty strings.</p>
*
* <p>See the examples here: {@link #join(Object[],char)}. </p>
*
* @param iterator the {@code Iterator} of values to join together, may be null
* @param separator the separator character to use
* @return the joined String, {@code null} if null iterator input
* @since 2.0
*/
public static String join(final Iterator<?> iterator, final char separator) {
// handle null, zero and one elements before building a buffer
if (iterator == null) {
return null;
}
if (!iterator.hasNext()) {
return EMPTY;
}
final Object first = iterator.next();
if (!iterator.hasNext()) {
return Objects.toString(first, EMPTY);
}
// two or more elements
final StringBuilder buf = new StringBuilder(STRING_BUILDER_SIZE); // Java default is 16, probably too small
if (first != null) {
buf.append(first);
}
while (iterator.hasNext()) {
buf.append(separator);
final Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided {@code Iterator} into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list.
* A {@code null} separator is the same as an empty String ("").</p>
*
* <p>See the examples here: {@link #join(Object[],String)}. </p>
*
* @param iterator the {@code Iterator} of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, {@code null} if null iterator input
*/
public static String join(final Iterator<?> iterator, final String separator) {
// handle null, zero and one elements before building a buffer
if (iterator == null) {
return null;
}
if (!iterator.hasNext()) {
return EMPTY;
}
final Object first = iterator.next();
if (!iterator.hasNext()) {
return Objects.toString(first, "");
}
// two or more elements
final StringBuilder buf = new StringBuilder(STRING_BUILDER_SIZE); // Java default is 16, probably too small
if (first != null) {
buf.append(first);
}
while (iterator.hasNext()) {
if (separator != null) {
buf.append(separator);
}
final Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided {@code List} into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join([null, "", "a"], ';') = ";;a"
* </pre>
*
* @param list the {@code List} of values to join together, may be null
* @param separator the separator character to use
* @param startIndex the first index to start joining from. It is
* an error to pass in a start index past the end of the list
* @param endIndex the index to stop joining from (exclusive). It is
* an error to pass in an end index past the end of the list
* @return the joined String, {@code null} if null list input
* @since 3.8
*/
public static String join(final List<?> list, final char separator, final int startIndex, final int endIndex) {
if (list == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final List<?> subList = list.subList(startIndex, endIndex);
return join(subList.iterator(), separator);
}
/**
* <p>Joins the elements of the provided {@code List} into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join([null, "", "a"], ';') = ";;a"
* </pre>
*
* @param list the {@code List} of values to join together, may be null
* @param separator the separator character to use
* @param startIndex the first index to start joining from. It is
* an error to pass in a start index past the end of the list
* @param endIndex the index to stop joining from (exclusive). It is
* an error to pass in an end index past the end of the list
* @return the joined String, {@code null} if null list input
* @since 3.8
*/
public static String join(final List<?> list, final String separator, final int startIndex, final int endIndex) {
if (list == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final List<?> subList = list.subList(startIndex, endIndex);
return join(subList.iterator(), separator);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final long[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in a start index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final long[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = newStringBuilder(noOfItems);
buf.append(array[startIndex]);
for (int i = startIndex + 1; i < endIndex; i++) {
buf.append(separator);
buf.append(array[i]);
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join([null, "", "a"], ';') = ";;a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use
* @return the joined String, {@code null} if null array input
* @since 2.0
*/
public static String join(final Object[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join([null, "", "a"], ';') = ";;a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use
* @param startIndex the first index to start joining from. It is
* an error to pass in a start index past the end of the array
* @param endIndex the index to stop joining from (exclusive). It is
* an error to pass in an end index past the end of the array
* @return the joined String, {@code null} if null array input
* @since 2.0
*/
public static String join(final Object[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = newStringBuilder(noOfItems);
if (array[startIndex] != null) {
buf.append(array[startIndex]);
}
for (int i = startIndex + 1; i < endIndex; i++) {
buf.append(separator);
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* A {@code null} separator is the same as an empty String ("").
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join(["a", "b", "c"], "") = "abc"
* StringUtils.join([null, "", "a"], ',') = ",,a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, {@code null} if null array input
*/
public static String join(final Object[] array, final String separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* A {@code null} separator is the same as an empty String ("").
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *, *, *) = null
* StringUtils.join([], *, *, *) = ""
* StringUtils.join([null], *, *, *) = ""
* StringUtils.join(["a", "b", "c"], "--", 0, 3) = "a--b--c"
* StringUtils.join(["a", "b", "c"], "--", 1, 3) = "b--c"
* StringUtils.join(["a", "b", "c"], "--", 2, 3) = "c"
* StringUtils.join(["a", "b", "c"], "--", 2, 2) = ""
* StringUtils.join(["a", "b", "c"], null, 0, 3) = "abc"
* StringUtils.join(["a", "b", "c"], "", 0, 3) = "abc"
* StringUtils.join([null, "", "a"], ',', 0, 3) = ",,a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @param startIndex the first index to start joining from.
* @param endIndex the index to stop joining from (exclusive).
* @return the joined String, {@code null} if null array input; or the empty string
* if {@code endIndex - startIndex <= 0}. The number of joined entries is given by
* {@code endIndex - startIndex}
* @throws ArrayIndexOutOfBoundsException ife<br>
* {@code startIndex < 0} or <br>
* {@code startIndex >= array.length()} or <br>
* {@code endIndex < 0} or <br>
* {@code endIndex > array.length()}
*/
public static String join(final Object[] array, String separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
if (separator == null) {
separator = EMPTY;
}
// endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator))
// (Assuming that all Strings are roughly equally long)
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = newStringBuilder(noOfItems);
if (array[startIndex] != null) {
buf.append(array[startIndex]);
}
for (int i = startIndex + 1; i < endIndex; i++) {
buf.append(separator);
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final short[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in a start index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final short[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = newStringBuilder(noOfItems);
buf.append(array[startIndex]);
for (int i = startIndex + 1; i < endIndex; i++) {
buf.append(separator);
buf.append(array[i]);
}
return buf.toString();
}
// Joining
//-----------------------------------------------------------------------
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No separator is added to the joined String.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null) = null
* StringUtils.join([]) = ""
* StringUtils.join([null]) = ""
* StringUtils.join(["a", "b", "c"]) = "abc"
* StringUtils.join([null, "", "a"]) = "a"
* </pre>
*
* @param <T> the specific type of values to join together
* @param elements the values to join together, may be null
* @return the joined String, {@code null} if null array input
* @since 2.0
* @since 3.0 Changed signature to use varargs
*/
@SafeVarargs
public static <T> String join(final T... elements) {
return join(elements, null);
}
/**
* <p>Joins the elements of the provided varargs into a
* single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list.
* {@code null} elements and separator are treated as empty Strings ("").</p>
*
* <pre>
* StringUtils.joinWith(",", {"a", "b"}) = "a,b"
* StringUtils.joinWith(",", {"a", "b",""}) = "a,b,"
* StringUtils.joinWith(",", {"a", null, "b"}) = "a,,b"
* StringUtils.joinWith(null, {"a", "b"}) = "ab"
* </pre>
*
* @param separator the separator character to use, null treated as ""
* @param objects the varargs providing the values to join together. {@code null} elements are treated as ""
* @return the joined String.
* @throws java.lang.IllegalArgumentException if a null varargs is provided
* @since 3.5
*/
public static String joinWith(final String separator, final Object... objects) {
if (objects == null) {
throw new IllegalArgumentException("Object varargs must not be null");
}
final String sanitizedSeparator = defaultString(separator);
final StringBuilder result = new StringBuilder();
final Iterator<Object> iterator = Arrays.asList(objects).iterator();
while (iterator.hasNext()) {
final String value = Objects.toString(iterator.next(), "");
result.append(value);
if (iterator.hasNext()) {
result.append(sanitizedSeparator);
}
}
return result.toString();
}
/**
* <p>Finds the last index within a CharSequence, handling {@code null}.
* This method uses {@link String#lastIndexOf(String)} if possible.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.</p>
*
* <pre>
* StringUtils.lastIndexOf(null, *) = -1
* StringUtils.lastIndexOf(*, null) = -1
* StringUtils.lastIndexOf("", "") = 0
* StringUtils.lastIndexOf("aabaabaa", "a") = 7
* StringUtils.lastIndexOf("aabaabaa", "b") = 5
* StringUtils.lastIndexOf("aabaabaa", "ab") = 4
* StringUtils.lastIndexOf("aabaabaa", "") = 8
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchSeq the CharSequence to find, may be null
* @return the last index of the search String,
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from lastIndexOf(String, String) to lastIndexOf(CharSequence, CharSequence)
*/
public static int lastIndexOf(final CharSequence seq, final CharSequence searchSeq) {
if (seq == null || searchSeq == null) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.lastIndexOf(seq, searchSeq, seq.length());
}
/**
* <p>Finds the last index within a CharSequence, handling {@code null}.
* This method uses {@link String#lastIndexOf(String, int)} if possible.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A negative start position returns {@code -1}.
* An empty ("") search CharSequence always matches unless the start position is negative.
* A start position greater than the string length searches the whole string.
* The search starts at the startPos and works backwards; matches starting after the start
* position are ignored.
* </p>
*
* <pre>
* StringUtils.lastIndexOf(null, *, *) = -1
* StringUtils.lastIndexOf(*, null, *) = -1
* StringUtils.lastIndexOf("aabaabaa", "a", 8) = 7
* StringUtils.lastIndexOf("aabaabaa", "b", 8) = 5
* StringUtils.lastIndexOf("aabaabaa", "ab", 8) = 4
* StringUtils.lastIndexOf("aabaabaa", "b", 9) = 5
* StringUtils.lastIndexOf("aabaabaa", "b", -1) = -1
* StringUtils.lastIndexOf("aabaabaa", "a", 0) = 0
* StringUtils.lastIndexOf("aabaabaa", "b", 0) = -1
* StringUtils.lastIndexOf("aabaabaa", "b", 1) = -1
* StringUtils.lastIndexOf("aabaabaa", "b", 2) = 2
* StringUtils.lastIndexOf("aabaabaa", "ba", 2) = 2
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchSeq the CharSequence to find, may be null
* @param startPos the start position, negative treated as zero
* @return the last index of the search CharSequence (always ≤ startPos),
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from lastIndexOf(String, String, int) to lastIndexOf(CharSequence, CharSequence, int)
*/
public static int lastIndexOf(final CharSequence seq, final CharSequence searchSeq, final int startPos) {
if (seq == null || searchSeq == null) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.lastIndexOf(seq, searchSeq, startPos);
}
// LastIndexOf
//-----------------------------------------------------------------------
/**
* Returns the index within {@code seq} of the last occurrence of
* the specified character. For values of {@code searchChar} in the
* range from 0 to 0xFFFF (inclusive), the index (in Unicode code
* units) returned is the largest value <i>k</i> such that:
* <blockquote><pre>
* this.charAt(<i>k</i>) == searchChar
* </pre></blockquote>
* is true. For other values of {@code searchChar}, it is the
* largest value <i>k</i> such that:
* <blockquote><pre>
* this.codePointAt(<i>k</i>) == searchChar
* </pre></blockquote>
* is true. In either case, if no such character occurs in this
* string, then {@code -1} is returned. Furthermore, a {@code null} or empty ("")
* {@code CharSequence} will return {@code -1}. The
* {@code seq} {@code CharSequence} object is searched backwards
* starting at the last character.
*
* <pre>
* StringUtils.lastIndexOf(null, *) = -1
* StringUtils.lastIndexOf("", *) = -1
* StringUtils.lastIndexOf("aabaabaa", 'a') = 7
* StringUtils.lastIndexOf("aabaabaa", 'b') = 5
* </pre>
*
* @param seq the {@code CharSequence} to check, may be null
* @param searchChar the character to find
* @return the last index of the search character,
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from lastIndexOf(String, int) to lastIndexOf(CharSequence, int)
* @since 3.6 Updated {@link CharSequenceUtils} call to behave more like {@code String}
*/
public static int lastIndexOf(final CharSequence seq, final int searchChar) {
if (isEmpty(seq)) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.lastIndexOf(seq, searchChar, seq.length());
}
/**
* Returns the index within {@code seq} of the last occurrence of
* the specified character, searching backward starting at the
* specified index. For values of {@code searchChar} in the range
* from 0 to 0xFFFF (inclusive), the index returned is the largest
* value <i>k</i> such that:
* <blockquote><pre>
* (this.charAt(<i>k</i>) == searchChar) && (<i>k</i> <= startPos)
* </pre></blockquote>
* is true. For other values of {@code searchChar}, it is the
* largest value <i>k</i> such that:
* <blockquote><pre>
* (this.codePointAt(<i>k</i>) == searchChar) && (<i>k</i> <= startPos)
* </pre></blockquote>
* is true. In either case, if no such character occurs in {@code seq}
* at or before position {@code startPos}, then
* {@code -1} is returned. Furthermore, a {@code null} or empty ("")
* {@code CharSequence} will return {@code -1}. A start position greater
* than the string length searches the whole string.
* The search starts at the {@code startPos} and works backwards;
* matches starting after the start position are ignored.
*
* <p>All indices are specified in {@code char} values
* (Unicode code units).
*
* <pre>
* StringUtils.lastIndexOf(null, *, *) = -1
* StringUtils.lastIndexOf("", *, *) = -1
* StringUtils.lastIndexOf("aabaabaa", 'b', 8) = 5
* StringUtils.lastIndexOf("aabaabaa", 'b', 4) = 2
* StringUtils.lastIndexOf("aabaabaa", 'b', 0) = -1
* StringUtils.lastIndexOf("aabaabaa", 'b', 9) = 5
* StringUtils.lastIndexOf("aabaabaa", 'b', -1) = -1
* StringUtils.lastIndexOf("aabaabaa", 'a', 0) = 0
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchChar the character to find
* @param startPos the start position
* @return the last index of the search character (always ≤ startPos),
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from lastIndexOf(String, int, int) to lastIndexOf(CharSequence, int, int)
*/
public static int lastIndexOf(final CharSequence seq, final int searchChar, final int startPos) {
if (isEmpty(seq)) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.lastIndexOf(seq, searchChar, startPos);
}
/**
* <p>Find the latest index of any of a set of potential substrings.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A {@code null} search array will return {@code -1}.
* A {@code null} or zero length search array entry will be ignored,
* but a search array containing "" will return the length of {@code str}
* if {@code str} is not null. This method uses {@link String#indexOf(String)} if possible</p>
*
* <pre>
* StringUtils.lastIndexOfAny(null, *) = -1
* StringUtils.lastIndexOfAny(*, null) = -1
* StringUtils.lastIndexOfAny(*, []) = -1
* StringUtils.lastIndexOfAny(*, [null]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["ab", "cd"]) = 6
* StringUtils.lastIndexOfAny("zzabyycdxx", ["cd", "ab"]) = 6
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn", "op"]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn", "op"]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn", ""]) = 10
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStrs the CharSequences to search for, may be null
* @return the last index of any of the CharSequences, -1 if no match
* @since 3.0 Changed signature from lastIndexOfAny(String, String[]) to lastIndexOfAny(CharSequence, CharSequence)
*/
public static int lastIndexOfAny(final CharSequence str, final CharSequence... searchStrs) {
if (str == null || searchStrs == null) {
return INDEX_NOT_FOUND;
}
int ret = INDEX_NOT_FOUND;
int tmp = 0;
for (final CharSequence search : searchStrs) {
if (search == null) {
continue;
}
tmp = CharSequenceUtils.lastIndexOf(str, search, str.length());
if (tmp > ret) {
ret = tmp;
}
}
return ret;
}
/**
* <p>Case in-sensitive find of the last index within a CharSequence.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A negative start position returns {@code -1}.
* An empty ("") search CharSequence always matches unless the start position is negative.
* A start position greater than the string length searches the whole string.</p>
*
* <pre>
* StringUtils.lastIndexOfIgnoreCase(null, *) = -1
* StringUtils.lastIndexOfIgnoreCase(*, null) = -1
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A") = 7
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B") = 5
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB") = 4
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @return the first index of the search CharSequence,
* -1 if no match or {@code null} string input
* @since 2.5
* @since 3.0 Changed signature from lastIndexOfIgnoreCase(String, String) to lastIndexOfIgnoreCase(CharSequence, CharSequence)
*/
public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
return lastIndexOfIgnoreCase(str, searchStr, str.length());
}
/**
* <p>Case in-sensitive find of the last index within a CharSequence
* from the specified position.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A negative start position returns {@code -1}.
* An empty ("") search CharSequence always matches unless the start position is negative.
* A start position greater than the string length searches the whole string.
* The search starts at the startPos and works backwards; matches starting after the start
* position are ignored.
* </p>
*
* <pre>
* StringUtils.lastIndexOfIgnoreCase(null, *, *) = -1
* StringUtils.lastIndexOfIgnoreCase(*, null, *) = -1
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 8) = 7
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 8) = 5
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB", 8) = 4
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 9) = 5
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", -1) = -1
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 0) = 0
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 0) = -1
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @param startPos the start position
* @return the last index of the search CharSequence (always ≤ startPos),
* -1 if no match or {@code null} input
* @since 2.5
* @since 3.0 Changed signature from lastIndexOfIgnoreCase(String, String, int) to lastIndexOfIgnoreCase(CharSequence, CharSequence, int)
*/
public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int startPos) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
if (startPos > str.length() - searchStr.length()) {
startPos = str.length() - searchStr.length();
}
if (startPos < 0) {
return INDEX_NOT_FOUND;
}
if (searchStr.length() == 0) {
return startPos;
}
for (int i = startPos; i >= 0; i--) {
if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, searchStr.length())) {
return i;
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Finds the n-th last index within a String, handling {@code null}.
* This method uses {@link String#lastIndexOf(String)}.</p>
*
* <p>A {@code null} String will return {@code -1}.</p>
*
* <pre>
* StringUtils.lastOrdinalIndexOf(null, *, *) = -1
* StringUtils.lastOrdinalIndexOf(*, null, *) = -1
* StringUtils.lastOrdinalIndexOf("", "", *) = 0
* StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 1) = 7
* StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 2) = 6
* StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 1) = 5
* StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 2) = 2
* StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 1) = 4
* StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2) = 1
* StringUtils.lastOrdinalIndexOf("aabaabaa", "", 1) = 8
* StringUtils.lastOrdinalIndexOf("aabaabaa", "", 2) = 8
* </pre>
*
* <p>Note that 'tail(CharSequence str, int n)' may be implemented as: </p>
*
* <pre>
* str.substring(lastOrdinalIndexOf(str, "\n", n) + 1)
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @param ordinal the n-th last {@code searchStr} to find
* @return the n-th last index of the search CharSequence,
* {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input
* @since 2.5
* @since 3.0 Changed signature from lastOrdinalIndexOf(String, String, int) to lastOrdinalIndexOf(CharSequence, CharSequence, int)
*/
public static int lastOrdinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal) {
return ordinalIndexOf(str, searchStr, ordinal, true);
}
// Left/Right/Mid
//-----------------------------------------------------------------------
/**
* <p>Gets the leftmost {@code len} characters of a String.</p>
*
* <p>If {@code len} characters are not available, or the
* String is {@code null}, the String will be returned without
* an exception. An empty String is returned if len is negative.</p>
*
* <pre>
* StringUtils.left(null, *) = null
* StringUtils.left(*, -ve) = ""
* StringUtils.left("", *) = ""
* StringUtils.left("abc", 0) = ""
* StringUtils.left("abc", 2) = "ab"
* StringUtils.left("abc", 4) = "abc"
* </pre>
*
* @param str the String to get the leftmost characters from, may be null
* @param len the length of the required String
* @return the leftmost characters, {@code null} if null String input
*/
public static String left(final String str, final int len) {
if (str == null) {
return null;
}
if (len < 0) {
return EMPTY;
}
if (str.length() <= len) {
return str;
}
return str.substring(0, len);
}
/**
* <p>Left pad a String with spaces (' ').</p>
*
* <p>The String is padded to the size of {@code size}.</p>
*
* <pre>
* StringUtils.leftPad(null, *) = null
* StringUtils.leftPad("", 3) = " "
* StringUtils.leftPad("bat", 3) = "bat"
* StringUtils.leftPad("bat", 5) = " bat"
* StringUtils.leftPad("bat", 1) = "bat"
* StringUtils.leftPad("bat", -1) = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @return left padded String or original String if no padding is necessary,
* {@code null} if null String input
*/
public static String leftPad(final String str, final int size) {
return leftPad(str, size, ' ');
}
/**
* <p>Left pad a String with a specified character.</p>
*
* <p>Pad to a size of {@code size}.</p>
*
* <pre>
* StringUtils.leftPad(null, *, *) = null
* StringUtils.leftPad("", 3, 'z') = "zzz"
* StringUtils.leftPad("bat", 3, 'z') = "bat"
* StringUtils.leftPad("bat", 5, 'z') = "zzbat"
* StringUtils.leftPad("bat", 1, 'z') = "bat"
* StringUtils.leftPad("bat", -1, 'z') = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padChar the character to pad with
* @return left padded String or original String if no padding is necessary,
* {@code null} if null String input
* @since 2.0
*/
public static String leftPad(final String str, final int size, final char padChar) {
if (str == null) {
return null;
}
final int pads = size - str.length();
if (pads <= 0) {
return str; // returns original String when possible
}
if (pads > PAD_LIMIT) {
return leftPad(str, size, String.valueOf(padChar));
}
return repeat(padChar, pads).concat(str);
}
/**
* <p>Left pad a String with a specified String.</p>
*
* <p>Pad to a size of {@code size}.</p>
*
* <pre>
* StringUtils.leftPad(null, *, *) = null
* StringUtils.leftPad("", 3, "z") = "zzz"
* StringUtils.leftPad("bat", 3, "yz") = "bat"
* StringUtils.leftPad("bat", 5, "yz") = "yzbat"
* StringUtils.leftPad("bat", 8, "yz") = "yzyzybat"
* StringUtils.leftPad("bat", 1, "yz") = "bat"
* StringUtils.leftPad("bat", -1, "yz") = "bat"
* StringUtils.leftPad("bat", 5, null) = " bat"
* StringUtils.leftPad("bat", 5, "") = " bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padStr the String to pad with, null or empty treated as single space
* @return left padded String or original String if no padding is necessary,
* {@code null} if null String input
*/
public static String leftPad(final String str, final int size, String padStr) {
if (str == null) {
return null;
}
if (isEmpty(padStr)) {
padStr = SPACE;
}
final int padLen = padStr.length();
final int strLen = str.length();
final int pads = size - strLen;
if (pads <= 0) {
return str; // returns original String when possible
}
if (padLen == 1 && pads <= PAD_LIMIT) {
return leftPad(str, size, padStr.charAt(0));
}
if (pads == padLen) {
return padStr.concat(str);
} else if (pads < padLen) {
return padStr.substring(0, pads).concat(str);
} else {
final char[] padding = new char[pads];
final char[] padChars = padStr.toCharArray();
for (int i = 0; i < pads; i++) {
padding[i] = padChars[i % padLen];
}
return new String(padding).concat(str);
}
}
/**
* Gets a CharSequence length or {@code 0} if the CharSequence is
* {@code null}.
*
* @param cs
* a CharSequence or {@code null}
* @return CharSequence length or {@code 0} if the CharSequence is
* {@code null}.
* @since 2.4
* @since 3.0 Changed signature from length(String) to length(CharSequence)
*/
public static int length(final CharSequence cs) {
return cs == null ? 0 : cs.length();
}
/**
* <p>Converts a String to lower case as per {@link String#toLowerCase()}.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.lowerCase(null) = null
* StringUtils.lowerCase("") = ""
* StringUtils.lowerCase("aBc") = "abc"
* </pre>
*
* <p><strong>Note:</strong> As described in the documentation for {@link String#toLowerCase()},
* the result of this method is affected by the current locale.
* For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}
* should be used with a specific locale (e.g. {@link Locale#ENGLISH}).</p>
*
* @param str the String to lower case, may be null
* @return the lower cased String, {@code null} if null String input
*/
public static String lowerCase(final String str) {
if (str == null) {
return null;
}
return str.toLowerCase();
}
/**
* <p>Converts a String to lower case as per {@link String#toLowerCase(Locale)}.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.lowerCase(null, Locale.ENGLISH) = null
* StringUtils.lowerCase("", Locale.ENGLISH) = ""
* StringUtils.lowerCase("aBc", Locale.ENGLISH) = "abc"
* </pre>
*
* @param str the String to lower case, may be null
* @param locale the locale that defines the case transformation rules, must not be null
* @return the lower cased String, {@code null} if null String input
* @since 2.5
*/
public static String lowerCase(final String str, final Locale locale) {
if (str == null) {
return null;
}
return str.toLowerCase(locale);
}
private static int[] matches(final CharSequence first, final CharSequence second) {
CharSequence max, min;
if (first.length() > second.length()) {
max = first;
min = second;
} else {
max = second;
min = first;
}
final int range = Math.max(max.length() / 2 - 1, 0);
final int[] matchIndexes = new int[min.length()];
Arrays.fill(matchIndexes, -1);
final boolean[] matchFlags = new boolean[max.length()];
int matches = 0;
for (int mi = 0; mi < min.length(); mi++) {
final char c1 = min.charAt(mi);
for (int xi = Math.max(mi - range, 0), xn = Math.min(mi + range + 1, max.length()); xi < xn; xi++) {
if (!matchFlags[xi] && c1 == max.charAt(xi)) {
matchIndexes[mi] = xi;
matchFlags[xi] = true;
matches++;
break;
}
}
}
final char[] ms1 = new char[matches];
final char[] ms2 = new char[matches];
for (int i = 0, si = 0; i < min.length(); i++) {
if (matchIndexes[i] != -1) {
ms1[si] = min.charAt(i);
si++;
}
}
for (int i = 0, si = 0; i < max.length(); i++) {
if (matchFlags[i]) {
ms2[si] = max.charAt(i);
si++;
}
}
int transpositions = 0;
for (int mi = 0; mi < ms1.length; mi++) {
if (ms1[mi] != ms2[mi]) {
transpositions++;
}
}
int prefix = 0;
for (int mi = 0; mi < min.length(); mi++) {
if (first.charAt(mi) == second.charAt(mi)) {
prefix++;
} else {
break;
}
}
return new int[] { matches, transpositions / 2, prefix, max.length() };
}
/**
* <p>Gets {@code len} characters from the middle of a String.</p>
*
* <p>If {@code len} characters are not available, the remainder
* of the String will be returned without an exception. If the
* String is {@code null}, {@code null} will be returned.
* An empty String is returned if len is negative or exceeds the
* length of {@code str}.</p>
*
* <pre>
* StringUtils.mid(null, *, *) = null
* StringUtils.mid(*, *, -ve) = ""
* StringUtils.mid("", 0, *) = ""
* StringUtils.mid("abc", 0, 2) = "ab"
* StringUtils.mid("abc", 0, 4) = "abc"
* StringUtils.mid("abc", 2, 4) = "c"
* StringUtils.mid("abc", 4, 2) = ""
* StringUtils.mid("abc", -2, 2) = "ab"
* </pre>
*
* @param str the String to get the characters from, may be null
* @param pos the position to start from, negative treated as zero
* @param len the length of the required String
* @return the middle characters, {@code null} if null String input
*/
public static String mid(final String str, int pos, final int len) {
if (str == null) {
return null;
}
if (len < 0 || pos > str.length()) {
return EMPTY;
}
if (pos < 0) {
pos = 0;
}
if (str.length() <= pos + len) {
return str.substring(pos);
}
return str.substring(pos, pos + len);
}
private static StringBuilder newStringBuilder(final int noOfItems) {
return new StringBuilder(noOfItems * 16);
}
/**
* <p>
* Similar to <a
* href="http://www.w3.org/TR/xpath/#function-normalize-space">http://www.w3.org/TR/xpath/#function-normalize
* -space</a>
* </p>
* <p>
* The function returns the argument string with whitespace normalized by using
* {@code {@link #trim(String)}} to remove leading and trailing whitespace
* and then replacing sequences of whitespace characters by a single space.
* </p>
* In XML Whitespace characters are the same as those allowed by the <a
* href="http://www.w3.org/TR/REC-xml/#NT-S">S</a> production, which is S ::= (#x20 | #x9 | #xD | #xA)+
* <p>
* Java's regexp pattern \s defines whitespace as [ \t\n\x0B\f\r]
*
* <p>For reference:</p>
* <ul>
* <li>\x0B = vertical tab</li>
* <li>\f = #xC = form feed</li>
* <li>#x20 = space</li>
* <li>#x9 = \t</li>
* <li>#xA = \n</li>
* <li>#xD = \r</li>
* </ul>
*
* <p>
* The difference is that Java's whitespace includes vertical tab and form feed, which this functional will also
* normalize. Additionally {@code {@link #trim(String)}} removes control characters (char <= 32) from both
* ends of this String.
* </p>
*
* @see Pattern
* @see #trim(String)
* @see <a
* href="http://www.w3.org/TR/xpath/#function-normalize-space">http://www.w3.org/TR/xpath/#function-normalize-space</a>
* @param str the source String to normalize whitespaces from, may be null
* @return the modified string with whitespace normalized, {@code null} if null String input
*
* @since 3.0
*/
public static String normalizeSpace(final String str) {
// LANG-1020: Improved performance significantly by normalizing manually instead of using regex
// See https://github.com/librucha/commons-lang-normalizespaces-benchmark for performance test
if (isEmpty(str)) {
return str;
}
final int size = str.length();
final char[] newChars = new char[size];
int count = 0;
int whitespacesCount = 0;
boolean startWhitespaces = true;
for (int i = 0; i < size; i++) {
final char actualChar = str.charAt(i);
final boolean isWhitespace = Character.isWhitespace(actualChar);
if (isWhitespace) {
if (whitespacesCount == 0 && !startWhitespaces) {
newChars[count++] = SPACE.charAt(0);
}
whitespacesCount++;
} else {
startWhitespaces = false;
newChars[count++] = (actualChar == 160 ? 32 : actualChar);
whitespacesCount = 0;
}
}
if (startWhitespaces) {
return EMPTY;
}
return new String(newChars, 0, count - (whitespacesCount > 0 ? 1 : 0)).trim();
}
/**
* <p>Finds the n-th index within a CharSequence, handling {@code null}.
* This method uses {@link String#indexOf(String)} if possible.</p>
* <p><b>Note:</b> The code starts looking for a match at the start of the target,
* incrementing the starting index by one after each successful match
* (unless {@code searchStr} is an empty string in which case the position
* is never incremented and {@code 0} is returned immediately).
* This means that matches may overlap.</p>
* <p>A {@code null} CharSequence will return {@code -1}.</p>
*
* <pre>
* StringUtils.ordinalIndexOf(null, *, *) = -1
* StringUtils.ordinalIndexOf(*, null, *) = -1
* StringUtils.ordinalIndexOf("", "", *) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "a", 1) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "a", 2) = 1
* StringUtils.ordinalIndexOf("aabaabaa", "b", 1) = 2
* StringUtils.ordinalIndexOf("aabaabaa", "b", 2) = 5
* StringUtils.ordinalIndexOf("aabaabaa", "ab", 1) = 1
* StringUtils.ordinalIndexOf("aabaabaa", "ab", 2) = 4
* StringUtils.ordinalIndexOf("aabaabaa", "", 1) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "", 2) = 0
* </pre>
*
* <p>Matches may overlap:</p>
* <pre>
* StringUtils.ordinalIndexOf("ababab", "aba", 1) = 0
* StringUtils.ordinalIndexOf("ababab", "aba", 2) = 2
* StringUtils.ordinalIndexOf("ababab", "aba", 3) = -1
*
* StringUtils.ordinalIndexOf("abababab", "abab", 1) = 0
* StringUtils.ordinalIndexOf("abababab", "abab", 2) = 2
* StringUtils.ordinalIndexOf("abababab", "abab", 3) = 4
* StringUtils.ordinalIndexOf("abababab", "abab", 4) = -1
* </pre>
*
* <p>Note that 'head(CharSequence str, int n)' may be implemented as: </p>
*
* <pre>
* str.substring(0, lastOrdinalIndexOf(str, "\n", n))
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @param ordinal the n-th {@code searchStr} to find
* @return the n-th index of the search CharSequence,
* {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input
* @since 2.1
* @since 3.0 Changed signature from ordinalIndexOf(String, String, int) to ordinalIndexOf(CharSequence, CharSequence, int)
*/
public static int ordinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal) {
return ordinalIndexOf(str, searchStr, ordinal, false);
}
/**
* <p>Finds the n-th index within a String, handling {@code null}.
* This method uses {@link String#indexOf(String)} if possible.</p>
* <p>Note that matches may overlap<p>
*
* <p>A {@code null} CharSequence will return {@code -1}.</p>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @param ordinal the n-th {@code searchStr} to find, overlapping matches are allowed.
* @param lastIndex true if lastOrdinalIndexOf() otherwise false if ordinalIndexOf()
* @return the n-th index of the search CharSequence,
* {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input
*/
// Shared code between ordinalIndexOf(String, String, int) and lastOrdinalIndexOf(String, String, int)
private static int ordinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal, final boolean lastIndex) {
if (str == null || searchStr == null || ordinal <= 0) {
return INDEX_NOT_FOUND;
}
if (searchStr.length() == 0) {
return lastIndex ? str.length() : 0;
}
int found = 0;
// set the initial index beyond the end of the string
// this is to allow for the initial index decrement/increment
int index = lastIndex ? str.length() : INDEX_NOT_FOUND;
do {
if (lastIndex) {
index = CharSequenceUtils.lastIndexOf(str, searchStr, index - 1); // step backwards thru string
} else {
index = CharSequenceUtils.indexOf(str, searchStr, index + 1); // step forwards through string
}
if (index < 0) {
return index;
}
found++;
} while (found < ordinal);
return index;
}
// Overlay
//-----------------------------------------------------------------------
/**
* <p>Overlays part of a String with another String.</p>
*
* <p>A {@code null} string input returns {@code null}.
* A negative index is treated as zero.
* An index greater than the string length is treated as the string length.
* The start index is always the smaller of the two indices.</p>
*
* <pre>
* StringUtils.overlay(null, *, *, *) = null
* StringUtils.overlay("", "abc", 0, 0) = "abc"
* StringUtils.overlay("abcdef", null, 2, 4) = "abef"
* StringUtils.overlay("abcdef", "", 2, 4) = "abef"
* StringUtils.overlay("abcdef", "", 4, 2) = "abef"
* StringUtils.overlay("abcdef", "zzzz", 2, 4) = "abzzzzef"
* StringUtils.overlay("abcdef", "zzzz", 4, 2) = "abzzzzef"
* StringUtils.overlay("abcdef", "zzzz", -1, 4) = "zzzzef"
* StringUtils.overlay("abcdef", "zzzz", 2, 8) = "abzzzz"
* StringUtils.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef"
* StringUtils.overlay("abcdef", "zzzz", 8, 10) = "abcdefzzzz"
* </pre>
*
* @param str the String to do overlaying in, may be null
* @param overlay the String to overlay, may be null
* @param start the position to start overlaying at
* @param end the position to stop overlaying before
* @return overlayed String, {@code null} if null String input
* @since 2.0
*/
public static String overlay(final String str, String overlay, int start, int end) {
if (str == null) {
return null;
}
if (overlay == null) {
overlay = EMPTY;
}
final int len = str.length();
if (start < 0) {
start = 0;
}
if (start > len) {
start = len;
}
if (end < 0) {
end = 0;
}
if (end > len) {
end = len;
}
if (start > end) {
final int temp = start;
start = end;
end = temp;
}
return str.substring(0, start) +
overlay +
str.substring(end);
}
/**
* Prepends the prefix to the start of the string if the string does not
* already start with any of the prefixes.
*
* @param str The string.
* @param prefix The prefix to prepend to the start of the string.
* @param ignoreCase Indicates whether the compare should ignore case.
* @param prefixes Additional prefixes that are valid (optional).
*
* @return A new String if prefix was prepended, the same string otherwise.
*/
private static String prependIfMissing(final String str, final CharSequence prefix, final boolean ignoreCase, final CharSequence... prefixes) {
if (str == null || isEmpty(prefix) || startsWith(str, prefix, ignoreCase)) {
return str;
}
if (ArrayUtils.isNotEmpty(prefixes)) {
for (final CharSequence p : prefixes) {
if (startsWith(str, p, ignoreCase)) {
return str;
}
}
}
return prefix.toString() + str;
}
/**
* Prepends the prefix to the start of the string if the string does not
* already start with any of the prefixes.
*
* <pre>
* StringUtils.prependIfMissing(null, null) = null
* StringUtils.prependIfMissing("abc", null) = "abc"
* StringUtils.prependIfMissing("", "xyz") = "xyz"
* StringUtils.prependIfMissing("abc", "xyz") = "xyzabc"
* StringUtils.prependIfMissing("xyzabc", "xyz") = "xyzabc"
* StringUtils.prependIfMissing("XYZabc", "xyz") = "xyzXYZabc"
* </pre>
* <p>With additional prefixes,</p>
* <pre>
* StringUtils.prependIfMissing(null, null, null) = null
* StringUtils.prependIfMissing("abc", null, null) = "abc"
* StringUtils.prependIfMissing("", "xyz", null) = "xyz"
* StringUtils.prependIfMissing("abc", "xyz", new CharSequence[]{null}) = "xyzabc"
* StringUtils.prependIfMissing("abc", "xyz", "") = "abc"
* StringUtils.prependIfMissing("abc", "xyz", "mno") = "xyzabc"
* StringUtils.prependIfMissing("xyzabc", "xyz", "mno") = "xyzabc"
* StringUtils.prependIfMissing("mnoabc", "xyz", "mno") = "mnoabc"
* StringUtils.prependIfMissing("XYZabc", "xyz", "mno") = "xyzXYZabc"
* StringUtils.prependIfMissing("MNOabc", "xyz", "mno") = "xyzMNOabc"
* </pre>
*
* @param str The string.
* @param prefix The prefix to prepend to the start of the string.
* @param prefixes Additional prefixes that are valid.
*
* @return A new String if prefix was prepended, the same string otherwise.
*
* @since 3.2
*/
public static String prependIfMissing(final String str, final CharSequence prefix, final CharSequence... prefixes) {
return prependIfMissing(str, prefix, false, prefixes);
}
/**
* Prepends the prefix to the start of the string if the string does not
* already start, case insensitive, with any of the prefixes.
*
* <pre>
* StringUtils.prependIfMissingIgnoreCase(null, null) = null
* StringUtils.prependIfMissingIgnoreCase("abc", null) = "abc"
* StringUtils.prependIfMissingIgnoreCase("", "xyz") = "xyz"
* StringUtils.prependIfMissingIgnoreCase("abc", "xyz") = "xyzabc"
* StringUtils.prependIfMissingIgnoreCase("xyzabc", "xyz") = "xyzabc"
* StringUtils.prependIfMissingIgnoreCase("XYZabc", "xyz") = "XYZabc"
* </pre>
* <p>With additional prefixes,</p>
* <pre>
* StringUtils.prependIfMissingIgnoreCase(null, null, null) = null
* StringUtils.prependIfMissingIgnoreCase("abc", null, null) = "abc"
* StringUtils.prependIfMissingIgnoreCase("", "xyz", null) = "xyz"
* StringUtils.prependIfMissingIgnoreCase("abc", "xyz", new CharSequence[]{null}) = "xyzabc"
* StringUtils.prependIfMissingIgnoreCase("abc", "xyz", "") = "abc"
* StringUtils.prependIfMissingIgnoreCase("abc", "xyz", "mno") = "xyzabc"
* StringUtils.prependIfMissingIgnoreCase("xyzabc", "xyz", "mno") = "xyzabc"
* StringUtils.prependIfMissingIgnoreCase("mnoabc", "xyz", "mno") = "mnoabc"
* StringUtils.prependIfMissingIgnoreCase("XYZabc", "xyz", "mno") = "XYZabc"
* StringUtils.prependIfMissingIgnoreCase("MNOabc", "xyz", "mno") = "MNOabc"
* </pre>
*
* @param str The string.
* @param prefix The prefix to prepend to the start of the string.
* @param prefixes Additional prefixes that are valid (optional).
*
* @return A new String if prefix was prepended, the same string otherwise.
*
* @since 3.2
*/
public static String prependIfMissingIgnoreCase(final String str, final CharSequence prefix, final CharSequence... prefixes) {
return prependIfMissing(str, prefix, true, prefixes);
}
/**
* <p>Removes all occurrences of a character from within the source string.</p>
*
* <p>A {@code null} source string will return {@code null}.
* An empty ("") source string will return the empty string.</p>
*
* <pre>
* StringUtils.remove(null, *) = null
* StringUtils.remove("", *) = ""
* StringUtils.remove("queued", 'u') = "qeed"
* StringUtils.remove("queued", 'z') = "queued"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the char to search for and remove, may be null
* @return the substring with the char removed if found,
* {@code null} if null String input
* @since 2.1
*/
public static String remove(final String str, final char remove) {
if (isEmpty(str) || str.indexOf(remove) == INDEX_NOT_FOUND) {
return str;
}
final char[] chars = str.toCharArray();
int pos = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] != remove) {
chars[pos++] = chars[i];
}
}
return new String(chars, 0, pos);
}
/**
* <p>Removes all occurrences of a substring from within the source string.</p>
*
* <p>A {@code null} source string will return {@code null}.
* An empty ("") source string will return the empty string.
* A {@code null} remove string will return the source string.
* An empty ("") remove string will return the source string.</p>
*
* <pre>
* StringUtils.remove(null, *) = null
* StringUtils.remove("", *) = ""
* StringUtils.remove(*, null) = *
* StringUtils.remove(*, "") = *
* StringUtils.remove("queued", "ue") = "qd"
* StringUtils.remove("queued", "zz") = "queued"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for and remove, may be null
* @return the substring with the string removed if found,
* {@code null} if null String input
* @since 2.1
*/
public static String remove(final String str, final String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
return replace(str, remove, EMPTY, -1);
}
/**
* <p>Removes each substring of the text String that matches the given regular expression.</p>
*
* This method is a {@code null} safe equivalent to:
* <ul>
* <li>{@code text.replaceAll(regex, StringUtils.EMPTY)}</li>
* <li>{@code Pattern.compile(regex).matcher(text).replaceAll(StringUtils.EMPTY)}</li>
* </ul>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <p>Unlike in the {@link #removePattern(String, String)} method, the {@link Pattern#DOTALL} option
* is NOT automatically added.
* To use the DOTALL option prepend {@code "(?s)"} to the regex.
* DOTALL is also known as single-line mode in Perl.</p>
*
* <pre>
* StringUtils.removeAll(null, *) = null
* StringUtils.removeAll("any", (String) null) = "any"
* StringUtils.removeAll("any", "") = "any"
* StringUtils.removeAll("any", ".*") = ""
* StringUtils.removeAll("any", ".+") = ""
* StringUtils.removeAll("abc", ".?") = ""
* StringUtils.removeAll("A<__>\n<__>B", "<.*>") = "A\nB"
* StringUtils.removeAll("A<__>\n<__>B", "(?s)<.*>") = "AB"
* StringUtils.removeAll("ABCabc123abc", "[a-z]") = "ABC123"
* </pre>
*
* @param text text to remove from, may be null
* @param regex the regular expression to which this string is to be matched
* @return the text with any removes processed,
* {@code null} if null String input
*
* @throws java.util.regex.PatternSyntaxException
* if the regular expression's syntax is invalid
*
* @see #replaceAll(String, String, String)
* @see #removePattern(String, String)
* @see String#replaceAll(String, String)
* @see java.util.regex.Pattern
* @see java.util.regex.Pattern#DOTALL
* @since 3.5
*
* @deprecated Moved to RegExUtils.
*/
@Deprecated
public static String removeAll(final String text, final String regex) {
return RegExUtils.removeAll(text, regex);
}
/**
* <p>Removes a substring only if it is at the end of a source string,
* otherwise returns the source string.</p>
*
* <p>A {@code null} source string will return {@code null}.
* An empty ("") source string will return the empty string.
* A {@code null} search string will return the source string.</p>
*
* <pre>
* StringUtils.removeEnd(null, *) = null
* StringUtils.removeEnd("", *) = ""
* StringUtils.removeEnd(*, null) = *
* StringUtils.removeEnd("www.domain.com", ".com.") = "www.domain.com"
* StringUtils.removeEnd("www.domain.com", ".com") = "www.domain"
* StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeEnd("abc", "") = "abc"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for and remove, may be null
* @return the substring with the string removed if found,
* {@code null} if null String input
* @since 2.1
*/
public static String removeEnd(final String str, final String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (str.endsWith(remove)) {
return str.substring(0, str.length() - remove.length());
}
return str;
}
/**
* <p>Case insensitive removal of a substring if it is at the end of a source string,
* otherwise returns the source string.</p>
*
* <p>A {@code null} source string will return {@code null}.
* An empty ("") source string will return the empty string.
* A {@code null} search string will return the source string.</p>
*
* <pre>
* StringUtils.removeEndIgnoreCase(null, *) = null
* StringUtils.removeEndIgnoreCase("", *) = ""
* StringUtils.removeEndIgnoreCase(*, null) = *
* StringUtils.removeEndIgnoreCase("www.domain.com", ".com.") = "www.domain.com"
* StringUtils.removeEndIgnoreCase("www.domain.com", ".com") = "www.domain"
* StringUtils.removeEndIgnoreCase("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeEndIgnoreCase("abc", "") = "abc"
* StringUtils.removeEndIgnoreCase("www.domain.com", ".COM") = "www.domain")
* StringUtils.removeEndIgnoreCase("www.domain.COM", ".com") = "www.domain")
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for (case insensitive) and remove, may be null
* @return the substring with the string removed if found,
* {@code null} if null String input
* @since 2.4
*/
public static String removeEndIgnoreCase(final String str, final String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (endsWithIgnoreCase(str, remove)) {
return str.substring(0, str.length() - remove.length());
}
return str;
}
/**
* <p>Removes the first substring of the text string that matches the given regular expression.</p>
*
* This method is a {@code null} safe equivalent to:
* <ul>
* <li>{@code text.replaceFirst(regex, StringUtils.EMPTY)}</li>
* <li>{@code Pattern.compile(regex).matcher(text).replaceFirst(StringUtils.EMPTY)}</li>
* </ul>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <p>The {@link Pattern#DOTALL} option is NOT automatically added.
* To use the DOTALL option prepend {@code "(?s)"} to the regex.
* DOTALL is also known as single-line mode in Perl.</p>
*
* <pre>
* StringUtils.removeFirst(null, *) = null
* StringUtils.removeFirst("any", (String) null) = "any"
* StringUtils.removeFirst("any", "") = "any"
* StringUtils.removeFirst("any", ".*") = ""
* StringUtils.removeFirst("any", ".+") = ""
* StringUtils.removeFirst("abc", ".?") = "bc"
* StringUtils.removeFirst("A<__>\n<__>B", "<.*>") = "A\n<__>B"
* StringUtils.removeFirst("A<__>\n<__>B", "(?s)<.*>") = "AB"
* StringUtils.removeFirst("ABCabc123", "[a-z]") = "ABCbc123"
* StringUtils.removeFirst("ABCabc123abc", "[a-z]+") = "ABC123abc"
* </pre>
*
* @param text text to remove from, may be null
* @param regex the regular expression to which this string is to be matched
* @return the text with the first replacement processed,
* {@code null} if null String input
*
* @throws java.util.regex.PatternSyntaxException
* if the regular expression's syntax is invalid
*
* @see #replaceFirst(String, String, String)
* @see String#replaceFirst(String, String)
* @see java.util.regex.Pattern
* @see java.util.regex.Pattern#DOTALL
* @since 3.5
*
* @deprecated Moved to RegExUtils.
*/
@Deprecated
public static String removeFirst(final String text, final String regex) {
return replaceFirst(text, regex, EMPTY);
}
/**
* <p>
* Case insensitive removal of all occurrences of a substring from within
* the source string.
* </p>
*
* <p>
* A {@code null} source string will return {@code null}. An empty ("")
* source string will return the empty string. A {@code null} remove string
* will return the source string. An empty ("") remove string will return
* the source string.
* </p>
*
* <pre>
* StringUtils.removeIgnoreCase(null, *) = null
* StringUtils.removeIgnoreCase("", *) = ""
* StringUtils.removeIgnoreCase(*, null) = *
* StringUtils.removeIgnoreCase(*, "") = *
* StringUtils.removeIgnoreCase("queued", "ue") = "qd"
* StringUtils.removeIgnoreCase("queued", "zz") = "queued"
* StringUtils.removeIgnoreCase("quEUed", "UE") = "qd"
* StringUtils.removeIgnoreCase("queued", "zZ") = "queued"
* </pre>
*
* @param str
* the source String to search, may be null
* @param remove
* the String to search for (case insensitive) and remove, may be
* null
* @return the substring with the string removed if found, {@code null} if
* null String input
* @since 3.5
*/
public static String removeIgnoreCase(final String str, final String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
return replaceIgnoreCase(str, remove, EMPTY, -1);
}
/**
* <p>Removes each substring of the source String that matches the given regular expression using the DOTALL option.
* </p>
*
* This call is a {@code null} safe equivalent to:
* <ul>
* <li>{@code source.replaceAll("(?s)" + regex, StringUtils.EMPTY)}</li>
* <li>{@code Pattern.compile(regex, Pattern.DOTALL).matcher(source).replaceAll(StringUtils.EMPTY)}</li>
* </ul>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.removePattern(null, *) = null
* StringUtils.removePattern("any", (String) null) = "any"
* StringUtils.removePattern("A<__>\n<__>B", "<.*>") = "AB"
* StringUtils.removePattern("ABCabc123", "[a-z]") = "ABC123"
* </pre>
*
* @param source
* the source string
* @param regex
* the regular expression to which this string is to be matched
* @return The resulting {@code String}
* @see #replacePattern(String, String, String)
* @see String#replaceAll(String, String)
* @see Pattern#DOTALL
* @since 3.2
* @since 3.5 Changed {@code null} reference passed to this method is a no-op.
*
* @deprecated Moved to RegExUtils.
*/
@Deprecated
public static String removePattern(final String source, final String regex) {
return RegExUtils.removePattern(source, regex);
}
// Remove
//-----------------------------------------------------------------------
/**
* <p>Removes a substring only if it is at the beginning of a source string,
* otherwise returns the source string.</p>
*
* <p>A {@code null} source string will return {@code null}.
* An empty ("") source string will return the empty string.
* A {@code null} search string will return the source string.</p>
*
* <pre>
* StringUtils.removeStart(null, *) = null
* StringUtils.removeStart("", *) = ""
* StringUtils.removeStart(*, null) = *
* StringUtils.removeStart("www.domain.com", "www.") = "domain.com"
* StringUtils.removeStart("domain.com", "www.") = "domain.com"
* StringUtils.removeStart("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeStart("abc", "") = "abc"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for and remove, may be null
* @return the substring with the string removed if found,
* {@code null} if null String input
* @since 2.1
*/
public static String removeStart(final String str, final String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (str.startsWith(remove)) {
return str.substring(remove.length());
}
return str;
}
/**
* <p>Case insensitive removal of a substring if it is at the beginning of a source string,
* otherwise returns the source string.</p>
*
* <p>A {@code null} source string will return {@code null}.
* An empty ("") source string will return the empty string.
* A {@code null} search string will return the source string.</p>
*
* <pre>
* StringUtils.removeStartIgnoreCase(null, *) = null
* StringUtils.removeStartIgnoreCase("", *) = ""
* StringUtils.removeStartIgnoreCase(*, null) = *
* StringUtils.removeStartIgnoreCase("www.domain.com", "www.") = "domain.com"
* StringUtils.removeStartIgnoreCase("www.domain.com", "WWW.") = "domain.com"
* StringUtils.removeStartIgnoreCase("domain.com", "www.") = "domain.com"
* StringUtils.removeStartIgnoreCase("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeStartIgnoreCase("abc", "") = "abc"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for (case insensitive) and remove, may be null
* @return the substring with the string removed if found,
* {@code null} if null String input
* @since 2.4
*/
public static String removeStartIgnoreCase(final String str, final String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (startsWithIgnoreCase(str, remove)) {
return str.substring(remove.length());
}
return str;
}
/**
* <p>Returns padding using the specified delimiter repeated
* to a given length.</p>
*
* <pre>
* StringUtils.repeat('e', 0) = ""
* StringUtils.repeat('e', 3) = "eee"
* StringUtils.repeat('e', -2) = ""
* </pre>
*
* <p>Note: this method does not support padding with
* <a href="http://www.unicode.org/glossary/#supplementary_character">Unicode Supplementary Characters</a>
* as they require a pair of {@code char}s to be represented.
* If you are needing to support full I18N of your applications
* consider using {@link #repeat(String, int)} instead.
* </p>
*
* @param ch character to repeat
* @param repeat number of times to repeat char, negative treated as zero
* @return String with repeated character
* @see #repeat(String, int)
*/
public static String repeat(final char ch, final int repeat) {
if (repeat <= 0) {
return EMPTY;
}
final char[] buf = new char[repeat];
for (int i = repeat - 1; i >= 0; i--) {
buf[i] = ch;
}
return new String(buf);
}
// Padding
//-----------------------------------------------------------------------
/**
* <p>Repeat a String {@code repeat} times to form a
* new String.</p>
*
* <pre>
* StringUtils.repeat(null, 2) = null
* StringUtils.repeat("", 0) = ""
* StringUtils.repeat("", 2) = ""
* StringUtils.repeat("a", 3) = "aaa"
* StringUtils.repeat("ab", 2) = "abab"
* StringUtils.repeat("a", -2) = ""
* </pre>
*
* @param str the String to repeat, may be null
* @param repeat number of times to repeat str, negative treated as zero
* @return a new String consisting of the original String repeated,
* {@code null} if null String input
*/
public static String repeat(final String str, final int repeat) {
// Performance tuned for 2.0 (JDK1.4)
if (str == null) {
return null;
}
if (repeat <= 0) {
return EMPTY;
}
final int inputLength = str.length();
if (repeat == 1 || inputLength == 0) {
return str;
}
if (inputLength == 1 && repeat <= PAD_LIMIT) {
return repeat(str.charAt(0), repeat);
}
final int outputLength = inputLength * repeat;
switch (inputLength) {
case 1 :
return repeat(str.charAt(0), repeat);
case 2 :
final char ch0 = str.charAt(0);
final char ch1 = str.charAt(1);
final char[] output2 = new char[outputLength];
for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
output2[i] = ch0;
output2[i + 1] = ch1;
}
return new String(output2);
default :
final StringBuilder buf = new StringBuilder(outputLength);
for (int i = 0; i < repeat; i++) {
buf.append(str);
}
return buf.toString();
}
}
// Conversion
//-----------------------------------------------------------------------
/**
* <p>Repeat a String {@code repeat} times to form a
* new String, with a String separator injected each time. </p>
*
* <pre>
* StringUtils.repeat(null, null, 2) = null
* StringUtils.repeat(null, "x", 2) = null
* StringUtils.repeat("", null, 0) = ""
* StringUtils.repeat("", "", 2) = ""
* StringUtils.repeat("", "x", 3) = "xxx"
* StringUtils.repeat("?", ", ", 3) = "?, ?, ?"
* </pre>
*
* @param str the String to repeat, may be null
* @param separator the String to inject, may be null
* @param repeat number of times to repeat str, negative treated as zero
* @return a new String consisting of the original String repeated,
* {@code null} if null String input
* @since 2.5
*/
public static String repeat(final String str, final String separator, final int repeat) {
if (str == null || separator == null) {
return repeat(str, repeat);
}
// given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it
final String result = repeat(str + separator, repeat);
return removeEnd(result, separator);
}
/**
* <p>Replaces all occurrences of a String within another String.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replace(null, *, *) = null
* StringUtils.replace("", *, *) = ""
* StringUtils.replace("any", null, *) = "any"
* StringUtils.replace("any", *, null) = "any"
* StringUtils.replace("any", "", *) = "any"
* StringUtils.replace("aba", "a", null) = "aba"
* StringUtils.replace("aba", "a", "") = "b"
* StringUtils.replace("aba", "a", "z") = "zbz"
* </pre>
*
* @see #replace(String text, String searchString, String replacement, int max)
* @param text text to search and replace in, may be null
* @param searchString the String to search for, may be null
* @param replacement the String to replace it with, may be null
* @return the text with any replacements processed,
* {@code null} if null String input
*/
public static String replace(final String text, final String searchString, final String replacement) {
return replace(text, searchString, replacement, -1);
}
/**
* <p>Replaces a String with another String inside a larger String,
* for the first {@code max} values of the search String.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replace(null, *, *, *) = null
* StringUtils.replace("", *, *, *) = ""
* StringUtils.replace("any", null, *, *) = "any"
* StringUtils.replace("any", *, null, *) = "any"
* StringUtils.replace("any", "", *, *) = "any"
* StringUtils.replace("any", *, *, 0) = "any"
* StringUtils.replace("abaa", "a", null, -1) = "abaa"
* StringUtils.replace("abaa", "a", "", -1) = "b"
* StringUtils.replace("abaa", "a", "z", 0) = "abaa"
* StringUtils.replace("abaa", "a", "z", 1) = "zbaa"
* StringUtils.replace("abaa", "a", "z", 2) = "zbza"
* StringUtils.replace("abaa", "a", "z", -1) = "zbzz"
* </pre>
*
* @param text text to search and replace in, may be null
* @param searchString the String to search for, may be null
* @param replacement the String to replace it with, may be null
* @param max maximum number of values to replace, or {@code -1} if no maximum
* @return the text with any replacements processed,
* {@code null} if null String input
*/
public static String replace(final String text, final String searchString, final String replacement, final int max) {
return replace(text, searchString, replacement, max, false);
}
/**
* <p>Replaces a String with another String inside a larger String,
* for the first {@code max} values of the search String,
* case sensitively/insensisitively based on {@code ignoreCase} value.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replace(null, *, *, *, false) = null
* StringUtils.replace("", *, *, *, false) = ""
* StringUtils.replace("any", null, *, *, false) = "any"
* StringUtils.replace("any", *, null, *, false) = "any"
* StringUtils.replace("any", "", *, *, false) = "any"
* StringUtils.replace("any", *, *, 0, false) = "any"
* StringUtils.replace("abaa", "a", null, -1, false) = "abaa"
* StringUtils.replace("abaa", "a", "", -1, false) = "b"
* StringUtils.replace("abaa", "a", "z", 0, false) = "abaa"
* StringUtils.replace("abaa", "A", "z", 1, false) = "abaa"
* StringUtils.replace("abaa", "A", "z", 1, true) = "zbaa"
* StringUtils.replace("abAa", "a", "z", 2, true) = "zbza"
* StringUtils.replace("abAa", "a", "z", -1, true) = "zbzz"
* </pre>
*
* @param text text to search and replace in, may be null
* @param searchString the String to search for (case insensitive), may be null
* @param replacement the String to replace it with, may be null
* @param max maximum number of values to replace, or {@code -1} if no maximum
* @param ignoreCase if true replace is case insensitive, otherwise case sensitive
* @return the text with any replacements processed,
* {@code null} if null String input
*/
private static String replace(final String text, String searchString, final String replacement, int max, final boolean ignoreCase) {
if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) {
return text;
}
if (ignoreCase) {
searchString = searchString.toLowerCase();
}
int start = 0;
int end = ignoreCase ? indexOfIgnoreCase(text, searchString, start) : indexOf(text, searchString, start);
if (end == INDEX_NOT_FOUND) {
return text;
}
final int replLength = searchString.length();
int increase = replacement.length() - replLength;
increase = increase < 0 ? 0 : increase;
increase *= max < 0 ? 16 : max > 64 ? 64 : max;
final StringBuilder buf = new StringBuilder(text.length() + increase);
while (end != INDEX_NOT_FOUND) {
buf.append(text, start, end).append(replacement);
start = end + replLength;
if (--max == 0) {
break;
}
end = ignoreCase ? indexOfIgnoreCase(text, searchString, start) : indexOf(text, searchString, start);
}
buf.append(text, start, text.length());
return buf.toString();
}
/**
* <p>Replaces each substring of the text String that matches the given regular expression
* with the given replacement.</p>
*
* This method is a {@code null} safe equivalent to:
* <ul>
* <li>{@code text.replaceAll(regex, replacement)}</li>
* <li>{@code Pattern.compile(regex).matcher(text).replaceAll(replacement)}</li>
* </ul>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <p>Unlike in the {@link #replacePattern(String, String, String)} method, the {@link Pattern#DOTALL} option
* is NOT automatically added.
* To use the DOTALL option prepend {@code "(?s)"} to the regex.
* DOTALL is also known as single-line mode in Perl.</p>
*
* <pre>
* StringUtils.replaceAll(null, *, *) = null
* StringUtils.replaceAll("any", (String) null, *) = "any"
* StringUtils.replaceAll("any", *, null) = "any"
* StringUtils.replaceAll("", "", "zzz") = "zzz"
* StringUtils.replaceAll("", ".*", "zzz") = "zzz"
* StringUtils.replaceAll("", ".+", "zzz") = ""
* StringUtils.replaceAll("abc", "", "ZZ") = "ZZaZZbZZcZZ"
* StringUtils.replaceAll("<__>\n<__>", "<.*>", "z") = "z\nz"
* StringUtils.replaceAll("<__>\n<__>", "(?s)<.*>", "z") = "z"
* StringUtils.replaceAll("ABCabc123", "[a-z]", "_") = "ABC___123"
* StringUtils.replaceAll("ABCabc123", "[^A-Z0-9]+", "_") = "ABC_123"
* StringUtils.replaceAll("ABCabc123", "[^A-Z0-9]+", "") = "ABC123"
* StringUtils.replaceAll("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2") = "Lorem_ipsum_dolor_sit"
* </pre>
*
* @param text text to search and replace in, may be null
* @param regex the regular expression to which this string is to be matched
* @param replacement the string to be substituted for each match
* @return the text with any replacements processed,
* {@code null} if null String input
*
* @throws java.util.regex.PatternSyntaxException
* if the regular expression's syntax is invalid
*
* @see #replacePattern(String, String, String)
* @see String#replaceAll(String, String)
* @see java.util.regex.Pattern
* @see java.util.regex.Pattern#DOTALL
* @since 3.5
*
* @deprecated Moved to RegExUtils.
*/
@Deprecated
public static String replaceAll(final String text, final String regex, final String replacement) {
return RegExUtils.replaceAll(text, regex, replacement);
}
// Replace, character based
//-----------------------------------------------------------------------
/**
* <p>Replaces all occurrences of a character in a String with another.
* This is a null-safe version of {@link String#replace(char, char)}.</p>
*
* <p>A {@code null} string input returns {@code null}.
* An empty ("") string input returns an empty string.</p>
*
* <pre>
* StringUtils.replaceChars(null, *, *) = null
* StringUtils.replaceChars("", *, *) = ""
* StringUtils.replaceChars("abcba", 'b', 'y') = "aycya"
* StringUtils.replaceChars("abcba", 'z', 'y') = "abcba"
* </pre>
*
* @param str String to replace characters in, may be null
* @param searchChar the character to search for, may be null
* @param replaceChar the character to replace, may be null
* @return modified String, {@code null} if null string input
* @since 2.0
*/
public static String replaceChars(final String str, final char searchChar, final char replaceChar) {
if (str == null) {
return null;
}
return str.replace(searchChar, replaceChar);
}
/**
* <p>Replaces multiple characters in a String in one go.
* This method can also be used to delete characters.</p>
*
* <p>For example:<br>
* {@code replaceChars("hello", "ho", "jy") = jelly}.</p>
*
* <p>A {@code null} string input returns {@code null}.
* An empty ("") string input returns an empty string.
* A null or empty set of search characters returns the input string.</p>
*
* <p>The length of the search characters should normally equal the length
* of the replace characters.
* If the search characters is longer, then the extra search characters
* are deleted.
* If the search characters is shorter, then the extra replace characters
* are ignored.</p>
*
* <pre>
* StringUtils.replaceChars(null, *, *) = null
* StringUtils.replaceChars("", *, *) = ""
* StringUtils.replaceChars("abc", null, *) = "abc"
* StringUtils.replaceChars("abc", "", *) = "abc"
* StringUtils.replaceChars("abc", "b", null) = "ac"
* StringUtils.replaceChars("abc", "b", "") = "ac"
* StringUtils.replaceChars("abcba", "bc", "yz") = "ayzya"
* StringUtils.replaceChars("abcba", "bc", "y") = "ayya"
* StringUtils.replaceChars("abcba", "bc", "yzx") = "ayzya"
* </pre>
*
* @param str String to replace characters in, may be null
* @param searchChars a set of characters to search for, may be null
* @param replaceChars a set of characters to replace, may be null
* @return modified String, {@code null} if null string input
* @since 2.0
*/
public static String replaceChars(final String str, final String searchChars, String replaceChars) {
if (isEmpty(str) || isEmpty(searchChars)) {
return str;
}
if (replaceChars == null) {
replaceChars = EMPTY;
}
boolean modified = false;
final int replaceCharsLength = replaceChars.length();
final int strLength = str.length();
final StringBuilder buf = new StringBuilder(strLength);
for (int i = 0; i < strLength; i++) {
final char ch = str.charAt(i);
final int index = searchChars.indexOf(ch);
if (index >= 0) {
modified = true;
if (index < replaceCharsLength) {
buf.append(replaceChars.charAt(index));
}
} else {
buf.append(ch);
}
}
if (modified) {
return buf.toString();
}
return str;
}
/**
* <p>
* Replaces all occurrences of Strings within another String.
* </p>
*
* <p>
* A {@code null} reference passed to this method is a no-op, or if
* any "search string" or "string to replace" is null, that replace will be
* ignored. This will not repeat. For repeating replaces, call the
* overloaded method.
* </p>
*
* <pre>
* StringUtils.replaceEach(null, *, *) = null
* StringUtils.replaceEach("", *, *) = ""
* StringUtils.replaceEach("aba", null, null) = "aba"
* StringUtils.replaceEach("aba", new String[0], null) = "aba"
* StringUtils.replaceEach("aba", null, new String[0]) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, null) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}) = "b"
* StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}) = "aba"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte"
* (example of how it does not repeat)
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "dcte"
* </pre>
*
* @param text
* text to search and replace in, no-op if null
* @param searchList
* the Strings to search for, no-op if null
* @param replacementList
* the Strings to replace them with, no-op if null
* @return the text with any replacements processed, {@code null} if
* null String input
* @throws IllegalArgumentException
* if the lengths of the arrays are not the same (null is ok,
* and/or size 0)
* @since 2.4
*/
public static String replaceEach(final String text, final String[] searchList, final String[] replacementList) {
return replaceEach(text, searchList, replacementList, false, 0);
}
/**
* <p>
* Replace all occurrences of Strings within another String.
* This is a private recursive helper method for {@link #replaceEachRepeatedly(String, String[], String[])} and
* {@link #replaceEach(String, String[], String[])}
* </p>
*
* <p>
* A {@code null} reference passed to this method is a no-op, or if
* any "search string" or "string to replace" is null, that replace will be
* ignored.
* </p>
*
* <pre>
* StringUtils.replaceEach(null, *, *, *, *) = null
* StringUtils.replaceEach("", *, *, *, *) = ""
* StringUtils.replaceEach("aba", null, null, *, *) = "aba"
* StringUtils.replaceEach("aba", new String[0], null, *, *) = "aba"
* StringUtils.replaceEach("aba", null, new String[0], *, *) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, null, *, *) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}, *, >=0) = "b"
* StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}, *, >=0) = "aba"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}, *, >=0) = "wcte"
* (example of how it repeats)
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, false, >=0) = "dcte"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, true, >=2) = "tcte"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, *, *) = IllegalStateException
* </pre>
*
* @param text
* text to search and replace in, no-op if null
* @param searchList
* the Strings to search for, no-op if null
* @param replacementList
* the Strings to replace them with, no-op if null
* @param repeat if true, then replace repeatedly
* until there are no more possible replacements or timeToLive < 0
* @param timeToLive
* if less than 0 then there is a circular reference and endless
* loop
* @return the text with any replacements processed, {@code null} if
* null String input
* @throws IllegalStateException
* if the search is repeating and there is an endless loop due
* to outputs of one being inputs to another
* @throws IllegalArgumentException
* if the lengths of the arrays are not the same (null is ok,
* and/or size 0)
* @since 2.4
*/
private static String replaceEach(
final String text, final String[] searchList, final String[] replacementList, final boolean repeat, final int timeToLive) {
// mchyzer Performance note: This creates very few new objects (one major goal)
// let me know if there are performance requests, we can create a harness to measure
if (isEmpty(text) || ArrayUtils.isEmpty(searchList) || ArrayUtils.isEmpty(replacementList)) {
return text;
}
// if recursing, this shouldn't be less than 0
if (timeToLive < 0) {
throw new IllegalStateException("Aborting to protect against StackOverflowError - " +
"output of one loop is the input of another");
}
final int searchLength = searchList.length;
final int replacementLength = replacementList.length;
// make sure lengths are ok, these need to be equal
if (searchLength != replacementLength) {
throw new IllegalArgumentException("Search and Replace array lengths don't match: "
+ searchLength
+ " vs "
+ replacementLength);
}
// keep track of which still have matches
final boolean[] noMoreMatchesForReplIndex = new boolean[searchLength];
// index on index that the match was found
int textIndex = -1;
int replaceIndex = -1;
int tempIndex = -1;
// index of replace array that will replace the search string found
// NOTE: logic duplicated below START
for (int i = 0; i < searchLength; i++) {
if (noMoreMatchesForReplIndex[i] || searchList[i] == null ||
searchList[i].isEmpty() || replacementList[i] == null) {
continue;
}
tempIndex = text.indexOf(searchList[i]);
// see if we need to keep searching for this
if (tempIndex == -1) {
noMoreMatchesForReplIndex[i] = true;
} else {
if (textIndex == -1 || tempIndex < textIndex) {
textIndex = tempIndex;
replaceIndex = i;
}
}
}
// NOTE: logic mostly below END
// no search strings found, we are done
if (textIndex == -1) {
return text;
}
int start = 0;
// get a good guess on the size of the result buffer so it doesn't have to double if it goes over a bit
int increase = 0;
// count the replacement text elements that are larger than their corresponding text being replaced
for (int i = 0; i < searchList.length; i++) {
if (searchList[i] == null || replacementList[i] == null) {
continue;
}
final int greater = replacementList[i].length() - searchList[i].length();
if (greater > 0) {
increase += 3 * greater; // assume 3 matches
}
}
// have upper-bound at 20% increase, then let Java take over
increase = Math.min(increase, text.length() / 5);
final StringBuilder buf = new StringBuilder(text.length() + increase);
while (textIndex != -1) {
for (int i = start; i < textIndex; i++) {
buf.append(text.charAt(i));
}
buf.append(replacementList[replaceIndex]);
start = textIndex + searchList[replaceIndex].length();
textIndex = -1;
replaceIndex = -1;
tempIndex = -1;
// find the next earliest match
// NOTE: logic mostly duplicated above START
for (int i = 0; i < searchLength; i++) {
if (noMoreMatchesForReplIndex[i] || searchList[i] == null ||
searchList[i].isEmpty() || replacementList[i] == null) {
continue;
}
tempIndex = text.indexOf(searchList[i], start);
// see if we need to keep searching for this
if (tempIndex == -1) {
noMoreMatchesForReplIndex[i] = true;
} else {
if (textIndex == -1 || tempIndex < textIndex) {
textIndex = tempIndex;
replaceIndex = i;
}
}
}
// NOTE: logic duplicated above END
}
final int textLength = text.length();
for (int i = start; i < textLength; i++) {
buf.append(text.charAt(i));
}
final String result = buf.toString();
if (!repeat) {
return result;
}
return replaceEach(result, searchList, replacementList, repeat, timeToLive - 1);
}
/**
* <p>
* Replaces all occurrences of Strings within another String.
* </p>
*
* <p>
* A {@code null} reference passed to this method is a no-op, or if
* any "search string" or "string to replace" is null, that replace will be
* ignored.
* </p>
*
* <pre>
* StringUtils.replaceEachRepeatedly(null, *, *) = null
* StringUtils.replaceEachRepeatedly("", *, *) = ""
* StringUtils.replaceEachRepeatedly("aba", null, null) = "aba"
* StringUtils.replaceEachRepeatedly("aba", new String[0], null) = "aba"
* StringUtils.replaceEachRepeatedly("aba", null, new String[0]) = "aba"
* StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, null) = "aba"
* StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, new String[]{""}) = "b"
* StringUtils.replaceEachRepeatedly("aba", new String[]{null}, new String[]{"a"}) = "aba"
* StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte"
* (example of how it repeats)
* StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "tcte"
* StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}) = IllegalStateException
* </pre>
*
* @param text
* text to search and replace in, no-op if null
* @param searchList
* the Strings to search for, no-op if null
* @param replacementList
* the Strings to replace them with, no-op if null
* @return the text with any replacements processed, {@code null} if
* null String input
* @throws IllegalStateException
* if the search is repeating and there is an endless loop due
* to outputs of one being inputs to another
* @throws IllegalArgumentException
* if the lengths of the arrays are not the same (null is ok,
* and/or size 0)
* @since 2.4
*/
public static String replaceEachRepeatedly(final String text, final String[] searchList, final String[] replacementList) {
// timeToLive should be 0 if not used or nothing to replace, else it's
// the length of the replace array
final int timeToLive = searchList == null ? 0 : searchList.length;
return replaceEach(text, searchList, replacementList, true, timeToLive);
}
/**
* <p>Replaces the first substring of the text string that matches the given regular expression
* with the given replacement.</p>
*
* This method is a {@code null} safe equivalent to:
* <ul>
* <li>{@code text.replaceFirst(regex, replacement)}</li>
* <li>{@code Pattern.compile(regex).matcher(text).replaceFirst(replacement)}</li>
* </ul>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <p>The {@link Pattern#DOTALL} option is NOT automatically added.
* To use the DOTALL option prepend {@code "(?s)"} to the regex.
* DOTALL is also known as single-line mode in Perl.</p>
*
* <pre>
* StringUtils.replaceFirst(null, *, *) = null
* StringUtils.replaceFirst("any", (String) null, *) = "any"
* StringUtils.replaceFirst("any", *, null) = "any"
* StringUtils.replaceFirst("", "", "zzz") = "zzz"
* StringUtils.replaceFirst("", ".*", "zzz") = "zzz"
* StringUtils.replaceFirst("", ".+", "zzz") = ""
* StringUtils.replaceFirst("abc", "", "ZZ") = "ZZabc"
* StringUtils.replaceFirst("<__>\n<__>", "<.*>", "z") = "z\n<__>"
* StringUtils.replaceFirst("<__>\n<__>", "(?s)<.*>", "z") = "z"
* StringUtils.replaceFirst("ABCabc123", "[a-z]", "_") = "ABC_bc123"
* StringUtils.replaceFirst("ABCabc123abc", "[^A-Z0-9]+", "_") = "ABC_123abc"
* StringUtils.replaceFirst("ABCabc123abc", "[^A-Z0-9]+", "") = "ABC123abc"
* StringUtils.replaceFirst("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2") = "Lorem_ipsum dolor sit"
* </pre>
*
* @param text text to search and replace in, may be null
* @param regex the regular expression to which this string is to be matched
* @param replacement the string to be substituted for the first match
* @return the text with the first replacement processed,
* {@code null} if null String input
*
* @throws java.util.regex.PatternSyntaxException
* if the regular expression's syntax is invalid
*
* @see String#replaceFirst(String, String)
* @see java.util.regex.Pattern
* @see java.util.regex.Pattern#DOTALL
* @since 3.5
*
* @deprecated Moved to RegExUtils.
*/
@Deprecated
public static String replaceFirst(final String text, final String regex, final String replacement) {
return RegExUtils.replaceFirst(text, regex, replacement);
}
/**
* <p>Case insensitively replaces all occurrences of a String within another String.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replaceIgnoreCase(null, *, *) = null
* StringUtils.replaceIgnoreCase("", *, *) = ""
* StringUtils.replaceIgnoreCase("any", null, *) = "any"
* StringUtils.replaceIgnoreCase("any", *, null) = "any"
* StringUtils.replaceIgnoreCase("any", "", *) = "any"
* StringUtils.replaceIgnoreCase("aba", "a", null) = "aba"
* StringUtils.replaceIgnoreCase("abA", "A", "") = "b"
* StringUtils.replaceIgnoreCase("aba", "A", "z") = "zbz"
* </pre>
*
* @see #replaceIgnoreCase(String text, String searchString, String replacement, int max)
* @param text text to search and replace in, may be null
* @param searchString the String to search for (case insensitive), may be null
* @param replacement the String to replace it with, may be null
* @return the text with any replacements processed,
* {@code null} if null String input
* @since 3.5
*/
public static String replaceIgnoreCase(final String text, final String searchString, final String replacement) {
return replaceIgnoreCase(text, searchString, replacement, -1);
}
/**
* <p>Case insensitively replaces a String with another String inside a larger String,
* for the first {@code max} values of the search String.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replaceIgnoreCase(null, *, *, *) = null
* StringUtils.replaceIgnoreCase("", *, *, *) = ""
* StringUtils.replaceIgnoreCase("any", null, *, *) = "any"
* StringUtils.replaceIgnoreCase("any", *, null, *) = "any"
* StringUtils.replaceIgnoreCase("any", "", *, *) = "any"
* StringUtils.replaceIgnoreCase("any", *, *, 0) = "any"
* StringUtils.replaceIgnoreCase("abaa", "a", null, -1) = "abaa"
* StringUtils.replaceIgnoreCase("abaa", "a", "", -1) = "b"
* StringUtils.replaceIgnoreCase("abaa", "a", "z", 0) = "abaa"
* StringUtils.replaceIgnoreCase("abaa", "A", "z", 1) = "zbaa"
* StringUtils.replaceIgnoreCase("abAa", "a", "z", 2) = "zbza"
* StringUtils.replaceIgnoreCase("abAa", "a", "z", -1) = "zbzz"
* </pre>
*
* @param text text to search and replace in, may be null
* @param searchString the String to search for (case insensitive), may be null
* @param replacement the String to replace it with, may be null
* @param max maximum number of values to replace, or {@code -1} if no maximum
* @return the text with any replacements processed,
* {@code null} if null String input
* @since 3.5
*/
public static String replaceIgnoreCase(final String text, final String searchString, final String replacement, final int max) {
return replace(text, searchString, replacement, max, true);
}
// Replacing
//-----------------------------------------------------------------------
/**
* <p>Replaces a String with another String inside a larger String, once.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replaceOnce(null, *, *) = null
* StringUtils.replaceOnce("", *, *) = ""
* StringUtils.replaceOnce("any", null, *) = "any"
* StringUtils.replaceOnce("any", *, null) = "any"
* StringUtils.replaceOnce("any", "", *) = "any"
* StringUtils.replaceOnce("aba", "a", null) = "aba"
* StringUtils.replaceOnce("aba", "a", "") = "ba"
* StringUtils.replaceOnce("aba", "a", "z") = "zba"
* </pre>
*
* @see #replace(String text, String searchString, String replacement, int max)
* @param text text to search and replace in, may be null
* @param searchString the String to search for, may be null
* @param replacement the String to replace with, may be null
* @return the text with any replacements processed,
* {@code null} if null String input
*/
public static String replaceOnce(final String text, final String searchString, final String replacement) {
return replace(text, searchString, replacement, 1);
}
/**
* <p>Case insensitively replaces a String with another String inside a larger String, once.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replaceOnceIgnoreCase(null, *, *) = null
* StringUtils.replaceOnceIgnoreCase("", *, *) = ""
* StringUtils.replaceOnceIgnoreCase("any", null, *) = "any"
* StringUtils.replaceOnceIgnoreCase("any", *, null) = "any"
* StringUtils.replaceOnceIgnoreCase("any", "", *) = "any"
* StringUtils.replaceOnceIgnoreCase("aba", "a", null) = "aba"
* StringUtils.replaceOnceIgnoreCase("aba", "a", "") = "ba"
* StringUtils.replaceOnceIgnoreCase("aba", "a", "z") = "zba"
* StringUtils.replaceOnceIgnoreCase("FoOFoofoo", "foo", "") = "Foofoo"
* </pre>
*
* @see #replaceIgnoreCase(String text, String searchString, String replacement, int max)
* @param text text to search and replace in, may be null
* @param searchString the String to search for (case insensitive), may be null
* @param replacement the String to replace with, may be null
* @return the text with any replacements processed,
* {@code null} if null String input
* @since 3.5
*/
public static String replaceOnceIgnoreCase(final String text, final String searchString, final String replacement) {
return replaceIgnoreCase(text, searchString, replacement, 1);
}
/**
* <p>Replaces each substring of the source String that matches the given regular expression with the given
* replacement using the {@link Pattern#DOTALL} option. DOTALL is also known as single-line mode in Perl.</p>
*
* This call is a {@code null} safe equivalent to:
* <ul>
* <li>{@code source.replaceAll("(?s)" + regex, replacement)}</li>
* <li>{@code Pattern.compile(regex, Pattern.DOTALL).matcher(source).replaceAll(replacement)}</li>
* </ul>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replacePattern(null, *, *) = null
* StringUtils.replacePattern("any", (String) null, *) = "any"
* StringUtils.replacePattern("any", *, null) = "any"
* StringUtils.replacePattern("", "", "zzz") = "zzz"
* StringUtils.replacePattern("", ".*", "zzz") = "zzz"
* StringUtils.replacePattern("", ".+", "zzz") = ""
* StringUtils.replacePattern("<__>\n<__>", "<.*>", "z") = "z"
* StringUtils.replacePattern("ABCabc123", "[a-z]", "_") = "ABC___123"
* StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "_") = "ABC_123"
* StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "") = "ABC123"
* StringUtils.replacePattern("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2") = "Lorem_ipsum_dolor_sit"
* </pre>
*
* @param source
* the source string
* @param regex
* the regular expression to which this string is to be matched
* @param replacement
* the string to be substituted for each match
* @return The resulting {@code String}
* @see #replaceAll(String, String, String)
* @see String#replaceAll(String, String)
* @see Pattern#DOTALL
* @since 3.2
* @since 3.5 Changed {@code null} reference passed to this method is a no-op.
*
* @deprecated Moved to RegExUtils.
*/
@Deprecated
public static String replacePattern(final String source, final String regex, final String replacement) {
return RegExUtils.replacePattern(source, regex, replacement);
}
// Reversing
//-----------------------------------------------------------------------
/**
* <p>Reverses a String as per {@link StringBuilder#reverse()}.</p>
*
* <p>A {@code null} String returns {@code null}.</p>
*
* <pre>
* StringUtils.reverse(null) = null
* StringUtils.reverse("") = ""
* StringUtils.reverse("bat") = "tab"
* </pre>
*
* @param str the String to reverse, may be null
* @return the reversed String, {@code null} if null String input
*/
public static String reverse(final String str) {
if (str == null) {
return null;
}
return new StringBuilder(str).reverse().toString();
}
/**
* <p>Reverses a String that is delimited by a specific character.</p>
*
* <p>The Strings between the delimiters are not reversed.
* Thus java.lang.String becomes String.lang.java (if the delimiter
* is {@code '.'}).</p>
*
* <pre>
* StringUtils.reverseDelimited(null, *) = null
* StringUtils.reverseDelimited("", *) = ""
* StringUtils.reverseDelimited("a.b.c", 'x') = "a.b.c"
* StringUtils.reverseDelimited("a.b.c", ".") = "c.b.a"
* </pre>
*
* @param str the String to reverse, may be null
* @param separatorChar the separator character to use
* @return the reversed String, {@code null} if null String input
* @since 2.0
*/
public static String reverseDelimited(final String str, final char separatorChar) {
if (str == null) {
return null;
}
// could implement manually, but simple way is to reuse other,
// probably slower, methods.
final String[] strs = split(str, separatorChar);
ArrayUtils.reverse(strs);
return join(strs, separatorChar);
}
/**
* <p>Gets the rightmost {@code len} characters of a String.</p>
*
* <p>If {@code len} characters are not available, or the String
* is {@code null}, the String will be returned without an
* an exception. An empty String is returned if len is negative.</p>
*
* <pre>
* StringUtils.right(null, *) = null
* StringUtils.right(*, -ve) = ""
* StringUtils.right("", *) = ""
* StringUtils.right("abc", 0) = ""
* StringUtils.right("abc", 2) = "bc"
* StringUtils.right("abc", 4) = "abc"
* </pre>
*
* @param str the String to get the rightmost characters from, may be null
* @param len the length of the required String
* @return the rightmost characters, {@code null} if null String input
*/
public static String right(final String str, final int len) {
if (str == null) {
return null;
}
if (len < 0) {
return EMPTY;
}
if (str.length() <= len) {
return str;
}
return str.substring(str.length() - len);
}
/**
* <p>Right pad a String with spaces (' ').</p>
*
* <p>The String is padded to the size of {@code size}.</p>
*
* <pre>
* StringUtils.rightPad(null, *) = null
* StringUtils.rightPad("", 3) = " "
* StringUtils.rightPad("bat", 3) = "bat"
* StringUtils.rightPad("bat", 5) = "bat "
* StringUtils.rightPad("bat", 1) = "bat"
* StringUtils.rightPad("bat", -1) = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @return right padded String or original String if no padding is necessary,
* {@code null} if null String input
*/
public static String rightPad(final String str, final int size) {
return rightPad(str, size, ' ');
}
/**
* <p>Right pad a String with a specified character.</p>
*
* <p>The String is padded to the size of {@code size}.</p>
*
* <pre>
* StringUtils.rightPad(null, *, *) = null
* StringUtils.rightPad("", 3, 'z') = "zzz"
* StringUtils.rightPad("bat", 3, 'z') = "bat"
* StringUtils.rightPad("bat", 5, 'z') = "batzz"
* StringUtils.rightPad("bat", 1, 'z') = "bat"
* StringUtils.rightPad("bat", -1, 'z') = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padChar the character to pad with
* @return right padded String or original String if no padding is necessary,
* {@code null} if null String input
* @since 2.0
*/
public static String rightPad(final String str, final int size, final char padChar) {
if (str == null) {
return null;
}
final int pads = size - str.length();
if (pads <= 0) {
return str; // returns original String when possible
}
if (pads > PAD_LIMIT) {
return rightPad(str, size, String.valueOf(padChar));
}
return str.concat(repeat(padChar, pads));
}
/**
* <p>Right pad a String with a specified String.</p>
*
* <p>The String is padded to the size of {@code size}.</p>
*
* <pre>
* StringUtils.rightPad(null, *, *) = null
* StringUtils.rightPad("", 3, "z") = "zzz"
* StringUtils.rightPad("bat", 3, "yz") = "bat"
* StringUtils.rightPad("bat", 5, "yz") = "batyz"
* StringUtils.rightPad("bat", 8, "yz") = "batyzyzy"
* StringUtils.rightPad("bat", 1, "yz") = "bat"
* StringUtils.rightPad("bat", -1, "yz") = "bat"
* StringUtils.rightPad("bat", 5, null) = "bat "
* StringUtils.rightPad("bat", 5, "") = "bat "
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padStr the String to pad with, null or empty treated as single space
* @return right padded String or original String if no padding is necessary,
* {@code null} if null String input
*/
public static String rightPad(final String str, final int size, String padStr) {
if (str == null) {
return null;
}
if (isEmpty(padStr)) {
padStr = SPACE;
}
final int padLen = padStr.length();
final int strLen = str.length();
final int pads = size - strLen;
if (pads <= 0) {
return str; // returns original String when possible
}
if (padLen == 1 && pads <= PAD_LIMIT) {
return rightPad(str, size, padStr.charAt(0));
}
if (pads == padLen) {
return str.concat(padStr);
} else if (pads < padLen) {
return str.concat(padStr.substring(0, pads));
} else {
final char[] padding = new char[pads];
final char[] padChars = padStr.toCharArray();
for (int i = 0; i < pads; i++) {
padding[i] = padChars[i % padLen];
}
return str.concat(new String(padding));
}
}
// Rotating (circular shift)
//-----------------------------------------------------------------------
/**
* <p>Rotate (circular shift) a String of {@code shift} characters.</p>
* <ul>
* <li>If {@code shift > 0}, right circular shift (ex : ABCDEF => FABCDE)</li>
* <li>If {@code shift < 0}, left circular shift (ex : ABCDEF => BCDEFA)</li>
* </ul>
*
* <pre>
* StringUtils.rotate(null, *) = null
* StringUtils.rotate("", *) = ""
* StringUtils.rotate("abcdefg", 0) = "abcdefg"
* StringUtils.rotate("abcdefg", 2) = "fgabcde"
* StringUtils.rotate("abcdefg", -2) = "cdefgab"
* StringUtils.rotate("abcdefg", 7) = "abcdefg"
* StringUtils.rotate("abcdefg", -7) = "abcdefg"
* StringUtils.rotate("abcdefg", 9) = "fgabcde"
* StringUtils.rotate("abcdefg", -9) = "cdefgab"
* </pre>
*
* @param str the String to rotate, may be null
* @param shift number of time to shift (positive : right shift, negative : left shift)
* @return the rotated String,
* or the original String if {@code shift == 0},
* or {@code null} if null String input
* @since 3.5
*/
public static String rotate(final String str, final int shift) {
if (str == null) {
return null;
}
final int strLen = str.length();
if (shift == 0 || strLen == 0 || shift % strLen == 0) {
return str;
}
final StringBuilder builder = new StringBuilder(strLen);
final int offset = - (shift % strLen);
builder.append(substring(str, offset));
builder.append(substring(str, 0, offset));
return builder.toString();
}
// Splitting
//-----------------------------------------------------------------------
/**
* <p>Splits the provided text into an array, using whitespace as the
* separator.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.split(null) = null
* StringUtils.split("") = []
* StringUtils.split("abc def") = ["abc", "def"]
* StringUtils.split("abc def") = ["abc", "def"]
* StringUtils.split(" abc ") = ["abc"]
* </pre>
*
* @param str the String to parse, may be null
* @return an array of parsed Strings, {@code null} if null String input
*/
public static String[] split(final String str) {
return split(str, null, -1);
}
/**
* <p>Splits the provided text into an array, separator specified.
* This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.split(null, *) = null
* StringUtils.split("", *) = []
* StringUtils.split("a.b.c", '.') = ["a", "b", "c"]
* StringUtils.split("a..b.c", '.') = ["a", "b", "c"]
* StringUtils.split("a:b:c", '.') = ["a:b:c"]
* StringUtils.split("a b c", ' ') = ["a", "b", "c"]
* </pre>
*
* @param str the String to parse, may be null
* @param separatorChar the character used as the delimiter
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.0
*/
public static String[] split(final String str, final char separatorChar) {
return splitWorker(str, separatorChar, false);
}
/**
* <p>Splits the provided text into an array, separators specified.
* This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separatorChars splits on whitespace.</p>
*
* <pre>
* StringUtils.split(null, *) = null
* StringUtils.split("", *) = []
* StringUtils.split("abc def", null) = ["abc", "def"]
* StringUtils.split("abc def", " ") = ["abc", "def"]
* StringUtils.split("abc def", " ") = ["abc", "def"]
* StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separatorChars the characters used as the delimiters,
* {@code null} splits on whitespace
* @return an array of parsed Strings, {@code null} if null String input
*/
public static String[] split(final String str, final String separatorChars) {
return splitWorker(str, separatorChars, -1, false);
}
/**
* <p>Splits the provided text into an array with a maximum length,
* separators specified.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separatorChars splits on whitespace.</p>
*
* <p>If more than {@code max} delimited substrings are found, the last
* returned string includes all characters after the first {@code max - 1}
* returned strings (including separator characters).</p>
*
* <pre>
* StringUtils.split(null, *, *) = null
* StringUtils.split("", *, *) = []
* StringUtils.split("ab cd ef", null, 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab cd ef", null, 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separatorChars the characters used as the delimiters,
* {@code null} splits on whitespace
* @param max the maximum number of elements to include in the
* array. A zero or negative value implies no limit
* @return an array of parsed Strings, {@code null} if null String input
*/
public static String[] split(final String str, final String separatorChars, final int max) {
return splitWorker(str, separatorChars, max, false);
}
/**
* <p>Splits a String by Character type as returned by
* {@code java.lang.Character.getType(char)}. Groups of contiguous
* characters of the same type are returned as complete tokens.
* <pre>
* StringUtils.splitByCharacterType(null) = null
* StringUtils.splitByCharacterType("") = []
* StringUtils.splitByCharacterType("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterType("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterType("ab:cd:ef") = ["ab", ":", "cd", ":", "ef"]
* StringUtils.splitByCharacterType("number5") = ["number", "5"]
* StringUtils.splitByCharacterType("fooBar") = ["foo", "B", "ar"]
* StringUtils.splitByCharacterType("foo200Bar") = ["foo", "200", "B", "ar"]
* StringUtils.splitByCharacterType("ASFRules") = ["ASFR", "ules"]
* </pre>
* @param str the String to split, may be {@code null}
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.4
*/
public static String[] splitByCharacterType(final String str) {
return splitByCharacterType(str, false);
}
/**
* <p>Splits a String by Character type as returned by
* {@code java.lang.Character.getType(char)}. Groups of contiguous
* characters of the same type are returned as complete tokens, with the
* following exception: if {@code camelCase} is {@code true},
* the character of type {@code Character.UPPERCASE_LETTER}, if any,
* immediately preceding a token of type {@code Character.LOWERCASE_LETTER}
* will belong to the following token rather than to the preceding, if any,
* {@code Character.UPPERCASE_LETTER} token.
* @param str the String to split, may be {@code null}
* @param camelCase whether to use so-called "camel-case" for letter types
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.4
*/
private static String[] splitByCharacterType(final String str, final boolean camelCase) {
if (str == null) {
return null;
}
if (str.isEmpty()) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
final char[] c = str.toCharArray();
final List<String> list = new ArrayList<>();
int tokenStart = 0;
int currentType = Character.getType(c[tokenStart]);
for (int pos = tokenStart + 1; pos < c.length; pos++) {
final int type = Character.getType(c[pos]);
if (type == currentType) {
continue;
}
if (camelCase && type == Character.LOWERCASE_LETTER && currentType == Character.UPPERCASE_LETTER) {
final int newTokenStart = pos - 1;
if (newTokenStart != tokenStart) {
list.add(new String(c, tokenStart, newTokenStart - tokenStart));
tokenStart = newTokenStart;
}
} else {
list.add(new String(c, tokenStart, pos - tokenStart));
tokenStart = pos;
}
currentType = type;
}
list.add(new String(c, tokenStart, c.length - tokenStart));
return list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
/**
* <p>Splits a String by Character type as returned by
* {@code java.lang.Character.getType(char)}. Groups of contiguous
* characters of the same type are returned as complete tokens, with the
* following exception: the character of type
* {@code Character.UPPERCASE_LETTER}, if any, immediately
* preceding a token of type {@code Character.LOWERCASE_LETTER}
* will belong to the following token rather than to the preceding, if any,
* {@code Character.UPPERCASE_LETTER} token.
* <pre>
* StringUtils.splitByCharacterTypeCamelCase(null) = null
* StringUtils.splitByCharacterTypeCamelCase("") = []
* StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterTypeCamelCase("ab:cd:ef") = ["ab", ":", "cd", ":", "ef"]
* StringUtils.splitByCharacterTypeCamelCase("number5") = ["number", "5"]
* StringUtils.splitByCharacterTypeCamelCase("fooBar") = ["foo", "Bar"]
* StringUtils.splitByCharacterTypeCamelCase("foo200Bar") = ["foo", "200", "Bar"]
* StringUtils.splitByCharacterTypeCamelCase("ASFRules") = ["ASF", "Rules"]
* </pre>
* @param str the String to split, may be {@code null}
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.4
*/
public static String[] splitByCharacterTypeCamelCase(final String str) {
return splitByCharacterType(str, true);
}
/**
* <p>Splits the provided text into an array, separator string specified.</p>
*
* <p>The separator(s) will not be included in the returned String array.
* Adjacent separators are treated as one separator.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separator splits on whitespace.</p>
*
* <pre>
* StringUtils.splitByWholeSeparator(null, *) = null
* StringUtils.splitByWholeSeparator("", *) = []
* StringUtils.splitByWholeSeparator("ab de fg", null) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab de fg", null) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separator String containing the String to be used as a delimiter,
* {@code null} splits on whitespace
* @return an array of parsed Strings, {@code null} if null String was input
*/
public static String[] splitByWholeSeparator(final String str, final String separator) {
return splitByWholeSeparatorWorker(str, separator, -1, false);
}
/**
* <p>Splits the provided text into an array, separator string specified.
* Returns a maximum of {@code max} substrings.</p>
*
* <p>The separator(s) will not be included in the returned String array.
* Adjacent separators are treated as one separator.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separator splits on whitespace.</p>
*
* <pre>
* StringUtils.splitByWholeSeparator(null, *, *) = null
* StringUtils.splitByWholeSeparator("", *, *) = []
* StringUtils.splitByWholeSeparator("ab de fg", null, 0) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab de fg", null, 0) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separator String containing the String to be used as a delimiter,
* {@code null} splits on whitespace
* @param max the maximum number of elements to include in the returned
* array. A zero or negative value implies no limit.
* @return an array of parsed Strings, {@code null} if null String was input
*/
public static String[] splitByWholeSeparator( final String str, final String separator, final int max) {
return splitByWholeSeparatorWorker(str, separator, max, false);
}
/**
* <p>Splits the provided text into an array, separator string specified. </p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separator splits on whitespace.</p>
*
* <pre>
* StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *) = null
* StringUtils.splitByWholeSeparatorPreserveAllTokens("", *) = []
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null) = ["ab", "", "", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separator String containing the String to be used as a delimiter,
* {@code null} splits on whitespace
* @return an array of parsed Strings, {@code null} if null String was input
* @since 2.4
*/
public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator) {
return splitByWholeSeparatorWorker(str, separator, -1, true);
}
/**
* <p>Splits the provided text into an array, separator string specified.
* Returns a maximum of {@code max} substrings.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separator splits on whitespace.</p>
*
* <pre>
* StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *, *) = null
* StringUtils.splitByWholeSeparatorPreserveAllTokens("", *, *) = []
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null, 0) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null, 0) = ["ab", "", "", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separator String containing the String to be used as a delimiter,
* {@code null} splits on whitespace
* @param max the maximum number of elements to include in the returned
* array. A zero or negative value implies no limit.
* @return an array of parsed Strings, {@code null} if null String was input
* @since 2.4
*/
public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator, final int max) {
return splitByWholeSeparatorWorker(str, separator, max, true);
}
/**
* Performs the logic for the {@code splitByWholeSeparatorPreserveAllTokens} methods.
*
* @param str the String to parse, may be {@code null}
* @param separator String containing the String to be used as a delimiter,
* {@code null} splits on whitespace
* @param max the maximum number of elements to include in the returned
* array. A zero or negative value implies no limit.
* @param preserveAllTokens if {@code true}, adjacent separators are
* treated as empty token separators; if {@code false}, adjacent
* separators are treated as one separator.
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.4
*/
private static String[] splitByWholeSeparatorWorker(
final String str, final String separator, final int max, final boolean preserveAllTokens) {
if (str == null) {
return null;
}
final int len = str.length();
if (len == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
if (separator == null || EMPTY.equals(separator)) {
// Split on whitespace.
return splitWorker(str, null, max, preserveAllTokens);
}
final int separatorLength = separator.length();
final ArrayList<String> substrings = new ArrayList<>();
int numberOfSubstrings = 0;
int beg = 0;
int end = 0;
while (end < len) {
end = str.indexOf(separator, beg);
if (end > -1) {
if (end > beg) {
numberOfSubstrings += 1;
if (numberOfSubstrings == max) {
end = len;
substrings.add(str.substring(beg));
} else {
// The following is OK, because String.substring( beg, end ) excludes
// the character at the position 'end'.
substrings.add(str.substring(beg, end));
// Set the starting point for the next search.
// The following is equivalent to beg = end + (separatorLength - 1) + 1,
// which is the right calculation:
beg = end + separatorLength;
}
} else {
// We found a consecutive occurrence of the separator, so skip it.
if (preserveAllTokens) {
numberOfSubstrings += 1;
if (numberOfSubstrings == max) {
end = len;
substrings.add(str.substring(beg));
} else {
substrings.add(EMPTY);
}
}
beg = end + separatorLength;
}
} else {
// String.substring( beg ) goes from 'beg' to the end of the String.
substrings.add(str.substring(beg));
end = len;
}
}
return substrings.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
// -----------------------------------------------------------------------
/**
* <p>Splits the provided text into an array, using whitespace as the
* separator, preserving all tokens, including empty tokens created by
* adjacent separators. This is an alternative to using StringTokenizer.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.splitPreserveAllTokens(null) = null
* StringUtils.splitPreserveAllTokens("") = []
* StringUtils.splitPreserveAllTokens("abc def") = ["abc", "def"]
* StringUtils.splitPreserveAllTokens("abc def") = ["abc", "", "def"]
* StringUtils.splitPreserveAllTokens(" abc ") = ["", "abc", ""]
* </pre>
*
* @param str the String to parse, may be {@code null}
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.1
*/
public static String[] splitPreserveAllTokens(final String str) {
return splitWorker(str, null, -1, true);
}
/**
* <p>Splits the provided text into an array, separator specified,
* preserving all tokens, including empty tokens created by adjacent
* separators. This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.splitPreserveAllTokens(null, *) = null
* StringUtils.splitPreserveAllTokens("", *) = []
* StringUtils.splitPreserveAllTokens("a.b.c", '.') = ["a", "b", "c"]
* StringUtils.splitPreserveAllTokens("a..b.c", '.') = ["a", "", "b", "c"]
* StringUtils.splitPreserveAllTokens("a:b:c", '.') = ["a:b:c"]
* StringUtils.splitPreserveAllTokens("a\tb\nc", null) = ["a", "b", "c"]
* StringUtils.splitPreserveAllTokens("a b c", ' ') = ["a", "b", "c"]
* StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", ""]
* StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", "", ""]
* StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", a", "b", "c"]
* StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", "", a", "b", "c"]
* StringUtils.splitPreserveAllTokens(" a b c ", ' ') = ["", a", "b", "c", ""]
* </pre>
*
* @param str the String to parse, may be {@code null}
* @param separatorChar the character used as the delimiter,
* {@code null} splits on whitespace
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.1
*/
public static String[] splitPreserveAllTokens(final String str, final char separatorChar) {
return splitWorker(str, separatorChar, true);
}
/**
* <p>Splits the provided text into an array, separators specified,
* preserving all tokens, including empty tokens created by adjacent
* separators. This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separatorChars splits on whitespace.</p>
*
* <pre>
* StringUtils.splitPreserveAllTokens(null, *) = null
* StringUtils.splitPreserveAllTokens("", *) = []
* StringUtils.splitPreserveAllTokens("abc def", null) = ["abc", "def"]
* StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "def"]
* StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "", def"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef:", ":") = ["ab", "cd", "ef", ""]
* StringUtils.splitPreserveAllTokens("ab:cd:ef::", ":") = ["ab", "cd", "ef", "", ""]
* StringUtils.splitPreserveAllTokens("ab::cd:ef", ":") = ["ab", "", cd", "ef"]
* StringUtils.splitPreserveAllTokens(":cd:ef", ":") = ["", cd", "ef"]
* StringUtils.splitPreserveAllTokens("::cd:ef", ":") = ["", "", cd", "ef"]
* StringUtils.splitPreserveAllTokens(":cd:ef:", ":") = ["", cd", "ef", ""]
* </pre>
*
* @param str the String to parse, may be {@code null}
* @param separatorChars the characters used as the delimiters,
* {@code null} splits on whitespace
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.1
*/
public static String[] splitPreserveAllTokens(final String str, final String separatorChars) {
return splitWorker(str, separatorChars, -1, true);
}
/**
* <p>Splits the provided text into an array with a maximum length,
* separators specified, preserving all tokens, including empty tokens
* created by adjacent separators.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* Adjacent separators are treated as one separator.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separatorChars splits on whitespace.</p>
*
* <p>If more than {@code max} delimited substrings are found, the last
* returned string includes all characters after the first {@code max - 1}
* returned strings (including separator characters).</p>
*
* <pre>
* StringUtils.splitPreserveAllTokens(null, *, *) = null
* StringUtils.splitPreserveAllTokens("", *, *) = []
* StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "de", "fg"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "", "", "de", "fg"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 2) = ["ab", " de fg"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 3) = ["ab", "", " de fg"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 4) = ["ab", "", "", "de fg"]
* </pre>
*
* @param str the String to parse, may be {@code null}
* @param separatorChars the characters used as the delimiters,
* {@code null} splits on whitespace
* @param max the maximum number of elements to include in the
* array. A zero or negative value implies no limit
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.1
*/
public static String[] splitPreserveAllTokens(final String str, final String separatorChars, final int max) {
return splitWorker(str, separatorChars, max, true);
}
/**
* Performs the logic for the {@code split} and
* {@code splitPreserveAllTokens} methods that do not return a
* maximum array length.
*
* @param str the String to parse, may be {@code null}
* @param separatorChar the separate character
* @param preserveAllTokens if {@code true}, adjacent separators are
* treated as empty token separators; if {@code false}, adjacent
* separators are treated as one separator.
* @return an array of parsed Strings, {@code null} if null String input
*/
private static String[] splitWorker(final String str, final char separatorChar, final boolean preserveAllTokens) {
// Performance tuned for 2.0 (JDK1.4)
if (str == null) {
return null;
}
final int len = str.length();
if (len == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
final List<String> list = new ArrayList<>();
int i = 0, start = 0;
boolean match = false;
boolean lastMatch = false;
while (i < len) {
if (str.charAt(i) == separatorChar) {
if (match || preserveAllTokens) {
list.add(str.substring(start, i));
match = false;
lastMatch = true;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
if (match || preserveAllTokens && lastMatch) {
list.add(str.substring(start, i));
}
return list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
/**
* Performs the logic for the {@code split} and
* {@code splitPreserveAllTokens} methods that return a maximum array
* length.
*
* @param str the String to parse, may be {@code null}
* @param separatorChars the separate character
* @param max the maximum number of elements to include in the
* array. A zero or negative value implies no limit.
* @param preserveAllTokens if {@code true}, adjacent separators are
* treated as empty token separators; if {@code false}, adjacent
* separators are treated as one separator.
* @return an array of parsed Strings, {@code null} if null String input
*/
private static String[] splitWorker(final String str, final String separatorChars, final int max, final boolean preserveAllTokens) {
// Performance tuned for 2.0 (JDK1.4)
// Direct code is quicker than StringTokenizer.
// Also, StringTokenizer uses isSpace() not isWhitespace()
if (str == null) {
return null;
}
final int len = str.length();
if (len == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
final List<String> list = new ArrayList<>();
int sizePlus1 = 1;
int i = 0, start = 0;
boolean match = false;
boolean lastMatch = false;
if (separatorChars == null) {
// Null separator means use whitespace
while (i < len) {
if (Character.isWhitespace(str.charAt(i))) {
if (match || preserveAllTokens) {
lastMatch = true;
if (sizePlus1++ == max) {
i = len;
lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
} else if (separatorChars.length() == 1) {
// Optimise 1 character case
final char sep = separatorChars.charAt(0);
while (i < len) {
if (str.charAt(i) == sep) {
if (match || preserveAllTokens) {
lastMatch = true;
if (sizePlus1++ == max) {
i = len;
lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
} else {
// standard case
while (i < len) {
if (separatorChars.indexOf(str.charAt(i)) >= 0) {
if (match || preserveAllTokens) {
lastMatch = true;
if (sizePlus1++ == max) {
i = len;
lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
}
if (match || preserveAllTokens && lastMatch) {
list.add(str.substring(start, i));
}
return list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
/**
* <p>Check if a CharSequence starts with a specified prefix.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered to be equal. The comparison is case sensitive.</p>
*
* <pre>
* StringUtils.startsWith(null, null) = true
* StringUtils.startsWith(null, "abc") = false
* StringUtils.startsWith("abcdef", null) = false
* StringUtils.startsWith("abcdef", "abc") = true
* StringUtils.startsWith("ABCDEF", "abc") = false
* </pre>
*
* @see java.lang.String#startsWith(String)
* @param str the CharSequence to check, may be null
* @param prefix the prefix to find, may be null
* @return {@code true} if the CharSequence starts with the prefix, case sensitive, or
* both {@code null}
* @since 2.4
* @since 3.0 Changed signature from startsWith(String, String) to startsWith(CharSequence, CharSequence)
*/
public static boolean startsWith(final CharSequence str, final CharSequence prefix) {
return startsWith(str, prefix, false);
}
/**
* <p>Check if a CharSequence starts with a specified prefix (optionally case insensitive).</p>
*
* @see java.lang.String#startsWith(String)
* @param str the CharSequence to check, may be null
* @param prefix the prefix to find, may be null
* @param ignoreCase indicates whether the compare should ignore case
* (case insensitive) or not.
* @return {@code true} if the CharSequence starts with the prefix or
* both {@code null}
*/
private static boolean startsWith(final CharSequence str, final CharSequence prefix, final boolean ignoreCase) {
if (str == null || prefix == null) {
return str == prefix;
}
if (prefix.length() > str.length()) {
return false;
}
return CharSequenceUtils.regionMatches(str, ignoreCase, 0, prefix, 0, prefix.length());
}
/**
* <p>Check if a CharSequence starts with any of the provided case-sensitive prefixes.</p>
*
* <pre>
* StringUtils.startsWithAny(null, null) = false
* StringUtils.startsWithAny(null, new String[] {"abc"}) = false
* StringUtils.startsWithAny("abcxyz", null) = false
* StringUtils.startsWithAny("abcxyz", new String[] {""}) = true
* StringUtils.startsWithAny("abcxyz", new String[] {"abc"}) = true
* StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true
* StringUtils.startsWithAny("abcxyz", null, "xyz", "ABCX") = false
* StringUtils.startsWithAny("ABCXYZ", null, "xyz", "abc") = false
* </pre>
*
* @param sequence the CharSequence to check, may be null
* @param searchStrings the case-sensitive CharSequence prefixes, may be empty or contain {@code null}
* @see StringUtils#startsWith(CharSequence, CharSequence)
* @return {@code true} if the input {@code sequence} is {@code null} AND no {@code searchStrings} are provided, or
* the input {@code sequence} begins with any of the provided case-sensitive {@code searchStrings}.
* @since 2.5
* @since 3.0 Changed signature from startsWithAny(String, String[]) to startsWithAny(CharSequence, CharSequence...)
*/
public static boolean startsWithAny(final CharSequence sequence, final CharSequence... searchStrings) {
if (isEmpty(sequence) || ArrayUtils.isEmpty(searchStrings)) {
return false;
}
for (final CharSequence searchString : searchStrings) {
if (startsWith(sequence, searchString)) {
return true;
}
}
return false;
}
/**
* <p>Case insensitive check if a CharSequence starts with a specified prefix.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered to be equal. The comparison is case insensitive.</p>
*
* <pre>
* StringUtils.startsWithIgnoreCase(null, null) = true
* StringUtils.startsWithIgnoreCase(null, "abc") = false
* StringUtils.startsWithIgnoreCase("abcdef", null) = false
* StringUtils.startsWithIgnoreCase("abcdef", "abc") = true
* StringUtils.startsWithIgnoreCase("ABCDEF", "abc") = true
* </pre>
*
* @see java.lang.String#startsWith(String)
* @param str the CharSequence to check, may be null
* @param prefix the prefix to find, may be null
* @return {@code true} if the CharSequence starts with the prefix, case insensitive, or
* both {@code null}
* @since 2.4
* @since 3.0 Changed signature from startsWithIgnoreCase(String, String) to startsWithIgnoreCase(CharSequence, CharSequence)
*/
public static boolean startsWithIgnoreCase(final CharSequence str, final CharSequence prefix) {
return startsWith(str, prefix, true);
}
// Stripping
//-----------------------------------------------------------------------
/**
* <p>Strips whitespace from the start and end of a String.</p>
*
* <p>This is similar to {@link #trim(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.strip(null) = null
* StringUtils.strip("") = ""
* StringUtils.strip(" ") = ""
* StringUtils.strip("abc") = "abc"
* StringUtils.strip(" abc") = "abc"
* StringUtils.strip("abc ") = "abc"
* StringUtils.strip(" abc ") = "abc"
* StringUtils.strip(" ab c ") = "ab c"
* </pre>
*
* @param str the String to remove whitespace from, may be null
* @return the stripped String, {@code null} if null String input
*/
public static String strip(final String str) {
return strip(str, null);
}
/**
* <p>Strips any of a set of characters from the start and end of a String.
* This is similar to {@link String#trim()} but allows the characters
* to be stripped to be controlled.</p>
*
* <p>A {@code null} input String returns {@code null}.
* An empty string ("") input returns the empty string.</p>
*
* <p>If the stripChars String is {@code null}, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.
* Alternatively use {@link #strip(String)}.</p>
*
* <pre>
* StringUtils.strip(null, *) = null
* StringUtils.strip("", *) = ""
* StringUtils.strip("abc", null) = "abc"
* StringUtils.strip(" abc", null) = "abc"
* StringUtils.strip("abc ", null) = "abc"
* StringUtils.strip(" abc ", null) = "abc"
* StringUtils.strip(" abcyx", "xyz") = " abc"
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped String, {@code null} if null String input
*/
public static String strip(String str, final String stripChars) {
if (isEmpty(str)) {
return str;
}
str = stripStart(str, stripChars);
return stripEnd(str, stripChars);
}
/**
* <p>Removes diacritics (~= accents) from a string. The case will not be altered.</p>
* <p>For instance, 'à' will be replaced by 'a'.</p>
* <p>Note that ligatures will be left as is.</p>
*
* <pre>
* StringUtils.stripAccents(null) = null
* StringUtils.stripAccents("") = ""
* StringUtils.stripAccents("control") = "control"
* StringUtils.stripAccents("éclair") = "eclair"
* </pre>
*
* @param input String to be stripped
* @return input text with diacritics removed
*
* @since 3.0
*/
// See also Lucene's ASCIIFoldingFilter (Lucene 2.9) that replaces accented characters by their unaccented equivalent (and uncommitted bug fix: https://issues.apache.org/jira/browse/LUCENE-1343?focusedCommentId=12858907&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#action_12858907).
public static String stripAccents(final String input) {
if (input == null) {
return null;
}
final Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); //$NON-NLS-1$
final StringBuilder decomposed = new StringBuilder(Normalizer.normalize(input, Normalizer.Form.NFD));
convertRemainingAccentCharacters(decomposed);
// Note that this doesn't correctly remove ligatures...
return pattern.matcher(decomposed).replaceAll(EMPTY);
}
// StripAll
//-----------------------------------------------------------------------
/**
* <p>Strips whitespace from the start and end of every String in an array.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>A new array is returned each time, except for length zero.
* A {@code null} array will return {@code null}.
* An empty array will return itself.
* A {@code null} array entry will be ignored.</p>
*
* <pre>
* StringUtils.stripAll(null) = null
* StringUtils.stripAll([]) = []
* StringUtils.stripAll(["abc", " abc"]) = ["abc", "abc"]
* StringUtils.stripAll(["abc ", null]) = ["abc", null]
* </pre>
*
* @param strs the array to remove whitespace from, may be null
* @return the stripped Strings, {@code null} if null array input
*/
public static String[] stripAll(final String... strs) {
return stripAll(strs, null);
}
/**
* <p>Strips any of a set of characters from the start and end of every
* String in an array.</p>
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>A new array is returned each time, except for length zero.
* A {@code null} array will return {@code null}.
* An empty array will return itself.
* A {@code null} array entry will be ignored.
* A {@code null} stripChars will strip whitespace as defined by
* {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripAll(null, *) = null
* StringUtils.stripAll([], *) = []
* StringUtils.stripAll(["abc", " abc"], null) = ["abc", "abc"]
* StringUtils.stripAll(["abc ", null], null) = ["abc", null]
* StringUtils.stripAll(["abc ", null], "yz") = ["abc ", null]
* StringUtils.stripAll(["yabcz", null], "yz") = ["abc", null]
* </pre>
*
* @param strs the array to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped Strings, {@code null} if null array input
*/
public static String[] stripAll(final String[] strs, final String stripChars) {
int strsLen;
if (strs == null || (strsLen = strs.length) == 0) {
return strs;
}
final String[] newArr = new String[strsLen];
for (int i = 0; i < strsLen; i++) {
newArr[i] = strip(strs[i], stripChars);
}
return newArr;
}
/**
* <p>Strips any of a set of characters from the end of a String.</p>
*
* <p>A {@code null} input String returns {@code null}.
* An empty string ("") input returns the empty string.</p>
*
* <p>If the stripChars String is {@code null}, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripEnd(null, *) = null
* StringUtils.stripEnd("", *) = ""
* StringUtils.stripEnd("abc", "") = "abc"
* StringUtils.stripEnd("abc", null) = "abc"
* StringUtils.stripEnd(" abc", null) = " abc"
* StringUtils.stripEnd("abc ", null) = "abc"
* StringUtils.stripEnd(" abc ", null) = " abc"
* StringUtils.stripEnd(" abcyx", "xyz") = " abc"
* StringUtils.stripEnd("120.00", ".0") = "12"
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the set of characters to remove, null treated as whitespace
* @return the stripped String, {@code null} if null String input
*/
public static String stripEnd(final String str, final String stripChars) {
int end = length(str);
if (end == 0) {
return str;
}
if (stripChars == null) {
while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) {
end--;
}
} else if (stripChars.isEmpty()) {
return str;
} else {
while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != INDEX_NOT_FOUND) {
end--;
}
}
return str.substring(0, end);
}
/**
* <p>Strips any of a set of characters from the start of a String.</p>
*
* <p>A {@code null} input String returns {@code null}.
* An empty string ("") input returns the empty string.</p>
*
* <p>If the stripChars String is {@code null}, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripStart(null, *) = null
* StringUtils.stripStart("", *) = ""
* StringUtils.stripStart("abc", "") = "abc"
* StringUtils.stripStart("abc", null) = "abc"
* StringUtils.stripStart(" abc", null) = "abc"
* StringUtils.stripStart("abc ", null) = "abc "
* StringUtils.stripStart(" abc ", null) = "abc "
* StringUtils.stripStart("yxabc ", "xyz") = "abc "
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped String, {@code null} if null String input
*/
public static String stripStart(final String str, final String stripChars) {
final int strLen = length(str);
if (strLen == 0) {
return str;
}
int start = 0;
if (stripChars == null) {
while (start != strLen && Character.isWhitespace(str.charAt(start))) {
start++;
}
} else if (stripChars.isEmpty()) {
return str;
} else {
while (start != strLen && stripChars.indexOf(str.charAt(start)) != INDEX_NOT_FOUND) {
start++;
}
}
return str.substring(start);
}
/**
* <p>Strips whitespace from the start and end of a String returning
* an empty String if {@code null} input.</p>
*
* <p>This is similar to {@link #trimToEmpty(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripToEmpty(null) = ""
* StringUtils.stripToEmpty("") = ""
* StringUtils.stripToEmpty(" ") = ""
* StringUtils.stripToEmpty("abc") = "abc"
* StringUtils.stripToEmpty(" abc") = "abc"
* StringUtils.stripToEmpty("abc ") = "abc"
* StringUtils.stripToEmpty(" abc ") = "abc"
* StringUtils.stripToEmpty(" ab c ") = "ab c"
* </pre>
*
* @param str the String to be stripped, may be null
* @return the trimmed String, or an empty String if {@code null} input
* @since 2.0
*/
public static String stripToEmpty(final String str) {
return str == null ? EMPTY : strip(str, null);
}
/**
* <p>Strips whitespace from the start and end of a String returning
* {@code null} if the String is empty ("") after the strip.</p>
*
* <p>This is similar to {@link #trimToNull(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripToNull(null) = null
* StringUtils.stripToNull("") = null
* StringUtils.stripToNull(" ") = null
* StringUtils.stripToNull("abc") = "abc"
* StringUtils.stripToNull(" abc") = "abc"
* StringUtils.stripToNull("abc ") = "abc"
* StringUtils.stripToNull(" abc ") = "abc"
* StringUtils.stripToNull(" ab c ") = "ab c"
* </pre>
*
* @param str the String to be stripped, may be null
* @return the stripped String,
* {@code null} if whitespace, empty or null String input
* @since 2.0
*/
public static String stripToNull(String str) {
if (str == null) {
return null;
}
str = strip(str, null);
return str.isEmpty() ? null : str;
}
// Substring
//-----------------------------------------------------------------------
/**
* <p>Gets a substring from the specified String avoiding exceptions.</p>
*
* <p>A negative start position can be used to start {@code n}
* characters from the end of the String.</p>
*
* <p>A {@code null} String will return {@code null}.
* An empty ("") String will return "".</p>
*
* <pre>
* StringUtils.substring(null, *) = null
* StringUtils.substring("", *) = ""
* StringUtils.substring("abc", 0) = "abc"
* StringUtils.substring("abc", 2) = "c"
* StringUtils.substring("abc", 4) = ""
* StringUtils.substring("abc", -2) = "bc"
* StringUtils.substring("abc", -4) = "abc"
* </pre>
*
* @param str the String to get the substring from, may be null
* @param start the position to start from, negative means
* count back from the end of the String by this many characters
* @return substring from start position, {@code null} if null String input
*/
public static String substring(final String str, int start) {
if (str == null) {
return null;
}
// handle negatives, which means last n characters
if (start < 0) {
start = str.length() + start; // remember start is negative
}
if (start < 0) {
start = 0;
}
if (start > str.length()) {
return EMPTY;
}
return str.substring(start);
}
/**
* <p>Gets a substring from the specified String avoiding exceptions.</p>
*
* <p>A negative start position can be used to start/end {@code n}
* characters from the end of the String.</p>
*
* <p>The returned substring starts with the character in the {@code start}
* position and ends before the {@code end} position. All position counting is
* zero-based -- i.e., to start at the beginning of the string use
* {@code start = 0}. Negative start and end positions can be used to
* specify offsets relative to the end of the String.</p>
*
* <p>If {@code start} is not strictly to the left of {@code end}, ""
* is returned.</p>
*
* <pre>
* StringUtils.substring(null, *, *) = null
* StringUtils.substring("", * , *) = "";
* StringUtils.substring("abc", 0, 2) = "ab"
* StringUtils.substring("abc", 2, 0) = ""
* StringUtils.substring("abc", 2, 4) = "c"
* StringUtils.substring("abc", 4, 6) = ""
* StringUtils.substring("abc", 2, 2) = ""
* StringUtils.substring("abc", -2, -1) = "b"
* StringUtils.substring("abc", -4, 2) = "ab"
* </pre>
*
* @param str the String to get the substring from, may be null
* @param start the position to start from, negative means
* count back from the end of the String by this many characters
* @param end the position to end at (exclusive), negative means
* count back from the end of the String by this many characters
* @return substring from start position to end position,
* {@code null} if null String input
*/
public static String substring(final String str, int start, int end) {
if (str == null) {
return null;
}
// handle negatives
if (end < 0) {
end = str.length() + end; // remember end is negative
}
if (start < 0) {
start = str.length() + start; // remember start is negative
}
// check length next
if (end > str.length()) {
end = str.length();
}
// if start is greater than end, return ""
if (start > end) {
return EMPTY;
}
if (start < 0) {
start = 0;
}
if (end < 0) {
end = 0;
}
return str.substring(start, end);
}
/**
* <p>Gets the substring after the first occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A {@code null} string input will return {@code null}.
* An empty ("") string input will return the empty string.
* A {@code null} separator will return the empty string if the
* input string is not {@code null}.</p>
*
* <p>If nothing is found, the empty string is returned.</p>
*
* <pre>
* StringUtils.substringAfter(null, *) = null
* StringUtils.substringAfter("", *) = ""
* StringUtils.substringAfter(*, null) = ""
* StringUtils.substringAfter("abc", "a") = "bc"
* StringUtils.substringAfter("abcba", "b") = "cba"
* StringUtils.substringAfter("abc", "c") = ""
* StringUtils.substringAfter("abc", "d") = ""
* StringUtils.substringAfter("abc", "") = "abc"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring after the first occurrence of the separator,
* {@code null} if null String input
* @since 2.0
*/
public static String substringAfter(final String str, final String separator) {
if (isEmpty(str)) {
return str;
}
if (separator == null) {
return EMPTY;
}
final int pos = str.indexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return EMPTY;
}
return str.substring(pos + separator.length());
}
// startsWith
//-----------------------------------------------------------------------
/**
* <p>Gets the substring after the last occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A {@code null} string input will return {@code null}.
* An empty ("") string input will return the empty string.
* An empty or {@code null} separator will return the empty string if
* the input string is not {@code null}.</p>
*
* <p>If nothing is found, the empty string is returned.</p>
*
* <pre>
* StringUtils.substringAfterLast(null, *) = null
* StringUtils.substringAfterLast("", *) = ""
* StringUtils.substringAfterLast(*, "") = ""
* StringUtils.substringAfterLast(*, null) = ""
* StringUtils.substringAfterLast("abc", "a") = "bc"
* StringUtils.substringAfterLast("abcba", "b") = "a"
* StringUtils.substringAfterLast("abc", "c") = ""
* StringUtils.substringAfterLast("a", "a") = ""
* StringUtils.substringAfterLast("a", "z") = ""
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring after the last occurrence of the separator,
* {@code null} if null String input
* @since 2.0
*/
public static String substringAfterLast(final String str, final String separator) {
if (isEmpty(str)) {
return str;
}
if (isEmpty(separator)) {
return EMPTY;
}
final int pos = str.lastIndexOf(separator);
if (pos == INDEX_NOT_FOUND || pos == str.length() - separator.length()) {
return EMPTY;
}
return str.substring(pos + separator.length());
}
// SubStringAfter/SubStringBefore
//-----------------------------------------------------------------------
/**
* <p>Gets the substring before the first occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A {@code null} string input will return {@code null}.
* An empty ("") string input will return the empty string.
* A {@code null} separator will return the input string.</p>
*
* <p>If nothing is found, the string input is returned.</p>
*
* <pre>
* StringUtils.substringBefore(null, *) = null
* StringUtils.substringBefore("", *) = ""
* StringUtils.substringBefore("abc", "a") = ""
* StringUtils.substringBefore("abcba", "b") = "a"
* StringUtils.substringBefore("abc", "c") = "ab"
* StringUtils.substringBefore("abc", "d") = "abc"
* StringUtils.substringBefore("abc", "") = ""
* StringUtils.substringBefore("abc", null) = "abc"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring before the first occurrence of the separator,
* {@code null} if null String input
* @since 2.0
*/
public static String substringBefore(final String str, final String separator) {
if (isEmpty(str) || separator == null) {
return str;
}
if (separator.isEmpty()) {
return EMPTY;
}
final int pos = str.indexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return str;
}
return str.substring(0, pos);
}
/**
* <p>Gets the substring before the last occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A {@code null} string input will return {@code null}.
* An empty ("") string input will return the empty string.
* An empty or {@code null} separator will return the input string.</p>
*
* <p>If nothing is found, the string input is returned.</p>
*
* <pre>
* StringUtils.substringBeforeLast(null, *) = null
* StringUtils.substringBeforeLast("", *) = ""
* StringUtils.substringBeforeLast("abcba", "b") = "abc"
* StringUtils.substringBeforeLast("abc", "c") = "ab"
* StringUtils.substringBeforeLast("a", "a") = ""
* StringUtils.substringBeforeLast("a", "z") = "a"
* StringUtils.substringBeforeLast("a", null) = "a"
* StringUtils.substringBeforeLast("a", "") = "a"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring before the last occurrence of the separator,
* {@code null} if null String input
* @since 2.0
*/
public static String substringBeforeLast(final String str, final String separator) {
if (isEmpty(str) || isEmpty(separator)) {
return str;
}
final int pos = str.lastIndexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return str;
}
return str.substring(0, pos);
}
// Substring between
//-----------------------------------------------------------------------
/**
* <p>Gets the String that is nested in between two instances of the
* same String.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} tag returns {@code null}.</p>
*
* <pre>
* StringUtils.substringBetween(null, *) = null
* StringUtils.substringBetween("", "") = ""
* StringUtils.substringBetween("", "tag") = null
* StringUtils.substringBetween("tagabctag", null) = null
* StringUtils.substringBetween("tagabctag", "") = ""
* StringUtils.substringBetween("tagabctag", "tag") = "abc"
* </pre>
*
* @param str the String containing the substring, may be null
* @param tag the String before and after the substring, may be null
* @return the substring, {@code null} if no match
* @since 2.0
*/
public static String substringBetween(final String str, final String tag) {
return substringBetween(str, tag, tag);
}
// endsWith
//-----------------------------------------------------------------------
/**
* <p>Gets the String that is nested in between two Strings.
* Only the first match is returned.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} open/close returns {@code null} (no match).
* An empty ("") open and close returns an empty string.</p>
*
* <pre>
* StringUtils.substringBetween("wx[b]yz", "[", "]") = "b"
* StringUtils.substringBetween(null, *, *) = null
* StringUtils.substringBetween(*, null, *) = null
* StringUtils.substringBetween(*, *, null) = null
* StringUtils.substringBetween("", "", "") = ""
* StringUtils.substringBetween("", "", "]") = null
* StringUtils.substringBetween("", "[", "]") = null
* StringUtils.substringBetween("yabcz", "", "") = ""
* StringUtils.substringBetween("yabcz", "y", "z") = "abc"
* StringUtils.substringBetween("yabczyabcz", "y", "z") = "abc"
* </pre>
*
* @param str the String containing the substring, may be null
* @param open the String before the substring, may be null
* @param close the String after the substring, may be null
* @return the substring, {@code null} if no match
* @since 2.0
*/
public static String substringBetween(final String str, final String open, final String close) {
if (str == null || open == null || close == null) {
return null;
}
final int start = str.indexOf(open);
if (start != INDEX_NOT_FOUND) {
final int end = str.indexOf(close, start + open.length());
if (end != INDEX_NOT_FOUND) {
return str.substring(start + open.length(), end);
}
}
return null;
}
/**
* <p>Searches a String for substrings delimited by a start and end tag,
* returning all matching substrings in an array.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} open/close returns {@code null} (no match).
* An empty ("") open/close returns {@code null} (no match).</p>
*
* <pre>
* StringUtils.substringsBetween("[a][b][c]", "[", "]") = ["a","b","c"]
* StringUtils.substringsBetween(null, *, *) = null
* StringUtils.substringsBetween(*, null, *) = null
* StringUtils.substringsBetween(*, *, null) = null
* StringUtils.substringsBetween("", "[", "]") = []
* </pre>
*
* @param str the String containing the substrings, null returns null, empty returns empty
* @param open the String identifying the start of the substring, empty returns null
* @param close the String identifying the end of the substring, empty returns null
* @return a String Array of substrings, or {@code null} if no match
* @since 2.3
*/
public static String[] substringsBetween(final String str, final String open, final String close) {
if (str == null || isEmpty(open) || isEmpty(close)) {
return null;
}
final int strLen = str.length();
if (strLen == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
final int closeLen = close.length();
final int openLen = open.length();
final List<String> list = new ArrayList<>();
int pos = 0;
while (pos < strLen - closeLen) {
int start = str.indexOf(open, pos);
if (start < 0) {
break;
}
start += openLen;
final int end = str.indexOf(close, start);
if (end < 0) {
break;
}
list.add(str.substring(start, end));
pos = end + closeLen;
}
if (list.isEmpty()) {
return null;
}
return list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
/**
* <p>Swaps the case of a String changing upper and title case to
* lower case, and lower case to upper case.</p>
*
* <ul>
* <li>Upper case character converts to Lower case</li>
* <li>Title case character converts to Lower case</li>
* <li>Lower case character converts to Upper case</li>
* </ul>
*
* <p>For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#swapCase(String)}.
* A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.swapCase(null) = null
* StringUtils.swapCase("") = ""
* StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer performs a word based algorithm.
* If you only use ASCII, you will notice no change.
* That functionality is available in org.apache.commons.lang3.text.WordUtils.</p>
*
* @param str the String to swap case, may be null
* @return the changed String, {@code null} if null String input
*/
public static String swapCase(final String str) {
if (isEmpty(str)) {
return str;
}
final int strLen = str.length();
final int newCodePoints[] = new int[strLen]; // cannot be longer than the char array
int outOffset = 0;
for (int i = 0; i < strLen; ) {
final int oldCodepoint = str.codePointAt(i);
final int newCodePoint;
if (Character.isUpperCase(oldCodepoint)) {
newCodePoint = Character.toLowerCase(oldCodepoint);
} else if (Character.isTitleCase(oldCodepoint)) {
newCodePoint = Character.toLowerCase(oldCodepoint);
} else if (Character.isLowerCase(oldCodepoint)) {
newCodePoint = Character.toUpperCase(oldCodepoint);
} else {
newCodePoint = oldCodepoint;
}
newCodePoints[outOffset++] = newCodePoint;
i += Character.charCount(newCodePoint);
}
return new String(newCodePoints, 0, outOffset);
}
/**
* <p>Converts a {@code CharSequence} into an array of code points.</p>
*
* <p>Valid pairs of surrogate code units will be converted into a single supplementary
* code point. Isolated surrogate code units (i.e. a high surrogate not followed by a low surrogate or
* a low surrogate not preceded by a high surrogate) will be returned as-is.</p>
*
* <pre>
* StringUtils.toCodePoints(null) = null
* StringUtils.toCodePoints("") = [] // empty array
* </pre>
*
* @param str the character sequence to convert
* @return an array of code points
* @since 3.6
*/
public static int[] toCodePoints(final CharSequence str) {
if (str == null) {
return null;
}
if (str.length() == 0) {
return ArrayUtils.EMPTY_INT_ARRAY;
}
final String s = str.toString();
final int[] result = new int[s.codePointCount(0, s.length())];
int index = 0;
for (int i = 0; i < result.length; i++) {
result[i] = s.codePointAt(index);
index += Character.charCount(result[i]);
}
return result;
}
/**
* Converts a {@code byte[]} to a String using the specified character encoding.
*
* @param bytes
* the byte array to read from
* @param charset
* the encoding to use, if null then use the platform default
* @return a new String
* @throws NullPointerException
* if {@code bytes} is null
* @since 3.2
* @since 3.3 No longer throws {@link UnsupportedEncodingException}.
*/
public static String toEncodedString(final byte[] bytes, final Charset charset) {
return new String(bytes, Charsets.toCharset(charset));
}
/**
* Converts the given source String as a lower-case using the {@link Locale#ROOT} locale in a null-safe manner.
*
* @param source A source String or null.
* @return the given source String as a lower-case using the {@link Locale#ROOT} locale or null.
* @since 3.10
*/
public static String toRootLowerCase(final String source) {
return source == null ? null : source.toLowerCase(Locale.ROOT);
}
/**
* Converts the given source String as a upper-case using the {@link Locale#ROOT} locale in a null-safe manner.
*
* @param source A source String or null.
* @return the given source String as a upper-case using the {@link Locale#ROOT} locale or null.
* @since 3.10
*/
public static String toRootUpperCase(final String source) {
return source == null ? null : source.toUpperCase(Locale.ROOT);
}
/**
* Converts a {@code byte[]} to a String using the specified character encoding.
*
* @param bytes
* the byte array to read from
* @param charsetName
* the encoding to use, if null then use the platform default
* @return a new String
* @throws UnsupportedEncodingException
* If the named charset is not supported
* @throws NullPointerException
* if the input is null
* @deprecated use {@link StringUtils#toEncodedString(byte[], Charset)} instead of String constants in your code
* @since 3.1
*/
@Deprecated
public static String toString(final byte[] bytes, final String charsetName) throws UnsupportedEncodingException {
return charsetName != null ? new String(bytes, charsetName) : new String(bytes, Charset.defaultCharset());
}
// Trim
//-----------------------------------------------------------------------
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String, handling {@code null} by returning
* {@code null}.</p>
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #strip(String)}.</p>
*
* <p>To trim your choice of characters, use the
* {@link #strip(String, String)} methods.</p>
*
* <pre>
* StringUtils.trim(null) = null
* StringUtils.trim("") = ""
* StringUtils.trim(" ") = ""
* StringUtils.trim("abc") = "abc"
* StringUtils.trim(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed string, {@code null} if null String input
*/
public static String trim(final String str) {
return str == null ? null : str.trim();
}
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String returning an empty String ("") if the String
* is empty ("") after the trim or if it is {@code null}.
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #stripToEmpty(String)}.</p>
*
* <pre>
* StringUtils.trimToEmpty(null) = ""
* StringUtils.trimToEmpty("") = ""
* StringUtils.trimToEmpty(" ") = ""
* StringUtils.trimToEmpty("abc") = "abc"
* StringUtils.trimToEmpty(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed String, or an empty String if {@code null} input
* @since 2.0
*/
public static String trimToEmpty(final String str) {
return str == null ? EMPTY : str.trim();
}
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String returning {@code null} if the String is
* empty ("") after the trim or if it is {@code null}.
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #stripToNull(String)}.</p>
*
* <pre>
* StringUtils.trimToNull(null) = null
* StringUtils.trimToNull("") = null
* StringUtils.trimToNull(" ") = null
* StringUtils.trimToNull("abc") = "abc"
* StringUtils.trimToNull(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed String,
* {@code null} if only chars <= 32, empty or null String input
* @since 2.0
*/
public static String trimToNull(final String str) {
final String ts = trim(str);
return isEmpty(ts) ? null : ts;
}
/**
* <p>Truncates a String. This will turn
* "Now is the time for all good men" into "Now is the time for".</p>
*
* <p>Specifically:</p>
* <ul>
* <li>If {@code str} is less than {@code maxWidth} characters
* long, return it.</li>
* <li>Else truncate it to {@code substring(str, 0, maxWidth)}.</li>
* <li>If {@code maxWidth} is less than {@code 0}, throw an
* {@code IllegalArgumentException}.</li>
* <li>In no case will it return a String of length greater than
* {@code maxWidth}.</li>
* </ul>
*
* <pre>
* StringUtils.truncate(null, 0) = null
* StringUtils.truncate(null, 2) = null
* StringUtils.truncate("", 4) = ""
* StringUtils.truncate("abcdefg", 4) = "abcd"
* StringUtils.truncate("abcdefg", 6) = "abcdef"
* StringUtils.truncate("abcdefg", 7) = "abcdefg"
* StringUtils.truncate("abcdefg", 8) = "abcdefg"
* StringUtils.truncate("abcdefg", -1) = throws an IllegalArgumentException
* </pre>
*
* @param str the String to truncate, may be null
* @param maxWidth maximum length of result String, must be positive
* @return truncated String, {@code null} if null String input
* @throws IllegalArgumentException If {@code maxWidth} is less than {@code 0}
* @since 3.5
*/
public static String truncate(final String str, final int maxWidth) {
return truncate(str, 0, maxWidth);
}
/**
* <p>Truncates a String. This will turn
* "Now is the time for all good men" into "is the time for all".</p>
*
* <p>Works like {@code truncate(String, int)}, but allows you to specify
* a "left edge" offset.
*
* <p>Specifically:</p>
* <ul>
* <li>If {@code str} is less than {@code maxWidth} characters
* long, return it.</li>
* <li>Else truncate it to {@code substring(str, offset, maxWidth)}.</li>
* <li>If {@code maxWidth} is less than {@code 0}, throw an
* {@code IllegalArgumentException}.</li>
* <li>If {@code offset} is less than {@code 0}, throw an
* {@code IllegalArgumentException}.</li>
* <li>In no case will it return a String of length greater than
* {@code maxWidth}.</li>
* </ul>
*
* <pre>
* StringUtils.truncate(null, 0, 0) = null
* StringUtils.truncate(null, 2, 4) = null
* StringUtils.truncate("", 0, 10) = ""
* StringUtils.truncate("", 2, 10) = ""
* StringUtils.truncate("abcdefghij", 0, 3) = "abc"
* StringUtils.truncate("abcdefghij", 5, 6) = "fghij"
* StringUtils.truncate("raspberry peach", 10, 15) = "peach"
* StringUtils.truncate("abcdefghijklmno", 0, 10) = "abcdefghij"
* StringUtils.truncate("abcdefghijklmno", -1, 10) = throws an IllegalArgumentException
* StringUtils.truncate("abcdefghijklmno", Integer.MIN_VALUE, 10) = throws an IllegalArgumentException
* StringUtils.truncate("abcdefghijklmno", Integer.MIN_VALUE, Integer.MAX_VALUE) = throws an IllegalArgumentException
* StringUtils.truncate("abcdefghijklmno", 0, Integer.MAX_VALUE) = "abcdefghijklmno"
* StringUtils.truncate("abcdefghijklmno", 1, 10) = "bcdefghijk"
* StringUtils.truncate("abcdefghijklmno", 2, 10) = "cdefghijkl"
* StringUtils.truncate("abcdefghijklmno", 3, 10) = "defghijklm"
* StringUtils.truncate("abcdefghijklmno", 4, 10) = "efghijklmn"
* StringUtils.truncate("abcdefghijklmno", 5, 10) = "fghijklmno"
* StringUtils.truncate("abcdefghijklmno", 5, 5) = "fghij"
* StringUtils.truncate("abcdefghijklmno", 5, 3) = "fgh"
* StringUtils.truncate("abcdefghijklmno", 10, 3) = "klm"
* StringUtils.truncate("abcdefghijklmno", 10, Integer.MAX_VALUE) = "klmno"
* StringUtils.truncate("abcdefghijklmno", 13, 1) = "n"
* StringUtils.truncate("abcdefghijklmno", 13, Integer.MAX_VALUE) = "no"
* StringUtils.truncate("abcdefghijklmno", 14, 1) = "o"
* StringUtils.truncate("abcdefghijklmno", 14, Integer.MAX_VALUE) = "o"
* StringUtils.truncate("abcdefghijklmno", 15, 1) = ""
* StringUtils.truncate("abcdefghijklmno", 15, Integer.MAX_VALUE) = ""
* StringUtils.truncate("abcdefghijklmno", Integer.MAX_VALUE, Integer.MAX_VALUE) = ""
* StringUtils.truncate("abcdefghij", 3, -1) = throws an IllegalArgumentException
* StringUtils.truncate("abcdefghij", -2, 4) = throws an IllegalArgumentException
* </pre>
*
* @param str the String to truncate, may be null
* @param offset left edge of source String
* @param maxWidth maximum length of result String, must be positive
* @return truncated String, {@code null} if null String input
* @throws IllegalArgumentException If {@code offset} or {@code maxWidth} is less than {@code 0}
* @since 3.5
*/
public static String truncate(final String str, final int offset, final int maxWidth) {
if (offset < 0) {
throw new IllegalArgumentException("offset cannot be negative");
}
if (maxWidth < 0) {
throw new IllegalArgumentException("maxWith cannot be negative");
}
if (str == null) {
return null;
}
if (offset > str.length()) {
return EMPTY;
}
if (str.length() > maxWidth) {
final int ix = offset + maxWidth > str.length() ? str.length() : offset + maxWidth;
return str.substring(offset, ix);
}
return str.substring(offset);
}
/**
* <p>Uncapitalizes a String, changing the first character to lower case as
* per {@link Character#toLowerCase(int)}. No other characters are changed.</p>
*
* <p>For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#uncapitalize(String)}.
* A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.uncapitalize(null) = null
* StringUtils.uncapitalize("") = ""
* StringUtils.uncapitalize("cat") = "cat"
* StringUtils.uncapitalize("Cat") = "cat"
* StringUtils.uncapitalize("CAT") = "cAT"
* </pre>
*
* @param str the String to uncapitalize, may be null
* @return the uncapitalized String, {@code null} if null String input
* @see org.apache.commons.lang3.text.WordUtils#uncapitalize(String)
* @see #capitalize(String)
* @since 2.0
*/
public static String uncapitalize(final String str) {
final int strLen = length(str);
if (strLen == 0) {
return str;
}
final int firstCodepoint = str.codePointAt(0);
final int newCodePoint = Character.toLowerCase(firstCodepoint);
if (firstCodepoint == newCodePoint) {
// already capitalized
return str;
}
final int newCodePoints[] = new int[strLen]; // cannot be longer than the char array
int outOffset = 0;
newCodePoints[outOffset++] = newCodePoint; // copy the first codepoint
for (int inOffset = Character.charCount(firstCodepoint); inOffset < strLen; ) {
final int codepoint = str.codePointAt(inOffset);
newCodePoints[outOffset++] = codepoint; // copy the remaining ones
inOffset += Character.charCount(codepoint);
}
return new String(newCodePoints, 0, outOffset);
}
/**
* <p>
* Unwraps a given string from a character.
* </p>
*
* <pre>
* StringUtils.unwrap(null, null) = null
* StringUtils.unwrap(null, '\0') = null
* StringUtils.unwrap(null, '1') = null
* StringUtils.unwrap("a", 'a') = "a"
* StringUtils.unwrap("aa", 'a') = ""
* StringUtils.unwrap("\'abc\'", '\'') = "abc"
* StringUtils.unwrap("AABabcBAA", 'A') = "ABabcBA"
* StringUtils.unwrap("A", '#') = "A"
* StringUtils.unwrap("#A", '#') = "#A"
* StringUtils.unwrap("A#", '#') = "A#"
* </pre>
*
* @param str
* the String to be unwrapped, can be null
* @param wrapChar
* the character used to unwrap
* @return unwrapped String or the original string
* if it is not quoted properly with the wrapChar
* @since 3.6
*/
public static String unwrap(final String str, final char wrapChar) {
if (isEmpty(str) || wrapChar == CharUtils.NUL || str.length() == 1) {
return str;
}
if (str.charAt(0) == wrapChar && str.charAt(str.length() - 1) == wrapChar) {
final int startIndex = 0;
final int endIndex = str.length() - 1;
return str.substring(startIndex + 1, endIndex);
}
return str;
}
/**
* <p>
* Unwraps a given string from anther string.
* </p>
*
* <pre>
* StringUtils.unwrap(null, null) = null
* StringUtils.unwrap(null, "") = null
* StringUtils.unwrap(null, "1") = null
* StringUtils.unwrap("a", "a") = "a"
* StringUtils.unwrap("aa", "a") = ""
* StringUtils.unwrap("\'abc\'", "\'") = "abc"
* StringUtils.unwrap("\"abc\"", "\"") = "abc"
* StringUtils.unwrap("AABabcBAA", "AA") = "BabcB"
* StringUtils.unwrap("A", "#") = "A"
* StringUtils.unwrap("#A", "#") = "#A"
* StringUtils.unwrap("A#", "#") = "A#"
* </pre>
*
* @param str
* the String to be unwrapped, can be null
* @param wrapToken
* the String used to unwrap
* @return unwrapped String or the original string
* if it is not quoted properly with the wrapToken
* @since 3.6
*/
public static String unwrap(final String str, final String wrapToken) {
if (isEmpty(str) || isEmpty(wrapToken) || str.length() == 1) {
return str;
}
if (startsWith(str, wrapToken) && endsWith(str, wrapToken)) {
final int startIndex = str.indexOf(wrapToken);
final int endIndex = str.lastIndexOf(wrapToken);
final int wrapLength = wrapToken.length();
if (startIndex != -1 && endIndex != -1) {
return str.substring(startIndex + wrapLength, endIndex);
}
}
return str;
}
// Case conversion
//-----------------------------------------------------------------------
/**
* <p>Converts a String to upper case as per {@link String#toUpperCase()}.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.upperCase(null) = null
* StringUtils.upperCase("") = ""
* StringUtils.upperCase("aBc") = "ABC"
* </pre>
*
* <p><strong>Note:</strong> As described in the documentation for {@link String#toUpperCase()},
* the result of this method is affected by the current locale.
* For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}
* should be used with a specific locale (e.g. {@link Locale#ENGLISH}).</p>
*
* @param str the String to upper case, may be null
* @return the upper cased String, {@code null} if null String input
*/
public static String upperCase(final String str) {
if (str == null) {
return null;
}
return str.toUpperCase();
}
/**
* <p>Converts a String to upper case as per {@link String#toUpperCase(Locale)}.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.upperCase(null, Locale.ENGLISH) = null
* StringUtils.upperCase("", Locale.ENGLISH) = ""
* StringUtils.upperCase("aBc", Locale.ENGLISH) = "ABC"
* </pre>
*
* @param str the String to upper case, may be null
* @param locale the locale that defines the case transformation rules, must not be null
* @return the upper cased String, {@code null} if null String input
* @since 2.5
*/
public static String upperCase(final String str, final Locale locale) {
if (str == null) {
return null;
}
return str.toUpperCase(locale);
}
/**
* Returns the string representation of the {@code char} array or null.
*
* @param value the character array.
* @return a String or null
* @see String#valueOf(char[])
* @since 3.9
*/
public static String valueOf(final char[] value) {
return value == null ? null : String.valueOf(value);
}
/**
* <p>
* Wraps a string with a char.
* </p>
*
* <pre>
* StringUtils.wrap(null, *) = null
* StringUtils.wrap("", *) = ""
* StringUtils.wrap("ab", '\0') = "ab"
* StringUtils.wrap("ab", 'x') = "xabx"
* StringUtils.wrap("ab", '\'') = "'ab'"
* StringUtils.wrap("\"ab\"", '\"') = "\"\"ab\"\""
* </pre>
*
* @param str
* the string to be wrapped, may be {@code null}
* @param wrapWith
* the char that will wrap {@code str}
* @return the wrapped string, or {@code null} if {@code str==null}
* @since 3.4
*/
public static String wrap(final String str, final char wrapWith) {
if (isEmpty(str) || wrapWith == CharUtils.NUL) {
return str;
}
return wrapWith + str + wrapWith;
}
/**
* <p>
* Wraps a String with another String.
* </p>
*
* <p>
* A {@code null} input String returns {@code null}.
* </p>
*
* <pre>
* StringUtils.wrap(null, *) = null
* StringUtils.wrap("", *) = ""
* StringUtils.wrap("ab", null) = "ab"
* StringUtils.wrap("ab", "x") = "xabx"
* StringUtils.wrap("ab", "\"") = "\"ab\""
* StringUtils.wrap("\"ab\"", "\"") = "\"\"ab\"\""
* StringUtils.wrap("ab", "'") = "'ab'"
* StringUtils.wrap("'abcd'", "'") = "''abcd''"
* StringUtils.wrap("\"abcd\"", "'") = "'\"abcd\"'"
* StringUtils.wrap("'abcd'", "\"") = "\"'abcd'\""
* </pre>
*
* @param str
* the String to be wrapper, may be null
* @param wrapWith
* the String that will wrap str
* @return wrapped String, {@code null} if null String input
* @since 3.4
*/
public static String wrap(final String str, final String wrapWith) {
if (isEmpty(str) || isEmpty(wrapWith)) {
return str;
}
return wrapWith.concat(str).concat(wrapWith);
}
/**
* <p>
* Wraps a string with a char if that char is missing from the start or end of the given string.
* </p>
*
* <p>A new {@code String} will not be created if {@code str} is already wrapped.</p>
*
* <pre>
* StringUtils.wrapIfMissing(null, *) = null
* StringUtils.wrapIfMissing("", *) = ""
* StringUtils.wrapIfMissing("ab", '\0') = "ab"
* StringUtils.wrapIfMissing("ab", 'x') = "xabx"
* StringUtils.wrapIfMissing("ab", '\'') = "'ab'"
* StringUtils.wrapIfMissing("\"ab\"", '\"') = "\"ab\""
* StringUtils.wrapIfMissing("/", '/') = "/"
* StringUtils.wrapIfMissing("a/b/c", '/') = "/a/b/c/"
* StringUtils.wrapIfMissing("/a/b/c", '/') = "/a/b/c/"
* StringUtils.wrapIfMissing("a/b/c/", '/') = "/a/b/c/"
* </pre>
*
* @param str
* the string to be wrapped, may be {@code null}
* @param wrapWith
* the char that will wrap {@code str}
* @return the wrapped string, or {@code null} if {@code str==null}
* @since 3.5
*/
public static String wrapIfMissing(final String str, final char wrapWith) {
if (isEmpty(str) || wrapWith == CharUtils.NUL) {
return str;
}
final boolean wrapStart = str.charAt(0) != wrapWith;
final boolean wrapEnd = str.charAt(str.length() - 1) != wrapWith;
if (!wrapStart && !wrapEnd) {
return str;
}
final StringBuilder builder = new StringBuilder(str.length() + 2);
if (wrapStart) {
builder.append(wrapWith);
}
builder.append(str);
if (wrapEnd) {
builder.append(wrapWith);
}
return builder.toString();
}
/**
* <p>
* Wraps a string with a string if that string is missing from the start or end of the given string.
* </p>
*
* <p>A new {@code String} will not be created if {@code str} is already wrapped.</p>
*
* <pre>
* StringUtils.wrapIfMissing(null, *) = null
* StringUtils.wrapIfMissing("", *) = ""
* StringUtils.wrapIfMissing("ab", null) = "ab"
* StringUtils.wrapIfMissing("ab", "x") = "xabx"
* StringUtils.wrapIfMissing("ab", "\"") = "\"ab\""
* StringUtils.wrapIfMissing("\"ab\"", "\"") = "\"ab\""
* StringUtils.wrapIfMissing("ab", "'") = "'ab'"
* StringUtils.wrapIfMissing("'abcd'", "'") = "'abcd'"
* StringUtils.wrapIfMissing("\"abcd\"", "'") = "'\"abcd\"'"
* StringUtils.wrapIfMissing("'abcd'", "\"") = "\"'abcd'\""
* StringUtils.wrapIfMissing("/", "/") = "/"
* StringUtils.wrapIfMissing("a/b/c", "/") = "/a/b/c/"
* StringUtils.wrapIfMissing("/a/b/c", "/") = "/a/b/c/"
* StringUtils.wrapIfMissing("a/b/c/", "/") = "/a/b/c/"
* </pre>
*
* @param str
* the string to be wrapped, may be {@code null}
* @param wrapWith
* the string that will wrap {@code str}
* @return the wrapped string, or {@code null} if {@code str==null}
* @since 3.5
*/
public static String wrapIfMissing(final String str, final String wrapWith) {
if (isEmpty(str) || isEmpty(wrapWith)) {
return str;
}
final boolean wrapStart = !str.startsWith(wrapWith);
final boolean wrapEnd = !str.endsWith(wrapWith);
if (!wrapStart && !wrapEnd) {
return str;
}
final StringBuilder builder = new StringBuilder(str.length() + wrapWith.length() + wrapWith.length());
if (wrapStart) {
builder.append(wrapWith);
}
builder.append(str);
if (wrapEnd) {
builder.append(wrapWith);
}
return builder.toString();
}
/**
* <p>{@code StringUtils} instances should NOT be constructed in
* standard programming. Instead, the class should be used as
* {@code StringUtils.trim(" foo ");}.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean
* instance to operate.</p>
*/
public StringUtils() {
super();
}
}
|
Fix some spelling and grammar issues in the StringUtils Javadoc.
|
src/main/java/org/apache/commons/lang3/StringUtils.java
|
Fix some spelling and grammar issues in the StringUtils Javadoc.
|
<ide><path>rc/main/java/org/apache/commons/lang3/StringUtils.java
<ide> * <li><b>Trim/Strip</b>
<ide> * - removes leading and trailing whitespace</li>
<ide> * <li><b>Equals/Compare</b>
<del> * - compares two strings null-safe</li>
<add> * - compares two strings in a null-safe manner</li>
<ide> * <li><b>startsWith</b>
<del> * - check if a String starts with a prefix null-safe</li>
<add> * - check if a String starts with a prefix in a null-safe manner</li>
<ide> * <li><b>endsWith</b>
<del> * - check if a String ends with a suffix null-safe</li>
<add> * - check if a String ends with a suffix in a null-safe manner</li>
<ide> * <li><b>IndexOf/LastIndexOf/Contains</b>
<ide> * - null-safe index-of checks
<ide> * <li><b>IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut</b>
<ide> * - index-of any of a set of Strings</li>
<ide> * <li><b>ContainsOnly/ContainsNone/ContainsAny</b>
<del> * - does String contains only/none/any of these characters</li>
<add> * - checks if String contains only/none/any of these characters</li>
<ide> * <li><b>Substring/Left/Right/Mid</b>
<ide> * - null-safe substring extractions</li>
<ide> * <li><b>SubstringBefore/SubstringAfter/SubstringBetween</b>
<ide> * <li><b>Reverse/ReverseDelimited</b>
<ide> * - reverses a String</li>
<ide> * <li><b>Abbreviate</b>
<del> * - abbreviates a string using ellipsis or another given String</li>
<add> * - abbreviates a string using ellipses or another given String</li>
<ide> * <li><b>Difference</b>
<ide> * - compares Strings and reports on their differences</li>
<ide> * <li><b>LevenshteinDistance</b>
<ide> * {@code NullPointerException} should be considered a bug in
<ide> * {@code StringUtils}.</p>
<ide> *
<del> * <p>Methods in this class give sample code to explain their operation.
<add> * <p>Methods in this class include sample code in their Javadoc comments to explain their operation.
<ide> * The symbol {@code *} is used to indicate any input including {@code null}.</p>
<ide> *
<ide> * <p>#ThreadSafe#</p>
<ide> * <p>Centers a String in a larger String of size {@code size}
<ide> * using the space character (' ').</p>
<ide> *
<del> * <p>If the size is less than the String length, the String is returned.
<add> * <p>If the size is less than the String length, the original String is returned.
<ide> * A {@code null} String returns {@code null}.
<ide> * A negative size is treated as zero.</p>
<ide> *
<ide> }
<ide>
<ide> /**
<del> * <p>Find the latest index of any of a set of potential substrings.</p>
<add> * <p>Find the latest index of any substring in a set of potential substrings.</p>
<ide> *
<ide> * <p>A {@code null} CharSequence will return {@code -1}.
<ide> * A {@code null} search array will return {@code -1}.
<ide> /**
<ide> * <p>Replaces a String with another String inside a larger String,
<ide> * for the first {@code max} values of the search String,
<del> * case sensitively/insensisitively based on {@code ignoreCase} value.</p>
<add> * case sensitively/insensitively based on {@code ignoreCase} value.</p>
<ide> *
<ide> * <p>A {@code null} reference passed to this method is a no-op.</p>
<ide> *
|
|
Java
|
apache-2.0
|
86eca4966f89e8faa5cd29b18bb9a7536d55274a
| 0 |
powertac/powertac-core
|
/*
* Copyright (c) 2011 by the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.powertac.common;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.powertac.common.msg.CustomerBootstrapData;
import org.powertac.common.msg.SimEnd;
import org.powertac.common.msg.SimPause;
import org.powertac.common.msg.SimResume;
import org.powertac.common.msg.SimStart;
import org.powertac.common.spring.SpringApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;
import org.springframework.util.SystemPropertyUtils;
import com.thoughtworks.xstream.XStream;
@Service
public class XMLMessageConverter
{
private static final Logger log = LogManager.getLogger(XMLMessageConverter.class);
@SuppressWarnings("rawtypes")
private Class[] commandClasses = { CustomerBootstrapData.class, SimEnd.class,
SimStart.class, SimPause.class, SimResume.class };
private XStream xstream;
// inject context here so that it would be initialized before this class
// @PostConstruct method get called and use the singleton.
@Autowired
private SpringApplicationContext context;
@SuppressWarnings("rawtypes")
@PostConstruct
public void afterPropertiesSet() {
xstream = new XStream();
try {
List<Class> classes = findMyTypes("org.powertac.common");
for (Class clazz : classes) {
log.info("processing class " + clazz.getName());
xstream.processAnnotations(clazz);
}
} catch (IOException e) {
log.error("failed to process annotation", e);
} catch (ClassNotFoundException e) {
log.error("failed to process annotation", e);
}
for (Class commandClazz : commandClasses) {
xstream.processAnnotations(commandClazz);
}
xstream.autodetectAnnotations(true);
xstream.aliasSystemAttribute(null, "class");
}
public String toXML(Object message) {
return xstream.toXML(message);
}
public Object fromXML(String xml) {
return xstream.fromXML(xml);
}
@SuppressWarnings("rawtypes")
private List<Class> findMyTypes(String basePackage) throws IOException, ClassNotFoundException
{
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
List<Class> candidates = new ArrayList<Class>();
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
resolveBasePackage(basePackage) + "/" + "**/*.class";
Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
for (Resource resource : resources) {
if (resource.isReadable()) {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
candidates.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
}
}
return candidates;
}
private String resolveBasePackage(String basePackage) {
return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage));
}
}
|
src/main/java/org/powertac/common/XMLMessageConverter.java
|
/*
* Copyright (c) 2011 by the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.powertac.common;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.powertac.common.msg.CustomerBootstrapData;
import org.powertac.common.msg.SimEnd;
import org.powertac.common.msg.SimPause;
import org.powertac.common.msg.SimResume;
import org.powertac.common.msg.SimStart;
import org.powertac.common.spring.SpringApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;
import org.springframework.util.SystemPropertyUtils;
import com.thoughtworks.xstream.XStream;
@Service
public class XMLMessageConverter
{
private static final Logger log = LogManager.getLogger(XMLMessageConverter.class);
@SuppressWarnings("rawtypes")
private Class[] commandClasses = { CustomerBootstrapData.class, SimEnd.class,
SimStart.class, SimPause.class, SimResume.class };
private XStream xstream;
// inject context here so that it would be initialized before this class
// @PostConstruct method get called and use the singleton.
@SuppressWarnings("unused")
@Autowired
private SpringApplicationContext context;
@SuppressWarnings("rawtypes")
@PostConstruct
public void afterPropertiesSet() {
xstream = new XStream();
try {
List<Class> classes = findMyTypes("org.powertac.common");
for (Class clazz : classes) {
log.info("processing class " + clazz.getName());
xstream.processAnnotations(clazz);
}
} catch (IOException e) {
log.error("failed to process annotation", e);
} catch (ClassNotFoundException e) {
log.error("failed to process annotation", e);
}
for (Class commandClazz : commandClasses) {
xstream.processAnnotations(commandClazz);
}
xstream.autodetectAnnotations(true);
xstream.aliasSystemAttribute(null, "class");
}
public String toXML(Object message) {
return xstream.toXML(message);
}
public Object fromXML(String xml) {
return xstream.fromXML(xml);
}
@SuppressWarnings("rawtypes")
private List<Class> findMyTypes(String basePackage) throws IOException, ClassNotFoundException
{
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
List<Class> candidates = new ArrayList<Class>();
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
resolveBasePackage(basePackage) + "/" + "**/*.class";
Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
for (Resource resource : resources) {
if (resource.isReadable()) {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
candidates.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
}
}
return candidates;
}
private String resolveBasePackage(String basePackage) {
return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage));
}
}
|
remove unused annotation
|
src/main/java/org/powertac/common/XMLMessageConverter.java
|
remove unused annotation
|
<ide><path>rc/main/java/org/powertac/common/XMLMessageConverter.java
<ide>
<ide> // inject context here so that it would be initialized before this class
<ide> // @PostConstruct method get called and use the singleton.
<del> @SuppressWarnings("unused")
<ide> @Autowired
<ide> private SpringApplicationContext context;
<ide>
|
|
Java
|
apache-2.0
|
9e62c4ccfb5d165aa21199face500fd65ce787aa
| 0 |
hank/litecoinj-new
|
/**
* Copyright 2011 Google 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.google.litecoin.core;
import com.google.litecoin.script.Script;
import com.google.litecoin.script.ScriptBuilder;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import static com.google.litecoin.core.Utils.doubleDigest;
import static com.google.litecoin.core.Utils.doubleDigestTwoBuffers;
import static com.google.litecoin.core.Utils.scryptDigest;
/**
* <p>A block is a group of transactions, and is one of the fundamental data structures of the Bitcoin system.
* It records a set of {@link Transaction}s together with some data that links it into a place in the global block
* chain, and proves that a difficult calculation was done over its contents. See
* <a href="http://www.litecoin.org/litecoin.pdf">the Bitcoin technical paper</a> for
* more detail on blocks. <p/>
*
* To get a block, you can either build one from the raw bytes you can get from another implementation, or request one
* specifically using {@link Peer#getBlock(Sha256Hash)}, or grab one from a downloaded {@link BlockChain}.
*/
public class Block extends Message {
private static final Logger log = LoggerFactory.getLogger(Block.class);
private static final long serialVersionUID = 2738848929966035281L;
/** How many bytes are required to represent a block header WITHOUT the trailing 00 length byte. */
public static final int HEADER_SIZE = 80;
static final long ALLOWED_TIME_DRIFT = 2 * 60 * 60; // Same value as official client.
/**
* A constant shared by the entire network: how large in bytes a block is allowed to be. One day we may have to
* upgrade everyone to change this, so Bitcoin can continue to grow. For now it exists as an anti-DoS measure to
* avoid somebody creating a titanically huge but valid block and forcing everyone to download/store it forever.
*/
public static final int MAX_BLOCK_SIZE = 1 * 1000 * 1000;
/**
* A "sigop" is a signature verification operation. Because they're expensive we also impose a separate limit on
* the number in a block to prevent somebody mining a huge block that has way more sigops than normal, so is very
* expensive/slow to verify.
*/
public static final int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE / 50;
/** A value for difficultyTarget (nBits) that allows half of all possible hash solutions. Used in unit testing. */
public static final long EASIEST_DIFFICULTY_TARGET = 0x207fFFFFL;
// Fields defined as part of the protocol format.
private long version;
private Sha256Hash prevBlockHash;
private Sha256Hash merkleRoot;
private long time;
private long difficultyTarget; // "nBits"
private long nonce;
/** If null, it means this object holds only the headers. */
List<Transaction> transactions;
/** Stores the hash of the block. If null, getHash() will recalculate it. */
private transient Sha256Hash hash;
private transient Sha256Hash scryptHash;
private transient boolean headerParsed;
private transient boolean transactionsParsed;
private transient boolean headerBytesValid;
private transient boolean transactionBytesValid;
// Blocks can be encoded in a way that will use more bytes than is optimal (due to VarInts having multiple encodings)
// MAX_BLOCK_SIZE must be compared to the optimal encoding, not the actual encoding, so when parsing, we keep track
// of the size of the ideal encoding in addition to the actual message size (which Message needs)
private transient int optimalEncodingMessageSize;
/** Special case constructor, used for the genesis node, cloneAsHeader and unit tests. */
Block(NetworkParameters params) {
super(params);
// Set up a few basic things. We are not complete after this though.
version = 1;
difficultyTarget = 0x1d07fff8L;
time = System.currentTimeMillis() / 1000;
prevBlockHash = Sha256Hash.ZERO_HASH;
length = 80;
}
/** Constructs a block object from the Bitcoin wire format. */
public Block(NetworkParameters params, byte[] payloadBytes) throws ProtocolException {
super(params, payloadBytes, 0, false, false, payloadBytes.length);
}
/**
* Contruct a block object from the Bitcoin wire format.
* @param params NetworkParameters object.
* @param parseLazy Whether to perform a full parse immediately or delay until a read is requested.
* @param parseRetain Whether to retain the backing byte array for quick reserialization.
* If true and the backing byte array is invalidated due to modification of a field then
* the cached bytes may be repopulated and retained if the message is serialized again in the future.
* @param length The length of message if known. Usually this is provided when deserializing of the wire
* as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH
* @throws ProtocolException
*/
public Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length)
throws ProtocolException {
super(params, payloadBytes, 0, parseLazy, parseRetain, length);
}
/**
* Construct a block initialized with all the given fields.
* @param params Which network the block is for.
* @param version This should usually be set to 1 or 2, depending on if the height is in the coinbase input.
* @param prevBlockHash Reference to previous block in the chain or {@link Sha256Hash#ZERO_HASH} if genesis.
* @param merkleRoot The root of the merkle tree formed by the transactions.
* @param time UNIX time when the block was mined.
* @param difficultyTarget Number which this block hashes lower than.
* @param nonce Arbitrary number to make the block hash lower than the target.
* @param transactions List of transactions including the coinbase.
*/
public Block(NetworkParameters params, long version, Sha256Hash prevBlockHash, Sha256Hash merkleRoot, long time,
long difficultyTarget, long nonce, List<Transaction> transactions) {
super(params);
this.version = version;
this.prevBlockHash = prevBlockHash;
this.merkleRoot = merkleRoot;
this.time = time;
this.difficultyTarget = difficultyTarget;
this.nonce = nonce;
this.transactions = new LinkedList<Transaction>();
this.transactions.addAll(transactions);
}
/**
* <p>A utility method that calculates how much new Bitcoin would be created by the block at the given height.
* The inflation of Bitcoin is predictable and drops roughly every 4 years (210,000 blocks). At the dawn of
* the system it was 50 coins per block, in late 2012 it went to 25 coins per block, and so on. The size of
* a coinbase transaction is inflation plus fees.</p>
*
* <p>The half-life is controlled by {@link com.google.litecoin.core.NetworkParameters#getSubsidyDecreaseBlockCount()}.
* </p>
*/
public BigInteger getBlockInflation(int height) {
return Utils.toNanoCoins(50, 0).shiftRight(height / params.getSubsidyDecreaseBlockCount());
}
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
ois.defaultReadObject();
// This code is not actually necessary, as transient fields are initialized to the default value which is in
// this case null. However it clears out a FindBugs warning and makes it explicit what we're doing.
hash = null;
}
private void parseHeader() throws ProtocolException {
if (headerParsed)
return;
cursor = offset;
version = readUint32();
prevBlockHash = readHash();
merkleRoot = readHash();
time = readUint32();
difficultyTarget = readUint32();
nonce = readUint32();
hash = new Sha256Hash(Utils.reverseBytes(Utils.doubleDigest(bytes, offset, cursor)));
headerParsed = true;
headerBytesValid = parseRetain;
}
private void parseTransactions() throws ProtocolException {
if (transactionsParsed)
return;
cursor = offset + HEADER_SIZE;
optimalEncodingMessageSize = HEADER_SIZE;
if (bytes.length == cursor) {
// This message is just a header, it has no transactions.
transactionsParsed = true;
transactionBytesValid = false;
return;
}
int numTransactions = (int) readVarInt();
optimalEncodingMessageSize += VarInt.sizeOf(numTransactions);
transactions = new ArrayList<Transaction>(numTransactions);
for (int i = 0; i < numTransactions; i++) {
Transaction tx = new Transaction(params, bytes, cursor, this, parseLazy, parseRetain, UNKNOWN_LENGTH);
// Label the transaction as coming from the P2P network, so code that cares where we first saw it knows.
tx.getConfidence().setSource(TransactionConfidence.Source.NETWORK);
transactions.add(tx);
cursor += tx.getMessageSize();
optimalEncodingMessageSize += tx.getOptimalEncodingMessageSize();
}
// No need to set length here. If length was not provided then it should be set at the end of parseLight().
// If this is a genuine lazy parse then length must have been provided to the constructor.
transactionsParsed = true;
transactionBytesValid = parseRetain;
}
void parse() throws ProtocolException {
parseHeader();
parseTransactions();
length = cursor - offset;
}
public int getOptimalEncodingMessageSize() {
if (optimalEncodingMessageSize != 0)
return optimalEncodingMessageSize;
maybeParseTransactions();
if (optimalEncodingMessageSize != 0)
return optimalEncodingMessageSize;
optimalEncodingMessageSize = getMessageSize();
return optimalEncodingMessageSize;
}
protected void parseLite() throws ProtocolException {
// Ignore the header since it has fixed length. If length is not provided we will have to
// invoke a light parse of transactions to calculate the length.
if (length == UNKNOWN_LENGTH) {
Preconditions.checkState(parseLazy,
"Performing lite parse of block transaction as block was initialised from byte array " +
"without providing length. This should never need to happen.");
parseTransactions();
length = cursor - offset;
} else {
transactionBytesValid = !transactionsParsed || parseRetain && length > HEADER_SIZE;
}
headerBytesValid = !headerParsed || parseRetain && length >= HEADER_SIZE;
}
/*
* Block uses some special handling for lazy parsing and retention of cached bytes. Parsing and serializing the
* block header and the transaction list are both non-trivial so there are good efficiency gains to be had by
* separating them. There are many cases where a user may need to access or change one or the other but not both.
*
* With this in mind we ignore the inherited checkParse() and unCache() methods and implement a separate version
* of them for both header and transactions.
*
* Serializing methods are also handled in their own way. Whilst they deal with separate parts of the block structure
* there are some interdependencies. For example altering a tx requires invalidating the Merkle root and therefore
* the cached header bytes.
*/
private void maybeParseHeader() {
if (headerParsed || bytes == null)
return;
try {
parseHeader();
if (!(headerBytesValid || transactionBytesValid))
bytes = null;
} catch (ProtocolException e) {
throw new LazyParseException(
"ProtocolException caught during lazy parse. For safe access to fields call ensureParsed before attempting read or write access",
e);
}
}
private void maybeParseTransactions() {
if (transactionsParsed || bytes == null)
return;
try {
parseTransactions();
if (!parseRetain) {
transactionBytesValid = false;
if (headerParsed)
bytes = null;
}
} catch (ProtocolException e) {
throw new LazyParseException(
"ProtocolException caught during lazy parse. For safe access to fields call ensureParsed before attempting read or write access",
e);
}
}
/**
* Ensure the object is parsed if needed. This should be called in every getter before returning a value. If the
* lazy parse flag is not set this is a method returns immediately.
*/
protected void maybeParse() {
throw new LazyParseException(
"checkParse() should never be called on a Block. Instead use checkParseHeader() and checkParseTransactions()");
}
/**
* In lazy parsing mode access to getters and setters may throw an unchecked LazyParseException. If guaranteed
* safe access is required this method will force parsing to occur immediately thus ensuring LazyParseExeption will
* never be thrown from this Message. If the Message contains child messages (e.g. a Block containing Transaction
* messages) this will not force child messages to parse.
*
* This method ensures parsing of both headers and transactions.
*
* @throws ProtocolException
*/
public void ensureParsed() throws ProtocolException {
try {
maybeParseHeader();
maybeParseTransactions();
} catch (LazyParseException e) {
if (e.getCause() instanceof ProtocolException)
throw (ProtocolException) e.getCause();
throw new ProtocolException(e);
}
}
/**
* In lazy parsing mode access to getters and setters may throw an unchecked LazyParseException. If guaranteed
* safe access is required this method will force parsing to occur immediately thus ensuring LazyParseExeption
* will never be thrown from this Message. If the Message contains child messages (e.g. a Block containing
* Transaction messages) this will not force child messages to parse.
*
* This method ensures parsing of headers only.
*
* @throws ProtocolException
*/
public void ensureParsedHeader() throws ProtocolException {
try {
maybeParseHeader();
} catch (LazyParseException e) {
if (e.getCause() instanceof ProtocolException)
throw (ProtocolException) e.getCause();
throw new ProtocolException(e);
}
}
/**
* In lazy parsing mode access to getters and setters may throw an unchecked LazyParseException. If guaranteed
* safe access is required this method will force parsing to occur immediately thus ensuring LazyParseExeption will
* never be thrown from this Message. If the Message contains child messages (e.g. a Block containing Transaction
* messages) this will not force child messages to parse.
*
* This method ensures parsing of transactions only.
*
* @throws ProtocolException
*/
public void ensureParsedTransactions() throws ProtocolException {
try {
maybeParseTransactions();
} catch (LazyParseException e) {
if (e.getCause() instanceof ProtocolException)
throw (ProtocolException) e.getCause();
throw new ProtocolException(e);
}
}
// default for testing
void writeHeader(OutputStream stream) throws IOException {
// try for cached write first
if (headerBytesValid && bytes != null && bytes.length >= offset + HEADER_SIZE) {
stream.write(bytes, offset, HEADER_SIZE);
return;
}
// fall back to manual write
maybeParseHeader();
Utils.uint32ToByteStreamLE(version, stream);
stream.write(Utils.reverseBytes(prevBlockHash.getBytes()));
stream.write(Utils.reverseBytes(getMerkleRoot().getBytes()));
Utils.uint32ToByteStreamLE(time, stream);
Utils.uint32ToByteStreamLE(difficultyTarget, stream);
Utils.uint32ToByteStreamLE(nonce, stream);
}
private void writeTransactions(OutputStream stream) throws IOException {
// check for no transaction conditions first
// must be a more efficient way to do this but I'm tired atm.
if (transactions == null && transactionsParsed) {
return;
}
// confirmed we must have transactions either cached or as objects.
if (transactionBytesValid && bytes != null && bytes.length >= offset + length) {
stream.write(bytes, offset + HEADER_SIZE, length - HEADER_SIZE);
return;
}
if (transactions != null) {
stream.write(new VarInt(transactions.size()).encode());
for (Transaction tx : transactions) {
tx.bitcoinSerialize(stream);
}
}
}
/**
* Special handling to check if we have a valid byte array for both header
* and transactions
*
* @throws IOException
*/
public byte[] bitcoinSerialize() {
// we have completely cached byte array.
if (headerBytesValid && transactionBytesValid) {
Preconditions.checkNotNull(bytes, "Bytes should never be null if headerBytesValid && transactionBytesValid");
if (length == bytes.length) {
return bytes;
} else {
// byte array is offset so copy out the correct range.
byte[] buf = new byte[length];
System.arraycopy(bytes, offset, buf, 0, length);
return buf;
}
}
// At least one of the two cacheable components is invalid
// so fall back to stream write since we can't be sure of the length.
ByteArrayOutputStream stream = new UnsafeByteArrayOutputStream(length == UNKNOWN_LENGTH ? HEADER_SIZE + guessTransactionsLength() : length);
try {
writeHeader(stream);
writeTransactions(stream);
} catch (IOException e) {
// Cannot happen, we are serializing to a memory stream.
}
return stream.toByteArray();
}
@Override
protected void bitcoinSerializeToStream(OutputStream stream) throws IOException {
writeHeader(stream);
// We may only have enough data to write the header.
writeTransactions(stream);
}
/**
* Provides a reasonable guess at the byte length of the transactions part of the block.
* The returned value will be accurate in 99% of cases and in those cases where not will probably slightly
* oversize.
*
* This is used to preallocate the underlying byte array for a ByteArrayOutputStream. If the size is under the
* real value the only penalty is resizing of the underlying byte array.
*/
private int guessTransactionsLength() {
if (transactionBytesValid)
return bytes.length - HEADER_SIZE;
if (transactions == null)
return 0;
int len = VarInt.sizeOf(transactions.size());
for (Transaction tx : transactions) {
// 255 is just a guess at an average tx length
len += tx.length == UNKNOWN_LENGTH ? 255 : tx.length;
}
return len;
}
protected void unCache() {
// Since we have alternate uncache methods to use internally this will only ever be called by a child
// transaction so we only need to invalidate that part of the cache.
unCacheTransactions();
}
private void unCacheHeader() {
maybeParseHeader();
headerBytesValid = false;
if (!transactionBytesValid)
bytes = null;
hash = null;
checksum = null;
}
private void unCacheTransactions() {
maybeParseTransactions();
transactionBytesValid = false;
if (!headerBytesValid)
bytes = null;
// Current implementation has to uncache headers as well as any change to a tx will alter the merkle root. In
// future we can go more granular and cache merkle root separately so rest of the header does not need to be
// rewritten.
unCacheHeader();
// Clear merkleRoot last as it may end up being parsed during unCacheHeader().
merkleRoot = null;
}
/**
* Calculates the block hash by serializing the block and hashing the
* resulting bytes.
*/
private Sha256Hash calculateHash() {
try {
ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(HEADER_SIZE);
writeHeader(bos);
return new Sha256Hash(Utils.reverseBytes(doubleDigest(bos.toByteArray())));
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
}
private Sha256Hash calculateScryptHash() {
try {
ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(HEADER_SIZE);
writeHeader(bos);
return new Sha256Hash(Utils.reverseBytes(scryptDigest(bos.toByteArray())));
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
}
/**
* Returns the hash of the block (which for a valid, solved block should be below the target) in the form seen on
* the block explorer. If you call this on block 1 in the production chain
* you will get "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048".
*/
public String getHashAsString() {
return getHash().toString();
}
public String getScryptHashAsString() {
return getScryptHash().toString();
}
/**
* Returns the hash of the block (which for a valid, solved block should be
* below the target). Big endian.
*/
public Sha256Hash getHash() {
if (hash == null)
hash = calculateHash();
return hash;
}
public Sha256Hash getScryptHash() {
if (hash == null)
hash = calculateScryptHash();
return hash;
}
/**
* The number that is one greater than the largest representable SHA-256
* hash.
*/
static private BigInteger LARGEST_HASH = BigInteger.ONE.shiftLeft(256);
/**
* Returns the work represented by this block.<p>
*
* Work is defined as the number of tries needed to solve a block in the
* average case. Consider a difficulty target that covers 5% of all possible
* hash values. Then the work of the block will be 20. As the target gets
* lower, the amount of work goes up.
*/
public BigInteger getWork() throws VerificationException {
BigInteger target = getDifficultyTargetAsInteger();
return LARGEST_HASH.divide(target.add(BigInteger.ONE));
}
/** Returns a copy of the block, but without any transactions. */
public Block cloneAsHeader() {
maybeParseHeader();
Block block = new Block(params);
block.nonce = nonce;
block.prevBlockHash = prevBlockHash.duplicate();
block.merkleRoot = getMerkleRoot().duplicate();
block.version = version;
block.time = time;
block.difficultyTarget = difficultyTarget;
block.transactions = null;
block.hash = getScryptHash().duplicate();
return block;
}
/**
* Returns a multi-line string containing a description of the contents of
* the block. Use for debugging purposes only.
*/
@Override
public String toString() {
StringBuilder s = new StringBuilder("v");
s.append(version);
s.append(" block: \n");
s.append(" previous block: ");
s.append(getPrevBlockHash());
s.append("\n");
s.append(" merkle root: ");
s.append(getMerkleRoot());
s.append("\n");
s.append(" time: [");
s.append(time);
s.append("] ");
s.append(new Date(time * 1000));
s.append("\n");
s.append(" difficulty target (nBits): ");
s.append(difficultyTarget);
s.append("\n");
s.append(" nonce: ");
s.append(nonce);
s.append("\n");
if (transactions != null && transactions.size() > 0) {
s.append(" with ").append(transactions.size()).append(" transaction(s):\n");
for (Transaction tx : transactions) {
s.append(tx.toString());
}
}
return s.toString();
}
/**
* <p>Finds a value of nonce that makes the blocks hash lower than the difficulty target. This is called mining, but
* solve() is far too slow to do real mining with. It exists only for unit testing purposes.
*
* <p>This can loop forever if a solution cannot be found solely by incrementing nonce. It doesn't change
* extraNonce.</p>
*/
public void solve() {
maybeParseHeader();
while (true) {
try {
// Is our proof of work valid yet?
if (checkProofOfWork(false))
return;
// No, so increment the nonce and try again.
setNonce(getNonce() + 1);
} catch (VerificationException e) {
throw new RuntimeException(e); // Cannot happen.
}
}
}
/**
* Returns the difficulty target as a 256 bit value that can be compared to a SHA-256 hash. Inside a block the
* target is represented using a compact form. If this form decodes to a value that is out of bounds, an exception
* is thrown.
*/
public BigInteger getDifficultyTargetAsInteger() throws VerificationException {
maybeParseHeader();
BigInteger target = Utils.decodeCompactBits(difficultyTarget);
if (target.compareTo(BigInteger.ZERO) <= 0 || target.compareTo(params.proofOfWorkLimit) > 0)
throw new VerificationException("Difficulty target is bad: " + target.toString() + " or " + difficultyTarget);
return target;
}
/** Returns true if the hash of the block is OK (lower than difficulty target). */
private boolean checkProofOfWork(boolean throwException) throws VerificationException {
// This part is key - it is what proves the block was as difficult to make as it claims
// to be. Note however that in the context of this function, the block can claim to be
// as difficult as it wants to be .... if somebody was able to take control of our network
// connection and fork us onto a different chain, they could send us valid blocks with
// ridiculously easy difficulty and this function would accept them.
//
// To prevent this attack from being possible, elsewhere we check that the difficultyTarget
// field is of the right value. This requires us to have the preceeding blocks.
BigInteger target = getDifficultyTargetAsInteger();
BigInteger h = getScryptHash().toBigInteger();
if (h.compareTo(target) > 0) {
// Proof of work check failed!
if (throwException)
throw new VerificationException("Hash is higher than target: " + getScryptHashAsString() + " vs "
+ target.toString(16));
else
return false;
}
return true;
}
private void checkTimestamp() throws VerificationException {
maybeParseHeader();
// Allow injection of a fake clock to allow unit testing.
long currentTime = Utils.now().getTime()/1000;
if (time > currentTime + ALLOWED_TIME_DRIFT)
throw new VerificationException("Block too far in future");
}
private void checkSigOps() throws VerificationException {
// Check there aren't too many signature verifications in the block. This is an anti-DoS measure, see the
// comments for MAX_BLOCK_SIGOPS.
int sigOps = 0;
for (Transaction tx : transactions) {
sigOps += tx.getSigOpCount();
}
if (sigOps > MAX_BLOCK_SIGOPS)
throw new VerificationException("Block had too many Signature Operations");
}
private void checkMerkleRoot() throws VerificationException {
Sha256Hash calculatedRoot = calculateMerkleRoot();
if (!calculatedRoot.equals(merkleRoot)) {
log.error("Merkle tree did not verify");
throw new VerificationException("Merkle hashes do not match: " + calculatedRoot + " vs " + merkleRoot);
}
}
private Sha256Hash calculateMerkleRoot() {
List<byte[]> tree = buildMerkleTree();
return new Sha256Hash(tree.get(tree.size() - 1));
}
private List<byte[]> buildMerkleTree() {
// The Merkle root is based on a tree of hashes calculated from the transactions:
//
// root
// / \
// A B
// / \ / \
// t1 t2 t3 t4
//
// The tree is represented as a list: t1,t2,t3,t4,A,B,root where each
// entry is a hash.
//
// The hashing algorithm is double SHA-256. The leaves are a hash of the serialized contents of the transaction.
// The interior nodes are hashes of the concenation of the two child hashes.
//
// This structure allows the creation of proof that a transaction was included into a block without having to
// provide the full block contents. Instead, you can provide only a Merkle branch. For example to prove tx2 was
// in a block you can just provide tx2, the hash(tx1) and B. Now the other party has everything they need to
// derive the root, which can be checked against the block header. These proofs aren't used right now but
// will be helpful later when we want to download partial block contents.
//
// Note that if the number of transactions is not even the last tx is repeated to make it so (see
// tx3 above). A tree with 5 transactions would look like this:
//
// root
// / \
// 1 5
// / \ / \
// 2 3 4 4
// / \ / \ / \
// t1 t2 t3 t4 t5 t5
maybeParseTransactions();
ArrayList<byte[]> tree = new ArrayList<byte[]>();
// Start by adding all the hashes of the transactions as leaves of the tree.
for (Transaction t : transactions) {
tree.add(t.getHash().getBytes());
}
int levelOffset = 0; // Offset in the list where the currently processed level starts.
// Step through each level, stopping when we reach the root (levelSize == 1).
for (int levelSize = transactions.size(); levelSize > 1; levelSize = (levelSize + 1) / 2) {
// For each pair of nodes on that level:
for (int left = 0; left < levelSize; left += 2) {
// The right hand node can be the same as the left hand, in the case where we don't have enough
// transactions.
int right = Math.min(left + 1, levelSize - 1);
byte[] leftBytes = Utils.reverseBytes(tree.get(levelOffset + left));
byte[] rightBytes = Utils.reverseBytes(tree.get(levelOffset + right));
tree.add(Utils.reverseBytes(doubleDigestTwoBuffers(leftBytes, 0, 32, rightBytes, 0, 32)));
}
// Move to the next level.
levelOffset += levelSize;
}
return tree;
}
private void checkTransactions() throws VerificationException {
// The first transaction in a block must always be a coinbase transaction.
if (!transactions.get(0).isCoinBase())
throw new VerificationException("First tx is not coinbase");
// The rest must not be.
for (int i = 1; i < transactions.size(); i++) {
if (transactions.get(i).isCoinBase())
throw new VerificationException("TX " + i + " is coinbase when it should not be.");
}
}
/**
* Checks the block data to ensure it follows the rules laid out in the network parameters. Specifically,
* throws an exception if the proof of work is invalid, or if the timestamp is too far from what it should be.
* This is <b>not</b> everything that is required for a block to be valid, only what is checkable independent
* of the chain and without a transaction index.
*
* @throws VerificationException
*/
public void verifyHeader() throws VerificationException {
// Prove that this block is OK. It might seem that we can just ignore most of these checks given that the
// network is also verifying the blocks, but we cannot as it'd open us to a variety of obscure attacks.
//
// Firstly we need to ensure this block does in fact represent real work done. If the difficulty is high
// enough, it's probably been done by the network.
maybeParseHeader();
checkProofOfWork(true);
checkTimestamp();
}
/**
* Checks the block contents
*
* @throws VerificationException
*/
public void verifyTransactions() throws VerificationException {
// Now we need to check that the body of the block actually matches the headers. The network won't generate
// an invalid block, but if we didn't validate this then an untrusted man-in-the-middle could obtain the next
// valid block from the network and simply replace the transactions in it with their own fictional
// transactions that reference spent or non-existant inputs.
if (transactions.isEmpty())
throw new VerificationException("Block had no transactions");
maybeParseTransactions();
if (this.getOptimalEncodingMessageSize() > MAX_BLOCK_SIZE)
throw new VerificationException("Block larger than MAX_BLOCK_SIZE");
checkTransactions();
checkMerkleRoot();
checkSigOps();
for (Transaction transaction : transactions)
transaction.verify();
}
/**
* Verifies both the header and that the transactions hash to the merkle root.
*/
public void verify() throws VerificationException {
verifyHeader();
verifyTransactions();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Block))
return false;
Block other = (Block) o;
return getHash().equals(other.getHash());
}
@Override
public int hashCode() {
return getHash().hashCode();
}
/**
* Returns the merkle root in big endian form, calculating it from transactions if necessary.
*/
public Sha256Hash getMerkleRoot() {
maybeParseHeader();
if (merkleRoot == null) {
//TODO check if this is really necessary.
unCacheHeader();
merkleRoot = calculateMerkleRoot();
}
return merkleRoot;
}
public void setMerkleRoot(Sha256Hash value) {
unCacheHeader();
merkleRoot = value;
hash = null;
}
/** Adds a transaction to this block. The nonce and merkle root are invalid after this. */
public void addTransaction(Transaction t) {
addTransaction(t, true);
}
/** Adds a transaction to this block, with or without checking the sanity of doing so */
void addTransaction(Transaction t, boolean runSanityChecks) {
unCacheTransactions();
if (transactions == null) {
transactions = new ArrayList<Transaction>();
}
t.setParent(this);
if (runSanityChecks && transactions.size() == 0 && !t.isCoinBase())
throw new RuntimeException("Attempted to add a non-coinbase transaction as the first transaction: " + t);
else if (runSanityChecks && transactions.size() > 0 && t.isCoinBase())
throw new RuntimeException("Attempted to add a coinbase transaction when there already is one: " + t);
transactions.add(t);
adjustLength(transactions.size(), t.length);
// Force a recalculation next time the values are needed.
merkleRoot = null;
hash = null;
}
/** Returns the version of the block data structure as defined by the Bitcoin protocol. */
public long getVersion() {
maybeParseHeader();
return version;
}
/**
* Returns the hash of the previous block in the chain, as defined by the block header.
*/
public Sha256Hash getPrevBlockHash() {
maybeParseHeader();
return prevBlockHash;
}
void setPrevBlockHash(Sha256Hash prevBlockHash) {
unCacheHeader();
this.prevBlockHash = prevBlockHash;
this.hash = null;
this.scryptHash = null;
}
/**
* Returns the time at which the block was solved and broadcast, according to the clock of the solving node. This
* is measured in seconds since the UNIX epoch (midnight Jan 1st 1970).
*/
public long getTimeSeconds() {
maybeParseHeader();
return time;
}
/**
* Returns the time at which the block was solved and broadcast, according to the clock of the solving node.
*/
public Date getTime() {
return new Date(getTimeSeconds()*1000);
}
public void setTime(long time) {
unCacheHeader();
this.time = time;
this.hash = null;
this.scryptHash = null;
}
/**
* Returns the difficulty of the proof of work that this block should meet encoded <b>in compact form</b>. The {@link
* BlockChain} verifies that this is not too easy by looking at the length of the chain when the block is added.
* To find the actual value the hash should be compared against, use
* {@link com.google.litecoin.core.Block#getDifficultyTargetAsInteger()}. Note that this is <b>not</b> the same as
* the difficulty value reported by the Bitcoin "getdifficulty" RPC that you may see on various block explorers.
* That number is the result of applying a formula to the underlying difficulty to normalize the minimum to 1.
* Calculating the difficulty that way is currently unsupported.
*/
public long getDifficultyTarget() {
maybeParseHeader();
return difficultyTarget;
}
/** Sets the difficulty target in compact form. */
public void setDifficultyTarget(long compactForm) {
unCacheHeader();
this.difficultyTarget = compactForm;
this.hash = null;
this.scryptHash = null;
}
/**
* Returns the nonce, an arbitrary value that exists only to make the hash of the block header fall below the
* difficulty target.
*/
public long getNonce() {
maybeParseHeader();
return nonce;
}
/** Sets the nonce and clears any cached data. */
public void setNonce(long nonce) {
unCacheHeader();
this.nonce = nonce;
this.hash = null;
this.scryptHash = null;
}
/** Returns an immutable list of transactions held in this block. */
public List<Transaction> getTransactions() {
maybeParseTransactions();
return ImmutableList.copyOf(transactions);
}
// ///////////////////////////////////////////////////////////////////////////////////////////////
// Unit testing related methods.
// Used to make transactions unique.
static private int txCounter;
/** Adds a coinbase transaction to the block. This exists for unit tests. */
void addCoinbaseTransaction(byte[] pubKeyTo, BigInteger value) {
unCacheTransactions();
transactions = new ArrayList<Transaction>();
Transaction coinbase = new Transaction(params);
// A real coinbase transaction has some stuff in the scriptSig like the extraNonce and difficulty. The
// transactions are distinguished by every TX output going to a different key.
//
// Here we will do things a bit differently so a new address isn't needed every time. We'll put a simple
// counter in the scriptSig so every transaction has a different hash.
coinbase.addInput(new TransactionInput(params, coinbase, new byte[]{(byte) txCounter, (byte) (txCounter++ >> 8)}));
coinbase.addOutput(new TransactionOutput(params, coinbase, value,
ScriptBuilder.createOutputScript(new ECKey(null, pubKeyTo)).getProgram()));
transactions.add(coinbase);
coinbase.setParent(this);
coinbase.length = coinbase.bitcoinSerialize().length;
adjustLength(transactions.size(), coinbase.length);
}
static final byte[] EMPTY_BYTES = new byte[32];
/**
* Returns a solved block that builds on top of this one. This exists for unit tests.
*/
@VisibleForTesting
public Block createNextBlock(Address to, long time) {
return createNextBlock(to, null, time, EMPTY_BYTES, Utils.toNanoCoins(50, 0));
}
/**
* Returns a solved block that builds on top of this one. This exists for unit tests.
* In this variant you can specify a public key (pubkey) for use in generating coinbase blocks.
*/
Block createNextBlock(@Nullable Address to, @Nullable TransactionOutPoint prevOut, long time,
byte[] pubKey, BigInteger coinbaseValue) {
Block b = new Block(params);
b.setDifficultyTarget(difficultyTarget);
b.addCoinbaseTransaction(pubKey, coinbaseValue);
if (to != null) {
// Add a transaction paying 50 coins to the "to" address.
Transaction t = new Transaction(params);
t.addOutput(new TransactionOutput(params, t, Utils.toNanoCoins(50, 0), to));
// The input does not really need to be a valid signature, as long as it has the right general form.
TransactionInput input;
if (prevOut == null) {
input = new TransactionInput(params, t, Script.createInputScript(EMPTY_BYTES, EMPTY_BYTES));
// Importantly the outpoint hash cannot be zero as that's how we detect a coinbase transaction in isolation
// but it must be unique to avoid 'different' transactions looking the same.
byte[] counter = new byte[32];
counter[0] = (byte) txCounter;
counter[1] = (byte) (txCounter++ >> 8);
input.getOutpoint().setHash(new Sha256Hash(counter));
} else {
input = new TransactionInput(params, t, Script.createInputScript(EMPTY_BYTES, EMPTY_BYTES), prevOut);
}
t.addInput(input);
b.addTransaction(t);
}
b.setPrevBlockHash(getHash());
// Don't let timestamp go backwards
if (getTimeSeconds() >= time)
b.setTime(getTimeSeconds() + 1);
else
b.setTime(time);
b.solve();
try {
b.verifyHeader();
} catch (VerificationException e) {
throw new RuntimeException(e); // Cannot happen.
}
return b;
}
@VisibleForTesting
public Block createNextBlock(@Nullable Address to, TransactionOutPoint prevOut) {
return createNextBlock(to, prevOut, Utils.now().getTime() / 1000, EMPTY_BYTES, Utils.toNanoCoins(50, 0));
}
@VisibleForTesting
public Block createNextBlock(@Nullable Address to, BigInteger value) {
return createNextBlock(to, null, Utils.now().getTime() / 1000, EMPTY_BYTES, value);
}
@VisibleForTesting
public Block createNextBlock(@Nullable Address to) {
return createNextBlock(to, Utils.toNanoCoins(50, 0));
}
@VisibleForTesting
public Block createNextBlockWithCoinbase(byte[] pubKey, BigInteger coinbaseValue) {
return createNextBlock(null, null, Utils.now().getTime() / 1000, pubKey, coinbaseValue);
}
/**
* Create a block sending 50BTC as a coinbase transaction to the public key specified.
* This method is intended for test use only.
*/
@VisibleForTesting
Block createNextBlockWithCoinbase(byte[] pubKey) {
return createNextBlock(null, null, Utils.now().getTime() / 1000, pubKey, Utils.toNanoCoins(50, 0));
}
@VisibleForTesting
boolean isParsedHeader() {
return headerParsed;
}
@VisibleForTesting
boolean isParsedTransactions() {
return transactionsParsed;
}
@VisibleForTesting
boolean isHeaderBytesValid() {
return headerBytesValid;
}
@VisibleForTesting
boolean isTransactionBytesValid() {
return transactionBytesValid;
}
}
|
core/src/main/java/com/google/litecoin/core/Block.java
|
/**
* Copyright 2011 Google 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.google.litecoin.core;
import com.google.litecoin.script.Script;
import com.google.litecoin.script.ScriptBuilder;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import static com.google.litecoin.core.Utils.doubleDigest;
import static com.google.litecoin.core.Utils.doubleDigestTwoBuffers;
import static com.google.litecoin.core.Utils.scryptDigest;
/**
* <p>A block is a group of transactions, and is one of the fundamental data structures of the Bitcoin system.
* It records a set of {@link Transaction}s together with some data that links it into a place in the global block
* chain, and proves that a difficult calculation was done over its contents. See
* <a href="http://www.litecoin.org/litecoin.pdf">the Bitcoin technical paper</a> for
* more detail on blocks. <p/>
*
* To get a block, you can either build one from the raw bytes you can get from another implementation, or request one
* specifically using {@link Peer#getBlock(Sha256Hash)}, or grab one from a downloaded {@link BlockChain}.
*/
public class Block extends Message {
private static final Logger log = LoggerFactory.getLogger(Block.class);
private static final long serialVersionUID = 2738848929966035281L;
/** How many bytes are required to represent a block header WITHOUT the trailing 00 length byte. */
public static final int HEADER_SIZE = 80;
static final long ALLOWED_TIME_DRIFT = 2 * 60 * 60; // Same value as official client.
/**
* A constant shared by the entire network: how large in bytes a block is allowed to be. One day we may have to
* upgrade everyone to change this, so Bitcoin can continue to grow. For now it exists as an anti-DoS measure to
* avoid somebody creating a titanically huge but valid block and forcing everyone to download/store it forever.
*/
public static final int MAX_BLOCK_SIZE = 1 * 1000 * 1000;
/**
* A "sigop" is a signature verification operation. Because they're expensive we also impose a separate limit on
* the number in a block to prevent somebody mining a huge block that has way more sigops than normal, so is very
* expensive/slow to verify.
*/
public static final int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE / 50;
/** A value for difficultyTarget (nBits) that allows half of all possible hash solutions. Used in unit testing. */
public static final long EASIEST_DIFFICULTY_TARGET = 0x207fFFFFL;
// Fields defined as part of the protocol format.
private long version;
private Sha256Hash prevBlockHash;
private Sha256Hash merkleRoot;
private long time;
private long difficultyTarget; // "nBits"
private long nonce;
/** If null, it means this object holds only the headers. */
List<Transaction> transactions;
/** Stores the hash of the block. If null, getHash() will recalculate it. */
private transient Sha256Hash hash;
private transient Sha256Hash scryptHash;
private transient boolean headerParsed;
private transient boolean transactionsParsed;
private transient boolean headerBytesValid;
private transient boolean transactionBytesValid;
// Blocks can be encoded in a way that will use more bytes than is optimal (due to VarInts having multiple encodings)
// MAX_BLOCK_SIZE must be compared to the optimal encoding, not the actual encoding, so when parsing, we keep track
// of the size of the ideal encoding in addition to the actual message size (which Message needs)
private transient int optimalEncodingMessageSize;
/** Special case constructor, used for the genesis node, cloneAsHeader and unit tests. */
Block(NetworkParameters params) {
super(params);
// Set up a few basic things. We are not complete after this though.
version = 1;
difficultyTarget = 0x1d07fff8L;
time = System.currentTimeMillis() / 1000;
prevBlockHash = Sha256Hash.ZERO_HASH;
length = 80;
}
/** Constructs a block object from the Bitcoin wire format. */
public Block(NetworkParameters params, byte[] payloadBytes) throws ProtocolException {
super(params, payloadBytes, 0, false, false, payloadBytes.length);
}
/**
* Contruct a block object from the Bitcoin wire format.
* @param params NetworkParameters object.
* @param parseLazy Whether to perform a full parse immediately or delay until a read is requested.
* @param parseRetain Whether to retain the backing byte array for quick reserialization.
* If true and the backing byte array is invalidated due to modification of a field then
* the cached bytes may be repopulated and retained if the message is serialized again in the future.
* @param length The length of message if known. Usually this is provided when deserializing of the wire
* as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH
* @throws ProtocolException
*/
public Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length)
throws ProtocolException {
super(params, payloadBytes, 0, parseLazy, parseRetain, length);
}
/**
* Construct a block initialized with all the given fields.
* @param params Which network the block is for.
* @param version This should usually be set to 1 or 2, depending on if the height is in the coinbase input.
* @param prevBlockHash Reference to previous block in the chain or {@link Sha256Hash#ZERO_HASH} if genesis.
* @param merkleRoot The root of the merkle tree formed by the transactions.
* @param time UNIX time when the block was mined.
* @param difficultyTarget Number which this block hashes lower than.
* @param nonce Arbitrary number to make the block hash lower than the target.
* @param transactions List of transactions including the coinbase.
*/
public Block(NetworkParameters params, long version, Sha256Hash prevBlockHash, Sha256Hash merkleRoot, long time,
long difficultyTarget, long nonce, List<Transaction> transactions) {
super(params);
this.version = version;
this.prevBlockHash = prevBlockHash;
this.merkleRoot = merkleRoot;
this.time = time;
this.difficultyTarget = difficultyTarget;
this.nonce = nonce;
this.transactions = new LinkedList<Transaction>();
this.transactions.addAll(transactions);
}
/**
* <p>A utility method that calculates how much new Bitcoin would be created by the block at the given height.
* The inflation of Bitcoin is predictable and drops roughly every 4 years (210,000 blocks). At the dawn of
* the system it was 50 coins per block, in late 2012 it went to 25 coins per block, and so on. The size of
* a coinbase transaction is inflation plus fees.</p>
*
* <p>The half-life is controlled by {@link com.google.litecoin.core.NetworkParameters#getSubsidyDecreaseBlockCount()}.
* </p>
*/
public BigInteger getBlockInflation(int height) {
return Utils.toNanoCoins(50, 0).shiftRight(height / params.getSubsidyDecreaseBlockCount());
}
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
ois.defaultReadObject();
// This code is not actually necessary, as transient fields are initialized to the default value which is in
// this case null. However it clears out a FindBugs warning and makes it explicit what we're doing.
hash = null;
}
private void parseHeader() throws ProtocolException {
if (headerParsed)
return;
cursor = offset;
version = readUint32();
prevBlockHash = readHash();
merkleRoot = readHash();
time = readUint32();
difficultyTarget = readUint32();
nonce = readUint32();
hash = new Sha256Hash(Utils.reverseBytes(Utils.doubleDigest(bytes, offset, cursor)));
headerParsed = true;
headerBytesValid = parseRetain;
}
private void parseTransactions() throws ProtocolException {
if (transactionsParsed)
return;
cursor = offset + HEADER_SIZE;
optimalEncodingMessageSize = HEADER_SIZE;
if (bytes.length == cursor) {
// This message is just a header, it has no transactions.
transactionsParsed = true;
transactionBytesValid = false;
return;
}
int numTransactions = (int) readVarInt();
optimalEncodingMessageSize += VarInt.sizeOf(numTransactions);
transactions = new ArrayList<Transaction>(numTransactions);
for (int i = 0; i < numTransactions; i++) {
Transaction tx = new Transaction(params, bytes, cursor, this, parseLazy, parseRetain, UNKNOWN_LENGTH);
// Label the transaction as coming from the P2P network, so code that cares where we first saw it knows.
tx.getConfidence().setSource(TransactionConfidence.Source.NETWORK);
transactions.add(tx);
cursor += tx.getMessageSize();
optimalEncodingMessageSize += tx.getOptimalEncodingMessageSize();
}
// No need to set length here. If length was not provided then it should be set at the end of parseLight().
// If this is a genuine lazy parse then length must have been provided to the constructor.
transactionsParsed = true;
transactionBytesValid = parseRetain;
}
void parse() throws ProtocolException {
parseHeader();
parseTransactions();
length = cursor - offset;
}
public int getOptimalEncodingMessageSize() {
if (optimalEncodingMessageSize != 0)
return optimalEncodingMessageSize;
maybeParseTransactions();
if (optimalEncodingMessageSize != 0)
return optimalEncodingMessageSize;
optimalEncodingMessageSize = getMessageSize();
return optimalEncodingMessageSize;
}
protected void parseLite() throws ProtocolException {
// Ignore the header since it has fixed length. If length is not provided we will have to
// invoke a light parse of transactions to calculate the length.
if (length == UNKNOWN_LENGTH) {
Preconditions.checkState(parseLazy,
"Performing lite parse of block transaction as block was initialised from byte array " +
"without providing length. This should never need to happen.");
parseTransactions();
length = cursor - offset;
} else {
transactionBytesValid = !transactionsParsed || parseRetain && length > HEADER_SIZE;
}
headerBytesValid = !headerParsed || parseRetain && length >= HEADER_SIZE;
}
/*
* Block uses some special handling for lazy parsing and retention of cached bytes. Parsing and serializing the
* block header and the transaction list are both non-trivial so there are good efficiency gains to be had by
* separating them. There are many cases where a user may need to access or change one or the other but not both.
*
* With this in mind we ignore the inherited checkParse() and unCache() methods and implement a separate version
* of them for both header and transactions.
*
* Serializing methods are also handled in their own way. Whilst they deal with separate parts of the block structure
* there are some interdependencies. For example altering a tx requires invalidating the Merkle root and therefore
* the cached header bytes.
*/
private void maybeParseHeader() {
if (headerParsed || bytes == null)
return;
try {
parseHeader();
if (!(headerBytesValid || transactionBytesValid))
bytes = null;
} catch (ProtocolException e) {
throw new LazyParseException(
"ProtocolException caught during lazy parse. For safe access to fields call ensureParsed before attempting read or write access",
e);
}
}
private void maybeParseTransactions() {
if (transactionsParsed || bytes == null)
return;
try {
parseTransactions();
if (!parseRetain) {
transactionBytesValid = false;
if (headerParsed)
bytes = null;
}
} catch (ProtocolException e) {
throw new LazyParseException(
"ProtocolException caught during lazy parse. For safe access to fields call ensureParsed before attempting read or write access",
e);
}
}
/**
* Ensure the object is parsed if needed. This should be called in every getter before returning a value. If the
* lazy parse flag is not set this is a method returns immediately.
*/
protected void maybeParse() {
throw new LazyParseException(
"checkParse() should never be called on a Block. Instead use checkParseHeader() and checkParseTransactions()");
}
/**
* In lazy parsing mode access to getters and setters may throw an unchecked LazyParseException. If guaranteed
* safe access is required this method will force parsing to occur immediately thus ensuring LazyParseExeption will
* never be thrown from this Message. If the Message contains child messages (e.g. a Block containing Transaction
* messages) this will not force child messages to parse.
*
* This method ensures parsing of both headers and transactions.
*
* @throws ProtocolException
*/
public void ensureParsed() throws ProtocolException {
try {
maybeParseHeader();
maybeParseTransactions();
} catch (LazyParseException e) {
if (e.getCause() instanceof ProtocolException)
throw (ProtocolException) e.getCause();
throw new ProtocolException(e);
}
}
/**
* In lazy parsing mode access to getters and setters may throw an unchecked LazyParseException. If guaranteed
* safe access is required this method will force parsing to occur immediately thus ensuring LazyParseExeption
* will never be thrown from this Message. If the Message contains child messages (e.g. a Block containing
* Transaction messages) this will not force child messages to parse.
*
* This method ensures parsing of headers only.
*
* @throws ProtocolException
*/
public void ensureParsedHeader() throws ProtocolException {
try {
maybeParseHeader();
} catch (LazyParseException e) {
if (e.getCause() instanceof ProtocolException)
throw (ProtocolException) e.getCause();
throw new ProtocolException(e);
}
}
/**
* In lazy parsing mode access to getters and setters may throw an unchecked LazyParseException. If guaranteed
* safe access is required this method will force parsing to occur immediately thus ensuring LazyParseExeption will
* never be thrown from this Message. If the Message contains child messages (e.g. a Block containing Transaction
* messages) this will not force child messages to parse.
*
* This method ensures parsing of transactions only.
*
* @throws ProtocolException
*/
public void ensureParsedTransactions() throws ProtocolException {
try {
maybeParseTransactions();
} catch (LazyParseException e) {
if (e.getCause() instanceof ProtocolException)
throw (ProtocolException) e.getCause();
throw new ProtocolException(e);
}
}
// default for testing
void writeHeader(OutputStream stream) throws IOException {
// try for cached write first
if (headerBytesValid && bytes != null && bytes.length >= offset + HEADER_SIZE) {
stream.write(bytes, offset, HEADER_SIZE);
return;
}
// fall back to manual write
maybeParseHeader();
Utils.uint32ToByteStreamLE(version, stream);
stream.write(Utils.reverseBytes(prevBlockHash.getBytes()));
stream.write(Utils.reverseBytes(getMerkleRoot().getBytes()));
Utils.uint32ToByteStreamLE(time, stream);
Utils.uint32ToByteStreamLE(difficultyTarget, stream);
Utils.uint32ToByteStreamLE(nonce, stream);
}
private void writeTransactions(OutputStream stream) throws IOException {
// check for no transaction conditions first
// must be a more efficient way to do this but I'm tired atm.
if (transactions == null && transactionsParsed) {
return;
}
// confirmed we must have transactions either cached or as objects.
if (transactionBytesValid && bytes != null && bytes.length >= offset + length) {
stream.write(bytes, offset + HEADER_SIZE, length - HEADER_SIZE);
return;
}
if (transactions != null) {
stream.write(new VarInt(transactions.size()).encode());
for (Transaction tx : transactions) {
tx.bitcoinSerialize(stream);
}
}
}
/**
* Special handling to check if we have a valid byte array for both header
* and transactions
*
* @throws IOException
*/
public byte[] bitcoinSerialize() {
// we have completely cached byte array.
if (headerBytesValid && transactionBytesValid) {
Preconditions.checkNotNull(bytes, "Bytes should never be null if headerBytesValid && transactionBytesValid");
if (length == bytes.length) {
return bytes;
} else {
// byte array is offset so copy out the correct range.
byte[] buf = new byte[length];
System.arraycopy(bytes, offset, buf, 0, length);
return buf;
}
}
// At least one of the two cacheable components is invalid
// so fall back to stream write since we can't be sure of the length.
ByteArrayOutputStream stream = new UnsafeByteArrayOutputStream(length == UNKNOWN_LENGTH ? HEADER_SIZE + guessTransactionsLength() : length);
try {
writeHeader(stream);
writeTransactions(stream);
} catch (IOException e) {
// Cannot happen, we are serializing to a memory stream.
}
return stream.toByteArray();
}
@Override
protected void bitcoinSerializeToStream(OutputStream stream) throws IOException {
writeHeader(stream);
// We may only have enough data to write the header.
writeTransactions(stream);
}
/**
* Provides a reasonable guess at the byte length of the transactions part of the block.
* The returned value will be accurate in 99% of cases and in those cases where not will probably slightly
* oversize.
*
* This is used to preallocate the underlying byte array for a ByteArrayOutputStream. If the size is under the
* real value the only penalty is resizing of the underlying byte array.
*/
private int guessTransactionsLength() {
if (transactionBytesValid)
return bytes.length - HEADER_SIZE;
if (transactions == null)
return 0;
int len = VarInt.sizeOf(transactions.size());
for (Transaction tx : transactions) {
// 255 is just a guess at an average tx length
len += tx.length == UNKNOWN_LENGTH ? 255 : tx.length;
}
return len;
}
protected void unCache() {
// Since we have alternate uncache methods to use internally this will only ever be called by a child
// transaction so we only need to invalidate that part of the cache.
unCacheTransactions();
}
private void unCacheHeader() {
maybeParseHeader();
headerBytesValid = false;
if (!transactionBytesValid)
bytes = null;
hash = null;
checksum = null;
}
private void unCacheTransactions() {
maybeParseTransactions();
transactionBytesValid = false;
if (!headerBytesValid)
bytes = null;
// Current implementation has to uncache headers as well as any change to a tx will alter the merkle root. In
// future we can go more granular and cache merkle root separately so rest of the header does not need to be
// rewritten.
unCacheHeader();
// Clear merkleRoot last as it may end up being parsed during unCacheHeader().
merkleRoot = null;
}
/**
* Calculates the block hash by serializing the block and hashing the
* resulting bytes.
*/
private Sha256Hash calculateHash() {
try {
ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(HEADER_SIZE);
writeHeader(bos);
return new Sha256Hash(Utils.reverseBytes(doubleDigest(bos.toByteArray())));
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
}
private Sha256Hash calculateScryptHash() {
try {
ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(HEADER_SIZE);
writeHeader(bos);
return new Sha256Hash(Utils.reverseBytes(scryptDigest(bos.toByteArray())));
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
}
/**
* Returns the hash of the block (which for a valid, solved block should be below the target) in the form seen on
* the block explorer. If you call this on block 1 in the production chain
* you will get "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048".
*/
public String getHashAsString() {
return getHash().toString();
}
public String getScryptHashAsString() {
return getScryptHash().toString();
}
/**
* Returns the hash of the block (which for a valid, solved block should be
* below the target). Big endian.
*/
public Sha256Hash getHash() {
if (hash == null)
hash = calculateHash();
return hash;
}
public Sha256Hash getScryptHash() {
if (hash == null)
hash = calculateScryptHash();
return hash;
}
/**
* The number that is one greater than the largest representable SHA-256
* hash.
*/
static private BigInteger LARGEST_HASH = BigInteger.ONE.shiftLeft(256);
/**
* Returns the work represented by this block.<p>
*
* Work is defined as the number of tries needed to solve a block in the
* average case. Consider a difficulty target that covers 5% of all possible
* hash values. Then the work of the block will be 20. As the target gets
* lower, the amount of work goes up.
*/
public BigInteger getWork() throws VerificationException {
BigInteger target = getDifficultyTargetAsInteger();
return LARGEST_HASH.divide(target.add(BigInteger.ONE));
}
/** Returns a copy of the block, but without any transactions. */
public Block cloneAsHeader() {
maybeParseHeader();
Block block = new Block(params);
block.nonce = nonce;
block.prevBlockHash = prevBlockHash.duplicate();
block.merkleRoot = getMerkleRoot().duplicate();
block.version = version;
block.time = time;
block.difficultyTarget = difficultyTarget;
block.transactions = null;
block.hash = getScryptHash().duplicate();
return block;
}
/**
* Returns a multi-line string containing a description of the contents of
* the block. Use for debugging purposes only.
*/
@Override
public String toString() {
StringBuilder s = new StringBuilder("v");
s.append(version);
s.append(" block: \n");
s.append(" previous block: ");
s.append(getPrevBlockHash());
s.append("\n");
s.append(" merkle root: ");
s.append(getMerkleRoot());
s.append("\n");
s.append(" time: [");
s.append(time);
s.append("] ");
s.append(new Date(time * 1000));
s.append("\n");
s.append(" difficulty target (nBits): ");
s.append(difficultyTarget);
s.append("\n");
s.append(" nonce: ");
s.append(nonce);
s.append("\n");
if (transactions != null && transactions.size() > 0) {
s.append(" with ").append(transactions.size()).append(" transaction(s):\n");
for (Transaction tx : transactions) {
s.append(tx.toString());
}
}
return s.toString();
}
/**
* <p>Finds a value of nonce that makes the blocks hash lower than the difficulty target. This is called mining, but
* solve() is far too slow to do real mining with. It exists only for unit testing purposes.
*
* <p>This can loop forever if a solution cannot be found solely by incrementing nonce. It doesn't change
* extraNonce.</p>
*/
public void solve() {
maybeParseHeader();
while (true) {
try {
// Is our proof of work valid yet?
if (checkProofOfWork(false))
return;
// No, so increment the nonce and try again.
setNonce(getNonce() + 1);
} catch (VerificationException e) {
throw new RuntimeException(e); // Cannot happen.
}
}
}
/**
* Returns the difficulty target as a 256 bit value that can be compared to a SHA-256 hash. Inside a block the
* target is represented using a compact form. If this form decodes to a value that is out of bounds, an exception
* is thrown.
*/
public BigInteger getDifficultyTargetAsInteger() throws VerificationException {
maybeParseHeader();
BigInteger target = Utils.decodeCompactBits(difficultyTarget);
if (target.compareTo(BigInteger.ZERO) <= 0 || target.compareTo(params.proofOfWorkLimit) > 0)
throw new VerificationException("Difficulty target is bad: " + target.toString() + " or " + difficultyTarget);
return target;
}
/** Returns true if the hash of the block is OK (lower than difficulty target). */
private boolean checkProofOfWork(boolean throwException) throws VerificationException {
// This part is key - it is what proves the block was as difficult to make as it claims
// to be. Note however that in the context of this function, the block can claim to be
// as difficult as it wants to be .... if somebody was able to take control of our network
// connection and fork us onto a different chain, they could send us valid blocks with
// ridiculously easy difficulty and this function would accept them.
//
// To prevent this attack from being possible, elsewhere we check that the difficultyTarget
// field is of the right value. This requires us to have the preceeding blocks.
BigInteger target = getDifficultyTargetAsInteger();
BigInteger h = getScryptHash().toBigInteger();
if (h.compareTo(target) > 0) {
// Proof of work check failed!
if (throwException)
throw new VerificationException("Hash is higher than target: " + getScryptHashAsString() + " vs "
+ target.toString(16));
else
return false;
}
return true;
}
private void checkTimestamp() throws VerificationException {
maybeParseHeader();
// Allow injection of a fake clock to allow unit testing.
long currentTime = Utils.now().getTime()/1000;
if (time > currentTime + ALLOWED_TIME_DRIFT)
throw new VerificationException("Block too far in future");
}
private void checkSigOps() throws VerificationException {
// Check there aren't too many signature verifications in the block. This is an anti-DoS measure, see the
// comments for MAX_BLOCK_SIGOPS.
int sigOps = 0;
for (Transaction tx : transactions) {
sigOps += tx.getSigOpCount();
}
if (sigOps > MAX_BLOCK_SIGOPS)
throw new VerificationException("Block had too many Signature Operations");
}
private void checkMerkleRoot() throws VerificationException {
Sha256Hash calculatedRoot = calculateMerkleRoot();
if (!calculatedRoot.equals(merkleRoot)) {
log.error("Merkle tree did not verify");
throw new VerificationException("Merkle hashes do not match: " + calculatedRoot + " vs " + merkleRoot);
}
}
private Sha256Hash calculateMerkleRoot() {
List<byte[]> tree = buildMerkleTree();
return new Sha256Hash(tree.get(tree.size() - 1));
}
private List<byte[]> buildMerkleTree() {
// The Merkle root is based on a tree of hashes calculated from the transactions:
//
// root
// / \
// A B
// / \ / \
// t1 t2 t3 t4
//
// The tree is represented as a list: t1,t2,t3,t4,A,B,root where each
// entry is a hash.
//
// The hashing algorithm is double SHA-256. The leaves are a hash of the serialized contents of the transaction.
// The interior nodes are hashes of the concenation of the two child hashes.
//
// This structure allows the creation of proof that a transaction was included into a block without having to
// provide the full block contents. Instead, you can provide only a Merkle branch. For example to prove tx2 was
// in a block you can just provide tx2, the hash(tx1) and B. Now the other party has everything they need to
// derive the root, which can be checked against the block header. These proofs aren't used right now but
// will be helpful later when we want to download partial block contents.
//
// Note that if the number of transactions is not even the last tx is repeated to make it so (see
// tx3 above). A tree with 5 transactions would look like this:
//
// root
// / \
// 1 5
// / \ / \
// 2 3 4 4
// / \ / \ / \
// t1 t2 t3 t4 t5 t5
maybeParseTransactions();
ArrayList<byte[]> tree = new ArrayList<byte[]>();
// Start by adding all the hashes of the transactions as leaves of the tree.
for (Transaction t : transactions) {
tree.add(t.getHash().getBytes());
}
int levelOffset = 0; // Offset in the list where the currently processed level starts.
// Step through each level, stopping when we reach the root (levelSize == 1).
for (int levelSize = transactions.size(); levelSize > 1; levelSize = (levelSize + 1) / 2) {
// For each pair of nodes on that level:
for (int left = 0; left < levelSize; left += 2) {
// The right hand node can be the same as the left hand, in the case where we don't have enough
// transactions.
int right = Math.min(left + 1, levelSize - 1);
byte[] leftBytes = Utils.reverseBytes(tree.get(levelOffset + left));
byte[] rightBytes = Utils.reverseBytes(tree.get(levelOffset + right));
tree.add(Utils.reverseBytes(doubleDigestTwoBuffers(leftBytes, 0, 32, rightBytes, 0, 32)));
}
// Move to the next level.
levelOffset += levelSize;
}
return tree;
}
private void checkTransactions() throws VerificationException {
// The first transaction in a block must always be a coinbase transaction.
if (!transactions.get(0).isCoinBase())
throw new VerificationException("First tx is not coinbase");
// The rest must not be.
for (int i = 1; i < transactions.size(); i++) {
if (transactions.get(i).isCoinBase())
throw new VerificationException("TX " + i + " is coinbase when it should not be.");
}
}
/**
* Checks the block data to ensure it follows the rules laid out in the network parameters. Specifically,
* throws an exception if the proof of work is invalid, or if the timestamp is too far from what it should be.
* This is <b>not</b> everything that is required for a block to be valid, only what is checkable independent
* of the chain and without a transaction index.
*
* @throws VerificationException
*/
public void verifyHeader() throws VerificationException {
// Prove that this block is OK. It might seem that we can just ignore most of these checks given that the
// network is also verifying the blocks, but we cannot as it'd open us to a variety of obscure attacks.
//
// Firstly we need to ensure this block does in fact represent real work done. If the difficulty is high
// enough, it's probably been done by the network.
maybeParseHeader();
checkProofOfWork(true);
checkTimestamp();
}
/**
* Checks the block contents
*
* @throws VerificationException
*/
public void verifyTransactions() throws VerificationException {
// Now we need to check that the body of the block actually matches the headers. The network won't generate
// an invalid block, but if we didn't validate this then an untrusted man-in-the-middle could obtain the next
// valid block from the network and simply replace the transactions in it with their own fictional
// transactions that reference spent or non-existant inputs.
if (transactions.isEmpty())
throw new VerificationException("Block had no transactions");
maybeParseTransactions();
if (this.getOptimalEncodingMessageSize() > MAX_BLOCK_SIZE)
throw new VerificationException("Block larger than MAX_BLOCK_SIZE");
checkTransactions();
checkMerkleRoot();
checkSigOps();
for (Transaction transaction : transactions)
transaction.verify();
}
/**
* Verifies both the header and that the transactions hash to the merkle root.
*/
public void verify() throws VerificationException {
verifyHeader();
verifyTransactions();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Block))
return false;
Block other = (Block) o;
return getScryptHash().equals(other.getScryptHash());
}
@Override
public int hashCode() {
return getScryptHash().hashCode();
}
/**
* Returns the merkle root in big endian form, calculating it from transactions if necessary.
*/
public Sha256Hash getMerkleRoot() {
maybeParseHeader();
if (merkleRoot == null) {
//TODO check if this is really necessary.
unCacheHeader();
merkleRoot = calculateMerkleRoot();
}
return merkleRoot;
}
public void setMerkleRoot(Sha256Hash value) {
unCacheHeader();
merkleRoot = value;
hash = null;
}
/** Adds a transaction to this block. The nonce and merkle root are invalid after this. */
public void addTransaction(Transaction t) {
addTransaction(t, true);
}
/** Adds a transaction to this block, with or without checking the sanity of doing so */
void addTransaction(Transaction t, boolean runSanityChecks) {
unCacheTransactions();
if (transactions == null) {
transactions = new ArrayList<Transaction>();
}
t.setParent(this);
if (runSanityChecks && transactions.size() == 0 && !t.isCoinBase())
throw new RuntimeException("Attempted to add a non-coinbase transaction as the first transaction: " + t);
else if (runSanityChecks && transactions.size() > 0 && t.isCoinBase())
throw new RuntimeException("Attempted to add a coinbase transaction when there already is one: " + t);
transactions.add(t);
adjustLength(transactions.size(), t.length);
// Force a recalculation next time the values are needed.
merkleRoot = null;
hash = null;
}
/** Returns the version of the block data structure as defined by the Bitcoin protocol. */
public long getVersion() {
maybeParseHeader();
return version;
}
/**
* Returns the hash of the previous block in the chain, as defined by the block header.
*/
public Sha256Hash getPrevBlockHash() {
maybeParseHeader();
return prevBlockHash;
}
void setPrevBlockHash(Sha256Hash prevBlockHash) {
unCacheHeader();
this.prevBlockHash = prevBlockHash;
this.hash = null;
this.scryptHash = null;
}
/**
* Returns the time at which the block was solved and broadcast, according to the clock of the solving node. This
* is measured in seconds since the UNIX epoch (midnight Jan 1st 1970).
*/
public long getTimeSeconds() {
maybeParseHeader();
return time;
}
/**
* Returns the time at which the block was solved and broadcast, according to the clock of the solving node.
*/
public Date getTime() {
return new Date(getTimeSeconds()*1000);
}
public void setTime(long time) {
unCacheHeader();
this.time = time;
this.hash = null;
this.scryptHash = null;
}
/**
* Returns the difficulty of the proof of work that this block should meet encoded <b>in compact form</b>. The {@link
* BlockChain} verifies that this is not too easy by looking at the length of the chain when the block is added.
* To find the actual value the hash should be compared against, use
* {@link com.google.litecoin.core.Block#getDifficultyTargetAsInteger()}. Note that this is <b>not</b> the same as
* the difficulty value reported by the Bitcoin "getdifficulty" RPC that you may see on various block explorers.
* That number is the result of applying a formula to the underlying difficulty to normalize the minimum to 1.
* Calculating the difficulty that way is currently unsupported.
*/
public long getDifficultyTarget() {
maybeParseHeader();
return difficultyTarget;
}
/** Sets the difficulty target in compact form. */
public void setDifficultyTarget(long compactForm) {
unCacheHeader();
this.difficultyTarget = compactForm;
this.hash = null;
this.scryptHash = null;
}
/**
* Returns the nonce, an arbitrary value that exists only to make the hash of the block header fall below the
* difficulty target.
*/
public long getNonce() {
maybeParseHeader();
return nonce;
}
/** Sets the nonce and clears any cached data. */
public void setNonce(long nonce) {
unCacheHeader();
this.nonce = nonce;
this.hash = null;
this.scryptHash = null;
}
/** Returns an immutable list of transactions held in this block. */
public List<Transaction> getTransactions() {
maybeParseTransactions();
return ImmutableList.copyOf(transactions);
}
// ///////////////////////////////////////////////////////////////////////////////////////////////
// Unit testing related methods.
// Used to make transactions unique.
static private int txCounter;
/** Adds a coinbase transaction to the block. This exists for unit tests. */
void addCoinbaseTransaction(byte[] pubKeyTo, BigInteger value) {
unCacheTransactions();
transactions = new ArrayList<Transaction>();
Transaction coinbase = new Transaction(params);
// A real coinbase transaction has some stuff in the scriptSig like the extraNonce and difficulty. The
// transactions are distinguished by every TX output going to a different key.
//
// Here we will do things a bit differently so a new address isn't needed every time. We'll put a simple
// counter in the scriptSig so every transaction has a different hash.
coinbase.addInput(new TransactionInput(params, coinbase, new byte[]{(byte) txCounter, (byte) (txCounter++ >> 8)}));
coinbase.addOutput(new TransactionOutput(params, coinbase, value,
ScriptBuilder.createOutputScript(new ECKey(null, pubKeyTo)).getProgram()));
transactions.add(coinbase);
coinbase.setParent(this);
coinbase.length = coinbase.bitcoinSerialize().length;
adjustLength(transactions.size(), coinbase.length);
}
static final byte[] EMPTY_BYTES = new byte[32];
/**
* Returns a solved block that builds on top of this one. This exists for unit tests.
*/
@VisibleForTesting
public Block createNextBlock(Address to, long time) {
return createNextBlock(to, null, time, EMPTY_BYTES, Utils.toNanoCoins(50, 0));
}
/**
* Returns a solved block that builds on top of this one. This exists for unit tests.
* In this variant you can specify a public key (pubkey) for use in generating coinbase blocks.
*/
Block createNextBlock(@Nullable Address to, @Nullable TransactionOutPoint prevOut, long time,
byte[] pubKey, BigInteger coinbaseValue) {
Block b = new Block(params);
b.setDifficultyTarget(difficultyTarget);
b.addCoinbaseTransaction(pubKey, coinbaseValue);
if (to != null) {
// Add a transaction paying 50 coins to the "to" address.
Transaction t = new Transaction(params);
t.addOutput(new TransactionOutput(params, t, Utils.toNanoCoins(50, 0), to));
// The input does not really need to be a valid signature, as long as it has the right general form.
TransactionInput input;
if (prevOut == null) {
input = new TransactionInput(params, t, Script.createInputScript(EMPTY_BYTES, EMPTY_BYTES));
// Importantly the outpoint hash cannot be zero as that's how we detect a coinbase transaction in isolation
// but it must be unique to avoid 'different' transactions looking the same.
byte[] counter = new byte[32];
counter[0] = (byte) txCounter;
counter[1] = (byte) (txCounter++ >> 8);
input.getOutpoint().setHash(new Sha256Hash(counter));
} else {
input = new TransactionInput(params, t, Script.createInputScript(EMPTY_BYTES, EMPTY_BYTES), prevOut);
}
t.addInput(input);
b.addTransaction(t);
}
b.setPrevBlockHash(getScryptHash());
// Don't let timestamp go backwards
if (getTimeSeconds() >= time)
b.setTime(getTimeSeconds() + 1);
else
b.setTime(time);
b.solve();
try {
b.verifyHeader();
} catch (VerificationException e) {
throw new RuntimeException(e); // Cannot happen.
}
return b;
}
@VisibleForTesting
public Block createNextBlock(@Nullable Address to, TransactionOutPoint prevOut) {
return createNextBlock(to, prevOut, Utils.now().getTime() / 1000, EMPTY_BYTES, Utils.toNanoCoins(50, 0));
}
@VisibleForTesting
public Block createNextBlock(@Nullable Address to, BigInteger value) {
return createNextBlock(to, null, Utils.now().getTime() / 1000, EMPTY_BYTES, value);
}
@VisibleForTesting
public Block createNextBlock(@Nullable Address to) {
return createNextBlock(to, Utils.toNanoCoins(50, 0));
}
@VisibleForTesting
public Block createNextBlockWithCoinbase(byte[] pubKey, BigInteger coinbaseValue) {
return createNextBlock(null, null, Utils.now().getTime() / 1000, pubKey, coinbaseValue);
}
/**
* Create a block sending 50BTC as a coinbase transaction to the public key specified.
* This method is intended for test use only.
*/
@VisibleForTesting
Block createNextBlockWithCoinbase(byte[] pubKey) {
return createNextBlock(null, null, Utils.now().getTime() / 1000, pubKey, Utils.toNanoCoins(50, 0));
}
@VisibleForTesting
boolean isParsedHeader() {
return headerParsed;
}
@VisibleForTesting
boolean isParsedTransactions() {
return transactionsParsed;
}
@VisibleForTesting
boolean isHeaderBytesValid() {
return headerBytesValid;
}
@VisibleForTesting
boolean isTransactionBytesValid() {
return transactionBytesValid;
}
}
|
Reverting block calc changes
|
core/src/main/java/com/google/litecoin/core/Block.java
|
Reverting block calc changes
|
<ide><path>ore/src/main/java/com/google/litecoin/core/Block.java
<ide> }
<ide> }
<ide> private Sha256Hash calculateScryptHash() {
<del>
<ide> try {
<ide> ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(HEADER_SIZE);
<ide> writeHeader(bos);
<ide> } catch (IOException e) {
<ide> throw new RuntimeException(e); // Cannot happen.
<ide> }
<del>
<ide> }
<ide>
<ide> /**
<ide> if (!(o instanceof Block))
<ide> return false;
<ide> Block other = (Block) o;
<del> return getScryptHash().equals(other.getScryptHash());
<add> return getHash().equals(other.getHash());
<ide> }
<ide>
<ide> @Override
<ide> public int hashCode() {
<del> return getScryptHash().hashCode();
<add> return getHash().hashCode();
<ide> }
<ide>
<ide> /**
<ide> b.addTransaction(t);
<ide> }
<ide>
<del> b.setPrevBlockHash(getScryptHash());
<add> b.setPrevBlockHash(getHash());
<ide> // Don't let timestamp go backwards
<ide> if (getTimeSeconds() >= time)
<ide> b.setTime(getTimeSeconds() + 1);
|
|
Java
|
apache-2.0
|
a20567405c8c69b5c3233ce38328c7f9cfe431e1
| 0 |
m21077319/test01ap01,m21077319/test01ap01,m21077319/test01ap01
|
package jp.co.exacorp.matchingapp.logic;
import java.util.Map;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;
import jp.co.exacorp.matchingapp.beans.DFLItemInfo;
import jp.co.exacorp.matchingapp.beans.PsychologicalTest;
import jp.co.exacorp.matchingapp.beans.QueryMapBean;
import jp.co.exacorp.matchingapp.logic.api.NLCContact;
import jp.co.exacorp.matchingapp.logic.api.PersonalityInsightsContact;
import jp.co.exacorp.matchingapp.util.Constants;
import jp.co.exacorp.matchingapp.util.DFLConstants;
import jp.co.exacorp.matchingapp.util.LINEConstants;
import jp.co.exacorp.matchingapp.util.MessageAPIUtil;
import jp.co.exacorp.matchingapp.util.MessageAPIforDFLUtil;
@Stateless
public class DFLRecommendItem {
private static final String ITEM = "item";
private static final String ITEM_SELECT_BEFORE = "itemSelectBefore";
private static final String ITEM_SELECT = "itemSelect";
// private static final String SELECT_ITEM_EXPLANATION = "おすすめのプラン";
private static final String SELECT_PLAN_EXPLANATION = "おすすめのプラン";
private static final String SELECT_PLAN1_EXPLANATION = "備前焼体験";
private static final String SELECT_NEWS1_EXPLANATION = "観光ニュース";
private static final String SELECT_NEWS2_EXPLANATION = "観光ニュースつづき";
private static final String ITEM_EXPLANATION = "itemExplanation";
private static final String END = "もういいや";
private static final String UNRELATED = "unrelated";
private static final String NO_TEXT = "noText";
private static final String OTHERS_ITEM = "他のプランをおすすめして!";
private static final String RECOMMEND = "recommend";
private static final String RECOMMEND_BEFORE = "recommendBefore";
private static final String RECOMMEND_OK = "recommendOk";
private static final String RECOMMEND_END = "recommendEnd";
private static final String PI_OK = "piOk";
private static final String SELECT_RECOMMEND = "レコメンド";
private static final String Q_NUM = "qNum";
private static final String Q = "question";
private static final String A1 = "answer1";
private static final String A2 = "answer2";
private static final String A3 = "answer3";
private static final String T1 = "text1";
private static final String T2 = "text2";
private static final String T3 = "text3";
// 質問数を入れる
private static final String Q_NUM_MAX = "2";
private static final String OK = "OK!";
private static final String NG = "うーん";
private static final String ITEM_OK_OR_NG = "itemOKorNG";
@EJB
QueryMapBean qmb;
@EJB
NLCContact nlcc;
@EJB
PersonalityInsightsContact pic;
@EJB
MatchMaker mm;
@EJB
DFLItemInfo dflii;
@EJB
PsychologicalTest pt;
public String teachItem(Map<String, String> eventMap, String imgDir) {
String type = eventMap.get("messageType");
String replyToken = eventMap.get("replyToken");
JsonArrayBuilder mesJab = Json.createArrayBuilder();
boolean flag = false;
System.out.println("---------- Logic Start. ----------");
// ユーザーID取得
String userId = eventMap.get(LINEConstants.USERID);
// qMapにいろいろ持たせちゃう
Map<String, String> qMap = qmb.getQueryMap(userId);
// テキスト取得
String text = eventMap.get(LINEConstants.TEXT);
// おすすめプラン押下
if (text.equals(SELECT_PLAN_EXPLANATION)) {
mesJab.add(MessageAPIUtil.giveMessage("お好みのプランを選んでください"));
// カルーセルでプラン表示
mesJab.add(makeCarousel5AItem());
} else if (text.equals(SELECT_PLAN1_EXPLANATION)) {
mesJab.add(MessageAPIUtil.giveMessage("シーンを選んでください"));
// カルーセルでスポット表示
mesJab.add(makeCarousel5BItem());
} else if (text.equals(SELECT_NEWS1_EXPLANATION)) {
mesJab.add(MessageAPIUtil.giveMessage("気になるニュースを選んでください"));
// カルーセルでニュース表示
mesJab.add(makeCarousel5CItem());
} else if (text.equals(SELECT_NEWS2_EXPLANATION)) {
mesJab.add(MessageAPIUtil.giveMessage("気になるニュースを選んでください"));
// カルーセルでニュース表示
mesJab.add(makeCarousel2AItem());
}
//
// switch (text) {
// // おすすめプラン押下
// case SELECT_PLAN_EXPLANATION:
// mesJab.add(MessageAPIUtil.giveMessage("お好みのプランを選んでください"));
//
// // カルーセルでプラン表示
// mesJab.add(makeCarousel5AItem());
//
// // おすすめプラン陶芸体験押下
// case SELECT_PLAN1_EXPLANATION:
// mesJab.add(MessageAPIUtil.giveMessage("シーンを選んでください"));
//
// // カルーセルでスポット表示
// mesJab.add(makeCarousel5BItem());
//
// // NEWS1押下
// case SELECT_NEWS1_EXPLANATION:
// mesJab.add(MessageAPIUtil.giveMessage("気になるニュースを選んでください"));
//
// // カルーセルでニュース1表示
// mesJab.add(makeCarousel5CItem());
//
// // NEWS1押下
// case SELECT_NEWS2_EXPLANATION:
// mesJab.add(MessageAPIUtil.giveMessage("気になるニュースを選んでください"));
//
// // カルーセルでニュース2表示
// mesJab.add(makeCarousel2AItem());
// }
// 質問
// NLCにテキスト投げて返ってきた結果を表示させる
// if (!text.equals(SELECT_PLAN_EXPLANATION) &
// !text.equals(SELECT_PLAN1_EXPLANATION)) {
String cid = dflii.getCID(qMap.get(ITEM));
String[] nlcResults = nlcc.getNLCResult(text, cid);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < nlcResults.length; i++) {
if (i == nlcResults.length - 1) {
sb.append(nlcResults[i]);
} else {
// if ("0000001".equals(nlcResults[i]) |
// "0000002".equals(nlcResults[i]) ) {
if ("0000001".equals(nlcResults[i]) &
!text.equals(SELECT_PLAN_EXPLANATION) &
!text.equals(SELECT_PLAN1_EXPLANATION)) {
mesJab.add(makeCarousel1Item());
}
}
}
mesJab.add(MessageAPIUtil.giveMessage(sb.toString()));
// デバッグ用に状態を出力
System.out.println("---------- Logic End. ----------");
return MessageAPIUtil.makeRequestJson(replyToken, mesJab);
}
//}
/** 営業職員さんが扱える三種類のカルーセルを返す */
private JsonObjectBuilder makeCarousel1Item() {
JsonArrayBuilder columns = Json.createArrayBuilder();
JsonArrayBuilder action1 = Json.createArrayBuilder();
JsonObjectBuilder carousel = Json.createObjectBuilder();
action1.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_FIS));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_FIS_IMG,
DFLConstants.PREMIRE_RECEIVE_FIS,
DFLConstants.PREMIRE_RECEIVE_FIS_TXT, action1));
carousel = MessageAPIUtil.giveCarousel("プラン一覧カルーセル", columns);
return carousel;
}
/** おすすめプランのカルーセルを返す */
private JsonObjectBuilder makeCarousel5AItem() {
JsonArrayBuilder columns = Json.createArrayBuilder();
JsonArrayBuilder action1 = Json.createArrayBuilder();
JsonArrayBuilder action2 = Json.createArrayBuilder();
JsonArrayBuilder action3 = Json.createArrayBuilder();
JsonArrayBuilder action4 = Json.createArrayBuilder();
JsonArrayBuilder action5 = Json.createArrayBuilder();
JsonObjectBuilder carousel = Json.createObjectBuilder();
action1.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_PL1));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_PL1_IMG,
DFLConstants.PREMIRE_RECEIVE_PL1,
DFLConstants.PREMIRE_RECEIVE_PL1_TXT, action1));
action2.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_PL2));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_PL2_IMG,
DFLConstants.PREMIRE_RECEIVE_PL2,
DFLConstants.PREMIRE_RECEIVE_PL2_TXT, action2));
action3.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_PL3));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_PL3_IMG,
DFLConstants.PREMIRE_RECEIVE_PL3,
DFLConstants.PREMIRE_RECEIVE_PL3_TXT, action3));
action4.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_PL4));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_PL4_IMG,
DFLConstants.PREMIRE_RECEIVE_PL4,
DFLConstants.PREMIRE_RECEIVE_PL4_TXT, action4));
action5.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_PL5));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_PL5_IMG,
DFLConstants.PREMIRE_RECEIVE_PL5,
DFLConstants.PREMIRE_RECEIVE_PL5_TXT, action5));
carousel = MessageAPIUtil.giveCarousel("プラン一覧カルーセル", columns);
return carousel;
}
/** おすすめプラン備前焼体験のカルーセルを返す */
private JsonObjectBuilder makeCarousel5BItem() {
JsonArrayBuilder columns = Json.createArrayBuilder();
JsonArrayBuilder action1 = Json.createArrayBuilder();
JsonArrayBuilder action2 = Json.createArrayBuilder();
JsonArrayBuilder action3 = Json.createArrayBuilder();
JsonArrayBuilder action4 = Json.createArrayBuilder();
JsonArrayBuilder action5 = Json.createArrayBuilder();
JsonObjectBuilder carousel = Json.createObjectBuilder();
action1.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_PL6));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_PL6_IMG,
DFLConstants.PREMIRE_RECEIVE_PL6,
DFLConstants.PREMIRE_RECEIVE_PL6_TXT, action1));
action2.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_PL7));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_PL7_IMG,
DFLConstants.PREMIRE_RECEIVE_PL7,
DFLConstants.PREMIRE_RECEIVE_PL7_TXT, action2));
action3.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_PL8));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_PL8_IMG,
DFLConstants.PREMIRE_RECEIVE_PL8,
DFLConstants.PREMIRE_RECEIVE_PL8_TXT, action3));
action4.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_PL9));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_PL9_IMG,
DFLConstants.PREMIRE_RECEIVE_PL9,
DFLConstants.PREMIRE_RECEIVE_PL9_TXT, action4));
action5.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_P10));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_P10_IMG,
DFLConstants.PREMIRE_RECEIVE_P10,
DFLConstants.PREMIRE_RECEIVE_P10_TXT, action5));
carousel = MessageAPIUtil.giveCarousel("プラン一覧カルーセル", columns);
return carousel;
}
/** ニュース1のカルーセルを返す */
private JsonObjectBuilder makeCarousel5CItem() {
JsonArrayBuilder columns = Json.createArrayBuilder();
JsonArrayBuilder action1 = Json.createArrayBuilder();
JsonArrayBuilder action2 = Json.createArrayBuilder();
JsonArrayBuilder action3 = Json.createArrayBuilder();
JsonArrayBuilder action4 = Json.createArrayBuilder();
JsonArrayBuilder action5 = Json.createArrayBuilder();
JsonObjectBuilder carousel = Json.createObjectBuilder();
action1.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_NEWS_001));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_NEWS_001_IMG,
DFLConstants.PREMIRE_NEWS_001,
DFLConstants.PREMIRE_NEWS_001_TXT, action1));
action2.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_NEWS_002));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_NEWS_002_IMG,
DFLConstants.PREMIRE_NEWS_002,
DFLConstants.PREMIRE_NEWS_002_TXT, action2));
action3.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_NEWS_003));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_NEWS_003_IMG,
DFLConstants.PREMIRE_NEWS_003,
DFLConstants.PREMIRE_NEWS_003_TXT, action3));
action4.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_NEWS_004));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_NEWS_004_IMG,
DFLConstants.PREMIRE_NEWS_004,
DFLConstants.PREMIRE_NEWS_004_TXT, action4));
action5.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_NEWS_005));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_NEWS_005_IMG,
DFLConstants.PREMIRE_NEWS_005,
DFLConstants.PREMIRE_NEWS_005_TXT, action5));
carousel = MessageAPIUtil.giveCarousel("プラン一覧カルーセル", columns);
return carousel;
}
/** ニュース2のカルーセルを返す */
private JsonObjectBuilder makeCarousel2AItem() {
JsonArrayBuilder columns = Json.createArrayBuilder();
JsonArrayBuilder action1 = Json.createArrayBuilder();
JsonArrayBuilder action2 = Json.createArrayBuilder();
JsonObjectBuilder carousel = Json.createObjectBuilder();
action1.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_NEWS_006));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_NEWS_006_IMG,
DFLConstants.PREMIRE_NEWS_006,
DFLConstants.PREMIRE_NEWS_006_TXT, action1));
action2.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_NEWS_007));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_NEWS_007_IMG,
DFLConstants.PREMIRE_NEWS_007,
DFLConstants.PREMIRE_NEWS_007_TXT, action2));
carousel = MessageAPIUtil.giveCarousel("プラン一覧カルーセル", columns);
return carousel;
}
/** 営業職員さんが扱える三種類のカルーセルを返す */
private JsonObjectBuilder makeCarousel5Item() {
JsonArrayBuilder columns = Json.createArrayBuilder();
JsonArrayBuilder action1 = Json.createArrayBuilder();
JsonArrayBuilder action2 = Json.createArrayBuilder();
JsonArrayBuilder action3 = Json.createArrayBuilder();
JsonArrayBuilder action4 = Json.createArrayBuilder();
JsonArrayBuilder action5 = Json.createArrayBuilder();
JsonObjectBuilder carousel = Json.createObjectBuilder();
action1.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_GLB));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_GLB_IMG,
DFLConstants.PREMIRE_RECEIVE_GLB,
DFLConstants.PREMIRE_RECEIVE_GLB_TXT, action1));
action2.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_GLB));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_GLB_IMG,
DFLConstants.PREMIRE_RECEIVE_GLB,
DFLConstants.PREMIRE_RECEIVE_GLB_TXT, action2));
action3.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_GLB));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_GLB_IMG,
DFLConstants.PREMIRE_RECEIVE_GLB,
DFLConstants.PREMIRE_RECEIVE_GLB_TXT, action3));
action4.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_GLB));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_GLB_IMG,
DFLConstants.PREMIRE_RECEIVE_GLB,
DFLConstants.PREMIRE_RECEIVE_GLB_TXT, action4));
action5.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_GLB));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_GLB_IMG,
DFLConstants.PREMIRE_RECEIVE_GLB,
DFLConstants.PREMIRE_RECEIVE_GLB_TXT, action5));
carousel = MessageAPIUtil.giveCarousel("プラン一覧カルーセル", columns);
return carousel;
}
}
////追加 END
//
// /** 営業職員さんが扱える三種類のカルーセルを返す */
// private JsonObjectBuilder makeCarousel3Item() {
// JsonArrayBuilder columns = Json.createArrayBuilder();
// JsonArrayBuilder actionA = Json.createArrayBuilder();
// JsonArrayBuilder actionB = Json.createArrayBuilder();
// JsonArrayBuilder actionC = Json.createArrayBuilder();
// JsonObjectBuilder carousel = Json.createObjectBuilder();
//
// actionA.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
// DFLConstants.PREMIRE_RECEIVE_GLB));
// columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
// + DFLConstants.PREMIRE_RECEIVE_GLB_IMG,
// DFLConstants.PREMIRE_RECEIVE_GLB,
// DFLConstants.PREMIRE_RECEIVE_GLB_TXT, actionA));
//
// actionB.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
// DFLConstants.PREMIRE_CURRENCY_PLUS2));
// columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
// + DFLConstants.PREMIRE_CURRENCY_PLUS2_IMG,
// DFLConstants.PREMIRE_CURRENCY_PLUS2,
// DFLConstants.PREMIRE_CURRENCY_PLUS2_TXT, actionB));
//
// actionC.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
// DFLConstants.PREMIRE_STORY));
// columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
// + DFLConstants.PREMIRE_STORY_IMG, DFLConstants.PREMIRE_STORY,
// DFLConstants.PREMIRE_STORY_TXT, actionC));
//
// carousel = MessageAPIUtil.giveCarousel("プラン一覧カルーセル", columns);
//
// return carousel;
// }
//
// public static void callMatchMaker(String userId, String query,
// String imgDir, JsonArrayBuilder mesJab) {
// List<Map<String, String>> resultList = MessageAPIforDFLUtil.mm
// .actMatchMaker(userId, query, imgDir);
// mesJab.add(MessageAPIUtil.giveMessage("君におすすめのプランはコレ!"));
// mesJab.add(MessageAPIUtil.giveMessage("「相談する」をタップすると君と私と選んだアドバイザーさんの"
// + "LINEグループを作成するよ!"));
// mesJab.add(MessageAPIforDFLUtil.giveCarouselRecommend(resultList));
// }
//}
|
src/main/java/jp/co/exacorp/matchingapp/logic/DFLRecommendItem.java
|
package jp.co.exacorp.matchingapp.logic;
import java.util.Map;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;
import jp.co.exacorp.matchingapp.beans.DFLItemInfo;
import jp.co.exacorp.matchingapp.beans.PsychologicalTest;
import jp.co.exacorp.matchingapp.beans.QueryMapBean;
import jp.co.exacorp.matchingapp.logic.api.NLCContact;
import jp.co.exacorp.matchingapp.logic.api.PersonalityInsightsContact;
import jp.co.exacorp.matchingapp.util.Constants;
import jp.co.exacorp.matchingapp.util.DFLConstants;
import jp.co.exacorp.matchingapp.util.LINEConstants;
import jp.co.exacorp.matchingapp.util.MessageAPIUtil;
import jp.co.exacorp.matchingapp.util.MessageAPIforDFLUtil;
@Stateless
public class DFLRecommendItem {
private static final String ITEM = "item";
private static final String ITEM_SELECT_BEFORE = "itemSelectBefore";
private static final String ITEM_SELECT = "itemSelect";
// private static final String SELECT_ITEM_EXPLANATION = "おすすめのプラン";
private static final String SELECT_PLAN_EXPLANATION = "おすすめのプラン";
private static final String SELECT_PLAN1_EXPLANATION = "備前焼体験";
private static final String SELECT_NEWS1_EXPLANATION = "観光ニュース";
private static final String SELECT_NEWS2_EXPLANATION = "観光ニュースつづき";
private static final String ITEM_EXPLANATION = "itemExplanation";
private static final String END = "もういいや";
private static final String UNRELATED = "unrelated";
private static final String NO_TEXT = "noText";
private static final String OTHERS_ITEM = "他のプランをおすすめして!";
private static final String RECOMMEND = "recommend";
private static final String RECOMMEND_BEFORE = "recommendBefore";
private static final String RECOMMEND_OK = "recommendOk";
private static final String RECOMMEND_END = "recommendEnd";
private static final String PI_OK = "piOk";
private static final String SELECT_RECOMMEND = "レコメンド";
private static final String Q_NUM = "qNum";
private static final String Q = "question";
private static final String A1 = "answer1";
private static final String A2 = "answer2";
private static final String A3 = "answer3";
private static final String T1 = "text1";
private static final String T2 = "text2";
private static final String T3 = "text3";
// 質問数を入れる
private static final String Q_NUM_MAX = "2";
private static final String OK = "OK!";
private static final String NG = "うーん";
private static final String ITEM_OK_OR_NG = "itemOKorNG";
@EJB
QueryMapBean qmb;
@EJB
NLCContact nlcc;
@EJB
PersonalityInsightsContact pic;
@EJB
MatchMaker mm;
@EJB
DFLItemInfo dflii;
@EJB
PsychologicalTest pt;
public String teachItem(Map<String, String> eventMap, String imgDir) {
String type = eventMap.get("messageType");
String replyToken = eventMap.get("replyToken");
JsonArrayBuilder mesJab = Json.createArrayBuilder();
boolean flag = false;
System.out.println("---------- Logic Start. ----------");
// ユーザーID取得
String userId = eventMap.get(LINEConstants.USERID);
// qMapにいろいろ持たせちゃう
Map<String, String> qMap = qmb.getQueryMap(userId);
// テキスト取得
String text = eventMap.get(LINEConstants.TEXT);
// // おすすめプラン押下
// if (text.equals(SELECT_PLAN_EXPLANATION)) {
// mesJab.add(MessageAPIUtil.giveMessage("お好みのプランを選んでください"));
//
// // カルーセルで商品表示
// mesJab.add(makeCarousel5AItem());
//
// } else {
// // おすすめプラン陶芸体験押下
// if (text.equals(SELECT_PLAN1_EXPLANATION)) {
// mesJab.add(MessageAPIUtil.giveMessage("シーンを選んでください"));
//
// // カルーセルで商品表示
// mesJab.add(makeCarousel5BItem());
// }else {
// // 観光ニュース
// if (text.equals(SELECT_NEWS1_EXPLANATION)) {
// mesJab.add(MessageAPIUtil.giveMessage("気になるニュースを選んでください"));
//
// // カルーセルで商品表示
// mesJab.add(makeCarousel5CItem());
// }else {
// // 観光ニュース2
// if (text.equals(SELECT_NEWS2_EXPLANATION)) {
// mesJab.add(MessageAPIUtil.giveMessage("気になるニュースを選んでください"));
//
// // カルーセルで商品表示
// mesJab.add(makeCarousel5CItem());
// }
// }
// }
switch (text) {
// おすすめプラン押下
case SELECT_PLAN_EXPLANATION:
mesJab.add(MessageAPIUtil.giveMessage("お好みのプランを選んでください"));
// カルーセルでプラン表示
mesJab.add(makeCarousel5AItem());
// おすすめプラン陶芸体験押下
case SELECT_PLAN1_EXPLANATION:
mesJab.add(MessageAPIUtil.giveMessage("シーンを選んでください"));
// カルーセルでスポット表示
mesJab.add(makeCarousel5BItem());
// NEWS1押下
case SELECT_NEWS1_EXPLANATION:
mesJab.add(MessageAPIUtil.giveMessage("気になるニュースを選んでください"));
// カルーセルでニュース1表示
mesJab.add(makeCarousel5CItem());
// NEWS1押下
case SELECT_NEWS2_EXPLANATION:
mesJab.add(MessageAPIUtil.giveMessage("気になるニュースを選んでください"));
// カルーセルでニュース2表示
mesJab.add(makeCarousel2AItem());
}
// 質問
// NLCにテキスト投げて返ってきた結果を表示させる
// if (!text.equals(SELECT_PLAN_EXPLANATION) &
// !text.equals(SELECT_PLAN1_EXPLANATION)) {
String cid = dflii.getCID(qMap.get(ITEM));
String[] nlcResults = nlcc.getNLCResult(text, cid);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < nlcResults.length; i++) {
if (i == nlcResults.length - 1) {
sb.append(nlcResults[i]);
} else {
// if ("0000001".equals(nlcResults[i]) |
// "0000002".equals(nlcResults[i]) ) {
if ("0000001".equals(nlcResults[i]) &
!text.equals(SELECT_PLAN_EXPLANATION) &
!text.equals(SELECT_PLAN1_EXPLANATION)) {
mesJab.add(makeCarousel1Item());
}
}
}
mesJab.add(MessageAPIUtil.giveMessage(sb.toString()));
// デバッグ用に状態を出力
System.out.println("---------- Logic End. ----------");
return MessageAPIUtil.makeRequestJson(replyToken, mesJab);
}
//}
/** 営業職員さんが扱える三種類のカルーセルを返す */
private JsonObjectBuilder makeCarousel1Item() {
JsonArrayBuilder columns = Json.createArrayBuilder();
JsonArrayBuilder action1 = Json.createArrayBuilder();
JsonObjectBuilder carousel = Json.createObjectBuilder();
action1.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_FIS));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_FIS_IMG,
DFLConstants.PREMIRE_RECEIVE_FIS,
DFLConstants.PREMIRE_RECEIVE_FIS_TXT, action1));
carousel = MessageAPIUtil.giveCarousel("プラン一覧カルーセル", columns);
return carousel;
}
/** おすすめプランのカルーセルを返す */
private JsonObjectBuilder makeCarousel5AItem() {
JsonArrayBuilder columns = Json.createArrayBuilder();
JsonArrayBuilder action1 = Json.createArrayBuilder();
JsonArrayBuilder action2 = Json.createArrayBuilder();
JsonArrayBuilder action3 = Json.createArrayBuilder();
JsonArrayBuilder action4 = Json.createArrayBuilder();
JsonArrayBuilder action5 = Json.createArrayBuilder();
JsonObjectBuilder carousel = Json.createObjectBuilder();
action1.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_PL1));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_PL1_IMG,
DFLConstants.PREMIRE_RECEIVE_PL1,
DFLConstants.PREMIRE_RECEIVE_PL1_TXT, action1));
action2.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_PL2));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_PL2_IMG,
DFLConstants.PREMIRE_RECEIVE_PL2,
DFLConstants.PREMIRE_RECEIVE_PL2_TXT, action2));
action3.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_PL3));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_PL3_IMG,
DFLConstants.PREMIRE_RECEIVE_PL3,
DFLConstants.PREMIRE_RECEIVE_PL3_TXT, action3));
action4.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_PL4));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_PL4_IMG,
DFLConstants.PREMIRE_RECEIVE_PL4,
DFLConstants.PREMIRE_RECEIVE_PL4_TXT, action4));
action5.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_PL5));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_PL5_IMG,
DFLConstants.PREMIRE_RECEIVE_PL5,
DFLConstants.PREMIRE_RECEIVE_PL5_TXT, action5));
carousel = MessageAPIUtil.giveCarousel("プラン一覧カルーセル", columns);
return carousel;
}
/** おすすめプラン備前焼体験のカルーセルを返す */
private JsonObjectBuilder makeCarousel5BItem() {
JsonArrayBuilder columns = Json.createArrayBuilder();
JsonArrayBuilder action1 = Json.createArrayBuilder();
JsonArrayBuilder action2 = Json.createArrayBuilder();
JsonArrayBuilder action3 = Json.createArrayBuilder();
JsonArrayBuilder action4 = Json.createArrayBuilder();
JsonArrayBuilder action5 = Json.createArrayBuilder();
JsonObjectBuilder carousel = Json.createObjectBuilder();
action1.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_PL6));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_PL6_IMG,
DFLConstants.PREMIRE_RECEIVE_PL6,
DFLConstants.PREMIRE_RECEIVE_PL6_TXT, action1));
action2.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_PL7));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_PL7_IMG,
DFLConstants.PREMIRE_RECEIVE_PL7,
DFLConstants.PREMIRE_RECEIVE_PL7_TXT, action2));
action3.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_PL8));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_PL8_IMG,
DFLConstants.PREMIRE_RECEIVE_PL8,
DFLConstants.PREMIRE_RECEIVE_PL8_TXT, action3));
action4.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_PL9));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_PL9_IMG,
DFLConstants.PREMIRE_RECEIVE_PL9,
DFLConstants.PREMIRE_RECEIVE_PL9_TXT, action4));
action5.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_P10));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_P10_IMG,
DFLConstants.PREMIRE_RECEIVE_P10,
DFLConstants.PREMIRE_RECEIVE_P10_TXT, action5));
carousel = MessageAPIUtil.giveCarousel("プラン一覧カルーセル", columns);
return carousel;
}
/** ニュース1のカルーセルを返す */
private JsonObjectBuilder makeCarousel5CItem() {
JsonArrayBuilder columns = Json.createArrayBuilder();
JsonArrayBuilder action1 = Json.createArrayBuilder();
JsonArrayBuilder action2 = Json.createArrayBuilder();
JsonArrayBuilder action3 = Json.createArrayBuilder();
JsonArrayBuilder action4 = Json.createArrayBuilder();
JsonArrayBuilder action5 = Json.createArrayBuilder();
JsonObjectBuilder carousel = Json.createObjectBuilder();
action1.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_NEWS_001));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_NEWS_001_IMG,
DFLConstants.PREMIRE_NEWS_001,
DFLConstants.PREMIRE_NEWS_001_TXT, action1));
action2.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_NEWS_002));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_NEWS_002_IMG,
DFLConstants.PREMIRE_NEWS_002,
DFLConstants.PREMIRE_NEWS_002_TXT, action2));
action3.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_NEWS_003));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_NEWS_003_IMG,
DFLConstants.PREMIRE_NEWS_003,
DFLConstants.PREMIRE_NEWS_003_TXT, action3));
action4.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_NEWS_004));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_NEWS_004_IMG,
DFLConstants.PREMIRE_NEWS_004,
DFLConstants.PREMIRE_NEWS_004_TXT, action4));
action5.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_NEWS_005));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_NEWS_005_IMG,
DFLConstants.PREMIRE_NEWS_005,
DFLConstants.PREMIRE_NEWS_005_TXT, action5));
carousel = MessageAPIUtil.giveCarousel("プラン一覧カルーセル", columns);
return carousel;
}
/** ニュース2のカルーセルを返す */
private JsonObjectBuilder makeCarousel2AItem() {
JsonArrayBuilder columns = Json.createArrayBuilder();
JsonArrayBuilder action1 = Json.createArrayBuilder();
JsonArrayBuilder action2 = Json.createArrayBuilder();
JsonObjectBuilder carousel = Json.createObjectBuilder();
action1.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_NEWS_006));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_NEWS_006_IMG,
DFLConstants.PREMIRE_NEWS_006,
DFLConstants.PREMIRE_NEWS_006_TXT, action1));
action2.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_NEWS_007));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_NEWS_007_IMG,
DFLConstants.PREMIRE_NEWS_007,
DFLConstants.PREMIRE_NEWS_007_TXT, action2));
carousel = MessageAPIUtil.giveCarousel("プラン一覧カルーセル", columns);
return carousel;
}
/** 営業職員さんが扱える三種類のカルーセルを返す */
private JsonObjectBuilder makeCarousel5Item() {
JsonArrayBuilder columns = Json.createArrayBuilder();
JsonArrayBuilder action1 = Json.createArrayBuilder();
JsonArrayBuilder action2 = Json.createArrayBuilder();
JsonArrayBuilder action3 = Json.createArrayBuilder();
JsonArrayBuilder action4 = Json.createArrayBuilder();
JsonArrayBuilder action5 = Json.createArrayBuilder();
JsonObjectBuilder carousel = Json.createObjectBuilder();
action1.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_GLB));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_GLB_IMG,
DFLConstants.PREMIRE_RECEIVE_GLB,
DFLConstants.PREMIRE_RECEIVE_GLB_TXT, action1));
action2.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_GLB));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_GLB_IMG,
DFLConstants.PREMIRE_RECEIVE_GLB,
DFLConstants.PREMIRE_RECEIVE_GLB_TXT, action2));
action3.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_GLB));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_GLB_IMG,
DFLConstants.PREMIRE_RECEIVE_GLB,
DFLConstants.PREMIRE_RECEIVE_GLB_TXT, action3));
action4.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_GLB));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_GLB_IMG,
DFLConstants.PREMIRE_RECEIVE_GLB,
DFLConstants.PREMIRE_RECEIVE_GLB_TXT, action4));
action5.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
DFLConstants.PREMIRE_RECEIVE_GLB));
columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
+ DFLConstants.PREMIRE_RECEIVE_GLB_IMG,
DFLConstants.PREMIRE_RECEIVE_GLB,
DFLConstants.PREMIRE_RECEIVE_GLB_TXT, action5));
carousel = MessageAPIUtil.giveCarousel("プラン一覧カルーセル", columns);
return carousel;
}
}
////追加 END
//
// /** 営業職員さんが扱える三種類のカルーセルを返す */
// private JsonObjectBuilder makeCarousel3Item() {
// JsonArrayBuilder columns = Json.createArrayBuilder();
// JsonArrayBuilder actionA = Json.createArrayBuilder();
// JsonArrayBuilder actionB = Json.createArrayBuilder();
// JsonArrayBuilder actionC = Json.createArrayBuilder();
// JsonObjectBuilder carousel = Json.createObjectBuilder();
//
// actionA.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
// DFLConstants.PREMIRE_RECEIVE_GLB));
// columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
// + DFLConstants.PREMIRE_RECEIVE_GLB_IMG,
// DFLConstants.PREMIRE_RECEIVE_GLB,
// DFLConstants.PREMIRE_RECEIVE_GLB_TXT, actionA));
//
// actionB.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
// DFLConstants.PREMIRE_CURRENCY_PLUS2));
// columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
// + DFLConstants.PREMIRE_CURRENCY_PLUS2_IMG,
// DFLConstants.PREMIRE_CURRENCY_PLUS2,
// DFLConstants.PREMIRE_CURRENCY_PLUS2_TXT, actionB));
//
// actionC.add(MessageAPIforDFLUtil.giveMes4Actions("これにする",
// DFLConstants.PREMIRE_STORY));
// columns.add(MessageAPIUtil.giveColumns4Carousel(Constants.IMG_URL
// + DFLConstants.PREMIRE_STORY_IMG, DFLConstants.PREMIRE_STORY,
// DFLConstants.PREMIRE_STORY_TXT, actionC));
//
// carousel = MessageAPIUtil.giveCarousel("プラン一覧カルーセル", columns);
//
// return carousel;
// }
//
// public static void callMatchMaker(String userId, String query,
// String imgDir, JsonArrayBuilder mesJab) {
// List<Map<String, String>> resultList = MessageAPIforDFLUtil.mm
// .actMatchMaker(userId, query, imgDir);
// mesJab.add(MessageAPIUtil.giveMessage("君におすすめのプランはコレ!"));
// mesJab.add(MessageAPIUtil.giveMessage("「相談する」をタップすると君と私と選んだアドバイザーさんの"
// + "LINEグループを作成するよ!"));
// mesJab.add(MessageAPIforDFLUtil.giveCarouselRecommend(resultList));
// }
//}
|
TEST201705331_02
|
src/main/java/jp/co/exacorp/matchingapp/logic/DFLRecommendItem.java
|
TEST201705331_02
|
<ide><path>rc/main/java/jp/co/exacorp/matchingapp/logic/DFLRecommendItem.java
<ide> // テキスト取得
<ide> String text = eventMap.get(LINEConstants.TEXT);
<ide>
<add> // おすすめプラン押下
<add> if (text.equals(SELECT_PLAN_EXPLANATION)) {
<add> mesJab.add(MessageAPIUtil.giveMessage("お好みのプランを選んでください"));
<add>
<add> // カルーセルでプラン表示
<add> mesJab.add(makeCarousel5AItem());
<add>
<add> } else if (text.equals(SELECT_PLAN1_EXPLANATION)) {
<add> mesJab.add(MessageAPIUtil.giveMessage("シーンを選んでください"));
<add>
<add> // カルーセルでスポット表示
<add> mesJab.add(makeCarousel5BItem());
<add> } else if (text.equals(SELECT_NEWS1_EXPLANATION)) {
<add> mesJab.add(MessageAPIUtil.giveMessage("気になるニュースを選んでください"));
<add>
<add> // カルーセルでニュース表示
<add> mesJab.add(makeCarousel5CItem());
<add> } else if (text.equals(SELECT_NEWS2_EXPLANATION)) {
<add> mesJab.add(MessageAPIUtil.giveMessage("気になるニュースを選んでください"));
<add>
<add> // カルーセルでニュース表示
<add> mesJab.add(makeCarousel2AItem());
<add> }
<add>
<add>//
<add>// switch (text) {
<ide> // // おすすめプラン押下
<del>// if (text.equals(SELECT_PLAN_EXPLANATION)) {
<del>// mesJab.add(MessageAPIUtil.giveMessage("お好みのプランを選んでください"));
<del>//
<del>// // カルーセルで商品表示
<del>// mesJab.add(makeCarousel5AItem());
<del>//
<del>// } else {
<add>// case SELECT_PLAN_EXPLANATION:
<add>// mesJab.add(MessageAPIUtil.giveMessage("お好みのプランを選んでください"));
<add>//
<add>// // カルーセルでプラン表示
<add>// mesJab.add(makeCarousel5AItem());
<add>//
<ide> // // おすすめプラン陶芸体験押下
<del>// if (text.equals(SELECT_PLAN1_EXPLANATION)) {
<del>// mesJab.add(MessageAPIUtil.giveMessage("シーンを選んでください"));
<del>//
<del>// // カルーセルで商品表示
<del>// mesJab.add(makeCarousel5BItem());
<del>// }else {
<del>// // 観光ニュース
<del>// if (text.equals(SELECT_NEWS1_EXPLANATION)) {
<del>// mesJab.add(MessageAPIUtil.giveMessage("気になるニュースを選んでください"));
<del>//
<del>// // カルーセルで商品表示
<del>// mesJab.add(makeCarousel5CItem());
<del>// }else {
<del>// // 観光ニュース2
<del>// if (text.equals(SELECT_NEWS2_EXPLANATION)) {
<del>// mesJab.add(MessageAPIUtil.giveMessage("気になるニュースを選んでください"));
<del>//
<del>// // カルーセルで商品表示
<del>// mesJab.add(makeCarousel5CItem());
<del>// }
<del>// }
<del>// }
<del>
<del>
<del> switch (text) {
<del> // おすすめプラン押下
<del> case SELECT_PLAN_EXPLANATION:
<del> mesJab.add(MessageAPIUtil.giveMessage("お好みのプランを選んでください"));
<del>
<del> // カルーセルでプラン表示
<del> mesJab.add(makeCarousel5AItem());
<del>
<del> // おすすめプラン陶芸体験押下
<del> case SELECT_PLAN1_EXPLANATION:
<del> mesJab.add(MessageAPIUtil.giveMessage("シーンを選んでください"));
<del>
<del> // カルーセルでスポット表示
<del> mesJab.add(makeCarousel5BItem());
<del>
<del> // NEWS1押下
<del> case SELECT_NEWS1_EXPLANATION:
<del> mesJab.add(MessageAPIUtil.giveMessage("気になるニュースを選んでください"));
<del>
<del> // カルーセルでニュース1表示
<del> mesJab.add(makeCarousel5CItem());
<del>
<del> // NEWS1押下
<del> case SELECT_NEWS2_EXPLANATION:
<del> mesJab.add(MessageAPIUtil.giveMessage("気になるニュースを選んでください"));
<del>
<del> // カルーセルでニュース2表示
<del> mesJab.add(makeCarousel2AItem());
<del> }
<add>// case SELECT_PLAN1_EXPLANATION:
<add>// mesJab.add(MessageAPIUtil.giveMessage("シーンを選んでください"));
<add>//
<add>// // カルーセルでスポット表示
<add>// mesJab.add(makeCarousel5BItem());
<add>//
<add>// // NEWS1押下
<add>// case SELECT_NEWS1_EXPLANATION:
<add>// mesJab.add(MessageAPIUtil.giveMessage("気になるニュースを選んでください"));
<add>//
<add>// // カルーセルでニュース1表示
<add>// mesJab.add(makeCarousel5CItem());
<add>//
<add>// // NEWS1押下
<add>// case SELECT_NEWS2_EXPLANATION:
<add>// mesJab.add(MessageAPIUtil.giveMessage("気になるニュースを選んでください"));
<add>//
<add>// // カルーセルでニュース2表示
<add>// mesJab.add(makeCarousel2AItem());
<add>// }
<ide>
<ide>
<ide> // 質問
|
|
JavaScript
|
unlicense
|
f235339432a07aa3c856fc8342cfc3f0f1a69e6f
| 0 |
Humanise/hui,Humanise/hui,Humanise/hui,Humanise/hui,Humanise/hui,Humanise/hui,Humanise/hui
|
/**
* @constructor
* @param {Object} options The options : {modal:false}
*/
hui.ui.Box = function(options) {
this.options = hui.override({},options);
this.name = options.name;
this.element = hui.get(options.element);
this.body = hui.get.firstByClass(this.element,'hui_box_body');
this.close = hui.get.firstByClass(this.element,'hui_box_close');
this.visible = !this.options.absolute;
if (this.close) {
hui.listen(this.close,'click',this._close.bind(this));
}
hui.ui.extend(this);
};
/**
* Creates a new box widget
* @param {Object} options The options : {width:0,padding:0,absolute:false,closable:false}
*/
hui.ui.Box.create = function(options) {
options = options || {};
options.element = hui.build('div',{
'class' : options.absolute ? 'hui_box hui_box_absolute' : 'hui_box',
html : (options.closable ? '<a class="hui_box_close" href="#"></a>' : '')+
'<div class="hui_box_top"><div><div></div></div></div>'+
'<div class="hui_box_middle"><div class="hui_box_middle">'+
(options.title ? '<div class="hui_box_header"><strong class="hui_box_title">'+hui.string.escape(hui.ui.getTranslated(options.title))+'</strong></div>' : '')+
'<div class="hui_box_body" style="'+
(options.padding ? 'padding: '+options.padding+'px;' : '')+
(options.width ? 'width: '+options.width+'px;' : '')+
'"></div>'+
'</div></div>'+
'<div class="hui_box_bottom"><div><div></div></div></div>',
style : options.width ? options.width+'px' : null
});
return new hui.ui.Box(options);
};
hui.ui.Box.prototype = {
_close : function(e) {
hui.stop(e);
this.hide();
this.fire('boxWasClosed'); // Deprecated
this.fire('close');
},
shake : function() {
hui.effect.shake({element:this.element});
},
/**
* Adds the box to the end of the body
*/
addToDocument : function() {
document.body.appendChild(this.element);
},
/**
* Adds a child widget or node
*/
add : function(widget) {
if (widget.getElement) {
this.body.appendChild(widget.getElement());
} else {
this.body.appendChild(widget);
}
},
/**
* Shows the box
*/
show : function() {
var e = this.element;
if (this.options.modal) {
var index = hui.ui.nextPanelIndex();
e.style.zIndex = index+1;
hui.ui.showCurtain({widget:this,zIndex:index});
}
if (this.options.absolute) {
hui.style.set(e,{ display : 'block', visibility : 'hidden' });
var w = e.clientWidth;
var top = (hui.window.getViewHeight() - e.clientHeight) / 2 + hui.window.getScrollTop();
hui.style.set(e,{
marginLeft : (w/-2)+'px',
top : top+'px',
display : 'block',
visibility : 'visible'
});
} else {
e.style.display = 'block';
}
this.visible = true;
hui.ui.callVisible(this);
},
/** If the box is visible */
isVisible : function() {
return this.visible;
},
/** @private */
$$layout : function() {
if (this.options.absolute && this.visible) {
var e = this.element;
var w = e.clientWidth;
var top = (hui.window.getViewHeight()-e.clientHeight)/2+hui.window.getScrollTop();
hui.style.set(e,{'marginLeft':(w/-2)+'px',top:top+'px'});
}
},
/**
* Hides the box
*/
hide : function() {
hui.ui.hideCurtain(this);
this.element.style.display='none';
this.visible = false;
hui.ui.callVisible(this);
},
/** @private */
$curtainWasClicked : function() {
this.fire('boxCurtainWasClicked');
if (this.options.curtainCloses) {
this._close();
}
}
};
|
hui/js/Box.js
|
/**
* @constructor
* @param {Object} options The options : {modal:false}
*/
hui.ui.Box = function(options) {
this.options = hui.override({},options);
this.name = options.name;
this.element = hui.get(options.element);
this.body = hui.get.firstByClass(this.element,'hui_box_body');
this.close = hui.get.firstByClass(this.element,'hui_box_close');
this.visible = !this.options.absolute;
if (this.close) {
hui.listen(this.close,'click',this._close.bind(this));
}
hui.ui.extend(this);
};
/**
* Creates a new box widget
* @param {Object} options The options : {width:0,padding:0,absolute:false,closable:false}
*/
hui.ui.Box.create = function(options) {
options = options || {};
options.element = hui.build('div',{
'class' : options.absolute ? 'hui_box hui_box_absolute' : 'hui_box',
html : (options.closable ? '<a class="hui_box_close" href="#"></a>' : '')+
'<div class="hui_box_top"><div><div></div></div></div>'+
'<div class="hui_box_middle"><div class="hui_box_middle">'+
(options.title ? '<div class="hui_box_header"><strong class="hui_box_title">'+hui.string.escape(hui.ui.getTranslated(options.title))+'</strong></div>' : '')+
'<div class="hui_box_body" style="'+
(options.padding ? 'padding: '+options.padding+'px;' : '')+
(options.width ? 'width: '+options.width+'px;' : '')+
'"></div>'+
'</div></div>'+
'<div class="hui_box_bottom"><div><div></div></div></div>',
style : options.width ? options.width+'px' : null
});
return new hui.ui.Box(options);
};
hui.ui.Box.prototype = {
_close : function(e) {
hui.stop(e);
this.hide();
this.fire('boxWasClosed'); // Deprecated
this.fire('close');
},
shake : function() {
hui.effect.shake({element:this.element});
},
/**
* Adds the box to the end of the body
*/
addToDocument : function() {
document.body.appendChild(this.element);
},
/**
* Adds a child widget or node
*/
add : function(widget) {
if (widget.getElement) {
this.body.appendChild(widget.getElement());
} else {
this.body.appendChild(widget);
}
},
/**
* Shows the box
*/
show : function() {
var e = this.element;
if (this.options.modal) {
var index = hui.ui.nextPanelIndex();
e.style.zIndex = index+1;
hui.ui.showCurtain({widget:this,zIndex:index});
}
if (this.options.absolute) {
hui.style.set(e,{display:'block',visibility:'hidden'});
var w = e.clientWidth;
var top = (hui.window.getViewHeight()-e.clientHeight)/2+hui.window.getScrollTop();
hui.style.set(e,{'marginLeft':(w/-2)+'px',top:top+'px'});
hui.style.set(e,{display:'block',visibility:'visible'});
} else {
e.style.display='block';
}
this.visible = true;
hui.ui.callVisible(this);
},
/** If the box is visible */
isVisible : function() {
return this.visible;
},
/** @private */
$$layout : function() {
if (this.options.absolute && this.visible) {
var e = this.element;
var w = e.clientWidth;
var top = (hui.window.getViewHeight()-e.clientHeight)/2+hui.window.getScrollTop();
hui.style.set(e,{'marginLeft':(w/-2)+'px',top:top+'px'});
}
},
/**
* Hides the box
*/
hide : function() {
hui.ui.hideCurtain(this);
this.element.style.display='none';
this.visible = false;
hui.ui.callVisible(this);
},
/** @private */
$curtainWasClicked : function() {
this.fire('boxCurtainWasClicked');
if (this.options.curtainCloses) {
this._close();
}
}
};
|
Simplified box code
|
hui/js/Box.js
|
Simplified box code
|
<ide><path>ui/js/Box.js
<ide> shake : function() {
<ide> hui.effect.shake({element:this.element});
<ide> },
<del>
<add>
<ide> /**
<ide> * Adds the box to the end of the body
<ide> */
<ide> hui.ui.showCurtain({widget:this,zIndex:index});
<ide> }
<ide> if (this.options.absolute) {
<del> hui.style.set(e,{display:'block',visibility:'hidden'});
<add> hui.style.set(e,{ display : 'block', visibility : 'hidden' });
<ide> var w = e.clientWidth;
<del> var top = (hui.window.getViewHeight()-e.clientHeight)/2+hui.window.getScrollTop();
<del> hui.style.set(e,{'marginLeft':(w/-2)+'px',top:top+'px'});
<del> hui.style.set(e,{display:'block',visibility:'visible'});
<add> var top = (hui.window.getViewHeight() - e.clientHeight) / 2 + hui.window.getScrollTop();
<add> hui.style.set(e,{
<add> marginLeft : (w/-2)+'px',
<add> top : top+'px',
<add> display : 'block',
<add> visibility : 'visible'
<add> });
<ide> } else {
<del> e.style.display='block';
<add> e.style.display = 'block';
<ide> }
<ide> this.visible = true;
<ide> hui.ui.callVisible(this);
|
|
JavaScript
|
mit
|
d25dcae60bf0f529438ef6da89940f84f15d2f5b
| 0 |
atomicjolt/OpenAssessmentsClient,atomicjolt/open_assessments,atomicjolt/open_assessments,atomicjolt/OpenAssessmentsClient,atomicjolt/open_assessments,atomicjolt/OpenAssessmentsClient
|
client/js/middleware/qbank_answers.js
|
import { Constants as AssessmentProgressConstants } from "../actions/assessment_progress";
import callMap from "./qbank";
const QbankAnswers = store => next => action => {
switch(action.type) {
case AssessmentProgressConstants.ASSESSMENT_NEXT_QUESTIONS:
const state = store.getState();
const currentItemIndex = state.progress.get("currentItemIndex");
const questionIndexes = _.range(currentItemIndex, currentItemIndex + action.pageSize);
const checkAction = {
type: AssessmentProgressConstants.ASSESSMENT_CHECK_ANSWER,
questionIds: questionIndexes
}
callMap[AssessmentProgressConstants.ASSESSMENT_NEXT_QUESTIONS](store, checkAction)
break;
}
// call the next middleWare
next(action);
};
export { QbankAnswer as default };
|
Delete unneeded file
|
client/js/middleware/qbank_answers.js
|
Delete unneeded file
|
<ide><path>lient/js/middleware/qbank_answers.js
<del>import { Constants as AssessmentProgressConstants } from "../actions/assessment_progress";
<del>import callMap from "./qbank";
<del>
<del>const QbankAnswers = store => next => action => {
<del>
<del> switch(action.type) {
<del>
<del> case AssessmentProgressConstants.ASSESSMENT_NEXT_QUESTIONS:
<del> const state = store.getState();
<del> const currentItemIndex = state.progress.get("currentItemIndex");
<del> const questionIndexes = _.range(currentItemIndex, currentItemIndex + action.pageSize);
<del>
<del> const checkAction = {
<del> type: AssessmentProgressConstants.ASSESSMENT_CHECK_ANSWER,
<del> questionIds: questionIndexes
<del> }
<del>
<del> callMap[AssessmentProgressConstants.ASSESSMENT_NEXT_QUESTIONS](store, checkAction)
<del> break;
<del> }
<del>
<del> // call the next middleWare
<del> next(action);
<del>
<del>};
<del>
<del>export { QbankAnswer as default };
|
||
Java
|
apache-2.0
|
9b971edb45cf020d6edb3124c9d4b18dd4c8845a
| 0 |
gravitee-io/gravitee-management-rest-api,gravitee-io/gravitee-management-rest-api,gravitee-io/gravitee-management-rest-api
|
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.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.gravitee.management.rest.resource;
import io.gravitee.common.http.MediaType;
import io.gravitee.management.model.*;
import io.gravitee.management.model.permissions.ApiPermission;
import io.gravitee.management.rest.resource.LifecycleActionParam.LifecycleAction;
import io.gravitee.management.rest.security.ApiPermissionsRequired;
import io.gravitee.management.service.ApiService;
import io.gravitee.management.service.exceptions.ApiNotFoundException;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.*;
import javax.ws.rs.container.ResourceContext;
import javax.ws.rs.core.*;
import javax.ws.rs.core.Response.Status;
import java.io.ByteArrayOutputStream;
import static java.lang.String.format;
/**
* Defines the REST resources to manage API.
*
* @author David BRASSELY (brasseld at gmail.com)
*/
public class ApiResource extends AbstractResource {
@Context
private UriInfo uriInfo;
@Context
private ResourceContext resourceContext;
@Inject
private ApiService apiService;
@PathParam("api")
private String api;
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiPermissionsRequired(ApiPermission.READ)
public ApiEntity get() throws ApiNotFoundException {
ApiEntity api = apiService.findById(this.api);
final UriBuilder ub = uriInfo.getAbsolutePathBuilder();
final UriBuilder uriBuilder = ub.path("picture");
if (api.getPicture() != null) {
// force browser to get if updated
uriBuilder.queryParam("hash", api.getPicture().hashCode());
}
api.setPictureUrl(uriBuilder.build().toString());
api.setPicture(null);
setPermission(api);
return api;
}
@GET
@Path("picture")
@ApiPermissionsRequired(ApiPermission.READ)
public Response picture(@Context Request request) throws ApiNotFoundException {
apiService.findById(this.api);
CacheControl cc = new CacheControl();
cc.setNoTransform(true);
cc.setMustRevalidate(false);
cc.setNoCache(false);
cc.setMaxAge(86400);
ImageEntity image = apiService.getPicture(this.api);
EntityTag etag = new EntityTag(Integer.toString(new String(image.getContent()).hashCode()));
Response.ResponseBuilder builder = request.evaluatePreconditions(etag);
if (builder != null) {
// Preconditions are not met, returning HTTP 304 'not-modified'
return builder
.cacheControl(cc)
.build();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(image.getContent(), 0, image.getContent().length);
return Response
.ok()
.entity(baos)
.cacheControl(cc)
.tag(etag)
.type(image.getType())
.build();
}
@POST
@ApiPermissionsRequired(ApiPermission.MANAGE_LIFECYCLE)
public Response doLifecycleAction(@QueryParam("action") LifecycleActionParam action) {
ApiEntity api = apiService.findById(this.api);
switch (action.getAction()) {
case START:
checkAPILifeCycle(api, action.getAction());
apiService.start(api.getId(), getAuthenticatedUsername());
break;
case STOP:
checkAPILifeCycle(api, action.getAction());
apiService.stop(api.getId(), getAuthenticatedUsername());
break;
default:
break;
}
return Response.noContent().build();
}
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiPermissionsRequired(ApiPermission.MANAGE_API)
public ApiEntity update(@Valid @NotNull final UpdateApiEntity api) {
final ApiEntity currentApi = this.get();
// Force context-path if user is not the primary_owner or an administrator
if (currentApi.getPermission() != MembershipType.PRIMARY_OWNER) {
api.getProxy().setContextPath(currentApi.getProxy().getContextPath());
}
final ApiEntity updatedApi = apiService.update(this.api, api);
setPermission(updatedApi);
return updatedApi;
}
@DELETE
@ApiPermissionsRequired(ApiPermission.DELETE)
public Response delete() {
apiService.delete(api);
return Response.noContent().build();
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("deploy")
@ApiPermissionsRequired(ApiPermission.MANAGE_LIFECYCLE)
public Response deployAPI() {
try {
ApiEntity apiEntity = apiService.deploy(api, getAuthenticatedUsername(), EventType.PUBLISH_API);
return Response.status(Status.OK).entity(apiEntity).build();
} catch (Exception e) {
return Response.status(Status.INTERNAL_SERVER_ERROR).entity("JsonProcessingException " + e).build();
}
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("state")
@ApiPermissionsRequired(ApiPermission.MANAGE_LIFECYCLE)
public io.gravitee.management.rest.model.ApiEntity isAPISynchronized() {
io.gravitee.management.rest.model.ApiEntity apiEntity = new io.gravitee.management.rest.model.ApiEntity();
apiEntity.setApiId(this.api);
setSynchronizationState(apiEntity);
return apiEntity;
}
@POST
@Consumes
@Produces(MediaType.APPLICATION_JSON)
@Path("rollback")
@ApiPermissionsRequired(ApiPermission.MANAGE_LIFECYCLE)
public Response rollback(@Valid @NotNull final UpdateApiEntity api) {
try {
ApiEntity apiEntity = apiService.rollback(this.api, api);
return Response.status(Status.OK).entity(apiEntity).build();
} catch (Exception e) {
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e).build();
}
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("import")
@ApiPermissionsRequired(ApiPermission.MANAGE_API)
public Response importDefinition(String apiDefinition) {
final ApiEntity apiEntity = get();
return Response.ok(apiService.createOrUpdateWithDefinition(apiEntity, apiDefinition, getAuthenticatedUsername())).build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("export")
@ApiPermissionsRequired(ApiPermission.MANAGE_API)
public Response exportDefinition() {
final ApiEntity apiEntity = get();
setPermission(apiEntity);
return Response
.ok(apiService.exportAsJson(api, apiEntity.getPermission()))
.header(HttpHeaders.CONTENT_DISPOSITION, format("attachment;filename=%s",getExportFilename(apiEntity)))
.build();
}
@Path("keys")
public ApiKeysResource getApiKeyResource() {
return resourceContext.getResource(ApiKeysResource.class);
}
@Path("members")
public ApiMembersResource getApiMembersResource() {
return resourceContext.getResource(ApiMembersResource.class);
}
@Path("analytics")
public ApiAnalyticsResource getApiAnalyticsResource() {
return resourceContext.getResource(ApiAnalyticsResource.class);
}
@Path("health")
public ApiHealthResource getApiHealthResource() {
return resourceContext.getResource(ApiHealthResource.class);
}
@Path("pages")
public ApiPagesResource getApiPagesResource() {
return resourceContext.getResource(ApiPagesResource.class);
}
@Path("events")
public ApiEventsResource getApiEventsResource() {
return resourceContext.getResource(ApiEventsResource.class);
}
private void setPermission(ApiEntity api) {
if (isAdmin()) {
api.setPermission(MembershipType.PRIMARY_OWNER);
} else if (isAuthenticated()) {
MemberEntity member = apiService.getMember(api.getId(), getAuthenticatedUsername());
if (member != null) {
api.setPermission(member.getType());
} else {
if (api.getVisibility() == Visibility.PUBLIC) {
// If API is public, all users have the user permission
api.setPermission(MembershipType.USER);
}
}
}
}
private void setSynchronizationState(io.gravitee.management.rest.model.ApiEntity apiEntity) {
if (apiService.isAPISynchronized(api)) {
apiEntity.setIsSynchronized(true);
} else {
apiEntity.setIsSynchronized(false);
}
}
private void checkAPILifeCycle(ApiEntity api, LifecycleAction action) {
switch(api.getState()) {
case STARTED:
if (LifecycleAction.START.equals(action)) {
throw new BadRequestException("API is already started");
}
break;
case STOPPED:
if (LifecycleAction.STOP.equals(action)) {
throw new BadRequestException("API is already stopped");
}
break;
default:
break;
}
}
private String getExportFilename(ApiEntity apiEntity) {
return format("%s-%s.json", apiEntity.getName(), apiEntity.getVersion())
.trim()
.toLowerCase()
.replaceAll(" +", " ")
.replaceAll(" ", "-")
.replaceAll("[^\\w\\s\\.]","-")
.replaceAll("-+", "-");
}
}
|
gravitee-management-api-rest/src/main/java/io/gravitee/management/rest/resource/ApiResource.java
|
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.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.gravitee.management.rest.resource;
import io.gravitee.common.http.MediaType;
import io.gravitee.management.model.*;
import io.gravitee.management.model.permissions.ApiPermission;
import io.gravitee.management.rest.resource.LifecycleActionParam.LifecycleAction;
import io.gravitee.management.rest.security.ApiPermissionsRequired;
import io.gravitee.management.service.ApiService;
import io.gravitee.management.service.exceptions.ApiNotFoundException;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.*;
import javax.ws.rs.container.ResourceContext;
import javax.ws.rs.core.*;
import javax.ws.rs.core.Response.Status;
import java.io.ByteArrayOutputStream;
import static java.lang.String.format;
/**
* Defines the REST resources to manage API.
*
* @author David BRASSELY (brasseld at gmail.com)
*/
public class ApiResource extends AbstractResource {
@Context
private UriInfo uriInfo;
@Context
private ResourceContext resourceContext;
@Inject
private ApiService apiService;
@PathParam("api")
private String api;
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiPermissionsRequired(ApiPermission.READ)
public ApiEntity get() throws ApiNotFoundException {
ApiEntity api = apiService.findById(this.api);
final UriBuilder ub = uriInfo.getAbsolutePathBuilder();
final UriBuilder uriBuilder = ub.path("picture");
if (api.getPicture() != null) {
// force browser to get if updated
uriBuilder.queryParam("hash", api.getPicture().hashCode());
}
api.setPictureUrl(uriBuilder.build().toString());
api.setPicture(null);
setPermission(api);
return api;
}
@GET
@Path("picture")
@ApiPermissionsRequired(ApiPermission.READ)
public Response picture(@Context Request request) throws ApiNotFoundException {
apiService.findById(this.api);
CacheControl cc = new CacheControl();
cc.setNoTransform(true);
cc.setMustRevalidate(false);
cc.setNoCache(false);
cc.setMaxAge(86400);
ImageEntity image = apiService.getPicture(this.api);
EntityTag etag = new EntityTag(Integer.toString(new String(image.getContent()).hashCode()));
Response.ResponseBuilder builder = request.evaluatePreconditions(etag);
if (builder != null) {
// Preconditions are not met, returning HTTP 304 'not-modified'
return builder
.cacheControl(cc)
.build();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(image.getContent(), 0, image.getContent().length);
return Response
.ok()
.entity(baos)
.cacheControl(cc)
.tag(etag)
.type(image.getType())
.build();
}
@POST
@ApiPermissionsRequired(ApiPermission.MANAGE_LIFECYCLE)
public Response doLifecycleAction(@QueryParam("action") LifecycleActionParam action) {
ApiEntity api = apiService.findById(this.api);
switch (action.getAction()) {
case START:
checkAPILifeCycle(api, action.getAction());
apiService.start(api.getId(), getAuthenticatedUsername());
break;
case STOP:
checkAPILifeCycle(api, action.getAction());
apiService.stop(api.getId(), getAuthenticatedUsername());
break;
default:
break;
}
return Response.noContent().build();
}
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiPermissionsRequired(ApiPermission.MANAGE_API)
public ApiEntity update(@Valid @NotNull final UpdateApiEntity api) {
final ApiEntity updatedApi = apiService.update(this.api, api);
setPermission(updatedApi);
return updatedApi;
}
@DELETE
@ApiPermissionsRequired(ApiPermission.DELETE)
public Response delete() {
apiService.delete(api);
return Response.noContent().build();
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("deploy")
@ApiPermissionsRequired(ApiPermission.MANAGE_LIFECYCLE)
public Response deployAPI() {
try {
ApiEntity apiEntity = apiService.deploy(api, getAuthenticatedUsername(), EventType.PUBLISH_API);
return Response.status(Status.OK).entity(apiEntity).build();
} catch (Exception e) {
return Response.status(Status.INTERNAL_SERVER_ERROR).entity("JsonProcessingException " + e).build();
}
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("state")
@ApiPermissionsRequired(ApiPermission.MANAGE_LIFECYCLE)
public io.gravitee.management.rest.model.ApiEntity isAPISynchronized() {
io.gravitee.management.rest.model.ApiEntity apiEntity = new io.gravitee.management.rest.model.ApiEntity();
apiEntity.setApiId(this.api);
setSynchronizationState(apiEntity);
return apiEntity;
}
@POST
@Consumes
@Produces(MediaType.APPLICATION_JSON)
@Path("rollback")
@ApiPermissionsRequired(ApiPermission.MANAGE_LIFECYCLE)
public Response rollback(@Valid @NotNull final UpdateApiEntity api) {
try {
ApiEntity apiEntity = apiService.rollback(this.api, api);
return Response.status(Status.OK).entity(apiEntity).build();
} catch (Exception e) {
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e).build();
}
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("import")
@ApiPermissionsRequired(ApiPermission.MANAGE_API)
public Response importDefinition(String apiDefinition) {
final ApiEntity apiEntity = get();
return Response.ok(apiService.createOrUpdateWithDefinition(apiEntity, apiDefinition, getAuthenticatedUsername())).build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("export")
@ApiPermissionsRequired(ApiPermission.MANAGE_API)
public Response exportDefinition() {
final ApiEntity apiEntity = get();
setPermission(apiEntity);
return Response
.ok(apiService.exportAsJson(api, apiEntity.getPermission()))
.header(HttpHeaders.CONTENT_DISPOSITION, format("attachment;filename=%s",getExportFilename(apiEntity)))
.build();
}
@Path("keys")
public ApiKeysResource getApiKeyResource() {
return resourceContext.getResource(ApiKeysResource.class);
}
@Path("members")
public ApiMembersResource getApiMembersResource() {
return resourceContext.getResource(ApiMembersResource.class);
}
@Path("analytics")
public ApiAnalyticsResource getApiAnalyticsResource() {
return resourceContext.getResource(ApiAnalyticsResource.class);
}
@Path("health")
public ApiHealthResource getApiHealthResource() {
return resourceContext.getResource(ApiHealthResource.class);
}
@Path("pages")
public ApiPagesResource getApiPagesResource() {
return resourceContext.getResource(ApiPagesResource.class);
}
@Path("events")
public ApiEventsResource getApiEventsResource() {
return resourceContext.getResource(ApiEventsResource.class);
}
private void setPermission(ApiEntity api) {
if (isAdmin()) {
api.setPermission(MembershipType.PRIMARY_OWNER);
} else if (isAuthenticated()) {
MemberEntity member = apiService.getMember(api.getId(), getAuthenticatedUsername());
if (member != null) {
api.setPermission(member.getType());
} else {
if (api.getVisibility() == Visibility.PUBLIC) {
// If API is public, all users have the user permission
api.setPermission(MembershipType.USER);
}
}
}
}
private void setSynchronizationState(io.gravitee.management.rest.model.ApiEntity apiEntity) {
if (apiService.isAPISynchronized(api)) {
apiEntity.setIsSynchronized(true);
} else {
apiEntity.setIsSynchronized(false);
}
}
private void checkAPILifeCycle(ApiEntity api, LifecycleAction action) {
switch(api.getState()) {
case STARTED:
if (LifecycleAction.START.equals(action)) {
throw new BadRequestException("API is already started");
}
break;
case STOPPED:
if (LifecycleAction.STOP.equals(action)) {
throw new BadRequestException("API is already stopped");
}
break;
default:
break;
}
}
private String getExportFilename(ApiEntity apiEntity) {
return format("%s-%s.json", apiEntity.getName(), apiEntity.getVersion())
.trim()
.toLowerCase()
.replaceAll(" +", " ")
.replaceAll(" ", "-")
.replaceAll("[^\\w\\s\\.]","-")
.replaceAll("-+", "-");
}
}
|
feat(api): Do not change context-path if user is not allowed to do so. (#115)
Only the primary_owner of the API or an administrator is able to change the API's context-path to preserve coherency.
Closes gravitee-io/issues#203
|
gravitee-management-api-rest/src/main/java/io/gravitee/management/rest/resource/ApiResource.java
|
feat(api): Do not change context-path if user is not allowed to do so. (#115)
|
<ide><path>ravitee-management-api-rest/src/main/java/io/gravitee/management/rest/resource/ApiResource.java
<ide> @Produces(MediaType.APPLICATION_JSON)
<ide> @ApiPermissionsRequired(ApiPermission.MANAGE_API)
<ide> public ApiEntity update(@Valid @NotNull final UpdateApiEntity api) {
<add> final ApiEntity currentApi = this.get();
<add> // Force context-path if user is not the primary_owner or an administrator
<add> if (currentApi.getPermission() != MembershipType.PRIMARY_OWNER) {
<add> api.getProxy().setContextPath(currentApi.getProxy().getContextPath());
<add> }
<add>
<ide> final ApiEntity updatedApi = apiService.update(this.api, api);
<ide> setPermission(updatedApi);
<ide>
|
|
Java
|
apache-2.0
|
cf95585d57c28cdece970b6d3f9af4086ec131b3
| 0 |
AlexSafatli/NootBot
|
package net.dirtydeeds.discordsoundboard.async;
import java.util.List;
import java.util.LinkedList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import net.dirtydeeds.discordsoundboard.audio.AudioScheduler;
import net.dirtydeeds.discordsoundboard.audio.AudioTrackScheduler;
import net.dirtydeeds.discordsoundboard.beans.SoundFile;
import net.dirtydeeds.discordsoundboard.service.SoundboardBot;
import net.dirtydeeds.discordsoundboard.service.SoundboardDispatcher;
import net.dirtydeeds.discordsoundboard.utils.MessageBuilder;
import net.dirtydeeds.discordsoundboard.utils.StringUtils;
import net.dirtydeeds.discordsoundboard.utils.StyledEmbedMessage;
import net.dirtydeeds.discordsoundboard.org.Category;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.entities.VoiceChannel;
import net.dv8tion.jda.core.requests.RestAction;
public class PlaySoundsJob implements SoundboardJob {
private String[] sounds;
private SoundboardBot bot;
private User user;
private String category;
public PlaySoundsJob(String[] sounds, SoundboardBot bot, User user) {
this.sounds = sounds;
this.bot = bot;
this.user = user;
}
public PlaySoundsJob(String[] sounds, SoundboardBot bot, User user, String category) {
this(sounds, bot, user);
this.category = category;
}
public boolean isApplicable(SoundboardDispatcher dispatcher) {
return true;
}
private long schedule(SoundboardDispatcher dispatcher, AudioTrackScheduler scheduler, String name) throws InterruptedException, ExecutionException, TimeoutException {
long time = 0;
SoundFile f = bot.getSoundMap().get(name);
f.addOneToNumberOfPlays();
Long duration = f.getDuration();
if (duration != null) time = duration;
bot.getDispatcher().saveSound(f);
scheduler.load(f.getSoundFile().getPath(), new AudioScheduler(scheduler)).get(5, TimeUnit.SECONDS);
return time;
}
public void run(SoundboardDispatcher dispatcher) {
if (bot != null && sounds != null && sounds.length > 0) {
boolean same = true, randomed = false, allRandomed = true;
Guild guild = null;
VoiceChannel voice = null;
String firstSound = null;
try {
voice = bot.getUsersVoiceChannel(user);
if (voice == null) {
bot.sendMessageToUser(SoundboardBot.NOT_IN_VOICE_CHANNEL_MESSAGE, user);
return;
}
guild = voice.getGuild();
bot.moveToChannel(voice);
} catch (Exception e) { return; }
long timePlaying = 0;
MessageBuilder mb = new MessageBuilder();
AudioTrackScheduler scheduler = bot.getSchedulerForGuild(guild);
for (int i = 0; i < sounds.length; ++i) {
String sound = sounds[i];
if (sound == null || sound.equals("*")) {
if (category == null) try {
sound = bot.getRandomSoundName();
if (sound != null) timePlaying += schedule(dispatcher, scheduler, sound);
} catch (Exception e) { e.printStackTrace(); continue; }
else try {
sound = bot.getRandomSoundNameForCategory(category);
if (sound != null) timePlaying += schedule(dispatcher, scheduler, sound);
} catch (Exception e) { e.printStackTrace(); continue; }
randomed = true;
} else {
if (allRandomed) allRandomed = false;
try {
if (sound != null) timePlaying += schedule(dispatcher, scheduler, sound);
} catch (Exception e) { e.printStackTrace(); continue; }
}
if (sound != null) {
try {
if (firstSound == null) firstSound = sound;
if (!sound.equals(firstSound)) same = false;
mb.append("`" + sound + "` (**" + dispatcher.getSoundFileByName(sound).getNumberOfPlays() + "** plays)");
if (i == sounds.length - 2 && sounds.length > 1) mb.append(", and ");
else if (i < sounds.length - 1) mb.append(", ");
} catch (Exception e) { e.printStackTrace(); continue; }
}
}
String end = "";
if (category != null) {
Category c = bot.getSoundCategory(category);
if (c != null) end += "from category **" + c.getName() + "** ";
}
if (allRandomed) end += "*all of which were randomed*";
else if (randomed) end += "*some of which were randomed*";
if (guild != null) {
List<Message> msgs;
if (!same || sounds.length == 1) {
msgs = makeMessages("Queued sound(s) " + end + " \u2014 " + user.getAsMention(), user, mb, timePlaying);
} else {
msgs = makeMessages("Looping `" + firstSound + "` **" + sounds.length + "** times \u2014 " + user.getAsMention(), user, null, timePlaying);
}
for (Message msg : msgs) {
RestAction<Message> m = guild.getPublicChannel().sendMessage(msg);
if (m != null) {
m.queue((Message s)-> {
dispatcher.getAsyncService().runJob(new DeleteMessageJob(s, 1800));
});
}
}
}
}
}
private List<Message> makeMessages(String description, User user, MessageBuilder mb, long duration) {
List<Message> msgs = new LinkedList<>();
if (mb != null) {
for (String str : mb) {
String titleSuffix = (msgs.size() > 1) ? " \u2014 (*" + msgs.size() + "*)" : "";
StyledEmbedMessage msg = StyledEmbedMessage.forUser(bot, user, "Playing Multiple Sounds" + titleSuffix, description);
if (mb != null) msg.addContent("Sounds Queued", str, false);
if (duration > 0) msg.addContent("Total Duration", Long.toString(duration) + " seconds", false);
msgs.add(msg.getMessage());
}
} else {
msgs.add(StyledEmbedMessage.forUser(bot, user, "Loop", description).getMessage());
}
return msgs;
}
}
|
src/main/java/net/dirtydeeds/discordsoundboard/async/PlaySoundsJob.java
|
package net.dirtydeeds.discordsoundboard.async;
import java.util.List;
import java.util.LinkedList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import net.dirtydeeds.discordsoundboard.audio.AudioScheduler;
import net.dirtydeeds.discordsoundboard.audio.AudioTrackScheduler;
import net.dirtydeeds.discordsoundboard.beans.SoundFile;
import net.dirtydeeds.discordsoundboard.service.SoundboardBot;
import net.dirtydeeds.discordsoundboard.service.SoundboardDispatcher;
import net.dirtydeeds.discordsoundboard.utils.MessageBuilder;
import net.dirtydeeds.discordsoundboard.utils.StringUtils;
import net.dirtydeeds.discordsoundboard.utils.StyledEmbedMessage;
import net.dirtydeeds.discordsoundboard.org.Category;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.entities.VoiceChannel;
import net.dv8tion.jda.core.requests.RestAction;
public class PlaySoundsJob implements SoundboardJob {
private String[] sounds;
private SoundboardBot bot;
private User user;
private String category;
public PlaySoundsJob(String[] sounds, SoundboardBot bot, User user) {
this.sounds = sounds;
this.bot = bot;
this.user = user;
}
public PlaySoundsJob(String[] sounds, SoundboardBot bot, User user, String category) {
this(sounds, bot, user);
this.category = category;
}
public boolean isApplicable(SoundboardDispatcher dispatcher) {
return true;
}
private long schedule(SoundboardDispatcher dispatcher, AudioTrackScheduler scheduler, String name) throws InterruptedException, ExecutionException, TimeoutException {
long time = 0;
SoundFile f = bot.getSoundMap().get(name);
f.addOneToNumberOfPlays();
Long duration = f.getDuration();
if (duration != null) time = duration;
bot.getDispatcher().saveSound(f);
scheduler.load(f.getSoundFile().getPath(), new AudioScheduler(scheduler)).get(5, TimeUnit.SECONDS);
return time;
}
public void run(SoundboardDispatcher dispatcher) {
if (bot != null && sounds != null && sounds.length > 0) {
boolean same = true, randomed = false, allRandomed = true;
Guild guild = null;
VoiceChannel voice = null;
String firstSound = null;
try {
voice = bot.getUsersVoiceChannel(user);
if (voice == null) {
bot.sendMessageToUser(SoundboardBot.NOT_IN_VOICE_CHANNEL_MESSAGE, user);
return;
}
guild = voice.getGuild();
bot.moveToChannel(voice);
} catch (Exception e) { return; }
long timePlaying = 0;
MessageBuilder mb = new MessageBuilder();
AudioTrackScheduler scheduler = bot.getSchedulerForGuild(guild);
for (int i = 0; i < sounds.length; ++i) {
String sound = sounds[i];
if (sound == null || sound.equals("*")) {
if (category == null) try {
sound = bot.getRandomSoundName();
if (sound != null) timePlaying += schedule(dispatcher, scheduler, sound);
} catch (Exception e) { e.printStackTrace(); continue; }
else try {
sound = bot.getRandomSoundNameForCategory(category);
if (sound != null) timePlaying += schedule(dispatcher, scheduler, sound);
} catch (Exception e) { e.printStackTrace(); continue; }
randomed = true;
} else {
if (allRandomed) allRandomed = false;
try {
if (sound != null) timePlaying += schedule(dispatcher, scheduler, sound);
} catch (Exception e) { e.printStackTrace(); continue; }
}
if (sound != null) {
try {
if (firstSound == null) firstSound = sound;
if (!sound.equals(firstSound)) same = false;
mb.append("`" + sound + "` (**" + dispatcher.getSoundFileByName(sound).getNumberOfPlays() + "** plays)");
if (i == sounds.length - 2 && sounds.length > 1) mb.append(", and ");
else if (i < sounds.length - 1) mb.append(", ");
} catch (Exception e) { e.printStackTrace(); continue; }
}
}
String end = "";
if (category != null) {
Category c = bot.getSoundCategory(category);
if (c != null) end += " from category **" + c.getName() + "**";
}
if (allRandomed) end += " *all of which were randomed*";
else if (randomed) end += " *some of which were randomed*";
if (guild != null) {
List<Message> msgs;
if (!same || sounds.length == 1) {
msgs = makeMessages("Queued sound(s) " + end + " " + user.getAsMention() + ".", user, mb, timePlaying);
} else {
msgs = makeMessages("Looping `" + firstSound + "` **" + sounds.length + "** times " + user.getAsMention() + ".", user, null, timePlaying);
}
for (Message msg : msgs) {
RestAction<Message> m = guild.getPublicChannel().sendMessage(msg);
if (m != null) {
m.queue((Message s)-> {
dispatcher.getAsyncService().runJob(new DeleteMessageJob(s, 1800));
});
}
}
}
}
}
private List<Message> makeMessages(String description, User user, MessageBuilder mb, long duration) {
List<Message> msgs = new LinkedList<>();
if (mb != null) {
for (String str : mb) {
String titleSuffix = (msgs.size() > 1) ? " \u2014 (*" + msgs.size() + "*)" : "";
StyledEmbedMessage msg = StyledEmbedMessage.forUser(bot, user, "Playing Multiple Sounds" + titleSuffix, description);
if (mb != null) msg.addContent("Sounds Queued", str, false);
if (duration > 0) msg.addContent("Total Duration", Long.toString(duration) + " seconds", false);
msgs.add(msg.getMessage());
}
} else {
msgs.add(StyledEmbedMessage.forUser(bot, user, "Loop", description).getMessage());
}
return msgs;
}
}
|
Anta baka?
|
src/main/java/net/dirtydeeds/discordsoundboard/async/PlaySoundsJob.java
|
Anta baka?
|
<ide><path>rc/main/java/net/dirtydeeds/discordsoundboard/async/PlaySoundsJob.java
<ide> String end = "";
<ide> if (category != null) {
<ide> Category c = bot.getSoundCategory(category);
<del> if (c != null) end += " from category **" + c.getName() + "**";
<add> if (c != null) end += "from category **" + c.getName() + "** ";
<ide> }
<del> if (allRandomed) end += " *all of which were randomed*";
<del> else if (randomed) end += " *some of which were randomed*";
<add> if (allRandomed) end += "*all of which were randomed*";
<add> else if (randomed) end += "*some of which were randomed*";
<ide> if (guild != null) {
<ide> List<Message> msgs;
<ide> if (!same || sounds.length == 1) {
<del> msgs = makeMessages("Queued sound(s) " + end + " " + user.getAsMention() + ".", user, mb, timePlaying);
<add> msgs = makeMessages("Queued sound(s) " + end + " \u2014 " + user.getAsMention(), user, mb, timePlaying);
<ide> } else {
<del> msgs = makeMessages("Looping `" + firstSound + "` **" + sounds.length + "** times " + user.getAsMention() + ".", user, null, timePlaying);
<add> msgs = makeMessages("Looping `" + firstSound + "` **" + sounds.length + "** times \u2014 " + user.getAsMention(), user, null, timePlaying);
<ide> }
<ide> for (Message msg : msgs) {
<ide> RestAction<Message> m = guild.getPublicChannel().sendMessage(msg);
|
|
JavaScript
|
mit
|
bb28f5da098815d201e2ec3973be5fd9e8f9e5c8
| 0 |
lgbouma/astrobase,waqasbhatti/astrobase,waqasbhatti/astrobase,waqasbhatti/astrobase,lgbouma/astrobase,lgbouma/astrobase
|
// cpserver.js - Waqas Bhatti ([email protected]) - Jan 2017
// License: MIT. See LICENSE for the full text.
//
// This contains the JS to drive the checkplotserver's interface.
//
//////////////
// JS BELOW //
//////////////
// this contains utility functions
var cputils = {
// this encodes a string to base64
// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
b64_encode: function (str) {
return btoa(
encodeURIComponent(str)
.replace(/%([0-9A-F]{2})/g,
function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
},
// this turns a base64 string into an image by updating its source
b64_to_image: function (str, targetelem) {
var datauri = 'data:image/png;base64,' + str;
$(targetelem).attr('src',datauri);
},
// this displays a base64 encoded image on the canvas
b64_to_canvas: function (str, targetelem) {
var datauri = 'data:image/png;base64,' + str;
var newimg = new Image();
var canvas = document.getElementById(targetelem.replace('#',''));
var imgheight = 300;
var imgwidth = 300;
var cnvwidth = canvas.width;
canvas.height = cnvwidth;
var imgscale = cnvwidth/imgwidth;
var ctx = canvas.getContext('2d');
// this event listener will fire when the image is loaded
newimg.addEventListener('load', function () {
ctx.drawImage(newimg,
0,
0,
imgwidth*imgscale,
imgheight*imgscale);
});
// load the image and fire the listener
newimg.src = datauri;
},
// this holds imagedata for the canvas so we can restore changed parts of
// the image
pixeltracker: null
};
// this contains updates to current checkplots, tracks the entire project's info
// and provides functions to save everything to CSV or JSON
var cptracker = {
// this is a list of all checkplots
checkplotlist: [],
// this is the actual object that will get written to JSON or CSV
cpdata: {},
// this is the order of columns for generating the CSV
infocolumns: [
'objectid',
'checkplot',
'objectinfo.twomassid',
'objectinfo.network',
'objectinfo.stations',
'objectinfo.ndet',
'objectinfo.objecttags',
'objectinfo.umag',
'objectinfo.bmag',
'objectinfo.vmag',
'objectinfo.rmag',
'objectinfo.imag',
'objectinfo.sdssu',
'objectinfo.sdssg',
'objectinfo.sdssr',
'objectinfo.sdssi',
'objectinfo.sdssz',
'objectinfo.jmag',
'objectinfo.hmag',
'objectinfo.kmag',
'objectinfo.ujmag',
'objectinfo.uhmag',
'objectinfo.ukmag',
'objectinfo.irac1',
'objectinfo.irac2',
'objectinfo.irac3',
'objectinfo.irac4',
'objectinfo.wise1',
'objectinfo.wise2',
'objectinfo.wise3',
'objectinfo.wise4',
'objectinfo.deredb',
'objectinfo.deredv',
'objectinfo.deredu',
'objectinfo.deredg',
'objectinfo.deredr',
'objectinfo.deredi',
'objectinfo.deredz',
'objectinfo.deredj',
'objectinfo.deredh',
'objectinfo.deredk',
'objectinfo.dered_umag',
'objectinfo.dered_bmag',
'objectinfo.dered_vmag',
'objectinfo.dered_rmag',
'objectinfo.dered_imag',
'objectinfo.dered_jmag',
'objectinfo.dered_hmag',
'objectinfo.dered_kmag',
'objectinfo.dered_sdssu',
'objectinfo.dered_sdssg',
'objectinfo.dered_sdssr',
'objectinfo.dered_sdssi',
'objectinfo.dered_sdssz',
'objectinfo.dered_ujmag',
'objectinfo.dered_uhmag',
'objectinfo.dered_ukmag',
'objectinfo.dered_irac1',
'objectinfo.dered_irac2',
'objectinfo.dered_irac3',
'objectinfo.dered_irac4',
'objectinfo.dered_wise1',
'objectinfo.dered_wise2',
'objectinfo.dered_wise3',
'objectinfo.dered_wise4',
'objectinfo.bvcolor',
'objectinfo.gjcolor',
'objectinfo.ijcolor',
'objectinfo.jkcolor',
'objectinfo.gkcolor',
'objectinfo.vkcolor',
'objectinfo.ugcolor',
'objectinfo.grcolor',
'objectinfo.ricolor',
'objectinfo.izcolor',
'objectinfo.sdssu-sdssg',
'objectinfo.sdssg-sdssr',
'objectinfo.sdssr-sdssi',
'objectinfo.sdssi-sdssz',
'objectinfo.sdssg-sdssi',
'objectinfo.sdssg-jmag',
'objectinfo.sdssg-kmag',
'objectinfo.umag-bmag',
'objectinfo.bmag-vmag',
'objectinfo.vmag-rmag',
'objectinfo.vmag-imag',
'objectinfo.rmag-imag',
'objectinfo.vmag-kmag',
'objectinfo.jmag-hmag',
'objectinfo.hmag-kmag',
'objectinfo.jmag-kmag',
'objectinfo.dereddened',
'objectinfo.bmagfromjhk',
'objectinfo.vmagfromjhk',
'objectinfo.sdssufromjhk',
'objectinfo.sdssgfromjhk',
'objectinfo.sdssrfromjhk',
'objectinfo.sdssifromjhk',
'objectinfo.sdsszfromjhk',
'objectinfo.color_classes',
'objectinfo.ra',
'objectinfo.decl',
'objectinfo.gl',
'objectinfo.gb',
'objectinfo.pmra',
'objectinfo.pmra_err',
'objectinfo.pmdecl',
'objectinfo.pmdecl_err',
'objectinfo.propermotion',
'objectinfo.rpmj',
'objectinfo.reducedpropermotion',
'objectinfo.gaiamag',
'objectinfo.gaia_parallax',
'objectinfo.gaia_parallax_err',
'objectinfo.neighbors',
'objectinfo.closestdistarcsec',
'objectinfo.gaia_neighbors',
'objectinfo.gaia_closest_distarcsec',
'objectinfo.gaia_closest_gmagdiff',
'objectinfo.d_ug',
'objectinfo.d_gr',
'objectinfo.s_color',
'objectinfo.l_color',
'objectinfo.v_color',
'objectinfo.p1_color',
'objectinfo.m_sti',
'objectinfo.m_sts',
'objectinfo.extinctb',
'objectinfo.extinctv',
'objectinfo.extinctu',
'objectinfo.extinctg',
'objectinfo.extinctr',
'objectinfo.extincti',
'objectinfo.extinctz',
'objectinfo.extinctj',
'objectinfo.extincth',
'objectinfo.extinctk',
'objectinfo.extinction_umag',
'objectinfo.extinction_bmag',
'objectinfo.extinction_vmag',
'objectinfo.extinction_rmag',
'objectinfo.extinction_imag',
'objectinfo.extinction_sdssu',
'objectinfo.extinction_sdssg',
'objectinfo.extinction_sdssr',
'objectinfo.extinction_sdssi',
'objectinfo.extinction_sdssz',
'objectinfo.extinction_jmag',
'objectinfo.extinction_hmag',
'objectinfo.extinction_kmag',
'varinfo.objectisvar',
'varinfo.varperiod',
'varinfo.varepoch',
'varinfo.vartags',
'comments'
],
// this function generates a CSV row for a single object in the
// cptracker.cpdata object
cpdata_get_csvrow: function (cpdkey, separator) {
var thisdata = cptracker.cpdata[cpdkey];
var rowarr = [];
cptracker.infocolumns.forEach(function (e, i, a) {
// if the key is a compound one (firstlev.secondlev)
if (e.indexOf('.') != -1) {
var keys = e.split('.');
rowarr.push(thisdata[keys[0]][keys[1]]);
}
// otherwise, it's just in the first level
else {
// special case of checkplot filename
if (e == 'checkplot') {
rowarr.push(cpdkey);
}
else {
rowarr.push(thisdata[e]);
}
}
});
// join the output row
var csvrow = rowarr.join(separator);
return csvrow
},
// this generates a CSV for download
cpdata_to_csv: function () {
var csvarr = [cptracker.infocolumns.join('|')];
for (obj in cptracker.cpdata) {
csvarr.push(cptracker.cpdata_get_csvrow(obj,'|'));
}
csvarr = "data:text/csv;charset=utf-8," +
encodeURIComponent(csvarr.join('\n'));
$('#download-anchor').attr('href', csvarr);
$('#download-anchor').attr('download', 'project-objectlist.csv');
$('#download-anchor').html('get CSV for reviewed objects');
$('#download-anchor').css({'display': 'inline'});
},
// this generates a JSON for download
cpdata_to_json: function () {
// we need to reverse the keys of the cpdata, so they're objectid first,
// add the object's checkplot file into its own dict
var jsonobj = {};
for (obj in cptracker.cpdata) {
var thisdata = cptracker.cpdata[obj];
thisdata['checkplot'] = obj;
jsonobj[thisdata['objectid']] = thisdata;
}
// generate the string
var jsonstr = "data:text/json;charset=utf-8," +
encodeURIComponent(JSON.stringify(jsonobj));
$('#download-anchor').attr('href', jsonstr);
$('#download-anchor').attr('download', 'project-objectlist.json');
$('#download-anchor').html('get JSON for reviewed objects');
$('#download-anchor').css({'display': 'inline'});
},
// this saves a single object back to the checkplotlist JSON
reviewed_object_to_cplist: function () {
var saveinfo = {checkplot: cpv.currfile,
varinfo: cpv.currcp.varinfo,
objectinfo: cpv.currcp.objectinfo,
comments: cpv.currcp.comments}
var postmsg = {objectid: cpv.currcp.objectid,
changes: JSON.stringify(saveinfo)}
if (cpv.readonlymode) {
// if we're in readonly mode, inform the user
$('#alert-box').html(
'The checkplot server is in readonly mode. ' +
'Edits to object information will not be saved.'
);
}
// if we're not in readonly mode, post the results
else {
// send this back to the checkplotserver
$.post('/list', postmsg, function (data) {
var success = data.status;
var message = data.message;
var result = data.result;
if (!success) {
$('#alert-box').html('could not save info for <strong>' +
postmsg.objectid + '</strong>!');
console.log('saving the changes back to the '+
'JSON file failed for ' + postmsg.objectid);
}
}, 'json').fail(function (xhr) {
$('#alert-box').html('could not save info for <strong>' +
postmsg.objectid + '</strong>!');
console.log('saving the changes back to the '+
'JSON file failed for ' + postmsg.objectid);
});
}
},
// this loads all the reviewed objects from the current project's JSON
// checkplot file list, and updates the reviewed objects list
all_reviewed_from_cplist: function () {
$.getJSON('/list', function (data) {
var reviewedobjects = data.reviewed;
// generate the object info rows and append to the reviewed object
// list
for (obj in reviewedobjects) {
var objdict = reviewedobjects[obj];
var objectid = obj;
var objcp = objdict.checkplot;
var objectinfo = objdict.objectinfo;
var varinfo = objdict.varinfo;
// generate the new list element: this contains objectid -
// variability flag, variability tags, object tags
var objectidelem = '<div class="tracker-obj" data-objectid="' +
objectid +
'"><a href="#" class="objload-checkplot" ' +
'data-fname="' + objcp + '" ';
if (varinfo.objectisvar == '1') {
objectidelem = objectidelem +
'data-objectisvar="1"' +
'>' +
objectid + '</a>: ' +
'variable';
}
else if (varinfo.objectisvar == '2') {
objectidelem = objectidelem +
'data-objectisvar="2"' +
'>' +
objectid + '</a>: ' +
'not variable';
}
else if (varinfo.objectisvar == '3') {
objectidelem = objectidelem +
'data-objectisvar="3"' +
'>' +
objectid + '</a>: ' +
'maybe variable';
}
else if (varinfo.objectisvar == '0') {
objectidelem = objectidelem +
'data-objectisvar="0"' +
'>' +
objectid + '</a>: ' +
'no varflag set';
}
if (varinfo.vartags != null) {
var thisvartags =
varinfo.vartags.split(', ');
if (thisvartags[0].length > 0) {
objectidelem = objectidelem + ' ';
thisvartags.forEach(function (e, i, a) {
objectidelem = objectidelem +
'<span class="cp-tag">' +
e + '</span> ';
});
}
}
if (objectinfo.objecttags != null) {
var thisobjtags =
objectinfo.objecttags.split(', ');
if (thisobjtags[0].length > 0) {
objectidelem = objectidelem + ' ';
thisobjtags.forEach(function (e, i, a) {
objectidelem = objectidelem +
'<span class="cp-tag">' +
e + '</span> ';
});
}
}
// finish the objectidelem li tag
objectidelem = objectidelem + '</div>';
$('#project-status').append(objectidelem);
// update the count in saved-count
var nsaved = $('#project-status div').length;
$('#saved-count').html(nsaved + '/' + cpv.totalcps);
}
}).fail(function (xhr) {
$('#alert-box').html('could not load the existing checkplot list');
console.log('could not load the existing checkplot list');
});
}
};
// this is the container for the main functions
var cpv = {
// these hold the current checkplot's data and filename respectively
currentfind: 0,
currfile: '',
currcp: {},
totalcps: 0,
cpfpng: null,
// this checks if the server is in readonly mode. disables controls if so.
readonlymode: false,
// these help in moving quickly through the phased LCs
currphasedind: null,
maxphasedind: null,
// this function generates a spinner
make_spinner: function (spinnermsg) {
var spinner = spinnermsg +
'<div class="spinner">' +
'<div class="rect1"></div>' +
'<div class="rect2"></div>' +
'<div class="rect3"></div>' +
'<div class="rect4"></div>' +
'<div class="rect5"></div>' +
'</div>';
$('#alert-box').html(spinner);
},
// this function generates an alert box
make_alert: function (alertmsg) {
var xalert =
'<div class="alert alert-warning alert-dismissible fade show" ' +
'role="alert">' +
'<button type="button" class="close" data-dismiss="alert" ' +
'aria-label="Close">' +
'<span aria-hidden="true">×</span>' +
'</button>' +
alertmsg +
'</div>';
$('#alert-box').html(xalert);
},
// this loads a checkplot from an image file into an HTML canvas object
load_checkplot: function (filename) {
// remove the summary download anchor from view since it's stale now
$('#download-anchor').css({'display': 'none'});
// start the spinny thing
cpv.make_spinner('loading...');
// build the title for this current file
var plottitle = $('#checkplot-current');
var filelink = filename;
var objectidelem = $('#objectid');
var twomassidelem = $('#twomassid');
plottitle.html(filelink);
if (cpv.currfile.length > 0) {
// un-highlight the previous file in side bar
$("a.checkplot-load")
.filter("[data-fname='" + cpv.currfile + "']")
.unwrap();
}
// do the AJAX call to get this checkplot
var ajaxurl = '/cp/' + cputils.b64_encode(filename);
// add the current object's fname to the objectid data-fname
objectidelem.attr('data-fname', filename);
$.getJSON(ajaxurl, function (data) {
cpv.currcp = data.result;
console.log(cpv.currcp);
/////////////////////////////////////////////////
// update the UI with elems for this checkplot //
/////////////////////////////////////////////////
// update the readonly status
cpv.readonlymode = data.readonly;
// update the objectid header
objectidelem.html(cpv.currcp.objectid);
// update the twomassid header
if (cpv.currcp.objectinfo.twomassid != undefined) {
twomassidelem.html('2MASS J' + cpv.currcp.objectinfo.twomassid);
}
else {
twomassidelem.html('');
}
//
// first, update the period search tab
//
// update the time0 placeholders
$('.time0').html(cpv.currcp.time0);
// set the items in the filters from existing if possible
if (cpv.currcp.hasOwnProperty('uifilters')) {
if (cpv.currcp.uifilters != null &&
cpv.currcp.uifilters.psearch_timefilters != null) {
$('#psearch-timefilters').val(
cpv.currcp.uifilters.psearch_timefilters
);
}
else {
$('#psearch-timefilters').val('');
}
if (cpv.currcp.uifilters != null &&
cpv.currcp.uifilters.psearch_magfilters != null) {
$('#psearch-magfilters').val(
cpv.currcp.uifilters.psearch_magfilters
);
}
else {
$('#psearch-magfilters').val('');
}
if (cpv.currcp.uifilters != null &&
cpv.currcp.uifilters.psearch_sigclip != null) {
$('#psearch-sigclip').val(
cpv.currcp.uifilters.psearch_sigclip
);
}
else {
$('#psearch-sigclip').val('');
}
}
// otherwise, use default nothing
else {
$('#psearch-timefilters').val('');
$('#psearch-magfilters').val('');
$('#psearch-sigclip').val('');
}
//
// set up the rest of period-search tab
//
// set the period and epoch from the current period and epoch
if (cpv.currcp.varinfo.varperiod != null &&
cpv.currcp.varinfo.varepoch != null) {
$('#psearch-plotperiod').val(cpv.currcp.varinfo.varperiod);
$('#psearch-plotepoch').val(cpv.currcp.varinfo.varepoch);
$("#psearch-pgrampeaks").html(
'<option value="0|' + cpv.currcp.varinfo.varperiod + '|' +
cpv.currcp.varinfo.varepoch +
'">prev. saved period</option>'
);
}
else {
$("#psearch-pgrampeaks").html(
'<option value="none">no tool results yet</option>'
);
$('#psearch-plotperiod').val('');
$('#psearch-plotepoch').val('');
}
// these are the plot frames, nothing by default
$('#psearch-periodogram-display')
.attr('src','/static/no-tool-results.png');
$('#psearch-phasedlc-display')
.attr('src','/static/no-tool-results.png');
//
// update object information now
//
// update the finder chart
// cputils.b64_to_image(cpv.currcp.finderchart,
// '#finderchart');
cputils.b64_to_canvas(cpv.currcp.finderchart,
'#finderchart');
// get the HAT stations
var hatstations = cpv.currcp.objectinfo.stations;
if (hatstations != undefined && hatstations) {
var splitstations =
(String(hatstations).split(',')).join(', ');
}
else {
var splitstations = '';
}
// get the number of detections
var objndet = cpv.currcp.objectinfo.ndet;
if (objndet == undefined) {
objndet = cpv.currcp.magseries_ndet;
}
// update the objectinfo
var hatinfo = '<strong>' +
splitstations +
'</strong><br>' +
'<strong>LC points:</strong> ' + objndet;
$('#hatinfo').html(hatinfo);
// get the GAIA status (useful for G mags, colors, etc.)
if (cpv.currcp.objectinfo.gaia_status != undefined) {
var gaia_ok =
cpv.currcp.objectinfo.gaia_status.indexOf('ok') != -1;
var gaia_message =
cpv.currcp.objectinfo.gaia_status.split(':')[1];
}
else {
var gaia_ok = false;
var gaia_message = (
'no RA/DEC provided, so no GAIA cross-match possible'
);
console.log('no GAIA info');
}
//
// get the coordinates
//
// ra
if (cpv.currcp.objectinfo.ra != undefined) {
var objectra = math.format(
cpv.currcp.objectinfo.ra, 6
);
}
else {
var objectra = '';
}
// decl
if (cpv.currcp.objectinfo.decl != undefined) {
var objectdecl = math.format(
cpv.currcp.objectinfo.decl, 6
);
}
else {
var objectdecl = '';
}
// gl
if (cpv.currcp.objectinfo.gl != undefined) {
var objectgl = math.format(
cpv.currcp.objectinfo.gl, 6
);
}
else {
var objectgl = '';
}
// gb
if (cpv.currcp.objectinfo.gb != undefined) {
var objectgb = math.format(
cpv.currcp.objectinfo.gb, 6
);
}
else {
var objectgb = '';
}
// total proper motion
if (cpv.currcp.objectinfo.propermotion != undefined) {
var objectpm = math.format(
cpv.currcp.objectinfo.propermotion, 5
) + ' mas/yr';
}
else {
var objectpm = '';
}
// reduced proper motion [Jmag]
if (cpv.currcp.objectinfo.rpmj != undefined) {
var objectrpmj = math.format(
cpv.currcp.objectinfo.rpmj, 4
);
}
else if (cpv.currcp.objectinfo.reducedpropermotion != undefined) {
var objectrpmj = math.format(
cpv.currcp.objectinfo.reducedpropermotion, 4
);
}
else {
var objectrpmj = '';
}
// format the coordinates and PM
var coordspm =
'<strong>Equatorial (α, δ):</strong> ' +
'<a title="SIMBAD search at these coordinates" ' +
'href="http://simbad.u-strasbg.fr/simbad/sim-coo?Coord=' +
cpv.currcp.objectinfo.ra + '+' + cpv.currcp.objectinfo.decl +
'&Radius=1&Radius.unit=arcmin' +
'" rel="nofollow" target="_blank">' +
objectra + ', ' + objectdecl + '</a><br>' +
'<strong>Galactic (l, b):</strong> ' +
objectgl + ', ' + objectgb + '<br>' +
'<strong>Total PM:</strong> ' + objectpm + '<br>' +
'<strong>Reduced PM<sub>J</sub>:</strong> ' + objectrpmj;
// see if we can get the GAIA parallax
if (gaia_ok && cpv.currcp.objectinfo.gaia_parallaxes[0]) {
var gaia_parallax = math.format(
cpv.currcp.objectinfo.gaia_parallaxes[0], 5
);
coordspm = coordspm + '<br>' +
'<strong>GAIA parallax:</strong> ' +
gaia_parallax + ' mas';
}
$('#coordspm').html(coordspm);
//
// handle the mags
//
var magnotices = [];
if (cpv.currcp.objectinfo.bmagfromjhk != undefined &&
cpv.currcp.objectinfo.bmagfromjhk) {
magnotices.push('B');
}
if (cpv.currcp.objectinfo.vmagfromjhk != undefined &&
cpv.currcp.objectinfo.vmagfromjhk) {
magnotices.push('V');
}
if (cpv.currcp.objectinfo.sdssufromjhk != undefined &&
cpv.currcp.objectinfo.sdssufromjhk) {
magnotices.push('u');
}
if (cpv.currcp.objectinfo.sdssgfromjhk != undefined &&
cpv.currcp.objectinfo.sdssgfromjhk) {
magnotices.push('g');
}
if (cpv.currcp.objectinfo.sdssrfromjhk != undefined &&
cpv.currcp.objectinfo.sdssrfromjhk) {
magnotices.push('r');
}
if (cpv.currcp.objectinfo.sdssifromjhk != undefined &&
cpv.currcp.objectinfo.sdssifromjhk) {
magnotices.push('i');
}
if (cpv.currcp.objectinfo.sdsszfromjhk != undefined &&
cpv.currcp.objectinfo.sdsszfromjhk) {
magnotices.push('z');
}
if (magnotices.length > 0) {
$('#magnotice').html('<br>(' + magnotices.join('') +
' via JHK transform)');
}
// set up the cmdplots property for currcp
cpv.currcp.cmdplots = [];
if (gaia_ok) {
var gaiamag = cpv.currcp.objectinfo.gaia_mags[0];
if (cpv.currcp.objectinfo.gaiak_colors != null) {
var gaiakcolor = cpv.currcp.objectinfo.gaiak_colors[0];
}
else {
var gaiakcolor = null;
}
var gaiaabsmag = cpv.currcp.objectinfo.gaia_absolute_mags[0];
}
else {
var gaiamag = null;
var gaiakcolor = null;
var gaiaabsmag = null;
}
//
// now we need to handle both generations of checkplots
//
// this is for the current generation of checkplots
if (cpv.currcp.objectinfo.hasOwnProperty('available_bands')) {
var mind = 0;
var cind = 0;
var mlen = cpv.currcp.objectinfo['available_bands'].length;
var clen = cpv.currcp.objectinfo['available_colors'].length;
var maglabel_pairs = [];
var colorlabel_pairs = [];
var thiskey = null;
var thislabel = null;
var thisval = null;
// generate the mag-label pairs
for (mind; mind < mlen; mind++) {
thiskey = cpv.currcp.objectinfo['available_bands'][mind];
thislabel =
cpv.currcp.objectinfo['available_band_labels'][mind];
thisval = math.format(cpv.currcp.objectinfo[thiskey],
5);
maglabel_pairs.push('<span class="no-wrap-break">' +
'<strong><em>' +
thislabel +
'</em>:</strong> ' +
thisval +
'</span>');
}
// generate the color-label pairs
for (cind; cind < clen; cind++) {
thiskey = cpv.currcp.objectinfo['available_colors'][cind];
thislabel =
cpv.currcp.objectinfo['available_color_labels'][cind];
thisval = math.format(cpv.currcp.objectinfo[thiskey],
4);
if (cpv.currcp.objectinfo.dereddened != undefined &&
cpv.currcp.objectinfo.dereddened) {
thislabel = '(' + thislabel
+ ')<sub>0</sub>';
$('#derednotice').html('<br>(dereddened)');
}
else {
thislabel = '(' + thislabel + ')';
}
colorlabel_pairs.push('<span class="no-wrap-break">' +
'<strong><em>' +
thislabel +
'</em>:</strong> ' +
thisval +
'</span>');
}
// now add the GAIA information if it exists
maglabel_pairs.push(
'<span class="no-wrap-break">' +
'<strong><em>GAIA G</em>:</strong> ' +
math.format(gaiamag,5) +
'</span>'
);
maglabel_pairs.push(
'<span class="no-wrap-break">' +
'<strong><em>GAIA M<sub>G</sub></em>:</strong> ' +
math.format(gaiaabsmag,5) +
'</span>'
);
maglabel_pairs = maglabel_pairs.join(', ');
colorlabel_pairs = colorlabel_pairs.join(', ');
$('#mags').html(maglabel_pairs);
$('#colors').html(colorlabel_pairs);
}
// this is for the older generation of checkplots
else {
var mags = '<strong><em>ugriz</em>:</strong> ' +
math.format(cpv.currcp.objectinfo.sdssu,5) + ', ' +
math.format(cpv.currcp.objectinfo.sdssg,5) + ', ' +
math.format(cpv.currcp.objectinfo.sdssr,5) + ', ' +
math.format(cpv.currcp.objectinfo.sdssi,5) + ', ' +
math.format(cpv.currcp.objectinfo.sdssz,5) + '<br>' +
'<strong><em>JHK</em>:</strong> ' +
math.format(cpv.currcp.objectinfo.jmag,5) + ', ' +
math.format(cpv.currcp.objectinfo.hmag,5) + ', ' +
math.format(cpv.currcp.objectinfo.kmag,5) + '<br>' +
'<strong><em>BV</em>:</strong> ' +
math.format(cpv.currcp.objectinfo.bmag,5) + ', ' +
math.format(cpv.currcp.objectinfo.vmag,5) + '<br>' +
'<strong><em>GAIA G</em>:</strong> ' +
math.format(gaiamag,5) + ', ' +
'<strong><em>GAIA M<sub>G</sub></em>:</strong> ' +
math.format(gaiaabsmag,5);
$('#mags').html(mags);
//
// handle the colors
//
if (cpv.currcp.objectinfo.dereddened != undefined &&
cpv.currcp.objectinfo.dereddened) {
$('#derednotice').html('<br>(dereddened)');
var colors =
'<strong><em>(B - V)<sub>0</sub></em>:</strong> ' +
math.format(cpv.currcp.objectinfo.bvcolor,4) + ', ' +
'<strong><em>(V - K)<sub>0</sub></em>:</strong> ' +
math.format(cpv.currcp.objectinfo.vkcolor,4) + '<br>' +
'<strong><em>(J - K)<sub>0</sub></em>:</strong> ' +
math.format(cpv.currcp.objectinfo.jkcolor,4) + ', ' +
'<strong><em>(i - J)<sub>0</sub></em>:</strong> ' +
math.format(cpv.currcp.objectinfo.ijcolor,4) + '<br>' +
'<strong><em>(g - K)<sub>0</sub></em>:</strong> ' +
math.format(cpv.currcp.objectinfo.gkcolor,4) + ', ' +
'<strong><em>(g - r)<sub>0</sub></em>:</strong> ' +
math.format(cpv.currcp.objectinfo.grcolor,4);
}
else {
var colors =
'<strong><em>(B - V)</em>:</strong> ' +
math.format(cpv.currcp.objectinfo.bvcolor,4) + ', ' +
'<strong><em>(V - K)</em>:</strong> ' +
math.format(cpv.currcp.objectinfo.vkcolor,4) + '<br>' +
'<strong><em>(J - K)</em>:</strong> ' +
math.format(cpv.currcp.objectinfo.jkcolor,4) + ', ' +
'<strong><em>(i - J)</em>:</strong> ' +
math.format(cpv.currcp.objectinfo.ijcolor,4) + '<br>' +
'<strong><em>(g - K)</em>:</strong> ' +
math.format(cpv.currcp.objectinfo.gkcolor,4) + ', ' +
'<strong><em>(g - r)</em>:</strong> ' +
math.format(cpv.currcp.objectinfo.grcolor,4);
}
// format the colors
$('#colors').html(colors);
}
//
// additional stuff
//
// first, empty out the extra info table
$("#objectinfo-extra").empty();
// add the color classification if available
if (cpv.currcp.objectinfo.color_classes != undefined &&
cpv.currcp.objectinfo.color_classes.length > 0) {
var formatted_color_classes =
cpv.currcp.objectinfo.color_classes.join(', ');
$('#objectinfo-extra')
.append(
"<tr>" +
"<th>Color classification</th>" +
"<td>" + formatted_color_classes + "</td>" +
"</tr>"
);
}
// neighbors
if (cpv.currcp.objectinfo.neighbors != undefined ||
(cpv.currcp.objectinfo.gaia_ids != undefined &&
cpv.currcp.objectinfo.gaia_ids.length > 0) ) {
if (cpv.currcp.objectinfo.neighbors > 0) {
var formatted_neighbors =
'<strong><em>from LCs in collection</em>:</strong> ' +
cpv.currcp.objectinfo.neighbors + '<br>' +
'<em>closest distance</em>: ' +
math.format(cpv.currcp.objectinfo.closestdistarcsec,4) +
'″<br>';
}
else {
var formatted_neighbors =
'<strong><em>from LCs in collection</em>:</strong> 0<br>';
}
if (gaia_ok) {
var formatted_gaia =
'<strong><em>from GAIA</em>:</strong> ' +
(cpv.currcp.objectinfo.gaia_ids.length - 1) + '<br>' +
'<em>closest distance</em>: ' +
math.format(
cpv.currcp.objectinfo.gaia_closest_distarcsec, 4
) + '″<br>' +
'<em>closest G mag (obj - nbr)</em>: ' +
math.format(
cpv.currcp.objectinfo.gaia_closest_gmagdiff, 4
) + ' mag';
}
else {
var formatted_gaia =
'<strong><em>GAIA query failed</em>:</strong> ' +
gaia_message;
}
$('#objectinfo-extra')
.append(
"<tr>" +
"<th>Neighbors within " +
math.format(cpv.currcp.objectinfo.searchradarcsec,
3) + "″</th>" +
"<td>" + formatted_neighbors +
formatted_gaia +
"</td>" +
"</tr>"
);
}
// get the CMDs for this object if there are any
if (cpv.currcp.hasOwnProperty('colormagdiagram') &&
cpv.currcp.colormagdiagram != null) {
var cmdlist = Object.getOwnPropertyNames(
cpv.currcp.colormagdiagram
);
var cmdkey = '<tr><th>' +
'Color-magnitude diagrams' +
'</th>';
var cmdval = '<td>';
var cmdimgs = [];
// prepare the img divs
var cmdi = 0;
for (cmdi; cmdi < cmdlist.length; cmdi++) {
var thiscmdlabel = cmdlist[cmdi];
var thiscmdplot = cpv.currcp.colormagdiagram[cmdlist[cmdi]];
var cmddd =
'<div class="dropdown">' +
'<a href="#" ' +
'title="Click to see the ' +
thiscmdlabel +
' color-magnitude ' +
'diagram for this object" ' +
'id="cmd-' + cmdi +
'-dropdown" data-toggle="dropdown" ' +
'aria-haspopup="true" aria-expanded="false">' +
'<strong>' + thiscmdlabel + ' CMD</strong>' +
'</a>' +
'<div class="dropdown-menu text-sm-center cmd-dn" ' +
'aria-labelledby="cmd-' + cmdi + '-dropdown">' +
'<img id="cmd-' + cmdi +'-plot" class="img-fluid">' +
'</div></div>';
cmdval = cmdval + cmddd;
cmdimgs.push('#cmd-' + cmdi + '-plot');
}
cmdval = cmdkey + cmdval + '</td></tr>';
$('#objectinfo-extra').append(cmdval);
// now populate the img divs with the actual CMD images
cmdi = 0;
for (cmdi; cmdi < cmdlist.length; cmdi++) {
var thiscmdlabel = cmdlist[cmdi];
var thiscmdplot = cpv.currcp.colormagdiagram[thiscmdlabel];
cputils.b64_to_image(thiscmdplot, cmdimgs[cmdi]);
}
}
// update the magseries plot
cputils.b64_to_image(cpv.currcp.magseries,
'.magseriesplot');
// update the varinfo
if (cpv.currcp.varinfo.objectisvar == 1) {
$('#varcheck').val(1);
}
else if (cpv.currcp.varinfo.objectisvar == 2) {
$('#varcheck').val(2);
}
else if (cpv.currcp.varinfo.objectisvar == 3) {
$('#varcheck').val(3);
}
else {
$('#varcheck').val(0);
}
// get the period and epoch
$('#objectperiod').val(cpv.currcp.varinfo.varperiod);
$('#objectepoch').val(cpv.currcp.varinfo.varepoch);
// update the rest of the object info
$('#objecttags').val(cpv.currcp.objectinfo.objecttags);
$('#objectcomments').val(cpv.currcp.objectcomments);
$('#vartags').val(cpv.currcp.varinfo.vartags);
// update the phased light curves
// first, count the number of methods we have in the cp
var lspmethods = cpv.currcp.pfmethods;
var ncols = lspmethods.length;
var colwidth = math.ceil(12/ncols);
// zero out previous stuff
$('.phased-container').empty();
cpv.currphasedind = null;
cpv.maxphasedind = null;
// this is the fast scroll index for moving quickly through the
// phased plots and selecting them as the best
var phasedplotindex = 0;
// then go through each lsp method, and generate the containers
for (let lspmethod of lspmethods) {
if (lspmethod in cpv.currcp) {
var nbestperiods = cpv.currcp[lspmethod].nbestperiods;
var periodogram = cpv.currcp[lspmethod].periodogram;
// start putting together the container for this method
var mcontainer_coltop =
'<div class="col-sm-' + colwidth +
'" data-lspmethod="' + lspmethod + '">';
var mcontainer_colbot = '</div>';
var periodogram_row =
'<div class="row periodogram-container">' +
'<div class="col-sm-12">' +
'<img src="data:image/png;base64,' +
cpv.currcp[lspmethod].periodogram + '" ' +
'class="img-fluid" id="periodogram-' +
lspmethod + '">' + '</div></div>';
var phasedlcrows= [];
// up to 5 periods are possible
var periodindexes = ['phasedlc0',
'phasedlc1',
'phasedlc2',
'phasedlc3',
'phasedlc4'];
for (let periodind of periodindexes) {
if (periodind in cpv.currcp[lspmethod]) {
var phasedlcrow =
'<a href="#" class="phasedlc-select" ' +
'title="use this period and epoch" ' +
'data-lspmethod="' + lspmethod + '" ' +
'data-periodind="' + periodind + '" ' +
'data-phasedind="' + phasedplotindex + '" ' +
'data-currentbest="no" ' +
'data-period="' +
cpv.currcp[lspmethod][periodind].period + '" ' +
'data-epoch="' +
cpv.currcp[lspmethod][periodind].epoch + '">' +
'<div class="row py-1 phasedlc-container-row" ' +
'data-periodind="' + periodind + '">' +
'<div class="col-sm-12">' +
'<img src="data:image/png;base64,' +
cpv.currcp[lspmethod][periodind].plot + '"' +
'class="img-fluid" id="plot-' +
periodind + '">' + '</div></div></a>';
phasedlcrows.push(phasedlcrow);
phasedplotindex = phasedplotindex + 1;
}
}
// now that we've collected everything, generate the
// container column
var mcontainer = mcontainer_coltop + periodogram_row +
phasedlcrows.join(' ') + mcontainer_colbot;
// write the column to the phasedlc-container
$('.phased-container').append(mcontainer);
}
}
// write the max phasedind
cpv.maxphasedind = phasedplotindex;
//
// handle the neighbors tab for this object
//
// 1. empty the rows for the gaia table and lcc neighbor list
$('#neighbor-container').empty();
$('#gaia-neighbor-tbody').empty();
if (cpv.currcp.objectinfo.gaia_ids != undefined) {
$('#gaia-neighbor-count').html(
cpv.currcp.objectinfo.gaia_ids.length
);
}
else {
$('#gaia-neighbor-count').html('No');
}
$('#lcc-neighbor-container').empty();
$("#lcc-neighbor-count").html(cpv.currcp.neighbors.length);
// 2. update the search radius
if (cpv.currcp.objectinfo.searchradarcsec != undefined) {
$('#gaia-neighbor-maxdist').html(
cpv.currcp.objectinfo.searchradarcsec
);
$('#lcc-neighbor-maxdist').html(
cpv.currcp.objectinfo.searchradarcsec
);
}
// 3. update the GAIA neighbors
if (gaia_ok) {
// for each gaia neighbor, put in a table row
var gi = 0;
for (gi; gi < cpv.currcp.objectinfo.gaia_ids.length; gi++) {
// special formatting for the object itself
if (gi == 0) {
var rowhtml = '<tr class="gaia-objectlist-row ' +
'text-primary' +
'" ' +
'data-gaiaid="' +
cpv.currcp.objectinfo.gaia_ids[gi] +
'" data-xpos="' +
cpv.currcp.objectinfo.gaia_xypos[gi][0] +
'" data-ypos="' +
cpv.currcp.objectinfo.gaia_xypos[gi][1] +
'" >' +
'<td>obj: ' + cpv.currcp.objectinfo.gaia_ids[gi] +
'</td>' +
'<td>' + math.format(
cpv.currcp.objectinfo.gaia_dists[gi], 3
) +
'</td>' +
'<td>' +
math.format(
cpv.currcp.objectinfo.gaia_parallaxes[gi], 3
) + ' ± ' +
math.format(
cpv.currcp.objectinfo.gaia_parallax_errs[gi], 3
) +
'</td>' +
'<td>' +
math.format(
cpv.currcp.objectinfo.gaia_mags[gi], 3
) +
'</td>' +
'<td>' +
math.format(
cpv.currcp.objectinfo.gaia_absolute_mags[gi], 3
) +
'</td>' +
'</tr>';
}
else {
var rowhtml = '<tr class="gaia-objectlist-row" ' +
'data-gaiaid="' +
cpv.currcp.objectinfo.gaia_ids[gi] +
'" data-xpos="' +
cpv.currcp.objectinfo.gaia_xypos[gi][0] +
'" data-ypos="' +
cpv.currcp.objectinfo.gaia_xypos[gi][1] +
'" >' +
'<td>' + cpv.currcp.objectinfo.gaia_ids[gi] +
'</td>' +
'<td>' + math.format(
cpv.currcp.objectinfo.gaia_dists[gi], 3
) +
'</td>' +
'<td>' +
math.format(
cpv.currcp.objectinfo.gaia_parallaxes[gi], 3
) + ' ± ' +
math.format(
cpv.currcp.objectinfo.gaia_parallax_errs[gi], 3
) +
'</td>' +
'<td>' +
math.format(
cpv.currcp.objectinfo.gaia_mags[gi], 3
) +
'</td>' +
'<td>' +
math.format(
cpv.currcp.objectinfo.gaia_absolute_mags[gi], 3
) +
'</td>' +
'</tr>';
}
$('#gaia-neighbor-tbody').append(rowhtml);
}
}
// if GAIA xmatch failed, fill in the table without special
// formatting if possible
else if (cpv.currcp.objectinfo.gaia_ids != undefined) {
// for each gaia neighbor, put in a table row
var gi = 0;
// put in any rows of neighbors if there are any
for (gi; gi < cpv.currcp.objectinfo.gaia_ids.length; gi++) {
var rowhtml = '<tr class="gaia-objectlist-row" ' +
'data-gaiaid="' +
cpv.currcp.objectinfo.gaia_ids[gi] +
'" data-xpos="' +
cpv.currcp.objectinfo.gaia_xypos[gi][0] +
'" data-ypos="' +
cpv.currcp.objectinfo.gaia_xypos[gi][1] +
'" >' +
'<td>' + cpv.currcp.objectinfo.gaia_ids[gi] +
'</td>' +
'<td>' + math.format(
cpv.currcp.objectinfo.gaia_dists[gi], 3
) +
'</td>' +
'<td>' +
math.format(
cpv.currcp.objectinfo.gaia_parallaxes[gi], 3
) + ' ± ' +
math.format(
cpv.currcp.objectinfo.gaia_parallax_errs[gi], 3
) +
'</td>' +
'<td>' +
math.format(
cpv.currcp.objectinfo.gaia_mags[gi], 3
) +
'</td>' +
'<td>' +
math.format(
cpv.currcp.objectinfo.gaia_absolute_mags[gi], 3
) +
'</td>' +
'</tr>';
$('#gaia-neighbor-tbody').append(rowhtml);
}
}
// 4. update the LCC neighbor list
//
// first, add the target in any case
//
var ni = 0;
// set the column width
var nbrcolw = colwidth - 1;
// make the plots for the target object
var rowheader = '<h6>' + 'Target: ' +
cpv.currcp.objectid + ' at (α, δ) = (' +
math.format(cpv.currcp.objectinfo.ra, 5) + ', ' +
math.format(cpv.currcp.objectinfo.decl, 5) + ')</h6>';
var rowplots = [
'<div class="col-sm-' + nbrcolw + ' mx-0 px-0">' +
'<img src="data:image/png;base64,' +
cpv.currcp.magseries +
'" class="img-fluid">' +
'</div>'
];
var nli = 0;
for (nli; nli < lspmethods.length; nli++) {
var thisnphased =
'<div class="col-sm-' + nbrcolw + ' px-0">' +
'<img src="data:image/png;base64,' +
cpv.currcp[lspmethods[nli]]['phasedlc0']['plot'] +
'" class="img-fluid">' +
'</div>';
rowplots.push(thisnphased);
}
// put together this row of plots
var rowplots_str = rowplots.join(' ');
// put together this row
var nbrrow = '<div class="row">' +
'<div class="col-sm-12">' +
rowheader + '</div></div>' +
'<div class="row bot-mrg-20px">' +
rowplots_str +
'</div>';
$('#lcc-neighbor-container').append(nbrrow);
//
// then, add the neighbors if there are any
//
if (cpv.currcp.neighbors.length > 0) {
// now make the plots for the neighbors
for (ni; ni < cpv.currcp.neighbors.length; ni++) {
var nbrobjectid = cpv.currcp.neighbors[ni].objectid;
var nbrra = cpv.currcp.neighbors[ni].objectinfo.ra;
var nbrdecl = cpv.currcp.neighbors[ni].objectinfo.decl;
var nbrdist =
cpv.currcp.neighbors[ni].objectinfo.distarcsec;
// check if this neighbor is present in the current
// collection
var nbrcp = $('#checkplot-current').text().replace(
cpv.currcp.objectid,
nbrobjectid
);
if (cptracker.checkplotlist.indexOf(nbrcp) != -1) {
var nbrlink =
'<a title="load the checkplot for this object" ' +
'href="#" class="nbrload-checkplot" ' +
'data-fname="' + nbrcp + '">' +
nbrobjectid + '</a>';
}
else {
var nbrlink = nbrobjectid;
}
rowheader = '<h6>' + '<span class="neighbor-num">N' +
(ni+1) +
'</span>: ' +
nbrlink + ' at (α, δ) = <a href="' +
'http://simbad.u-strasbg.fr/simbad/sim-coo?Coord=' +
nbrra + '+' + nbrdecl +
'&Radius=30&Radius.unit=arcsec" rel="nofollow" ' +
'target="_blank" ' +
'title="SIMBAD search at these coordinates">' +
'(' + math.format(nbrra, 5) + ', ' +
math.format(nbrdecl, 5) + ')</a>, distance: ' +
math.format(nbrdist,3) + '″</h6>';
if (cpv.currcp.neighbors[ni].magseries != undefined) {
// add the magseries plot for this neighbor
rowplots = [
'<div class="col-sm-' + nbrcolw + ' mx-0 px-0">' +
'<img src="data:image/png;base64,' +
cpv.currcp.neighbors[ni].magseries +
'" class="img-fluid">' +
'</div>'
];
}
else {
rowplots = [
'<div class="col-sm-' + nbrcolw + ' mx-0 px-0">' +
'<img src="/static/nolc-available.png"' +
' class="img-fluid">' +
'</div>'
];
}
// for each lspmethod, add the phased LC for the neighbor
for (nli = 0; nli < lspmethods.length; nli++) {
if (cpv.currcp.neighbors[ni][lspmethods[nli]]
!= undefined) {
thisnphased =
'<div class="col-sm-' + nbrcolw + ' px-0">' +
'<img src="data:image/png;base64,' +
cpv.currcp.neighbors[ni][lspmethods[nli]]['plot'] +
'" class="img-fluid">' +
'</div>';
rowplots.push(thisnphased);
}
else {
thisnphased =
'<div class="col-sm-' + nbrcolw + ' px-0">' +
'<img src="/static/nolc-available.png"' +
'" class="img-fluid">' +
'</div>';
rowplots.push(thisnphased);
}
}
// put together this row of plots
rowplots_str = rowplots.join(' ');
// put together this row
nbrrow = '<div class="row">' +
'<div class="col-sm-12">' +
rowheader + '</div></div>' +
'<div class="row bot-mrg-20px">' +
rowplots_str +
'</div>';
$('#lcc-neighbor-container').append(nbrrow);
}
}
// 5. put together the xmatch info
// first, reset stuff
$('#unmatched-catalogs').html(
'<p>No cross-matches for this object were found.</p>'
);
$('#matched-catalogs').empty();
// then, go through the xmatch content
if (cpv.currcp.xmatch != undefined) {
var xmcatrows = [];
var unxmcatrows = [];
var xmk = null;
var tablecolkeys = null
var tablecolnames = null;
var tablecolunits = null;
var xmcrow = null;
var tci = 0;
var thisunit = '';
var xm = null;
for (xm in cpv.currcp.xmatch) {
xmk = cpv.currcp.xmatch[xm];
// if we found a cross-match, then generate the table for it
if (xmk['found'] == true) {
tablecolkeys = xmk['colkeys'];
tablecolnames = xmk['colnames'];
tablecolunits = xmk['colunit'];
xmcrow = [
'<div class="row mt-1">' +
'<div class="col-sm-12">' +
'<h6>Matched to: <abbr ' +
'title="' + xmk['desc'] + ' ">' +
'<strong>' +
xmk['name'] +
'</strong></abbr> within ' +
math.format(xmk['distarcsec'],3) + '″' +
'</h6>'
];
xmcrow.push(
'<table class="table-sm objectinfo-table">' +
'<thead><tr>'
)
// first, the header row
for (tci = 0;
tci < tablecolkeys.length;
tci++) {
if (tablecolunits[tci] != null) {
thisunit = '[' + tablecolunits[tci] + ']';
}
else {
thisunit = ' ';
}
xmcrow.push(
'<th>' +
tablecolnames[tci] + '<br>' + thisunit +
'</th>'
);
}
// close out this row
xmcrow.push(
'</tr></thead><tbody><tr>'
);
// next, do the value row
// first, the header row
for (tci = 0;
tci < tablecolkeys.length;
tci++) {
// format float things
if (tablecolunits[tci] != null) {
xmcrow.push(
'<td>' +
math.format(
xmk['info'][tablecolkeys[tci]],
5
) +
'</td>'
);
}
// otherwise, leave them alone
else {
xmcrow.push(
'<td>' +
xmk['info'][tablecolkeys[tci]] +
'</td>'
);
}
}
// close out the table
xmcrow.push(
'</tr></tbody></table></div></div>'
);
xmcrow = xmcrow.join(' ');
xmcatrows.push(xmcrow)
}
else {
unxmcatrows.push(
'<div class="row mt-1">' +
'<div class="col-sm-12">' +
'<h6>No matches found in <abbr ' +
'title="' + xmk['desc'] + ' ">' +
'<strong>' +
xmk['name'] +
'</strong></abbr></h6></div></div>'
);
}
}
xmcatrows = xmcatrows.join(' ');
unxmcatrows = unxmcatrows.join(' ');
$('#matched-catalogs').html(xmcatrows);
$('#unmatched-catalogs').html(unxmcatrows);
}
//
// end of main processing for a checkplot
//
}).done(function () {
// update the current file trackers
cpv.currfile = filename;
cpv.currentfind = parseInt(
$("a.checkplot-load")
.filter("[data-fname='" + filename + "']")
.attr('data-findex')
);
// FIXME: get this checkplot's cptools results
// if no cptools results, then populate the phased LCs
// - on the psearch tab, with GLS pgram + phasedlc0
// - on the var tab, with phasedlc0
// - on the lcfit tab, with phasedlc0
// FIXME: if the checkplot's cptools results are available in either
// the cptools.allresults object or in the temp checkplot, get them
// from there. this will probably need a separate call to
// cptools.load_results() and an AJAX endpoint
// FIXME: on the psearch tab, need to populate select with peaks for
// each period finding method in the checkplot
// FIXME: when we load the checkplot, load it's cptools results into
// the cptools.current object.
// re-initialize all popovers
$('[data-toggle="popover"]').popover();
// highlight the file in the sidebar list
$("a.checkplot-load")
.filter("[data-fname='" + filename + "']")
.wrap('<strong></strong>')
// fix the height of the sidebar as required
var winheight = $(window).height();
var docheight = $(document).height();
var ctrlheight = $('.sidebar-controls').height()
$('.sidebar').css({'height': docheight + 'px'});
// get rid of the spinny thing
$('#alert-box').empty();
if (cpv.readonlymode) {
// if we're in readonly mode, inform the user
$('#alert-box').html(
'The checkplot server is in readonly mode. ' +
'Edits to object information will not be saved.'
);
}
}).fail (function (xhr) {
$('#alert-box').html('could not load checkplot <strong>' +
filename + '</strong>!');
});
},
// this functions saves the current checkplot by doing a POST request to the
// backend. this MUST be called on every checkplot list action (i.e. next,
// prev, before load of a new checkplot, so changes are always saved). UI
// elements in the checkplot list will tag the saved checkplots
// appropriately
save_checkplot: function (nextfunc_callback, nextfunc_arg, savetopng) {
// make sure we're not in readonly mode
// if we are, then just bail out immediately
if (cpv.readonlymode) {
$('#alert-box').html(
'The checkplot server is in readonly mode. ' +
'Edits to object information will not be saved.'
);
// call the next function. we call this here so we can be sure the
// next action starts correctly even if we're not saving anything
if (!(nextfunc_callback === undefined) &&
!(nextfunc_arg === undefined)) {
nextfunc_callback(nextfunc_arg);
}
}
// if we're not in readonly mode, go ahead and save stuff
else {
// do the AJAX call to get this checkplot
var ajaxurl = '/cp/' + cputils.b64_encode(cpv.currfile);
// get the current value of the objectisvar select box
cpv.currcp.varinfo.objectisvar = $('#varcheck').val();
// make sure that we've saved the input varinfo, objectinfo and
// comments, period, epoch, etc.
cpv.currcp.varinfo.vartags = $('#vartags').val();
cpv.currcp.objectinfo.objecttags = $('#objecttags').val();
cpv.currcp.objectcomments = $('#objectcomments').val();
cpv.currcp.varinfo.objectisvar = parseInt($('#varcheck').val());
cpv.currcp.varinfo.varperiod = parseFloat($('#objectperiod').val());
cpv.currcp.varinfo.varepoch = parseFloat($('#objectepoch').val());
// make sure we also save the applied filters in the period-search
// tab
cpv.currcp.uifilters = {
psearch_timefilters:$('#psearch-timefilters').val(),
psearch_magfilters:$('#psearch-magfilters').val(),
psearch_sigclip:$('#psearch-sigclip').val()
}
var cppayload = JSON.stringify(
{objectid: cpv.currcp.objectid,
objectinfo: cpv.currcp.objectinfo,
varinfo: cpv.currcp.varinfo,
comments: cpv.currcp.objectcomments,
uifilters: cpv.currcp.uifilters}
);
// first, generate the object to send with the POST request
var postobj = {cpfile: cpv.currfile,
cpcontents: cppayload,
savetopng: savetopng};
// this is to deal with UI elements later
var currfile = postobj.cpfile;
// next, do a saving animation in the alert box
cpv.make_spinner('saving...');
// next, send the POST request and handle anything the server
// returns. FIXME: this should use _xsrf once we set that up
$.post(ajaxurl, postobj, function (data) {
// get the info from the backend
var updatestatus = data.status;
var updatemsg = data.message;
var updateinfo = data.result;
// update the cptracker with what changed so we can try to undo
// later if necessary.
if (updatestatus == 'success') {
// store only the latest update in the tracker
// FIXME: think about adding in update history
// probably a better fit for indexedDB or something
cptracker.cpdata[postobj.cpfile] = updateinfo.changes;
// check if this object is already present and remove if it
// so
var statobjcheck = $('.tracker-obj').filter(
'[data-objectid="' +
updateinfo.changes.objectid +
'"]'
);
// we need to update the project status widget
// generate the new list element: this contains objectid -
// variability flag, variability tags, object tags
var objectli =
'<div class="tracker-obj" ' +
'data-objectid="' + updateinfo.changes.objectid + '">';
var objectidelem = '<a class="objload-checkplot" ' +
'href="#" data-fname="' + postobj.cpfile + '" ' +
'data-objectisvar="' +
updateinfo.changes.varinfo.objectisvar + '">' +
updateinfo.changes.objectid +
'</a>:';
if (updateinfo.changes.varinfo.objectisvar == '1') {
var varelem = 'variable';
}
else if (updateinfo.changes.varinfo.objectisvar == '2') {
var varelem = 'not variable';
}
else if (updateinfo.changes.varinfo.objectisvar == '3') {
var varelem = 'maybe variable';
}
else if (updateinfo.changes.varinfo.objectisvar == '0') {
var varelem = 'no varflag set';
}
var thisvartags =
updateinfo.changes.varinfo.vartags.split(', ');
var thisobjtags =
updateinfo.changes.objectinfo.objecttags.split(', ');
var vartaglist = [];
if ((thisvartags != null) && (thisvartags[0].length > 0)) {
thisvartags.forEach(function (e, i, a) {
vartaglist.push('<span class="cp-tag">' +
e + '</span>');
});
vartaglist = vartaglist.join(' ');
}
else {
vartaglist = '';
}
var objtaglist = [];
if ((thisobjtags != null) && (thisobjtags[0].length > 0)) {
thisobjtags.forEach(function (e, i, a) {
objtaglist.push('<span class="cp-tag">' +
e + '</span>');
});
objtaglist = objtaglist.join(' ');
}
else {
objtaglist = '';
}
var finelem = [objectidelem,
varelem,
vartaglist,
objtaglist].join(' ');
// if this object exists in the list already
// replace it with the new content
if (statobjcheck.length > 0) {
statobjcheck.html(finelem);
console.log('updating existing entry for ' +
updateinfo.changes.objectid);
}
// if this object doesn't exist, add a new row
else {
console.log('adding new entry for ' +
updateinfo.changes.objectid);
$('#project-status').append(objectli + finelem +
'</div>');
}
// update the count in saved-count
var nsaved = $('#project-status div').length;
$('#saved-count').html(nsaved + '/' + cpv.totalcps);
// if we called a save to PNG, show it if it succeeded
if (!(savetopng === undefined) &&
(updateinfo.cpfpng != 'png making failed')) {
updatemsg = 'saved PNG to:<br>' +
'<textarea rows="3" ' +
'class="form-control" readonly>' +
updateinfo.cpfpng +
'</textarea>';
$('#alert-box').html(updatemsg);
}
else if (!(savetopng === undefined) &&
(updateinfo.cpfpng == 'png making failed')) {
updatemsg = 'sorry, making a PNG for ' +
'this object failed!';
$('#alert-box').html(updatemsg);
}
}
else {
$('#alert-box').html(updatemsg);
}
// on POST done, update the UI elements in the checkplot list
// and call the next function.
},'json').done(function (xhr) {
// send the changes to the backend so they're present in the
// checkplot-filelist.json file for the next time around
cptracker.reviewed_object_to_cplist();
// update the filter select box
$('#reviewedfilter').change();
// call the next function. we call this here so we can be sure
// the save finished before the next action starts
if (!(nextfunc_callback === undefined) &&
!(nextfunc_arg === undefined)) {
nextfunc_callback(nextfunc_arg);
// clean out the alert box if there's a next function
$('#alert-box').empty();
}
// if POST failed, pop up an alert in the alert box
}).fail(function (xhr) {
var errmsg = 'could not update ' +
currfile + ' because of an internal server error';
$('#alert-box').html(errmsg);
});
}
},
// this binds actions to the web-app controls
action_setup: function () {
// the previous checkplot link
$('.checkplot-prev').on('click',function (evt) {
evt.preventDefault();
// find the current index
var prevfilelink = $("a.checkplot-load")
.filter("[data-findex='" +
(cpv.currentfind-1) + "']");
var prevfile = prevfilelink.attr('data-fname');
if (prevfile != undefined) {
cpv.save_checkplot(cpv.load_checkplot,prevfile);
// $(prevfilelink)[0].scrollIntoView();
}
else {
// make sure to save current
cpv.save_checkplot(null,null);
}
});
// the next checkplot link
$('.checkplot-next').on('click',function (evt) {
evt.preventDefault();
// find the current index
var nextfilelink = $("a.checkplot-load")
.filter("[data-findex='" +
(cpv.currentfind+1) + "']");
var nextfile = nextfilelink.attr('data-fname');
if (nextfile != undefined) {
cpv.save_checkplot(cpv.load_checkplot,nextfile);
// $(nextfilelink)[0].scrollIntoView();
}
else {
// make sure to save current
cpv.save_checkplot(null,null);
}
});
// clicking on the generate JSON button
$('#save-project-json').click(function (evt) {
// make sure we have at least one object in the saved list
nsaved = $('#project-status div').length;
if (nsaved > 0) {
cptracker.cpdata_to_json();
}
});
// clicking on the generate CSV button
$('#save-project-csv').click(function (evt) {
// make sure we have at least one object in the saved list
nsaved = $('#project-status div').length;
if (nsaved > 0) {
cptracker.cpdata_to_csv();
}
});
$('#reviewedfilter').on('change', function (evt) {
// get this value
var filterval = $(this).val();
if (filterval == 0) {
$('.objload-checkplot')
.filter('[data-objectisvar="0"]')
.parent()
.show();
$('.objload-checkplot')
.filter('[data-objectisvar!="0"]')
.parent()
.hide();
}
else if (filterval == 1) {
$('.objload-checkplot')
.filter('[data-objectisvar="1"]')
.parent()
.show();
$('.objload-checkplot')
.filter('[data-objectisvar!="1"]')
.parent()
.hide();
}
else if (filterval == 2) {
$('.objload-checkplot')
.filter('[data-objectisvar="2"]')
.parent()
.show();
$('.objload-checkplot')
.filter('[data-objectisvar!="2"]')
.parent()
.hide();
}
else if (filterval == 3) {
$('.objload-checkplot')
.filter('[data-objectisvar="3"]')
.parent()
.show();
$('.objload-checkplot')
.filter('[data-objectisvar!="3"]')
.parent()
.hide();
}
else {
$('.objload-checkplot').parent().show();
}
});
// FIXME: fill this in later
$('#checkplotfilter').on('change', function (evt) {
// get this value
var filterval = $(this).val();
if (filterval == 0) {
$('.checkplot-load').show();
}
else if (filterval == 1) {
var reviewedcps = [];
}
else if (filterval == 2) {
}
});
// this handles adding object tags from the dropdown
$('.objtag-dn').click(function (evt) {
evt.preventDefault();
var thisobjtag = $(this).attr('data-dnobjtag');
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (objecttags.indexOf(thisobjtag) == -1) {
objecttags.push(thisobjtag);
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
// this handles adding object tags from the dropdown
$('.vartag-dn').click(function (evt) {
evt.preventDefault();
var thisvartag = $(this).attr('data-dnvartag');
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf(thisvartag) == -1) {
vartags.push(thisvartag);
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
// clicking on a checkplot file in the sidebar
$('#checkplotlist').on('click', '.checkplot-load', function (evt) {
evt.preventDefault();
var filetoload = $(this).attr('data-fname');
// save the currentcp if one exists, use the load_checkplot as a
// callback to load the next one
if (('objectid' in cpv.currcp) && (cpv.currfile.length > 0)) {
cpv.save_checkplot(cpv.load_checkplot,filetoload);
}
else {
// ask the backend for this file
cpv.load_checkplot(filetoload);
}
});
// this loads the neighbor's checkplot if it's in the current LC
// collection loaded into the checkplotserver
$('#lcc-neighbor-container').on('click','.nbrload-checkplot', function (e) {
e.preventDefault();
var filetoload = $(this).attr('data-fname');
// save the currentcp if one exists, use the load_checkplot as a
// callback to load the next one
if (('objectid' in cpv.currcp) && (cpv.currfile.length > 0)) {
cpv.save_checkplot(cpv.load_checkplot,filetoload);
}
else {
// ask the backend for this file
cpv.load_checkplot(filetoload);
}
});
// this handles the hover per objectid row to highlight the object in
// the finder chart
$('#gaia-neighbors').on('mouseover','.gaia-objectlist-row', function (e) {
e.preventDefault();
var canvas = document.getElementById('finderchart');
var canvaswidth = canvas.width;
var canvasheight = canvas.height;
var ctx = canvas.getContext('2d');
var thisx = $(this).attr('data-xpos');
var thisy = $(this).attr('data-ypos');
var cnvx = thisx * canvaswidth/300.0;
// y is from the top of the image for canvas
// FITS coords are from the bottom of the image
var cnvy = (300.0 - thisy) * canvasheight/300.0;
// save the damaged part of the image
cputils.pixeltracker = ctx.getImageData(cnvx-20,cnvy-20,40,40);
ctx.strokeStyle = 'green';
ctx.lineWidth = 3.0
ctx.strokeRect(cnvx-7.5,cnvy-7.5,12.5,12.5);
});
// this handles the repair to the canvas after the user mouses out of
// the row
$('#gaia-neighbors').on('mouseout','.gaia-objectlist-row', function (e) {
e.preventDefault();
var canvas = document.getElementById('finderchart');
var canvaswidth = canvas.width;
var canvasheight = canvas.height;
var ctx = canvas.getContext('2d');
var thisx = $(this).attr('data-xpos');
var thisy = $(this).attr('data-ypos');
var cnvx = thisx * canvaswidth/300.0;
// y is from the top of the image for canvas
// FITS coords are from the bottom of the image
var cnvy = (300.0 - thisy) * canvasheight/300.0;
// restore the imagedata if we have any
if (cputils.pixeltracker != null) {
ctx.putImageData(cputils.pixeltracker,
cnvx-20, cnvy-20);
}
});
// clicking on a objectid in the sidebar
$('#project-status').on('click', '.objload-checkplot', function (evt) {
evt.preventDefault();
var filetoload = $(this).attr('data-fname');
// save the currentcp if one exists, use the load_checkplot as a
// callback to load the next one
if (('objectid' in cpv.currcp) && (cpv.currfile.length > 0)) {
cpv.save_checkplot(cpv.load_checkplot,filetoload);
}
else {
// ask the backend for this file
cpv.load_checkplot(filetoload);
}
});
// clicking on a phased LC loads its period and epoch into the boxes
// also saves them to the currcp
$('.phased-container').on('click','.phasedlc-select', function (evt) {
evt.preventDefault();
var period = $(this).attr('data-period');
var epoch = $(this).attr('data-epoch');
// update the boxes
$('#objectperiod').val(period);
$('#objectepoch').val(epoch);
// save to currcp
cpv.currcp.varinfo.varperiod = parseFloat(period);
cpv.currcp.varinfo.varepoch = parseFloat(epoch);
// add a selected class
var selector = '[data-periodind="' +
$(this).attr('data-periodind') +
'"]';
$('.phasedlc-container-row').removeClass('phasedlc-selected');
$(this)
.children('.phasedlc-container-row')
.filter(selector).addClass('phasedlc-selected');
// change the variability flag to 'probably variable' automatically.
// since we've set a period and epoch, we probably think this is a
// variable
var currvarflag = $('#varcheck').val();
// we only change if the flag is not set already
if (currvarflag == 0) {
$('#varcheck').val(1);
}
});
// resizing the window fixes the sidebar again
$(window).on('resize', function (evt) {
// fix the height of the sidebar as required
var winheight = $(window).height();
var docheight = $(document).height();
var ctrlheight = $('.sidebar-controls').height()
$('.sidebar').css({'height': docheight + 'px'});
});
$('#save-to-png').on('click', function(evt) {
evt.preventDefault();
cpv.save_checkplot(undefined, undefined, true);
});
},
// this does keyboard shortcut setup
keyboard_setup: function () {
/////////////////////////
// SETTING VARIABILITY //
/////////////////////////
// alt+shift+v: object is variable
Mousetrap.bind('alt+shift+v', function() {
$('#varcheck').val(1);
});
// alt+shift+u: object is not variable
Mousetrap.bind('alt+shift+n', function() {
$('#varcheck').val(2);
});
// alt+shift+m: object is maybe a variable
Mousetrap.bind('alt+shift+m', function() {
$('#varcheck').val(3);
});
// alt+shift+u: unset variability flag
Mousetrap.bind('alt+shift+u', function() {
$('#varcheck').val(0);
});
//////////
// TABS //
//////////
// alt+shift+o: overview tab
Mousetrap.bind('alt+shift+o', function() {
$('#overview-tab').click();
});
// alt+shift+l: overview tab
Mousetrap.bind('alt+shift+l', function() {
$('#phasedlcs-tab').click();
});
// alt+shift+x: overview tab
Mousetrap.bind('alt+shift+x', function() {
$('#xmatches-tab').click();
});
// alt+shift+p: overview tab
Mousetrap.bind('alt+shift+p', function() {
$('#periodsearch-tab').click();
});
//////////////
// MOVEMENT //
//////////////
// ctrl+right: save this, move to next checkplot
Mousetrap.bind(['ctrl+right','alt+shift+right'], function() {
$('.checkplot-next').click();
});
// ctrl+left: save this, move to prev checkplot
Mousetrap.bind(['ctrl+left','alt+shift+left'], function() {
$('.checkplot-prev').click();
});
// ctrl+enter: save this, move to next checkplot
Mousetrap.bind('ctrl+enter', function() {
$('.checkplot-next').click();
});
// shift+enter: save this, but don't go anywhere
Mousetrap.bind('shift+enter', function() {
cpv.save_checkplot(undefined, undefined);
$('#alert-box').empty();
});
// ctrl+shift+e: save this as a PNG
Mousetrap.bind('alt+shift+e', function() {
cpv.save_checkplot(undefined, undefined, true);
});
// ctrl+down: move to the next phased LC and set it as the best
Mousetrap.bind(['ctrl+shift+down'], function() {
// check the current phased index, if it's null, then set it to 0
if (cpv.currphasedind == null) {
cpv.currphasedind = 0;
}
else if (cpv.currphasedind < cpv.maxphasedind) {
cpv.currphasedind = cpv.currphasedind + 1;
}
var targetelem = $('a[data-phasedind="' +
cpv.currphasedind + '"]');
if (targetelem.length > 0) {
// scroll into view if the bottom of this plot is off the screen
if ( (targetelem.offset().top + targetelem.height()) >
$(window).height() ) {
targetelem[0].scrollIntoView(true);
}
// click on the target elem to select it
targetelem.click();
}
});
// ctrl+up: move to the prev phased LC and set it as the best
Mousetrap.bind(['ctrl+shift+up'], function() {
// check the current phased index, if it's null, then set it to 0
if (cpv.currphasedind == null) {
cpv.currphasedind = 0;
}
else if (cpv.currphasedind > 0) {
cpv.currphasedind = cpv.currphasedind - 1;
}
var targetelem = $('a[data-phasedind="' +
cpv.currphasedind + '"]');
if (targetelem.length > 0) {
// scroll into view if the top of this plot is off the screen
if ( (targetelem.offset().top) > $(window).height() ) {
targetelem[0].scrollIntoView(true);
}
// click on the target elem to select it
targetelem.click();
}
});
// ctrl+backspace: clear variability tags
Mousetrap.bind('ctrl+backspace', function() {
// clean out the variability info and input boxes
$('#vartags').val('');
$('#objectperiod').val('');
$('#objectepoch').val('');
$('#varcheck').val(0);
cpv.currcp.varinfo.objectisvar = null;
cpv.currcp.varinfo.varepoch = null;
cpv.currcp.varinfo.varisperiodic = null;
cpv.currcp.varinfo.varperiod = null;
cpv.currcp.varinfo.vartags = null;
});
// ctrl+shift+backspace: clear all info
Mousetrap.bind('ctrl+shift+backspace', function() {
// clean out the all info and input boxes
$('#vartags').val('');
$('#objectperiod').val('');
$('#objectepoch').val('');
$('#objecttags').val('');
$('#objectcomments').val('');
$('#varcheck').val(0);
cpv.currcp.varinfo.objectisvar = null;
cpv.currcp.varinfo.varepoch = null;
cpv.currcp.varinfo.varisperiodic = null;
cpv.currcp.varinfo.varperiod = null;
cpv.currcp.varinfo.vartags = null;
cpv.currcp.objectinfo.objecttags = null;
cpv.currcp.comments = null;
});
///////////////////////
// TAGGING VARIABLES //
///////////////////////
// ctrl+shift+1: planet candidate
Mousetrap.bind('ctrl+shift+1', function () {
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf('planet candidate') == -1) {
vartags.push('planet candidate');
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
// ctrl+shift+2: RRab pulsator
Mousetrap.bind('ctrl+shift+2', function () {
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf('RR Lyrae pulsator') == -1) {
vartags.push('RR Lyrae pulsator');
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
// ctrl+shift+3: RRc pulsator
Mousetrap.bind('ctrl+shift+3', function () {
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf('Cepheid pulsator') == -1) {
vartags.push('Cepheid pulsator');
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
// ctrl+shift+4: starspot rotation
Mousetrap.bind('ctrl+shift+4', function () {
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf('starspot rotation') == -1) {
vartags.push('starspot rotation');
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
// ctrl+shift+5: flare star
Mousetrap.bind('ctrl+shift+5', function () {
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf('flare star') == -1) {
vartags.push('flare star');
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
// ctrl+shift+6: contact EB
Mousetrap.bind('ctrl+shift+6', function () {
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf('contact EB') == -1) {
vartags.push('contact EB');
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
// ctrl+shift+7: semi-detached EB
Mousetrap.bind('ctrl+shift+7', function () {
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf('semi-detached EB') == -1) {
vartags.push('semi-detached EB');
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
// ctrl+shift+8: detached EB
Mousetrap.bind('ctrl+shift+8', function () {
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf('detached EB') == -1) {
vartags.push('detached EB');
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
// ctrl+shift+9: weird variability
Mousetrap.bind('ctrl+shift+9', function () {
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf('weird variability') == -1) {
vartags.push('weird variability');
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
// ctrl+shift+0: period harmonic
Mousetrap.bind('ctrl+shift+0', function () {
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf('period harmonic') == -1) {
vartags.push('period harmonic');
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
//////////////////////////
// TAGGING OBJECT TYPES //
//////////////////////////
// alt+shift+1: white dwarf
Mousetrap.bind(['alt+shift+1','command+shift+1'], function () {
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this objecttag in the list and append it
// if we don't.
if (objecttags.indexOf('white dwarf') == -1) {
objecttags.push('white dwarf');
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
// alt+shift+2: hot star (OB)
Mousetrap.bind(['alt+shift+2','command+shift+2'], function () {
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this objecttag in the list and append it
// if we don't.
if (objecttags.indexOf('hot star (OB)') == -1) {
objecttags.push('hot star (OB)');
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
// alt+shift+3: A star
Mousetrap.bind(['alt+shift+3','command+shift+3'], function () {
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this objecttag in the list and append it
// if we don't.
if (objecttags.indexOf('A star') == -1) {
objecttags.push('A star');
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
// alt+shift+4: F or G dwarf
Mousetrap.bind(['alt+shift+4','command+shift+4'], function () {
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this objecttag in the list and append it
// if we don't.
if (objecttags.indexOf('F or G dwarf') == -1) {
objecttags.push('F or G dwarf');
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
// alt+shift+5: red giant
Mousetrap.bind(['alt+shift+5','command+shift+5'], function () {
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this objecttag in the list and append it
// if we don't.
if (objecttags.indexOf('red giant') == -1) {
objecttags.push('red giant');
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
// alt+shift+6: K or M dwarf
Mousetrap.bind(['alt+shift+6','command+shift+6'], function () {
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this objecttag in the list and append it
// if we don't.
if (objecttags.indexOf('K or M dwarf') == -1) {
objecttags.push('K or M dwarf');
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
// alt+shift+7: giant star
Mousetrap.bind(['alt+shift+7','command+shift+7'], function () {
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this objecttag in the list and append it
// if we don't.
if (objecttags.indexOf('giant star') == -1) {
objecttags.push('giant star');
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
// alt+shift+8: dwarf star
Mousetrap.bind(['alt+shift+8','command+shift+8'], function () {
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this objecttag in the list and append it
// if we don't.
if (objecttags.indexOf('dwarf star') == -1) {
objecttags.push('dwarf star');
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
// alt+shift+9: blended with neighbors
Mousetrap.bind(['alt+shift+9','command+shift+9'], function () {
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this objecttag in the list and append it
// if we don't.
if (objecttags.indexOf('blended with neighbors') == -1) {
objecttags.push('blended with neighbors');
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
// alt+shift+0: weird object
Mousetrap.bind(['alt+shift+0','command+shift+0'], function () {
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this objecttag in the list and append it
// if we don't.
if (objecttags.indexOf('weird object') == -1) {
objecttags.push('weird object');
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
}
};
var cptools = {
// allobjects contains objects of the form:
// '<objectid>': {various lctool results}
// this is indexed by objectid
allobjects: {},
// processing contains objects of the form:
// '<objectid>': {'lctool':name of lctool currently running}
running: {},
// failed contains objects of the form:
// '<lctool-objectid>': message from backend explaining what happened
failed: {},
// this holds the current checkplot's results for fast review
current: {},
// this loads the current checkplot's results in order of priority:
// - from cptools.allresults.objects if objectid is present
// - from the checkplot-<objectid>.pkl-cpserver-temp file if that is present
// if neither are present, then this object doesn't have any results yet
// checks the processing list in the allresults for the objectid requested.
// if it's found there, then shows the spinner with the current tool
// that's running. if it's found in the objects
load_results: function () {
},
// this fires the POST action to save all outstanding stuff to the
// checkplot pickle permanently
sync_results: function (saveelem) {
},
// this clears out the currentresults and the allresults entry for the
// current checkplot and deletes the -cpserver-temp pickle file.
reset_results: function () {
},
run_periodsearch: function () {
// get the current objectid and checkplot filename
var currobjectid = $('#objectid').text();
var currfname = $('#objectid').attr('data-fname');
// this tracks if we're ok to proceed
var proceed = false;
// this tracks any errors in input. we join them all with <br>
// and show them in the alert box.
var messages = [];
// get which period search to run
var lspmethod = $('#psearch-lspmethod').val();
// this is the lctool to call
var lctooltocall = 'psearch-' + lspmethod;
// see if magsarefluxes is checked
var magsarefluxes = $('#psearch-magsarefluxes').prop('checked');
// see if autofreq is checked
var autofreq = $('#psearch-autofreq').prop('checked');
if ( (lspmethod == 'gls') || (lspmethod == 'bls') ||
(lspmethod == 'pdm') || (lspmethod == 'aov') ||
(lspmethod == 'mav') || (lspmethod == 'acf') ||
(lspmethod == 'win') ) {
proceed = true;
}
else {
messages.push("unknown periodogram method specified");
}
// if it's not checked, get the startp, endp, and frequency step
if (!autofreq) {
var startp = $('#psearch-startp').val();
var endp = $('#psearch-endp').val();
var freqstep = $('#psearch-freqstep').val();
startp = parseFloat(startp);
endp = parseFloat(endp);
freqstep = parseFloat(freqstep);
// check startp
if (isNaN(startp)) {
messages.push("no start period provided");
proceed = false;
}
else if ((startp == 0.0) || (startp < 0.0)) {
messages.push("start period cannot be 0.0 or < 0.0");
proceed = false;
}
else if (startp > endp) {
messages.push("start period cannot be larger than end period");
proceed = false;
}
else {
messages.push("using start period: " + math.format(startp, 5));
proceed = true;
}
// check endp
if (isNaN(endp)) {
messages.push("no end period provided");
proceed = false;
}
else if ((endp == 0.0) || (endp < 0.0)) {
messages.push("end period cannot be 0.0 or < 0.0");
proceed = false;
}
else {
messages.push("using end period: " + math.format(endp, 5));
proceed = true;
}
// check freqstep
if (isNaN(freqstep)) {
messages.push("no frequency step provided");
proceed = false;
}
else if ((freqstep == 0.0) || (freqstep < 0.0)) {
messages.push("frequency step cannot be 0.0 or < 0.0");
proceed = false;
}
else {
messages.push("using frequency step: " +
math.format(freqstep, 8));
proceed = true;
}
}
// get the specified sigma clip
var sigclip = $('#psearch-sigclip').val();
if (sigclip.length > 0) {
// try to see if this is a composite sigma clip for lo, hi
if (sigclip.indexOf(',') != -1) {
sigclip = sigclip.trim().split(',');
sigclip = [sigclip[0].trim(), sigclip[1].trim()];
sigclip = [parseFloat(sigclip[0]), parseFloat(sigclip[1])];
if (isNaN(sigclip[0]) || isNaN(sigclip[1]) ||
(sigclip[0] < 0) || (sigclip[1] < 0)) {
messages.push("one or both sigclip values is invalid");
proceed = false;
}
}
// if a single sigma clip, parse it
else {
sigclip = parseFloat(sigclip.trim());
if (isNaN(sigclip) || sigclip < 0) {
messages.push("sigclip value is invalid");
proceed = false;
}
else {
sigclip = [sigclip, sigclip];
}
}
}
else {
sigclip = null;
}
// check the number of peaks to retrieve
var nbestpeaks = $('#psearch-nbestpeaks').val();
if (nbestpeaks.length > 0) {
nbestpeaks = parseInt(nbestpeaks.trim());
if (isNaN(nbestpeaks) || nbestpeaks < 0) {
messages.push("nbestpeaks value is invalid");
proceed = false;
}
}
else {
nbestpeaks = 10;
}
// get the lctimefilters and lcmagfilters
// these will be processed server-side so nothing is required here
var lctimefilters = $('#psearch-timefilters').val();
if (lctimefilters.length == 0) {
lctimefilters = null;
}
var lcmagfilters = $('#psearch-magfilters').val();
if (lcmagfilters.length == 0) {
lcmagfilters = null;
}
var extraparams = {};
// finally, get the extra parameters for this periodogram method
$('.pf-extraparam').each(function (index) {
extraparams[$(this).attr('name')] = $(this).val();
});
console.log(extraparams);
// proceed if we can
if (proceed) {
// generate the alert box messages
messages.push("running " + lspmethod.toUpperCase() + '...');
messages = messages.join("<br>");
cpv.make_spinner('<span class="text-primary">' +
messages +
'</span><br>');
// generate the tool queue box
var tqbox = '<div class="tq-box" data-objectid="' + currobjectid +
'" data-fname="' + currfname +
'" data-lctool="' + lctooltocall +
'" data-toolstate="running">' +
'<strong>' + currobjectid + '</strong><br>' +
lctooltocall + ' — ' +
'<span class="tq-state">running</span></div>';
$('.tool-queue').append(tqbox);
// the call to the backend
var ajaxurl = '/tools/' + cputils.b64_encode(cpv.currfile);
if (autofreq) {
if (lctooltocall == 'psearch-acf') {
var sentdata = {
objectid: currobjectid,
lctool: lctooltocall,
forcereload: true,
magsarefluxes: magsarefluxes,
autofreq: autofreq,
sigclip: sigclip,
maxacfpeaks: nbestpeaks,
lctimefilters: lctimefilters,
lcmagfilters: lcmagfilters
};
}
else {
// this is the data object to send to the backend
var sentdata = {
objectid: currobjectid,
lctool: lctooltocall,
forcereload: true,
magsarefluxes: magsarefluxes,
autofreq: autofreq,
sigclip: sigclip,
nbestpeaks: nbestpeaks,
lctimefilters: lctimefilters,
lcmagfilters: lcmagfilters
};
}
}
else {
if (lctooltocall == 'psearch-acf') {
// this is the data object to send to the backend
var sentdata = {
objectid: currobjectid,
lctool: lctooltocall,
forcereload: true,
magsarefluxes: magsarefluxes,
autofreq: autofreq,
startp: startp,
endp: endp,
stepsize: freqstep,
sigclip: sigclip,
maxacfpeaks: nbestpeaks,
lctimefilters: lctimefilters,
lcmagfilters: lcmagfilters
};
}
else {
// this is the data object to send to the backend
var sentdata = {
objectid: currobjectid,
lctool: lctooltocall,
forcereload: true,
magsarefluxes: magsarefluxes,
autofreq: autofreq,
startp: startp,
endp: endp,
stepsize: freqstep,
sigclip: sigclip,
nbestpeaks: nbestpeaks,
lctimefilters: lctimefilters,
lcmagfilters: lcmagfilters
};
}
}
// update the sentdata with the extraparams
var ei = 0;
var ep = Object.getOwnPropertyNames(extraparams);
for (ei; ei < ep.length; ei++) {
sentdata[ep[ei]] = extraparams[ep[ei]];
}
console.log(sentdata);
// make the call
$.getJSON(ajaxurl, sentdata, function (recvdata) {
// the received data is in the standard form
var reqstatus = recvdata.status;
var reqmsg = recvdata.message;
var reqresult = recvdata.result;
var cpobjectid = reqresult.objectid;
// update this after we get back from the AJAX call
var currobjectid = $('#objectid').text();
if (reqstatus == 'success' || reqstatus == 'warning') {
var lsp = reqresult[lspmethod];
// only update if the user is still on the object
// we started with
if (cpobjectid == currobjectid) {
// update the select control for the periodogram peaks
// with all best peaks
$('#psearch-pgrampeaks').empty();
//
// first, get the first 3 peaks
//
$('#psearch-pgrampeaks').append(
'<option value="0|' + lsp.phasedlc0.period +
'|' + lsp.phasedlc0.epoch +
'" selected>peak 1: ' +
math.format(lsp.phasedlc0.period, 7) +
'</option>'
);
$('#psearch-pgrampeaks').append(
'<option value="1|' + lsp.phasedlc1.period +
'|' + lsp.phasedlc1.epoch +
'">peak 2: ' +
math.format(lsp.phasedlc1.period, 7) +
'</option>'
);
$('#psearch-pgrampeaks').append(
'<option value="2|' + lsp.phasedlc2.period +
'|' + lsp.phasedlc2.epoch +
'">peak 3: ' +
math.format(lsp.phasedlc2.period, 7) +
'</option>'
);
//
// then get any more peaks if remaining
//
if (lsp.nbestperiods.length > 3) {
var peakind = 3;
for (peakind;
peakind < lsp.nbestperiods.length;
peakind++) {
$('#psearch-pgrampeaks').append(
'<option value="' + peakind +
'|' + lsp.nbestperiods[peakind] +
'|' + 'auto-minimumlight' +
'">peak ' + (peakind + 1) + ': ' +
math.format(
lsp.nbestperiods[peakind], 7) +
'</option>'
);
}
}
// update the period box with the best period
$('#psearch-plotperiod').val(lsp.phasedlc0.period);
// update the epoch box with the epoch of the best period
$('#psearch-plotepoch').val(lsp.phasedlc0.epoch);
// put the periodogram into #psearch-periodogram-display
cputils.b64_to_image(lsp.periodogram,
'#psearch-periodogram-display');
// put the phased LC for the best period into
// #psearch-phasedlc-display
cputils.b64_to_image(lsp.phasedlc0.plot,
'#psearch-phasedlc-display');
// update the cptools tracker with the results for this
// object
// if this objectid is in the tracker
if (cpobjectid in cptools.allobjects) {
cptools.allobjects[cpobjectid][lspmethod] = lsp;
}
// if it's not in the tracker, add it
else {
cptools.allobjects[cpobjectid] = reqresult;
}
// update the cptools currentresults with these results
cptools.current[lspmethod] = lsp;
// add a warning to the alert box if there was one
if (reqstatus == 'warning') {
// show the error if something exploded
// but only if we're on the right objectid.
var errmsg = '<span class="text-warning">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
}
// update the tool queue
// fade out and remove the matching entry
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-primary">DONE<span>');
tqboxelem.fadeOut(2000, function () {
$(this).remove();
});
// clear out the alert box only if we're on the same
// objectid
$('#alert-box').empty();
}
// if the user has moved on,
// update the tool queue and allresults tracker
else {
console.log('results received for ' + cpobjectid +
' but user has moved to ' + currobjectid +
', updated tracker...');
// if this objectid is in the tracker
if (cpobjectid in cptools.allobjects) {
cptools.allobjects[cpobjectid][lspmethod] = lsp;
}
// if it's not in the tracker, add it
else {
cptools.allobjects[cpobjectid] = reqresult;
}
// update the tool queue
// fade out and remove the matching entry
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-primary">DONE<span>');
tqboxelem.fadeOut(2000, function () {
$(this).remove();
});
}
}
// if the request failed
else {
// show the error if something exploded but only if we're on
// the right objectid.
if (cpobjectid == currobjectid) {
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
}
// update the tool queue to show what happened
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-danger">FAILED<span>');
tqboxelem.fadeOut(2500, function () {
$(this).remove();
});
// update the cptools.failed tracker
var failedkey = lctooltocall + '-' + cpobjectid;
cptools.failed[failedkey] = reqmsg;
}
}).fail(function (xhr) {
// show the error - here we don't know which objectid was
// returned, so show the error wherever we are
var reqmsg = "could not run " + lctooltocall +
" because of a server error!";
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
});
}
// otherwise we can't proceed, bail out and show the error messages
else {
// generate the alert box messages
messages = messages.join("<br>");
$('#alert-box').html('<span class="text-warning">' +
messages +
'</span>');
}
},
get_varfeatures: function () {
// get the current objectid and checkplot filename
var currobjectid = $('#objectid').text();
var currfname = $('#objectid').attr('data-fname');
// this is the lctool to call
var lctooltocall = 'var-varfeatures';
// this tracks any errors in input. we join them all with <br>
// and show them in the alert box.
var messages = [];
// generate the alert box messages
messages.push("getting variability features...");
messages = messages.join("<br>");
cpv.make_spinner('<span class="text-primary">' +
messages +
'</span><br>');
// generate the tool queue box
var tqbox = '<div class="tq-box" data-objectid="' + currobjectid +
'" data-fname="' + currfname +
'" data-lctool="' + lctooltocall +
'" data-toolstate="running">' +
'<strong>' + currobjectid + '</strong><br>' +
lctooltocall + ' — ' +
'<span class="tq-state">running</span></div>';
$('.tool-queue').append(tqbox);
// the call to the backend
var ajaxurl = '/tools/' + cputils.b64_encode(cpv.currfile);
// this is the data object to send to the backend
var sentdata = {
objectid: currobjectid,
lctool: lctooltocall,
forcereload: true,
};
// make the call
$.getJSON(ajaxurl, sentdata, function (recvdata) {
// the received data is in the standard form
var reqstatus = recvdata.status;
var reqmsg = recvdata.message;
var reqresult = recvdata.result;
var cpobjectid = reqresult.objectid;
// update this after we get back from the AJAX call
var currobjectid = $('#objectid').text();
if (reqstatus == 'success' || reqstatus == 'warning') {
// only update if the user is still on the object
// we started with
if (cpobjectid == currobjectid) {
// this is the target element where we'll make a table
var featreselem = $('#var-varfeatures-results');
// these are the results
var vfeatures = reqresult.varinfo.varfeatures;
var feat_table = [
'<textarea class="form-control" rows="30" readonly>'
];
feat_table.push(JSON.stringify(vfeatures, null, 2));
feat_table = feat_table.join('') + '</textarea>';
featreselem.html(feat_table);
// update the cptools tracker with the results for this
// object
// if this objectid is in the tracker
if (cpobjectid in cptools.allobjects) {
if ('varinfo' in cptools.allobjects[cpobjectid]) {
cptools.allobjects[
cpobjectid
]['varinfo']['varfeatures'] = vfeatures;
}
else {
cptools.allobjects[cpobjectid] = {
varinfo:{
varfeatures: vfeatures
}
};
}
}
// if it's not in the tracker, add it
else {
cptools.allobjects[cpobjectid] = reqresult;
}
// update the cptools currentresults with these results
if ('varinfo' in cptools.current) {
cptools.current['varinfo']['varfeatures'] = vfeatures;
}
else {
cptools.current['varinfo'] = {varfeatures: vfeatures};
}
// add a warning to the alert box if there was one
if (reqstatus == 'warning') {
// show the error if something exploded
// but only if we're on the right objectid.
var errmsg = '<span class="text-warning">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
}
// update the tool queue
// fade out and remove the matching entry
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-primary">DONE<span>');
tqboxelem.fadeOut(2000, function () {
$(this).remove();
});
// clear out the alert box only if we're on the same
// objectid
$('#alert-box').empty();
}
// if the user has moved on...
else {
console.log('results received for ' + cpobjectid +
' but user has moved to ' + currobjectid +
', updated tracker...');
// if this objectid is in the tracker
if (cpobjectid in cptools.allobjects) {
if ('varinfo' in cptools.allobjects[cpobjectid]) {
cptools.allobjects[
cpobjectid
]['varinfo']['varfeatures'] = vfeatures;
}
else {
cptools.allobjects[cpobjectid] = {
varinfo:{
varfeatures: vfeatures
}
};
}
}
// if it's not in the tracker, add it
else {
cptools.allobjects[cpobjectid] = reqresult;
}
// update the tool queue
// fade out and remove the matching entry
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-primary">DONE<span>');
tqboxelem.fadeOut(2000, function () {
$(this).remove();
});
}
}
// if the request failed
else {
// show the error if something exploded but only if we're on
// the right objectid.
if (cpobjectid == currobjectid) {
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
}
// update the tool queue to show what happened
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-danger">FAILED<span>');
tqboxelem.fadeOut(2500, function () {
$(this).remove();
});
// update the cptools.failed tracker
var failedkey = lctooltocall + '-' + cpobjectid;
cptools.failed[failedkey] = reqmsg;
}
}).fail(function (xhr) {
// show the error - here we don't know which objectid was
// returned, so show the error wherever we are
var reqmsg = "could not run " + lctooltocall +
" because of a server error!";
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
});
},
new_phasedlc_plot: function () {
// get the current objectid and checkplot filename
var currobjectid = $('#objectid').text();
var currfname = $('#objectid').attr('data-fname');
// this is the lctool to call
var lctooltocall = 'phasedlc-newplot';
// this tracks any errors in input. we join them all with <br>
// and show them in the alert box.
var messages = [];
// this tracks if we're ok to proceed
var proceed = true;
// collect the form values
var plotperiod = parseFloat($('#psearch-plotperiod').val());
var plotepoch = parseFloat($('#psearch-plotepoch').val());
var plotxlim = $('#psearch-plotxlim').val();
if (plotxlim != '') {
plotxlim = plotxlim.replace(']','').replace('[','').split(', ');
plotxlim = [parseFloat(plotxlim[0]), parseFloat(plotxlim[1])];
// if the plot limits aren't the default, then we probably want
// xliminsetmode on
if ((plotxlim[1] - plotxlim[0]) > 1.0) {
var xliminsetmode = false;
}
else {
var xliminsetmode = true;
}
}
else {
var xliminsetmode = false;
}
var phasebin = parseFloat($('#psearch-binphase').val());
var periodind = $('#psearch-pgrampeaks').val();
if (periodind === null || periodind == 'none') {
periodind = 0;
}
else {
periodind = parseInt(periodind.split('|')[0]);
}
var lspmethod = $('#psearch-lspmethod').val();
var magsarefluxes = $('#psearch-magsarefluxes').prop('checked');
// see if we can proceed
if ((isNaN(plotperiod)) || (plotperiod < 0.0)) {
messages.push("plot period is invalid")
proceed = false;
}
if ((isNaN(plotepoch)) || (plotepoch < 0.0)) {
messages.push(
"plot epoch not provided or invalid, set to automatic"
)
proceed = true;
plotepoch = null;
}
if ((isNaN(plotxlim[0])) ||
(plotxlim[0] < -1.0) ||
(plotxlim[0] > plotxlim[1])) {
messages.push("plot x-axis lower limit is invalid")
proceed = false;
}
if ((isNaN(plotxlim[1])) ||
(plotxlim[1] > 1.0) ||
(plotxlim[1] < plotxlim[0])) {
messages.push("plot x-axis upper limit is invalid")
proceed = false;
}
if ((isNaN(phasebin)) ||
(phasebin > 0.25) ||
(phasebin < 0.0)) {
messages.push("plot phase bin size is invalid")
proceed = false;
}
// get the specified sigma clip
var sigclip = $('#psearch-sigclip').val();
if (sigclip.length > 0) {
// try to see if this is a composite sigma clip for lo, hi
if (sigclip.indexOf(',') != -1) {
sigclip = sigclip.trim().split(',');
sigclip = [sigclip[0].trim(), sigclip[1].trim()];
sigclip = [parseFloat(sigclip[0]), parseFloat(sigclip[1])];
if (isNaN(sigclip[0]) || isNaN(sigclip[1]) ||
(sigclip[0] < 0) || (sigclip[1] < 0)) {
messages.push("one or both sigclip values is invalid");
proceed = false;
}
}
// if a single sigma clip, parse it
else {
sigclip = parseFloat(sigclip.trim());
if (isNaN(sigclip) || sigclip < 0) {
messages.push("sigclip value is invalid");
proceed = false;
}
else {
sigclip = [sigclip, sigclip];
}
}
}
else {
sigclip = null;
}
// finally, get the lctimefilters and lcmagfilters
// these will be processed server-side so nothing is required here
var lctimefilters = $('#psearch-timefilters').val();
if (lctimefilters.length == 0) {
lctimefilters = null;
}
var lcmagfilters = $('#psearch-magfilters').val();
if (lcmagfilters.length == 0) {
lcmagfilters = null;
}
// don't go any further if the input is valid
if (!proceed) {
// generate the alert box messages
messages = messages.join("<br>");
$('#alert-box').html('<span class="text-warning">' +
messages +
'</span>');
}
// otherwise, we're good to go
else {
// generate the alert box messages
messages.push("making phased LC plot...");
messages = messages.join("<br>");
cpv.make_spinner('<span class="text-primary">' +
messages +
'</span><br>');
// generate the tool queue box
var tqbox = '<div class="tq-box" data-objectid="' + currobjectid +
'" data-fname="' + currfname +
'" data-lctool="' + lctooltocall +
'" data-toolstate="running">' +
'<strong>' + currobjectid + '</strong><br>' +
lctooltocall + ' — ' +
'<span class="tq-state">running</span></div>';
$('.tool-queue').append(tqbox);
// the call to the backend
var ajaxurl = '/tools/' + cputils.b64_encode(cpv.currfile);
// this is the data object to send to the backend
var sentdata = {
// common stuff
objectid: currobjectid,
lctool: lctooltocall,
forcereload: true,
// request values
magsarefluxes: magsarefluxes,
lspmethod: lspmethod,
periodind: periodind,
varperiod: plotperiod,
varepoch: plotepoch,
xliminsetmode: xliminsetmode,
plotxlim: plotxlim,
phasebin: phasebin,
sigclip: sigclip,
lctimefilters: lctimefilters,
lcmagfilters: lcmagfilters
};
console.log(sentdata);
// make the call
$.getJSON(ajaxurl, sentdata, function (recvdata) {
// the received data is in the standard form
var reqstatus = recvdata.status;
var reqmsg = recvdata.message;
var reqresult = recvdata.result;
var cpobjectid = reqresult.objectid;
// update this after we get back from the AJAX call
var currobjectid = $('#objectid').text();
if (reqstatus == 'success' || reqstatus == 'warning') {
var lsp = reqresult[lspmethod];
// only update if the user is still on the object
// we started with
if (cpobjectid == currobjectid) {
var lckey = 'phasedlc' + periodind;
// put the phased LC for the best period into
// #psearch-phasedlc-display
cputils.b64_to_image(lsp[lckey]['plot'],
'#psearch-phasedlc-display');
// update the text box for epoch using the returned
// value from the plotter
$('#psearch-plotepoch').val(lsp[lckey]['epoch']);
// update the global object period and epoch with the
// period and epoch used here if told to do so
var pupdate = $('#psearch-updateperiod').prop('checked');
var eupdate = $('#psearch-updateepoch').prop('checked');
if (pupdate) {
$('#objectperiod').val(plotperiod);
}
if (eupdate) {
$('#objectepoch').val(plotepoch);
}
// update current cptools object
if (lspmethod in cptools.current) {
cptools.current[lspmethod][lckey] = lsp[lckey];
}
else {
cptools.current[lspmethod] = {lckey: lsp[lckey]};
}
// update cptools tracker
if (cpobjectid in cptools.allobjects) {
if (lspmethod in cptools.allobjects[cpobjectid]) {
cptools.allobjects[
cpobjectid
][lspmethod][lckey] = lsp[lckey];
}
else {
cptools.allobjects[
cpobjectid
][lspmethod] = {lckey: lsp[lckey]};
}
}
else {
cptools.allobjects[cpobjectid] = reqresult;
}
// add a warning to the alert box if there was one
if (reqstatus == 'warning') {
// show the error if something exploded
// but only if we're on the right objectid.
var errmsg = '<span class="text-warning">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
}
// update the tool queue
// fade out and remove the matching entry
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-primary">DONE<span>');
tqboxelem.fadeOut(2000, function () {
$(this).remove();
});
// clear out the alert box only if we're on the same
// objectid
$('#alert-box').empty();
}
// if the user has moved on...
else {
console.log('results received for ' + cpobjectid +
' but user has moved to ' + currobjectid +
', updated tracker...');
// update cptools tracker
if (cpobjectid in cptools.allobjects) {
if (lspmethod in cptools.allobjects[cpobjectid]) {
cptools.allobjects[
cpobjectid
][lspmethod][lckey] = lsp[lckey];
}
else {
cptools.allobjects[
cpobjectid
][lspmethod] = {lckey: lsp[lckey]};
}
}
else {
cptools.allobjects[cpobjectid] = reqresult;
}
// update the tool queue
// fade out and remove the matching entry
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-primary">DONE<span>');
tqboxelem.fadeOut(2000, function () {
$(this).remove();
});
}
}
// if the request failed
else {
// show the error if something exploded but only if we're on
// the right objectid.
if (cpobjectid == currobjectid) {
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
}
// update the tool queue to show what happened
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-danger">FAILED<span>');
tqboxelem.fadeOut(2500, function () {
$(this).remove();
});
// update the cptools.failed tracker
var failedkey = lctooltocall + '-' + cpobjectid;
cptools.failed[failedkey] = reqmsg;
}
}).fail(function (xhr) {
// show the error - here we don't know which objectid was
// returned, so show the error wherever we are
var reqmsg = "could not run " + lctooltocall +
" because of a server error!";
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
});
}
},
prewhiten_lightcurve: function () {
// get the current objectid and checkplot filename
var currobjectid = $('#objectid').text();
var currfname = $('#objectid').attr('data-fname');
// this is the lctool to call
var lctooltocall = 'var-prewhiten';
// this tracks any errors in input. we join them all with <br>
// and show them in the alert box.
var messages = [];
// generate the alert box messages
messages.push("getting variability features...");
messages = messages.join("<br>");
cpv.make_spinner('<span class="text-primary">' +
messages +
'</span><br>');
// generate the tool queue box
var tqbox = '<div class="tq-box" data-objectid="' + currobjectid +
'" data-fname="' + currfname +
'" data-lctool="' + lctooltocall +
'" data-toolstate="running">' +
'<strong>' + currobjectid + '</strong><br>' +
lctooltocall + ' — ' +
'<span class="tq-state">running</span></div>';
$('.tool-queue').append(tqbox);
// the call to the backend
var ajaxurl = '/tools/' + cputils.b64_encode(cpv.currfile);
// this is the data object to send to the backend
var sentdata = {
objectid: currobjectid,
lctool: lctooltocall,
forcereload: true,
};
// make the call
$.getJSON(ajaxurl, sentdata, function (recvdata) {
// the received data is in the standard form
var reqstatus = recvdata.status;
var reqmsg = recvdata.message;
var reqresult = recvdata.result;
var cpobjectid = reqresult.objectid;
// update this after we get back from the AJAX call
var currobjectid = $('#objectid').text();
if (reqstatus == 'success' || reqstatus == 'warning') {
// only update if the user is still on the object
// we started with
if (cpobjectid == currobjectid) {
}
// if the user has moved on...
else {
}
}
// if the request failed
else {
// show the error if something exploded but only if we're on
// the right objectid.
if (cpobjectid == currobjectid) {
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
}
// update the tool queue to show what happened
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-danger">FAILED<span>');
tqboxelem.fadeOut(2500, function () {
$(this).remove();
});
// update the cptools.failed tracker
var failedkey = lctooltocall + '-' + cpobjectid;
cptools.failed[failedkey] = reqmsg;
}
}).fail(function (xhr) {
// show the error - here we don't know which objectid was
// returned, so show the error wherever we are
var reqmsg = "could not run " + lctooltocall +
" because of a server error!";
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
});
},
mask_signal: function () {
// get the current objectid and checkplot filename
var currobjectid = $('#objectid').text();
var currfname = $('#objectid').attr('data-fname');
// this is the lctool to call
var lctooltocall = 'var-masksig';
// this tracks any errors in input. we join them all with <br>
// and show them in the alert box.
var messages = [];
// generate the alert box messages
messages.push("getting variability features...");
messages = messages.join("<br>");
cpv.make_spinner('<span class="text-primary">' +
messages +
'</span><br>');
// generate the tool queue box
var tqbox = '<div class="tq-box" data-objectid="' + currobjectid +
'" data-fname="' + currfname +
'" data-lctool="' + lctooltocall +
'" data-toolstate="running">' +
'<strong>' + currobjectid + '</strong><br>' +
lctooltocall + ' — ' +
'<span class="tq-state">running</span></div>';
$('.tool-queue').append(tqbox);
// the call to the backend
var ajaxurl = '/tools/' + cputils.b64_encode(cpv.currfile);
// this is the data object to send to the backend
var sentdata = {
objectid: currobjectid,
lctool: lctooltocall,
forcereload: true,
};
// make the call
$.getJSON(ajaxurl, sentdata, function (recvdata) {
// the received data is in the standard form
var reqstatus = recvdata.status;
var reqmsg = recvdata.message;
var reqresult = recvdata.result;
var cpobjectid = reqresult.objectid;
// update this after we get back from the AJAX call
var currobjectid = $('#objectid').text();
if (reqstatus == 'success' || reqstatus == 'warning') {
// only update if the user is still on the object
// we started with
if (cpobjectid == currobjectid) {
}
// if the user has moved on...
else {
}
}
// if the request failed
else {
// show the error if something exploded but only if we're on
// the right objectid.
if (cpobjectid == currobjectid) {
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
}
// update the tool queue to show what happened
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-danger">FAILED<span>');
tqboxelem.fadeOut(2500, function () {
$(this).remove();
});
// update the cptools.failed tracker
var failedkey = lctooltocall + '-' + cpobjectid;
cptools.failed[failedkey] = reqmsg;
}
}).fail(function (xhr) {
// show the error - here we don't know which objectid was
// returned, so show the error wherever we are
var reqmsg = "could not run " + lctooltocall +
" because of a server error!";
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
});
},
lcfit_magseries: function () {
// get the current objectid and checkplot filename
var currobjectid = $('#objectid').text();
var currfname = $('#objectid').attr('data-fname');
// get which period search to run
var fitmethod = $('#lcfit-fitmethod').val();
// this is the lctool to call
var lctooltocall = 'lcfit-' + fitmethod;
// this tracks any errors in input. we join them all with <br>
// and show them in the alert box.
var messages = [];
// this tracks if we're ok to proceed
var proceed = false;
// generate the alert box messages
messages.push("getting variability features...");
messages = messages.join("<br>");
cpv.make_spinner('<span class="text-primary">' +
messages +
'</span><br>');
// generate the tool queue box
var tqbox = '<div class="tq-box" data-objectid="' + currobjectid +
'" data-fname="' + currfname +
'" data-lctool="' + lctooltocall +
'" data-toolstate="running">' +
'<strong>' + currobjectid + '</strong><br>' +
lctooltocall + ' — ' +
'<span class="tq-state">running</span></div>';
$('.tool-queue').append(tqbox);
// the call to the backend
var ajaxurl = '/tools/' + cputils.b64_encode(cpv.currfile);
// this is the data object to send to the backend
var sentdata = {
objectid: currobjectid,
lctool: lctooltocall,
forcereload: true,
};
// make the call
$.getJSON(ajaxurl, sentdata, function (recvdata) {
// the received data is in the standard form
var reqstatus = recvdata.status;
var reqmsg = recvdata.message;
var reqresult = recvdata.result;
var cpobjectid = reqresult.objectid;
// update this after we get back from the AJAX call
var currobjectid = $('#objectid').text();
if (reqstatus == 'success' || reqstatus == 'warning') {
// only update if the user is still on the object
// we started with
if (cpobjectid == currobjectid) {
}
// if the user has moved on...
else {
}
}
// if the request failed
else {
// show the error if something exploded but only if we're on
// the right objectid.
if (cpobjectid == currobjectid) {
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
}
// update the tool queue to show what happened
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-danger">FAILED<span>');
tqboxelem.fadeOut(2500, function () {
$(this).remove();
});
// update the cptools.failed tracker
var failedkey = lctooltocall + '-' + cpobjectid;
cptools.failed[failedkey] = reqmsg;
}
}).fail(function (xhr) {
// show the error - here we don't know which objectid was
// returned, so show the error wherever we are
var reqmsg = "could not run " + lctooltocall +
" because of a server error!";
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
});
},
action_setup: function () {
///////////////////////
// PERIOD SEARCH TAB //
///////////////////////
// periodogram method select - change options as needed
$('#psearch-lspmethod').on('change', function (evt) {
var newval = $(this).val();
// FIXME: update the psearch param panel for any special params for
// this period-finder
var extraparamelem = $('#psearch-pf-extraparams');
extraparamelem.empty();
if (newval == 'acf') {
extraparamelem.append(
'<div class="form-group">' +
'<label for="psearch-smoothacf">' +
'ACF smoothing parameter' +
'</label>' +
'<input type="text" name="smoothacf" ' +
'class="form-control form-control-sm pf-extraparam" ' +
'id="psearch-smoothacf" value="721"></div>'
);
extraparamelem.append(
'<div class="form-group">' +
'<label for="psearch-fillgaps">' +
'Fill value for time-series gaps' +
'</label>' +
'<input type="text" name="fillgaps" ' +
'class="form-control form-control-sm pf-extraparam" ' +
'id="psearch-fillgaps" value="0.0"></div>'
);
}
else if (newval == 'aov') {
extraparamelem.append(
'<div class="form-group">' +
'<label for="psearch-phasebinsize">' +
'Phase bin size' +
'</label>' +
'<input type="text" name="phasebinsize" ' +
'class="form-control form-control-sm pf-extraparam" ' +
'id="psearch-phasebinsize" value="0.05"></div>'
);
extraparamelem.append(
'<div class="form-group">' +
'<label for="psearch-mindetperbin">' +
'Min observations per phase bin' +
'</label>' +
'<input type="text" name="mindetperbin" ' +
'class="form-control form-control-sm pf-extraparam" ' +
'id="psearch-mindetperbin" value="9"></div>'
);
}
else if (newval == 'bls') {
extraparamelem.append(
'<div class="form-group">' +
'<label for="psearch-mintransitduration">' +
'Min transit duration [fractional phase]' +
'</label>' +
'<input type="text" name="mintransitduration" ' +
'class="form-control form-control-sm pf-extraparam" ' +
'id="psearch-mintransitduration" value="0.01"></div>'
);
extraparamelem.append(
'<div class="form-group">' +
'<label for="psearch-maxtransitduration">' +
'Max transit duration [fractional phase]' +
'</label>' +
'<input type="text" name="maxtransitduration" ' +
'class="form-control form-control-sm pf-extraparam" ' +
'id="psearch-maxtransitduration" value="0.8"></div>'
);
}
else if (newval == 'gls') {
}
else if (newval == 'mav') {
extraparamelem.append(
'<div class="form-group">' +
'<label for="psearch-nharmonics">' +
'Number of harmonics' +
'</label>' +
'<input type="text" name="nharmonics" ' +
'class="form-control form-control-sm pf-extraparam" ' +
'id="psearch-nharmonics" value="6"></div>'
);
}
else if (newval == 'pdm') {
extraparamelem.append(
'<div class="form-group">' +
'<label for="psearch-phasebinsize">' +
'Phase bin size' +
'</label>' +
'<input type="text" name="phasebinsize" ' +
'class="form-control form-control-sm pf-extraparam" ' +
'id="psearch-phasebinsize" value="0.05"></div>'
);
extraparamelem.append(
'<div class="form-group">' +
'<label for="psearch-mindetperbin">' +
'Min observations per phase bin' +
'</label>' +
'<input type="text" name="mindetperbin" ' +
'class="form-control form-control-sm pf-extraparam" ' +
'id="psearch-mindetperbin" value="9"></div>'
);
}
});
// periodogram search - half period
$('#psearch-halfperiod').on('click', function (evt) {
evt.preventDefault();
var plotperiod = parseFloat($('#psearch-plotperiod').val());
if (!isNaN(plotperiod)) {
$('#psearch-plotperiod').val(plotperiod/2.0);
}
});
// periodogram search - 2x period
$('#psearch-doubleperiod').on('click', function (evt) {
evt.preventDefault();
var plotperiod = parseFloat($('#psearch-plotperiod').val());
if (!isNaN(plotperiod)) {
$('#psearch-plotperiod').val(plotperiod*2.0);
}
});
// periodogram search - add half period to epoch
$('#psearch-addhalfp-epoch').on('click', function (evt) {
evt.preventDefault();
var plotperiod = parseFloat($('#psearch-plotperiod').val());
var plotepoch = parseFloat($('#psearch-plotepoch').val());
if (!isNaN(plotperiod) && !isNaN(plotepoch)) {
$('#psearch-plotepoch').val(plotepoch + plotperiod/2.0);
}
});
// periodogram search - subtract half period to epoch
$('#psearch-subhalfp-epoch').on('click', function (evt) {
evt.preventDefault();
var plotperiod = parseFloat($('#psearch-plotperiod').val());
var plotepoch = parseFloat($('#psearch-plotepoch').val());
if (!isNaN(plotperiod) && !isNaN(plotepoch)) {
$('#psearch-plotepoch').val(plotepoch - plotperiod/2.0);
}
});
// periodogram search - plot phased LC
$('#psearch-makephasedlc').on('click', function (evt) {
evt.preventDefault();
cptools.new_phasedlc_plot();
});
// periodogram search - periodogram peak select
$('#psearch-pgrampeaks').on('change', function (evt) {
var newval = $(this).val().split('|');
$('#psearch-plotperiod').val(newval[1]);
$('#psearch-plotepoch').val(newval[2]);
});
// periodogram search - start
$('#psearch-start').on('click', function (evt) {
evt.preventDefault();
cptools.run_periodsearch();
});
// periodogram search - handle autofreq
$('#psearch-autofreq').on('click', function (evt) {
var thischecked = $(this).prop('checked');
if (!thischecked) {
$('#psearch-startp').prop('disabled',false);
$('#psearch-endp').prop('disabled',false);
$('#psearch-freqstep').prop('disabled',false);
}
else {
$('#psearch-startp').prop('disabled',true);
$('#psearch-endp').prop('disabled',true);
$('#psearch-freqstep').prop('disabled',true);
}
});
// FIXME: bind the periodogram select so it looks for existing periods
// for that periodogram method and loads them into the period select
// box.
/////////////////////
// VARIABILITY TAB //
/////////////////////
// variability - get variability features
$('#get-varfeatures').on('click', function (evt) {
evt.preventDefault();
cptools.get_varfeatures();
});
////////////////
// LC FIT TAB //
////////////////
////////////////////
// SAVE/RESET TAB //
////////////////////
}
};
|
astrobase/cpserver/cps-assets/cpserver.js
|
// cpserver.js - Waqas Bhatti ([email protected]) - Jan 2017
// License: MIT. See LICENSE for the full text.
//
// This contains the JS to drive the checkplotserver's interface.
//
//////////////
// JS BELOW //
//////////////
// this contains utility functions
var cputils = {
// this encodes a string to base64
// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
b64_encode: function (str) {
return btoa(
encodeURIComponent(str)
.replace(/%([0-9A-F]{2})/g,
function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
},
// this turns a base64 string into an image by updating its source
b64_to_image: function (str, targetelem) {
var datauri = 'data:image/png;base64,' + str;
$(targetelem).attr('src',datauri);
},
// this displays a base64 encoded image on the canvas
b64_to_canvas: function (str, targetelem) {
var datauri = 'data:image/png;base64,' + str;
var newimg = new Image();
var canvas = document.getElementById(targetelem.replace('#',''));
var imgheight = 300;
var imgwidth = 300;
var cnvwidth = canvas.width;
canvas.height = cnvwidth;
var imgscale = cnvwidth/imgwidth;
var ctx = canvas.getContext('2d');
// this event listener will fire when the image is loaded
newimg.addEventListener('load', function () {
ctx.drawImage(newimg,
0,
0,
imgwidth*imgscale,
imgheight*imgscale);
});
// load the image and fire the listener
newimg.src = datauri;
},
// this holds imagedata for the canvas so we can restore changed parts of
// the image
pixeltracker: null
};
// this contains updates to current checkplots, tracks the entire project's info
// and provides functions to save everything to CSV or JSON
var cptracker = {
// this is a list of all checkplots
checkplotlist: [],
// this is the actual object that will get written to JSON or CSV
cpdata: {},
// this is the order of columns for generating the CSV
infocolumns: [
'objectid',
'checkplot',
'objectinfo.twomassid',
'objectinfo.network',
'objectinfo.stations',
'objectinfo.ndet',
'objectinfo.objecttags',
'objectinfo.umag',
'objectinfo.bmag',
'objectinfo.vmag',
'objectinfo.rmag',
'objectinfo.imag',
'objectinfo.sdssu',
'objectinfo.sdssg',
'objectinfo.sdssr',
'objectinfo.sdssi',
'objectinfo.sdssz',
'objectinfo.jmag',
'objectinfo.hmag',
'objectinfo.kmag',
'objectinfo.ujmag',
'objectinfo.uhmag',
'objectinfo.ukmag',
'objectinfo.irac1',
'objectinfo.irac2',
'objectinfo.irac3',
'objectinfo.irac4',
'objectinfo.wise1',
'objectinfo.wise2',
'objectinfo.wise3',
'objectinfo.wise4',
'objectinfo.deredb',
'objectinfo.deredv',
'objectinfo.deredu',
'objectinfo.deredg',
'objectinfo.deredr',
'objectinfo.deredi',
'objectinfo.deredz',
'objectinfo.deredj',
'objectinfo.deredh',
'objectinfo.deredk',
'objectinfo.dered_umag',
'objectinfo.dered_bmag',
'objectinfo.dered_vmag',
'objectinfo.dered_rmag',
'objectinfo.dered_imag',
'objectinfo.dered_jmag',
'objectinfo.dered_hmag',
'objectinfo.dered_kmag',
'objectinfo.dered_sdssu',
'objectinfo.dered_sdssg',
'objectinfo.dered_sdssr',
'objectinfo.dered_sdssi',
'objectinfo.dered_sdssz',
'objectinfo.dered_ujmag',
'objectinfo.dered_uhmag',
'objectinfo.dered_ukmag',
'objectinfo.dered_irac1',
'objectinfo.dered_irac2',
'objectinfo.dered_irac3',
'objectinfo.dered_irac4',
'objectinfo.dered_wise1',
'objectinfo.dered_wise2',
'objectinfo.dered_wise3',
'objectinfo.dered_wise4',
'objectinfo.bvcolor',
'objectinfo.gjcolor',
'objectinfo.ijcolor',
'objectinfo.jkcolor',
'objectinfo.gkcolor',
'objectinfo.vkcolor',
'objectinfo.ugcolor',
'objectinfo.grcolor',
'objectinfo.ricolor',
'objectinfo.izcolor',
'objectinfo.sdssu-sdssg',
'objectinfo.sdssg-sdssr',
'objectinfo.sdssr-sdssi',
'objectinfo.sdssi-sdssz',
'objectinfo.sdssg-sdssi',
'objectinfo.sdssg-jmag',
'objectinfo.sdssg-kmag',
'objectinfo.umag-bmag',
'objectinfo.bmag-vmag',
'objectinfo.vmag-rmag',
'objectinfo.vmag-imag',
'objectinfo.rmag-imag',
'objectinfo.vmag-kmag',
'objectinfo.jmag-hmag',
'objectinfo.hmag-kmag',
'objectinfo.jmag-kmag',
'objectinfo.dereddened',
'objectinfo.bmagfromjhk',
'objectinfo.vmagfromjhk',
'objectinfo.sdssufromjhk',
'objectinfo.sdssgfromjhk',
'objectinfo.sdssrfromjhk',
'objectinfo.sdssifromjhk',
'objectinfo.sdsszfromjhk',
'objectinfo.color_classes',
'objectinfo.ra',
'objectinfo.decl',
'objectinfo.gl',
'objectinfo.gb',
'objectinfo.pmra',
'objectinfo.pmra_err',
'objectinfo.pmdecl',
'objectinfo.pmdecl_err',
'objectinfo.propermotion',
'objectinfo.rpmj',
'objectinfo.reducedpropermotion',
'objectinfo.gaiamag',
'objectinfo.gaia_parallax',
'objectinfo.gaia_parallax_err',
'objectinfo.neighbors',
'objectinfo.closestdistarcsec',
'objectinfo.gaia_neighbors',
'objectinfo.gaia_closest_distarcsec',
'objectinfo.gaia_closest_gmagdiff',
'objectinfo.d_ug',
'objectinfo.d_gr',
'objectinfo.s_color',
'objectinfo.l_color',
'objectinfo.v_color',
'objectinfo.p1_color',
'objectinfo.m_sti',
'objectinfo.m_sts',
'objectinfo.extinctb',
'objectinfo.extinctv',
'objectinfo.extinctu',
'objectinfo.extinctg',
'objectinfo.extinctr',
'objectinfo.extincti',
'objectinfo.extinctz',
'objectinfo.extinctj',
'objectinfo.extincth',
'objectinfo.extinctk',
'objectinfo.extinction_umag',
'objectinfo.extinction_bmag',
'objectinfo.extinction_vmag',
'objectinfo.extinction_rmag',
'objectinfo.extinction_imag',
'objectinfo.extinction_sdssu',
'objectinfo.extinction_sdssg',
'objectinfo.extinction_sdssr',
'objectinfo.extinction_sdssi',
'objectinfo.extinction_sdssz',
'objectinfo.extinction_jmag',
'objectinfo.extinction_hmag',
'objectinfo.extinction_kmag',
'varinfo.objectisvar',
'varinfo.varperiod',
'varinfo.varepoch',
'varinfo.vartags',
'comments'
],
// this function generates a CSV row for a single object in the
// cptracker.cpdata object
cpdata_get_csvrow: function (cpdkey, separator) {
var thisdata = cptracker.cpdata[cpdkey];
var rowarr = [];
cptracker.infocolumns.forEach(function (e, i, a) {
// if the key is a compound one (firstlev.secondlev)
if (e.indexOf('.') != -1) {
var keys = e.split('.');
rowarr.push(thisdata[keys[0]][keys[1]]);
}
// otherwise, it's just in the first level
else {
// special case of checkplot filename
if (e == 'checkplot') {
rowarr.push(cpdkey);
}
else {
rowarr.push(thisdata[e]);
}
}
});
// join the output row
var csvrow = rowarr.join(separator);
return csvrow
},
// this generates a CSV for download
cpdata_to_csv: function () {
var csvarr = [cptracker.infocolumns.join('|')];
for (obj in cptracker.cpdata) {
csvarr.push(cptracker.cpdata_get_csvrow(obj,'|'));
}
csvarr = "data:text/csv;charset=utf-8," +
encodeURIComponent(csvarr.join('\n'));
$('#download-anchor').attr('href', csvarr);
$('#download-anchor').attr('download', 'project-objectlist.csv');
$('#download-anchor').html('get CSV for reviewed objects');
$('#download-anchor').css({'display': 'inline'});
},
// this generates a JSON for download
cpdata_to_json: function () {
// we need to reverse the keys of the cpdata, so they're objectid first,
// add the object's checkplot file into its own dict
var jsonobj = {};
for (obj in cptracker.cpdata) {
var thisdata = cptracker.cpdata[obj];
thisdata['checkplot'] = obj;
jsonobj[thisdata['objectid']] = thisdata;
}
// generate the string
var jsonstr = "data:text/json;charset=utf-8," +
encodeURIComponent(JSON.stringify(jsonobj));
$('#download-anchor').attr('href', jsonstr);
$('#download-anchor').attr('download', 'project-objectlist.json');
$('#download-anchor').html('get JSON for reviewed objects');
$('#download-anchor').css({'display': 'inline'});
},
// this saves a single object back to the checkplotlist JSON
reviewed_object_to_cplist: function () {
var saveinfo = {checkplot: cpv.currfile,
varinfo: cpv.currcp.varinfo,
objectinfo: cpv.currcp.objectinfo,
comments: cpv.currcp.comments}
var postmsg = {objectid: cpv.currcp.objectid,
changes: JSON.stringify(saveinfo)}
if (cpv.readonlymode) {
// if we're in readonly mode, inform the user
$('#alert-box').html(
'The checkplot server is in readonly mode. ' +
'Edits to object information will not be saved.'
);
}
// if we're not in readonly mode, post the results
else {
// send this back to the checkplotserver
$.post('/list', postmsg, function (data) {
var success = data.status;
var message = data.message;
var result = data.result;
if (!success) {
$('#alert-box').html('could not save info for <strong>' +
postmsg.objectid + '</strong>!');
console.log('saving the changes back to the '+
'JSON file failed for ' + postmsg.objectid);
}
}, 'json').fail(function (xhr) {
$('#alert-box').html('could not save info for <strong>' +
postmsg.objectid + '</strong>!');
console.log('saving the changes back to the '+
'JSON file failed for ' + postmsg.objectid);
});
}
},
// this loads all the reviewed objects from the current project's JSON
// checkplot file list, and updates the reviewed objects list
all_reviewed_from_cplist: function () {
$.getJSON('/list', function (data) {
var reviewedobjects = data.reviewed;
// generate the object info rows and append to the reviewed object
// list
for (obj in reviewedobjects) {
var objdict = reviewedobjects[obj];
var objectid = obj;
var objcp = objdict.checkplot;
var objectinfo = objdict.objectinfo;
var varinfo = objdict.varinfo;
// generate the new list element: this contains objectid -
// variability flag, variability tags, object tags
var objectidelem = '<div class="tracker-obj" data-objectid="' +
objectid +
'"><a href="#" class="objload-checkplot" ' +
'data-fname="' + objcp + '" ';
if (varinfo.objectisvar == '1') {
objectidelem = objectidelem +
'data-objectisvar="1"' +
'>' +
objectid + '</a>: ' +
'variable';
}
else if (varinfo.objectisvar == '2') {
objectidelem = objectidelem +
'data-objectisvar="2"' +
'>' +
objectid + '</a>: ' +
'not variable';
}
else if (varinfo.objectisvar == '3') {
objectidelem = objectidelem +
'data-objectisvar="3"' +
'>' +
objectid + '</a>: ' +
'maybe variable';
}
else if (varinfo.objectisvar == '0') {
objectidelem = objectidelem +
'data-objectisvar="0"' +
'>' +
objectid + '</a>: ' +
'no varflag set';
}
if (varinfo.vartags != null) {
var thisvartags =
varinfo.vartags.split(', ');
if (thisvartags[0].length > 0) {
objectidelem = objectidelem + ' ';
thisvartags.forEach(function (e, i, a) {
objectidelem = objectidelem +
'<span class="cp-tag">' +
e + '</span> ';
});
}
}
if (objectinfo.objecttags != null) {
var thisobjtags =
objectinfo.objecttags.split(', ');
if (thisobjtags[0].length > 0) {
objectidelem = objectidelem + ' ';
thisobjtags.forEach(function (e, i, a) {
objectidelem = objectidelem +
'<span class="cp-tag">' +
e + '</span> ';
});
}
}
// finish the objectidelem li tag
objectidelem = objectidelem + '</div>';
$('#project-status').append(objectidelem);
// update the count in saved-count
var nsaved = $('#project-status div').length;
$('#saved-count').html(nsaved + '/' + cpv.totalcps);
}
}).fail(function (xhr) {
$('#alert-box').html('could not load the existing checkplot list');
console.log('could not load the existing checkplot list');
});
}
};
// this is the container for the main functions
var cpv = {
// these hold the current checkplot's data and filename respectively
currentfind: 0,
currfile: '',
currcp: {},
totalcps: 0,
cpfpng: null,
// this checks if the server is in readonly mode. disables controls if so.
readonlymode: false,
// these help in moving quickly through the phased LCs
currphasedind: null,
maxphasedind: null,
// this function generates a spinner
make_spinner: function (spinnermsg) {
var spinner = spinnermsg +
'<div class="spinner">' +
'<div class="rect1"></div>' +
'<div class="rect2"></div>' +
'<div class="rect3"></div>' +
'<div class="rect4"></div>' +
'<div class="rect5"></div>' +
'</div>';
$('#alert-box').html(spinner);
},
// this function generates an alert box
make_alert: function (alertmsg) {
var xalert =
'<div class="alert alert-warning alert-dismissible fade show" ' +
'role="alert">' +
'<button type="button" class="close" data-dismiss="alert" ' +
'aria-label="Close">' +
'<span aria-hidden="true">×</span>' +
'</button>' +
alertmsg +
'</div>';
$('#alert-box').html(xalert);
},
// this loads a checkplot from an image file into an HTML canvas object
load_checkplot: function (filename) {
// remove the summary download anchor from view since it's stale now
$('#download-anchor').css({'display': 'none'});
// start the spinny thing
cpv.make_spinner('loading...');
// build the title for this current file
var plottitle = $('#checkplot-current');
var filelink = filename;
var objectidelem = $('#objectid');
var twomassidelem = $('#twomassid');
plottitle.html(filelink);
if (cpv.currfile.length > 0) {
// un-highlight the previous file in side bar
$("a.checkplot-load")
.filter("[data-fname='" + cpv.currfile + "']")
.unwrap();
}
// do the AJAX call to get this checkplot
var ajaxurl = '/cp/' + cputils.b64_encode(filename);
// add the current object's fname to the objectid data-fname
objectidelem.attr('data-fname', filename);
$.getJSON(ajaxurl, function (data) {
cpv.currcp = data.result;
console.log(cpv.currcp);
/////////////////////////////////////////////////
// update the UI with elems for this checkplot //
/////////////////////////////////////////////////
// update the readonly status
cpv.readonlymode = data.readonly;
// update the objectid header
objectidelem.html(cpv.currcp.objectid);
// update the twomassid header
if (cpv.currcp.objectinfo.twomassid != undefined) {
twomassidelem.html('2MASS J' + cpv.currcp.objectinfo.twomassid);
}
else {
twomassidelem.html('');
}
//
// first, update the period search tab
//
// update the time0 placeholders
$('.time0').html(cpv.currcp.time0);
// set the items in the filters from existing if possible
if (cpv.currcp.hasOwnProperty('uifilters')) {
if (cpv.currcp.uifilters != null &&
cpv.currcp.uifilters.psearch_timefilters != null) {
$('#psearch-timefilters').val(
cpv.currcp.uifilters.psearch_timefilters
);
}
else {
$('#psearch-timefilters').val('');
}
if (cpv.currcp.uifilters != null &&
cpv.currcp.uifilters.psearch_magfilters != null) {
$('#psearch-magfilters').val(
cpv.currcp.uifilters.psearch_magfilters
);
}
else {
$('#psearch-magfilters').val('');
}
if (cpv.currcp.uifilters != null &&
cpv.currcp.uifilters.psearch_sigclip != null) {
$('#psearch-sigclip').val(
cpv.currcp.uifilters.psearch_sigclip
);
}
else {
$('#psearch-sigclip').val('');
}
}
// otherwise, use default nothing
else {
$('#psearch-timefilters').val('');
$('#psearch-magfilters').val('');
$('#psearch-sigclip').val('');
}
//
// set up the rest of period-search tab
//
// set the period and epoch from the current period and epoch
if (cpv.currcp.varinfo.varperiod != null &&
cpv.currcp.varinfo.varepoch != null) {
$('#psearch-plotperiod').val(cpv.currcp.varinfo.varperiod);
$('#psearch-plotepoch').val(cpv.currcp.varinfo.varepoch);
$("#psearch-pgrampeaks").html(
'<option value="0|' + cpv.currcp.varinfo.varperiod + '|' +
cpv.currcp.varinfo.varepoch +
'">prev. saved period</option>'
);
}
else {
$("#psearch-pgrampeaks").html(
'<option value="none">no tool results yet</option>'
);
$('#psearch-plotperiod').val('');
$('#psearch-plotepoch').val('');
}
// these are the plot frames, nothing by default
$('#psearch-periodogram-display')
.attr('src','/static/no-tool-results.png');
$('#psearch-phasedlc-display')
.attr('src','/static/no-tool-results.png');
//
// update object information now
//
// update the finder chart
// cputils.b64_to_image(cpv.currcp.finderchart,
// '#finderchart');
cputils.b64_to_canvas(cpv.currcp.finderchart,
'#finderchart');
// get the HAT stations
var hatstations = cpv.currcp.objectinfo.stations;
if (hatstations != undefined && hatstations) {
var splitstations =
(String(hatstations).split(',')).join(', ');
}
else {
var splitstations = '';
}
// get the number of detections
var objndet = cpv.currcp.objectinfo.ndet;
if (objndet == undefined) {
objndet = cpv.currcp.magseries_ndet;
}
// update the objectinfo
var hatinfo = '<strong>' +
splitstations +
'</strong><br>' +
'<strong>LC points:</strong> ' + objndet;
$('#hatinfo').html(hatinfo);
// get the GAIA status (useful for G mags, colors, etc.)
if (cpv.currcp.objectinfo.gaia_status != undefined) {
var gaia_ok =
cpv.currcp.objectinfo.gaia_status.indexOf('ok') != -1;
var gaia_message =
cpv.currcp.objectinfo.gaia_status.split(':')[1];
}
else {
var gaia_ok = false;
var gaia_message = (
'no RA/DEC provided, so no GAIA cross-match possible'
);
console.log('no GAIA info');
}
//
// get the coordinates
//
// ra
if (cpv.currcp.objectinfo.ra != undefined) {
var objectra = math.format(
cpv.currcp.objectinfo.ra, 6
);
}
else {
var objectra = '';
}
// decl
if (cpv.currcp.objectinfo.decl != undefined) {
var objectdecl = math.format(
cpv.currcp.objectinfo.decl, 6
);
}
else {
var objectdecl = '';
}
// gl
if (cpv.currcp.objectinfo.gl != undefined) {
var objectgl = math.format(
cpv.currcp.objectinfo.gl, 6
);
}
else {
var objectgl = '';
}
// gb
if (cpv.currcp.objectinfo.gb != undefined) {
var objectgb = math.format(
cpv.currcp.objectinfo.gb, 6
);
}
else {
var objectgb = '';
}
// total proper motion
if (cpv.currcp.objectinfo.propermotion != undefined) {
var objectpm = math.format(
cpv.currcp.objectinfo.propermotion, 5
) + ' mas/yr';
}
else {
var objectpm = '';
}
// reduced proper motion [Jmag]
if (cpv.currcp.objectinfo.rpmj != undefined) {
var objectrpmj = math.format(
cpv.currcp.objectinfo.rpmj, 4
);
}
else if (cpv.currcp.objectinfo.reducedpropermotion != undefined) {
var objectrpmj = math.format(
cpv.currcp.objectinfo.reducedpropermotion, 4
);
}
else {
var objectrpmj = '';
}
// format the coordinates and PM
var coordspm =
'<strong>Equatorial (α, δ):</strong> ' +
'<a title="SIMBAD search at these coordinates" ' +
'href="http://simbad.u-strasbg.fr/simbad/sim-coo?Coord=' +
cpv.currcp.objectinfo.ra + '+' + cpv.currcp.objectinfo.decl +
'&Radius=1&Radius.unit=arcmin' +
'" rel="nofollow" target="_blank">' +
objectra + ', ' + objectdecl + '</a><br>' +
'<strong>Galactic (l, b):</strong> ' +
objectgl + ', ' + objectgb + '<br>' +
'<strong>Total PM:</strong> ' + objectpm + '<br>' +
'<strong>Reduced PM<sub>J</sub>:</strong> ' + objectrpmj;
// see if we can get the GAIA parallax
if (gaia_ok && cpv.currcp.objectinfo.gaia_parallaxes[0]) {
var gaia_parallax = math.format(
cpv.currcp.objectinfo.gaia_parallaxes[0], 5
);
coordspm = coordspm + '<br>' +
'<strong>GAIA parallax:</strong> ' +
gaia_parallax + ' mas';
}
$('#coordspm').html(coordspm);
//
// handle the mags
//
var magnotices = [];
if (cpv.currcp.objectinfo.bmagfromjhk != undefined &&
cpv.currcp.objectinfo.bmagfromjhk) {
magnotices.push('B');
}
if (cpv.currcp.objectinfo.vmagfromjhk != undefined &&
cpv.currcp.objectinfo.vmagfromjhk) {
magnotices.push('V');
}
if (cpv.currcp.objectinfo.sdssufromjhk != undefined &&
cpv.currcp.objectinfo.sdssufromjhk) {
magnotices.push('u');
}
if (cpv.currcp.objectinfo.sdssgfromjhk != undefined &&
cpv.currcp.objectinfo.sdssgfromjhk) {
magnotices.push('g');
}
if (cpv.currcp.objectinfo.sdssrfromjhk != undefined &&
cpv.currcp.objectinfo.sdssrfromjhk) {
magnotices.push('r');
}
if (cpv.currcp.objectinfo.sdssifromjhk != undefined &&
cpv.currcp.objectinfo.sdssifromjhk) {
magnotices.push('i');
}
if (cpv.currcp.objectinfo.sdsszfromjhk != undefined &&
cpv.currcp.objectinfo.sdsszfromjhk) {
magnotices.push('z');
}
if (magnotices.length > 0) {
$('#magnotice').html('<br>(' + magnotices.join('') +
' via JHK transform)');
}
// set up the cmdplots property for currcp
cpv.currcp.cmdplots = [];
if (gaia_ok) {
var gaiamag = cpv.currcp.objectinfo.gaia_mags[0];
if (cpv.currcp.objectinfo.gaiak_colors != null) {
var gaiakcolor = cpv.currcp.objectinfo.gaiak_colors[0];
}
else {
var gaiakcolor = null;
}
var gaiaabsmag = cpv.currcp.objectinfo.gaia_absolute_mags[0];
}
else {
var gaiamag = null;
var gaiakcolor = null;
var gaiaabsmag = null;
}
//
// now we need to handle both generations of checkplots
//
// this is for the current generation of checkplots
if (cpv.currcp.objectinfo.hasOwnProperty('available_bands')) {
var mind = 0;
var cind = 0;
var mlen = cpv.currcp.objectinfo['available_bands'].length;
var clen = cpv.currcp.objectinfo['available_colors'].length;
var maglabel_pairs = [];
var colorlabel_pairs = [];
var thiskey = null;
var thislabel = null;
var thisval = null;
// generate the mag-label pairs
for (mind; mind < mlen; mind++) {
thiskey = cpv.currcp.objectinfo['available_bands'][mind];
thislabel =
cpv.currcp.objectinfo['available_band_labels'][mind];
thisval = math.format(cpv.currcp.objectinfo[thiskey],
5);
maglabel_pairs.push('<span class="no-wrap-break">' +
'<strong><em>' +
thislabel +
'</em>:</strong> ' +
thisval +
'</span>');
}
// generate the color-label pairs
for (cind; cind < clen; cind++) {
thiskey = cpv.currcp.objectinfo['available_colors'][cind];
thislabel =
cpv.currcp.objectinfo['available_color_labels'][cind];
thisval = math.format(cpv.currcp.objectinfo[thiskey],
4);
if (cpv.currcp.objectinfo.dereddened != undefined &&
cpv.currcp.objectinfo.dereddened) {
thislabel = '(' + thislabel
+ ')<sub>0</sub>';
$('#derednotice').html('<br>(dereddened)');
}
else {
thislabel = '(' + thislabel + ')';
}
colorlabel_pairs.push('<span class="no-wrap-break">' +
'<strong><em>' +
thislabel +
'</em>:</strong> ' +
thisval +
'</span>');
}
// now add the GAIA information if it exists
maglabel_pairs.push(
'<span class="no-wrap-break">' +
'<strong><em>GAIA G</em>:</strong> ' +
math.format(gaiamag,5) +
'</span>'
);
maglabel_pairs.push(
'<span class="no-wrap-break">' +
'<strong><em>GAIA M<sub>G</sub></em>:</strong> ' +
math.format(gaiaabsmag,5) +
'</span>'
);
maglabel_pairs = maglabel_pairs.join(', ');
colorlabel_pairs = colorlabel_pairs.join(', ');
$('#mags').html(maglabel_pairs);
$('#colors').html(colorlabel_pairs);
}
// this is for the older generation of checkplots
else {
var mags = '<strong><em>ugriz</em>:</strong> ' +
math.format(cpv.currcp.objectinfo.sdssu,5) + ', ' +
math.format(cpv.currcp.objectinfo.sdssg,5) + ', ' +
math.format(cpv.currcp.objectinfo.sdssr,5) + ', ' +
math.format(cpv.currcp.objectinfo.sdssi,5) + ', ' +
math.format(cpv.currcp.objectinfo.sdssz,5) + '<br>' +
'<strong><em>JHK</em>:</strong> ' +
math.format(cpv.currcp.objectinfo.jmag,5) + ', ' +
math.format(cpv.currcp.objectinfo.hmag,5) + ', ' +
math.format(cpv.currcp.objectinfo.kmag,5) + '<br>' +
'<strong><em>BV</em>:</strong> ' +
math.format(cpv.currcp.objectinfo.bmag,5) + ', ' +
math.format(cpv.currcp.objectinfo.vmag,5) + '<br>' +
'<strong><em>GAIA G</em>:</strong> ' +
math.format(gaiamag,5) + ', ' +
'<strong><em>GAIA M<sub>G</sub></em>:</strong> ' +
math.format(gaiaabsmag,5);
$('#mags').html(mags);
//
// handle the colors
//
if (cpv.currcp.objectinfo.dereddened != undefined &&
cpv.currcp.objectinfo.dereddened) {
$('#derednotice').html('<br>(dereddened)');
var colors =
'<strong><em>(B - V)<sub>0</sub></em>:</strong> ' +
math.format(cpv.currcp.objectinfo.bvcolor,4) + ', ' +
'<strong><em>(V - K)<sub>0</sub></em>:</strong> ' +
math.format(cpv.currcp.objectinfo.vkcolor,4) + '<br>' +
'<strong><em>(J - K)<sub>0</sub></em>:</strong> ' +
math.format(cpv.currcp.objectinfo.jkcolor,4) + ', ' +
'<strong><em>(i - J)<sub>0</sub></em>:</strong> ' +
math.format(cpv.currcp.objectinfo.ijcolor,4) + '<br>' +
'<strong><em>(g - K)<sub>0</sub></em>:</strong> ' +
math.format(cpv.currcp.objectinfo.gkcolor,4) + ', ' +
'<strong><em>(g - r)<sub>0</sub></em>:</strong> ' +
math.format(cpv.currcp.objectinfo.grcolor,4);
}
else {
var colors =
'<strong><em>(B - V)</em>:</strong> ' +
math.format(cpv.currcp.objectinfo.bvcolor,4) + ', ' +
'<strong><em>(V - K)</em>:</strong> ' +
math.format(cpv.currcp.objectinfo.vkcolor,4) + '<br>' +
'<strong><em>(J - K)</em>:</strong> ' +
math.format(cpv.currcp.objectinfo.jkcolor,4) + ', ' +
'<strong><em>(i - J)</em>:</strong> ' +
math.format(cpv.currcp.objectinfo.ijcolor,4) + '<br>' +
'<strong><em>(g - K)</em>:</strong> ' +
math.format(cpv.currcp.objectinfo.gkcolor,4) + ', ' +
'<strong><em>(g - r)</em>:</strong> ' +
math.format(cpv.currcp.objectinfo.grcolor,4);
}
// format the colors
$('#colors').html(colors);
}
//
// additional stuff
//
// first, empty out the extra info table
$("#objectinfo-extra").empty();
// add the color classification if available
if (cpv.currcp.objectinfo.color_classes != undefined &&
cpv.currcp.objectinfo.color_classes.length > 0) {
var formatted_color_classes =
cpv.currcp.objectinfo.color_classes.join(', ');
$('#objectinfo-extra')
.append(
"<tr>" +
"<th>Color classification</th>" +
"<td>" + formatted_color_classes + "</td>" +
"</tr>"
);
}
// neighbors
if (cpv.currcp.objectinfo.neighbors != undefined ||
(cpv.currcp.objectinfo.gaia_ids != undefined &&
cpv.currcp.objectinfo.gaia_ids.length > 0) ) {
if (cpv.currcp.objectinfo.neighbors > 0) {
var formatted_neighbors =
'<strong><em>from LCs in collection</em>:</strong> ' +
cpv.currcp.objectinfo.neighbors + '<br>' +
'<em>closest distance</em>: ' +
math.format(cpv.currcp.objectinfo.closestdistarcsec,4) +
'″<br>';
}
else {
var formatted_neighbors =
'<strong><em>from LCs in collection</em>:</strong> 0<br>';
}
if (gaia_ok) {
var formatted_gaia =
'<strong><em>from GAIA</em>:</strong> ' +
(cpv.currcp.objectinfo.gaia_ids.length - 1) + '<br>' +
'<em>closest distance</em>: ' +
math.format(
cpv.currcp.objectinfo.gaia_closest_distarcsec, 4
) + '″<br>' +
'<em>closest G mag (obj - nbr)</em>: ' +
math.format(
cpv.currcp.objectinfo.gaia_closest_gmagdiff, 4
) + ' mag';
}
else {
var formatted_gaia =
'<strong><em>GAIA query failed</em>:</strong> ' +
gaia_message;
}
$('#objectinfo-extra')
.append(
"<tr>" +
"<th>Neighbors within " +
math.format(cpv.currcp.objectinfo.searchradarcsec,
3) + "″</th>" +
"<td>" + formatted_neighbors +
formatted_gaia +
"</td>" +
"</tr>"
);
}
// get the CMDs for this object if there are any
if (cpv.currcp.hasOwnProperty('colormagdiagram') &&
cpv.currcp.colormagdiagram != null) {
var cmdlist = Object.getOwnPropertyNames(
cpv.currcp.colormagdiagram
);
var cmdkey = '<tr><th>' +
'Color-magnitude diagrams' +
'</th>';
var cmdval = '<td>';
var cmdimgs = [];
// prepare the img divs
var cmdi = 0;
for (cmdi; cmdi < cmdlist.length; cmdi++) {
var thiscmdlabel = cmdlist[cmdi];
var thiscmdplot = cpv.currcp.colormagdiagram[cmdlist[cmdi]];
var cmddd =
'<div class="dropdown">' +
'<a href="#" ' +
'title="Click to see the ' +
thiscmdlabel +
' color-magnitude ' +
'diagram for this object" ' +
'id="cmd-' + cmdi +
'-dropdown" data-toggle="dropdown" ' +
'aria-haspopup="true" aria-expanded="false">' +
'<strong>' + thiscmdlabel + ' CMD</strong>' +
'</a>' +
'<div class="dropdown-menu text-sm-center cmd-dn" ' +
'aria-labelledby="cmd-' + cmdi + '-dropdown">' +
'<img id="cmd-' + cmdi +'-plot" class="img-fluid">' +
'</div></div>';
cmdval = cmdval + cmddd;
cmdimgs.push('#cmd-' + cmdi + '-plot');
}
cmdval = cmdkey + cmdval + '</td></tr>';
$('#objectinfo-extra').append(cmdval);
// now populate the img divs with the actual CMD images
cmdi = 0;
for (cmdi; cmdi < cmdlist.length; cmdi++) {
var thiscmdlabel = cmdlist[cmdi];
var thiscmdplot = cpv.currcp.colormagdiagram[thiscmdlabel];
cputils.b64_to_image(thiscmdplot, cmdimgs[cmdi]);
}
}
// update the magseries plot
cputils.b64_to_image(cpv.currcp.magseries,
'.magseriesplot');
// update the varinfo
if (cpv.currcp.varinfo.objectisvar == 1) {
$('#varcheck').val(1);
}
else if (cpv.currcp.varinfo.objectisvar == 2) {
$('#varcheck').val(2);
}
else if (cpv.currcp.varinfo.objectisvar == 3) {
$('#varcheck').val(3);
}
else {
$('#varcheck').val(0);
}
// get the period and epoch
$('#objectperiod').val(cpv.currcp.varinfo.varperiod);
$('#objectepoch').val(cpv.currcp.varinfo.varepoch);
// update the rest of the object info
$('#objecttags').val(cpv.currcp.objectinfo.objecttags);
$('#objectcomments').val(cpv.currcp.objectcomments);
$('#vartags').val(cpv.currcp.varinfo.vartags);
// update the phased light curves
// first, count the number of methods we have in the cp
var lspmethods = cpv.currcp.pfmethods;
var ncols = lspmethods.length;
var colwidth = 12/ncols;
// zero out previous stuff
$('.phased-container').empty();
cpv.currphasedind = null;
cpv.maxphasedind = null;
// this is the fast scroll index for moving quickly through the
// phased plots and selecting them as the best
var phasedplotindex = 0;
// then go through each lsp method, and generate the containers
for (let lspmethod of lspmethods) {
if (lspmethod in cpv.currcp) {
var nbestperiods = cpv.currcp[lspmethod].nbestperiods;
var periodogram = cpv.currcp[lspmethod].periodogram;
// start putting together the container for this method
var mcontainer_coltop =
'<div class="col-sm-' + colwidth +
'" data-lspmethod="' + lspmethod + '">';
var mcontainer_colbot = '</div>';
var periodogram_row =
'<div class="row periodogram-container">' +
'<div class="col-sm-12">' +
'<img src="data:image/png;base64,' +
cpv.currcp[lspmethod].periodogram + '" ' +
'class="img-fluid" id="periodogram-' +
lspmethod + '">' + '</div></div>';
var phasedlcrows= [];
// up to 5 periods are possible
var periodindexes = ['phasedlc0',
'phasedlc1',
'phasedlc2',
'phasedlc3',
'phasedlc4'];
for (let periodind of periodindexes) {
if (periodind in cpv.currcp[lspmethod]) {
var phasedlcrow =
'<a href="#" class="phasedlc-select" ' +
'title="use this period and epoch" ' +
'data-lspmethod="' + lspmethod + '" ' +
'data-periodind="' + periodind + '" ' +
'data-phasedind="' + phasedplotindex + '" ' +
'data-currentbest="no" ' +
'data-period="' +
cpv.currcp[lspmethod][periodind].period + '" ' +
'data-epoch="' +
cpv.currcp[lspmethod][periodind].epoch + '">' +
'<div class="row py-1 phasedlc-container-row" ' +
'data-periodind="' + periodind + '">' +
'<div class="col-sm-12">' +
'<img src="data:image/png;base64,' +
cpv.currcp[lspmethod][periodind].plot + '"' +
'class="img-fluid" id="plot-' +
periodind + '">' + '</div></div></a>';
phasedlcrows.push(phasedlcrow);
phasedplotindex = phasedplotindex + 1;
}
}
// now that we've collected everything, generate the
// container column
var mcontainer = mcontainer_coltop + periodogram_row +
phasedlcrows.join(' ') + mcontainer_colbot;
// write the column to the phasedlc-container
$('.phased-container').append(mcontainer);
}
}
// write the max phasedind
cpv.maxphasedind = phasedplotindex;
//
// handle the neighbors tab for this object
//
// 1. empty the rows for the gaia table and lcc neighbor list
$('#neighbor-container').empty();
$('#gaia-neighbor-tbody').empty();
if (cpv.currcp.objectinfo.gaia_ids != undefined) {
$('#gaia-neighbor-count').html(
cpv.currcp.objectinfo.gaia_ids.length
);
}
else {
$('#gaia-neighbor-count').html('No');
}
$('#lcc-neighbor-container').empty();
$("#lcc-neighbor-count").html(cpv.currcp.neighbors.length);
// 2. update the search radius
if (cpv.currcp.objectinfo.searchradarcsec != undefined) {
$('#gaia-neighbor-maxdist').html(
cpv.currcp.objectinfo.searchradarcsec
);
$('#lcc-neighbor-maxdist').html(
cpv.currcp.objectinfo.searchradarcsec
);
}
// 3. update the GAIA neighbors
if (gaia_ok) {
// for each gaia neighbor, put in a table row
var gi = 0;
for (gi; gi < cpv.currcp.objectinfo.gaia_ids.length; gi++) {
// special formatting for the object itself
if (gi == 0) {
var rowhtml = '<tr class="gaia-objectlist-row ' +
'text-primary' +
'" ' +
'data-gaiaid="' +
cpv.currcp.objectinfo.gaia_ids[gi] +
'" data-xpos="' +
cpv.currcp.objectinfo.gaia_xypos[gi][0] +
'" data-ypos="' +
cpv.currcp.objectinfo.gaia_xypos[gi][1] +
'" >' +
'<td>obj: ' + cpv.currcp.objectinfo.gaia_ids[gi] +
'</td>' +
'<td>' + math.format(
cpv.currcp.objectinfo.gaia_dists[gi], 3
) +
'</td>' +
'<td>' +
math.format(
cpv.currcp.objectinfo.gaia_parallaxes[gi], 3
) + ' ± ' +
math.format(
cpv.currcp.objectinfo.gaia_parallax_errs[gi], 3
) +
'</td>' +
'<td>' +
math.format(
cpv.currcp.objectinfo.gaia_mags[gi], 3
) +
'</td>' +
'<td>' +
math.format(
cpv.currcp.objectinfo.gaia_absolute_mags[gi], 3
) +
'</td>' +
'</tr>';
}
else {
var rowhtml = '<tr class="gaia-objectlist-row" ' +
'data-gaiaid="' +
cpv.currcp.objectinfo.gaia_ids[gi] +
'" data-xpos="' +
cpv.currcp.objectinfo.gaia_xypos[gi][0] +
'" data-ypos="' +
cpv.currcp.objectinfo.gaia_xypos[gi][1] +
'" >' +
'<td>' + cpv.currcp.objectinfo.gaia_ids[gi] +
'</td>' +
'<td>' + math.format(
cpv.currcp.objectinfo.gaia_dists[gi], 3
) +
'</td>' +
'<td>' +
math.format(
cpv.currcp.objectinfo.gaia_parallaxes[gi], 3
) + ' ± ' +
math.format(
cpv.currcp.objectinfo.gaia_parallax_errs[gi], 3
) +
'</td>' +
'<td>' +
math.format(
cpv.currcp.objectinfo.gaia_mags[gi], 3
) +
'</td>' +
'<td>' +
math.format(
cpv.currcp.objectinfo.gaia_absolute_mags[gi], 3
) +
'</td>' +
'</tr>';
}
$('#gaia-neighbor-tbody').append(rowhtml);
}
}
// if GAIA xmatch failed, fill in the table without special
// formatting if possible
else if (cpv.currcp.objectinfo.gaia_ids != undefined) {
// for each gaia neighbor, put in a table row
var gi = 0;
// put in any rows of neighbors if there are any
for (gi; gi < cpv.currcp.objectinfo.gaia_ids.length; gi++) {
var rowhtml = '<tr class="gaia-objectlist-row" ' +
'data-gaiaid="' +
cpv.currcp.objectinfo.gaia_ids[gi] +
'" data-xpos="' +
cpv.currcp.objectinfo.gaia_xypos[gi][0] +
'" data-ypos="' +
cpv.currcp.objectinfo.gaia_xypos[gi][1] +
'" >' +
'<td>' + cpv.currcp.objectinfo.gaia_ids[gi] +
'</td>' +
'<td>' + math.format(
cpv.currcp.objectinfo.gaia_dists[gi], 3
) +
'</td>' +
'<td>' +
math.format(
cpv.currcp.objectinfo.gaia_parallaxes[gi], 3
) + ' ± ' +
math.format(
cpv.currcp.objectinfo.gaia_parallax_errs[gi], 3
) +
'</td>' +
'<td>' +
math.format(
cpv.currcp.objectinfo.gaia_mags[gi], 3
) +
'</td>' +
'<td>' +
math.format(
cpv.currcp.objectinfo.gaia_absolute_mags[gi], 3
) +
'</td>' +
'</tr>';
$('#gaia-neighbor-tbody').append(rowhtml);
}
}
// 4. update the LCC neighbor list
//
// first, add the target in any case
//
var ni = 0;
// set the column width
var nbrcolw = colwidth - 1;
// make the plots for the target object
var rowheader = '<h6>' + 'Target: ' +
cpv.currcp.objectid + ' at (α, δ) = (' +
math.format(cpv.currcp.objectinfo.ra, 5) + ', ' +
math.format(cpv.currcp.objectinfo.decl, 5) + ')</h6>';
var rowplots = [
'<div class="col-sm-' + nbrcolw + ' mx-0 px-0">' +
'<img src="data:image/png;base64,' +
cpv.currcp.magseries +
'" class="img-fluid">' +
'</div>'
];
var nli = 0;
for (nli; nli < lspmethods.length; nli++) {
var thisnphased =
'<div class="col-sm-' + nbrcolw + ' px-0">' +
'<img src="data:image/png;base64,' +
cpv.currcp[lspmethods[nli]]['phasedlc0']['plot'] +
'" class="img-fluid">' +
'</div>';
rowplots.push(thisnphased);
}
// put together this row of plots
var rowplots_str = rowplots.join(' ');
// put together this row
var nbrrow = '<div class="row">' +
'<div class="col-sm-12">' +
rowheader + '</div></div>' +
'<div class="row bot-mrg-20px">' +
rowplots_str +
'</div>';
$('#lcc-neighbor-container').append(nbrrow);
//
// then, add the neighbors if there are any
//
if (cpv.currcp.neighbors.length > 0) {
// now make the plots for the neighbors
for (ni; ni < cpv.currcp.neighbors.length; ni++) {
var nbrobjectid = cpv.currcp.neighbors[ni].objectid;
var nbrra = cpv.currcp.neighbors[ni].objectinfo.ra;
var nbrdecl = cpv.currcp.neighbors[ni].objectinfo.decl;
var nbrdist =
cpv.currcp.neighbors[ni].objectinfo.distarcsec;
// check if this neighbor is present in the current
// collection
var nbrcp = $('#checkplot-current').text().replace(
cpv.currcp.objectid,
nbrobjectid
);
if (cptracker.checkplotlist.indexOf(nbrcp) != -1) {
var nbrlink =
'<a title="load the checkplot for this object" ' +
'href="#" class="nbrload-checkplot" ' +
'data-fname="' + nbrcp + '">' +
nbrobjectid + '</a>';
}
else {
var nbrlink = nbrobjectid;
}
rowheader = '<h6>' + '<span class="neighbor-num">N' +
(ni+1) +
'</span>: ' +
nbrlink + ' at (α, δ) = <a href="' +
'http://simbad.u-strasbg.fr/simbad/sim-coo?Coord=' +
nbrra + '+' + nbrdecl +
'&Radius=30&Radius.unit=arcsec" rel="nofollow" ' +
'target="_blank" ' +
'title="SIMBAD search at these coordinates">' +
'(' + math.format(nbrra, 5) + ', ' +
math.format(nbrdecl, 5) + ')</a>, distance: ' +
math.format(nbrdist,3) + '″</h6>';
if (cpv.currcp.neighbors[ni].magseries != undefined) {
// add the magseries plot for this neighbor
rowplots = [
'<div class="col-sm-' + nbrcolw + ' mx-0 px-0">' +
'<img src="data:image/png;base64,' +
cpv.currcp.neighbors[ni].magseries +
'" class="img-fluid">' +
'</div>'
];
}
else {
rowplots = [
'<div class="col-sm-' + nbrcolw + ' mx-0 px-0">' +
'<img src="/static/nolc-available.png"' +
' class="img-fluid">' +
'</div>'
];
}
// for each lspmethod, add the phased LC for the neighbor
for (nli = 0; nli < lspmethods.length; nli++) {
if (cpv.currcp.neighbors[ni][lspmethods[nli]]
!= undefined) {
thisnphased =
'<div class="col-sm-' + nbrcolw + ' px-0">' +
'<img src="data:image/png;base64,' +
cpv.currcp.neighbors[ni][lspmethods[nli]]['plot'] +
'" class="img-fluid">' +
'</div>';
rowplots.push(thisnphased);
}
else {
thisnphased =
'<div class="col-sm-' + nbrcolw + ' px-0">' +
'<img src="/static/nolc-available.png"' +
'" class="img-fluid">' +
'</div>';
rowplots.push(thisnphased);
}
}
// put together this row of plots
rowplots_str = rowplots.join(' ');
// put together this row
nbrrow = '<div class="row">' +
'<div class="col-sm-12">' +
rowheader + '</div></div>' +
'<div class="row bot-mrg-20px">' +
rowplots_str +
'</div>';
$('#lcc-neighbor-container').append(nbrrow);
}
}
// 5. put together the xmatch info
// first, reset stuff
$('#unmatched-catalogs').html(
'<p>No cross-matches for this object were found.</p>'
);
$('#matched-catalogs').empty();
// then, go through the xmatch content
if (cpv.currcp.xmatch != undefined) {
var xmcatrows = [];
var unxmcatrows = [];
var xmk = null;
var tablecolkeys = null
var tablecolnames = null;
var tablecolunits = null;
var xmcrow = null;
var tci = 0;
var thisunit = '';
var xm = null;
for (xm in cpv.currcp.xmatch) {
xmk = cpv.currcp.xmatch[xm];
// if we found a cross-match, then generate the table for it
if (xmk['found'] == true) {
tablecolkeys = xmk['colkeys'];
tablecolnames = xmk['colnames'];
tablecolunits = xmk['colunit'];
xmcrow = [
'<div class="row mt-1">' +
'<div class="col-sm-12">' +
'<h6>Matched to: <abbr ' +
'title="' + xmk['desc'] + ' ">' +
'<strong>' +
xmk['name'] +
'</strong></abbr> within ' +
math.format(xmk['distarcsec'],3) + '″' +
'</h6>'
];
xmcrow.push(
'<table class="table-sm objectinfo-table">' +
'<thead><tr>'
)
// first, the header row
for (tci = 0;
tci < tablecolkeys.length;
tci++) {
if (tablecolunits[tci] != null) {
thisunit = '[' + tablecolunits[tci] + ']';
}
else {
thisunit = ' ';
}
xmcrow.push(
'<th>' +
tablecolnames[tci] + '<br>' + thisunit +
'</th>'
);
}
// close out this row
xmcrow.push(
'</tr></thead><tbody><tr>'
);
// next, do the value row
// first, the header row
for (tci = 0;
tci < tablecolkeys.length;
tci++) {
// format float things
if (tablecolunits[tci] != null) {
xmcrow.push(
'<td>' +
math.format(
xmk['info'][tablecolkeys[tci]],
5
) +
'</td>'
);
}
// otherwise, leave them alone
else {
xmcrow.push(
'<td>' +
xmk['info'][tablecolkeys[tci]] +
'</td>'
);
}
}
// close out the table
xmcrow.push(
'</tr></tbody></table></div></div>'
);
xmcrow = xmcrow.join(' ');
xmcatrows.push(xmcrow)
}
else {
unxmcatrows.push(
'<div class="row mt-1">' +
'<div class="col-sm-12">' +
'<h6>No matches found in <abbr ' +
'title="' + xmk['desc'] + ' ">' +
'<strong>' +
xmk['name'] +
'</strong></abbr></h6></div></div>'
);
}
}
xmcatrows = xmcatrows.join(' ');
unxmcatrows = unxmcatrows.join(' ');
$('#matched-catalogs').html(xmcatrows);
$('#unmatched-catalogs').html(unxmcatrows);
}
//
// end of main processing for a checkplot
//
}).done(function () {
// update the current file trackers
cpv.currfile = filename;
cpv.currentfind = parseInt(
$("a.checkplot-load")
.filter("[data-fname='" + filename + "']")
.attr('data-findex')
);
// FIXME: get this checkplot's cptools results
// if no cptools results, then populate the phased LCs
// - on the psearch tab, with GLS pgram + phasedlc0
// - on the var tab, with phasedlc0
// - on the lcfit tab, with phasedlc0
// FIXME: if the checkplot's cptools results are available in either
// the cptools.allresults object or in the temp checkplot, get them
// from there. this will probably need a separate call to
// cptools.load_results() and an AJAX endpoint
// FIXME: on the psearch tab, need to populate select with peaks for
// each period finding method in the checkplot
// FIXME: when we load the checkplot, load it's cptools results into
// the cptools.current object.
// re-initialize all popovers
$('[data-toggle="popover"]').popover();
// highlight the file in the sidebar list
$("a.checkplot-load")
.filter("[data-fname='" + filename + "']")
.wrap('<strong></strong>')
// fix the height of the sidebar as required
var winheight = $(window).height();
var docheight = $(document).height();
var ctrlheight = $('.sidebar-controls').height()
$('.sidebar').css({'height': docheight + 'px'});
// get rid of the spinny thing
$('#alert-box').empty();
if (cpv.readonlymode) {
// if we're in readonly mode, inform the user
$('#alert-box').html(
'The checkplot server is in readonly mode. ' +
'Edits to object information will not be saved.'
);
}
}).fail (function (xhr) {
$('#alert-box').html('could not load checkplot <strong>' +
filename + '</strong>!');
});
},
// this functions saves the current checkplot by doing a POST request to the
// backend. this MUST be called on every checkplot list action (i.e. next,
// prev, before load of a new checkplot, so changes are always saved). UI
// elements in the checkplot list will tag the saved checkplots
// appropriately
save_checkplot: function (nextfunc_callback, nextfunc_arg, savetopng) {
// make sure we're not in readonly mode
// if we are, then just bail out immediately
if (cpv.readonlymode) {
$('#alert-box').html(
'The checkplot server is in readonly mode. ' +
'Edits to object information will not be saved.'
);
// call the next function. we call this here so we can be sure the
// next action starts correctly even if we're not saving anything
if (!(nextfunc_callback === undefined) &&
!(nextfunc_arg === undefined)) {
nextfunc_callback(nextfunc_arg);
}
}
// if we're not in readonly mode, go ahead and save stuff
else {
// do the AJAX call to get this checkplot
var ajaxurl = '/cp/' + cputils.b64_encode(cpv.currfile);
// get the current value of the objectisvar select box
cpv.currcp.varinfo.objectisvar = $('#varcheck').val();
// make sure that we've saved the input varinfo, objectinfo and
// comments, period, epoch, etc.
cpv.currcp.varinfo.vartags = $('#vartags').val();
cpv.currcp.objectinfo.objecttags = $('#objecttags').val();
cpv.currcp.objectcomments = $('#objectcomments').val();
cpv.currcp.varinfo.objectisvar = parseInt($('#varcheck').val());
cpv.currcp.varinfo.varperiod = parseFloat($('#objectperiod').val());
cpv.currcp.varinfo.varepoch = parseFloat($('#objectepoch').val());
// make sure we also save the applied filters in the period-search
// tab
cpv.currcp.uifilters = {
psearch_timefilters:$('#psearch-timefilters').val(),
psearch_magfilters:$('#psearch-magfilters').val(),
psearch_sigclip:$('#psearch-sigclip').val()
}
var cppayload = JSON.stringify(
{objectid: cpv.currcp.objectid,
objectinfo: cpv.currcp.objectinfo,
varinfo: cpv.currcp.varinfo,
comments: cpv.currcp.objectcomments,
uifilters: cpv.currcp.uifilters}
);
// first, generate the object to send with the POST request
var postobj = {cpfile: cpv.currfile,
cpcontents: cppayload,
savetopng: savetopng};
// this is to deal with UI elements later
var currfile = postobj.cpfile;
// next, do a saving animation in the alert box
cpv.make_spinner('saving...');
// next, send the POST request and handle anything the server
// returns. FIXME: this should use _xsrf once we set that up
$.post(ajaxurl, postobj, function (data) {
// get the info from the backend
var updatestatus = data.status;
var updatemsg = data.message;
var updateinfo = data.result;
// update the cptracker with what changed so we can try to undo
// later if necessary.
if (updatestatus == 'success') {
// store only the latest update in the tracker
// FIXME: think about adding in update history
// probably a better fit for indexedDB or something
cptracker.cpdata[postobj.cpfile] = updateinfo.changes;
// check if this object is already present and remove if it
// so
var statobjcheck = $('.tracker-obj').filter(
'[data-objectid="' +
updateinfo.changes.objectid +
'"]'
);
// we need to update the project status widget
// generate the new list element: this contains objectid -
// variability flag, variability tags, object tags
var objectli =
'<div class="tracker-obj" ' +
'data-objectid="' + updateinfo.changes.objectid + '">';
var objectidelem = '<a class="objload-checkplot" ' +
'href="#" data-fname="' + postobj.cpfile + '" ' +
'data-objectisvar="' +
updateinfo.changes.varinfo.objectisvar + '">' +
updateinfo.changes.objectid +
'</a>:';
if (updateinfo.changes.varinfo.objectisvar == '1') {
var varelem = 'variable';
}
else if (updateinfo.changes.varinfo.objectisvar == '2') {
var varelem = 'not variable';
}
else if (updateinfo.changes.varinfo.objectisvar == '3') {
var varelem = 'maybe variable';
}
else if (updateinfo.changes.varinfo.objectisvar == '0') {
var varelem = 'no varflag set';
}
var thisvartags =
updateinfo.changes.varinfo.vartags.split(', ');
var thisobjtags =
updateinfo.changes.objectinfo.objecttags.split(', ');
var vartaglist = [];
if ((thisvartags != null) && (thisvartags[0].length > 0)) {
thisvartags.forEach(function (e, i, a) {
vartaglist.push('<span class="cp-tag">' +
e + '</span>');
});
vartaglist = vartaglist.join(' ');
}
else {
vartaglist = '';
}
var objtaglist = [];
if ((thisobjtags != null) && (thisobjtags[0].length > 0)) {
thisobjtags.forEach(function (e, i, a) {
objtaglist.push('<span class="cp-tag">' +
e + '</span>');
});
objtaglist = objtaglist.join(' ');
}
else {
objtaglist = '';
}
var finelem = [objectidelem,
varelem,
vartaglist,
objtaglist].join(' ');
// if this object exists in the list already
// replace it with the new content
if (statobjcheck.length > 0) {
statobjcheck.html(finelem);
console.log('updating existing entry for ' +
updateinfo.changes.objectid);
}
// if this object doesn't exist, add a new row
else {
console.log('adding new entry for ' +
updateinfo.changes.objectid);
$('#project-status').append(objectli + finelem +
'</div>');
}
// update the count in saved-count
var nsaved = $('#project-status div').length;
$('#saved-count').html(nsaved + '/' + cpv.totalcps);
// if we called a save to PNG, show it if it succeeded
if (!(savetopng === undefined) &&
(updateinfo.cpfpng != 'png making failed')) {
updatemsg = 'saved PNG to:<br>' +
'<textarea rows="3" ' +
'class="form-control" readonly>' +
updateinfo.cpfpng +
'</textarea>';
$('#alert-box').html(updatemsg);
}
else if (!(savetopng === undefined) &&
(updateinfo.cpfpng == 'png making failed')) {
updatemsg = 'sorry, making a PNG for ' +
'this object failed!';
$('#alert-box').html(updatemsg);
}
}
else {
$('#alert-box').html(updatemsg);
}
// on POST done, update the UI elements in the checkplot list
// and call the next function.
},'json').done(function (xhr) {
// send the changes to the backend so they're present in the
// checkplot-filelist.json file for the next time around
cptracker.reviewed_object_to_cplist();
// update the filter select box
$('#reviewedfilter').change();
// call the next function. we call this here so we can be sure
// the save finished before the next action starts
if (!(nextfunc_callback === undefined) &&
!(nextfunc_arg === undefined)) {
nextfunc_callback(nextfunc_arg);
// clean out the alert box if there's a next function
$('#alert-box').empty();
}
// if POST failed, pop up an alert in the alert box
}).fail(function (xhr) {
var errmsg = 'could not update ' +
currfile + ' because of an internal server error';
$('#alert-box').html(errmsg);
});
}
},
// this binds actions to the web-app controls
action_setup: function () {
// the previous checkplot link
$('.checkplot-prev').on('click',function (evt) {
evt.preventDefault();
// find the current index
var prevfilelink = $("a.checkplot-load")
.filter("[data-findex='" +
(cpv.currentfind-1) + "']");
var prevfile = prevfilelink.attr('data-fname');
if (prevfile != undefined) {
cpv.save_checkplot(cpv.load_checkplot,prevfile);
// $(prevfilelink)[0].scrollIntoView();
}
else {
// make sure to save current
cpv.save_checkplot(null,null);
}
});
// the next checkplot link
$('.checkplot-next').on('click',function (evt) {
evt.preventDefault();
// find the current index
var nextfilelink = $("a.checkplot-load")
.filter("[data-findex='" +
(cpv.currentfind+1) + "']");
var nextfile = nextfilelink.attr('data-fname');
if (nextfile != undefined) {
cpv.save_checkplot(cpv.load_checkplot,nextfile);
// $(nextfilelink)[0].scrollIntoView();
}
else {
// make sure to save current
cpv.save_checkplot(null,null);
}
});
// clicking on the generate JSON button
$('#save-project-json').click(function (evt) {
// make sure we have at least one object in the saved list
nsaved = $('#project-status div').length;
if (nsaved > 0) {
cptracker.cpdata_to_json();
}
});
// clicking on the generate CSV button
$('#save-project-csv').click(function (evt) {
// make sure we have at least one object in the saved list
nsaved = $('#project-status div').length;
if (nsaved > 0) {
cptracker.cpdata_to_csv();
}
});
$('#reviewedfilter').on('change', function (evt) {
// get this value
var filterval = $(this).val();
if (filterval == 0) {
$('.objload-checkplot')
.filter('[data-objectisvar="0"]')
.parent()
.show();
$('.objload-checkplot')
.filter('[data-objectisvar!="0"]')
.parent()
.hide();
}
else if (filterval == 1) {
$('.objload-checkplot')
.filter('[data-objectisvar="1"]')
.parent()
.show();
$('.objload-checkplot')
.filter('[data-objectisvar!="1"]')
.parent()
.hide();
}
else if (filterval == 2) {
$('.objload-checkplot')
.filter('[data-objectisvar="2"]')
.parent()
.show();
$('.objload-checkplot')
.filter('[data-objectisvar!="2"]')
.parent()
.hide();
}
else if (filterval == 3) {
$('.objload-checkplot')
.filter('[data-objectisvar="3"]')
.parent()
.show();
$('.objload-checkplot')
.filter('[data-objectisvar!="3"]')
.parent()
.hide();
}
else {
$('.objload-checkplot').parent().show();
}
});
// FIXME: fill this in later
$('#checkplotfilter').on('change', function (evt) {
// get this value
var filterval = $(this).val();
if (filterval == 0) {
$('.checkplot-load').show();
}
else if (filterval == 1) {
var reviewedcps = [];
}
else if (filterval == 2) {
}
});
// this handles adding object tags from the dropdown
$('.objtag-dn').click(function (evt) {
evt.preventDefault();
var thisobjtag = $(this).attr('data-dnobjtag');
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (objecttags.indexOf(thisobjtag) == -1) {
objecttags.push(thisobjtag);
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
// this handles adding object tags from the dropdown
$('.vartag-dn').click(function (evt) {
evt.preventDefault();
var thisvartag = $(this).attr('data-dnvartag');
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf(thisvartag) == -1) {
vartags.push(thisvartag);
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
// clicking on a checkplot file in the sidebar
$('#checkplotlist').on('click', '.checkplot-load', function (evt) {
evt.preventDefault();
var filetoload = $(this).attr('data-fname');
// save the currentcp if one exists, use the load_checkplot as a
// callback to load the next one
if (('objectid' in cpv.currcp) && (cpv.currfile.length > 0)) {
cpv.save_checkplot(cpv.load_checkplot,filetoload);
}
else {
// ask the backend for this file
cpv.load_checkplot(filetoload);
}
});
// this loads the neighbor's checkplot if it's in the current LC
// collection loaded into the checkplotserver
$('#lcc-neighbor-container').on('click','.nbrload-checkplot', function (e) {
e.preventDefault();
var filetoload = $(this).attr('data-fname');
// save the currentcp if one exists, use the load_checkplot as a
// callback to load the next one
if (('objectid' in cpv.currcp) && (cpv.currfile.length > 0)) {
cpv.save_checkplot(cpv.load_checkplot,filetoload);
}
else {
// ask the backend for this file
cpv.load_checkplot(filetoload);
}
});
// this handles the hover per objectid row to highlight the object in
// the finder chart
$('#gaia-neighbors').on('mouseover','.gaia-objectlist-row', function (e) {
e.preventDefault();
var canvas = document.getElementById('finderchart');
var canvaswidth = canvas.width;
var canvasheight = canvas.height;
var ctx = canvas.getContext('2d');
var thisx = $(this).attr('data-xpos');
var thisy = $(this).attr('data-ypos');
var cnvx = thisx * canvaswidth/300.0;
// y is from the top of the image for canvas
// FITS coords are from the bottom of the image
var cnvy = (300.0 - thisy) * canvasheight/300.0;
// save the damaged part of the image
cputils.pixeltracker = ctx.getImageData(cnvx-20,cnvy-20,40,40);
ctx.strokeStyle = 'green';
ctx.lineWidth = 3.0
ctx.strokeRect(cnvx-7.5,cnvy-7.5,12.5,12.5);
});
// this handles the repair to the canvas after the user mouses out of
// the row
$('#gaia-neighbors').on('mouseout','.gaia-objectlist-row', function (e) {
e.preventDefault();
var canvas = document.getElementById('finderchart');
var canvaswidth = canvas.width;
var canvasheight = canvas.height;
var ctx = canvas.getContext('2d');
var thisx = $(this).attr('data-xpos');
var thisy = $(this).attr('data-ypos');
var cnvx = thisx * canvaswidth/300.0;
// y is from the top of the image for canvas
// FITS coords are from the bottom of the image
var cnvy = (300.0 - thisy) * canvasheight/300.0;
// restore the imagedata if we have any
if (cputils.pixeltracker != null) {
ctx.putImageData(cputils.pixeltracker,
cnvx-20, cnvy-20);
}
});
// clicking on a objectid in the sidebar
$('#project-status').on('click', '.objload-checkplot', function (evt) {
evt.preventDefault();
var filetoload = $(this).attr('data-fname');
// save the currentcp if one exists, use the load_checkplot as a
// callback to load the next one
if (('objectid' in cpv.currcp) && (cpv.currfile.length > 0)) {
cpv.save_checkplot(cpv.load_checkplot,filetoload);
}
else {
// ask the backend for this file
cpv.load_checkplot(filetoload);
}
});
// clicking on a phased LC loads its period and epoch into the boxes
// also saves them to the currcp
$('.phased-container').on('click','.phasedlc-select', function (evt) {
evt.preventDefault();
var period = $(this).attr('data-period');
var epoch = $(this).attr('data-epoch');
// update the boxes
$('#objectperiod').val(period);
$('#objectepoch').val(epoch);
// save to currcp
cpv.currcp.varinfo.varperiod = parseFloat(period);
cpv.currcp.varinfo.varepoch = parseFloat(epoch);
// add a selected class
var selector = '[data-periodind="' +
$(this).attr('data-periodind') +
'"]';
$('.phasedlc-container-row').removeClass('phasedlc-selected');
$(this)
.children('.phasedlc-container-row')
.filter(selector).addClass('phasedlc-selected');
// change the variability flag to 'probably variable' automatically.
// since we've set a period and epoch, we probably think this is a
// variable
var currvarflag = $('#varcheck').val();
// we only change if the flag is not set already
if (currvarflag == 0) {
$('#varcheck').val(1);
}
});
// resizing the window fixes the sidebar again
$(window).on('resize', function (evt) {
// fix the height of the sidebar as required
var winheight = $(window).height();
var docheight = $(document).height();
var ctrlheight = $('.sidebar-controls').height()
$('.sidebar').css({'height': docheight + 'px'});
});
$('#save-to-png').on('click', function(evt) {
evt.preventDefault();
cpv.save_checkplot(undefined, undefined, true);
});
},
// this does keyboard shortcut setup
keyboard_setup: function () {
/////////////////////////
// SETTING VARIABILITY //
/////////////////////////
// alt+shift+v: object is variable
Mousetrap.bind('alt+shift+v', function() {
$('#varcheck').val(1);
});
// alt+shift+u: object is not variable
Mousetrap.bind('alt+shift+n', function() {
$('#varcheck').val(2);
});
// alt+shift+m: object is maybe a variable
Mousetrap.bind('alt+shift+m', function() {
$('#varcheck').val(3);
});
// alt+shift+u: unset variability flag
Mousetrap.bind('alt+shift+u', function() {
$('#varcheck').val(0);
});
//////////
// TABS //
//////////
// alt+shift+o: overview tab
Mousetrap.bind('alt+shift+o', function() {
$('#overview-tab').click();
});
// alt+shift+l: overview tab
Mousetrap.bind('alt+shift+l', function() {
$('#phasedlcs-tab').click();
});
// alt+shift+x: overview tab
Mousetrap.bind('alt+shift+x', function() {
$('#xmatches-tab').click();
});
// alt+shift+p: overview tab
Mousetrap.bind('alt+shift+p', function() {
$('#periodsearch-tab').click();
});
//////////////
// MOVEMENT //
//////////////
// ctrl+right: save this, move to next checkplot
Mousetrap.bind(['ctrl+right','alt+shift+right'], function() {
$('.checkplot-next').click();
});
// ctrl+left: save this, move to prev checkplot
Mousetrap.bind(['ctrl+left','alt+shift+left'], function() {
$('.checkplot-prev').click();
});
// ctrl+enter: save this, move to next checkplot
Mousetrap.bind('ctrl+enter', function() {
$('.checkplot-next').click();
});
// shift+enter: save this, but don't go anywhere
Mousetrap.bind('shift+enter', function() {
cpv.save_checkplot(undefined, undefined);
$('#alert-box').empty();
});
// ctrl+shift+e: save this as a PNG
Mousetrap.bind('alt+shift+e', function() {
cpv.save_checkplot(undefined, undefined, true);
});
// ctrl+down: move to the next phased LC and set it as the best
Mousetrap.bind(['ctrl+shift+down'], function() {
// check the current phased index, if it's null, then set it to 0
if (cpv.currphasedind == null) {
cpv.currphasedind = 0;
}
else if (cpv.currphasedind < cpv.maxphasedind) {
cpv.currphasedind = cpv.currphasedind + 1;
}
var targetelem = $('a[data-phasedind="' +
cpv.currphasedind + '"]');
if (targetelem.length > 0) {
// scroll into view if the bottom of this plot is off the screen
if ( (targetelem.offset().top + targetelem.height()) >
$(window).height() ) {
targetelem[0].scrollIntoView(true);
}
// click on the target elem to select it
targetelem.click();
}
});
// ctrl+up: move to the prev phased LC and set it as the best
Mousetrap.bind(['ctrl+shift+up'], function() {
// check the current phased index, if it's null, then set it to 0
if (cpv.currphasedind == null) {
cpv.currphasedind = 0;
}
else if (cpv.currphasedind > 0) {
cpv.currphasedind = cpv.currphasedind - 1;
}
var targetelem = $('a[data-phasedind="' +
cpv.currphasedind + '"]');
if (targetelem.length > 0) {
// scroll into view if the top of this plot is off the screen
if ( (targetelem.offset().top) > $(window).height() ) {
targetelem[0].scrollIntoView(true);
}
// click on the target elem to select it
targetelem.click();
}
});
// ctrl+backspace: clear variability tags
Mousetrap.bind('ctrl+backspace', function() {
// clean out the variability info and input boxes
$('#vartags').val('');
$('#objectperiod').val('');
$('#objectepoch').val('');
$('#varcheck').val(0);
cpv.currcp.varinfo.objectisvar = null;
cpv.currcp.varinfo.varepoch = null;
cpv.currcp.varinfo.varisperiodic = null;
cpv.currcp.varinfo.varperiod = null;
cpv.currcp.varinfo.vartags = null;
});
// ctrl+shift+backspace: clear all info
Mousetrap.bind('ctrl+shift+backspace', function() {
// clean out the all info and input boxes
$('#vartags').val('');
$('#objectperiod').val('');
$('#objectepoch').val('');
$('#objecttags').val('');
$('#objectcomments').val('');
$('#varcheck').val(0);
cpv.currcp.varinfo.objectisvar = null;
cpv.currcp.varinfo.varepoch = null;
cpv.currcp.varinfo.varisperiodic = null;
cpv.currcp.varinfo.varperiod = null;
cpv.currcp.varinfo.vartags = null;
cpv.currcp.objectinfo.objecttags = null;
cpv.currcp.comments = null;
});
///////////////////////
// TAGGING VARIABLES //
///////////////////////
// ctrl+shift+1: planet candidate
Mousetrap.bind('ctrl+shift+1', function () {
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf('planet candidate') == -1) {
vartags.push('planet candidate');
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
// ctrl+shift+2: RRab pulsator
Mousetrap.bind('ctrl+shift+2', function () {
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf('RR Lyrae pulsator') == -1) {
vartags.push('RR Lyrae pulsator');
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
// ctrl+shift+3: RRc pulsator
Mousetrap.bind('ctrl+shift+3', function () {
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf('Cepheid pulsator') == -1) {
vartags.push('Cepheid pulsator');
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
// ctrl+shift+4: starspot rotation
Mousetrap.bind('ctrl+shift+4', function () {
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf('starspot rotation') == -1) {
vartags.push('starspot rotation');
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
// ctrl+shift+5: flare star
Mousetrap.bind('ctrl+shift+5', function () {
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf('flare star') == -1) {
vartags.push('flare star');
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
// ctrl+shift+6: contact EB
Mousetrap.bind('ctrl+shift+6', function () {
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf('contact EB') == -1) {
vartags.push('contact EB');
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
// ctrl+shift+7: semi-detached EB
Mousetrap.bind('ctrl+shift+7', function () {
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf('semi-detached EB') == -1) {
vartags.push('semi-detached EB');
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
// ctrl+shift+8: detached EB
Mousetrap.bind('ctrl+shift+8', function () {
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf('detached EB') == -1) {
vartags.push('detached EB');
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
// ctrl+shift+9: weird variability
Mousetrap.bind('ctrl+shift+9', function () {
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf('weird variability') == -1) {
vartags.push('weird variability');
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
// ctrl+shift+0: period harmonic
Mousetrap.bind('ctrl+shift+0', function () {
// get the current val for the vartags
var vartags = $('#vartags').val();
// split by comma and strip extra spaces
vartags = vartags.split(',');
vartags.forEach(function (item, index, arr) {
vartags[index] = item.trim();
});
// remove any item with zero length
vartags = vartags
.filter(function(val) { return val.length > 0 });
// check if we already have this vartag in the list and append it if
// we don't.
if (vartags.indexOf('period harmonic') == -1) {
vartags.push('period harmonic');
vartags = vartags.join(', ');
$('#vartags').val(vartags);
}
});
//////////////////////////
// TAGGING OBJECT TYPES //
//////////////////////////
// alt+shift+1: white dwarf
Mousetrap.bind(['alt+shift+1','command+shift+1'], function () {
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this objecttag in the list and append it
// if we don't.
if (objecttags.indexOf('white dwarf') == -1) {
objecttags.push('white dwarf');
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
// alt+shift+2: hot star (OB)
Mousetrap.bind(['alt+shift+2','command+shift+2'], function () {
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this objecttag in the list and append it
// if we don't.
if (objecttags.indexOf('hot star (OB)') == -1) {
objecttags.push('hot star (OB)');
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
// alt+shift+3: A star
Mousetrap.bind(['alt+shift+3','command+shift+3'], function () {
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this objecttag in the list and append it
// if we don't.
if (objecttags.indexOf('A star') == -1) {
objecttags.push('A star');
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
// alt+shift+4: F or G dwarf
Mousetrap.bind(['alt+shift+4','command+shift+4'], function () {
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this objecttag in the list and append it
// if we don't.
if (objecttags.indexOf('F or G dwarf') == -1) {
objecttags.push('F or G dwarf');
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
// alt+shift+5: red giant
Mousetrap.bind(['alt+shift+5','command+shift+5'], function () {
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this objecttag in the list and append it
// if we don't.
if (objecttags.indexOf('red giant') == -1) {
objecttags.push('red giant');
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
// alt+shift+6: K or M dwarf
Mousetrap.bind(['alt+shift+6','command+shift+6'], function () {
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this objecttag in the list and append it
// if we don't.
if (objecttags.indexOf('K or M dwarf') == -1) {
objecttags.push('K or M dwarf');
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
// alt+shift+7: giant star
Mousetrap.bind(['alt+shift+7','command+shift+7'], function () {
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this objecttag in the list and append it
// if we don't.
if (objecttags.indexOf('giant star') == -1) {
objecttags.push('giant star');
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
// alt+shift+8: dwarf star
Mousetrap.bind(['alt+shift+8','command+shift+8'], function () {
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this objecttag in the list and append it
// if we don't.
if (objecttags.indexOf('dwarf star') == -1) {
objecttags.push('dwarf star');
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
// alt+shift+9: blended with neighbors
Mousetrap.bind(['alt+shift+9','command+shift+9'], function () {
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this objecttag in the list and append it
// if we don't.
if (objecttags.indexOf('blended with neighbors') == -1) {
objecttags.push('blended with neighbors');
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
// alt+shift+0: weird object
Mousetrap.bind(['alt+shift+0','command+shift+0'], function () {
// get the current val for the objecttags
var objecttags = $('#objecttags').val();
// split by comma and strip extra spaces
objecttags = objecttags.split(',');
objecttags.forEach(function (item, index, arr) {
objecttags[index] = item.trim();
});
// remove any item with zero length
objecttags = objecttags
.filter(function(val) { return val.length > 0 });
// check if we already have this objecttag in the list and append it
// if we don't.
if (objecttags.indexOf('weird object') == -1) {
objecttags.push('weird object');
objecttags = objecttags.join(', ');
$('#objecttags').val(objecttags);
}
});
}
};
var cptools = {
// allobjects contains objects of the form:
// '<objectid>': {various lctool results}
// this is indexed by objectid
allobjects: {},
// processing contains objects of the form:
// '<objectid>': {'lctool':name of lctool currently running}
running: {},
// failed contains objects of the form:
// '<lctool-objectid>': message from backend explaining what happened
failed: {},
// this holds the current checkplot's results for fast review
current: {},
// this loads the current checkplot's results in order of priority:
// - from cptools.allresults.objects if objectid is present
// - from the checkplot-<objectid>.pkl-cpserver-temp file if that is present
// if neither are present, then this object doesn't have any results yet
// checks the processing list in the allresults for the objectid requested.
// if it's found there, then shows the spinner with the current tool
// that's running. if it's found in the objects
load_results: function () {
},
// this fires the POST action to save all outstanding stuff to the
// checkplot pickle permanently
sync_results: function (saveelem) {
},
// this clears out the currentresults and the allresults entry for the
// current checkplot and deletes the -cpserver-temp pickle file.
reset_results: function () {
},
run_periodsearch: function () {
// get the current objectid and checkplot filename
var currobjectid = $('#objectid').text();
var currfname = $('#objectid').attr('data-fname');
// this tracks if we're ok to proceed
var proceed = false;
// this tracks any errors in input. we join them all with <br>
// and show them in the alert box.
var messages = [];
// get which period search to run
var lspmethod = $('#psearch-lspmethod').val();
// this is the lctool to call
var lctooltocall = 'psearch-' + lspmethod;
// see if magsarefluxes is checked
var magsarefluxes = $('#psearch-magsarefluxes').prop('checked');
// see if autofreq is checked
var autofreq = $('#psearch-autofreq').prop('checked');
if ( (lspmethod == 'gls') || (lspmethod == 'bls') ||
(lspmethod == 'pdm') || (lspmethod == 'aov') ||
(lspmethod == 'mav') || (lspmethod == 'acf') ||
(lspmethod == 'win') ) {
proceed = true;
}
else {
messages.push("unknown periodogram method specified");
}
// if it's not checked, get the startp, endp, and frequency step
if (!autofreq) {
var startp = $('#psearch-startp').val();
var endp = $('#psearch-endp').val();
var freqstep = $('#psearch-freqstep').val();
startp = parseFloat(startp);
endp = parseFloat(endp);
freqstep = parseFloat(freqstep);
// check startp
if (isNaN(startp)) {
messages.push("no start period provided");
proceed = false;
}
else if ((startp == 0.0) || (startp < 0.0)) {
messages.push("start period cannot be 0.0 or < 0.0");
proceed = false;
}
else if (startp > endp) {
messages.push("start period cannot be larger than end period");
proceed = false;
}
else {
messages.push("using start period: " + math.format(startp, 5));
proceed = true;
}
// check endp
if (isNaN(endp)) {
messages.push("no end period provided");
proceed = false;
}
else if ((endp == 0.0) || (endp < 0.0)) {
messages.push("end period cannot be 0.0 or < 0.0");
proceed = false;
}
else {
messages.push("using end period: " + math.format(endp, 5));
proceed = true;
}
// check freqstep
if (isNaN(freqstep)) {
messages.push("no frequency step provided");
proceed = false;
}
else if ((freqstep == 0.0) || (freqstep < 0.0)) {
messages.push("frequency step cannot be 0.0 or < 0.0");
proceed = false;
}
else {
messages.push("using frequency step: " +
math.format(freqstep, 8));
proceed = true;
}
}
// get the specified sigma clip
var sigclip = $('#psearch-sigclip').val();
if (sigclip.length > 0) {
// try to see if this is a composite sigma clip for lo, hi
if (sigclip.indexOf(',') != -1) {
sigclip = sigclip.trim().split(',');
sigclip = [sigclip[0].trim(), sigclip[1].trim()];
sigclip = [parseFloat(sigclip[0]), parseFloat(sigclip[1])];
if (isNaN(sigclip[0]) || isNaN(sigclip[1]) ||
(sigclip[0] < 0) || (sigclip[1] < 0)) {
messages.push("one or both sigclip values is invalid");
proceed = false;
}
}
// if a single sigma clip, parse it
else {
sigclip = parseFloat(sigclip.trim());
if (isNaN(sigclip) || sigclip < 0) {
messages.push("sigclip value is invalid");
proceed = false;
}
else {
sigclip = [sigclip, sigclip];
}
}
}
else {
sigclip = null;
}
// check the number of peaks to retrieve
var nbestpeaks = $('#psearch-nbestpeaks').val();
if (nbestpeaks.length > 0) {
nbestpeaks = parseInt(nbestpeaks.trim());
if (isNaN(nbestpeaks) || nbestpeaks < 0) {
messages.push("nbestpeaks value is invalid");
proceed = false;
}
}
else {
nbestpeaks = 10;
}
// get the lctimefilters and lcmagfilters
// these will be processed server-side so nothing is required here
var lctimefilters = $('#psearch-timefilters').val();
if (lctimefilters.length == 0) {
lctimefilters = null;
}
var lcmagfilters = $('#psearch-magfilters').val();
if (lcmagfilters.length == 0) {
lcmagfilters = null;
}
var extraparams = {};
// finally, get the extra parameters for this periodogram method
$('.pf-extraparam').each(function (index) {
extraparams[$(this).attr('name')] = $(this).val();
});
console.log(extraparams);
// proceed if we can
if (proceed) {
// generate the alert box messages
messages.push("running " + lspmethod.toUpperCase() + '...');
messages = messages.join("<br>");
cpv.make_spinner('<span class="text-primary">' +
messages +
'</span><br>');
// generate the tool queue box
var tqbox = '<div class="tq-box" data-objectid="' + currobjectid +
'" data-fname="' + currfname +
'" data-lctool="' + lctooltocall +
'" data-toolstate="running">' +
'<strong>' + currobjectid + '</strong><br>' +
lctooltocall + ' — ' +
'<span class="tq-state">running</span></div>';
$('.tool-queue').append(tqbox);
// the call to the backend
var ajaxurl = '/tools/' + cputils.b64_encode(cpv.currfile);
if (autofreq) {
if (lctooltocall == 'psearch-acf') {
var sentdata = {
objectid: currobjectid,
lctool: lctooltocall,
forcereload: true,
magsarefluxes: magsarefluxes,
autofreq: autofreq,
sigclip: sigclip,
maxacfpeaks: nbestpeaks,
lctimefilters: lctimefilters,
lcmagfilters: lcmagfilters
};
}
else {
// this is the data object to send to the backend
var sentdata = {
objectid: currobjectid,
lctool: lctooltocall,
forcereload: true,
magsarefluxes: magsarefluxes,
autofreq: autofreq,
sigclip: sigclip,
nbestpeaks: nbestpeaks,
lctimefilters: lctimefilters,
lcmagfilters: lcmagfilters
};
}
}
else {
if (lctooltocall == 'psearch-acf') {
// this is the data object to send to the backend
var sentdata = {
objectid: currobjectid,
lctool: lctooltocall,
forcereload: true,
magsarefluxes: magsarefluxes,
autofreq: autofreq,
startp: startp,
endp: endp,
stepsize: freqstep,
sigclip: sigclip,
maxacfpeaks: nbestpeaks,
lctimefilters: lctimefilters,
lcmagfilters: lcmagfilters
};
}
else {
// this is the data object to send to the backend
var sentdata = {
objectid: currobjectid,
lctool: lctooltocall,
forcereload: true,
magsarefluxes: magsarefluxes,
autofreq: autofreq,
startp: startp,
endp: endp,
stepsize: freqstep,
sigclip: sigclip,
nbestpeaks: nbestpeaks,
lctimefilters: lctimefilters,
lcmagfilters: lcmagfilters
};
}
}
// update the sentdata with the extraparams
var ei = 0;
var ep = Object.getOwnPropertyNames(extraparams);
for (ei; ei < ep.length; ei++) {
sentdata[ep[ei]] = extraparams[ep[ei]];
}
console.log(sentdata);
// make the call
$.getJSON(ajaxurl, sentdata, function (recvdata) {
// the received data is in the standard form
var reqstatus = recvdata.status;
var reqmsg = recvdata.message;
var reqresult = recvdata.result;
var cpobjectid = reqresult.objectid;
// update this after we get back from the AJAX call
var currobjectid = $('#objectid').text();
if (reqstatus == 'success' || reqstatus == 'warning') {
var lsp = reqresult[lspmethod];
// only update if the user is still on the object
// we started with
if (cpobjectid == currobjectid) {
// update the select control for the periodogram peaks
// with all best peaks
$('#psearch-pgrampeaks').empty();
//
// first, get the first 3 peaks
//
$('#psearch-pgrampeaks').append(
'<option value="0|' + lsp.phasedlc0.period +
'|' + lsp.phasedlc0.epoch +
'" selected>peak 1: ' +
math.format(lsp.phasedlc0.period, 7) +
'</option>'
);
$('#psearch-pgrampeaks').append(
'<option value="1|' + lsp.phasedlc1.period +
'|' + lsp.phasedlc1.epoch +
'">peak 2: ' +
math.format(lsp.phasedlc1.period, 7) +
'</option>'
);
$('#psearch-pgrampeaks').append(
'<option value="2|' + lsp.phasedlc2.period +
'|' + lsp.phasedlc2.epoch +
'">peak 3: ' +
math.format(lsp.phasedlc2.period, 7) +
'</option>'
);
//
// then get any more peaks if remaining
//
if (lsp.nbestperiods.length > 3) {
var peakind = 3;
for (peakind;
peakind < lsp.nbestperiods.length;
peakind++) {
$('#psearch-pgrampeaks').append(
'<option value="' + peakind +
'|' + lsp.nbestperiods[peakind] +
'|' + 'auto-minimumlight' +
'">peak ' + (peakind + 1) + ': ' +
math.format(
lsp.nbestperiods[peakind], 7) +
'</option>'
);
}
}
// update the period box with the best period
$('#psearch-plotperiod').val(lsp.phasedlc0.period);
// update the epoch box with the epoch of the best period
$('#psearch-plotepoch').val(lsp.phasedlc0.epoch);
// put the periodogram into #psearch-periodogram-display
cputils.b64_to_image(lsp.periodogram,
'#psearch-periodogram-display');
// put the phased LC for the best period into
// #psearch-phasedlc-display
cputils.b64_to_image(lsp.phasedlc0.plot,
'#psearch-phasedlc-display');
// update the cptools tracker with the results for this
// object
// if this objectid is in the tracker
if (cpobjectid in cptools.allobjects) {
cptools.allobjects[cpobjectid][lspmethod] = lsp;
}
// if it's not in the tracker, add it
else {
cptools.allobjects[cpobjectid] = reqresult;
}
// update the cptools currentresults with these results
cptools.current[lspmethod] = lsp;
// add a warning to the alert box if there was one
if (reqstatus == 'warning') {
// show the error if something exploded
// but only if we're on the right objectid.
var errmsg = '<span class="text-warning">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
}
// update the tool queue
// fade out and remove the matching entry
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-primary">DONE<span>');
tqboxelem.fadeOut(2000, function () {
$(this).remove();
});
// clear out the alert box only if we're on the same
// objectid
$('#alert-box').empty();
}
// if the user has moved on,
// update the tool queue and allresults tracker
else {
console.log('results received for ' + cpobjectid +
' but user has moved to ' + currobjectid +
', updated tracker...');
// if this objectid is in the tracker
if (cpobjectid in cptools.allobjects) {
cptools.allobjects[cpobjectid][lspmethod] = lsp;
}
// if it's not in the tracker, add it
else {
cptools.allobjects[cpobjectid] = reqresult;
}
// update the tool queue
// fade out and remove the matching entry
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-primary">DONE<span>');
tqboxelem.fadeOut(2000, function () {
$(this).remove();
});
}
}
// if the request failed
else {
// show the error if something exploded but only if we're on
// the right objectid.
if (cpobjectid == currobjectid) {
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
}
// update the tool queue to show what happened
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-danger">FAILED<span>');
tqboxelem.fadeOut(2500, function () {
$(this).remove();
});
// update the cptools.failed tracker
var failedkey = lctooltocall + '-' + cpobjectid;
cptools.failed[failedkey] = reqmsg;
}
}).fail(function (xhr) {
// show the error - here we don't know which objectid was
// returned, so show the error wherever we are
var reqmsg = "could not run " + lctooltocall +
" because of a server error!";
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
});
}
// otherwise we can't proceed, bail out and show the error messages
else {
// generate the alert box messages
messages = messages.join("<br>");
$('#alert-box').html('<span class="text-warning">' +
messages +
'</span>');
}
},
get_varfeatures: function () {
// get the current objectid and checkplot filename
var currobjectid = $('#objectid').text();
var currfname = $('#objectid').attr('data-fname');
// this is the lctool to call
var lctooltocall = 'var-varfeatures';
// this tracks any errors in input. we join them all with <br>
// and show them in the alert box.
var messages = [];
// generate the alert box messages
messages.push("getting variability features...");
messages = messages.join("<br>");
cpv.make_spinner('<span class="text-primary">' +
messages +
'</span><br>');
// generate the tool queue box
var tqbox = '<div class="tq-box" data-objectid="' + currobjectid +
'" data-fname="' + currfname +
'" data-lctool="' + lctooltocall +
'" data-toolstate="running">' +
'<strong>' + currobjectid + '</strong><br>' +
lctooltocall + ' — ' +
'<span class="tq-state">running</span></div>';
$('.tool-queue').append(tqbox);
// the call to the backend
var ajaxurl = '/tools/' + cputils.b64_encode(cpv.currfile);
// this is the data object to send to the backend
var sentdata = {
objectid: currobjectid,
lctool: lctooltocall,
forcereload: true,
};
// make the call
$.getJSON(ajaxurl, sentdata, function (recvdata) {
// the received data is in the standard form
var reqstatus = recvdata.status;
var reqmsg = recvdata.message;
var reqresult = recvdata.result;
var cpobjectid = reqresult.objectid;
// update this after we get back from the AJAX call
var currobjectid = $('#objectid').text();
if (reqstatus == 'success' || reqstatus == 'warning') {
// only update if the user is still on the object
// we started with
if (cpobjectid == currobjectid) {
// this is the target element where we'll make a table
var featreselem = $('#var-varfeatures-results');
// these are the results
var vfeatures = reqresult.varinfo.varfeatures;
var feat_table = [
'<textarea class="form-control" rows="30" readonly>'
];
feat_table.push(JSON.stringify(vfeatures, null, 2));
feat_table = feat_table.join('') + '</textarea>';
featreselem.html(feat_table);
// update the cptools tracker with the results for this
// object
// if this objectid is in the tracker
if (cpobjectid in cptools.allobjects) {
if ('varinfo' in cptools.allobjects[cpobjectid]) {
cptools.allobjects[
cpobjectid
]['varinfo']['varfeatures'] = vfeatures;
}
else {
cptools.allobjects[cpobjectid] = {
varinfo:{
varfeatures: vfeatures
}
};
}
}
// if it's not in the tracker, add it
else {
cptools.allobjects[cpobjectid] = reqresult;
}
// update the cptools currentresults with these results
if ('varinfo' in cptools.current) {
cptools.current['varinfo']['varfeatures'] = vfeatures;
}
else {
cptools.current['varinfo'] = {varfeatures: vfeatures};
}
// add a warning to the alert box if there was one
if (reqstatus == 'warning') {
// show the error if something exploded
// but only if we're on the right objectid.
var errmsg = '<span class="text-warning">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
}
// update the tool queue
// fade out and remove the matching entry
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-primary">DONE<span>');
tqboxelem.fadeOut(2000, function () {
$(this).remove();
});
// clear out the alert box only if we're on the same
// objectid
$('#alert-box').empty();
}
// if the user has moved on...
else {
console.log('results received for ' + cpobjectid +
' but user has moved to ' + currobjectid +
', updated tracker...');
// if this objectid is in the tracker
if (cpobjectid in cptools.allobjects) {
if ('varinfo' in cptools.allobjects[cpobjectid]) {
cptools.allobjects[
cpobjectid
]['varinfo']['varfeatures'] = vfeatures;
}
else {
cptools.allobjects[cpobjectid] = {
varinfo:{
varfeatures: vfeatures
}
};
}
}
// if it's not in the tracker, add it
else {
cptools.allobjects[cpobjectid] = reqresult;
}
// update the tool queue
// fade out and remove the matching entry
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-primary">DONE<span>');
tqboxelem.fadeOut(2000, function () {
$(this).remove();
});
}
}
// if the request failed
else {
// show the error if something exploded but only if we're on
// the right objectid.
if (cpobjectid == currobjectid) {
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
}
// update the tool queue to show what happened
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-danger">FAILED<span>');
tqboxelem.fadeOut(2500, function () {
$(this).remove();
});
// update the cptools.failed tracker
var failedkey = lctooltocall + '-' + cpobjectid;
cptools.failed[failedkey] = reqmsg;
}
}).fail(function (xhr) {
// show the error - here we don't know which objectid was
// returned, so show the error wherever we are
var reqmsg = "could not run " + lctooltocall +
" because of a server error!";
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
});
},
new_phasedlc_plot: function () {
// get the current objectid and checkplot filename
var currobjectid = $('#objectid').text();
var currfname = $('#objectid').attr('data-fname');
// this is the lctool to call
var lctooltocall = 'phasedlc-newplot';
// this tracks any errors in input. we join them all with <br>
// and show them in the alert box.
var messages = [];
// this tracks if we're ok to proceed
var proceed = true;
// collect the form values
var plotperiod = parseFloat($('#psearch-plotperiod').val());
var plotepoch = parseFloat($('#psearch-plotepoch').val());
var plotxlim = $('#psearch-plotxlim').val();
if (plotxlim != '') {
plotxlim = plotxlim.replace(']','').replace('[','').split(', ');
plotxlim = [parseFloat(plotxlim[0]), parseFloat(plotxlim[1])];
// if the plot limits aren't the default, then we probably want
// xliminsetmode on
if ((plotxlim[1] - plotxlim[0]) > 1.0) {
var xliminsetmode = false;
}
else {
var xliminsetmode = true;
}
}
else {
var xliminsetmode = false;
}
var phasebin = parseFloat($('#psearch-binphase').val());
var periodind = $('#psearch-pgrampeaks').val();
if (periodind === null || periodind == 'none') {
periodind = 0;
}
else {
periodind = parseInt(periodind.split('|')[0]);
}
var lspmethod = $('#psearch-lspmethod').val();
var magsarefluxes = $('#psearch-magsarefluxes').prop('checked');
// see if we can proceed
if ((isNaN(plotperiod)) || (plotperiod < 0.0)) {
messages.push("plot period is invalid")
proceed = false;
}
if ((isNaN(plotepoch)) || (plotepoch < 0.0)) {
messages.push(
"plot epoch not provided or invalid, set to automatic"
)
proceed = true;
plotepoch = null;
}
if ((isNaN(plotxlim[0])) ||
(plotxlim[0] < -1.0) ||
(plotxlim[0] > plotxlim[1])) {
messages.push("plot x-axis lower limit is invalid")
proceed = false;
}
if ((isNaN(plotxlim[1])) ||
(plotxlim[1] > 1.0) ||
(plotxlim[1] < plotxlim[0])) {
messages.push("plot x-axis upper limit is invalid")
proceed = false;
}
if ((isNaN(phasebin)) ||
(phasebin > 0.25) ||
(phasebin < 0.0)) {
messages.push("plot phase bin size is invalid")
proceed = false;
}
// get the specified sigma clip
var sigclip = $('#psearch-sigclip').val();
if (sigclip.length > 0) {
// try to see if this is a composite sigma clip for lo, hi
if (sigclip.indexOf(',') != -1) {
sigclip = sigclip.trim().split(',');
sigclip = [sigclip[0].trim(), sigclip[1].trim()];
sigclip = [parseFloat(sigclip[0]), parseFloat(sigclip[1])];
if (isNaN(sigclip[0]) || isNaN(sigclip[1]) ||
(sigclip[0] < 0) || (sigclip[1] < 0)) {
messages.push("one or both sigclip values is invalid");
proceed = false;
}
}
// if a single sigma clip, parse it
else {
sigclip = parseFloat(sigclip.trim());
if (isNaN(sigclip) || sigclip < 0) {
messages.push("sigclip value is invalid");
proceed = false;
}
else {
sigclip = [sigclip, sigclip];
}
}
}
else {
sigclip = null;
}
// finally, get the lctimefilters and lcmagfilters
// these will be processed server-side so nothing is required here
var lctimefilters = $('#psearch-timefilters').val();
if (lctimefilters.length == 0) {
lctimefilters = null;
}
var lcmagfilters = $('#psearch-magfilters').val();
if (lcmagfilters.length == 0) {
lcmagfilters = null;
}
// don't go any further if the input is valid
if (!proceed) {
// generate the alert box messages
messages = messages.join("<br>");
$('#alert-box').html('<span class="text-warning">' +
messages +
'</span>');
}
// otherwise, we're good to go
else {
// generate the alert box messages
messages.push("making phased LC plot...");
messages = messages.join("<br>");
cpv.make_spinner('<span class="text-primary">' +
messages +
'</span><br>');
// generate the tool queue box
var tqbox = '<div class="tq-box" data-objectid="' + currobjectid +
'" data-fname="' + currfname +
'" data-lctool="' + lctooltocall +
'" data-toolstate="running">' +
'<strong>' + currobjectid + '</strong><br>' +
lctooltocall + ' — ' +
'<span class="tq-state">running</span></div>';
$('.tool-queue').append(tqbox);
// the call to the backend
var ajaxurl = '/tools/' + cputils.b64_encode(cpv.currfile);
// this is the data object to send to the backend
var sentdata = {
// common stuff
objectid: currobjectid,
lctool: lctooltocall,
forcereload: true,
// request values
magsarefluxes: magsarefluxes,
lspmethod: lspmethod,
periodind: periodind,
varperiod: plotperiod,
varepoch: plotepoch,
xliminsetmode: xliminsetmode,
plotxlim: plotxlim,
phasebin: phasebin,
sigclip: sigclip,
lctimefilters: lctimefilters,
lcmagfilters: lcmagfilters
};
console.log(sentdata);
// make the call
$.getJSON(ajaxurl, sentdata, function (recvdata) {
// the received data is in the standard form
var reqstatus = recvdata.status;
var reqmsg = recvdata.message;
var reqresult = recvdata.result;
var cpobjectid = reqresult.objectid;
// update this after we get back from the AJAX call
var currobjectid = $('#objectid').text();
if (reqstatus == 'success' || reqstatus == 'warning') {
var lsp = reqresult[lspmethod];
// only update if the user is still on the object
// we started with
if (cpobjectid == currobjectid) {
var lckey = 'phasedlc' + periodind;
// put the phased LC for the best period into
// #psearch-phasedlc-display
cputils.b64_to_image(lsp[lckey]['plot'],
'#psearch-phasedlc-display');
// update the text box for epoch using the returned
// value from the plotter
$('#psearch-plotepoch').val(lsp[lckey]['epoch']);
// update the global object period and epoch with the
// period and epoch used here if told to do so
var pupdate = $('#psearch-updateperiod').prop('checked');
var eupdate = $('#psearch-updateepoch').prop('checked');
if (pupdate) {
$('#objectperiod').val(plotperiod);
}
if (eupdate) {
$('#objectepoch').val(plotepoch);
}
// update current cptools object
if (lspmethod in cptools.current) {
cptools.current[lspmethod][lckey] = lsp[lckey];
}
else {
cptools.current[lspmethod] = {lckey: lsp[lckey]};
}
// update cptools tracker
if (cpobjectid in cptools.allobjects) {
if (lspmethod in cptools.allobjects[cpobjectid]) {
cptools.allobjects[
cpobjectid
][lspmethod][lckey] = lsp[lckey];
}
else {
cptools.allobjects[
cpobjectid
][lspmethod] = {lckey: lsp[lckey]};
}
}
else {
cptools.allobjects[cpobjectid] = reqresult;
}
// add a warning to the alert box if there was one
if (reqstatus == 'warning') {
// show the error if something exploded
// but only if we're on the right objectid.
var errmsg = '<span class="text-warning">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
}
// update the tool queue
// fade out and remove the matching entry
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-primary">DONE<span>');
tqboxelem.fadeOut(2000, function () {
$(this).remove();
});
// clear out the alert box only if we're on the same
// objectid
$('#alert-box').empty();
}
// if the user has moved on...
else {
console.log('results received for ' + cpobjectid +
' but user has moved to ' + currobjectid +
', updated tracker...');
// update cptools tracker
if (cpobjectid in cptools.allobjects) {
if (lspmethod in cptools.allobjects[cpobjectid]) {
cptools.allobjects[
cpobjectid
][lspmethod][lckey] = lsp[lckey];
}
else {
cptools.allobjects[
cpobjectid
][lspmethod] = {lckey: lsp[lckey]};
}
}
else {
cptools.allobjects[cpobjectid] = reqresult;
}
// update the tool queue
// fade out and remove the matching entry
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-primary">DONE<span>');
tqboxelem.fadeOut(2000, function () {
$(this).remove();
});
}
}
// if the request failed
else {
// show the error if something exploded but only if we're on
// the right objectid.
if (cpobjectid == currobjectid) {
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
}
// update the tool queue to show what happened
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-danger">FAILED<span>');
tqboxelem.fadeOut(2500, function () {
$(this).remove();
});
// update the cptools.failed tracker
var failedkey = lctooltocall + '-' + cpobjectid;
cptools.failed[failedkey] = reqmsg;
}
}).fail(function (xhr) {
// show the error - here we don't know which objectid was
// returned, so show the error wherever we are
var reqmsg = "could not run " + lctooltocall +
" because of a server error!";
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
});
}
},
prewhiten_lightcurve: function () {
// get the current objectid and checkplot filename
var currobjectid = $('#objectid').text();
var currfname = $('#objectid').attr('data-fname');
// this is the lctool to call
var lctooltocall = 'var-prewhiten';
// this tracks any errors in input. we join them all with <br>
// and show them in the alert box.
var messages = [];
// generate the alert box messages
messages.push("getting variability features...");
messages = messages.join("<br>");
cpv.make_spinner('<span class="text-primary">' +
messages +
'</span><br>');
// generate the tool queue box
var tqbox = '<div class="tq-box" data-objectid="' + currobjectid +
'" data-fname="' + currfname +
'" data-lctool="' + lctooltocall +
'" data-toolstate="running">' +
'<strong>' + currobjectid + '</strong><br>' +
lctooltocall + ' — ' +
'<span class="tq-state">running</span></div>';
$('.tool-queue').append(tqbox);
// the call to the backend
var ajaxurl = '/tools/' + cputils.b64_encode(cpv.currfile);
// this is the data object to send to the backend
var sentdata = {
objectid: currobjectid,
lctool: lctooltocall,
forcereload: true,
};
// make the call
$.getJSON(ajaxurl, sentdata, function (recvdata) {
// the received data is in the standard form
var reqstatus = recvdata.status;
var reqmsg = recvdata.message;
var reqresult = recvdata.result;
var cpobjectid = reqresult.objectid;
// update this after we get back from the AJAX call
var currobjectid = $('#objectid').text();
if (reqstatus == 'success' || reqstatus == 'warning') {
// only update if the user is still on the object
// we started with
if (cpobjectid == currobjectid) {
}
// if the user has moved on...
else {
}
}
// if the request failed
else {
// show the error if something exploded but only if we're on
// the right objectid.
if (cpobjectid == currobjectid) {
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
}
// update the tool queue to show what happened
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-danger">FAILED<span>');
tqboxelem.fadeOut(2500, function () {
$(this).remove();
});
// update the cptools.failed tracker
var failedkey = lctooltocall + '-' + cpobjectid;
cptools.failed[failedkey] = reqmsg;
}
}).fail(function (xhr) {
// show the error - here we don't know which objectid was
// returned, so show the error wherever we are
var reqmsg = "could not run " + lctooltocall +
" because of a server error!";
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
});
},
mask_signal: function () {
// get the current objectid and checkplot filename
var currobjectid = $('#objectid').text();
var currfname = $('#objectid').attr('data-fname');
// this is the lctool to call
var lctooltocall = 'var-masksig';
// this tracks any errors in input. we join them all with <br>
// and show them in the alert box.
var messages = [];
// generate the alert box messages
messages.push("getting variability features...");
messages = messages.join("<br>");
cpv.make_spinner('<span class="text-primary">' +
messages +
'</span><br>');
// generate the tool queue box
var tqbox = '<div class="tq-box" data-objectid="' + currobjectid +
'" data-fname="' + currfname +
'" data-lctool="' + lctooltocall +
'" data-toolstate="running">' +
'<strong>' + currobjectid + '</strong><br>' +
lctooltocall + ' — ' +
'<span class="tq-state">running</span></div>';
$('.tool-queue').append(tqbox);
// the call to the backend
var ajaxurl = '/tools/' + cputils.b64_encode(cpv.currfile);
// this is the data object to send to the backend
var sentdata = {
objectid: currobjectid,
lctool: lctooltocall,
forcereload: true,
};
// make the call
$.getJSON(ajaxurl, sentdata, function (recvdata) {
// the received data is in the standard form
var reqstatus = recvdata.status;
var reqmsg = recvdata.message;
var reqresult = recvdata.result;
var cpobjectid = reqresult.objectid;
// update this after we get back from the AJAX call
var currobjectid = $('#objectid').text();
if (reqstatus == 'success' || reqstatus == 'warning') {
// only update if the user is still on the object
// we started with
if (cpobjectid == currobjectid) {
}
// if the user has moved on...
else {
}
}
// if the request failed
else {
// show the error if something exploded but only if we're on
// the right objectid.
if (cpobjectid == currobjectid) {
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
}
// update the tool queue to show what happened
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-danger">FAILED<span>');
tqboxelem.fadeOut(2500, function () {
$(this).remove();
});
// update the cptools.failed tracker
var failedkey = lctooltocall + '-' + cpobjectid;
cptools.failed[failedkey] = reqmsg;
}
}).fail(function (xhr) {
// show the error - here we don't know which objectid was
// returned, so show the error wherever we are
var reqmsg = "could not run " + lctooltocall +
" because of a server error!";
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
});
},
lcfit_magseries: function () {
// get the current objectid and checkplot filename
var currobjectid = $('#objectid').text();
var currfname = $('#objectid').attr('data-fname');
// get which period search to run
var fitmethod = $('#lcfit-fitmethod').val();
// this is the lctool to call
var lctooltocall = 'lcfit-' + fitmethod;
// this tracks any errors in input. we join them all with <br>
// and show them in the alert box.
var messages = [];
// this tracks if we're ok to proceed
var proceed = false;
// generate the alert box messages
messages.push("getting variability features...");
messages = messages.join("<br>");
cpv.make_spinner('<span class="text-primary">' +
messages +
'</span><br>');
// generate the tool queue box
var tqbox = '<div class="tq-box" data-objectid="' + currobjectid +
'" data-fname="' + currfname +
'" data-lctool="' + lctooltocall +
'" data-toolstate="running">' +
'<strong>' + currobjectid + '</strong><br>' +
lctooltocall + ' — ' +
'<span class="tq-state">running</span></div>';
$('.tool-queue').append(tqbox);
// the call to the backend
var ajaxurl = '/tools/' + cputils.b64_encode(cpv.currfile);
// this is the data object to send to the backend
var sentdata = {
objectid: currobjectid,
lctool: lctooltocall,
forcereload: true,
};
// make the call
$.getJSON(ajaxurl, sentdata, function (recvdata) {
// the received data is in the standard form
var reqstatus = recvdata.status;
var reqmsg = recvdata.message;
var reqresult = recvdata.result;
var cpobjectid = reqresult.objectid;
// update this after we get back from the AJAX call
var currobjectid = $('#objectid').text();
if (reqstatus == 'success' || reqstatus == 'warning') {
// only update if the user is still on the object
// we started with
if (cpobjectid == currobjectid) {
}
// if the user has moved on...
else {
}
}
// if the request failed
else {
// show the error if something exploded but only if we're on
// the right objectid.
if (cpobjectid == currobjectid) {
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
}
// update the tool queue to show what happened
var tqsel = '[data-objectid="' + cpobjectid + '"]' +
'[data-lctool="' + lctooltocall + '"]';
var tqboxelem = $('.tq-box').filter(tqsel);
tqboxelem.children('span')
.html('<span class="text-danger">FAILED<span>');
tqboxelem.fadeOut(2500, function () {
$(this).remove();
});
// update the cptools.failed tracker
var failedkey = lctooltocall + '-' + cpobjectid;
cptools.failed[failedkey] = reqmsg;
}
}).fail(function (xhr) {
// show the error - here we don't know which objectid was
// returned, so show the error wherever we are
var reqmsg = "could not run " + lctooltocall +
" because of a server error!";
var errmsg = '<span class="text-danger">' +
reqmsg + '</span>';
$('#alert-box').html(errmsg);
});
},
action_setup: function () {
///////////////////////
// PERIOD SEARCH TAB //
///////////////////////
// periodogram method select - change options as needed
$('#psearch-lspmethod').on('change', function (evt) {
var newval = $(this).val();
// FIXME: update the psearch param panel for any special params for
// this period-finder
var extraparamelem = $('#psearch-pf-extraparams');
extraparamelem.empty();
if (newval == 'acf') {
extraparamelem.append(
'<div class="form-group">' +
'<label for="psearch-smoothacf">' +
'ACF smoothing parameter' +
'</label>' +
'<input type="text" name="smoothacf" ' +
'class="form-control form-control-sm pf-extraparam" ' +
'id="psearch-smoothacf" value="721"></div>'
);
extraparamelem.append(
'<div class="form-group">' +
'<label for="psearch-fillgaps">' +
'Fill value for time-series gaps' +
'</label>' +
'<input type="text" name="fillgaps" ' +
'class="form-control form-control-sm pf-extraparam" ' +
'id="psearch-fillgaps" value="0.0"></div>'
);
}
else if (newval == 'aov') {
extraparamelem.append(
'<div class="form-group">' +
'<label for="psearch-phasebinsize">' +
'Phase bin size' +
'</label>' +
'<input type="text" name="phasebinsize" ' +
'class="form-control form-control-sm pf-extraparam" ' +
'id="psearch-phasebinsize" value="0.05"></div>'
);
extraparamelem.append(
'<div class="form-group">' +
'<label for="psearch-mindetperbin">' +
'Min observations per phase bin' +
'</label>' +
'<input type="text" name="mindetperbin" ' +
'class="form-control form-control-sm pf-extraparam" ' +
'id="psearch-mindetperbin" value="9"></div>'
);
}
else if (newval == 'bls') {
extraparamelem.append(
'<div class="form-group">' +
'<label for="psearch-mintransitduration">' +
'Min transit duration [fractional phase]' +
'</label>' +
'<input type="text" name="mintransitduration" ' +
'class="form-control form-control-sm pf-extraparam" ' +
'id="psearch-mintransitduration" value="0.01"></div>'
);
extraparamelem.append(
'<div class="form-group">' +
'<label for="psearch-maxtransitduration">' +
'Max transit duration [fractional phase]' +
'</label>' +
'<input type="text" name="maxtransitduration" ' +
'class="form-control form-control-sm pf-extraparam" ' +
'id="psearch-maxtransitduration" value="0.8"></div>'
);
}
else if (newval == 'gls') {
}
else if (newval == 'mav') {
extraparamelem.append(
'<div class="form-group">' +
'<label for="psearch-nharmonics">' +
'Number of harmonics' +
'</label>' +
'<input type="text" name="nharmonics" ' +
'class="form-control form-control-sm pf-extraparam" ' +
'id="psearch-nharmonics" value="6"></div>'
);
}
else if (newval == 'pdm') {
extraparamelem.append(
'<div class="form-group">' +
'<label for="psearch-phasebinsize">' +
'Phase bin size' +
'</label>' +
'<input type="text" name="phasebinsize" ' +
'class="form-control form-control-sm pf-extraparam" ' +
'id="psearch-phasebinsize" value="0.05"></div>'
);
extraparamelem.append(
'<div class="form-group">' +
'<label for="psearch-mindetperbin">' +
'Min observations per phase bin' +
'</label>' +
'<input type="text" name="mindetperbin" ' +
'class="form-control form-control-sm pf-extraparam" ' +
'id="psearch-mindetperbin" value="9"></div>'
);
}
});
// periodogram search - half period
$('#psearch-halfperiod').on('click', function (evt) {
evt.preventDefault();
var plotperiod = parseFloat($('#psearch-plotperiod').val());
if (!isNaN(plotperiod)) {
$('#psearch-plotperiod').val(plotperiod/2.0);
}
});
// periodogram search - 2x period
$('#psearch-doubleperiod').on('click', function (evt) {
evt.preventDefault();
var plotperiod = parseFloat($('#psearch-plotperiod').val());
if (!isNaN(plotperiod)) {
$('#psearch-plotperiod').val(plotperiod*2.0);
}
});
// periodogram search - add half period to epoch
$('#psearch-addhalfp-epoch').on('click', function (evt) {
evt.preventDefault();
var plotperiod = parseFloat($('#psearch-plotperiod').val());
var plotepoch = parseFloat($('#psearch-plotepoch').val());
if (!isNaN(plotperiod) && !isNaN(plotepoch)) {
$('#psearch-plotepoch').val(plotepoch + plotperiod/2.0);
}
});
// periodogram search - subtract half period to epoch
$('#psearch-subhalfp-epoch').on('click', function (evt) {
evt.preventDefault();
var plotperiod = parseFloat($('#psearch-plotperiod').val());
var plotepoch = parseFloat($('#psearch-plotepoch').val());
if (!isNaN(plotperiod) && !isNaN(plotepoch)) {
$('#psearch-plotepoch').val(plotepoch - plotperiod/2.0);
}
});
// periodogram search - plot phased LC
$('#psearch-makephasedlc').on('click', function (evt) {
evt.preventDefault();
cptools.new_phasedlc_plot();
});
// periodogram search - periodogram peak select
$('#psearch-pgrampeaks').on('change', function (evt) {
var newval = $(this).val().split('|');
$('#psearch-plotperiod').val(newval[1]);
$('#psearch-plotepoch').val(newval[2]);
});
// periodogram search - start
$('#psearch-start').on('click', function (evt) {
evt.preventDefault();
cptools.run_periodsearch();
});
// periodogram search - handle autofreq
$('#psearch-autofreq').on('click', function (evt) {
var thischecked = $(this).prop('checked');
if (!thischecked) {
$('#psearch-startp').prop('disabled',false);
$('#psearch-endp').prop('disabled',false);
$('#psearch-freqstep').prop('disabled',false);
}
else {
$('#psearch-startp').prop('disabled',true);
$('#psearch-endp').prop('disabled',true);
$('#psearch-freqstep').prop('disabled',true);
}
});
// FIXME: bind the periodogram select so it looks for existing periods
// for that periodogram method and loads them into the period select
// box.
/////////////////////
// VARIABILITY TAB //
/////////////////////
// variability - get variability features
$('#get-varfeatures').on('click', function (evt) {
evt.preventDefault();
cptools.get_varfeatures();
});
////////////////
// LC FIT TAB //
////////////////
////////////////////
// SAVE/RESET TAB //
////////////////////
}
};
|
cpserver.js: fix phased LC columns not working for an odd number of pfmethods
|
astrobase/cpserver/cps-assets/cpserver.js
|
cpserver.js: fix phased LC columns not working for an odd number of pfmethods
|
<ide><path>strobase/cpserver/cps-assets/cpserver.js
<ide> var lspmethods = cpv.currcp.pfmethods;
<ide> var ncols = lspmethods.length;
<ide>
<del> var colwidth = 12/ncols;
<add> var colwidth = math.ceil(12/ncols);
<ide>
<ide> // zero out previous stuff
<ide> $('.phased-container').empty();
|
|
JavaScript
|
mit
|
09ddb0d063ae892e6f0c274af891359cc9077773
| 0 |
cheminfo/tools
|
#!/usr/bin/env node
'use strict';
var program = require('commander');
var webpack = require('webpack');
var path = require('path');
var fs = require('fs');
program
.option('-c, --cwd [dirname]', 'Working directory', process.cwd())
.option('-o, --out [dirname]', 'Output directory', 'dist')
.option('-n, --out-name [name]', 'Name of the output file')
.option('-r, --root [rootname]', 'Root name of the library')
.option('-e, --entry [file]', 'Library entry point')
.option('-b, --babel', 'Enable babel loader for ES6 features')
.option('-u, --no-uglify', 'Disable generation of min file with source map')
.option('-v, --verbose', 'Output warnings if any');
program.parse(process.argv);
var cwd = path.resolve(program.cwd);
var pkg = tryPackage(cwd);
var entryPoint = program.entry || pkg.main || 'index.js';
var name = program.root || pkg.name;
if (!name) {
throw new Error('No name found');
} else if (name.indexOf('-') > 0) {
name = name.replace(/[.-](\w)?/g, function (_, x) {
return x ? x.toUpperCase() : '';
});
}
var filename = program.outName || pkg.name || 'bundle';
var webpackConfig = {
context: cwd,
entry: path.resolve(cwd, entryPoint),
module: {
rules: []
},
output: {
path: path.resolve(cwd, program.out),
filename: filename + '.js',
library: name,
libraryTarget: 'umd'
},
plugins: []
};
if (program.babel) {
var babelConfig = {
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
presets: [
['env', {
targets: {
browsers: [
'chrome >= 54',
'last 2 edge versions',
'last 1 safari version'
]
}
}]
]
}
};
webpackConfig.module.rules.push(babelConfig);
}
webpack(webpackConfig, function (err, stats) {
var jsonStats = stats.toJson();
if (err) {
throw err;
} else if (jsonStats.errors.length > 0) {
printErrors(jsonStats.errors);
process.exit(1);
} else if (jsonStats.warnings.length > 0 && program.verbose) {
printErrors(jsonStats.warnings);
} else {
console.log('Build of ' + filename + ' successful');
if (program.uglify) {
doMinify();
}
}
});
function doMinify() {
webpackConfig.devtool = 'source-map';
webpackConfig.output.devtoolModuleFilenameTemplate = 'webpack:///' + (pkg.name || '') + '/[resource-path]';
webpackConfig.output.filename = filename + '.min.js';
var Babili = require('babili-webpack-plugin');
webpackConfig.plugins.push(new Babili());
webpack(webpackConfig, function (err, stats) {
var jsonStats = stats.toJson();
if (err) {
throw err;
} else if (jsonStats.errors.length > 0) {
printErrors(jsonStats.errors);
process.exit(1);
} else if (jsonStats.warnings.length > 0 && program.verbose) {
printErrors(jsonStats.warnings);
} else {
console.log('Build of ' + filename + ' (min) successful');
}
});
}
function tryPackage(cwd) {
var pkg = path.join(cwd, 'package.json');
try {
return JSON.parse(fs.readFileSync(pkg, 'utf8'));
} catch (e) {
return {};
}
}
function printErrors(errors) {
errors.forEach(function (error) {
console.error(error);
});
}
|
bin/cheminfo-build.js
|
#!/usr/bin/env node
'use strict';
var program = require('commander');
var webpack = require('webpack');
var path = require('path');
var fs = require('fs');
program
.option('-c, --cwd [dirname]', 'Working directory', process.cwd())
.option('-o, --out [dirname]', 'Output directory', 'dist')
.option('-n, --out-name [name]', 'Name of the output file')
.option('-r, --root [rootname]', 'Root name of the library')
.option('-e, --entry [file]', 'Library entry point')
.option('-b, --babel', 'Enable babel loader for ES6 features')
.option('-u, --no-uglify', 'Disable generation of min file with source map')
.option('-v, --verbose', 'Output warnings if any');
program.parse(process.argv);
var cwd = path.resolve(program.cwd);
var pkg = tryPackage(cwd);
var entryPoint = program.entry || pkg.main || 'index.js';
var name = program.root || pkg.name;
if (!name) {
throw new Error('No name found');
} else if (name.indexOf('-') > 0) {
name = name.replace(/[.-](\w)?/g, function (_, x) {
return x ? x.toUpperCase() : '';
});
}
var filename = program.outName || pkg.name || 'bundle';
var webpackConfig = {
context: cwd,
entry: path.resolve(cwd, entryPoint),
module: {
rules: []
},
output: {
path: path.resolve(cwd, program.out),
filename: filename + '.js',
library: name,
libraryTarget: 'umd'
},
plugins: []
};
if (program.babel) {
var babelConfig = {
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
presets: [
['env', {
targets: {
chrome: 54,
browsers: 'last 2 versions'
}
}]
]
}
};
webpackConfig.module.rules.push(babelConfig);
}
webpack(webpackConfig, function (err, stats) {
var jsonStats = stats.toJson();
if (err) {
throw err;
} else if (jsonStats.errors.length > 0) {
printErrors(jsonStats.errors);
process.exit(1);
} else if (jsonStats.warnings.length > 0 && program.verbose) {
printErrors(jsonStats.warnings);
} else {
console.log('Build of ' + filename + ' successful');
if (program.uglify) {
doMinify();
}
}
});
function doMinify() {
webpackConfig.devtool = 'source-map';
webpackConfig.output.devtoolModuleFilenameTemplate = 'webpack:///' + (pkg.name || '') + '/[resource-path]';
webpackConfig.output.filename = filename + '.min.js';
var Babili = require('babili-webpack-plugin');
webpackConfig.plugins.push(new Babili());
webpack(webpackConfig, function (err, stats) {
var jsonStats = stats.toJson();
if (err) {
throw err;
} else if (jsonStats.errors.length > 0) {
printErrors(jsonStats.errors);
process.exit(1);
} else if (jsonStats.warnings.length > 0 && program.verbose) {
printErrors(jsonStats.warnings);
} else {
console.log('Build of ' + filename + ' (min) successful');
}
});
}
function tryPackage(cwd) {
var pkg = path.join(cwd, 'package.json');
try {
return JSON.parse(fs.readFileSync(pkg, 'utf8'));
} catch (e) {
return {};
}
}
function printErrors(errors) {
errors.forEach(function (error) {
console.error(error);
});
}
|
build: change babel-preset-env browser config
|
bin/cheminfo-build.js
|
build: change babel-preset-env browser config
|
<ide><path>in/cheminfo-build.js
<ide> presets: [
<ide> ['env', {
<ide> targets: {
<del> chrome: 54,
<del> browsers: 'last 2 versions'
<add> browsers: [
<add> 'chrome >= 54',
<add> 'last 2 edge versions',
<add> 'last 1 safari version'
<add> ]
<ide> }
<ide> }]
<ide> ]
|
|
Java
|
apache-2.0
|
654ce80eec4a5cbbdc8a871c6da9242d2b70d08d
| 0 |
ddanny/achartengine,kaytdek/achartengine,ylfonline/achartengine,ddanny/achartengine,kaytdek/achartengine,ylfonline/achartengine
|
/**
* Copyright (C) 2009, 2010 SC 4ViewSoft SRL
*
* 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.achartengine;
import org.achartengine.chart.AbstractChart;
import org.achartengine.chart.RoundChart;
import org.achartengine.chart.XYChart;
import org.achartengine.model.SeriesSelection;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.tools.FitZoom;
import org.achartengine.tools.Zoom;
import org.achartengine.tools.ZoomListener;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Build;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
/**
* The view that encapsulates the graphical chart.
*/
public class GraphicalView extends View {
/** The chart to be drawn. */
private AbstractChart mChart;
/** The chart renderer. */
private DefaultRenderer mRenderer;
/** The view bounds. */
private Rect mRect = new Rect();
/** The user interface thread handler. */
private Handler mHandler;
/** The zoom buttons rectangle. */
private RectF zoomR = new RectF();
/** The zoom in icon. */
private Bitmap zoomInImage;
/** The zoom out icon. */
private Bitmap zoomOutImage;
/** The fit zoom icon. */
private Bitmap fitZoomImage;
/** The zoom area size. */
private int zoomSize = 50;
/** The zoom buttons background color. */
private static final int ZOOM_BUTTONS_COLOR = Color.argb(175, 150, 150, 150);
/** The zoom in tool. */
private Zoom mZoomIn;
/** The zoom out tool. */
private Zoom mZoomOut;
/** The fit zoom tool. */
private FitZoom mFitZoom;
/** The paint to be used when drawing the chart. */
private Paint mPaint = new Paint();
/** The touch handler. */
private ITouchHandler mTouchHandler;
/** The old x coordinate. */
private float oldX;
/** The old y coordinate. */
private float oldY;
/**
* Creates a new graphical view.
*
* @param context the context
* @param chart the chart to be drawn
*/
public GraphicalView(Context context, AbstractChart chart) {
super(context);
mChart = chart;
mHandler = new Handler();
if (mChart instanceof XYChart) {
mRenderer = ((XYChart) mChart).getRenderer();
} else {
mRenderer = ((RoundChart) mChart).getRenderer();
}
if (mRenderer.isZoomButtonsVisible()) {
zoomInImage = BitmapFactory.decodeStream(getClass().getResourceAsStream("image/zoom_in.png"));
zoomOutImage = BitmapFactory.decodeStream(getClass()
.getResourceAsStream("image/zoom_out.png"));
fitZoomImage = BitmapFactory.decodeStream(getClass().getResourceAsStream("image/zoom-1.png"));
}
if (mRenderer instanceof XYMultipleSeriesRenderer
&& ((XYMultipleSeriesRenderer) mRenderer).getMarginsColor() == XYMultipleSeriesRenderer.NO_COLOR) {
((XYMultipleSeriesRenderer) mRenderer).setMarginsColor(mPaint.getColor());
}
if (mRenderer.isZoomEnabled() && mRenderer.isZoomButtonsVisible()
|| mRenderer.isExternalZoomEnabled()) {
mZoomIn = new Zoom(mChart, true, mRenderer.getZoomRate());
mZoomOut = new Zoom(mChart, false, mRenderer.getZoomRate());
mFitZoom = new FitZoom(mChart);
}
int version = 7;
try {
version = Integer.valueOf(Build.VERSION.SDK);
} catch (Exception e) {
// do nothing
}
if (version < 7) {
mTouchHandler = new TouchHandlerOld(this, mChart);
} else {
mTouchHandler = new TouchHandler(this, mChart);
}
}
public SeriesSelection getCurrentSeriesAndPoint() {
return mChart.getSeriesAndPointForScreenCoordinate(new PointF(oldX, oldY));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.getClipBounds(mRect);
int top = mRect.top;
int left = mRect.left;
int width = mRect.width();
int height = mRect.height();
mChart.draw(canvas, left, top, width, height, mPaint);
if (mRenderer != null && mRenderer.isZoomEnabled() && mRenderer.isZoomButtonsVisible()) {
mPaint.setColor(ZOOM_BUTTONS_COLOR);
zoomSize = Math.max(zoomSize, Math.min(width, height) / 7);
zoomR.set(left + width - zoomSize * 3, top + height - zoomSize * 0.775f, left + width, top
+ height);
canvas.drawRoundRect(zoomR, zoomSize / 3, zoomSize / 3, mPaint);
float buttonY = top + height - zoomSize * 0.625f;
canvas.drawBitmap(zoomInImage, left + width - zoomSize * 2.75f, buttonY, null);
canvas.drawBitmap(zoomOutImage, left + width - zoomSize * 1.75f, buttonY, null);
canvas.drawBitmap(fitZoomImage, left + width - zoomSize * 0.75f, buttonY, null);
}
}
/**
* Sets the zoom rate.
*
* @param rate the zoom rate
*/
public void setZoomRate(float rate) {
if (mZoomIn != null && mZoomOut != null) {
mZoomIn.setZoomRate(rate);
mZoomOut.setZoomRate(rate);
}
}
/**
* Do a chart zoom in.
*/
public void zoomIn() {
if (mZoomIn != null) {
mZoomIn.apply();
repaint();
}
}
/**
* Do a chart zoom out.
*/
public void zoomOut() {
if (mZoomOut != null) {
mZoomOut.apply();
repaint();
}
}
/**
* Do a chart zoom reset / fit zoom.
*/
public void zoomReset() {
if (mFitZoom != null) {
mFitZoom.apply();
mZoomIn.notifyZoomResetListeners();
repaint();
}
}
/**
* Adds a new zoom listener.
*
* @param listener zoom listener
*/
public void addZoomListener(ZoomListener listener, boolean onButtons, boolean onPinch) {
if (onButtons) {
if (mZoomIn != null) {
mZoomIn.addZoomListener(listener);
mZoomOut.addZoomListener(listener);
}
if (onPinch) {
mTouchHandler.addZoomListener(listener);
}
}
}
/**
* Removes a zoom listener.
*
* @param listener zoom listener
*/
public synchronized void removeZoomListener(ZoomListener listener) {
if (mZoomIn != null) {
mZoomIn.removeZoomListener(listener);
mZoomOut.removeZoomListener(listener);
}
}
protected RectF getZoomRectangle() {
return zoomR;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// save the x and y so they can be used in the click and long press
// listeners
oldX = event.getX();
oldY = event.getY();
}
if (mRenderer != null && (mRenderer.isPanEnabled() || mRenderer.isZoomEnabled())) {
if (mTouchHandler.handleTouch(event)) {
return true;
}
}
return super.onTouchEvent(event);
}
/**
* Schedule a view content repaint.
*/
public void repaint() {
mHandler.post(new Runnable() {
public void run() {
invalidate();
}
});
}
/**
* Schedule a view content repaint, in the specified rectangle area.
*
* @param left the left position of the area to be repainted
* @param top the top position of the area to be repainted
* @param right the right position of the area to be repainted
* @param bottom the bottom position of the area to be repainted
*/
public void repaint(final int left, final int top, final int right, final int bottom) {
mHandler.post(new Runnable() {
public void run() {
invalidate(left, top, right, bottom);
}
});
}
/**
* Saves the content of the graphical view to a bitmap.
*
* @return the bitmap
*/
public Bitmap toBitmap() {
if (!isDrawingCacheEnabled()) {
setDrawingCacheEnabled(true);
}
setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
return getDrawingCache();
}
}
|
achartengine/src/org/achartengine/GraphicalView.java
|
/**
* Copyright (C) 2009, 2010 SC 4ViewSoft SRL
*
* 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.achartengine;
import org.achartengine.chart.AbstractChart;
import org.achartengine.chart.RoundChart;
import org.achartengine.chart.XYChart;
import org.achartengine.model.SeriesSelection;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.tools.FitZoom;
import org.achartengine.tools.Zoom;
import org.achartengine.tools.ZoomListener;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Build;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
/**
* The view that encapsulates the graphical chart.
*/
public class GraphicalView extends View {
/** The chart to be drawn. */
private AbstractChart mChart;
/** The chart renderer. */
private DefaultRenderer mRenderer;
/** The view bounds. */
private Rect mRect = new Rect();
/** The user interface thread handler. */
private Handler mHandler;
/** The zoom buttons rectangle. */
private RectF zoomR = new RectF();
/** The zoom in icon. */
private Bitmap zoomInImage;
/** The zoom out icon. */
private Bitmap zoomOutImage;
/** The fit zoom icon. */
private Bitmap fitZoomImage;
/** The zoom area size. */
private int zoomSize = 50;
/** The zoom buttons background color. */
private static final int ZOOM_BUTTONS_COLOR = Color.argb(175, 150, 150, 150);
/** The zoom in tool. */
private Zoom mZoomIn;
/** The zoom out tool. */
private Zoom mZoomOut;
/** The fit zoom tool. */
private FitZoom mFitZoom;
/** The paint to be used when drawing the chart. */
private Paint mPaint = new Paint();
/** The touch handler. */
private ITouchHandler mTouchHandler;
/** The old x coordinate. */
private float oldX;
/** The old y coordinate. */
private float oldY;
/**
* Creates a new graphical view.
*
* @param context the context
* @param chart the chart to be drawn
*/
public GraphicalView(Context context, AbstractChart chart) {
super(context);
mChart = chart;
mHandler = new Handler();
if (mChart instanceof XYChart) {
mRenderer = ((XYChart) mChart).getRenderer();
} else {
mRenderer = ((RoundChart) mChart).getRenderer();
}
if (mRenderer.isZoomButtonsVisible()) {
zoomInImage = BitmapFactory.decodeStream(getClass().getResourceAsStream("image/zoom_in.png"));
zoomOutImage = BitmapFactory.decodeStream(getClass()
.getResourceAsStream("image/zoom_out.png"));
fitZoomImage = BitmapFactory.decodeStream(getClass().getResourceAsStream("image/zoom-1.png"));
}
if (mRenderer instanceof XYMultipleSeriesRenderer
&& ((XYMultipleSeriesRenderer) mRenderer).getMarginsColor() == XYMultipleSeriesRenderer.NO_COLOR) {
((XYMultipleSeriesRenderer) mRenderer).setMarginsColor(mPaint.getColor());
}
if (mRenderer.isZoomEnabled() && mRenderer.isZoomButtonsVisible() || mRenderer.isExternalZoomEnabled()) {
mZoomIn = new Zoom(mChart, true, mRenderer.getZoomRate());
mZoomOut = new Zoom(mChart, false, mRenderer.getZoomRate());
mFitZoom = new FitZoom(mChart);
}
int version = 7;
try {
version = Integer.valueOf(Build.VERSION.SDK);
} catch (Exception e) {
// do nothing
}
if (version < 7) {
mTouchHandler = new TouchHandlerOld(this, mChart);
} else {
mTouchHandler = new TouchHandler(this, mChart);
}
}
public SeriesSelection getCurrentSeriesAndPoint() {
return mChart.getSeriesAndPointForScreenCoordinate(new PointF(oldX, oldY));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.getClipBounds(mRect);
int top = mRect.top;
int left = mRect.left;
int width = mRect.width();
int height = mRect.height();
mChart.draw(canvas, left, top, width, height, mPaint);
if (mRenderer != null && mRenderer.isZoomEnabled() && mRenderer.isZoomButtonsVisible()) {
mPaint.setColor(ZOOM_BUTTONS_COLOR);
zoomSize = Math.max(zoomSize, Math.min(width, height) / 7);
zoomR.set(left + width - zoomSize * 3, top + height - zoomSize * 0.775f, left + width, top
+ height);
canvas.drawRoundRect(zoomR, zoomSize / 3, zoomSize / 3, mPaint);
float buttonY = top + height - zoomSize * 0.625f;
canvas.drawBitmap(zoomInImage, left + width - zoomSize * 2.75f, buttonY, null);
canvas.drawBitmap(zoomOutImage, left + width - zoomSize * 1.75f, buttonY, null);
canvas.drawBitmap(fitZoomImage, left + width - zoomSize * 0.75f, buttonY, null);
}
}
/**
* Sets the zoom rate.
*
* @param rate the zoom rate
*/
public void setZoomRate(float rate) {
if (mZoomIn != null && mZoomOut != null) {
mZoomIn.setZoomRate(rate);
mZoomOut.setZoomRate(rate);
}
}
/**
* Do a chart zoom in.
*/
public void zoomIn() {
if (mZoomIn != null) {
mZoomIn.apply();
repaint();
}
}
/**
* Do a chart zoom out.
*/
public void zoomOut() {
if (mZoomOut != null) {
mZoomOut.apply();
repaint();
}
}
/**
* Do a chart zoom reset / fit zoom.
*/
public void zoomReset() {
if (mFitZoom != null) {
mFitZoom.apply();
mZoomIn.notifyZoomResetListeners();
repaint();
}
}
/**
* Adds a new zoom listener.
*
* @param listener zoom listener
*/
public void addZoomListener(ZoomListener listener, boolean onButtons, boolean onPinch) {
if (onButtons) {
if (mZoomIn != null) {
mZoomIn.addZoomListener(listener);
mZoomOut.addZoomListener(listener);
}
if (onPinch) {
mTouchHandler.addZoomListener(listener);
}
}
}
/**
* Removes a zoom listener.
*
* @param listener zoom listener
*/
public synchronized void removeZoomListener(ZoomListener listener) {
if (mZoomIn != null) {
mZoomIn.removeZoomListener(listener);
mZoomOut.removeZoomListener(listener);
}
}
protected RectF getZoomRectangle() {
return zoomR;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// save the x and y so they can be used in the click and long press
// listeners
oldX = event.getX();
oldY = event.getY();
}
if (mRenderer != null && (mRenderer.isPanEnabled() || mRenderer.isZoomEnabled())) {
if (mTouchHandler.handleTouch(event)) {
return true;
}
}
return super.onTouchEvent(event);
}
/**
* Schedule a view content repaint.
*/
public void repaint() {
mHandler.post(new Runnable() {
public void run() {
invalidate();
}
});
}
/**
* Schedule a view content repaint, in the specified rectangle area.
*
* @param left the left position of the area to be repainted
* @param top the top position of the area to be repainted
* @param right the right position of the area to be repainted
* @param bottom the bottom position of the area to be repainted
*/
public void repaint(final int left, final int top, final int right, final int bottom) {
mHandler.post(new Runnable() {
public void run() {
invalidate(left, top, right, bottom);
}
});
}
/**
* Saves the content of the graphical view to a bitmap.
*
* @return the bitmap
*/
public Bitmap toBitmap() {
if (!isDrawingCacheEnabled()) {
setDrawingCacheEnabled(true);
}
return getDrawingCache();
}
}
|
Some improvement for issue #98.
|
achartengine/src/org/achartengine/GraphicalView.java
|
Some improvement for issue #98.
|
<ide><path>chartengine/src/org/achartengine/GraphicalView.java
<ide> && ((XYMultipleSeriesRenderer) mRenderer).getMarginsColor() == XYMultipleSeriesRenderer.NO_COLOR) {
<ide> ((XYMultipleSeriesRenderer) mRenderer).setMarginsColor(mPaint.getColor());
<ide> }
<del> if (mRenderer.isZoomEnabled() && mRenderer.isZoomButtonsVisible() || mRenderer.isExternalZoomEnabled()) {
<add> if (mRenderer.isZoomEnabled() && mRenderer.isZoomButtonsVisible()
<add> || mRenderer.isExternalZoomEnabled()) {
<ide> mZoomIn = new Zoom(mChart, true, mRenderer.getZoomRate());
<ide> mZoomOut = new Zoom(mChart, false, mRenderer.getZoomRate());
<ide> mFitZoom = new FitZoom(mChart);
<ide> repaint();
<ide> }
<ide> }
<del>
<add>
<ide> /**
<ide> * Adds a new zoom listener.
<ide> *
<ide> }
<ide> return super.onTouchEvent(event);
<ide> }
<del>
<add>
<ide> /**
<ide> * Schedule a view content repaint.
<ide> */
<ide> if (!isDrawingCacheEnabled()) {
<ide> setDrawingCacheEnabled(true);
<ide> }
<add> setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
<ide> return getDrawingCache();
<ide> }
<ide>
|
|
Java
|
mit
|
error: pathspec 'src/main/java/br/com/dbsoft/util/DBSSort.java' did not match any file(s) known to git
|
d32f63eebca7b78ef97de1b82c21abf3ea0bad49
| 1 |
dbsoftcombr/dbssdk
|
package br.com.dbsoft.util;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import br.com.dbsoft.comparator.DBSComparator;
import br.com.dbsoft.util.DBSIO.SORT_DIRECTION;
public class DBSSort {
/**
* Retorna Map ordenado pelo value.
* @param pUnSortedMap
* @param pSortDirection
* @return
*/
public static <K, V> Map<K, V> getMapByValue(Map<K, V> pUnSortedMap, SORT_DIRECTION pSortDirection) {
DBSComparator<Map.Entry<K, V>> xComparator = new DBSComparator<Map.Entry<K, V>>("Value", pSortDirection);
// 1. Convert Map to List of Map
List<Map.Entry<K, V>> xList = new LinkedList<Map.Entry<K, V>>(pUnSortedMap.entrySet());
// 2. Sort list with Collections.sort(), provide a custom Comparator
Collections.sort(xList, xComparator);
// 3. Loop the sorted list and put it into a new insertion order Map LinkedHashMap
Map<K, V> xSortedMap = new LinkedHashMap<K ,V>();
for (Map.Entry<K, V> xEntry : xList){
xSortedMap.put(xEntry.getKey(), xEntry.getValue());
}
return xSortedMap;
}
}
|
src/main/java/br/com/dbsoft/util/DBSSort.java
|
sort de maps utilizando getMapByValue
|
src/main/java/br/com/dbsoft/util/DBSSort.java
|
sort de maps utilizando getMapByValue
|
<ide><path>rc/main/java/br/com/dbsoft/util/DBSSort.java
<add>package br.com.dbsoft.util;
<add>
<add>import java.util.Collections;
<add>import java.util.LinkedHashMap;
<add>import java.util.LinkedList;
<add>import java.util.List;
<add>import java.util.Map;
<add>
<add>import br.com.dbsoft.comparator.DBSComparator;
<add>import br.com.dbsoft.util.DBSIO.SORT_DIRECTION;
<add>
<add>public class DBSSort {
<add>
<add> /**
<add> * Retorna Map ordenado pelo value.
<add> * @param pUnSortedMap
<add> * @param pSortDirection
<add> * @return
<add> */
<add> public static <K, V> Map<K, V> getMapByValue(Map<K, V> pUnSortedMap, SORT_DIRECTION pSortDirection) {
<add> DBSComparator<Map.Entry<K, V>> xComparator = new DBSComparator<Map.Entry<K, V>>("Value", pSortDirection);
<add> // 1. Convert Map to List of Map
<add> List<Map.Entry<K, V>> xList = new LinkedList<Map.Entry<K, V>>(pUnSortedMap.entrySet());
<add>
<add> // 2. Sort list with Collections.sort(), provide a custom Comparator
<add> Collections.sort(xList, xComparator);
<add>
<add> // 3. Loop the sorted list and put it into a new insertion order Map LinkedHashMap
<add> Map<K, V> xSortedMap = new LinkedHashMap<K ,V>();
<add> for (Map.Entry<K, V> xEntry : xList){
<add> xSortedMap.put(xEntry.getKey(), xEntry.getValue());
<add> }
<add> return xSortedMap;
<add> }
<add>}
|
|
Java
|
mit
|
error: pathspec 'test/DroneCommanderTest.java' did not match any file(s) known to git
|
8409b1cb105e424a124963b5a5126b17841ef3dd
| 1 |
ugent-cros/cros-core,ugent-cros/cros-core,ugent-cros/cros-core
|
import drones.models.*;
import models.Drone;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import scala.concurrent.Await;
import scala.concurrent.Future;
import scala.concurrent.duration.Duration;
import simulation.SimulatorDriver;
import java.util.concurrent.TimeUnit;
/**
* Created by yasser on 25/03/15.
*/
public class DroneCommanderTest extends TestSuperclass {
private static final Duration TIME_OUT = Duration.create(5, TimeUnit.SECONDS);
@BeforeClass
public static void setup() {
startFakeApplication();
}
@AfterClass
public static void tearDown() {
stopFakeApplication();
}
private Drone testDrone;
@Before
public void createCommander() {
testDrone = new Drone("simulator", Drone.Status.AVAILABLE, SimulatorDriver.SIMULATOR_TYPE, "x");
testDrone.save();
DroneDriver driver = new SimulatorDriver();
Fleet.registerDriver(SimulatorDriver.SIMULATOR_TYPE, driver);
}
@Test(expected = DroneException.class)
public void takeOff_WithOutInit_Fails() throws Exception {
DroneCommander commander = Fleet.getFleet().getCommanderForDrone(testDrone);
Future future = commander.takeOff();
Await.result(future, TIME_OUT);
}
@Test(expected = DroneException.class)
public void land_WithOutInit_Fails() throws Exception {
DroneCommander commander = Fleet.getFleet().getCommanderForDrone(testDrone);
Future future = commander.land();
Await.result(future, TIME_OUT);
}
@Test(expected = DroneException.class)
public void setMaxHeight_WithOutInit_Fails() throws Exception {
DroneCommander commander = Fleet.getFleet().getCommanderForDrone(testDrone);
Future future = commander.setMaxHeight(20);
Await.result(future, TIME_OUT);
}
@Test(expected = DroneException.class)
public void moveToLocation_WithOutInit_Fails() throws Exception {
DroneCommander commander = Fleet.getFleet().getCommanderForDrone(testDrone);
Future future = commander.moveToLocation(20, 30, 20);
Await.result(future, TIME_OUT);
}
@Test
public void init_Simulator_Succeeds() throws Exception {
DroneCommander commander = Fleet.getFleet().getCommanderForDrone(testDrone);
Future future = commander.init();
Await.result(future, TIME_OUT);
}
@Test
public void calibrate_AfterInit_Succeeds() throws Exception {
DroneCommander commander = Fleet.getFleet().getCommanderForDrone(testDrone);
Future future = commander.init();
Await.result(future, TIME_OUT);
future = commander.calibrate(false, true);
Await.result(future, TIME_OUT);
}
@Test
public void getState_AfterInit_Succeeds() throws Exception {
DroneCommander commander = Fleet.getFleet().getCommanderForDrone(testDrone);
Future future = commander.init();
Await.result(future, TIME_OUT);
future = commander.getFlyingState();
FlyingState state = (FlyingState) Await.result(future, TIME_OUT);
}
}
|
test/DroneCommanderTest.java
|
Wrote tests for drone code
|
test/DroneCommanderTest.java
|
Wrote tests for drone code
|
<ide><path>est/DroneCommanderTest.java
<add>import drones.models.*;
<add>import models.Drone;
<add>import org.junit.AfterClass;
<add>import org.junit.Before;
<add>import org.junit.BeforeClass;
<add>import org.junit.Test;
<add>import scala.concurrent.Await;
<add>import scala.concurrent.Future;
<add>import scala.concurrent.duration.Duration;
<add>import simulation.SimulatorDriver;
<add>
<add>import java.util.concurrent.TimeUnit;
<add>
<add>/**
<add> * Created by yasser on 25/03/15.
<add> */
<add>public class DroneCommanderTest extends TestSuperclass {
<add>
<add> private static final Duration TIME_OUT = Duration.create(5, TimeUnit.SECONDS);
<add>
<add> @BeforeClass
<add> public static void setup() {
<add> startFakeApplication();
<add> }
<add>
<add> @AfterClass
<add> public static void tearDown() {
<add> stopFakeApplication();
<add> }
<add>
<add> private Drone testDrone;
<add>
<add> @Before
<add> public void createCommander() {
<add>
<add> testDrone = new Drone("simulator", Drone.Status.AVAILABLE, SimulatorDriver.SIMULATOR_TYPE, "x");
<add> testDrone.save();
<add>
<add> DroneDriver driver = new SimulatorDriver();
<add> Fleet.registerDriver(SimulatorDriver.SIMULATOR_TYPE, driver);
<add> }
<add>
<add> @Test(expected = DroneException.class)
<add> public void takeOff_WithOutInit_Fails() throws Exception {
<add>
<add> DroneCommander commander = Fleet.getFleet().getCommanderForDrone(testDrone);
<add> Future future = commander.takeOff();
<add> Await.result(future, TIME_OUT);
<add> }
<add>
<add> @Test(expected = DroneException.class)
<add> public void land_WithOutInit_Fails() throws Exception {
<add>
<add> DroneCommander commander = Fleet.getFleet().getCommanderForDrone(testDrone);
<add> Future future = commander.land();
<add> Await.result(future, TIME_OUT);
<add> }
<add>
<add> @Test(expected = DroneException.class)
<add> public void setMaxHeight_WithOutInit_Fails() throws Exception {
<add>
<add> DroneCommander commander = Fleet.getFleet().getCommanderForDrone(testDrone);
<add> Future future = commander.setMaxHeight(20);
<add> Await.result(future, TIME_OUT);
<add> }
<add>
<add> @Test(expected = DroneException.class)
<add> public void moveToLocation_WithOutInit_Fails() throws Exception {
<add>
<add> DroneCommander commander = Fleet.getFleet().getCommanderForDrone(testDrone);
<add> Future future = commander.moveToLocation(20, 30, 20);
<add> Await.result(future, TIME_OUT);
<add> }
<add>
<add> @Test
<add> public void init_Simulator_Succeeds() throws Exception {
<add>
<add> DroneCommander commander = Fleet.getFleet().getCommanderForDrone(testDrone);
<add> Future future = commander.init();
<add> Await.result(future, TIME_OUT);
<add> }
<add>
<add> @Test
<add> public void calibrate_AfterInit_Succeeds() throws Exception {
<add>
<add> DroneCommander commander = Fleet.getFleet().getCommanderForDrone(testDrone);
<add> Future future = commander.init();
<add> Await.result(future, TIME_OUT);
<add> future = commander.calibrate(false, true);
<add> Await.result(future, TIME_OUT);
<add> }
<add>
<add> @Test
<add> public void getState_AfterInit_Succeeds() throws Exception {
<add>
<add> DroneCommander commander = Fleet.getFleet().getCommanderForDrone(testDrone);
<add> Future future = commander.init();
<add> Await.result(future, TIME_OUT);
<add> future = commander.getFlyingState();
<add> FlyingState state = (FlyingState) Await.result(future, TIME_OUT);
<add> }
<add>}
|
|
Java
|
bsd-3-clause
|
00ebaec0a19f70e1ae85c5679e7b9afb4cf4788c
| 0 |
jamie-dryad/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,jamie-dryad/dryad-repo,rnathanday/dryad-repo,mdiggory/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,ojacobson/dryad-repo,ojacobson/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,ojacobson/dryad-repo,ojacobson/dryad-repo,jamie-dryad/dryad-repo,mdiggory/dryad-repo,mdiggory/dryad-repo,mdiggory/dryad-repo,rnathanday/dryad-repo,ojacobson/dryad-repo,jimallman/dryad-repo,jimallman/dryad-repo,jamie-dryad/dryad-repo,jimallman/dryad-repo,jamie-dryad/dryad-repo,ojacobson/dryad-repo,mdiggory/dryad-repo
|
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.discovery;
import org.apache.log4j.Logger;
import org.apache.commons.cli.*;
import org.dspace.core.Context;
import org.dspace.utils.DSpace;
import java.io.IOException;
import java.sql.SQLException;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
/**
* Class used to reindex dspace communities/collections/items into discovery
*
* @author Kevin Van de Velde (kevin at atmire dot com)
* @author Mark Diggory (markd at atmire dot com)
* @author Ben Bosman (ben at atmire dot com)
* @author Dan Leehr ([email protected])
*/
public class IndexClient {
private static final Logger log = Logger.getLogger(IndexClient.class);
/**
* When invoked as a command-line tool, creates, updates, removes content
* from the whole index
*
* @param args the command-line arguments, none used
* @throws java.io.IOException
* @throws java.sql.SQLException
* @throws org.apache.solr.client.solrj.SolrServerException
*
*/
public static void main(String[] args) throws SQLException, IOException, SearchServiceException {
Context context = new Context();
context.setIgnoreAuthorization(true);
String usage = "org.dspace.discovery.IndexClient [-cbhf[r <item handle>][i <item id>]] or nothing to update/clean an existing index.";
Options options = new Options();
HelpFormatter formatter = new HelpFormatter();
CommandLine line = null;
options
.addOption(OptionBuilder
.withArgName("item handle")
.hasArg(true)
.withDescription(
"remove an Item, Collection or Community from index based on its handle")
.create("r"));
options
.addOption(OptionBuilder
.isRequired(false)
.withDescription(
"clean existing index removing any documents that no longer exist in the db")
.create("c"));
options.addOption(OptionBuilder.isRequired(false).withDescription(
"(re)build index, wiping out current one if it exists").create(
"b"));
options
.addOption(OptionBuilder
.isRequired(false)
.withDescription(
"if updating existing index, force each handle to be reindexed even if uptodate")
.create("f"));
options.addOption(OptionBuilder.isRequired(false).withDescription(
"print this help message").create("h"));
options.addOption(OptionBuilder.isRequired(false).withDescription(
"optimize search solr core").create("o"));
options.addOption(OptionBuilder
.withArgName("item id")
.hasArg(true)
.withDescription(
"re-index an Item, based on its internal item_id")
.create("i"));
try {
line = new PosixParser().parse(options, args);
} catch (Exception e) {
// automatically generate the help statement
formatter.printHelp(usage, e.getMessage(), options, "");
System.exit(1);
}
if (line.hasOption("h")) {
// automatically generate the help statement
formatter.printHelp(usage, options);
System.exit(1);
}
/** Acquire from dspace-services in future */
/**
* new DSpace.getServiceManager().getServiceByName("org.dspace.discovery.SolrIndexer");
*/
DSpace dspace = new DSpace();
IndexingService indexer = dspace.getServiceManager().getServiceByName(IndexingService.class.getName(),IndexingService.class);
if (line.hasOption("r")) {
log.info("Removing " + line.getOptionValue("r") + " from Index");
indexer.unIndexContent(context, line.getOptionValue("r"));
} else if (line.hasOption("c")) {
log.info("Cleaning Index");
indexer.cleanIndex(line.hasOption("f"));
} else if (line.hasOption("b")) {
log.info("(Re)building index from scratch.");
indexer.createIndex(context);
} else if (line.hasOption("o")) {
log.info("Optimizing search core.");
indexer.optimize();
} else if (line.hasOption("i")) {
Integer itemId = Integer.valueOf(line.getOptionValue("i"));
DSpaceObject dso = Item.find(context, itemId);
log.info("Reindexing Object:" + dso);
indexer.reIndexContent(context, dso);
} else {
log.info("Updating and Cleaning Index");
indexer.cleanIndex(line.hasOption("f"));
indexer.updateIndex(context, line.hasOption("f"));
}
log.info("Done with indexing");
}
}
|
dspace/modules/api/src/main/java/org/dspace/discovery/IndexClient.java
|
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.discovery;
import org.apache.log4j.Logger;
import org.apache.commons.cli.*;
import org.dspace.core.Context;
import org.dspace.utils.DSpace;
import java.io.IOException;
import java.sql.SQLException;
/**
* Class used to reindex dspace communities/collections/items into discovery
*
* @author Kevin Van de Velde (kevin at atmire dot com)
* @author Mark Diggory (markd at atmire dot com)
* @author Ben Bosman (ben at atmire dot com)
*/
public class IndexClient {
private static final Logger log = Logger.getLogger(IndexClient.class);
/**
* When invoked as a command-line tool, creates, updates, removes content
* from the whole index
*
* @param args the command-line arguments, none used
* @throws java.io.IOException
* @throws java.sql.SQLException
* @throws org.apache.solr.client.solrj.SolrServerException
*
*/
public static void main(String[] args) throws SQLException, IOException, SearchServiceException {
Context context = new Context();
context.setIgnoreAuthorization(true);
String usage = "org.dspace.discovery.IndexClient [-cbhf[r <item handle>]] or nothing to update/clean an existing index.";
Options options = new Options();
HelpFormatter formatter = new HelpFormatter();
CommandLine line = null;
options
.addOption(OptionBuilder
.withArgName("item handle")
.hasArg(true)
.withDescription(
"remove an Item, Collection or Community from index based on its handle")
.create("r"));
options
.addOption(OptionBuilder
.isRequired(false)
.withDescription(
"clean existing index removing any documents that no longer exist in the db")
.create("c"));
options.addOption(OptionBuilder.isRequired(false).withDescription(
"(re)build index, wiping out current one if it exists").create(
"b"));
options
.addOption(OptionBuilder
.isRequired(false)
.withDescription(
"if updating existing index, force each handle to be reindexed even if uptodate")
.create("f"));
options.addOption(OptionBuilder.isRequired(false).withDescription(
"print this help message").create("h"));
options.addOption(OptionBuilder.isRequired(false).withDescription(
"optimize search solr core").create("o"));
try {
line = new PosixParser().parse(options, args);
} catch (Exception e) {
// automatically generate the help statement
formatter.printHelp(usage, e.getMessage(), options, "");
System.exit(1);
}
if (line.hasOption("h")) {
// automatically generate the help statement
formatter.printHelp(usage, options);
System.exit(1);
}
/** Acquire from dspace-services in future */
/**
* new DSpace.getServiceManager().getServiceByName("org.dspace.discovery.SolrIndexer");
*/
DSpace dspace = new DSpace();
IndexingService indexer = dspace.getServiceManager().getServiceByName(IndexingService.class.getName(),IndexingService.class);
if (line.hasOption("r")) {
log.info("Removing " + line.getOptionValue("r") + " from Index");
indexer.unIndexContent(context, line.getOptionValue("r"));
} else if (line.hasOption("c")) {
log.info("Cleaning Index");
indexer.cleanIndex(line.hasOption("f"));
} else if (line.hasOption("b")) {
log.info("(Re)building index from scratch.");
indexer.createIndex(context);
} else if (line.hasOption("o")) {
log.info("Optimizing search core.");
indexer.optimize();
} else {
log.info("Updating and Cleaning Index");
indexer.cleanIndex(line.hasOption("f"));
indexer.updateIndex(context, line.hasOption("f"));
}
log.info("Done with indexing");
}
}
|
Add -i option to IndexClient for re-indexing single items
|
dspace/modules/api/src/main/java/org/dspace/discovery/IndexClient.java
|
Add -i option to IndexClient for re-indexing single items
|
<ide><path>space/modules/api/src/main/java/org/dspace/discovery/IndexClient.java
<ide>
<ide> import java.io.IOException;
<ide> import java.sql.SQLException;
<add>import org.dspace.content.DSpaceObject;
<add>import org.dspace.content.Item;
<ide>
<ide> /**
<ide> * Class used to reindex dspace communities/collections/items into discovery
<ide> * @author Kevin Van de Velde (kevin at atmire dot com)
<ide> * @author Mark Diggory (markd at atmire dot com)
<ide> * @author Ben Bosman (ben at atmire dot com)
<add> * @author Dan Leehr ([email protected])
<ide> */
<ide> public class IndexClient {
<ide>
<ide> Context context = new Context();
<ide> context.setIgnoreAuthorization(true);
<ide>
<del> String usage = "org.dspace.discovery.IndexClient [-cbhf[r <item handle>]] or nothing to update/clean an existing index.";
<add> String usage = "org.dspace.discovery.IndexClient [-cbhf[r <item handle>][i <item id>]] or nothing to update/clean an existing index.";
<ide> Options options = new Options();
<ide> HelpFormatter formatter = new HelpFormatter();
<ide> CommandLine line = null;
<ide>
<ide> options.addOption(OptionBuilder.isRequired(false).withDescription(
<ide> "optimize search solr core").create("o"));
<add> options.addOption(OptionBuilder
<add> .withArgName("item id")
<add> .hasArg(true)
<add> .withDescription(
<add> "re-index an Item, based on its internal item_id")
<add> .create("i"));
<ide>
<ide> try {
<ide> line = new PosixParser().parse(options, args);
<ide> } else if (line.hasOption("o")) {
<ide> log.info("Optimizing search core.");
<ide> indexer.optimize();
<add> } else if (line.hasOption("i")) {
<add> Integer itemId = Integer.valueOf(line.getOptionValue("i"));
<add> DSpaceObject dso = Item.find(context, itemId);
<add> log.info("Reindexing Object:" + dso);
<add> indexer.reIndexContent(context, dso);
<ide> } else {
<ide> log.info("Updating and Cleaning Index");
<ide> indexer.cleanIndex(line.hasOption("f"));
|
|
Java
|
apache-2.0
|
24e296b86971d8e075cba241bbb44fe6f76b472a
| 0 |
sdnwiselab/onos,mengmoya/onos,opennetworkinglab/onos,osinstom/onos,LorenzReinhart/ONOSnew,osinstom/onos,maheshraju-Huawei/actn,opennetworkinglab/onos,VinodKumarS-Huawei/ietf96yang,VinodKumarS-Huawei/ietf96yang,sonu283304/onos,maheshraju-Huawei/actn,y-higuchi/onos,kuujo/onos,sdnwiselab/onos,y-higuchi/onos,maheshraju-Huawei/actn,VinodKumarS-Huawei/ietf96yang,kuujo/onos,oplinkoms/onos,LorenzReinhart/ONOSnew,VinodKumarS-Huawei/ietf96yang,Shashikanth-Huawei/bmp,opennetworkinglab/onos,sdnwiselab/onos,Shashikanth-Huawei/bmp,lsinfo3/onos,kuujo/onos,kuujo/onos,oplinkoms/onos,mengmoya/onos,lsinfo3/onos,kuujo/onos,LorenzReinhart/ONOSnew,oplinkoms/onos,donNewtonAlpha/onos,donNewtonAlpha/onos,sdnwiselab/onos,mengmoya/onos,LorenzReinhart/ONOSnew,maheshraju-Huawei/actn,sonu283304/onos,donNewtonAlpha/onos,oplinkoms/onos,gkatsikas/onos,donNewtonAlpha/onos,gkatsikas/onos,VinodKumarS-Huawei/ietf96yang,gkatsikas/onos,mengmoya/onos,y-higuchi/onos,kuujo/onos,osinstom/onos,lsinfo3/onos,Shashikanth-Huawei/bmp,sonu283304/onos,sdnwiselab/onos,osinstom/onos,sonu283304/onos,LorenzReinhart/ONOSnew,opennetworkinglab/onos,Shashikanth-Huawei/bmp,gkatsikas/onos,opennetworkinglab/onos,Shashikanth-Huawei/bmp,gkatsikas/onos,oplinkoms/onos,oplinkoms/onos,oplinkoms/onos,osinstom/onos,kuujo/onos,opennetworkinglab/onos,y-higuchi/onos,gkatsikas/onos,sdnwiselab/onos,y-higuchi/onos,donNewtonAlpha/onos,maheshraju-Huawei/actn,mengmoya/onos,lsinfo3/onos
|
/*
* Copyright 2014 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.net.flow;
import com.google.common.annotations.Beta;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.DefaultGroupId;
import org.onosproject.core.GroupId;
import org.onosproject.net.DeviceId;
import java.util.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
public class DefaultFlowRule implements FlowRule {
private final DeviceId deviceId;
private final int priority;
private final TrafficSelector selector;
private final TrafficTreatment treatment;
private final long created;
private final FlowId id;
private final Short appId;
private final int timeout;
private final boolean permanent;
private final GroupId groupId;
private final Integer tableId;
private final FlowRuleExtPayLoad payLoad;
public DefaultFlowRule(FlowRule rule) {
this.deviceId = rule.deviceId();
this.priority = rule.priority();
this.selector = rule.selector();
this.treatment = rule.treatment();
this.appId = rule.appId();
this.groupId = rule.groupId();
this.id = rule.id();
this.timeout = rule.timeout();
this.permanent = rule.isPermanent();
this.created = System.currentTimeMillis();
this.tableId = rule.tableId();
this.payLoad = rule.payLoad();
}
private DefaultFlowRule(DeviceId deviceId, TrafficSelector selector,
TrafficTreatment treatment, Integer priority,
FlowId flowId, Boolean permanent, Integer timeout,
Integer tableId) {
this.deviceId = deviceId;
this.selector = selector;
this.treatment = treatment;
this.priority = priority;
this.appId = (short) (flowId.value() >>> 48);
this.id = flowId;
this.permanent = permanent;
this.timeout = timeout;
this.tableId = tableId;
this.created = System.currentTimeMillis();
//FIXME: fields below will be removed.
this.groupId = new DefaultGroupId(0);
this.payLoad = null;
}
/**
* Support for the third party flow rule. Creates a flow rule of flow table.
*
* @param deviceId the identity of the device where this rule applies
* @param selector the traffic selector that identifies what traffic this
* rule
* @param treatment the traffic treatment that applies to selected traffic
* @param priority the flow rule priority given in natural order
* @param appId the application id of this flow
* @param timeout the timeout for this flow requested by an application
* @param permanent whether the flow is permanent i.e. does not time out
* @param payLoad 3rd-party origin private flow
*/
public DefaultFlowRule(DeviceId deviceId, TrafficSelector selector,
TrafficTreatment treatment, int priority,
ApplicationId appId, int timeout, boolean permanent,
FlowRuleExtPayLoad payLoad) {
if (priority < FlowRule.MIN_PRIORITY) {
throw new IllegalArgumentException("Priority cannot be less than "
+ MIN_PRIORITY);
}
this.deviceId = deviceId;
this.priority = priority;
this.selector = selector;
this.treatment = treatment;
this.appId = appId.id();
this.groupId = new DefaultGroupId(0);
this.timeout = timeout;
this.permanent = permanent;
this.tableId = 0;
this.created = System.currentTimeMillis();
this.payLoad = payLoad;
/*
* id consists of the following. | appId (16 bits) | groupId (16 bits) |
* flowId (32 bits) |
*/
this.id = FlowId.valueOf((((long) this.appId) << 48)
| (((long) this.groupId.id()) << 32)
| (this.hash() & 0xffffffffL));
}
/**
* Support for the third party flow rule. Creates a flow rule of group
* table.
*
* @param deviceId the identity of the device where this rule applies
* @param selector the traffic selector that identifies what traffic this
* rule
* @param treatment the traffic treatment that applies to selected traffic
* @param priority the flow rule priority given in natural order
* @param appId the application id of this flow
* @param groupId the group id of this flow
* @param timeout the timeout for this flow requested by an application
* @param permanent whether the flow is permanent i.e. does not time out
* @param payLoad 3rd-party origin private flow
*
*/
public DefaultFlowRule(DeviceId deviceId, TrafficSelector selector,
TrafficTreatment treatment, int priority,
ApplicationId appId, GroupId groupId, int timeout,
boolean permanent, FlowRuleExtPayLoad payLoad) {
if (priority < FlowRule.MIN_PRIORITY) {
throw new IllegalArgumentException("Priority cannot be less than "
+ MIN_PRIORITY);
}
this.deviceId = deviceId;
this.priority = priority;
this.selector = selector;
this.treatment = treatment;
this.appId = appId.id();
this.groupId = groupId;
this.timeout = timeout;
this.permanent = permanent;
this.created = System.currentTimeMillis();
this.tableId = 0;
this.payLoad = payLoad;
/*
* id consists of the following. | appId (16 bits) | groupId (16 bits) |
* flowId (32 bits) |
*/
this.id = FlowId.valueOf((((long) this.appId) << 48)
| (((long) this.groupId.id()) << 32)
| (this.hash() & 0xffffffffL));
}
@Override
public FlowId id() {
return id;
}
@Override
public short appId() {
return appId;
}
@Override
public GroupId groupId() {
return groupId;
}
@Override
public int priority() {
return priority;
}
@Override
public DeviceId deviceId() {
return deviceId;
}
@Override
public TrafficSelector selector() {
return selector;
}
@Override
public TrafficTreatment treatment() {
return treatment;
}
@Override
/*
* The priority and statistics can change on a given treatment and selector
*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
public int hashCode() {
return Objects.hash(deviceId, selector, tableId, payLoad);
}
//FIXME do we need this method in addition to hashCode()?
private int hash() {
return Objects.hash(deviceId, selector, tableId, payLoad);
}
@Override
/*
* The priority and statistics can change on a given treatment and selector
*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof DefaultFlowRule) {
DefaultFlowRule that = (DefaultFlowRule) obj;
return Objects.equals(deviceId, that.deviceId) &&
Objects.equals(priority, that.priority) &&
Objects.equals(selector, that.selector) &&
Objects.equals(tableId, that.tableId)
&& Objects.equals(payLoad, that.payLoad);
}
return false;
}
@Override
public boolean exactMatch(FlowRule rule) {
return this.equals(rule) &&
Objects.equals(this.id, rule.id()) &&
Objects.equals(this.treatment, rule.treatment());
}
@Override
public String toString() {
return toStringHelper(this)
.add("id", Long.toHexString(id.value()))
.add("deviceId", deviceId)
.add("priority", priority)
.add("selector", selector.criteria())
.add("treatment", treatment == null ? "N/A" : treatment.allInstructions())
.add("tableId", tableId)
.add("created", created)
.add("payLoad", payLoad)
.toString();
}
@Override
public int timeout() {
return timeout;
}
@Override
public boolean isPermanent() {
return permanent;
}
@Override
public int tableId() {
return tableId;
}
@Beta
public long created() {
return created;
}
public static Builder builder() {
return new Builder();
}
public static final class Builder implements FlowRule.Builder {
private FlowId flowId;
private ApplicationId appId;
private Integer priority;
private DeviceId deviceId;
private Integer tableId = 0;
private TrafficSelector selector = DefaultTrafficSelector.builder().build();
private TrafficTreatment treatment = DefaultTrafficTreatment.builder().build();
private Integer timeout;
private Boolean permanent;
@Override
public FlowRule.Builder withCookie(long cookie) {
this.flowId = FlowId.valueOf(cookie);
return this;
}
@Override
public FlowRule.Builder fromApp(ApplicationId appId) {
this.appId = appId;
return this;
}
@Override
public FlowRule.Builder withPriority(int priority) {
this.priority = priority;
return this;
}
@Override
public FlowRule.Builder forDevice(DeviceId deviceId) {
this.deviceId = deviceId;
return this;
}
@Override
public FlowRule.Builder forTable(int tableId) {
this.tableId = tableId;
return this;
}
@Override
public FlowRule.Builder withSelector(TrafficSelector selector) {
this.selector = selector;
return this;
}
@Override
public FlowRule.Builder withTreatment(TrafficTreatment treatment) {
this.treatment = checkNotNull(treatment);
return this;
}
@Override
public FlowRule.Builder makePermanent() {
this.timeout = 0;
this.permanent = true;
return this;
}
@Override
public FlowRule.Builder makeTemporary(int timeout) {
this.permanent = false;
this.timeout = timeout;
return this;
}
@Override
public FlowRule build() {
checkArgument(flowId != null || appId != null, "Either an application" +
" id or a cookie must be supplied");
checkNotNull(selector, "Traffic selector cannot be null");
checkArgument(timeout != null || permanent != null, "Must either have " +
"a timeout or be permanent");
checkNotNull(deviceId, "Must refer to a device");
checkNotNull(priority, "Priority cannot be null");
checkArgument(priority >= MIN_PRIORITY, "Priority cannot be less than " +
MIN_PRIORITY);
// Computing a flow ID based on appId takes precedence over setting
// the flow ID directly
if (appId != null) {
flowId = computeFlowId(appId);
}
return new DefaultFlowRule(deviceId, selector, treatment, priority,
flowId, permanent, timeout, tableId);
}
private FlowId computeFlowId(ApplicationId appId) {
return FlowId.valueOf((((long) appId.id()) << 48)
| (hash() & 0xffffffffL));
}
private int hash() {
return Objects.hash(deviceId, priority, selector, tableId);
}
}
@Override
public FlowRuleExtPayLoad payLoad() {
return payLoad;
}
}
|
core/api/src/main/java/org/onosproject/net/flow/DefaultFlowRule.java
|
/*
* Copyright 2014 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.net.flow;
import com.google.common.annotations.Beta;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.DefaultGroupId;
import org.onosproject.core.GroupId;
import org.onosproject.net.DeviceId;
import java.util.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
public class DefaultFlowRule implements FlowRule {
private final DeviceId deviceId;
private final int priority;
private final TrafficSelector selector;
private final TrafficTreatment treatment;
private final long created;
private final FlowId id;
private final Short appId;
private final int timeout;
private final boolean permanent;
private final GroupId groupId;
private final Integer tableId;
private final FlowRuleExtPayLoad payLoad;
public DefaultFlowRule(FlowRule rule) {
this.deviceId = rule.deviceId();
this.priority = rule.priority();
this.selector = rule.selector();
this.treatment = rule.treatment();
this.appId = rule.appId();
this.groupId = rule.groupId();
this.id = rule.id();
this.timeout = rule.timeout();
this.permanent = rule.isPermanent();
this.created = System.currentTimeMillis();
this.tableId = rule.tableId();
this.payLoad = rule.payLoad();
}
private DefaultFlowRule(DeviceId deviceId, TrafficSelector selector,
TrafficTreatment treatment, Integer priority,
FlowId flowId, Boolean permanent, Integer timeout,
Integer tableId) {
this.deviceId = deviceId;
this.selector = selector;
this.treatment = treatment;
this.priority = priority;
this.appId = (short) (flowId.value() >>> 48);
this.id = flowId;
this.permanent = permanent;
this.timeout = timeout;
this.tableId = tableId;
this.created = System.currentTimeMillis();
//FIXME: fields below will be removed.
this.groupId = new DefaultGroupId(0);
this.payLoad = null;
}
/**
* Support for the third party flow rule. Creates a flow rule of flow table.
*
* @param deviceId the identity of the device where this rule applies
* @param selector the traffic selector that identifies what traffic this
* rule
* @param treatment the traffic treatment that applies to selected traffic
* @param priority the flow rule priority given in natural order
* @param appId the application id of this flow
* @param timeout the timeout for this flow requested by an application
* @param permanent whether the flow is permanent i.e. does not time out
* @param payLoad 3rd-party origin private flow
*/
public DefaultFlowRule(DeviceId deviceId, TrafficSelector selector,
TrafficTreatment treatment, int priority,
ApplicationId appId, int timeout, boolean permanent,
FlowRuleExtPayLoad payLoad) {
if (priority < FlowRule.MIN_PRIORITY) {
throw new IllegalArgumentException("Priority cannot be less than "
+ MIN_PRIORITY);
}
this.deviceId = deviceId;
this.priority = priority;
this.selector = selector;
this.treatment = treatment;
this.appId = appId.id();
this.groupId = new DefaultGroupId(0);
this.timeout = timeout;
this.permanent = permanent;
this.tableId = 0;
this.created = System.currentTimeMillis();
this.payLoad = payLoad;
/*
* id consists of the following. | appId (16 bits) | groupId (16 bits) |
* flowId (32 bits) |
*/
this.id = FlowId.valueOf((((long) this.appId) << 48)
| (((long) this.groupId.id()) << 32)
| (this.hash() & 0xffffffffL));
}
/**
* Support for the third party flow rule. Creates a flow rule of group
* table.
*
* @param deviceId the identity of the device where this rule applies
* @param selector the traffic selector that identifies what traffic this
* rule
* @param treatment the traffic treatment that applies to selected traffic
* @param priority the flow rule priority given in natural order
* @param appId the application id of this flow
* @param groupId the group id of this flow
* @param timeout the timeout for this flow requested by an application
* @param permanent whether the flow is permanent i.e. does not time out
* @param payLoad 3rd-party origin private flow
*
*/
public DefaultFlowRule(DeviceId deviceId, TrafficSelector selector,
TrafficTreatment treatment, int priority,
ApplicationId appId, GroupId groupId, int timeout,
boolean permanent, FlowRuleExtPayLoad payLoad) {
if (priority < FlowRule.MIN_PRIORITY) {
throw new IllegalArgumentException("Priority cannot be less than "
+ MIN_PRIORITY);
}
this.deviceId = deviceId;
this.priority = priority;
this.selector = selector;
this.treatment = treatment;
this.appId = appId.id();
this.groupId = groupId;
this.timeout = timeout;
this.permanent = permanent;
this.created = System.currentTimeMillis();
this.tableId = 0;
this.payLoad = payLoad;
/*
* id consists of the following. | appId (16 bits) | groupId (16 bits) |
* flowId (32 bits) |
*/
this.id = FlowId.valueOf((((long) this.appId) << 48)
| (((long) this.groupId.id()) << 32)
| (this.hash() & 0xffffffffL));
}
@Override
public FlowId id() {
return id;
}
@Override
public short appId() {
return appId;
}
@Override
public GroupId groupId() {
return groupId;
}
@Override
public int priority() {
return priority;
}
@Override
public DeviceId deviceId() {
return deviceId;
}
@Override
public TrafficSelector selector() {
return selector;
}
@Override
public TrafficTreatment treatment() {
return treatment;
}
@Override
/*
* The priority and statistics can change on a given treatment and selector
*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
public int hashCode() {
return Objects.hash(deviceId, selector, tableId, payLoad);
}
//FIXME do we need this method in addition to hashCode()?
private int hash() {
return Objects.hash(deviceId, selector, tableId, payLoad);
}
@Override
/*
* The priority and statistics can change on a given treatment and selector
*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof DefaultFlowRule) {
DefaultFlowRule that = (DefaultFlowRule) obj;
return Objects.equals(deviceId, that.deviceId) &&
Objects.equals(priority, that.priority) &&
Objects.equals(selector, that.selector) &&
Objects.equals(tableId, that.tableId)
&& Objects.equals(payLoad, that.payLoad);
}
return false;
}
@Override
public boolean exactMatch(FlowRule rule) {
return this.equals(rule) &&
Objects.equals(this.id, rule.id()) &&
Objects.equals(this.treatment, rule.treatment());
}
@Override
public String toString() {
return toStringHelper(this)
.add("id", Long.toHexString(id.value()))
.add("deviceId", deviceId)
.add("priority", priority)
.add("selector", selector.criteria())
.add("treatment", treatment == null ? "N/A" : treatment.allInstructions())
.add("tableId", tableId)
.add("created", created)
.add("payLoad", payLoad)
.toString();
}
@Override
public int timeout() {
return timeout;
}
@Override
public boolean isPermanent() {
return permanent;
}
@Override
public int tableId() {
return tableId;
}
@Beta
public long created() {
return created;
}
public static Builder builder() {
return new Builder();
}
public static final class Builder implements FlowRule.Builder {
private FlowId flowId;
private ApplicationId appId;
private Integer priority;
private DeviceId deviceId;
private Integer tableId = 0;
private TrafficSelector selector = DefaultTrafficSelector.builder().build();
private TrafficTreatment treatment = DefaultTrafficTreatment.builder().build();
private Integer timeout;
private Boolean permanent;
@Override
public FlowRule.Builder withCookie(long cookie) {
this.flowId = FlowId.valueOf(cookie);
return this;
}
@Override
public FlowRule.Builder fromApp(ApplicationId appId) {
this.appId = appId;
return this;
}
@Override
public FlowRule.Builder withPriority(int priority) {
this.priority = priority;
return this;
}
@Override
public FlowRule.Builder forDevice(DeviceId deviceId) {
this.deviceId = deviceId;
return this;
}
@Override
public FlowRule.Builder forTable(int tableId) {
this.tableId = tableId;
return this;
}
@Override
public FlowRule.Builder withSelector(TrafficSelector selector) {
this.selector = selector;
return this;
}
@Override
public FlowRule.Builder withTreatment(TrafficTreatment treatment) {
this.treatment = treatment;
return this;
}
@Override
public FlowRule.Builder makePermanent() {
this.timeout = 0;
this.permanent = true;
return this;
}
@Override
public FlowRule.Builder makeTemporary(int timeout) {
this.permanent = false;
this.timeout = timeout;
return this;
}
@Override
public FlowRule build() {
checkArgument(flowId != null || appId != null, "Either an application" +
" id or a cookie must be supplied");
checkNotNull(selector, "Traffic selector cannot be null");
checkArgument(timeout != null || permanent != null, "Must either have " +
"a timeout or be permanent");
checkNotNull(deviceId, "Must refer to a device");
checkNotNull(priority, "Priority cannot be null");
checkArgument(priority >= MIN_PRIORITY, "Priority cannot be less than " +
MIN_PRIORITY);
// Computing a flow ID based on appId takes precedence over setting
// the flow ID directly
if (appId != null) {
flowId = computeFlowId(appId);
}
return new DefaultFlowRule(deviceId, selector, treatment, priority,
flowId, permanent, timeout, tableId);
}
private FlowId computeFlowId(ApplicationId appId) {
return FlowId.valueOf((((long) appId.id()) << 48)
| (hash() & 0xffffffffL));
}
private int hash() {
return Objects.hash(deviceId, priority, selector, tableId);
}
}
@Override
public FlowRuleExtPayLoad payLoad() {
return payLoad;
}
}
|
Prevent null treatments
Change-Id: Icd40ab7f986f9738d0445428cd1f0c9053ed4e88
|
core/api/src/main/java/org/onosproject/net/flow/DefaultFlowRule.java
|
Prevent null treatments
|
<ide><path>ore/api/src/main/java/org/onosproject/net/flow/DefaultFlowRule.java
<ide>
<ide> @Override
<ide> public FlowRule.Builder withTreatment(TrafficTreatment treatment) {
<del> this.treatment = treatment;
<add> this.treatment = checkNotNull(treatment);
<ide> return this;
<ide> }
<ide>
|
|
JavaScript
|
mit
|
5b49f50e8974f680d8bc574a1ca31b787633645a
| 0 |
mosbymc/pointfree-js,mosbymc/queryable-js
|
import { arraySet, objectSet, isArray } from './functionalHelpers';
import { curry, compose, kestrel, when } from './combinators';
import { Maybe } from './containers/monads/maybe_monad';
import { Identity } from './containers/monads/identity_monad';
import { Constant } from './containers/monads/constant_monad';
import { mapWith } from './pointlessContainers';
/**
* @description:
* @type: {function}
* @param: {number} idx
* @param: {function} f
* @param: {Array} xs
* @return: {Array}
*/
var arrayLens = curry(function _arrayLens(idx, f, xs) {
return mapWith(function (val) {
return arraySet(idx, val, xs)
}, f(xs[idx]));
});
/**
* @description:
* @type: {function}
* @param: {string} prop
* @param: {function} f
* @param: {Object} xs
* @return: {Object}
*/
var objectLens = curry(function _objectLens(prop, f, xs) {
return mapWith(function _map(rep) {
return objectSet(prop, rep, xs);
}, f(xs[prop]));
});
/**
* @description:
* @type: {function}
* @param: {function} lens
* @param: {Object} target
* @return:
*/
var view = curry(function _view(lens, target) {
return lens(Constant)(target).value;
});
/**
* @description:
* @type: {function}
* @param: {function} lens
* @param: {function} mapFn
* @param: {Object} target
* @return: {*}
*/
var over = curry(function _over(lens, mapFn, target) {
return lens(function _lens(y) {
return Identity(mapFn(y));
})(target).value;
});
/**
* @description:
* @type: {function}
* @param: {function} lens
* @param: {*} val
* @param: {*} target
* @return: {*}
*/
var put = curry(function _put(lens, val, target) {
return over(lens, kestrel(val), target);
});
/**
* @type: {*}
* @description:
* @param: {function} lens
* @param: {*} val
* @param: {Object} targetData
* @return: {*}
*/
var set = curry((lens, val, targetData) => over(lens, kestrel(val), targetData));
/**
* @description:
* @param: {Array} paths
* @return: {*}
*/
function makeLenses(...paths) {
return paths.reduce(function _pathReduce(cur, next) {
var ol = objectLens(next);
return put(ol, ol, cur);
}, { num: arrayLens });
}
/**
* @description:
* @param: {Array} path
* @return: {*}
*/
function lensPath(...path) {
return compose(...path.map(function _pathMap(p) {
return 'string' === typeof p ? objectLens(p) : arrayLens(p);
}));
}
/**
* @type: {*}
* @description:
* @param: {function} getter
* @param: {function} setter
* @param: {String} key
* @param: {function} f
* @param: {Array} xs
* @return: {*}
*/
var lens = curry(function _lens(getter, setter, key, f, xs) {
return mapWith(replace => setter(key, replace, xs), f(getter(key, xs)));
});
/**
* @type" {*}
* @description:
* @param: {Array|String} path
* @param: {Object} obj
* @return: {*}
*/
var maybePath = curry(function _maybePath(path, obj) {
path = when(not(isArray), split('.'), path);
var val = obj,
idx = 0;
while (idx < path.length) {
if (null == val) return Maybe.Nothing();
val = val[path[idx]];
++idx;
}
return Maybe(val);
});
/**
* @type {*}
* @description:
* @param: {String} delimiter
* @param: {String} string
* @return: {Array}
*/
var split = curry(function _split(delimiter, string) {
return string.split(delimiter);
});
export { arrayLens, objectLens, view, over, put, set, lens, maybePath, makeLenses, lensPath };
|
src/lenses.js
|
import { arraySet, objectSet, isArray } from './functionalHelpers';
import { curry, compose, identity, kestrel, when } from './combinators';
import { Maybe } from './containers/monads/maybe_monad';
/**
* @description:
* @type: {function}
* @param: {number} idx
* @param: {function} f
* @param: {Array} xs
* @return: {Array}
*/
var arrayLens = curry(function _arrayLens(idx, f, xs) {
return map(function (val) {
return arraySet(idx, val, xs)
}, f(xs[idx]));
});
/**
* @description:
* @type: {function}
* @param: {string} prop
* @param: {function} f
* @param: {Object} xs
* @return: {Object}
*/
var objectLens = curry(function _objectLens(prop, f, xs) {
return map(function _map(rep) {
return objectSet(prop, rep, xs);
}, f(xs[prop]));
});
/**
* @description:
* @type: {function}
* @param: {function} lens
* @param: {Object} target
* @return:
*/
var view = curry(function _view(lens, target) {
return lens(kestrel)(target).value;
});
/**
* @description:
* @type: {function}
* @param: {function} lens
* @param: {function} mapFn
* @param: {Object} target
* @return:
*/
var over = curry(function _over(lens, mapFn, target) {
return lens(function _lens(y) {
return identity(mapFn(y));
})(target).value;
});
/**
* @description:
* @type: {function}
* @param: {function} lens
* @param: {*} val
* @param: {*} target
* @return:
*/
var put = curry(function _put(lens, val, target) {
return over(lens, kestrel(val), target);
});
/**
* @description:
* @param: {Array} paths
* @return: {*}
*/
function makeLenses(...paths) {
return paths.reduce(function _pathReduce(cur, next) {
var ol = objectLens(next);
return put(ol, ol, cur);
}, { num: arrayLens });
}
/**
* @description:
* @param: {Array} path
* @return: {*}
*/
function lensPath(...path) {
return compose(...path.map(function _pathMap(p) {
return 'string' === typeof p ? objectLens(p) : arrayLens(p);
}));
}
var maybePath = curry(function _maybePath(path, obj) {
path = when(not(isArray), split('.'), path);
var val = obj,
idx = 0;
while (idx < path.length) {
if (null == val) return Maybe.Nothing();
val = val[path[idx]];
++idx;
}
return Maybe(val);
});
var split = curry(function _split(delimiter, string) {
return string.split(delimiter);
});
export { arrayLens, objectLens, view, over, put, makeLenses, lensPath };
|
develop: added comments to lens functions without; added a couple of new functions to lenses; fixed some of the original lens functions that expect to operate on top of a functor
|
src/lenses.js
|
develop: added comments to lens functions without; added a couple of new functions to lenses; fixed some of the original lens functions that expect to operate on top of a functor
|
<ide><path>rc/lenses.js
<ide> import { arraySet, objectSet, isArray } from './functionalHelpers';
<del>import { curry, compose, identity, kestrel, when } from './combinators';
<add>import { curry, compose, kestrel, when } from './combinators';
<ide> import { Maybe } from './containers/monads/maybe_monad';
<add>import { Identity } from './containers/monads/identity_monad';
<add>import { Constant } from './containers/monads/constant_monad';
<add>import { mapWith } from './pointlessContainers';
<ide>
<ide> /**
<ide> * @description:
<ide> * @return: {Array}
<ide> */
<ide> var arrayLens = curry(function _arrayLens(idx, f, xs) {
<del> return map(function (val) {
<add> return mapWith(function (val) {
<ide> return arraySet(idx, val, xs)
<ide> }, f(xs[idx]));
<ide> });
<ide> * @return: {Object}
<ide> */
<ide> var objectLens = curry(function _objectLens(prop, f, xs) {
<del> return map(function _map(rep) {
<add> return mapWith(function _map(rep) {
<ide> return objectSet(prop, rep, xs);
<ide> }, f(xs[prop]));
<ide> });
<ide> * @return:
<ide> */
<ide> var view = curry(function _view(lens, target) {
<del> return lens(kestrel)(target).value;
<add> return lens(Constant)(target).value;
<ide> });
<ide>
<ide> /**
<ide> * @param: {function} lens
<ide> * @param: {function} mapFn
<ide> * @param: {Object} target
<del> * @return:
<add> * @return: {*}
<ide> */
<ide> var over = curry(function _over(lens, mapFn, target) {
<ide> return lens(function _lens(y) {
<del> return identity(mapFn(y));
<add> return Identity(mapFn(y));
<ide> })(target).value;
<ide> });
<ide>
<ide> * @param: {function} lens
<ide> * @param: {*} val
<ide> * @param: {*} target
<del> * @return:
<add> * @return: {*}
<ide> */
<ide> var put = curry(function _put(lens, val, target) {
<ide> return over(lens, kestrel(val), target);
<ide> });
<add>
<add>/**
<add> * @type: {*}
<add> * @description:
<add> * @param: {function} lens
<add> * @param: {*} val
<add> * @param: {Object} targetData
<add> * @return: {*}
<add> */
<add>var set = curry((lens, val, targetData) => over(lens, kestrel(val), targetData));
<ide>
<ide> /**
<ide> * @description:
<ide> }));
<ide> }
<ide>
<add>/**
<add> * @type: {*}
<add> * @description:
<add> * @param: {function} getter
<add> * @param: {function} setter
<add> * @param: {String} key
<add> * @param: {function} f
<add> * @param: {Array} xs
<add> * @return: {*}
<add> */
<add>var lens = curry(function _lens(getter, setter, key, f, xs) {
<add> return mapWith(replace => setter(key, replace, xs), f(getter(key, xs)));
<add>});
<add>
<add>/**
<add> * @type" {*}
<add> * @description:
<add> * @param: {Array|String} path
<add> * @param: {Object} obj
<add> * @return: {*}
<add> */
<ide> var maybePath = curry(function _maybePath(path, obj) {
<ide> path = when(not(isArray), split('.'), path);
<ide> var val = obj,
<ide> return Maybe(val);
<ide> });
<ide>
<add>/**
<add> * @type {*}
<add> * @description:
<add> * @param: {String} delimiter
<add> * @param: {String} string
<add> * @return: {Array}
<add> */
<ide> var split = curry(function _split(delimiter, string) {
<ide> return string.split(delimiter);
<ide> });
<ide>
<del>export { arrayLens, objectLens, view, over, put, makeLenses, lensPath };
<add>export { arrayLens, objectLens, view, over, put, set, lens, maybePath, makeLenses, lensPath };
|
|
JavaScript
|
mit
|
c3bc49d5d4e10211f0fe4f4b9bbbf24f27c4823a
| 0 |
natefinch/discourse,natefinch/discourse
|
/**
Breaks up a long string
@method breakUp
@for Handlebars
**/
Handlebars.registerHelper('breakUp', function(property, hint, options) {
var prop = Ember.Handlebars.get(this, property, options);
if (!prop) return "";
if (typeof(hint) === 'string') {
hint = Ember.Handlebars.get(this, hint, options);
} else {
hint = undefined;
}
return new Handlebars.SafeString(Discourse.Formatter.breakUp(prop, hint));
});
// helper function for dates
function daysSinceEpoch(dt) {
// 1000 * 60 * 60 * 24 = days since epoch
return dt.getTime() / 86400000;
}
/**
Converts a date to a coldmap class
@method coldDate
**/
Handlebars.registerHelper('coldAgeClass', function(property, options) {
var dt = Em.Handlebars.get(this, property, options);
if (!dt) { return 'age'; }
// Show heat on age
var nowDays = daysSinceEpoch(new Date()),
epochDays = daysSinceEpoch(new Date(dt));
if (nowDays - epochDays > 60) return 'age coldmap-high';
if (nowDays - epochDays > 30) return 'age coldmap-med';
if (nowDays - epochDays > 14) return 'age coldmap-low';
return 'age';
});
/**
Truncates long strings
@method shorten
@for Handlebars
**/
Handlebars.registerHelper('shorten', function(property, options) {
return Ember.Handlebars.get(this, property, options).substring(0,35);
});
/**
Produces a link to a topic
@method topicLink
@for Handlebars
**/
Handlebars.registerHelper('topicLink', function(property, options) {
var topic = Ember.Handlebars.get(this, property, options),
title = topic.get('fancy_title') || topic.get('title');
return "<a href='" + topic.get('lastUnreadUrl') + "' class='title'>" + title + "</a>";
});
/**
Produces a link to a category given a category object and helper options
@method categoryLinkHTML
@param {Discourse.Category} category to link to
@param {Object} options standard from handlebars
**/
function categoryLinkHTML(category, options) {
var categoryOptions = {};
if (options.hash) {
if (options.hash.allowUncategorized) { categoryOptions.allowUncategorized = true; }
if (options.hash.showParent) { categoryOptions.showParent = true; }
if (options.hash.link !== undefined) { categoryOptions.link = options.hash.link; }
if (options.hash.extraClasses) { categoryOptions.extraClasses = options.hash.extraClasses; }
if (options.hash.categories) {
categoryOptions.categories = Em.Handlebars.get(this, options.hash.categories, options);
}
}
return new Handlebars.SafeString(Discourse.HTML.categoryBadge(category, categoryOptions));
}
/**
Produces a link to a category
@method categoryLink
@for Handlebars
**/
Handlebars.registerHelper('categoryLink', function(property, options) {
return categoryLinkHTML(Ember.Handlebars.get(this, property, options), options);
});
Handlebars.registerHelper('categoryLinkRaw', function(property, options) {
return categoryLinkHTML(property, options);
});
Handlebars.registerHelper('categoryBadge', function(property, options) {
options.hash.link = false;
return categoryLinkHTML(Ember.Handlebars.get(this, property, options), options);
});
/**
Produces a bound link to a category
@method boundCategoryLink
@for Handlebars
**/
Ember.Handlebars.registerBoundHelper('boundCategoryLink', categoryLinkHTML);
/**
Produces a link to a route with support for i18n on the title
@method titledLinkTo
@for Handlebars
**/
Handlebars.registerHelper('titledLinkTo', function(name, object) {
var options = [].slice.call(arguments, -1)[0];
if (options.hash.titleKey) {
options.hash.title = I18n.t(options.hash.titleKey);
}
if (arguments.length === 3) {
return Ember.Handlebars.helpers['link-to'].call(this, name, object, options);
} else {
return Ember.Handlebars.helpers['link-to'].call(this, name, options);
}
});
/**
Shorten a URL for display by removing common components
@method shortenUrl
@for Handlebars
**/
Handlebars.registerHelper('shortenUrl', function(property, options) {
var url, matches;
url = Ember.Handlebars.get(this, property, options);
// Remove trailing slash if it's a top level URL
matches = url.match(/\//g);
if (matches && matches.length === 3) {
url = url.replace(/\/$/, '');
}
url = url.replace(/^https?:\/\//, '');
url = url.replace(/^www\./, '');
return url.substring(0,80);
});
/**
Display a property in lower case
@method lower
@for Handlebars
**/
Handlebars.registerHelper('lower', function(property, options) {
var o;
o = Ember.Handlebars.get(this, property, options);
if (o && typeof o === 'string') {
return o.toLowerCase();
} else {
return "";
}
});
/**
Show an avatar for a user, intelligently making use of available properties
@method avatar
@for Handlebars
**/
Handlebars.registerHelper('avatar', function(user, options) {
if (typeof user === 'string') {
user = Ember.Handlebars.get(this, user, options);
}
if (user) {
var username = Em.get(user, 'username');
if (!username) username = Em.get(user, options.hash.usernamePath);
var avatarTemplate;
var template = options.hash.template;
if (template && template !== 'avatar_template') {
avatarTemplate = Em.get(user, template);
if (!avatarTemplate) avatarTemplate = Em.get(user, 'user.' + template);
}
if (!avatarTemplate) avatarTemplate = Em.get(user, 'avatar_template');
if (!avatarTemplate) avatarTemplate = Em.get(user, 'user.avatar_template');
var title;
if (!options.hash.ignoreTitle) {
// first try to get a title
title = Em.get(user, 'title');
// if there was no title provided
if (!title) {
// try to retrieve a description
var description = Em.get(user, 'description');
// if a description has been provided
if (description && description.length > 0) {
// preprend the username before the description
title = username + " - " + description;
}
}
}
return new Handlebars.SafeString(Discourse.Utilities.avatarImg({
size: options.hash.imageSize,
extraClasses: Em.get(user, 'extras') || options.hash.extraClasses,
title: title || username,
avatarTemplate: avatarTemplate
}));
} else {
return '';
}
});
/**
Bound avatar helper.
Will rerender whenever the "avatar_template" changes.
@method boundAvatar
@for Handlebars
**/
Ember.Handlebars.registerBoundHelper('boundAvatar', function(user, options) {
return new Handlebars.SafeString(Discourse.Utilities.avatarImg({
size: options.hash.imageSize,
avatarTemplate: Em.get(user, options.hash.template || 'avatar_template')
}));
}, 'avatar_template', 'uploaded_avatar_template', 'gravatar_template');
/**
Nicely format a date without binding or returning HTML
@method rawDate
@for Handlebars
**/
Handlebars.registerHelper('rawDate', function(property, options) {
var dt = new Date(Ember.Handlebars.get(this, property, options));
return Discourse.Formatter.longDate(dt);
});
/**
Live refreshing age helper
@method unboundAge
@for Handlebars
**/
Handlebars.registerHelper('unboundAge', function(property, options) {
var dt = new Date(Ember.Handlebars.get(this, property, options));
return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(dt));
});
/**
Live refreshing age helper, with a tooltip showing the date and time
@method unboundAgeWithTooltip
@for Handlebars
**/
Handlebars.registerHelper('unboundAgeWithTooltip', function(property, options) {
var dt = new Date(Ember.Handlebars.get(this, property, options));
return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(dt, {title: true}));
});
/**
Display a date related to an edit of a post
@method editDate
@for Handlebars
**/
Handlebars.registerHelper('editDate', function(property, options) {
// autoupdating this is going to be painful
var date = new Date(Ember.Handlebars.get(this, property, options));
return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(date, {format: 'medium', title: true, leaveAgo: true, wrapInSpan: false}));
});
/**
Displays a percentile based on a `percent_rank` field
@method percentile
@for Ember.Handlebars
**/
Ember.Handlebars.registerHelper('percentile', function(property, options) {
var percentile = Ember.Handlebars.get(this, property, options);
return Math.round((1.0 - percentile) * 100);
});
/**
Displays a float nicely
@method float
@for Ember.Handlebars
**/
Ember.Handlebars.registerHelper('float', function(property, options) {
var x = Ember.Handlebars.get(this, property, options);
if (!x) return "0";
if (Math.round(x) === x) return x;
return x.toFixed(3);
});
/**
Display logic for numbers.
@method number
@for Handlebars
**/
Handlebars.registerHelper('number', function(property, options) {
var orig = parseInt(Ember.Handlebars.get(this, property, options), 10);
if (isNaN(orig)) { orig = 0; }
var title = orig;
if (options.hash.numberKey) {
title = I18n.t(options.hash.numberKey, { number: orig });
}
var classNames = 'number';
if (options.hash['class']) {
classNames += ' ' + Ember.Handlebars.get(this, options.hash['class'], options);
}
var result = "<span class='" + classNames + "'";
// Round off the thousands to one decimal place
var n = Discourse.Formatter.number(orig);
if (n !== title) {
result += " title='" + Handlebars.Utils.escapeExpression(title) + "'";
}
result += ">" + n + "</span>";
return new Handlebars.SafeString(result);
});
/**
Display logic for dates. It is unbound in Ember but will use jQuery to
update the dates on a regular interval.
@method unboundDate
@for Handlebars
**/
Handlebars.registerHelper('unboundDate', function(property, options) {
var leaveAgo;
if (property.hash) {
if (property.hash.leaveAgo) {
leaveAgo = property.hash.leaveAgo === "true";
}
if (property.hash.path) {
property = property.hash.path;
}
}
var val = Ember.Handlebars.get(this, property, options);
if (val) {
var date = new Date(val);
return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(date, {format: 'medium', title: true, leaveAgo: leaveAgo}));
}
});
Ember.Handlebars.registerBoundHelper('date', function(dt) {
return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(new Date(dt), {format: 'medium', title: true }));
});
/**
Look for custom html content using `Discourse.HTML`. If none exists, look for a template
to render with that name.
@method customHTML
@for Handlebars
**/
Handlebars.registerHelper('customHTML', function(name, contextString, options) {
var html = Discourse.HTML.getCustomHTML(name);
if (html) { return html; }
var container = (options || contextString).data.keywords.controller.container;
if (container.lookup('template:' + name)) {
return Ember.Handlebars.helpers.partial.apply(this, arguments);
}
});
Ember.Handlebars.registerBoundHelper('humanSize', function(size) {
return new Handlebars.SafeString(I18n.toHumanSize(size));
});
/**
Renders the domain for a link if it's not internal and has a title.
@method link-domain
@for Handlebars
**/
Handlebars.registerHelper('link-domain', function(property, options) {
var link = Em.get(this, property, options);
if (link) {
var internal = Em.get(link, 'internal'),
hasTitle = (!Em.isEmpty(Em.get(link, 'title')));
if (hasTitle && !internal) {
var domain = Em.get(link, 'domain');
if (!Em.isEmpty(domain)) {
var s = domain.split('.');
domain = s[s.length-2] + "." + s[s.length-1];
return new Handlebars.SafeString("<span class='domain'>" + domain + "</span>");
}
}
}
});
|
app/assets/javascripts/discourse/helpers/application_helpers.js
|
/**
Breaks up a long string
@method breakUp
@for Handlebars
**/
Handlebars.registerHelper('breakUp', function(property, hint, options) {
var prop = Ember.Handlebars.get(this, property, options);
if (!prop) return "";
if (typeof(hint) === 'string') {
hint = Ember.Handlebars.get(this, hint, options);
} else {
hint = undefined;
}
return new Handlebars.SafeString(Discourse.Formatter.breakUp(prop, hint));
});
// helper function for dates
function daysSinceEpoch(dt) {
// 1000 * 60 * 60 * 24 = days since epoch
return dt.getTime() / 86400000;
}
/**
Converts a date to a coldmap class
@method coldDate
**/
Handlebars.registerHelper('coldAgeClass', function(property, options) {
var dt = Em.Handlebars.get(this, property, options);
if (!dt) { return 'age'; }
// Show heat on age
var nowDays = daysSinceEpoch(new Date()),
epochDays = daysSinceEpoch(new Date(dt));
if (nowDays - epochDays > 60) return 'age coldmap-high';
if (nowDays - epochDays > 30) return 'age coldmap-med';
if (nowDays - epochDays > 14) return 'age coldmap-low';
return 'age';
});
/**
Truncates long strings
@method shorten
@for Handlebars
**/
Handlebars.registerHelper('shorten', function(property, options) {
return Ember.Handlebars.get(this, property, options).substring(0,35);
});
/**
Produces a link to a topic
@method topicLink
@for Handlebars
**/
Handlebars.registerHelper('topicLink', function(property, options) {
var topic = Ember.Handlebars.get(this, property, options),
title = topic.get('fancy_title') || topic.get('title');
return "<a href='" + topic.get('lastUnreadUrl') + "' class='title'>" + title + "</a>";
});
/**
Produces a link to a category given a category object and helper options
@method categoryLinkHTML
@param {Discourse.Category} category to link to
@param {Object} options standard from handlebars
**/
function categoryLinkHTML(category, options) {
var categoryOptions = {};
if (options.hash) {
if (options.hash.allowUncategorized) { categoryOptions.allowUncategorized = true; }
if (options.hash.showParent) { categoryOptions.showParent = true; }
if (options.hash.link !== undefined) { categoryOptions.link = options.hash.link; }
if (options.hash.extraClasses) { categoryOptions.extraClasses = options.hash.extraClasses; }
if (options.hash.categories) {
categoryOptions.categories = Em.Handlebars.get(this, options.hash.categories, options);
}
}
return new Handlebars.SafeString(Discourse.HTML.categoryBadge(category, categoryOptions));
}
/**
Produces a link to a category
@method categoryLink
@for Handlebars
**/
Handlebars.registerHelper('categoryLink', function(property, options) {
return categoryLinkHTML(Ember.Handlebars.get(this, property, options), options);
});
Handlebars.registerHelper('categoryLinkRaw', function(property, options) {
return categoryLinkHTML(property, options);
});
Handlebars.registerHelper('categoryBadge', function(property, options) {
options.hash.link = false;
return categoryLinkHTML(Ember.Handlebars.get(this, property, options), options);
});
/**
Produces a bound link to a category
@method boundCategoryLink
@for Handlebars
**/
Ember.Handlebars.registerBoundHelper('boundCategoryLink', categoryLinkHTML);
/**
Produces a link to a route with support for i18n on the title
@method titledLinkTo
@for Handlebars
**/
Handlebars.registerHelper('titledLinkTo', function(name, object) {
var options = [].slice.call(arguments, -1)[0];
if (options.hash.titleKey) {
options.hash.title = I18n.t(options.hash.titleKey);
}
if (arguments.length === 3) {
return Ember.Handlebars.helpers['link-to'].call(this, name, object, options);
} else {
return Ember.Handlebars.helpers['link-to'].call(this, name, options);
}
});
/**
Shorten a URL for display by removing common components
@method shortenUrl
@for Handlebars
**/
Handlebars.registerHelper('shortenUrl', function(property, options) {
var url, matches;
url = Ember.Handlebars.get(this, property, options);
// Remove trailing slash if it's a top level URL
matches = url.match(/\//g);
if (matches && matches.length === 3) {
url = url.replace(/\/$/, '');
}
url = url.replace(/^https?:\/\//, '');
url = url.replace(/^www\./, '');
return url.substring(0,80);
});
/**
Display a property in lower case
@method lower
@for Handlebars
**/
Handlebars.registerHelper('lower', function(property, options) {
var o;
o = Ember.Handlebars.get(this, property, options);
if (o && typeof o === 'string') {
return o.toLowerCase();
} else {
return "";
}
});
/**
Show an avatar for a user, intelligently making use of available properties
@method avatar
@for Handlebars
**/
Handlebars.registerHelper('avatar', function(user, options) {
if (typeof user === 'string') {
user = Ember.Handlebars.get(this, user, options);
}
if (user) {
var username = Em.get(user, 'username');
if (!username) username = Em.get(user, options.hash.usernamePath);
var avatarTemplate;
var template = options.hash.template;
if (template && template !== 'avatar_template') {
avatarTemplate = Em.get(user, template);
if (!avatarTemplate) avatarTemplate = Em.get(user, 'user.' + template);
}
if (!avatarTemplate) avatarTemplate = Em.get(user, 'avatar_template');
if (!avatarTemplate) avatarTemplate = Em.get(user, 'user.avatar_template');
var title;
if (!options.hash.ignoreTitle) {
// first try to get a title
title = Em.get(user, 'title');
// if there was no title provided
if (!title) {
// try to retrieve a description
var description = Em.get(user, 'description');
// if a description has been provided
if (description && description.length > 0) {
// preprend the username before the description
title = username + " - " + description;
}
}
}
return new Handlebars.SafeString(Discourse.Utilities.avatarImg({
size: options.hash.imageSize,
extraClasses: Em.get(user, 'extras') || options.hash.extraClasses,
title: title || username,
avatarTemplate: avatarTemplate
}));
} else {
return '';
}
});
/**
Bound avatar helper.
Will rerender whenever the "avatar_template" changes.
@method boundAvatar
@for Handlebars
**/
Ember.Handlebars.registerBoundHelper('boundAvatar', function(user, options) {
return new Handlebars.SafeString(Discourse.Utilities.avatarImg({
size: options.hash.imageSize,
avatarTemplate: Em.get(user, options.hash.template || 'avatar_template')
}));
}, 'avatar_template', 'uploaded_avatar_template', 'gravatar_template');
/**
Nicely format a date without binding or returning HTML
@method rawDate
@for Handlebars
**/
Handlebars.registerHelper('rawDate', function(property, options) {
var dt = new Date(Ember.Handlebars.get(this, property, options));
return Discourse.Formatter.longDate(dt);
});
/**
Live refreshing age helper
@method unboundAge
@for Handlebars
**/
Handlebars.registerHelper('unboundAge', function(property, options) {
var dt = new Date(Ember.Handlebars.get(this, property, options));
return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(dt));
});
/**
Live refreshing age helper, with a tooltip showing the date and time
@method unboundAgeWithTooltip
@for Handlebars
**/
Handlebars.registerHelper('unboundAgeWithTooltip', function(property, options) {
var dt = new Date(Ember.Handlebars.get(this, property, options));
return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(dt, {title: true}));
});
/**
Display a date related to an edit of a post
@method editDate
@for Handlebars
**/
Handlebars.registerHelper('editDate', function(property, options) {
// autoupdating this is going to be painful
var date = new Date(Ember.Handlebars.get(this, property, options));
return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(date, {format: 'medium', title: true, leaveAgo: true, wrapInSpan: false}));
});
/**
Displays a percentile based on a `percent_rank` field
@method percentile
@for Ember.Handlebars
**/
Ember.Handlebars.registerHelper('percentile', function(property, options) {
var percentile = Ember.Handlebars.get(this, property, options);
return Math.round((1.0 - percentile) * 100);
});
/**
Displays a float nicely
@method float
@for Ember.Handlebars
**/
Ember.Handlebars.registerHelper('float', function(property, options) {
var x = Ember.Handlebars.get(this, property, options);
if (!x) return "0";
if (Math.round(x) === x) return x;
return x.toFixed(3);
});
/**
Display logic for numbers.
@method number
@for Handlebars
**/
Handlebars.registerHelper('number', function(property, options) {
var orig = parseInt(Ember.Handlebars.get(this, property, options), 10);
if (isNaN(orig)) { orig = 0; }
var title = orig;
if (options.hash.numberKey) {
title = I18n.t(options.hash.numberKey, { number: orig });
}
var classNames = 'number';
if (options.hash['class']) {
classNames += ' ' + Ember.Handlebars.get(this, options.hash['class'], options);
}
var result = "<span class='" + classNames + "'";
// Round off the thousands to one decimal place
var n = Discourse.Formatter.number(orig);
if (n !== title) {
result += " title='" + Handlebars.Utils.escapeExpression(title) + "'";
}
result += ">" + n + "</span>";
return new Handlebars.SafeString(result);
});
/**
Display logic for dates. It is unbound in Ember but will use jQuery to
update the dates on a regular interval.
@method unboundDate
@for Handlebars
**/
Handlebars.registerHelper('unboundDate', function(property, options) {
var leaveAgo;
if (property.hash) {
if (property.hash.leaveAgo) {
leaveAgo = property.hash.leaveAgo === "true";
}
if (property.hash.path) {
property = property.hash.path;
}
}
var val = Ember.Handlebars.get(this, property, options);
if (val) {
var date = new Date(val);
return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(date, {format: 'medium', title: true, leaveAgo: leaveAgo}));
}
});
Ember.Handlebars.registerBoundHelper('date', function(dt) {
return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(new Date(dt), {format: 'medium', title: true }));
});
/**
Look for custom html content using `Discourse.HTML`. If none exists, look for a template
to render with that name.
@method customHTML
@for Handlebars
**/
Handlebars.registerHelper('customHTML', function(name, contextString, options) {
var html = Discourse.HTML.getCustomHTML(name);
if (html) { return html; }
var container = (options || contextString).data.keywords.controller.container;
if (container.lookup('template:' + name)) {
return Ember.Handlebars.helpers.partial.apply(this, arguments);
}
});
Ember.Handlebars.registerBoundHelper('humanSize', function(size) {
return new Handlebars.SafeString(I18n.toHumanSize(size));
});
/**
Renders the domain for a link if it's not internal and has a title.
@method link-domain
@for Handlebars
**/
Handlebars.registerHelper('link-domain', function(property, options) {
var link = Em.get(this, property, options);
if (link) {
var internal = Em.get(link, 'internal'),
hasTitle = (!Em.isEmpty(Em.get(link, 'title')));
if (hasTitle && !internal) {
var domain = Em.get(link, 'domain');
if (!Em.isEmpty(domain)) {
var s = domain.split('.');
domain = s[s.length-2] + "." + s[s.length-1];
return new Handlebars.SafeString("<span class='domain'>(" + domain + ")</span>");
}
}
}
});
|
Ditch params when showing link domains
|
app/assets/javascripts/discourse/helpers/application_helpers.js
|
Ditch params when showing link domains
|
<ide><path>pp/assets/javascripts/discourse/helpers/application_helpers.js
<ide> if (!Em.isEmpty(domain)) {
<ide> var s = domain.split('.');
<ide> domain = s[s.length-2] + "." + s[s.length-1];
<del> return new Handlebars.SafeString("<span class='domain'>(" + domain + ")</span>");
<add> return new Handlebars.SafeString("<span class='domain'>" + domain + "</span>");
<ide> }
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
5097256b4b4d554272b815b8158f84a36bd3fc9e
| 0 |
Pranav02/dcos-cassandra-service,arun24816/dcos-cassandra-service,arun24816/dcos-cassandra-service,arun24816/dcos-cassandra-service,niteshjain1/dcos-cassandra-service,akshitjain/dcos-cassandra-service,Pranav02/dcos-cassandra-service,niteshjain1/dcos-cassandra-service,Pranav02/dcos-cassandra-service,niteshjain1/dcos-cassandra-service,akshitjain/dcos-cassandra-service,niteshjain1/dcos-cassandra-service,akshitjain/dcos-cassandra-service,akshitjain/dcos-cassandra-service,adobe-mds/dcos-cassandra-service,arun24816/dcos-cassandra-service,Pranav02/dcos-cassandra-service,adobe-mds/dcos-cassandra-service,adobe-mds/dcos-cassandra-service,adobe-mds/dcos-cassandra-service,adobe-mds/dcos-cassandra-service,arun24816/dcos-cassandra-service,Pranav02/dcos-cassandra-service,niteshjain1/dcos-cassandra-service,akshitjain/dcos-cassandra-service
|
package com.mesosphere.dcos.cassandra.scheduler.mds.resources;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.mesos.config.ConfigStoreException;
import org.apache.mesos.dcos.Capabilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.exceptions.NoHostAvailableException;
import com.datastax.driver.core.exceptions.QueryExecutionException;
import com.datastax.driver.core.exceptions.QueryValidationException;
import com.mesosphere.dcos.cassandra.common.config.ConfigurationManager;
import com.mesosphere.dcos.cassandra.common.tasks.CassandraState;
import com.mesosphere.dcos.cassandra.scheduler.resources.ConnectionResource;
@Path("/v1/itest")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class MdsItestManageResource {
private static final Logger LOGGER = LoggerFactory.getLogger(MdsItestManageResource.class);
private final ConfigurationManager configurationManager;
private final Capabilities capabilities;
private final CassandraState state;
@Inject
public MdsItestManageResource(Capabilities capabilities, CassandraState state,
ConfigurationManager configurationManager) {
this.configurationManager = configurationManager;
this.capabilities = capabilities;
this.state = state;
}
@PUT
@Path("/keyspace/{keyspace}")
public Response alterKeyspace(@PathParam("keyspace") final String keyspace,
AlterSystemAuthRequest alterSysteAuthRequest) throws ConfigStoreException {
try (Session session = getSession(alterSysteAuthRequest.getCassandraAuth())) {
// session = getSession(alterSysteAuthRequest.getCassandraAuth());
String dcRf = MdsCassandraUtills
.getDataCenterVsReplicationFactorString(alterSysteAuthRequest.getDataCenterVsReplicationFactor());
String query = "ALTER KEYSPACE " + keyspace + " WITH REPLICATION = {'class' : 'NetworkTopologyStrategy', "
+ dcRf + "};";
LOGGER.info("Alter keyspace1 query:" + query);
session.execute(query);
} catch (NoHostAvailableException e) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity(e.getMessage()).build();
} catch (QueryExecutionException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
} catch (QueryValidationException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch (Exception e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
return Response.status(Response.Status.OK).entity("Successfull").build();
}
private Session getSession(CassandraAuth cassandraAuth) throws ConfigStoreException {
final ConnectionResource connectionResource = new ConnectionResource(capabilities, state, configurationManager);
List<String> connectedNodes = connectionResource.connectAddress();
String conectionInfo = connectedNodes.get(0);
String[] hostAndPort = conectionInfo.split(":");
LOGGER.debug("connected node:" + hostAndPort);
InetSocketAddress addresses = new InetSocketAddress(hostAndPort[0], Integer.parseInt(hostAndPort[1]));
Cluster cluster = Cluster.builder().addContactPointsWithPorts(addresses)
.withCredentials(cassandraAuth.getUsername(), cassandraAuth.getPassword()).build();
Session session = cluster.connect();
return session;
}
}
|
cassandra-scheduler/src/main/java/com/mesosphere/dcos/cassandra/scheduler/mds/resources/MdsItestManageResource.java
|
package com.mesosphere.dcos.cassandra.scheduler.mds.resources;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.mesos.config.ConfigStoreException;
import org.apache.mesos.dcos.Capabilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.mesosphere.dcos.cassandra.common.config.ConfigurationManager;
import com.mesosphere.dcos.cassandra.common.tasks.CassandraState;
import com.mesosphere.dcos.cassandra.scheduler.resources.ConnectionResource;
@Path("/v1/itest")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class MdsItestManageResource {
private static final Logger LOGGER = LoggerFactory.getLogger(MdsItestManageResource.class);
private final ConfigurationManager configurationManager;
private final Capabilities capabilities;
private final CassandraState state;
@Inject
public MdsItestManageResource(Capabilities capabilities, CassandraState state,
ConfigurationManager configurationManager) {
this.configurationManager = configurationManager;
this.capabilities = capabilities;
this.state = state;
}
@PUT
@Path("/keyspace/{keyspace}/{replicationFactor}")
public Response alterKeyspace(@PathParam("keyspace") final String keyspace,
@PathParam("replicationFactor") final String replicationFactor, CassandraAuth cassandraAuth)
throws ConfigStoreException {
try (Session session = getSession(cassandraAuth)) {
// session = getSession(alterSysteAuthRequest.getCassandraAuth());
String query = "ALTER KEYSPACE " + keyspace
+ " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': " + replicationFactor
+ "};";
LOGGER.info("Alter keyspace query:" + query);
session.execute(query);
} catch (Exception e) {
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
}
return Response.status(Response.Status.OK).entity("Successfull").build();
}
private Session getSession(CassandraAuth cassandraAuth) throws ConfigStoreException {
final ConnectionResource connectionResource = new ConnectionResource(capabilities, state, configurationManager);
List<String> connectedNodes = connectionResource.connectAddress();
String conectionInfo = connectedNodes.get(0);
String[] hostAndPort = conectionInfo.split(":");
LOGGER.debug("connected node:" + hostAndPort);
InetSocketAddress addresses = new InetSocketAddress(hostAndPort[0], Integer.parseInt(hostAndPort[1]));
Cluster cluster = Cluster.builder().addContactPointsWithPorts(addresses)
.withCredentials(cassandraAuth.getUsername(), cassandraAuth.getPassword()).build();
Session session = cluster.connect();
return session;
}
}
|
Changed alter keyspace to networkStrategy
|
cassandra-scheduler/src/main/java/com/mesosphere/dcos/cassandra/scheduler/mds/resources/MdsItestManageResource.java
|
Changed alter keyspace to networkStrategy
|
<ide><path>assandra-scheduler/src/main/java/com/mesosphere/dcos/cassandra/scheduler/mds/resources/MdsItestManageResource.java
<ide>
<ide> import com.datastax.driver.core.Cluster;
<ide> import com.datastax.driver.core.Session;
<add>import com.datastax.driver.core.exceptions.NoHostAvailableException;
<add>import com.datastax.driver.core.exceptions.QueryExecutionException;
<add>import com.datastax.driver.core.exceptions.QueryValidationException;
<ide> import com.mesosphere.dcos.cassandra.common.config.ConfigurationManager;
<ide> import com.mesosphere.dcos.cassandra.common.tasks.CassandraState;
<ide> import com.mesosphere.dcos.cassandra.scheduler.resources.ConnectionResource;
<ide> }
<ide>
<ide> @PUT
<del> @Path("/keyspace/{keyspace}/{replicationFactor}")
<add> @Path("/keyspace/{keyspace}")
<ide> public Response alterKeyspace(@PathParam("keyspace") final String keyspace,
<del> @PathParam("replicationFactor") final String replicationFactor, CassandraAuth cassandraAuth)
<del> throws ConfigStoreException {
<add> AlterSystemAuthRequest alterSysteAuthRequest) throws ConfigStoreException {
<ide>
<del> try (Session session = getSession(cassandraAuth)) {
<del>
<add> try (Session session = getSession(alterSysteAuthRequest.getCassandraAuth())) {
<ide> // session = getSession(alterSysteAuthRequest.getCassandraAuth());
<del>
<del> String query = "ALTER KEYSPACE " + keyspace
<del> + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': " + replicationFactor
<del> + "};";
<del> LOGGER.info("Alter keyspace query:" + query);
<add> String dcRf = MdsCassandraUtills
<add> .getDataCenterVsReplicationFactorString(alterSysteAuthRequest.getDataCenterVsReplicationFactor());
<add> String query = "ALTER KEYSPACE " + keyspace + " WITH REPLICATION = {'class' : 'NetworkTopologyStrategy', "
<add> + dcRf + "};";
<add> LOGGER.info("Alter keyspace1 query:" + query);
<ide>
<ide> session.execute(query);
<add> } catch (NoHostAvailableException e) {
<add> return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity(e.getMessage()).build();
<add> } catch (QueryExecutionException e) {
<add> return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
<add> } catch (QueryValidationException e) {
<add> return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
<ide> } catch (Exception e) {
<del> return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
<add> return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
<ide> }
<ide>
<ide> return Response.status(Response.Status.OK).entity("Successfull").build();
|
|
Java
|
apache-2.0
|
79f8b707473a47b7a6988d7bd728a210f1e2be9b
| 0 |
onepf/OPFPush
|
/*******************************************************************************
* Copyright 2014 One Platform Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.onepf.openpush.sample;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.onepf.openpush.BroadcastListener;
import org.onepf.openpush.OpenPushBaseReceiver;
import org.onepf.openpush.OpenPushHelper;
import org.onepf.openpush.Options;
import org.onepf.openpush.gcm.GCMProvider;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
/**
* @author Anton Rutkevich, Alexey Vitenko
* @since 14.05.14
*/
public class PushSampleActivity extends ActionBarActivity {
private static final String TAG = "PushSampleActivity";
public static final String GCM_SENDER_ID = "76325631570";
@InjectView(R.id.label_registration_id)
TextView tvLabelRegistrationId;
@InjectView(R.id.tv_registration_id)
TextView tvRegistrationId;
@InjectView(R.id.tv_registration_status)
TextView tvRegistrationStatus;
@InjectView(R.id.tv_push_provider)
TextView tvProviderName;
@InjectView(R.id.btn_register)
Button btnRegister;
@InjectView(R.id.btn_copy_to_clipboard)
Button btnCopyToClipboard;
private BroadcastReceiver mOpenPushReceiver;
private static OpenPushHelper mOpenPushHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mOpenPushHelper == null) {
mOpenPushHelper = OpenPushHelper.getInstance(PushSampleActivity.this);
Options.Builder builder = new Options.Builder();
builder.addProvider(new GCMProvider(PushSampleActivity.this, GCM_SENDER_ID));
mOpenPushHelper.init(builder.build());
mOpenPushHelper.setListener(new BroadcastListener(this));
}
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
if (mOpenPushHelper.getState() == OpenPushHelper.STATE_RUNNING) {
switchToRegisteredState(mOpenPushHelper.getCurrentProviderName(),
mOpenPushHelper.getCurrentProviderRegistrationId());
}
}
@Override
protected void onResume() {
super.onResume();
if (mOpenPushReceiver == null) {
registerReceiver();
}
}
@Override
protected void onPause() {
super.onPause();
if (mOpenPushReceiver != null) {
unregisterReceiver(mOpenPushReceiver);
}
}
private void registerReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(BroadcastListener.ACTION_REGISTERED);
filter.addAction(BroadcastListener.ACTION_UNREGISTERED);
filter.addAction(BroadcastListener.ACTION_MESSAGE);
filter.addAction(BroadcastListener.ACTION_ERROR);
filter.addAction(BroadcastListener.ACTION_NO_AVAILABLE_PROVIDER);
filter.addAction(BroadcastListener.ACTION_DELETED_MESSAGES);
filter.addAction(BroadcastListener.ACTION_HOST_APP_REMOVED);
mOpenPushReceiver = new OpenPushEventReceiver();
registerReceiver(mOpenPushReceiver, filter);
}
@OnClick(R.id.btn_register)
void onRegisterClick() {
if (mOpenPushHelper.getState() == OpenPushHelper.STATE_RUNNING) {
mOpenPushHelper.unregister();
} else if (mOpenPushHelper.getState()
== OpenPushHelper.STATE_NONE) {
mOpenPushHelper.register();
}
}
@OnClick(R.id.btn_copy_to_clipboard)
void setBtnCopyToClipboard() {
Toast.makeText(PushSampleActivity.this,
PushSampleActivity.this.getString(R.string.toast_registration_id_copied),
Toast.LENGTH_LONG)
.show();
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(
ClipData.newPlainText("Push registration token", tvRegistrationId.getText())
);
Log.i(TAG, "Registration id: " + tvRegistrationId.getText());
}
private void switchToRegisteredState(String providerName, String registrationId) {
tvRegistrationId.setVisibility(View.VISIBLE);
tvRegistrationId.setText(registrationId);
tvLabelRegistrationId.setVisibility(View.VISIBLE);
tvProviderName.setText(providerName);
btnRegister.setText(R.string.btn_unregister);
btnCopyToClipboard.setVisibility(View.VISIBLE);
tvRegistrationStatus.setText(getString(R.string.registered));
}
private void switchToUnregisteredState() {
mOpenPushReceiver = null;
tvRegistrationId.setVisibility(View.GONE);
tvRegistrationId.setText(null);
tvLabelRegistrationId.setVisibility(View.GONE);
tvProviderName.setText("None");
btnRegister.setText(R.string.btn_register);
btnCopyToClipboard.setVisibility(View.GONE);
tvRegistrationStatus.setText(getString(R.string.not_registered));
}
public class OpenPushEventReceiver extends OpenPushBaseReceiver {
public OpenPushEventReceiver() {
}
@Override
public void onRegistered(@NotNull String providerName, @Nullable String registrationId) {
switchToRegisteredState(providerName, registrationId);
}
@Override
public void onUnregistered(@NotNull String providerName, @Nullable String registrationId) {
switchToUnregisteredState();
}
}
}
|
sample/src/main/java/org/onepf/openpush/sample/PushSampleActivity.java
|
/*******************************************************************************
* Copyright 2014 One Platform Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.onepf.openpush.sample;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.onepf.openpush.BroadcastListener;
import org.onepf.openpush.OpenPushBaseReceiver;
import org.onepf.openpush.OpenPushHelper;
import org.onepf.openpush.Options;
import org.onepf.openpush.gcm.GCMProvider;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
/**
* @author Anton Rutkevich, Alexey Vitenko
* @since 14.05.14
*/
public class PushSampleActivity extends ActionBarActivity {
private static final String TAG = "PushSampleActivity";
public static final String GCM_SENDER_ID = "76325631570";
@InjectView(R.id.label_registration_id)
TextView tvLabelRegistrationId;
@InjectView(R.id.tv_registration_id)
TextView tvRegistrationId;
@InjectView(R.id.tv_registration_status)
TextView tvRegistrationStatus;
@InjectView(R.id.tv_push_provider)
TextView tvProviderName;
@InjectView(R.id.btn_register)
Button btnRegister;
@InjectView(R.id.btn_copy_to_clipboard)
Button btnCopyToClipboard;
private BroadcastReceiver mOpenPushReceiver;
private static OpenPushHelper mOpenPushHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mOpenPushHelper == null) {
mOpenPushHelper = OpenPushHelper.getInstance(PushSampleActivity.this);
Options.Builder builder = new Options.Builder();
builder.addProvider(new GCMProvider(PushSampleActivity.this, GCM_SENDER_ID));
mOpenPushHelper.init(builder.build());
mOpenPushHelper.setListener(new BroadcastListener(this));
}
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
if (mOpenPushHelper.getState() == OpenPushHelper.STATE_RUNNING) {
switchToRegisteredState(mOpenPushHelper.getCurrentProviderName(),
mOpenPushHelper.getCurrentProviderRegistrationId());
}
}
@Override
protected void onResume() {
super.onResume();
if (mOpenPushReceiver == null) {
registerReceiver();
}
}
@Override
protected void onPause() {
super.onPause();
if (mOpenPushReceiver != null) {
unregisterReceiver(mOpenPushReceiver);
}
}
private void registerReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(BroadcastListener.ACTION_REGISTERED);
filter.addAction(BroadcastListener.ACTION_UNREGISTERED);
filter.addAction(BroadcastListener.ACTION_MESSAGE);
filter.addAction(BroadcastListener.ACTION_ERROR);
filter.addAction(BroadcastListener.ACTION_NO_AVAILABLE_PROVIDER);
filter.addAction(BroadcastListener.ACTION_DELETED_MESSAGES);
filter.addAction(BroadcastListener.ACTION_HOST_APP_REMOVED);
mOpenPushReceiver = new OpenPushEventReceiver();
registerReceiver(mOpenPushReceiver, filter);
}
@OnClick(R.id.btn_register)
void onRegisterClick() {
if (mOpenPushHelper.getState() == OpenPushHelper.STATE_RUNNING) {
mOpenPushHelper.unregister();
} else if (mOpenPushHelper.getState()
== OpenPushHelper.STATE_NONE) {
mOpenPushHelper.register();
}
}
@OnClick(R.id.btn_copy_to_clipboard)
void setBtnCopyToClipboard() {
Toast.makeText(PushSampleActivity.this,
PushSampleActivity.this.getString(R.string.toast_registration_id_copied),
Toast.LENGTH_LONG)
.show();
ClipboardManager clipboard
= (ClipboardManager) getSystemService(Activity.CLIPBOARD_SERVICE);
clipboard.setText(tvRegistrationId.getText());
Log.i(TAG, "Registration id: " + tvRegistrationId.getText());
}
private void switchToRegisteredState(String providerName, String registrationId) {
tvRegistrationId.setVisibility(View.VISIBLE);
tvRegistrationId.setText(providerName);
tvLabelRegistrationId.setVisibility(View.VISIBLE);
tvProviderName.setText(registrationId);
btnRegister.setText(R.string.btn_unregister);
btnCopyToClipboard.setVisibility(View.VISIBLE);
tvRegistrationStatus.setText(getString(R.string.registered));
}
private void switchToUnregisteredState() {
mOpenPushReceiver = null;
tvRegistrationId.setVisibility(View.GONE);
tvRegistrationId.setText(null);
tvLabelRegistrationId.setVisibility(View.GONE);
tvProviderName.setText("None");
btnRegister.setText(R.string.btn_register);
btnCopyToClipboard.setVisibility(View.GONE);
tvRegistrationStatus.setText(getString(R.string.not_registered));
}
public class OpenPushEventReceiver extends OpenPushBaseReceiver {
public OpenPushEventReceiver() {
}
@Override
public void onRegistered(@NotNull String providerName, @Nullable String registrationId) {
switchToRegisteredState(providerName, registrationId);
}
@Override
public void onUnregistered(@NotNull String providerName, @Nullable String registrationId) {
switchToUnregisteredState();
}
}
}
|
Update clipboard in sample.
|
sample/src/main/java/org/onepf/openpush/sample/PushSampleActivity.java
|
Update clipboard in sample.
|
<ide><path>ample/src/main/java/org/onepf/openpush/sample/PushSampleActivity.java
<ide>
<ide> import android.app.Activity;
<ide> import android.content.BroadcastReceiver;
<add>import android.content.ClipData;
<add>import android.content.ClipDescription;
<add>import android.content.ClipboardManager;
<ide> import android.content.IntentFilter;
<ide> import android.os.Bundle;
<ide> import android.support.v7.app.ActionBarActivity;
<del>import android.text.ClipboardManager;
<ide> import android.util.Log;
<ide> import android.view.View;
<ide> import android.widget.Button;
<ide> Toast.LENGTH_LONG)
<ide> .show();
<ide>
<del> ClipboardManager clipboard
<del> = (ClipboardManager) getSystemService(Activity.CLIPBOARD_SERVICE);
<del> clipboard.setText(tvRegistrationId.getText());
<add> ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
<add> clipboard.setPrimaryClip(
<add> ClipData.newPlainText("Push registration token", tvRegistrationId.getText())
<add> );
<ide>
<ide> Log.i(TAG, "Registration id: " + tvRegistrationId.getText());
<ide> }
<ide>
<ide> private void switchToRegisteredState(String providerName, String registrationId) {
<ide> tvRegistrationId.setVisibility(View.VISIBLE);
<del> tvRegistrationId.setText(providerName);
<add> tvRegistrationId.setText(registrationId);
<ide>
<ide> tvLabelRegistrationId.setVisibility(View.VISIBLE);
<ide>
<del> tvProviderName.setText(registrationId);
<add> tvProviderName.setText(providerName);
<ide>
<ide> btnRegister.setText(R.string.btn_unregister);
<ide>
|
|
JavaScript
|
bsd-3-clause
|
dbdbb9abe8a9ea359fa5e2c485594d02d86c2c80
| 0 |
readium/readium-shared-js,kivuto/readium-shared-js,kivuto/readium-shared-js,ravn-no/readium-shared-js,JoMedia/readium-shared-js,NYPL/readium-shared-js,readium/readium-shared-js,NYPL-Simplified/readium-shared-js,ravn-no/readium-shared-js,NYPL/readium-shared-js,NYPL-Simplified/readium-shared-js
|
// LauncherOSX
//
// Created by Boris Schneiderman.
// Copyright (c) 2014 Readium Foundation and/or its licensees. 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.
// 3. Neither the name of the organization 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 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.
/**
* CFI navigation helper class
*
* @param options Additional settings for NavigationLogic object
* - paginationInfo Layout details, used by clientRect-based geometry
* - visibleContentOffsets Function that returns offsets. If supplied it is used instead of the inferred offsets
* - frameDimensions Function that returns an object with width and height properties. Needs to be set.
* - $iframe Iframe reference, and needs to be set.
* @constructor
*/
define(["jquery", "underscore", "../helpers", 'readium_cfi_js'], function($, _, Helpers, epubCfi) {
var CfiNavigationLogic = function(options) {
var self = this;
options = options || {};
var debugMode = ReadiumSDK.DEBUG_MODE;
this.getRootElement = function(){
return options.$iframe[0].contentDocument.documentElement;
};
this.getRootDocument = function () {
return options.$iframe[0].contentDocument;
};
function createRange() {
return self.getRootDocument().createRange();
}
function getNodeClientRect(node) {
var range = createRange();
range.selectNode(node);
return normalizeRectangle(range.getBoundingClientRect(),0,0);
}
function getNodeContentsClientRect(node) {
var range = createRange();
range.selectNodeContents(node);
return normalizeRectangle(range.getBoundingClientRect(),0,0);
}
function getElementClientRect($element) {
return normalizeRectangle($element[0].getBoundingClientRect(),0,0);
}
function getNodeRangeClientRect(startNode, startOffset, endNode, endOffset) {
var range = createRange();
range.setStart(startNode, startOffset ? startOffset : 0);
if (endNode.nodeType === Node.ELEMENT_NODE) {
range.setEnd(endNode, endOffset ? endOffset : endNode.childNodes.length);
} else if (endNode.nodeType === Node.TEXT_NODE) {
range.setEnd(endNode, endOffset ? endOffset : 0);
}
return normalizeRectangle(range.getBoundingClientRect(),0,0);
}
function getNodeClientRectList(node, visibleContentOffsets) {
visibleContentOffsets = visibleContentOffsets || getVisibleContentOffsets();
var range = createRange();
range.selectNode(node);
return _.map(range.getClientRects(), function (rect) {
return normalizeRectangle(rect, visibleContentOffsets.left, visibleContentOffsets.top);
});
}
function getFrameDimensions() {
if (options.frameDimensions) {
return options.frameDimensions();
}
console.error('CfiNavigationLogic: No frame dimensions specified!');
return null;
}
function getCaretRangeFromPoint(x, y, document) {
document = document || self.getRootDocument();
Helpers.polyfillCaretRangeFromPoint(document); //only polyfills once, no-op afterwards
return document.caretRangeFromPoint(x, y);
}
function isPaginatedView() {
return !!options.paginationInfo;
}
/**
* @private
* Checks whether or not pages are rendered right-to-left
*
* @returns {boolean}
*/
function isPageProgressionRightToLeft() {
return options.paginationInfo && !!options.paginationInfo.rightToLeft;
}
/**
* @private
* Checks whether or not pages are rendered with vertical writing mode
*
* @returns {boolean}
*/
function isVerticalWritingMode() {
return options.paginationInfo && !!options.paginationInfo.isVerticalWritingMode;
}
/**
* @private
* Checks whether or not a (fully adjusted) rectangle is at least partly visible
*
* @param {Object} rect
* @param {Object} [frameDimensions]
* @param {boolean} [isVwm] isVerticalWritingMode
* @returns {boolean}
*/
function isRectVisible(rect, ignorePartiallyVisible, frameDimensions, isVwm) {
frameDimensions = frameDimensions || getFrameDimensions();
isVwm = isVwm || isVerticalWritingMode();
//Text nodes without printable text dont have client rectangles
if (!rect) {
return false;
}
//Sometimes we get client rects that are "empty" and aren't supposed to be visible
if (rect.left == 0 && rect.right == 0 && rect.top == 0 && rect.bottom == 0) {
return false;
}
if (isPaginatedView()) {
return (rect.left >= 0 && rect.left < frameDimensions.width) ||
(!ignorePartiallyVisible && rect.left < 0 && rect.right >= 0);
} else {
return (rect.top >= 0 && rect.top < frameDimensions.height) ||
(!ignorePartiallyVisible && rect.top < 0 && rect.bottom >= 0);
}
}
/**
* @private
* Retrieves _current_ full width of a column (including its gap)
*
* @returns {number} Full width of a column in pixels
*/
function getColumnFullWidth() {
if (!options.paginationInfo || isVerticalWritingMode())
{
return options.$iframe.width();
}
return options.paginationInfo.columnWidth + options.paginationInfo.columnGap;
}
/**
* @private
*
* Retrieves _current_ offset of a viewport
* (related to the beginning of the chapter)
*
* @returns {Object}
*/
function getVisibleContentOffsets() {
if (options.visibleContentOffsets) {
return options.visibleContentOffsets();
}
if (isVerticalWritingMode()) {
return {
top: (options.paginationInfo ? options.paginationInfo.pageOffset : 0),
left: 0
};
}
return {
top: 0,
left: 0
};
}
/**
* New (rectangle-based) algorithm, useful in multi-column layouts
*
* Note: the second param (props) is ignored intentionally
* (no need to use those in normalization)
*
* @param {jQuery} $element
* @param {Object} _props
* @param {boolean} shouldCalculateVisibilityPercentage
* @param {Object} [frameDimensions]
* @returns {number|null}
* 0 for non-visible elements,
* 0 < n <= 100 for visible elements
* (will just give 100, if `shouldCalculateVisibilityPercentage` => false)
* null for elements with display:none
*/
function checkVisibilityByRectangles($element, shouldCalculateVisibilityPercentage, visibleContentOffsets, frameDimensions) {
visibleContentOffsets = visibleContentOffsets || getVisibleContentOffsets();
frameDimensions = frameDimensions || getFrameDimensions();
var elementRectangles = getNormalizedRectangles($element, visibleContentOffsets);
var clientRectangles = elementRectangles.clientRectangles;
if (clientRectangles.length === 0) { // elements with display:none, etc.
return null;
}
var visibilityPercentage = 0;
if (clientRectangles.length === 1) {
var adjustedRect = clientRectangles[0];
if (isPaginatedView()) {
if (adjustedRect.bottom > frameDimensions.height || adjustedRect.top < 0) {
// because of webkit inconsistency, that single rectangle should be adjusted
// until it hits the end OR will be based on the FIRST column that is visible
adjustRectangle(adjustedRect, true, frameDimensions);
}
}
if (isRectVisible(adjustedRect, false, frameDimensions)) {
//it might still be partially visible in webkit
if (shouldCalculateVisibilityPercentage && adjustedRect.top < 0) {
visibilityPercentage =
Math.floor(100 * (adjustedRect.height + adjustedRect.top) / adjustedRect.height);
} else {
visibilityPercentage = 100;
}
}
} else {
// for an element split between several CSS columns,z
// both Firefox and IE produce as many client rectangles;
// each of those should be checked
for (var i = 0, l = clientRectangles.length; i < l; ++i) {
if (isRectVisible(clientRectangles[i], false, frameDimensions)) {
visibilityPercentage = shouldCalculateVisibilityPercentage
? measureVisibilityPercentageByRectangles(clientRectangles, i)
: 100;
break;
}
}
}
return visibilityPercentage;
}
/**
* Finds a page index (0-based) for a specific element.
* Calculations are based on rectangles retrieved with getClientRects() method.
*
* @param {jQuery} $element
* @param {number} spatialVerticalOffset
* @returns {number|null}
*/
function findPageByRectangles($element, spatialVerticalOffset) {
var visibleContentOffsets = getVisibleContentOffsets();
var elementRectangles = getNormalizedRectangles($element, visibleContentOffsets);
var clientRectangles = elementRectangles.clientRectangles;
if (clientRectangles.length === 0) { // elements with display:none, etc.
return null;
}
return calculatePageIndexByRectangles(clientRectangles, spatialVerticalOffset);
}
/**
* @private
* Calculate a page index (0-based) for given client rectangles.
*
* @param {object} clientRectangles
* @param {number} [spatialVerticalOffset]
* @param {object} [frameDimensions]
* @param {object} [columnFullWidth]
* @returns {number|null}
*/
function calculatePageIndexByRectangles(clientRectangles, spatialVerticalOffset, frameDimensions, columnFullWidth) {
var isRtl = isPageProgressionRightToLeft();
var isVwm = isVerticalWritingMode();
columnFullWidth = columnFullWidth || getColumnFullWidth();
frameDimensions = frameDimensions || getFrameDimensions();
if (spatialVerticalOffset) {
trimRectanglesByVertOffset(clientRectangles, spatialVerticalOffset,
frameDimensions, columnFullWidth, isRtl, isVwm);
}
var firstRectangle = _.first(clientRectangles);
if (clientRectangles.length === 1) {
adjustRectangle(firstRectangle, false, frameDimensions, columnFullWidth, isRtl, isVwm);
}
var pageIndex;
if (isVwm) {
var topOffset = firstRectangle.top;
pageIndex = Math.floor(topOffset / frameDimensions.height);
} else {
var leftOffset = firstRectangle.left;
if (isRtl) {
leftOffset = (columnFullWidth * (options.paginationInfo ? options.paginationInfo.visibleColumnCount : 1)) - leftOffset;
}
pageIndex = Math.floor(leftOffset / columnFullWidth);
}
if (pageIndex < 0) {
pageIndex = 0;
}
else if (pageIndex >= (options.paginationInfo ? options.paginationInfo.columnCount : 1)) {
pageIndex = (options.paginationInfo ? (options.paginationInfo.columnCount - 1) : 0);
}
return pageIndex;
}
/**
* Finds a page index (0-based) for a specific client rectangle.
* Calculations are based on viewport dimensions, offsets, and rectangle coordinates
*
* @param {ClientRect} clientRectangle
* @param {Object} [visibleContentOffsets]
* @param {Object} [frameDimensions]
* @returns {number|null}
*/
function findPageBySingleRectangle(clientRectangle, visibleContentOffsets, frameDimensions) {
visibleContentOffsets = visibleContentOffsets || getVisibleContentOffsets();
frameDimensions = frameDimensions || getFrameDimensions();
var normalizedRectangle = normalizeRectangle(
clientRectangle, visibleContentOffsets.left, visibleContentOffsets.top);
return calculatePageIndexByRectangles([normalizedRectangle], frameDimensions);
}
/**
* @private
* Calculates the visibility offset percentage based on ClientRect dimensions
*
* @param {Array} clientRectangles (should already be normalized)
* @param {number} firstVisibleRectIndex
* @returns {number} - visibility percentage (0 < n <= 100)
*/
function measureVisibilityPercentageByRectangles(clientRectangles, firstVisibleRectIndex) {
var heightTotal = 0;
var heightVisible = 0;
if (clientRectangles.length > 1) {
_.each(clientRectangles, function (rect, index) {
heightTotal += rect.height;
if (index >= firstVisibleRectIndex) {
// in this case, all the rectangles after the first visible
// should be counted as visible
heightVisible += rect.height;
}
});
}
else {
// should already be normalized and adjusted
heightTotal = clientRectangles[0].height;
heightVisible = clientRectangles[0].height - Math.max(
0, -clientRectangles[0].top);
}
return heightVisible === heightTotal
? 100 // trivial case: element is 100% visible
: Math.floor(100 * heightVisible / heightTotal);
}
/**
* @private
* Retrieves the position of $element in multi-column layout
*
* @param {jQuery} $el
* @param {Object} [visibleContentOffsets]
* @returns {Object}
*/
function getNormalizedRectangles($el, visibleContentOffsets) {
visibleContentOffsets = visibleContentOffsets || {};
var leftOffset = visibleContentOffsets.left || 0;
var topOffset = visibleContentOffsets.top || 0;
// union of all rectangles wrapping the element
var wrapperRectangle = normalizeRectangle(
$el[0].getBoundingClientRect(), leftOffset, topOffset);
// all the separate rectangles (for detecting position of the element
// split between several columns)
var clientRectangles = [];
var clientRectList = $el[0].getClientRects();
for (var i = 0, l = clientRectList.length; i < l; ++i) {
if (clientRectList[i].height > 0) {
// Firefox sometimes gets it wrong,
// adding literally empty (height = 0) client rectangle preceding the real one,
// that empty client rectanle shouldn't be retrieved
clientRectangles.push(
normalizeRectangle(clientRectList[i], leftOffset, topOffset));
}
}
if (clientRectangles.length === 0) {
// sometimes an element is either hidden or empty, and that means
// Webkit-based browsers fail to assign proper clientRects to it
// in this case we need to go for its sibling (if it exists)
$el = $el.next();
if ($el.length) {
return getNormalizedRectangles($el, visibleContentOffsets);
}
}
return {
wrapperRectangle: wrapperRectangle,
clientRectangles: clientRectangles
};
}
/**
* @private
* Converts TextRectangle object into a plain object,
* taking content offsets (=scrolls, position shifts etc.) into account
*
* @param {TextRectangle} textRect
* @param {number} leftOffset
* @param {number} topOffset
* @returns {Object}
*/
function normalizeRectangle(textRect, leftOffset, topOffset) {
var plainRectObject = {
left: textRect.left,
right: textRect.right,
top: textRect.top,
bottom: textRect.bottom,
width: textRect.right - textRect.left,
height: textRect.bottom - textRect.top
};
offsetRectangle(plainRectObject, leftOffset, topOffset);
return plainRectObject;
}
/**
* @private
* Offsets plain object (which represents a TextRectangle).
*
* @param {Object} rect
* @param {number} leftOffset
* @param {number} topOffset
*/
function offsetRectangle(rect, leftOffset, topOffset) {
rect.left += leftOffset;
rect.right += leftOffset;
rect.top += topOffset;
rect.bottom += topOffset;
}
/**
* @private
*
* When element is spilled over two or more columns,
* most of the time Webkit-based browsers
* still assign a single clientRectangle to it, setting its `top` property to negative value
* (so it looks like it's rendered based on the second column)
* Alas, sometimes they decide to continue the leftmost column - from _below_ its real height.
* In this case, `bottom` property is actually greater than element's height and had to be adjusted accordingly.
*
* Ugh.
*
* @param {Object} rect
* @param {boolean} [shouldLookForFirstVisibleColumn]
* If set, there'll be two-phase adjustment
* (to align a rectangle with a viewport)
* @param {Object} [frameDimensions]
* @param {number} [columnFullWidth]
* @param {boolean} [isRtl]
* @param {boolean} [isVwm] isVerticalWritingMode
*/
function adjustRectangle(rect, shouldLookForFirstVisibleColumn, frameDimensions, columnFullWidth, isRtl, isVwm) {
frameDimensions = frameDimensions || getFrameDimensions();
columnFullWidth = columnFullWidth || getColumnFullWidth();
isRtl = isRtl || isPageProgressionRightToLeft();
isVwm = isVwm || isVerticalWritingMode();
// Rectangle adjustment is not needed in VWM since it does not deal with columns
if (isVwm) {
return;
}
if (isRtl) {
columnFullWidth *= -1; // horizontal shifts are reverted in RTL mode
}
// first we go left/right (rebasing onto the very first column available)
while (rect.top < 0) {
offsetRectangle(rect, -columnFullWidth, frameDimensions.height);
}
// ... then, if necessary (for visibility offset checks),
// each column is tried again (now in reverse order)
// the loop will be stopped when the column is aligned with a viewport
// (i.e., is the first visible one).
if (shouldLookForFirstVisibleColumn) {
while (rect.bottom >= frameDimensions.height) {
if (isRectVisible(rect, false, frameDimensions, isVwm)) {
break;
}
offsetRectangle(rect, columnFullWidth, -frameDimensions.height);
}
}
}
/**
* @private
* Trims the rectangle(s) representing the given element.
*
* @param {Array} rects
* @param {number} verticalOffset
* @param {number} frameDimensions
* @param {number} columnFullWidth
* @param {boolean} isRtl
* @param {boolean} isVwm isVerticalWritingMode
*/
function trimRectanglesByVertOffset(
rects, verticalOffset, frameDimensions, columnFullWidth, isRtl, isVwm) {
frameDimensions = frameDimensions || getFrameDimensions();
columnFullWidth = columnFullWidth || getColumnFullWidth();
isRtl = isRtl || isPageProgressionRightToLeft();
isVwm = isVwm || isVerticalWritingMode();
//TODO: Support vertical writing mode
if (isVwm) {
return;
}
var totalHeight = _.reduce(rects, function(prev, cur) {
return prev + cur.height;
}, 0);
var heightToHide = totalHeight * verticalOffset / 100;
if (rects.length > 1) {
var heightAccum = 0;
do {
heightAccum += rects[0].height;
if (heightAccum > heightToHide) {
break;
}
rects.shift();
} while (rects.length > 1);
}
else {
// rebase to the last possible column
// (so that adding to top will be properly processed later)
if (isRtl) {
columnFullWidth *= -1;
}
while (rects[0].bottom >= frameDimensions.height) {
offsetRectangle(rects[0], columnFullWidth, -frameDimensions.height);
}
rects[0].top += heightToHide;
rects[0].height -= heightToHide;
}
}
this.getCfiForElement = function (element) {
var cfi = EPUBcfi.Generator.generateElementCFIComponent(element,
["cfi-marker"],
[],
["MathJax_Message", "MathJax_SVG_Hidden"]);
if (cfi[0] == "!") {
cfi = cfi.substring(1);
}
return cfi;
};
//TODO JC: Can now use getFirstVisibleCfi instead, use that instead of this at top levels
this.getFirstVisibleElementCfi = function (topOffset) {
return self.getFirstVisibleCfi();
};
this.getVisibleCfiFromPoint = function (x, y, precisePoint) {
var document = self.getRootDocument();
var firstVisibleCaretRange = getCaretRangeFromPoint(x, y, document);
var elementFromPoint = document.elementFromPoint(x, y);
var invalidElementFromPoint = !elementFromPoint || elementFromPoint === document.documentElement;
if (precisePoint) {
if (!elementFromPoint || invalidElementFromPoint) {
return null;
}
var testRect = getNodeContentsClientRect(elementFromPoint);
if (!isRectVisible(testRect, false)) {
return null;
}
if ((x < testRect.left || x > testRect.right) || (y < testRect.top || y > testRect.bottom)) {
return null;
}
}
if (!firstVisibleCaretRange) {
if (invalidElementFromPoint) {
console.error("Could not generate CFI no visible element on page");
return null;
}
firstVisibleCaretRange = createRange();
firstVisibleCaretRange.selectNode(elementFromPoint);
}
var range = firstVisibleCaretRange;
var cfi;
//if we get a text node we need to get an approximate range for the first visible character offsets.
var node = range.startContainer;
var startOffset, endOffset;
if (node.nodeType === Node.TEXT_NODE) {
if (precisePoint && node.parentNode !== elementFromPoint) {
return null;
}
if (node.length === 1 && range.startOffset === 1) {
startOffset = 0;
endOffset = 1;
} else if (range.startOffset === node.length) {
startOffset = range.startOffset - 1;
endOffset = range.startOffset;
} else {
startOffset = range.startOffset;
endOffset = range.startOffset + 1;
}
var wrappedRange = {
startContainer: node,
endContainer: node,
startOffset: startOffset,
endOffset: endOffset,
commonAncestorContainer: range.commonAncestorContainer
};
if (debugMode) {
drawDebugOverlayFromDomRange(wrappedRange);
}
cfi = generateCfiFromDomRange(wrappedRange);
} else if (node.nodeType === Node.ELEMENT_NODE) {
node =
range.startContainer.childNodes[range.startOffset] ||
range.startContainer.childNodes[0] ||
range.startContainer;
if (precisePoint && node !== elementFromPoint) {
return null;
}
if (node.nodeType !== Node.ELEMENT_NODE) {
cfi = generateCfiFromDomRange(range);
} else {
cfi = self.getCfiForElement(node);
}
} else {
if (precisePoint && node !== elementFromPoint) {
return null;
}
cfi = self.getCfiForElement(elementFromPoint);
}
//This should not happen but if it does print some output, just in case
if (cfi && cfi.indexOf('NaN') !== -1) {
console.log('Did not generate a valid CFI:' + cfi);
return undefined;
}
return cfi;
};
this.getRangeCfiFromPoints = function(startX, startY, endX, endY) {
var document = self.getRootDocument();
var start = getCaretRangeFromPoint(startX, startY, document),
end = getCaretRangeFromPoint(endX, endY, document),
range = createRange();
range.setStart(start.startContainer, start.startOffset);
range.setEnd(end.startContainer, end.startOffset);
// if we're looking at a text node create a nice range (n, n+1)
if (start.startContainer === start.endContainer && start.startContainer.nodeType === Node.TEXT_NODE && end.startContainer.length > end.startOffset+1) {
range.setEnd(end.startContainer, end.startOffset+1);
}
return generateCfiFromDomRange(range);
};
function getTextNodeRectCornerPairs(rect) {
//
// top left top right
// ╲ ╱
// ── ▒T▒E▒X▒T▒ ▒R▒E▒C▒T▒ ──
//
// top left corner & top right corner
// but for y coord use the mid point between top and bottom
if (isVerticalWritingMode()) {
var x = rect.right - (rect.width / 2);
return [{x: x, y: rect.top}, {x: x, y: rect.bottom}];
} else {
var y = rect.top + (rect.height / 2);
var result = [{x: rect.left, y: y}, {x: rect.right, y: y}]
return isPageProgressionRightToLeft() ? result.reverse() : result;
}
}
var DEBUG = false;
function getVisibleTextRangeOffsetsSelectedByFunc(textNode, pickerFunc, visibleContentOffsets, frameDimensions) {
visibleContentOffsets = visibleContentOffsets || getVisibleContentOffsets();
var textNodeFragments = getNodeClientRectList(textNode, visibleContentOffsets);
var visibleFragments = _.filter(textNodeFragments, function (rect) {
return isRectVisible(rect, false, frameDimensions);
});
var fragment = pickerFunc(visibleFragments);
if (!fragment) {
//no visible fragment, empty text node?
return null;
}
var fragmentCorner = pickerFunc(getTextNodeRectCornerPairs(fragment));
// Reverse taking into account of visible content offsets
fragmentCorner.x -= visibleContentOffsets.left;
fragmentCorner.y -= visibleContentOffsets.top;
var caretRange = getCaretRangeFromPoint(fragmentCorner.x, fragmentCorner.y);
if (DEBUG)
console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'a0');
// Desperately try to find it from all angles! Darn sub pixeling..
//TODO: remove the need for this brute-force method, since it's making the result non-deterministic
if (!caretRange || caretRange.startContainer !== textNode) {
caretRange = getCaretRangeFromPoint(fragmentCorner.x - 1, fragmentCorner.y);
if (DEBUG)
console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'a1');
}
if (!caretRange || caretRange.startContainer !== textNode) {
caretRange = getCaretRangeFromPoint(fragmentCorner.x, fragmentCorner.y - 1);
if (DEBUG)
console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'a2');
}
if (!caretRange || caretRange.startContainer !== textNode) {
caretRange = getCaretRangeFromPoint(fragmentCorner.x - 1, fragmentCorner.y - 1);
if (DEBUG)
console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'a3');
}
if (!caretRange || caretRange.startContainer !== textNode) {
fragmentCorner.x = Math.floor(fragmentCorner.x);
fragmentCorner.y = Math.floor(fragmentCorner.y);
caretRange = getCaretRangeFromPoint(fragmentCorner.x, fragmentCorner.y);
if (DEBUG)
console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'b0');
}
// Desperately try to find it from all angles! Darn sub pixeling..
if (!caretRange || caretRange.startContainer !== textNode) {
caretRange = getCaretRangeFromPoint(fragmentCorner.x - 1, fragmentCorner.y);
if (DEBUG)
console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'b1');
}
if (!caretRange || caretRange.startContainer !== textNode) {
caretRange = getCaretRangeFromPoint(fragmentCorner.x, fragmentCorner.y - 1);
if (DEBUG)
console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'b2');
}
if (!caretRange || caretRange.startContainer !== textNode) {
caretRange = getCaretRangeFromPoint(fragmentCorner.x - 1, fragmentCorner.y - 1);
if (DEBUG)
console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'b3');
}
// Still nothing? fall through..
if (!caretRange) {
if (DEBUG)
console.warn('getVisibleTextRangeOffsetsSelectedByFunc: no caret range result');
return null;
}
if (caretRange.startContainer === textNode) {
return pickerFunc(
[{start: caretRange.startOffset, end: caretRange.startOffset + 1},
{start: caretRange.startOffset - 1, end: caretRange.startOffset}]
);
} else {
if (DEBUG)
console.warn('getVisibleTextRangeOffsetsSelectedByFunc: incorrect caret range result');
return null;
}
}
function findVisibleLeafNodeCfi(leafNodeList, pickerFunc, targetLeafNode, visibleContentOffsets, frameDimensions) {
var index = 0;
if (!targetLeafNode) {
index = leafNodeList.indexOf(pickerFunc(leafNodeList))
} else {
index = leafNodeList.indexOf(targetLeafNode);
if (index === -1) {
//target leaf node not the right type? not in list?
return null;
}
// use the next leaf node in the list
index += pickerFunc([1, -1]);
}
var visibleLeafNode = leafNodeList[index];
if (!visibleLeafNode) {
return null;
}
var element = visibleLeafNode.element;
var textNode = visibleLeafNode.textNode;
//if a valid text node is found, try to generate a CFI with range offsets
if (textNode && isValidTextNode(textNode)) {
var visibleRange = getVisibleTextRangeOffsetsSelectedByFunc(textNode, pickerFunc, visibleContentOffsets, frameDimensions);
if (!visibleRange) {
//the text node is valid, but not visible..
//let's try again with the next node in the list
return findVisibleLeafNodeCfi(leafNodeList, pickerFunc, visibleLeafNode, visibleContentOffsets, frameDimensions);
}
var range = createRange();
range.setStart(textNode, visibleRange.start);
range.setEnd(textNode, visibleRange.end);
return generateCfiFromDomRange(range);
} else {
//if not then generate a CFI for the element
return self.getCfiForElement(element);
}
}
// get an array of visible text elements and then select one based on the func supplied
// and generate a CFI for the first visible text subrange.
function getVisibleTextRangeCfiForTextElementSelectedByFunc(pickerFunc, visibleContentOffsets, frameDimensions) {
var visibleLeafNodeList = self.getVisibleLeafNodes(visibleContentOffsets, frameDimensions);
return findVisibleLeafNodeCfi(visibleLeafNodeList, pickerFunc, null, visibleContentOffsets, frameDimensions);
}
function getLastVisibleTextRangeCfi(visibleContentOffsets, frameDimensions) {
return getVisibleTextRangeCfiForTextElementSelectedByFunc(_.last, visibleContentOffsets, frameDimensions);
}
function getFirstVisibleTextRangeCfi(visibleContentOffsets, frameDimensions) {
return getVisibleTextRangeCfiForTextElementSelectedByFunc(_.first, visibleContentOffsets, frameDimensions);
}
this.getFirstVisibleCfi = function (visibleContentOffsets, frameDimensions) {
return getFirstVisibleTextRangeCfi(visibleContentOffsets, frameDimensions);
};
this.getLastVisibleCfi = function (visibleContentOffsets, frameDimensions) {
return getLastVisibleTextRangeCfi(visibleContentOffsets, frameDimensions);
};
function generateCfiFromDomRange(range) {
return EPUBcfi.generateRangeComponent(
range.startContainer, range.startOffset,
range.endContainer, range.endOffset,
['cfi-marker'], [], ["MathJax_Message", "MathJax_SVG_Hidden"]);
}
function getRangeTargetNodes(rangeCfi) {
return EPUBcfi.getRangeTargetElements(
getWrappedCfiRelativeToContent(rangeCfi),
self.getRootDocument(),
['cfi-marker'], [], ["MathJax_Message", "MathJax_SVG_Hidden"]);
}
this.getDomRangeFromRangeCfi = function(rangeCfi, rangeCfi2, inclusive) {
var range = createRange();
if (!rangeCfi2) {
if (self.isRangeCfi(rangeCfi)) {
var rangeInfo = getRangeTargetNodes(rangeCfi);
range.setStart(rangeInfo.startElement, rangeInfo.startOffset);
range.setEnd(rangeInfo.endElement, rangeInfo.endOffset);
} else {
var element = self.getElementByCfi(rangeCfi,
['cfi-marker'], [], ["MathJax_Message", "MathJax_SVG_Hidden"])[0];
range.selectNode(element);
}
} else {
if (self.isRangeCfi(rangeCfi)) {
var rangeInfo1 = getRangeTargetNodes(rangeCfi);
range.setStart(rangeInfo1.startElement, rangeInfo1.startOffset);
} else {
var startElement = self.getElementByCfi(rangeCfi,
['cfi-marker'], [], ["MathJax_Message", "MathJax_SVG_Hidden"])[0];
range.setStart(startElement, 0);
}
if (self.isRangeCfi(rangeCfi2)) {
var rangeInfo2 = getRangeTargetNodes(rangeCfi2);
if (inclusive) {
range.setEnd(rangeInfo2.endElement, rangeInfo2.endOffset);
} else {
range.setEnd(rangeInfo2.startElement, rangeInfo2.startOffset);
}
} else {
var endElement = self.getElementByCfi(rangeCfi2,
['cfi-marker'], [], ["MathJax_Message", "MathJax_SVG_Hidden"])[0];
range.setEnd(endElement, endElement.childNodes.length);
}
}
return range;
};
this.getRangeCfiFromDomRange = function(domRange) {
return generateCfiFromDomRange(domRange);
};
function getWrappedCfi(partialCfi) {
return "epubcfi(" + partialCfi + ")";
}
function getWrappedCfiRelativeToContent(partialCfi) {
return "epubcfi(/99!" + partialCfi + ")";
}
this.isRangeCfi = function (partialCfi) {
return EPUBcfi.Interpreter.isRangeCfi(getWrappedCfi(partialCfi)) || EPUBcfi.Interpreter.isRangeCfi(getWrappedCfiRelativeToContent(partialCfi));
};
this.getPageForElementCfi = function (cfi, classBlacklist, elementBlacklist, idBlacklist) {
var cfiParts = splitCfi(cfi);
var partialCfi = cfiParts.cfi;
if (this.isRangeCfi(partialCfi)) {
//if given a range cfi the exact page index needs to be calculated by getting node info from the range cfi
var nodeRangeInfoFromCfi = this.getNodeRangeInfoFromCfi(partialCfi);
//the page index is calculated from the node's client rectangle
return findPageBySingleRectangle(nodeRangeInfoFromCfi.clientRect);
}
var $element = getElementByPartialCfi(cfiParts.cfi, classBlacklist, elementBlacklist, idBlacklist);
if (!$element) {
return -1;
}
var pageIndex = this.getPageForPointOnElement($element, cfiParts.x, cfiParts.y);
return pageIndex;
};
function getElementByPartialCfi(cfi, classBlacklist, elementBlacklist, idBlacklist) {
var contentDoc = self.getRootDocument();
var wrappedCfi = getWrappedCfi(cfi);
try {
//noinspection JSUnresolvedVariable
var $element = EPUBcfi.getTargetElementWithPartialCFI(wrappedCfi, contentDoc, classBlacklist, elementBlacklist, idBlacklist);
} catch (ex) {
//EPUBcfi.Interpreter can throw a SyntaxError
}
if (!$element || $element.length == 0) {
console.log("Can't find element for CFI: " + cfi);
return undefined;
}
return $element;
}
this.getElementFromPoint = function (x, y) {
var document = self.getRootDocument();
return document.elementFromPoint(x, y);
};
this.getNodeRangeInfoFromCfi = function (cfi) {
var contentDoc = self.getRootDocument();
if (self.isRangeCfi(cfi)) {
var wrappedCfi = getWrappedCfiRelativeToContent(cfi);
try {
//noinspection JSUnresolvedVariable
var nodeResult = EPUBcfi.Interpreter.getRangeTargetElements(wrappedCfi, contentDoc,
["cfi-marker"],
[],
["MathJax_Message", "MathJax_SVG_Hidden"]);
if (debugMode) {
console.log(nodeResult);
}
} catch (ex) {
//EPUBcfi.Interpreter can throw a SyntaxError
}
if (!nodeResult) {
console.log("Can't find nodes for range CFI: " + cfi);
return undefined;
}
var startRangeInfo = {node: nodeResult.startElement, offset: nodeResult.startOffset};
var endRangeInfo = {node: nodeResult.endElement, offset: nodeResult.endOffset};
var nodeRangeClientRect =
startRangeInfo && endRangeInfo ?
getNodeRangeClientRect(
startRangeInfo.node,
startRangeInfo.offset,
endRangeInfo.node,
endRangeInfo.offset)
: null;
if (debugMode) {
console.log(nodeRangeClientRect);
addOverlayRect(nodeRangeClientRect, 'purple', contentDoc);
}
return {startInfo: startRangeInfo, endInfo: endRangeInfo, clientRect: nodeRangeClientRect}
} else {
var $element = self.getElementByCfi(cfi,
["cfi-marker"],
[],
["MathJax_Message", "MathJax_SVG_Hidden"]);
var visibleContentOffsets = getVisibleContentOffsets();
var normRects = getNormalizedRectangles($element, visibleContentOffsets);
return {startInfo: null, endInfo: null, clientRect: normRects.wrapperRectangle }
}
};
this.isNodeFromRangeCfiVisible = function (cfi) {
var nodeRangeInfo = this.getNodeRangeInfoFromCfi(cfi);
if (nodeRangeInfo) {
return isRectVisible(nodeRangeInfo.clientRect, false);
} else {
return undefined;
}
};
this.getElementByCfi = function (cfi, classBlacklist, elementBlacklist, idBlacklist) {
var cfiParts = splitCfi(cfi);
return getElementByPartialCfi(cfiParts.cfi, classBlacklist, elementBlacklist, idBlacklist);
};
this.getPageForElement = function ($element) {
return this.getPageForPointOnElement($element, 0, 0);
};
this.getPageForPointOnElement = function ($element, x, y) {
var pageIndex;
if (options.rectangleBased) {
pageIndex = findPageByRectangles($element, y);
if (pageIndex === null) {
console.warn('Impossible to locate a hidden element: ', $element);
return 0;
}
return pageIndex;
}
var posInElement = this.getVerticalOffsetForPointOnElement($element, x, y);
return Math.floor(posInElement / getFrameDimensions().height);
};
this.getVerticalOffsetForElement = function ($element) {
return this.getVerticalOffsetForPointOnElement($element, 0, 0);
};
this.getVerticalOffsetForPointOnElement = function ($element, x, y) {
var elementRect = Helpers.Rect.fromElement($element);
return Math.ceil(elementRect.top + y * elementRect.height / 100);
};
this.getElementById = function (id) {
var contentDoc = this.getRootDocument();
var $element = $(contentDoc.getElementById(id));
//$("#" + Helpers.escapeJQuerySelector(id), contentDoc);
if($element.length == 0) {
return undefined;
}
return $element;
};
this.getPageForElementId = function (id) {
var $element = this.getElementById(id);
if (!$element) {
return -1;
}
return this.getPageForElement($element);
};
function splitCfi(cfi) {
var ret = {
cfi: "",
x: 0,
y: 0
};
var ix = cfi.indexOf("@");
if (ix != -1) {
var terminus = cfi.substring(ix + 1);
var colIx = terminus.indexOf(":");
if (colIx != -1) {
ret.x = parseInt(terminus.substr(0, colIx));
ret.y = parseInt(terminus.substr(colIx + 1));
}
else {
console.log("Unexpected terminating step format");
}
ret.cfi = cfi.substring(0, ix);
}
else {
ret.cfi = cfi;
}
return ret;
}
// returns raw DOM element (not $ jQuery-wrapped)
this.getFirstVisibleMediaOverlayElement = function(visibleContentOffsets) {
var docElement = this.getRootElement();
if (!docElement) return undefined;
var $root = $("body", docElement);
if (!$root || !$root.length || !$root[0]) return undefined;
var that = this;
var firstPartial = undefined;
function traverseArray(arr) {
if (!arr || !arr.length) return undefined;
for (var i = 0, count = arr.length; i < count; i++) {
var item = arr[i];
if (!item) continue;
var $item = $(item);
if ($item.data("mediaOverlayData")) {
var visible = that.getElementVisibility($item, visibleContentOffsets);
if (visible) {
if (!firstPartial) firstPartial = item;
if (visible == 100) return item;
}
}
else {
var elem = traverseArray(item.children);
if (elem) return elem;
}
}
return undefined;
}
var el = traverseArray([$root[0]]);
if (!el) el = firstPartial;
return el;
// var $elements = this.getMediaOverlayElements($root);
// return this.getVisibleElements($elements, visibleContentOffsets);
};
this.getElementVisibility = function ($element, visibleContentOffsets) {
return checkVisibilityByRectangles($element, true, visibleContentOffsets);
};
this.isElementVisible = checkVisibilityByRectangles;
this.getVisibleElementsWithFilter = function (visibleContentOffsets, filterFunction) {
var $elements = this.getElementsWithFilter($("body", this.getRootElement()), filterFunction);
return this.getVisibleElements($elements, visibleContentOffsets);
};
this.getAllElementsWithFilter = function (filterFunction) {
var $elements = this.getElementsWithFilter($("body", this.getRootElement()), filterFunction);
return $elements;
};
this.getAllVisibleElementsWithSelector = function (selector, visibleContentOffset) {
var elements = $(selector, this.getRootElement());
var $newElements = [];
$.each(elements, function () {
$newElements.push($(this));
});
var visibleElements = this.getVisibleElements($newElements, visibleContentOffset);
return visibleElements;
};
this.getVisibleElements = function ($elements, visibleContentOffsets, frameDimensions) {
var visibleElements = [];
_.each($elements, function ($node) {
var isTextNode = ($node[0].nodeType === Node.TEXT_NODE);
var $element = isTextNode ? $node.parent() : $node;
var visibilityPercentage = checkVisibilityByRectangles(
$element, true, visibleContentOffsets, frameDimensions);
if (visibilityPercentage) {
var $visibleElement = $element;
visibleElements.push({
element: $visibleElement[0], // DOM Element is pushed
textNode: isTextNode ? $node[0] : null,
percentVisible: visibilityPercentage
});
}
});
return visibleElements;
};
this.getVisibleLeafNodes = function (visibleContentOffsets, frameDimensions) {
if (_cacheEnabled) {
var cacheKey = (options.paginationInfo || {}).currentSpreadIndex || 0;
var fromCache = _cache.visibleLeafNodes.get(cacheKey);
if (fromCache) {
return fromCache;
}
}
var $elements = this.getLeafNodeElements($("body", this.getRootElement()));
var visibleElements = this.getVisibleElements($elements, visibleContentOffsets, frameDimensions);
if (_cacheEnabled) {
_cache.visibleLeafNodes.set(cacheKey, visibleElements);
}
return visibleElements;
};
this.getElementsWithFilter = function ($root, filterFunction) {
var $elements = [];
function traverseCollection(elements) {
if (elements == undefined) return;
for (var i = 0, count = elements.length; i < count; i++) {
var $element = $(elements[i]);
if (filterFunction($element)) {
$elements.push($element);
}
else {
traverseCollection($element[0].children);
}
}
}
traverseCollection([$root[0]]);
return $elements;
};
function isElementBlacklisted($element) {
//TODO: Ok we really need to have a single point of reference for this blacklist
var blacklist = {
classes: ["cfi-marker", "mo-cfi-highlight"],
elements: [], //not looked at
ids: ["MathJax_Message", "MathJax_SVG_Hidden"]
};
var isBlacklisted = false;
_.some(blacklist.classes, function (value) {
if ($element.hasClass(value)) {
isBlacklisted = true;
}
return isBlacklisted;
});
_.some(blacklist.ids, function (value) {
if ($element.attr("id") === value) {
isBlacklisted = true;
}
return isBlacklisted;
});
return isBlacklisted;
}
this.getLeafNodeElements = function ($root) {
if (_cacheEnabled) {
var fromCache = _cache.leafNodeElements.get($root);
if (fromCache) {
return fromCache;
}
}
var nodeIterator = document.createNodeIterator(
$root[0],
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,
function() {
return NodeFilter.FILTER_ACCEPT;
},
false
);
var $leafNodeElements = [];
var node;
while ((node = nodeIterator.nextNode())) {
var isLeafNode = node.nodeType === Node.ELEMENT_NODE && !node.childElementCount && !isValidTextNodeContent(node.textContent);
if (isLeafNode || isValidTextNode(node)){
var $node = $(node);
var $element = (node.nodeType === Node.TEXT_NODE) ? $node.parent() : $node;
if (!isElementBlacklisted($element)) {
$leafNodeElements.push($node);
}
}
}
if (_cacheEnabled) {
_cache.leafNodeElements.set($root, $leafNodeElements);
}
return $leafNodeElements;
};
function isValidTextNode(node) {
if (node.nodeType === Node.TEXT_NODE) {
return isValidTextNodeContent(node.nodeValue);
}
return false;
}
function isValidTextNodeContent(text) {
// Heuristic to find a text node with actual text
// If we don't do this, we may get a reference to a node that doesn't get rendered
// (such as for example a node that has tab character and a bunch of spaces)
// this is would be bad! ask me why.
return text.replace(/[\s\n\r\t]/g, "").length > 0;
}
this.getElements = function (selector) {
if (!selector) {
return $(this.getRootElement()).children();
}
return $(selector, this.getRootElement());
};
this.getElement = function (selector) {
var $element = this.getElements(selector);
if($element.length > 0) {
return $element;
}
return undefined;
};
function Cache() {
var that = this;
//true = survives invalidation
var props = {
leafNodeElements: true,
visibleLeafNodes: false
};
_.each(props, function (val, key) {
that[key] = new Map();
});
this._invalidate = function () {
_.each(props, function (val, key) {
if (!val) {
that[key] = new Map();
}
});
}
}
var _cache = new Cache();
var _cacheEnabled = false;
this.invalidateCache = function () {
_cache._invalidate();
};
// dmitry debug
// dmitry debug
// dmitry debug
// dmitry debug
// dmitry debug
// dmitry debug
var parseContentCfi = function(cont) {
return cont.replace(/\[(.*?)\]/, "").split(/[\/,:]/).map(function(n) { return parseInt(n); }).filter(Boolean);
};
var contentCfiComparator = function(cont1, cont2) {
cont1 = this.parseContentCfi(cont1);
cont2 = this.parseContentCfi(cont2);
//compare cont arrays looking for differences
for (var i=0; i<cont1.length; i++) {
if (cont1[i] > cont2[i]) {
return 1;
}
else if (cont1[i] < cont2[i]) {
return -1;
}
}
//no differences found, so confirm that cont2 did not have values we didn't check
if (cont1.length < cont2.length) {
return -1;
}
//cont arrays are identical
return 0;
};
// end dmitry debug
//if (debugMode) {
var $debugOverlays = [];
//used for visual debug atm
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
//used for visual debug atm
function addOverlayRect(rects, color, doc) {
var random = getRandomColor();
if (!(rects instanceof Array)) {
rects = [rects];
}
for (var i = 0; i != rects.length; i++) {
var rect = rects[i];
var overlayDiv = doc.createElement('div');
overlayDiv.style.position = 'absolute';
$(overlayDiv).css('z-index', '1000');
$(overlayDiv).css('pointer-events', 'none');
$(overlayDiv).css('opacity', '0.4');
overlayDiv.style.border = '1px solid white';
if (!color && !random) {
overlayDiv.style.background = 'purple';
} else if (random && !color) {
overlayDiv.style.background = random;
} else {
if (color === true) {
color = 'red';
}
overlayDiv.style.border = '1px dashed ' + color;
overlayDiv.style.background = 'yellow';
}
overlayDiv.style.margin = overlayDiv.style.padding = '0';
overlayDiv.style.top = (rect.top ) + 'px';
overlayDiv.style.left = (rect.left ) + 'px';
// we want rect.width to be the border width, so content width is 2px less.
overlayDiv.style.width = (rect.width - 2) + 'px';
overlayDiv.style.height = (rect.height - 2) + 'px';
doc.documentElement.appendChild(overlayDiv);
$debugOverlays.push($(overlayDiv));
}
}
function drawDebugOverlayFromRect(rect) {
var leftOffset, topOffset;
if (isVerticalWritingMode()) {
leftOffset = 0;
topOffset = -getPaginationLeftOffset();
} else {
leftOffset = -getPaginationLeftOffset();
topOffset = 0;
}
addOverlayRect({
left: rect.left + leftOffset,
top: rect.top + topOffset,
width: rect.width,
height: rect.height
}, true, self.getRootDocument());
}
function drawDebugOverlayFromDomRange(range) {
var rect = getNodeRangeClientRect(
range.startContainer,
range.startOffset,
range.endContainer,
range.endOffset);
drawDebugOverlayFromRect(rect);
return rect;
}
function drawDebugOverlayFromNode(node) {
drawDebugOverlayFromRect(getNodeClientRect(node));
}
function getPaginationLeftOffset() {
var $htmlElement = $("html", self.getRootDocument());
var offsetLeftPixels = $htmlElement.css(isVerticalWritingMode() ? "top" : (isPageProgressionRightToLeft() ? "right" : "left"));
var offsetLeft = parseInt(offsetLeftPixels.replace("px", ""));
if (isNaN(offsetLeft)) {
//for fixed layouts, $htmlElement.css("left") has no numerical value
offsetLeft = 0;
}
if (isPageProgressionRightToLeft() && !isVerticalWritingMode()) return -offsetLeft;
return offsetLeft;
}
function clearDebugOverlays() {
_.each($debugOverlays, function($el){
$el.remove();
});
$debugOverlays.clear();
}
ReadiumSDK._DEBUG_CfiNavigationLogic = {
clearDebugOverlays: clearDebugOverlays,
drawDebugOverlayFromRect: drawDebugOverlayFromRect,
drawDebugOverlayFromDomRange: drawDebugOverlayFromDomRange,
drawDebugOverlayFromNode: drawDebugOverlayFromNode,
debugVisibleCfis: function () {
console.log(JSON.stringify(ReadiumSDK.reader.getPaginationInfo().openPages));
var cfi1 = ReadiumSDK.reader.getFirstVisibleCfi();
var range1 = ReadiumSDK.reader.getDomRangeFromRangeCfi(cfi1);
console.log(cfi1, range1, drawDebugOverlayFromDomRange(range1));
var cfi2 = ReadiumSDK.reader.getLastVisibleCfi();
var range2 = ReadiumSDK.reader.getDomRangeFromRangeCfi(cfi2);
console.log(cfi2, range2, drawDebugOverlayFromDomRange(range2));
}
};
//
// }
};
return CfiNavigationLogic;
});
|
js/views/cfi_navigation_logic.js
|
// LauncherOSX
//
// Created by Boris Schneiderman.
// Copyright (c) 2014 Readium Foundation and/or its licensees. 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.
// 3. Neither the name of the organization 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 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.
/**
* CFI navigation helper class
*
* @param options Additional settings for NavigationLogic object
* - paginationInfo Layout details, used by clientRect-based geometry
* - visibleContentOffsets Function that returns offsets. If supplied it is used instead of the inferred offsets
* - frameDimensions Function that returns an object with width and height properties. Needs to be set.
* - $iframe Iframe reference, and needs to be set.
* @constructor
*/
define(["jquery", "underscore", "../helpers", 'readium_cfi_js'], function($, _, Helpers, epubCfi) {
var CfiNavigationLogic = function(options) {
var self = this;
options = options || {};
var debugMode = ReadiumSDK.DEBUG_MODE;
this.getRootElement = function(){
return options.$iframe[0].contentDocument.documentElement;
};
this.getRootDocument = function () {
return options.$iframe[0].contentDocument;
};
function createRange() {
return self.getRootDocument().createRange();
}
function getNodeClientRect(node) {
var range = createRange();
range.selectNode(node);
return normalizeRectangle(range.getBoundingClientRect(),0,0);
}
function getNodeContentsClientRect(node) {
var range = createRange();
range.selectNodeContents(node);
return normalizeRectangle(range.getBoundingClientRect(),0,0);
}
function getElementClientRect($element) {
return normalizeRectangle($element[0].getBoundingClientRect(),0,0);
}
function getNodeRangeClientRect(startNode, startOffset, endNode, endOffset) {
var range = createRange();
range.setStart(startNode, startOffset ? startOffset : 0);
if (endNode.nodeType === Node.ELEMENT_NODE) {
range.setEnd(endNode, endOffset ? endOffset : endNode.childNodes.length);
} else if (endNode.nodeType === Node.TEXT_NODE) {
range.setEnd(endNode, endOffset ? endOffset : 0);
}
return normalizeRectangle(range.getBoundingClientRect(),0,0);
}
function getNodeClientRectList(node, visibleContentOffsets) {
visibleContentOffsets = visibleContentOffsets || getVisibleContentOffsets();
var range = createRange();
range.selectNode(node);
return _.map(range.getClientRects(), function (rect) {
return normalizeRectangle(rect, visibleContentOffsets.left, visibleContentOffsets.top);
});
}
function getFrameDimensions() {
if (options.frameDimensions) {
return options.frameDimensions();
}
console.error('CfiNavigationLogic: No frame dimensions specified!');
return null;
}
function getCaretRangeFromPoint(x, y, document) {
document = document || self.getRootDocument();
Helpers.polyfillCaretRangeFromPoint(document); //only polyfills once, no-op afterwards
return document.caretRangeFromPoint(x, y);
}
function isPaginatedView() {
return !!options.paginationInfo;
}
/**
* @private
* Checks whether or not pages are rendered right-to-left
*
* @returns {boolean}
*/
function isPageProgressionRightToLeft() {
return options.paginationInfo && !!options.paginationInfo.rightToLeft;
}
/**
* @private
* Checks whether or not pages are rendered with vertical writing mode
*
* @returns {boolean}
*/
function isVerticalWritingMode() {
return options.paginationInfo && !!options.paginationInfo.isVerticalWritingMode;
}
/**
* @private
* Checks whether or not a (fully adjusted) rectangle is at least partly visible
*
* @param {Object} rect
* @param {Object} [frameDimensions]
* @param {boolean} [isVwm] isVerticalWritingMode
* @returns {boolean}
*/
function isRectVisible(rect, ignorePartiallyVisible, frameDimensions, isVwm) {
frameDimensions = frameDimensions || getFrameDimensions();
isVwm = isVwm || isVerticalWritingMode();
//Text nodes without printable text dont have client rectangles
if (!rect) {
return false;
}
//Sometimes we get client rects that are "empty" and aren't supposed to be visible
if (rect.left == 0 && rect.right == 0 && rect.top == 0 && rect.bottom == 0) {
return false;
}
if (isPaginatedView()) {
return (rect.left >= 0 && rect.left < frameDimensions.width) ||
(!ignorePartiallyVisible && rect.left < 0 && rect.right >= 0);
} else {
return (rect.top >= 0 && rect.top < frameDimensions.height) ||
(!ignorePartiallyVisible && rect.top < 0 && rect.bottom >= 0);
}
}
/**
* @private
* Retrieves _current_ full width of a column (including its gap)
*
* @returns {number} Full width of a column in pixels
*/
function getColumnFullWidth() {
if (!options.paginationInfo || isVerticalWritingMode())
{
return options.$iframe.width();
}
return options.paginationInfo.columnWidth + options.paginationInfo.columnGap;
}
/**
* @private
*
* Retrieves _current_ offset of a viewport
* (related to the beginning of the chapter)
*
* @returns {Object}
*/
function getVisibleContentOffsets() {
if (options.visibleContentOffsets) {
return options.visibleContentOffsets();
}
if (isVerticalWritingMode()) {
return {
top: (options.paginationInfo ? options.paginationInfo.pageOffset : 0),
left: 0
};
}
return {
top: 0,
left: 0
};
}
/**
* New (rectangle-based) algorithm, useful in multi-column layouts
*
* Note: the second param (props) is ignored intentionally
* (no need to use those in normalization)
*
* @param {jQuery} $element
* @param {Object} _props
* @param {boolean} shouldCalculateVisibilityPercentage
* @param {Object} [frameDimensions]
* @returns {number|null}
* 0 for non-visible elements,
* 0 < n <= 100 for visible elements
* (will just give 100, if `shouldCalculateVisibilityPercentage` => false)
* null for elements with display:none
*/
function checkVisibilityByRectangles($element, shouldCalculateVisibilityPercentage, visibleContentOffsets, frameDimensions) {
visibleContentOffsets = visibleContentOffsets || getVisibleContentOffsets();
frameDimensions = frameDimensions || getFrameDimensions();
var elementRectangles = getNormalizedRectangles($element, visibleContentOffsets);
var clientRectangles = elementRectangles.clientRectangles;
if (clientRectangles.length === 0) { // elements with display:none, etc.
return null;
}
var visibilityPercentage = 0;
if (clientRectangles.length === 1) {
var adjustedRect = clientRectangles[0];
if (isPaginatedView()) {
if (adjustedRect.bottom > frameDimensions.height || adjustedRect.top < 0) {
// because of webkit inconsistency, that single rectangle should be adjusted
// until it hits the end OR will be based on the FIRST column that is visible
adjustRectangle(adjustedRect, true, frameDimensions);
}
}
if (isRectVisible(adjustedRect, false, frameDimensions)) {
//it might still be partially visible in webkit
if (shouldCalculateVisibilityPercentage && adjustedRect.top < 0) {
visibilityPercentage =
Math.floor(100 * (adjustedRect.height + adjustedRect.top) / adjustedRect.height);
} else {
visibilityPercentage = 100;
}
}
} else {
// for an element split between several CSS columns,z
// both Firefox and IE produce as many client rectangles;
// each of those should be checked
for (var i = 0, l = clientRectangles.length; i < l; ++i) {
if (isRectVisible(clientRectangles[i], false, frameDimensions)) {
visibilityPercentage = shouldCalculateVisibilityPercentage
? measureVisibilityPercentageByRectangles(clientRectangles, i)
: 100;
break;
}
}
}
return visibilityPercentage;
}
/**
* Finds a page index (0-based) for a specific element.
* Calculations are based on rectangles retrieved with getClientRects() method.
*
* @param {jQuery} $element
* @param {number} spatialVerticalOffset
* @returns {number|null}
*/
function findPageByRectangles($element, spatialVerticalOffset) {
var visibleContentOffsets = getVisibleContentOffsets();
var elementRectangles = getNormalizedRectangles($element, visibleContentOffsets);
var clientRectangles = elementRectangles.clientRectangles;
if (clientRectangles.length === 0) { // elements with display:none, etc.
return null;
}
return calculatePageIndexByRectangles(clientRectangles, spatialVerticalOffset);
}
/**
* @private
* Calculate a page index (0-based) for given client rectangles.
*
* @param {object} clientRectangles
* @param {number} [spatialVerticalOffset]
* @param {object} [frameDimensions]
* @param {object} [columnFullWidth]
* @returns {number|null}
*/
function calculatePageIndexByRectangles(clientRectangles, spatialVerticalOffset, frameDimensions, columnFullWidth) {
var isRtl = isPageProgressionRightToLeft();
var isVwm = isVerticalWritingMode();
columnFullWidth = columnFullWidth || getColumnFullWidth();
frameDimensions = frameDimensions || getFrameDimensions();
if (spatialVerticalOffset) {
trimRectanglesByVertOffset(clientRectangles, spatialVerticalOffset,
frameDimensions, columnFullWidth, isRtl, isVwm);
}
var firstRectangle = _.first(clientRectangles);
if (clientRectangles.length === 1) {
adjustRectangle(firstRectangle, false, frameDimensions, columnFullWidth, isRtl, isVwm);
}
var pageIndex;
if (isVwm) {
var topOffset = firstRectangle.top;
pageIndex = Math.floor(topOffset / frameDimensions.height);
} else {
var leftOffset = firstRectangle.left;
if (isRtl) {
leftOffset = (columnFullWidth * (options.paginationInfo ? options.paginationInfo.visibleColumnCount : 1)) - leftOffset;
}
pageIndex = Math.floor(leftOffset / columnFullWidth);
}
if (pageIndex < 0) {
pageIndex = 0;
}
else if (pageIndex >= (options.paginationInfo ? options.paginationInfo.columnCount : 1)) {
pageIndex = (options.paginationInfo ? (options.paginationInfo.columnCount - 1) : 0);
}
return pageIndex;
}
/**
* Finds a page index (0-based) for a specific client rectangle.
* Calculations are based on viewport dimensions, offsets, and rectangle coordinates
*
* @param {ClientRect} clientRectangle
* @param {Object} [visibleContentOffsets]
* @param {Object} [frameDimensions]
* @returns {number|null}
*/
function findPageBySingleRectangle(clientRectangle, visibleContentOffsets, frameDimensions) {
visibleContentOffsets = visibleContentOffsets || getVisibleContentOffsets();
frameDimensions = frameDimensions || getFrameDimensions();
var normalizedRectangle = normalizeRectangle(
clientRectangle, visibleContentOffsets.left, visibleContentOffsets.top);
return calculatePageIndexByRectangles([normalizedRectangle], frameDimensions);
}
/**
* @private
* Calculates the visibility offset percentage based on ClientRect dimensions
*
* @param {Array} clientRectangles (should already be normalized)
* @param {number} firstVisibleRectIndex
* @returns {number} - visibility percentage (0 < n <= 100)
*/
function measureVisibilityPercentageByRectangles(clientRectangles, firstVisibleRectIndex) {
var heightTotal = 0;
var heightVisible = 0;
if (clientRectangles.length > 1) {
_.each(clientRectangles, function (rect, index) {
heightTotal += rect.height;
if (index >= firstVisibleRectIndex) {
// in this case, all the rectangles after the first visible
// should be counted as visible
heightVisible += rect.height;
}
});
}
else {
// should already be normalized and adjusted
heightTotal = clientRectangles[0].height;
heightVisible = clientRectangles[0].height - Math.max(
0, -clientRectangles[0].top);
}
return heightVisible === heightTotal
? 100 // trivial case: element is 100% visible
: Math.floor(100 * heightVisible / heightTotal);
}
/**
* @private
* Retrieves the position of $element in multi-column layout
*
* @param {jQuery} $el
* @param {Object} [visibleContentOffsets]
* @returns {Object}
*/
function getNormalizedRectangles($el, visibleContentOffsets) {
visibleContentOffsets = visibleContentOffsets || {};
var leftOffset = visibleContentOffsets.left || 0;
var topOffset = visibleContentOffsets.top || 0;
// union of all rectangles wrapping the element
var wrapperRectangle = normalizeRectangle(
$el[0].getBoundingClientRect(), leftOffset, topOffset);
// all the separate rectangles (for detecting position of the element
// split between several columns)
var clientRectangles = [];
var clientRectList = $el[0].getClientRects();
for (var i = 0, l = clientRectList.length; i < l; ++i) {
if (clientRectList[i].height > 0) {
// Firefox sometimes gets it wrong,
// adding literally empty (height = 0) client rectangle preceding the real one,
// that empty client rectanle shouldn't be retrieved
clientRectangles.push(
normalizeRectangle(clientRectList[i], leftOffset, topOffset));
}
}
if (clientRectangles.length === 0) {
// sometimes an element is either hidden or empty, and that means
// Webkit-based browsers fail to assign proper clientRects to it
// in this case we need to go for its sibling (if it exists)
$el = $el.next();
if ($el.length) {
return getNormalizedRectangles($el, visibleContentOffsets);
}
}
return {
wrapperRectangle: wrapperRectangle,
clientRectangles: clientRectangles
};
}
/**
* @private
* Converts TextRectangle object into a plain object,
* taking content offsets (=scrolls, position shifts etc.) into account
*
* @param {TextRectangle} textRect
* @param {number} leftOffset
* @param {number} topOffset
* @returns {Object}
*/
function normalizeRectangle(textRect, leftOffset, topOffset) {
var plainRectObject = {
left: textRect.left,
right: textRect.right,
top: textRect.top,
bottom: textRect.bottom,
width: textRect.right - textRect.left,
height: textRect.bottom - textRect.top
};
offsetRectangle(plainRectObject, leftOffset, topOffset);
return plainRectObject;
}
/**
* @private
* Offsets plain object (which represents a TextRectangle).
*
* @param {Object} rect
* @param {number} leftOffset
* @param {number} topOffset
*/
function offsetRectangle(rect, leftOffset, topOffset) {
rect.left += leftOffset;
rect.right += leftOffset;
rect.top += topOffset;
rect.bottom += topOffset;
}
/**
* @private
*
* When element is spilled over two or more columns,
* most of the time Webkit-based browsers
* still assign a single clientRectangle to it, setting its `top` property to negative value
* (so it looks like it's rendered based on the second column)
* Alas, sometimes they decide to continue the leftmost column - from _below_ its real height.
* In this case, `bottom` property is actually greater than element's height and had to be adjusted accordingly.
*
* Ugh.
*
* @param {Object} rect
* @param {boolean} [shouldLookForFirstVisibleColumn]
* If set, there'll be two-phase adjustment
* (to align a rectangle with a viewport)
* @param {Object} [frameDimensions]
* @param {number} [columnFullWidth]
* @param {boolean} [isRtl]
* @param {boolean} [isVwm] isVerticalWritingMode
*/
function adjustRectangle(rect, shouldLookForFirstVisibleColumn, frameDimensions, columnFullWidth, isRtl, isVwm) {
frameDimensions = frameDimensions || getFrameDimensions();
columnFullWidth = columnFullWidth || getColumnFullWidth();
isRtl = isRtl || isPageProgressionRightToLeft();
isVwm = isVwm || isVerticalWritingMode();
// Rectangle adjustment is not needed in VWM since it does not deal with columns
if (isVwm) {
return;
}
if (isRtl) {
columnFullWidth *= -1; // horizontal shifts are reverted in RTL mode
}
// first we go left/right (rebasing onto the very first column available)
while (rect.top < 0) {
offsetRectangle(rect, -columnFullWidth, frameDimensions.height);
}
// ... then, if necessary (for visibility offset checks),
// each column is tried again (now in reverse order)
// the loop will be stopped when the column is aligned with a viewport
// (i.e., is the first visible one).
if (shouldLookForFirstVisibleColumn) {
while (rect.bottom >= frameDimensions.height) {
if (isRectVisible(rect, false, frameDimensions, isVwm)) {
break;
}
offsetRectangle(rect, columnFullWidth, -frameDimensions.height);
}
}
}
/**
* @private
* Trims the rectangle(s) representing the given element.
*
* @param {Array} rects
* @param {number} verticalOffset
* @param {number} frameDimensions
* @param {number} columnFullWidth
* @param {boolean} isRtl
* @param {boolean} isVwm isVerticalWritingMode
*/
function trimRectanglesByVertOffset(
rects, verticalOffset, frameDimensions, columnFullWidth, isRtl, isVwm) {
frameDimensions = frameDimensions || getFrameDimensions();
columnFullWidth = columnFullWidth || getColumnFullWidth();
isRtl = isRtl || isPageProgressionRightToLeft();
isVwm = isVwm || isVerticalWritingMode();
//TODO: Support vertical writing mode
if (isVwm) {
return;
}
var totalHeight = _.reduce(rects, function(prev, cur) {
return prev + cur.height;
}, 0);
var heightToHide = totalHeight * verticalOffset / 100;
if (rects.length > 1) {
var heightAccum = 0;
do {
heightAccum += rects[0].height;
if (heightAccum > heightToHide) {
break;
}
rects.shift();
} while (rects.length > 1);
}
else {
// rebase to the last possible column
// (so that adding to top will be properly processed later)
if (isRtl) {
columnFullWidth *= -1;
}
while (rects[0].bottom >= frameDimensions.height) {
offsetRectangle(rects[0], columnFullWidth, -frameDimensions.height);
}
rects[0].top += heightToHide;
rects[0].height -= heightToHide;
}
}
this.getCfiForElement = function (element) {
var cfi = EPUBcfi.Generator.generateElementCFIComponent(element,
["cfi-marker"],
[],
["MathJax_Message", "MathJax_SVG_Hidden"]);
if (cfi[0] == "!") {
cfi = cfi.substring(1);
}
return cfi;
};
//TODO JC: Can now use getFirstVisibleCfi instead, use that instead of this at top levels
this.getFirstVisibleElementCfi = function (topOffset) {
return self.getFirstVisibleCfi();
};
this.getVisibleCfiFromPoint = function (x, y, precisePoint) {
var document = self.getRootDocument();
var firstVisibleCaretRange = getCaretRangeFromPoint(x, y, document);
var elementFromPoint = document.elementFromPoint(x, y);
var invalidElementFromPoint = !elementFromPoint || elementFromPoint === document.documentElement;
if (precisePoint) {
if (!elementFromPoint || invalidElementFromPoint) {
return null;
}
var testRect = getNodeContentsClientRect(elementFromPoint);
if (!isRectVisible(testRect, false)) {
return null;
}
if ((x < testRect.left || x > testRect.right) || (y < testRect.top || y > testRect.bottom)) {
return null;
}
}
if (!firstVisibleCaretRange) {
if (invalidElementFromPoint) {
console.error("Could not generate CFI no visible element on page");
return null;
}
firstVisibleCaretRange = createRange();
firstVisibleCaretRange.selectNode(elementFromPoint);
}
var range = firstVisibleCaretRange;
var cfi;
//if we get a text node we need to get an approximate range for the first visible character offsets.
var node = range.startContainer;
var startOffset, endOffset;
if (node.nodeType === Node.TEXT_NODE) {
if (precisePoint && node.parentNode !== elementFromPoint) {
return null;
}
if (node.length === 1 && range.startOffset === 1) {
startOffset = 0;
endOffset = 1;
} else if (range.startOffset === node.length) {
startOffset = range.startOffset - 1;
endOffset = range.startOffset;
} else {
startOffset = range.startOffset;
endOffset = range.startOffset + 1;
}
var wrappedRange = {
startContainer: node,
endContainer: node,
startOffset: startOffset,
endOffset: endOffset,
commonAncestorContainer: range.commonAncestorContainer
};
if (debugMode) {
drawDebugOverlayFromDomRange(wrappedRange);
}
cfi = generateCfiFromDomRange(wrappedRange);
} else if (node.nodeType === Node.ELEMENT_NODE) {
node =
range.startContainer.childNodes[range.startOffset] ||
range.startContainer.childNodes[0] ||
range.startContainer;
if (precisePoint && node !== elementFromPoint) {
return null;
}
if (node.nodeType !== Node.ELEMENT_NODE) {
cfi = generateCfiFromDomRange(range);
} else {
cfi = self.getCfiForElement(node);
}
} else {
if (precisePoint && node !== elementFromPoint) {
return null;
}
cfi = self.getCfiForElement(elementFromPoint);
}
//This should not happen but if it does print some output, just in case
if (cfi && cfi.indexOf('NaN') !== -1) {
console.log('Did not generate a valid CFI:' + cfi);
return undefined;
}
return cfi;
};
this.getRangeCfiFromPoints = function(startX, startY, endX, endY) {
var document = self.getRootDocument();
var start = getCaretRangeFromPoint(startX, startY, document),
end = getCaretRangeFromPoint(endX, endY, document),
range = createRange();
range.setStart(start.startContainer, start.startOffset);
range.setEnd(end.startContainer, end.startOffset);
// if we're looking at a text node create a nice range (n, n+1)
if (start.startContainer === start.endContainer && start.startContainer.nodeType === Node.TEXT_NODE && end.startContainer.length > end.startOffset+1) {
range.setEnd(end.startContainer, end.startOffset+1);
}
return generateCfiFromDomRange(range);
};
function getTextNodeRectCornerPairs(rect) {
//
// top left top right
// ╲ ╱
// ── ▒T▒E▒X▒T▒ ▒R▒E▒C▒T▒ ──
//
// top left corner & top right corner
// but for y coord use the mid point between top and bottom
if (isVerticalWritingMode()) {
var x = rect.right - (rect.width / 2);
return [{x: x, y: rect.top}, {x: x, y: rect.bottom}];
} else {
var y = rect.top + (rect.height / 2);
var result = [{x: rect.left, y: y}, {x: rect.right, y: y}]
return isPageProgressionRightToLeft() ? result.reverse() : result;
}
}
function getVisibleTextRangeOffsetsSelectedByFunc(textNode, pickerFunc, visibleContentOffsets, frameDimensions) {
visibleContentOffsets = visibleContentOffsets || getVisibleContentOffsets();
var textNodeFragments = getNodeClientRectList(textNode, visibleContentOffsets);
var visibleFragments = _.filter(textNodeFragments, function (rect) {
return isRectVisible(rect, false, frameDimensions);
});
var fragment = pickerFunc(visibleFragments);
if (!fragment) {
//no visible fragment, empty text node?
return null;
}
var fragmentCorner = pickerFunc(getTextNodeRectCornerPairs(fragment));
// Reverse taking into account of visible content offsets
fragmentCorner.x -= visibleContentOffsets.left;
fragmentCorner.y -= visibleContentOffsets.top;
var caretRange = getCaretRangeFromPoint(fragmentCorner.x, fragmentCorner.y);
console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'a0');
// Desperately try to find it from all angles! Darn sub pixeling..
//TODO: remove the need for this brute-force method, since it's making the result non-deterministic
if (!caretRange || caretRange.startContainer !== textNode) {
caretRange = getCaretRangeFromPoint(fragmentCorner.x - 1, fragmentCorner.y);
console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'a1');
}
if (!caretRange || caretRange.startContainer !== textNode) {
caretRange = getCaretRangeFromPoint(fragmentCorner.x, fragmentCorner.y - 1);
console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'a2');
}
if (!caretRange || caretRange.startContainer !== textNode) {
caretRange = getCaretRangeFromPoint(fragmentCorner.x - 1, fragmentCorner.y - 1);
console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'a3');
}
if (!caretRange || caretRange.startContainer !== textNode) {
fragmentCorner.x = Math.floor(fragmentCorner.x);
fragmentCorner.y = Math.floor(fragmentCorner.y);
caretRange = getCaretRangeFromPoint(fragmentCorner.x, fragmentCorner.y);
console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'b0');
}
// Desperately try to find it from all angles! Darn sub pixeling..
if (!caretRange || caretRange.startContainer !== textNode) {
caretRange = getCaretRangeFromPoint(fragmentCorner.x - 1, fragmentCorner.y);
console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'b1');
}
if (!caretRange || caretRange.startContainer !== textNode) {
caretRange = getCaretRangeFromPoint(fragmentCorner.x, fragmentCorner.y - 1);
console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'b2');
}
if (!caretRange || caretRange.startContainer !== textNode) {
caretRange = getCaretRangeFromPoint(fragmentCorner.x - 1, fragmentCorner.y - 1);
console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'b3');
}
// Still nothing? fall through..
if (!caretRange) {
console.warn('getVisibleTextRangeOffsetsSelectedByFunc: no caret range result');
return null;
}
if (caretRange.startContainer === textNode) {
return pickerFunc(
[{start: caretRange.startOffset, end: caretRange.startOffset + 1},
{start: caretRange.startOffset - 1, end: caretRange.startOffset}]
);
} else {
console.warn('getVisibleTextRangeOffsetsSelectedByFunc: incorrect caret range result');
return null;
}
}
function findVisibleLeafNodeCfi(leafNodeList, pickerFunc, targetLeafNode, visibleContentOffsets, frameDimensions) {
var index = 0;
if (!targetLeafNode) {
index = leafNodeList.indexOf(pickerFunc(leafNodeList))
} else {
index = leafNodeList.indexOf(targetLeafNode);
if (index === -1) {
//target leaf node not the right type? not in list?
return null;
}
// use the next leaf node in the list
index += pickerFunc([1, -1]);
}
var visibleLeafNode = leafNodeList[index];
if (!visibleLeafNode) {
return null;
}
var element = visibleLeafNode.element;
var textNode = visibleLeafNode.textNode;
//if a valid text node is found, try to generate a CFI with range offsets
if (textNode && isValidTextNode(textNode)) {
var visibleRange = getVisibleTextRangeOffsetsSelectedByFunc(textNode, pickerFunc, visibleContentOffsets, frameDimensions);
if (!visibleRange) {
//the text node is valid, but not visible..
//let's try again with the next node in the list
return findVisibleLeafNodeCfi(leafNodeList, pickerFunc, visibleLeafNode, visibleContentOffsets, frameDimensions);
}
var range = createRange();
range.setStart(textNode, visibleRange.start);
range.setEnd(textNode, visibleRange.end);
return generateCfiFromDomRange(range);
} else {
//if not then generate a CFI for the element
return self.getCfiForElement(element);
}
}
// get an array of visible text elements and then select one based on the func supplied
// and generate a CFI for the first visible text subrange.
function getVisibleTextRangeCfiForTextElementSelectedByFunc(pickerFunc, visibleContentOffsets, frameDimensions) {
var visibleLeafNodeList = self.getVisibleLeafNodes(visibleContentOffsets, frameDimensions);
return findVisibleLeafNodeCfi(visibleLeafNodeList, pickerFunc, null, visibleContentOffsets, frameDimensions);
}
function getLastVisibleTextRangeCfi(visibleContentOffsets, frameDimensions) {
return getVisibleTextRangeCfiForTextElementSelectedByFunc(_.last, visibleContentOffsets, frameDimensions);
}
function getFirstVisibleTextRangeCfi(visibleContentOffsets, frameDimensions) {
return getVisibleTextRangeCfiForTextElementSelectedByFunc(_.first, visibleContentOffsets, frameDimensions);
}
this.getFirstVisibleCfi = function (visibleContentOffsets, frameDimensions) {
return getFirstVisibleTextRangeCfi(visibleContentOffsets, frameDimensions);
};
this.getLastVisibleCfi = function (visibleContentOffsets, frameDimensions) {
return getLastVisibleTextRangeCfi(visibleContentOffsets, frameDimensions);
};
function generateCfiFromDomRange(range) {
return EPUBcfi.generateRangeComponent(
range.startContainer, range.startOffset,
range.endContainer, range.endOffset,
['cfi-marker'], [], ["MathJax_Message", "MathJax_SVG_Hidden"]);
}
function getRangeTargetNodes(rangeCfi) {
return EPUBcfi.getRangeTargetElements(
getWrappedCfiRelativeToContent(rangeCfi),
self.getRootDocument(),
['cfi-marker'], [], ["MathJax_Message", "MathJax_SVG_Hidden"]);
}
this.getDomRangeFromRangeCfi = function(rangeCfi, rangeCfi2, inclusive) {
var range = createRange();
if (!rangeCfi2) {
if (self.isRangeCfi(rangeCfi)) {
var rangeInfo = getRangeTargetNodes(rangeCfi);
range.setStart(rangeInfo.startElement, rangeInfo.startOffset);
range.setEnd(rangeInfo.endElement, rangeInfo.endOffset);
} else {
var element = self.getElementByCfi(rangeCfi,
['cfi-marker'], [], ["MathJax_Message", "MathJax_SVG_Hidden"])[0];
range.selectNode(element);
}
} else {
if (self.isRangeCfi(rangeCfi)) {
var rangeInfo1 = getRangeTargetNodes(rangeCfi);
range.setStart(rangeInfo1.startElement, rangeInfo1.startOffset);
} else {
var startElement = self.getElementByCfi(rangeCfi,
['cfi-marker'], [], ["MathJax_Message", "MathJax_SVG_Hidden"])[0];
range.setStart(startElement, 0);
}
if (self.isRangeCfi(rangeCfi2)) {
var rangeInfo2 = getRangeTargetNodes(rangeCfi2);
if (inclusive) {
range.setEnd(rangeInfo2.endElement, rangeInfo2.endOffset);
} else {
range.setEnd(rangeInfo2.startElement, rangeInfo2.startOffset);
}
} else {
var endElement = self.getElementByCfi(rangeCfi2,
['cfi-marker'], [], ["MathJax_Message", "MathJax_SVG_Hidden"])[0];
range.setEnd(endElement, endElement.childNodes.length);
}
}
return range;
};
this.getRangeCfiFromDomRange = function(domRange) {
return generateCfiFromDomRange(domRange);
};
function getWrappedCfi(partialCfi) {
return "epubcfi(" + partialCfi + ")";
}
function getWrappedCfiRelativeToContent(partialCfi) {
return "epubcfi(/99!" + partialCfi + ")";
}
this.isRangeCfi = function (partialCfi) {
return EPUBcfi.Interpreter.isRangeCfi(getWrappedCfi(partialCfi)) || EPUBcfi.Interpreter.isRangeCfi(getWrappedCfiRelativeToContent(partialCfi));
};
this.getPageForElementCfi = function (cfi, classBlacklist, elementBlacklist, idBlacklist) {
var cfiParts = splitCfi(cfi);
var partialCfi = cfiParts.cfi;
if (this.isRangeCfi(partialCfi)) {
//if given a range cfi the exact page index needs to be calculated by getting node info from the range cfi
var nodeRangeInfoFromCfi = this.getNodeRangeInfoFromCfi(partialCfi);
//the page index is calculated from the node's client rectangle
return findPageBySingleRectangle(nodeRangeInfoFromCfi.clientRect);
}
var $element = getElementByPartialCfi(cfiParts.cfi, classBlacklist, elementBlacklist, idBlacklist);
if (!$element) {
return -1;
}
var pageIndex = this.getPageForPointOnElement($element, cfiParts.x, cfiParts.y);
return pageIndex;
};
function getElementByPartialCfi(cfi, classBlacklist, elementBlacklist, idBlacklist) {
var contentDoc = self.getRootDocument();
var wrappedCfi = getWrappedCfi(cfi);
try {
//noinspection JSUnresolvedVariable
var $element = EPUBcfi.getTargetElementWithPartialCFI(wrappedCfi, contentDoc, classBlacklist, elementBlacklist, idBlacklist);
} catch (ex) {
//EPUBcfi.Interpreter can throw a SyntaxError
}
if (!$element || $element.length == 0) {
console.log("Can't find element for CFI: " + cfi);
return undefined;
}
return $element;
}
this.getElementFromPoint = function (x, y) {
var document = self.getRootDocument();
return document.elementFromPoint(x, y);
};
this.getNodeRangeInfoFromCfi = function (cfi) {
var contentDoc = self.getRootDocument();
if (self.isRangeCfi(cfi)) {
var wrappedCfi = getWrappedCfiRelativeToContent(cfi);
try {
//noinspection JSUnresolvedVariable
var nodeResult = EPUBcfi.Interpreter.getRangeTargetElements(wrappedCfi, contentDoc,
["cfi-marker"],
[],
["MathJax_Message", "MathJax_SVG_Hidden"]);
if (debugMode) {
console.log(nodeResult);
}
} catch (ex) {
//EPUBcfi.Interpreter can throw a SyntaxError
}
if (!nodeResult) {
console.log("Can't find nodes for range CFI: " + cfi);
return undefined;
}
var startRangeInfo = {node: nodeResult.startElement, offset: nodeResult.startOffset};
var endRangeInfo = {node: nodeResult.endElement, offset: nodeResult.endOffset};
var nodeRangeClientRect =
startRangeInfo && endRangeInfo ?
getNodeRangeClientRect(
startRangeInfo.node,
startRangeInfo.offset,
endRangeInfo.node,
endRangeInfo.offset)
: null;
if (debugMode) {
console.log(nodeRangeClientRect);
addOverlayRect(nodeRangeClientRect, 'purple', contentDoc);
}
return {startInfo: startRangeInfo, endInfo: endRangeInfo, clientRect: nodeRangeClientRect}
} else {
var $element = self.getElementByCfi(cfi,
["cfi-marker"],
[],
["MathJax_Message", "MathJax_SVG_Hidden"]);
var visibleContentOffsets = getVisibleContentOffsets();
var normRects = getNormalizedRectangles($element, visibleContentOffsets);
return {startInfo: null, endInfo: null, clientRect: normRects.wrapperRectangle }
}
};
this.isNodeFromRangeCfiVisible = function (cfi) {
var nodeRangeInfo = this.getNodeRangeInfoFromCfi(cfi);
if (nodeRangeInfo) {
return isRectVisible(nodeRangeInfo.clientRect, false);
} else {
return undefined;
}
};
this.getElementByCfi = function (cfi, classBlacklist, elementBlacklist, idBlacklist) {
var cfiParts = splitCfi(cfi);
return getElementByPartialCfi(cfiParts.cfi, classBlacklist, elementBlacklist, idBlacklist);
};
this.getPageForElement = function ($element) {
return this.getPageForPointOnElement($element, 0, 0);
};
this.getPageForPointOnElement = function ($element, x, y) {
var pageIndex;
if (options.rectangleBased) {
pageIndex = findPageByRectangles($element, y);
if (pageIndex === null) {
console.warn('Impossible to locate a hidden element: ', $element);
return 0;
}
return pageIndex;
}
var posInElement = this.getVerticalOffsetForPointOnElement($element, x, y);
return Math.floor(posInElement / getFrameDimensions().height);
};
this.getVerticalOffsetForElement = function ($element) {
return this.getVerticalOffsetForPointOnElement($element, 0, 0);
};
this.getVerticalOffsetForPointOnElement = function ($element, x, y) {
var elementRect = Helpers.Rect.fromElement($element);
return Math.ceil(elementRect.top + y * elementRect.height / 100);
};
this.getElementById = function (id) {
var contentDoc = this.getRootDocument();
var $element = $(contentDoc.getElementById(id));
//$("#" + Helpers.escapeJQuerySelector(id), contentDoc);
if($element.length == 0) {
return undefined;
}
return $element;
};
this.getPageForElementId = function (id) {
var $element = this.getElementById(id);
if (!$element) {
return -1;
}
return this.getPageForElement($element);
};
function splitCfi(cfi) {
var ret = {
cfi: "",
x: 0,
y: 0
};
var ix = cfi.indexOf("@");
if (ix != -1) {
var terminus = cfi.substring(ix + 1);
var colIx = terminus.indexOf(":");
if (colIx != -1) {
ret.x = parseInt(terminus.substr(0, colIx));
ret.y = parseInt(terminus.substr(colIx + 1));
}
else {
console.log("Unexpected terminating step format");
}
ret.cfi = cfi.substring(0, ix);
}
else {
ret.cfi = cfi;
}
return ret;
}
// returns raw DOM element (not $ jQuery-wrapped)
this.getFirstVisibleMediaOverlayElement = function(visibleContentOffsets) {
var docElement = this.getRootElement();
if (!docElement) return undefined;
var $root = $("body", docElement);
if (!$root || !$root.length || !$root[0]) return undefined;
var that = this;
var firstPartial = undefined;
function traverseArray(arr) {
if (!arr || !arr.length) return undefined;
for (var i = 0, count = arr.length; i < count; i++) {
var item = arr[i];
if (!item) continue;
var $item = $(item);
if ($item.data("mediaOverlayData")) {
var visible = that.getElementVisibility($item, visibleContentOffsets);
if (visible) {
if (!firstPartial) firstPartial = item;
if (visible == 100) return item;
}
}
else {
var elem = traverseArray(item.children);
if (elem) return elem;
}
}
return undefined;
}
var el = traverseArray([$root[0]]);
if (!el) el = firstPartial;
return el;
// var $elements = this.getMediaOverlayElements($root);
// return this.getVisibleElements($elements, visibleContentOffsets);
};
this.getElementVisibility = function ($element, visibleContentOffsets) {
return checkVisibilityByRectangles($element, true, visibleContentOffsets);
};
this.isElementVisible = checkVisibilityByRectangles;
this.getVisibleElementsWithFilter = function (visibleContentOffsets, filterFunction) {
var $elements = this.getElementsWithFilter($("body", this.getRootElement()), filterFunction);
return this.getVisibleElements($elements, visibleContentOffsets);
};
this.getAllElementsWithFilter = function (filterFunction) {
var $elements = this.getElementsWithFilter($("body", this.getRootElement()), filterFunction);
return $elements;
};
this.getAllVisibleElementsWithSelector = function (selector, visibleContentOffset) {
var elements = $(selector, this.getRootElement());
var $newElements = [];
$.each(elements, function () {
$newElements.push($(this));
});
var visibleElements = this.getVisibleElements($newElements, visibleContentOffset);
return visibleElements;
};
this.getVisibleElements = function ($elements, visibleContentOffsets, frameDimensions) {
var visibleElements = [];
_.each($elements, function ($node) {
var isTextNode = ($node[0].nodeType === Node.TEXT_NODE);
var $element = isTextNode ? $node.parent() : $node;
var visibilityPercentage = checkVisibilityByRectangles(
$element, true, visibleContentOffsets, frameDimensions);
if (visibilityPercentage) {
var $visibleElement = $element;
visibleElements.push({
element: $visibleElement[0], // DOM Element is pushed
textNode: isTextNode ? $node[0] : null,
percentVisible: visibilityPercentage
});
}
});
return visibleElements;
};
this.getVisibleLeafNodes = function (visibleContentOffsets, frameDimensions) {
if (_cacheEnabled) {
var cacheKey = (options.paginationInfo || {}).currentSpreadIndex || 0;
var fromCache = _cache.visibleLeafNodes.get(cacheKey);
if (fromCache) {
return fromCache;
}
}
var $elements = this.getLeafNodeElements($("body", this.getRootElement()));
var visibleElements = this.getVisibleElements($elements, visibleContentOffsets, frameDimensions);
if (_cacheEnabled) {
_cache.visibleLeafNodes.set(cacheKey, visibleElements);
}
return visibleElements;
};
this.getElementsWithFilter = function ($root, filterFunction) {
var $elements = [];
function traverseCollection(elements) {
if (elements == undefined) return;
for (var i = 0, count = elements.length; i < count; i++) {
var $element = $(elements[i]);
if (filterFunction($element)) {
$elements.push($element);
}
else {
traverseCollection($element[0].children);
}
}
}
traverseCollection([$root[0]]);
return $elements;
};
function isElementBlacklisted($element) {
//TODO: Ok we really need to have a single point of reference for this blacklist
var blacklist = {
classes: ["cfi-marker", "mo-cfi-highlight"],
elements: [], //not looked at
ids: ["MathJax_Message", "MathJax_SVG_Hidden"]
};
var isBlacklisted = false;
_.some(blacklist.classes, function (value) {
if ($element.hasClass(value)) {
isBlacklisted = true;
}
return isBlacklisted;
});
_.some(blacklist.ids, function (value) {
if ($element.attr("id") === value) {
isBlacklisted = true;
}
return isBlacklisted;
});
return isBlacklisted;
}
this.getLeafNodeElements = function ($root) {
if (_cacheEnabled) {
var fromCache = _cache.leafNodeElements.get($root);
if (fromCache) {
return fromCache;
}
}
var nodeIterator = document.createNodeIterator(
$root[0],
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,
function() {
return NodeFilter.FILTER_ACCEPT;
},
false
);
var $leafNodeElements = [];
var node;
while ((node = nodeIterator.nextNode())) {
var isLeafNode = node.nodeType === Node.ELEMENT_NODE && !node.childElementCount && !isValidTextNodeContent(node.textContent);
if (isLeafNode || isValidTextNode(node)){
var $node = $(node);
var $element = (node.nodeType === Node.TEXT_NODE) ? $node.parent() : $node;
if (!isElementBlacklisted($element)) {
$leafNodeElements.push($node);
}
}
}
if (_cacheEnabled) {
_cache.leafNodeElements.set($root, $leafNodeElements);
}
return $leafNodeElements;
};
function isValidTextNode(node) {
if (node.nodeType === Node.TEXT_NODE) {
return isValidTextNodeContent(node.nodeValue);
}
return false;
}
function isValidTextNodeContent(text) {
// Heuristic to find a text node with actual text
// If we don't do this, we may get a reference to a node that doesn't get rendered
// (such as for example a node that has tab character and a bunch of spaces)
// this is would be bad! ask me why.
return text.replace(/[\s\n\r\t]/g, "").length > 0;
}
this.getElements = function (selector) {
if (!selector) {
return $(this.getRootElement()).children();
}
return $(selector, this.getRootElement());
};
this.getElement = function (selector) {
var $element = this.getElements(selector);
if($element.length > 0) {
return $element;
}
return undefined;
};
function Cache() {
var that = this;
//true = survives invalidation
var props = {
leafNodeElements: true,
visibleLeafNodes: false
};
_.each(props, function (val, key) {
that[key] = new Map();
});
this._invalidate = function () {
_.each(props, function (val, key) {
if (!val) {
that[key] = new Map();
}
});
}
}
var _cache = new Cache();
var _cacheEnabled = false;
this.invalidateCache = function () {
_cache._invalidate();
};
// dmitry debug
// dmitry debug
// dmitry debug
// dmitry debug
// dmitry debug
// dmitry debug
var parseContentCfi = function(cont) {
return cont.replace(/\[(.*?)\]/, "").split(/[\/,:]/).map(function(n) { return parseInt(n); }).filter(Boolean);
};
var contentCfiComparator = function(cont1, cont2) {
cont1 = this.parseContentCfi(cont1);
cont2 = this.parseContentCfi(cont2);
//compare cont arrays looking for differences
for (var i=0; i<cont1.length; i++) {
if (cont1[i] > cont2[i]) {
return 1;
}
else if (cont1[i] < cont2[i]) {
return -1;
}
}
//no differences found, so confirm that cont2 did not have values we didn't check
if (cont1.length < cont2.length) {
return -1;
}
//cont arrays are identical
return 0;
};
// end dmitry debug
//if (debugMode) {
var $debugOverlays = [];
//used for visual debug atm
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
//used for visual debug atm
function addOverlayRect(rects, color, doc) {
var random = getRandomColor();
if (!(rects instanceof Array)) {
rects = [rects];
}
for (var i = 0; i != rects.length; i++) {
var rect = rects[i];
var overlayDiv = doc.createElement('div');
overlayDiv.style.position = 'absolute';
$(overlayDiv).css('z-index', '1000');
$(overlayDiv).css('pointer-events', 'none');
$(overlayDiv).css('opacity', '0.4');
overlayDiv.style.border = '1px solid white';
if (!color && !random) {
overlayDiv.style.background = 'purple';
} else if (random && !color) {
overlayDiv.style.background = random;
} else {
if (color === true) {
color = 'red';
}
overlayDiv.style.border = '1px dashed ' + color;
overlayDiv.style.background = 'yellow';
}
overlayDiv.style.margin = overlayDiv.style.padding = '0';
overlayDiv.style.top = (rect.top ) + 'px';
overlayDiv.style.left = (rect.left ) + 'px';
// we want rect.width to be the border width, so content width is 2px less.
overlayDiv.style.width = (rect.width - 2) + 'px';
overlayDiv.style.height = (rect.height - 2) + 'px';
doc.documentElement.appendChild(overlayDiv);
$debugOverlays.push($(overlayDiv));
}
}
function drawDebugOverlayFromRect(rect) {
var leftOffset, topOffset;
if (isVerticalWritingMode()) {
leftOffset = 0;
topOffset = -getPaginationLeftOffset();
} else {
leftOffset = -getPaginationLeftOffset();
topOffset = 0;
}
addOverlayRect({
left: rect.left + leftOffset,
top: rect.top + topOffset,
width: rect.width,
height: rect.height
}, true, self.getRootDocument());
}
function drawDebugOverlayFromDomRange(range) {
var rect = getNodeRangeClientRect(
range.startContainer,
range.startOffset,
range.endContainer,
range.endOffset);
drawDebugOverlayFromRect(rect);
return rect;
}
function drawDebugOverlayFromNode(node) {
drawDebugOverlayFromRect(getNodeClientRect(node));
}
function getPaginationLeftOffset() {
var $htmlElement = $("html", self.getRootDocument());
var offsetLeftPixels = $htmlElement.css(isVerticalWritingMode() ? "top" : (isPageProgressionRightToLeft() ? "right" : "left"));
var offsetLeft = parseInt(offsetLeftPixels.replace("px", ""));
if (isNaN(offsetLeft)) {
//for fixed layouts, $htmlElement.css("left") has no numerical value
offsetLeft = 0;
}
if (isPageProgressionRightToLeft() && !isVerticalWritingMode()) return -offsetLeft;
return offsetLeft;
}
function clearDebugOverlays() {
_.each($debugOverlays, function($el){
$el.remove();
});
$debugOverlays.clear();
}
ReadiumSDK._DEBUG_CfiNavigationLogic = {
clearDebugOverlays: clearDebugOverlays,
drawDebugOverlayFromRect: drawDebugOverlayFromRect,
drawDebugOverlayFromDomRange: drawDebugOverlayFromDomRange,
drawDebugOverlayFromNode: drawDebugOverlayFromNode,
debugVisibleCfis: function () {
console.log(JSON.stringify(ReadiumSDK.reader.getPaginationInfo().openPages));
var cfi1 = ReadiumSDK.reader.getFirstVisibleCfi();
var range1 = ReadiumSDK.reader.getDomRangeFromRangeCfi(cfi1);
console.log(cfi1, range1, drawDebugOverlayFromDomRange(range1));
var cfi2 = ReadiumSDK.reader.getLastVisibleCfi();
var range2 = ReadiumSDK.reader.getDomRangeFromRangeCfi(cfi2);
console.log(cfi2, range2, drawDebugOverlayFromDomRange(range2));
}
};
//
// }
};
return CfiNavigationLogic;
});
|
added DEBUG boolean flag for CFI navigation logic (to remove noisy console
logging in Internet Explorer, and also vertical writing mode in other web
browsers)
|
js/views/cfi_navigation_logic.js
|
added DEBUG boolean flag for CFI navigation logic (to remove noisy console logging in Internet Explorer, and also vertical writing mode in other web browsers)
|
<ide><path>s/views/cfi_navigation_logic.js
<ide> }
<ide> }
<ide>
<add> var DEBUG = false;
<add>
<ide> function getVisibleTextRangeOffsetsSelectedByFunc(textNode, pickerFunc, visibleContentOffsets, frameDimensions) {
<ide> visibleContentOffsets = visibleContentOffsets || getVisibleContentOffsets();
<ide>
<ide> fragmentCorner.y -= visibleContentOffsets.top;
<ide>
<ide> var caretRange = getCaretRangeFromPoint(fragmentCorner.x, fragmentCorner.y);
<add>
<add> if (DEBUG)
<ide> console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'a0');
<add>
<ide> // Desperately try to find it from all angles! Darn sub pixeling..
<ide> //TODO: remove the need for this brute-force method, since it's making the result non-deterministic
<ide> if (!caretRange || caretRange.startContainer !== textNode) {
<ide> caretRange = getCaretRangeFromPoint(fragmentCorner.x - 1, fragmentCorner.y);
<add>
<add> if (DEBUG)
<ide> console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'a1');
<ide> }
<ide> if (!caretRange || caretRange.startContainer !== textNode) {
<ide> caretRange = getCaretRangeFromPoint(fragmentCorner.x, fragmentCorner.y - 1);
<add>
<add> if (DEBUG)
<ide> console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'a2');
<ide> }
<ide> if (!caretRange || caretRange.startContainer !== textNode) {
<ide> caretRange = getCaretRangeFromPoint(fragmentCorner.x - 1, fragmentCorner.y - 1);
<add>
<add> if (DEBUG)
<ide> console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'a3');
<ide> }
<ide> if (!caretRange || caretRange.startContainer !== textNode) {
<ide> fragmentCorner.x = Math.floor(fragmentCorner.x);
<ide> fragmentCorner.y = Math.floor(fragmentCorner.y);
<ide> caretRange = getCaretRangeFromPoint(fragmentCorner.x, fragmentCorner.y);
<add>
<add> if (DEBUG)
<ide> console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'b0');
<ide> }
<ide> // Desperately try to find it from all angles! Darn sub pixeling..
<ide> if (!caretRange || caretRange.startContainer !== textNode) {
<ide> caretRange = getCaretRangeFromPoint(fragmentCorner.x - 1, fragmentCorner.y);
<add>
<add> if (DEBUG)
<ide> console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'b1');
<ide> }
<ide> if (!caretRange || caretRange.startContainer !== textNode) {
<ide> caretRange = getCaretRangeFromPoint(fragmentCorner.x, fragmentCorner.y - 1);
<add>
<add> if (DEBUG)
<ide> console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'b2');
<ide> }
<ide> if (!caretRange || caretRange.startContainer !== textNode) {
<ide> caretRange = getCaretRangeFromPoint(fragmentCorner.x - 1, fragmentCorner.y - 1);
<add>
<add> if (DEBUG)
<ide> console.log('getVisibleTextRangeOffsetsSelectedByFunc: ', 'b3');
<ide> }
<ide>
<ide> // Still nothing? fall through..
<ide> if (!caretRange) {
<add>
<add> if (DEBUG)
<ide> console.warn('getVisibleTextRangeOffsetsSelectedByFunc: no caret range result');
<add>
<ide> return null;
<ide> }
<ide>
<ide> {start: caretRange.startOffset - 1, end: caretRange.startOffset}]
<ide> );
<ide> } else {
<add>
<add> if (DEBUG)
<ide> console.warn('getVisibleTextRangeOffsetsSelectedByFunc: incorrect caret range result');
<add>
<ide> return null;
<ide> }
<ide> }
|
|
Java
|
mit
|
7a82de2f56cb196ca8b626543c1d6cf4d9608f75
| 0 |
microsoftgraph/msgraph-sdk-java
|
// ------------------------------------------------------------------------------
// Copyright (c) 2017 Microsoft Corporation
//
// 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, sub-license, 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.microsoft.graph.serializer;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CaseFormat;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.microsoft.graph.logger.ILogger;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* The default serializer implementation for the SDK
*/
public class DefaultSerializer implements ISerializer {
/**
* The instance of the internal serializer
*/
private final Gson gson;
/**
* The logger
*/
private final ILogger logger;
/**
* Creates a DefaultSerializer
*
* @param logger the logger
*/
public DefaultSerializer(final ILogger logger) {
this.logger = logger;
this.gson = GsonFactory.getGsonInstance(logger);
}
/**
* Deserializes an object from the input string
*
* @param inputString the string that stores the representation of the item
* @param clazz the class of the item to be deserialized
* @param <T> the type of the item to be deserialized
* @return the deserialized item from the input string
*/
@Override
public <T> T deserializeObject(final String inputString, final Class<T> clazz) {
return deserializeObject(inputString, clazz, null);
}
private static final String graphResponseHeadersKey = "graphResponseHeaders";
@SuppressWarnings("unchecked")
@Override
public <T> T deserializeObject(final String inputString, final Class<T> clazz, Map<String, java.util.List<String>> responseHeaders) {
final T jsonObject = gson.fromJson(inputString, clazz);
// Populate the JSON-backed fields for any annotations that are not in the object model
if (jsonObject instanceof IJsonBackedObject) {
logger.logDebug("Deserializing type " + clazz.getSimpleName());
final JsonObject rawObject = gson.fromJson(inputString, JsonObject.class);
// If there is a derived class, try to get it and deserialize to it
Class<?> derivedClass = this.getDerivedClass(rawObject, clazz);
final T jo;
if (derivedClass != null) {
jo = (T) gson.fromJson(inputString, derivedClass);
} else {
jo = jsonObject;
}
final IJsonBackedObject jsonBackedObject = (IJsonBackedObject) jo;
jsonBackedObject.setRawObject(this, rawObject);
if (responseHeaders != null) {
JsonElement convertedHeaders = gson.toJsonTree(responseHeaders);
jsonBackedObject.additionalDataManager().put(graphResponseHeadersKey, convertedHeaders);
}
jsonBackedObject.additionalDataManager().setAdditionalData(rawObject);
setChildAdditionalData(jsonBackedObject,rawObject);
return jo;
} else {
logger.logDebug("Deserializing a non-IJsonBackedObject type " + clazz.getSimpleName());
return jsonObject;
}
}
/**
* Recursively sets additional data for each child object
*
* @param serializedObject the parent object whose children will be iterated to set additional data
* @param rawJson the raw json
*/
@SuppressWarnings("unchecked")
private void setChildAdditionalData(IJsonBackedObject serializedObject, JsonObject rawJson) {
// Use reflection to iterate through fields for eligible Graph children
for (java.lang.reflect.Field field : serializedObject.getClass().getFields()) {
try {
Object fieldObject = field.get(serializedObject);
// If the object is a HashMap, iterate through its children
if (fieldObject instanceof HashMap) {
HashMap<String, Object> serializableChildren = (HashMap<String, Object>) fieldObject;
Iterator<Entry<String, Object>> it = serializableChildren.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Object> pair = (Map.Entry<String, Object>)it.next();
Object child = pair.getValue();
// If the item is a valid Graph object, set its additional data
if (child instanceof IJsonBackedObject) {
AdditionalDataManager childAdditionalDataManager = ((IJsonBackedObject) child).additionalDataManager();
if(rawJson != null && field != null && rawJson.get(field.getName()) != null && rawJson.get(field.getName()).isJsonObject()
&& rawJson.get(field.getName()).getAsJsonObject().get(pair.getKey()).isJsonObject()) {
childAdditionalDataManager.setAdditionalData(rawJson.get(field.getName()).getAsJsonObject().get(pair.getKey()).getAsJsonObject());
setChildAdditionalData((IJsonBackedObject) child,rawJson.get(field.getName()).getAsJsonObject().get(pair.getKey()).getAsJsonObject());
}
}
}
}
// If the object is a list of Graph objects, iterate through elements
else if (fieldObject instanceof List && rawJson != null) {
final JsonElement collectionJson = rawJson.get(field.getName());
final List<?> fieldObjectList = (List<?>) fieldObject;
if (collectionJson.isJsonArray() && ((JsonArray)collectionJson).size() == fieldObjectList.size()) {
final JsonArray rawJsonArray = (JsonArray) collectionJson;
for (int i = 0; i < fieldObjectList.size(); i++) {
final Object element = fieldObjectList.get(i);
if (element instanceof IJsonBackedObject) {
final JsonElement elementRawJson = rawJsonArray.get(i);
setChildAdditionalData((IJsonBackedObject) element, elementRawJson.getAsJsonObject());
}
}
}
}
// If the object is a valid Graph object, set its additional data
else if (fieldObject != null && fieldObject instanceof IJsonBackedObject) {
IJsonBackedObject serializedChild = (IJsonBackedObject) fieldObject;
AdditionalDataManager childAdditionalDataManager = serializedChild.additionalDataManager();
if(rawJson != null && field != null && rawJson.get(field.getName()) != null && rawJson.get(field.getName()).isJsonObject()) {
childAdditionalDataManager.setAdditionalData(rawJson.get(field.getName()).getAsJsonObject());
setChildAdditionalData((IJsonBackedObject) fieldObject,rawJson.get(field.getName()).getAsJsonObject());
}
}
} catch (IllegalArgumentException | IllegalAccessException e) {
logger.logError("Unable to access child fields of " + serializedObject.getClass().getSimpleName(), e);
}
}
}
/**
* Serializes an object into a string
*
* @param serializableObject the object to convert into a string
* @param <T> the type of the item to be serialized
* @return the string representation of that item
*/
@Override
public <T> String serializeObject(final T serializableObject) {
logger.logDebug("Serializing type " + serializableObject.getClass().getSimpleName());
JsonElement outJsonTree = gson.toJsonTree(serializableObject);
if (serializableObject instanceof IJsonBackedObject) {
IJsonBackedObject serializableJsonObject = (IJsonBackedObject) serializableObject;
AdditionalDataManager additionalData = serializableJsonObject.additionalDataManager();
// If the item is a valid Graph object, add its additional data
if (outJsonTree.isJsonObject()) {
JsonObject outJson = outJsonTree.getAsJsonObject();
addAdditionalDataToJson(additionalData, outJson);
outJson = getChildAdditionalData(serializableJsonObject, outJson);
outJsonTree = outJson;
}
}
return outJsonTree.toString();
}
/**
* Recursively populates additional data for each child object
*
* @param serializableObject the child to get additional data for
* @param outJson the serialized output JSON to add to
* @return the serialized output JSON including the additional child data
*/
@SuppressWarnings("unchecked")
private JsonObject getChildAdditionalData(IJsonBackedObject serializableObject, JsonObject outJson) {
// Use reflection to iterate through fields for eligible Graph children
for (java.lang.reflect.Field field : serializableObject.getClass().getFields()) {
try {
Object fieldObject = field.get(serializableObject);
// If the object is a HashMap, iterate through its children
if (fieldObject instanceof HashMap) {
HashMap<String, Object> serializableChildren = (HashMap<String, Object>) fieldObject;
Iterator<Entry<String, Object>> it = serializableChildren.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Object> pair = (Map.Entry<String, Object>)it.next();
Object child = pair.getValue();
// If the item is a valid Graph object, add its additional data
if (child instanceof IJsonBackedObject) {
AdditionalDataManager childAdditionalData = ((IJsonBackedObject) child).additionalDataManager();
addAdditionalDataToJson(
childAdditionalData,
outJson.getAsJsonObject(
field.getName())
.getAsJsonObject()
.get(pair.getKey()
.toString())
.getAsJsonObject());
// Serialize its children
outJson = getChildAdditionalData((IJsonBackedObject)child, outJson);
}
}
}
// If the object is a valid Graph object, add its additional data
else if (fieldObject != null && fieldObject instanceof IJsonBackedObject) {
IJsonBackedObject serializableChild = (IJsonBackedObject) fieldObject;
AdditionalDataManager childAdditionalData = serializableChild.additionalDataManager();
if(outJson != null && field != null && outJson.get(field.getName()) != null && outJson.get(field.getName()).isJsonObject()) {
addAdditionalDataToJson(childAdditionalData, outJson.get(field.getName()).getAsJsonObject());
}
// Serialize its children
outJson = getChildAdditionalData(serializableChild, outJson);
}
} catch (IllegalArgumentException | IllegalAccessException e) {
logger.logError("Unable to access child fields of " + serializableObject.getClass().getSimpleName(), e);
}
}
return outJson;
}
/**
* Add each non-transient additional data property to the given JSON node
*
* @param additionalDataManager the additional data bag to iterate through
* @param jsonNode the JSON node to add the additional data properties to
*/
private void addAdditionalDataToJson(AdditionalDataManager additionalDataManager, JsonObject jsonNode) {
for (Map.Entry<String, JsonElement> entry : additionalDataManager.entrySet()) {
if(!entry.getKey().equals(graphResponseHeadersKey)) {
jsonNode.add(entry.getKey(), entry.getValue());
}
}
}
/**
* Get the derived class for the given JSON object
* This covers scenarios in which the service may return one of several derived types
* of a base object, which it defines using the odata.type parameter
*
* @param jsonObject the raw JSON object of the response
* @param parentClass the parent class the derived class should inherit from
* @return the derived class if found, or null if not applicable
*/
private Class<?> getDerivedClass(JsonObject jsonObject, Class<?> parentClass) {
//Identify the odata.type information if provided
if (jsonObject.get("@odata.type") != null) {
String odataType = jsonObject.get("@odata.type").getAsString();
String derivedType = odataType.substring(odataType.lastIndexOf('.') + 1); //Remove microsoft.graph prefix
derivedType = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, derivedType);
derivedType = "com.microsoft.graph.models.extensions." + derivedType; //Add full package path
try {
Class<?> derivedClass = Class.forName(derivedType);
//Check that the derived class inherits from the given parent class
if (parentClass.isAssignableFrom(derivedClass)) {
return derivedClass;
}
return null;
} catch (ClassNotFoundException e) {
logger.logDebug("Unable to find a corresponding class for derived type " + derivedType + ". Falling back to parent class.");
//If we cannot determine the derived type to cast to, return null
//This may happen if the API and the SDK are out of sync
return null;
}
}
//If there is no defined OData type, return null
return null;
}
@VisibleForTesting
public ILogger getLogger() {
return logger;
}
}
|
src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java
|
// ------------------------------------------------------------------------------
// Copyright (c) 2017 Microsoft Corporation
//
// 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, sub-license, 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.microsoft.graph.serializer;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CaseFormat;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.microsoft.graph.logger.ILogger;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* The default serializer implementation for the SDK
*/
public class DefaultSerializer implements ISerializer {
/**
* The instance of the internal serializer
*/
private final Gson gson;
/**
* The logger
*/
private final ILogger logger;
/**
* Creates a DefaultSerializer
*
* @param logger the logger
*/
public DefaultSerializer(final ILogger logger) {
this.logger = logger;
this.gson = GsonFactory.getGsonInstance(logger);
}
/**
* Deserializes an object from the input string
*
* @param inputString the string that stores the representation of the item
* @param clazz the class of the item to be deserialized
* @param <T> the type of the item to be deserialized
* @return the deserialized item from the input string
*/
@Override
public <T> T deserializeObject(final String inputString, final Class<T> clazz) {
return deserializeObject(inputString, clazz, null);
}
@SuppressWarnings("unchecked")
@Override
public <T> T deserializeObject(final String inputString, final Class<T> clazz, Map<String, java.util.List<String>> responseHeaders) {
final T jsonObject = gson.fromJson(inputString, clazz);
// Populate the JSON-backed fields for any annotations that are not in the object model
if (jsonObject instanceof IJsonBackedObject) {
logger.logDebug("Deserializing type " + clazz.getSimpleName());
final JsonObject rawObject = gson.fromJson(inputString, JsonObject.class);
// If there is a derived class, try to get it and deserialize to it
Class<?> derivedClass = this.getDerivedClass(rawObject, clazz);
final T jo;
if (derivedClass != null) {
jo = (T) gson.fromJson(inputString, derivedClass);
} else {
jo = jsonObject;
}
final IJsonBackedObject jsonBackedObject = (IJsonBackedObject) jo;
jsonBackedObject.setRawObject(this, rawObject);
if (responseHeaders != null) {
JsonElement convertedHeaders = gson.toJsonTree(responseHeaders);
jsonBackedObject.additionalDataManager().put("graphResponseHeaders", convertedHeaders);
}
jsonBackedObject.additionalDataManager().setAdditionalData(rawObject);
setChildAdditionalData(jsonBackedObject,rawObject);
return jo;
} else {
logger.logDebug("Deserializing a non-IJsonBackedObject type " + clazz.getSimpleName());
return jsonObject;
}
}
/**
* Recursively sets additional data for each child object
*
* @param serializedObject the parent object whose children will be iterated to set additional data
* @param rawJson the raw json
*/
@SuppressWarnings("unchecked")
private void setChildAdditionalData(IJsonBackedObject serializedObject, JsonObject rawJson) {
// Use reflection to iterate through fields for eligible Graph children
for (java.lang.reflect.Field field : serializedObject.getClass().getFields()) {
try {
Object fieldObject = field.get(serializedObject);
// If the object is a HashMap, iterate through its children
if (fieldObject instanceof HashMap) {
HashMap<String, Object> serializableChildren = (HashMap<String, Object>) fieldObject;
Iterator<Entry<String, Object>> it = serializableChildren.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Object> pair = (Map.Entry<String, Object>)it.next();
Object child = pair.getValue();
// If the item is a valid Graph object, set its additional data
if (child instanceof IJsonBackedObject) {
AdditionalDataManager childAdditionalDataManager = ((IJsonBackedObject) child).additionalDataManager();
if(rawJson != null && field != null && rawJson.get(field.getName()) != null && rawJson.get(field.getName()).isJsonObject()
&& rawJson.get(field.getName()).getAsJsonObject().get(pair.getKey()).isJsonObject()) {
childAdditionalDataManager.setAdditionalData(rawJson.get(field.getName()).getAsJsonObject().get(pair.getKey()).getAsJsonObject());
setChildAdditionalData((IJsonBackedObject) child,rawJson.get(field.getName()).getAsJsonObject().get(pair.getKey()).getAsJsonObject());
}
}
}
}
// If the object is a list of Graph objects, iterate through elements
else if (fieldObject instanceof List && rawJson != null) {
final JsonElement collectionJson = rawJson.get(field.getName());
final List<?> fieldObjectList = (List<?>) fieldObject;
if (collectionJson.isJsonArray() && ((JsonArray)collectionJson).size() == fieldObjectList.size()) {
final JsonArray rawJsonArray = (JsonArray) collectionJson;
for (int i = 0; i < fieldObjectList.size(); i++) {
final Object element = fieldObjectList.get(i);
if (element instanceof IJsonBackedObject) {
final JsonElement elementRawJson = rawJsonArray.get(i);
setChildAdditionalData((IJsonBackedObject) element, elementRawJson.getAsJsonObject());
}
}
}
}
// If the object is a valid Graph object, set its additional data
else if (fieldObject != null && fieldObject instanceof IJsonBackedObject) {
IJsonBackedObject serializedChild = (IJsonBackedObject) fieldObject;
AdditionalDataManager childAdditionalDataManager = serializedChild.additionalDataManager();
if(rawJson != null && field != null && rawJson.get(field.getName()) != null && rawJson.get(field.getName()).isJsonObject()) {
childAdditionalDataManager.setAdditionalData(rawJson.get(field.getName()).getAsJsonObject());
setChildAdditionalData((IJsonBackedObject) fieldObject,rawJson.get(field.getName()).getAsJsonObject());
}
}
} catch (IllegalArgumentException | IllegalAccessException e) {
logger.logError("Unable to access child fields of " + serializedObject.getClass().getSimpleName(), e);
}
}
}
/**
* Serializes an object into a string
*
* @param serializableObject the object to convert into a string
* @param <T> the type of the item to be serialized
* @return the string representation of that item
*/
@Override
public <T> String serializeObject(final T serializableObject) {
logger.logDebug("Serializing type " + serializableObject.getClass().getSimpleName());
JsonElement outJsonTree = gson.toJsonTree(serializableObject);
if (serializableObject instanceof IJsonBackedObject) {
IJsonBackedObject serializableJsonObject = (IJsonBackedObject) serializableObject;
AdditionalDataManager additionalData = serializableJsonObject.additionalDataManager();
// If the item is a valid Graph object, add its additional data
if (outJsonTree.isJsonObject()) {
JsonObject outJson = outJsonTree.getAsJsonObject();
addAdditionalDataToJson(additionalData, outJson);
outJson = getChildAdditionalData(serializableJsonObject, outJson);
outJsonTree = outJson;
}
}
return outJsonTree.toString();
}
/**
* Recursively populates additional data for each child object
*
* @param serializableObject the child to get additional data for
* @param outJson the serialized output JSON to add to
* @return the serialized output JSON including the additional child data
*/
@SuppressWarnings("unchecked")
private JsonObject getChildAdditionalData(IJsonBackedObject serializableObject, JsonObject outJson) {
// Use reflection to iterate through fields for eligible Graph children
for (java.lang.reflect.Field field : serializableObject.getClass().getFields()) {
try {
Object fieldObject = field.get(serializableObject);
// If the object is a HashMap, iterate through its children
if (fieldObject instanceof HashMap) {
HashMap<String, Object> serializableChildren = (HashMap<String, Object>) fieldObject;
Iterator<Entry<String, Object>> it = serializableChildren.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Object> pair = (Map.Entry<String, Object>)it.next();
Object child = pair.getValue();
// If the item is a valid Graph object, add its additional data
if (child instanceof IJsonBackedObject) {
AdditionalDataManager childAdditionalData = ((IJsonBackedObject) child).additionalDataManager();
addAdditionalDataToJson(
childAdditionalData,
outJson.getAsJsonObject(
field.getName())
.getAsJsonObject()
.get(pair.getKey()
.toString())
.getAsJsonObject());
// Serialize its children
outJson = getChildAdditionalData((IJsonBackedObject)child, outJson);
}
}
}
// If the object is a valid Graph object, add its additional data
else if (fieldObject != null && fieldObject instanceof IJsonBackedObject) {
IJsonBackedObject serializableChild = (IJsonBackedObject) fieldObject;
AdditionalDataManager childAdditionalData = serializableChild.additionalDataManager();
if(outJson != null && field != null && outJson.get(field.getName()) != null && outJson.get(field.getName()).isJsonObject()) {
addAdditionalDataToJson(childAdditionalData, outJson.get(field.getName()).getAsJsonObject());
}
// Serialize its children
outJson = getChildAdditionalData(serializableChild, outJson);
}
} catch (IllegalArgumentException | IllegalAccessException e) {
logger.logError("Unable to access child fields of " + serializableObject.getClass().getSimpleName(), e);
}
}
return outJson;
}
/**
* Add each non-transient additional data property to the given JSON node
*
* @param additionalDataManager the additional data bag to iterate through
* @param jsonNode the JSON node to add the additional data properties to
*/
private void addAdditionalDataToJson(AdditionalDataManager additionalDataManager, JsonObject jsonNode) {
for (Map.Entry<String, JsonElement> entry : additionalDataManager.entrySet()) {
jsonNode.add(entry.getKey(), entry.getValue());
}
}
/**
* Get the derived class for the given JSON object
* This covers scenarios in which the service may return one of several derived types
* of a base object, which it defines using the odata.type parameter
*
* @param jsonObject the raw JSON object of the response
* @param parentClass the parent class the derived class should inherit from
* @return the derived class if found, or null if not applicable
*/
private Class<?> getDerivedClass(JsonObject jsonObject, Class<?> parentClass) {
//Identify the odata.type information if provided
if (jsonObject.get("@odata.type") != null) {
String odataType = jsonObject.get("@odata.type").getAsString();
String derivedType = odataType.substring(odataType.lastIndexOf('.') + 1); //Remove microsoft.graph prefix
derivedType = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, derivedType);
derivedType = "com.microsoft.graph.models.extensions." + derivedType; //Add full package path
try {
Class<?> derivedClass = Class.forName(derivedType);
//Check that the derived class inherits from the given parent class
if (parentClass.isAssignableFrom(derivedClass)) {
return derivedClass;
}
return null;
} catch (ClassNotFoundException e) {
logger.logDebug("Unable to find a corresponding class for derived type " + derivedType + ". Falling back to parent class.");
//If we cannot determine the derived type to cast to, return null
//This may happen if the API and the SDK are out of sync
return null;
}
}
//If there is no defined OData type, return null
return null;
}
@VisibleForTesting
public ILogger getLogger() {
return logger;
}
}
|
- fixes an issue where responses headers would be serialized with subsequent requests
|
src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java
|
- fixes an issue where responses headers would be serialized with subsequent requests
|
<ide><path>rc/main/java/com/microsoft/graph/serializer/DefaultSerializer.java
<ide> public <T> T deserializeObject(final String inputString, final Class<T> clazz) {
<ide> return deserializeObject(inputString, clazz, null);
<ide> }
<del>
<add> private static final String graphResponseHeadersKey = "graphResponseHeaders";
<ide> @SuppressWarnings("unchecked")
<ide> @Override
<ide> public <T> T deserializeObject(final String inputString, final Class<T> clazz, Map<String, java.util.List<String>> responseHeaders) {
<ide>
<ide> if (responseHeaders != null) {
<ide> JsonElement convertedHeaders = gson.toJsonTree(responseHeaders);
<del> jsonBackedObject.additionalDataManager().put("graphResponseHeaders", convertedHeaders);
<add> jsonBackedObject.additionalDataManager().put(graphResponseHeadersKey, convertedHeaders);
<ide> }
<ide>
<ide> jsonBackedObject.additionalDataManager().setAdditionalData(rawObject);
<ide> */
<ide> private void addAdditionalDataToJson(AdditionalDataManager additionalDataManager, JsonObject jsonNode) {
<ide> for (Map.Entry<String, JsonElement> entry : additionalDataManager.entrySet()) {
<add> if(!entry.getKey().equals(graphResponseHeadersKey)) {
<ide> jsonNode.add(entry.getKey(), entry.getValue());
<add> }
<ide> }
<ide> }
<ide>
|
|
Java
|
apache-2.0
|
5bdff1ac1bc330cc900b7dcd83bb8f55cb9f7fcd
| 0 |
virtuoushub/mavennatives,virtuoushub/mavennatives
|
package com.googlecode.mavennatives.nativedependencies;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.apache.commons.io.IOUtils;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugin.logging.SystemStreamLog;
import org.codehaus.plexus.component.annotations.Component;
@Component(role = IJarUnpacker.class)
public class JarUnpacker implements IJarUnpacker
{
private Log log = new SystemStreamLog();
public void copyJarContent(File jarPath, File targetDir) throws IOException
{
log.info("Copying natives from " + jarPath.getName());
JarFile jar = new JarFile(jarPath);
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements())
{
JarEntry file = entries.nextElement();
File f = new File(targetDir, file.getName());
log.info("Copying native - " + file.getName());
File parentFile = f.getParentFile();
parentFile.mkdirs();
if (file.isDirectory())
{ // if its a directory, create it
f.mkdir();
continue;
}
InputStream is = null;
FileOutputStream fos = null;
try
{
is = jar.getInputStream(file); // get the input stream
fos = new FileOutputStream(f);
IOUtils.copy(is, fos);
}
finally
{
if (fos != null)
fos.close();
if (is != null)
is.close();
}
}
}
}
|
maven-nativedependencies-plugin/src/main/java/com/googlecode/mavennatives/nativedependencies/JarUnpacker.java
|
package com.googlecode.mavennatives.nativedependencies;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugin.logging.SystemStreamLog;
import org.codehaus.plexus.component.annotations.Component;
@Component(role = IJarUnpacker.class)
public class JarUnpacker implements IJarUnpacker
{
private Log log = new SystemStreamLog();
@Override
public void copyJarContent(File jarPath, File targetDir) throws IOException
{
log.info("Copying natives from " + jarPath.getName());
JarFile jar = new JarFile(jarPath);
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements())
{
JarEntry file = entries.nextElement();
File f = new File(targetDir, file.getName());
log.info("Copying native - " + file.getName());
if (file.isDirectory())
{ // if its a directory, create it
f.mkdir();
continue;
}
InputStream is = null;
FileOutputStream fos = null;
try
{
is = jar.getInputStream(file); // get the input stream
fos = new FileOutputStream(f);
IOUtils.copy(is, fos);
}
finally
{
if (fos != null)
fos.close();
if (is != null)
is.close();
}
}
}
}
|
added parentFile.mkdirs() to fix a bug when the folders of the jar to decompress don't exists. (example: /META-INF for the MANIFEST file)
git-svn-id: ba1c8dd803690b42159dec359480c3e5fc2a5710@71 14773fa0-5302-11de-bb24-2d5e9b4af41d
|
maven-nativedependencies-plugin/src/main/java/com/googlecode/mavennatives/nativedependencies/JarUnpacker.java
|
added parentFile.mkdirs() to fix a bug when the folders of the jar to decompress don't exists. (example: /META-INF for the MANIFEST file)
|
<ide><path>aven-nativedependencies-plugin/src/main/java/com/googlecode/mavennatives/nativedependencies/JarUnpacker.java
<ide> import java.util.jar.JarEntry;
<ide> import java.util.jar.JarFile;
<ide>
<del>import org.apache.commons.io.FileUtils;
<ide> import org.apache.commons.io.IOUtils;
<ide> import org.apache.maven.plugin.logging.Log;
<ide> import org.apache.maven.plugin.logging.SystemStreamLog;
<ide> @Component(role = IJarUnpacker.class)
<ide> public class JarUnpacker implements IJarUnpacker
<ide> {
<del>
<ide> private Log log = new SystemStreamLog();
<ide>
<del> @Override
<ide> public void copyJarContent(File jarPath, File targetDir) throws IOException
<ide> {
<ide> log.info("Copying natives from " + jarPath.getName());
<ide> File f = new File(targetDir, file.getName());
<ide>
<ide> log.info("Copying native - " + file.getName());
<add>
<add> File parentFile = f.getParentFile();
<add> parentFile.mkdirs();
<add>
<ide> if (file.isDirectory())
<ide> { // if its a directory, create it
<ide> f.mkdir();
|
|
Java
|
apache-2.0
|
d90f5078ca29bfbe09836090ba8d8e0193abe431
| 0 |
bladecoder/bladecoder-adventure-engine,bladecoder/bladecoder-adventure-engine
|
/*******************************************************************************
* Copyright 2014 Rafael Garcia Moreno.
*
* 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.bladecoder.engine.actions;
import com.bladecoder.engine.model.BaseActor;
import com.bladecoder.engine.model.InteractiveActor;
import com.bladecoder.engine.model.Scene;
import com.bladecoder.engine.model.SpriteActor;
import com.bladecoder.engine.model.VerbRunner;
import com.bladecoder.engine.model.World;
import com.bladecoder.engine.util.ActionUtils;
import com.bladecoder.engine.util.EngineLogger;
@ActionDescription("Execute the actions inside the If/EndIf if the attribute has the specified value.")
public class IfAttrAction extends AbstractIfAction {
public static final String ENDTYPE_VALUE = "else";
public enum ActorAttribute {
STATE, VISIBLE, INTERACTIVE, IN_INVENTORY, TARGET
}
@ActionProperty
@ActionPropertyDescription("The target actor")
private SceneActorRef actor;
@ActionProperty(required = true, defaultValue = "STATE")
@ActionPropertyDescription("The actor attribute")
private ActorAttribute attr;
@ActionProperty
@ActionPropertyDescription("The attribute value")
private String value;
@Override
public boolean run(VerbRunner cb) {
Scene s = actor.getScene();
final String actorId = actor.getActorId();
if (actorId == null) {
// if called inside a scene verb and no actor is specified, return
EngineLogger.error(getClass() + ": No actor specified");
return false;
}
BaseActor a = s.getActor(actorId, true);
if (attr.equals(ActorAttribute.STATE) && a instanceof InteractiveActor) {
InteractiveActor ia = (InteractiveActor)a;
if (!ActionUtils.compareNullStr(value, ia.getState())) {
gotoElse((VerbRunner) cb);
}
} else if (attr.equals(ActorAttribute.VISIBLE)) {
boolean val = Boolean.parseBoolean(value);
if (val != a.isVisible()) {
gotoElse((VerbRunner) cb);
}
} else if (attr.equals(ActorAttribute.INTERACTIVE)) {
boolean val = Boolean.parseBoolean(value);
if(a instanceof InteractiveActor) {
if (val != ((InteractiveActor)a).getInteraction()) {
gotoElse((VerbRunner) cb);
}
} else if(val == true) {
gotoElse((VerbRunner) cb);
}
} else if (attr.equals(ActorAttribute.IN_INVENTORY)) {
boolean val = Boolean.parseBoolean(value);
SpriteActor item = null;
if(a != null)
item = World.getInstance().getInventory().getItem(a.getId());
if ((val && item == null) || (!val && item != null)) {
gotoElse((VerbRunner) cb);
}
} else if (attr.equals(ActorAttribute.TARGET)) {
if (!ActionUtils.compareNullStr(value, cb.getTarget())) {
gotoElse((VerbRunner) cb);
}
}
return false;
}
}
|
blade-engine/src/com/bladecoder/engine/actions/IfAttrAction.java
|
/*******************************************************************************
* Copyright 2014 Rafael Garcia Moreno.
*
* 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.bladecoder.engine.actions;
import com.bladecoder.engine.model.BaseActor;
import com.bladecoder.engine.model.InteractiveActor;
import com.bladecoder.engine.model.Scene;
import com.bladecoder.engine.model.SpriteActor;
import com.bladecoder.engine.model.VerbRunner;
import com.bladecoder.engine.model.World;
import com.bladecoder.engine.util.ActionUtils;
import com.bladecoder.engine.util.EngineLogger;
@ActionDescription("Execute the actions inside the If/EndIf if the attribute has the specified value.")
public class IfAttrAction extends AbstractIfAction {
public static final String ENDTYPE_VALUE = "else";
public enum ActorAttribute {
STATE, VISIBLE, INTERACTIVE, IN_INVENTORY, TARGET
}
@ActionProperty
@ActionPropertyDescription("The target actor")
private SceneActorRef actor;
@ActionProperty(required = true, defaultValue = "STATE")
@ActionPropertyDescription("The actor attribute")
private ActorAttribute attr;
@ActionProperty
@ActionPropertyDescription("The attribute value")
private String value;
@Override
public boolean run(VerbRunner cb) {
Scene s = actor.getScene();
final String actorId = actor.getActorId();
if (actorId == null) {
// if called inside a scene verb and no actor is specified, return
EngineLogger.error(getClass() + ": No actor specified");
return false;
}
BaseActor a = s.getActor(actorId, true);
if (attr.equals(ActorAttribute.STATE) && a instanceof InteractiveActor) {
InteractiveActor ia = (InteractiveActor)a;
if (!ActionUtils.compareNullStr(value, ia.getState())) {
gotoElse((VerbRunner) cb);
}
} else if (attr.equals(ActorAttribute.VISIBLE)) {
boolean val = Boolean.parseBoolean(value);
if (val != a.isVisible()) {
gotoElse((VerbRunner) cb);
}
} else if (attr.equals(ActorAttribute.INTERACTIVE)) {
boolean val = Boolean.parseBoolean(value);
if(a instanceof InteractiveActor) {
if (val != ((InteractiveActor)a).getInteraction()) {
gotoElse((VerbRunner) cb);
}
} else if(val == true) {
gotoElse((VerbRunner) cb);
}
} else if (attr.equals(ActorAttribute.IN_INVENTORY)) {
boolean val = Boolean.parseBoolean(value);
SpriteActor item = World.getInstance().getInventory().getItem(a.getId());
if ((val && item == null) || (!val && item != null)) {
gotoElse((VerbRunner) cb);
}
} else if (attr.equals(ActorAttribute.TARGET)) {
if (!ActionUtils.compareNullStr(value, cb.getTarget())) {
gotoElse((VerbRunner) cb);
}
}
return false;
}
}
|
Continue running verb when exception in action.
|
blade-engine/src/com/bladecoder/engine/actions/IfAttrAction.java
|
Continue running verb when exception in action.
|
<ide><path>lade-engine/src/com/bladecoder/engine/actions/IfAttrAction.java
<ide> } else if (attr.equals(ActorAttribute.IN_INVENTORY)) {
<ide> boolean val = Boolean.parseBoolean(value);
<ide>
<del> SpriteActor item = World.getInstance().getInventory().getItem(a.getId());
<add> SpriteActor item = null;
<add>
<add> if(a != null)
<add> item = World.getInstance().getInventory().getItem(a.getId());
<ide>
<ide> if ((val && item == null) || (!val && item != null)) {
<ide> gotoElse((VerbRunner) cb);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.