lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | mit | 313f85b7d50940ac2a38866388a07e255e905eda | 0 | student-capture/student-capture | package studentcapture.login;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
/**
* Custom login authentication for Spring Security
* Currently accepts "user" as username and password
*
* 2016-05-11
* Connected to DB
*
* @author Oskar Suikki, c13hbd
*/
@Component
public class LoginAuthentication implements AuthenticationProvider {
private static final String dbURI = "https://localhost:8443";
@Autowired
private RestTemplate requestSender;
/*
Login only works with users in the database.
If the username and password matches with the database,
the user will be given the role "ROLE_USER".
The role prevents authenticate() from being called more than once.
*/
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
String username = auth.getName().trim();
String password = auth.getCredentials().toString();
/*if(username.equals("user") && password.equals("user")) {
Authentication a = new UsernamePasswordAuthenticationToken(username, password);
return a;
} else {
return null;
}*/
if(checkUser(username, password)){
Collection<? extends GrantedAuthority> authorities =
Collections.singleton(new SimpleGrantedAuthority("ROLE_USER"));
Authentication a = new UsernamePasswordAuthenticationToken(username, password, authorities);
//a.setAuthenticated(arg0); //Should not be necessary
return a;
}
return null;
}
@Override
public boolean supports(Class<?> auth) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(auth));
}
public boolean checkUser(String username, String password) {
//Send request to DB and check if the username and password exists.
System.out.println("Checking user data in DB");
URI targetUrl = UriComponentsBuilder.fromUriString(dbURI)
.path("DB/login")
.queryParam("username", username)
.queryParam("pswd", password)
.build()
.toUri();
Boolean response = requestSender.getForObject(targetUrl, Boolean.class);
System.out.println("Boolean response received: Checkuser = " + response.toString());
return response;
}
}
| src/main/java/studentcapture/login/LoginAuthentication.java | package studentcapture.login;
import java.util.ArrayList;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
/**
* Custom login authentication for Spring Security
* Currently accepts "user" as username and password
* @author Oskar Suikki
*/
@Component
public class LoginAuthentication implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
String username = auth.getName().trim();
String password = auth.getCredentials().toString();
if(username.equals("user") && password.equals("user")) {
Authentication a = new UsernamePasswordAuthenticationToken(username, password);
return a;
} else {
return null;
}
}
@Override
public boolean supports(Class<?> auth) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(auth));
}
public boolean checkUser(String username, String password) {
//Send request to DB and check if the username and password exists.
return true;
}
}
| Login is connected to DB
Login only works with users in the database. Username and password is
sent to the database which returns true or false. | src/main/java/studentcapture/login/LoginAuthentication.java | Login is connected to DB | <ide><path>rc/main/java/studentcapture/login/LoginAuthentication.java
<ide> package studentcapture.login;
<ide>
<add>import java.net.URI;
<ide> import java.util.ArrayList;
<add>import java.util.Collection;
<add>import java.util.Collections;
<add>import java.util.HashMap;
<ide>
<add>import org.springframework.beans.factory.annotation.Autowired;
<ide> import org.springframework.security.authentication.AuthenticationProvider;
<ide> import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
<ide> import org.springframework.security.core.Authentication;
<ide> import org.springframework.security.core.AuthenticationException;
<add>import org.springframework.security.core.GrantedAuthority;
<add>import org.springframework.security.core.authority.SimpleGrantedAuthority;
<ide> import org.springframework.stereotype.Component;
<add>import org.springframework.web.client.RestTemplate;
<add>import org.springframework.web.util.UriComponentsBuilder;
<ide>
<ide> /**
<ide> * Custom login authentication for Spring Security
<ide> * Currently accepts "user" as username and password
<del> * @author Oskar Suikki
<add> *
<add> * 2016-05-11
<add> * Connected to DB
<add> *
<add> * @author Oskar Suikki, c13hbd
<ide> */
<ide> @Component
<ide> public class LoginAuthentication implements AuthenticationProvider {
<ide>
<add>
<add> private static final String dbURI = "https://localhost:8443";
<add>
<add> @Autowired
<add> private RestTemplate requestSender;
<add>
<add> /*
<add> Login only works with users in the database.
<add> If the username and password matches with the database,
<add> the user will be given the role "ROLE_USER".
<add> The role prevents authenticate() from being called more than once.
<add> */
<ide> @Override
<ide> public Authentication authenticate(Authentication auth) throws AuthenticationException {
<ide> String username = auth.getName().trim();
<ide> String password = auth.getCredentials().toString();
<del> if(username.equals("user") && password.equals("user")) {
<add> /*if(username.equals("user") && password.equals("user")) {
<ide> Authentication a = new UsernamePasswordAuthenticationToken(username, password);
<ide> return a;
<ide> } else {
<ide> return null;
<add> }*/
<add> if(checkUser(username, password)){
<add> Collection<? extends GrantedAuthority> authorities =
<add> Collections.singleton(new SimpleGrantedAuthority("ROLE_USER"));
<add> Authentication a = new UsernamePasswordAuthenticationToken(username, password, authorities);
<add> //a.setAuthenticated(arg0); //Should not be necessary
<add> return a;
<ide> }
<add>
<add> return null;
<ide> }
<ide>
<ide> @Override
<ide>
<ide> public boolean checkUser(String username, String password) {
<ide> //Send request to DB and check if the username and password exists.
<del> return true;
<add>
<add> System.out.println("Checking user data in DB");
<add>
<add> URI targetUrl = UriComponentsBuilder.fromUriString(dbURI)
<add> .path("DB/login")
<add> .queryParam("username", username)
<add> .queryParam("pswd", password)
<add> .build()
<add> .toUri();
<add>
<add> Boolean response = requestSender.getForObject(targetUrl, Boolean.class);
<add>
<add> System.out.println("Boolean response received: Checkuser = " + response.toString());
<add>
<add> return response;
<ide> }
<ide> } |
|
Java | mit | 0de942fbecf83873800343defacf0de09da02c2b | 0 | pselle/jenkins,sathiya-mit/jenkins,rsandell/jenkins,svanoort/jenkins,hemantojhaa/jenkins,bkmeneguello/jenkins,aduprat/jenkins,hashar/jenkins,intelchen/jenkins,varmenise/jenkins,hashar/jenkins,petermarcoen/jenkins,viqueen/jenkins,1and1/jenkins,arunsingh/jenkins,jglick/jenkins,amuniz/jenkins,aldaris/jenkins,FarmGeek4Life/jenkins,christ66/jenkins,ndeloof/jenkins,patbos/jenkins,SenolOzer/jenkins,recena/jenkins,viqueen/jenkins,jk47/jenkins,goldchang/jenkins,jenkinsci/jenkins,patbos/jenkins,petermarcoen/jenkins,292388900/jenkins,MarkEWaite/jenkins,mrooney/jenkins,hemantojhaa/jenkins,andresrc/jenkins,godfath3r/jenkins,stefanbrausch/hudson-main,github-api-test-org/jenkins,nandan4/Jenkins,liorhson/jenkins,azweb76/jenkins,arunsingh/jenkins,ChrisA89/jenkins,292388900/jenkins,wuwen5/jenkins,ikedam/jenkins,hashar/jenkins,amruthsoft9/Jenkis,kohsuke/hudson,verbitan/jenkins,lvotypko/jenkins,kohsuke/hudson,jcarrothers-sap/jenkins,lordofthejars/jenkins,chbiel/jenkins,olivergondza/jenkins,iterate/coding-dojo,gitaccountforprashant/gittest,protazy/jenkins,bkmeneguello/jenkins,stephenc/jenkins,my7seven/jenkins,Vlatombe/jenkins,svanoort/jenkins,vijayto/jenkins,aquarellian/jenkins,damianszczepanik/jenkins,jtnord/jenkins,morficus/jenkins,lvotypko/jenkins3,maikeffi/hudson,liupugong/jenkins,christ66/jenkins,arcivanov/jenkins,arcivanov/jenkins,dennisjlee/jenkins,mrobinet/jenkins,msrb/jenkins,alvarolobato/jenkins,h4ck3rm1k3/jenkins,morficus/jenkins,AustinKwang/jenkins,shahharsh/jenkins,goldchang/jenkins,mrobinet/jenkins,dariver/jenkins,bpzhang/jenkins,recena/jenkins,tfennelly/jenkins,patbos/jenkins,daniel-beck/jenkins,Jimilian/jenkins,noikiy/jenkins,thomassuckow/jenkins,FarmGeek4Life/jenkins,evernat/jenkins,evernat/jenkins,tfennelly/jenkins,lvotypko/jenkins3,ikedam/jenkins,abayer/jenkins,vijayto/jenkins,SenolOzer/jenkins,jcarrothers-sap/jenkins,CodeShane/jenkins,ChrisA89/jenkins,lilyJi/jenkins,vlajos/jenkins,brunocvcunha/jenkins,aquarellian/jenkins,mpeltonen/jenkins,liupugong/jenkins,hemantojhaa/jenkins,deadmoose/jenkins,ChrisA89/jenkins,vvv444/jenkins,guoxu0514/jenkins,jpederzolli/jenkins-1,KostyaSha/jenkins,varmenise/jenkins,FarmGeek4Life/jenkins,duzifang/my-jenkins,protazy/jenkins,deadmoose/jenkins,hudson/hudson-2.x,mattclark/jenkins,dennisjlee/jenkins,paulmillar/jenkins,azweb76/jenkins,ErikVerheul/jenkins,jzjzjzj/jenkins,paulwellnerbou/jenkins,mpeltonen/jenkins,soenter/jenkins,292388900/jenkins,everyonce/jenkins,lilyJi/jenkins,vivek/hudson,akshayabd/jenkins,liorhson/jenkins,alvarolobato/jenkins,tastatur/jenkins,elkingtonmcb/jenkins,ErikVerheul/jenkins,gitaccountforprashant/gittest,rashmikanta-1984/jenkins,synopsys-arc-oss/jenkins,sathiya-mit/jenkins,csimons/jenkins,lindzh/jenkins,jpederzolli/jenkins-1,khmarbaise/jenkins,jpbriend/jenkins,my7seven/jenkins,vjuranek/jenkins,DoctorQ/jenkins,lvotypko/jenkins2,1and1/jenkins,jhoblitt/jenkins,ajshastri/jenkins,huybrechts/hudson,akshayabd/jenkins,morficus/jenkins,seanlin816/jenkins,AustinKwang/jenkins,hplatou/jenkins,Jochen-A-Fuerbacher/jenkins,maikeffi/hudson,protazy/jenkins,samatdav/jenkins,dennisjlee/jenkins,samatdav/jenkins,bpzhang/jenkins,akshayabd/jenkins,hashar/jenkins,amruthsoft9/Jenkis,albers/jenkins,jcarrothers-sap/jenkins,csimons/jenkins,Ykus/jenkins,Wilfred/jenkins,NehemiahMi/jenkins,arcivanov/jenkins,aldaris/jenkins,jzjzjzj/jenkins,tfennelly/jenkins,azweb76/jenkins,gitaccountforprashant/gittest,samatdav/jenkins,ndeloof/jenkins,aquarellian/jenkins,viqueen/jenkins,shahharsh/jenkins,aldaris/jenkins,iqstack/jenkins,arunsingh/jenkins,thomassuckow/jenkins,tfennelly/jenkins,keyurpatankar/hudson,goldchang/jenkins,iqstack/jenkins,jcsirot/jenkins,singh88/jenkins,liorhson/jenkins,verbitan/jenkins,batmat/jenkins,Vlatombe/jenkins,paulwellnerbou/jenkins,DanielWeber/jenkins,wangyikai/jenkins,Ykus/jenkins,luoqii/jenkins,hudson/hudson-2.x,amuniz/jenkins,soenter/jenkins,wangyikai/jenkins,hashar/jenkins,hplatou/jenkins,CodeShane/jenkins,my7seven/jenkins,singh88/jenkins,Jochen-A-Fuerbacher/jenkins,lvotypko/jenkins3,deadmoose/jenkins,lvotypko/jenkins2,shahharsh/jenkins,jenkinsci/jenkins,jhoblitt/jenkins,noikiy/jenkins,tangkun75/jenkins,SebastienGllmt/jenkins,oleg-nenashev/jenkins,pjanouse/jenkins,olivergondza/jenkins,vijayto/jenkins,intelchen/jenkins,abayer/jenkins,pantheon-systems/jenkins,Vlatombe/jenkins,lordofthejars/jenkins,lvotypko/jenkins,github-api-test-org/jenkins,sathiya-mit/jenkins,maikeffi/hudson,verbitan/jenkins,everyonce/jenkins,SenolOzer/jenkins,jtnord/jenkins,akshayabd/jenkins,lordofthejars/jenkins,h4ck3rm1k3/jenkins,intelchen/jenkins,protazy/jenkins,FTG-003/jenkins,mattclark/jenkins,daniel-beck/jenkins,duzifang/my-jenkins,vivek/hudson,soenter/jenkins,gitaccountforprashant/gittest,huybrechts/hudson,aduprat/jenkins,escoem/jenkins,rashmikanta-1984/jenkins,pselle/jenkins,morficus/jenkins,chbiel/jenkins,1and1/jenkins,jenkinsci/jenkins,stephenc/jenkins,v1v/jenkins,Vlatombe/jenkins,gorcz/jenkins,svanoort/jenkins,yonglehou/jenkins,synopsys-arc-oss/jenkins,my7seven/jenkins,bkmeneguello/jenkins,mattclark/jenkins,hemantojhaa/jenkins,daspilker/jenkins,lvotypko/jenkins2,akshayabd/jenkins,synopsys-arc-oss/jenkins,rsandell/jenkins,luoqii/jenkins,dbroady1/jenkins,6WIND/jenkins,ajshastri/jenkins,github-api-test-org/jenkins,goldchang/jenkins,jpederzolli/jenkins-1,wuwen5/jenkins,ikedam/jenkins,verbitan/jenkins,CodeShane/jenkins,rsandell/jenkins,Jochen-A-Fuerbacher/jenkins,recena/jenkins,wuwen5/jenkins,sathiya-mit/jenkins,brunocvcunha/jenkins,jglick/jenkins,azweb76/jenkins,maikeffi/hudson,vivek/hudson,singh88/jenkins,my7seven/jenkins,batmat/jenkins,mattclark/jenkins,dbroady1/jenkins,albers/jenkins,pjanouse/jenkins,rashmikanta-1984/jenkins,samatdav/jenkins,6WIND/jenkins,h4ck3rm1k3/jenkins,paulwellnerbou/jenkins,vivek/hudson,scoheb/jenkins,jtnord/jenkins,mrobinet/jenkins,KostyaSha/jenkins,albers/jenkins,vivek/hudson,SebastienGllmt/jenkins,iqstack/jenkins,AustinKwang/jenkins,aheritier/jenkins,lilyJi/jenkins,amuniz/jenkins,guoxu0514/jenkins,ChrisA89/jenkins,keyurpatankar/hudson,pjanouse/jenkins,NehemiahMi/jenkins,huybrechts/hudson,dennisjlee/jenkins,jcarrothers-sap/jenkins,tangkun75/jenkins,aheritier/jenkins,luoqii/jenkins,amuniz/jenkins,vvv444/jenkins,goldchang/jenkins,vjuranek/jenkins,bkmeneguello/jenkins,scoheb/jenkins,stefanbrausch/hudson-main,lindzh/jenkins,Ykus/jenkins,gusreiber/jenkins,gusreiber/jenkins,DanielWeber/jenkins,rsandell/jenkins,daniel-beck/jenkins,paulmillar/jenkins,tfennelly/jenkins,ajshastri/jenkins,dennisjlee/jenkins,fbelzunc/jenkins,jcsirot/jenkins,1and1/jenkins,lvotypko/jenkins3,jenkinsci/jenkins,mpeltonen/jenkins,FTG-003/jenkins,damianszczepanik/jenkins,noikiy/jenkins,liupugong/jenkins,paulmillar/jenkins,KostyaSha/jenkins,lvotypko/jenkins2,KostyaSha/jenkins,Jimilian/jenkins,MadsNielsen/jtemp,pjanouse/jenkins,huybrechts/hudson,msrb/jenkins,DoctorQ/jenkins,fbelzunc/jenkins,aheritier/jenkins,KostyaSha/jenkins,mpeltonen/jenkins,batmat/jenkins,tangkun75/jenkins,protazy/jenkins,deadmoose/jenkins,iqstack/jenkins,andresrc/jenkins,gorcz/jenkins,huybrechts/hudson,AustinKwang/jenkins,arcivanov/jenkins,samatdav/jenkins,lvotypko/jenkins3,svanoort/jenkins,NehemiahMi/jenkins,patbos/jenkins,kohsuke/hudson,mrobinet/jenkins,vivek/hudson,wangyikai/jenkins,pantheon-systems/jenkins,pselle/jenkins,jzjzjzj/jenkins,escoem/jenkins,jpederzolli/jenkins-1,mpeltonen/jenkins,FTG-003/jenkins,arcivanov/jenkins,aquarellian/jenkins,jpbriend/jenkins,khmarbaise/jenkins,arunsingh/jenkins,iterate/coding-dojo,bpzhang/jenkins,SebastienGllmt/jenkins,ajshastri/jenkins,verbitan/jenkins,oleg-nenashev/jenkins,christ66/jenkins,MarkEWaite/jenkins,ErikVerheul/jenkins,github-api-test-org/jenkins,albers/jenkins,petermarcoen/jenkins,goldchang/jenkins,vlajos/jenkins,ErikVerheul/jenkins,brunocvcunha/jenkins,pantheon-systems/jenkins,protazy/jenkins,stefanbrausch/hudson-main,rsandell/jenkins,varmenise/jenkins,rashmikanta-1984/jenkins,khmarbaise/jenkins,vijayto/jenkins,ydubreuil/jenkins,vlajos/jenkins,FarmGeek4Life/jenkins,azweb76/jenkins,tastatur/jenkins,CodeShane/jenkins,ns163/jenkins,v1v/jenkins,rashmikanta-1984/jenkins,mrooney/jenkins,everyonce/jenkins,tangkun75/jenkins,kzantow/jenkins,wangyikai/jenkins,jcsirot/jenkins,christ66/jenkins,Vlatombe/jenkins,Krasnyanskiy/jenkins,oleg-nenashev/jenkins,everyonce/jenkins,jglick/jenkins,vjuranek/jenkins,paulmillar/jenkins,DoctorQ/jenkins,synopsys-arc-oss/jenkins,jk47/jenkins,ndeloof/jenkins,Jochen-A-Fuerbacher/jenkins,jglick/jenkins,Jimilian/jenkins,vlajos/jenkins,andresrc/jenkins,pselle/jenkins,KostyaSha/jenkins,petermarcoen/jenkins,dbroady1/jenkins,chbiel/jenkins,brunocvcunha/jenkins,rsandell/jenkins,keyurpatankar/hudson,aheritier/jenkins,hudson/hudson-2.x,viqueen/jenkins,yonglehou/jenkins,292388900/jenkins,thomassuckow/jenkins,jtnord/jenkins,oleg-nenashev/jenkins,msrb/jenkins,tfennelly/jenkins,fbelzunc/jenkins,huybrechts/hudson,paulmillar/jenkins,viqueen/jenkins,jk47/jenkins,mpeltonen/jenkins,MarkEWaite/jenkins,ydubreuil/jenkins,6WIND/jenkins,gorcz/jenkins,scoheb/jenkins,keyurpatankar/hudson,dariver/jenkins,svanoort/jenkins,jglick/jenkins,olivergondza/jenkins,petermarcoen/jenkins,Jochen-A-Fuerbacher/jenkins,jpbriend/jenkins,escoem/jenkins,vvv444/jenkins,my7seven/jenkins,ErikVerheul/jenkins,nandan4/Jenkins,jhoblitt/jenkins,liupugong/jenkins,SenolOzer/jenkins,MarkEWaite/jenkins,arunsingh/jenkins,pjanouse/jenkins,jcarrothers-sap/jenkins,Jimilian/jenkins,seanlin816/jenkins,gitaccountforprashant/gittest,h4ck3rm1k3/jenkins,daniel-beck/jenkins,h4ck3rm1k3/jenkins,mrooney/jenkins,jglick/jenkins,mdonohue/jenkins,dbroady1/jenkins,escoem/jenkins,azweb76/jenkins,synopsys-arc-oss/jenkins,bpzhang/jenkins,varmenise/jenkins,nandan4/Jenkins,hplatou/jenkins,FTG-003/jenkins,rlugojr/jenkins,guoxu0514/jenkins,ydubreuil/jenkins,jhoblitt/jenkins,tangkun75/jenkins,elkingtonmcb/jenkins,FarmGeek4Life/jenkins,tastatur/jenkins,Wilfred/jenkins,daniel-beck/jenkins,amruthsoft9/Jenkis,andresrc/jenkins,amruthsoft9/Jenkis,noikiy/jenkins,elkingtonmcb/jenkins,ydubreuil/jenkins,MichaelPranovich/jenkins_sc,ndeloof/jenkins,seanlin816/jenkins,ErikVerheul/jenkins,msrb/jenkins,abayer/jenkins,stephenc/jenkins,FTG-003/jenkins,albers/jenkins,vlajos/jenkins,amruthsoft9/Jenkis,scoheb/jenkins,intelchen/jenkins,azweb76/jenkins,luoqii/jenkins,v1v/jenkins,kzantow/jenkins,daniel-beck/jenkins,lvotypko/jenkins2,lilyJi/jenkins,singh88/jenkins,yonglehou/jenkins,yonglehou/jenkins,hemantojhaa/jenkins,paulmillar/jenkins,singh88/jenkins,synopsys-arc-oss/jenkins,DoctorQ/jenkins,aldaris/jenkins,ns163/jenkins,aduprat/jenkins,MarkEWaite/jenkins,sathiya-mit/jenkins,recena/jenkins,abayer/jenkins,jenkinsci/jenkins,jcarrothers-sap/jenkins,NehemiahMi/jenkins,thomassuckow/jenkins,chbiel/jenkins,alvarolobato/jenkins,lordofthejars/jenkins,samatdav/jenkins,csimons/jenkins,kzantow/jenkins,amruthsoft9/Jenkis,ajshastri/jenkins,rlugojr/jenkins,fbelzunc/jenkins,luoqii/jenkins,mcanthony/jenkins,rlugojr/jenkins,morficus/jenkins,DanielWeber/jenkins,292388900/jenkins,mcanthony/jenkins,Krasnyanskiy/jenkins,jk47/jenkins,chbiel/jenkins,daspilker/jenkins,tangkun75/jenkins,goldchang/jenkins,amuniz/jenkins,vjuranek/jenkins,DanielWeber/jenkins,duzifang/my-jenkins,dariver/jenkins,stefanbrausch/hudson-main,lvotypko/jenkins,v1v/jenkins,luoqii/jenkins,shahharsh/jenkins,gusreiber/jenkins,dennisjlee/jenkins,gorcz/jenkins,gusreiber/jenkins,jzjzjzj/jenkins,ChrisA89/jenkins,SebastienGllmt/jenkins,aduprat/jenkins,chbiel/jenkins,vvv444/jenkins,lindzh/jenkins,everyonce/jenkins,damianszczepanik/jenkins,FarmGeek4Life/jenkins,stephenc/jenkins,mattclark/jenkins,kzantow/jenkins,evernat/jenkins,MarkEWaite/jenkins,daniel-beck/jenkins,Krasnyanskiy/jenkins,lilyJi/jenkins,jzjzjzj/jenkins,intelchen/jenkins,Jimilian/jenkins,intelchen/jenkins,mdonohue/jenkins,v1v/jenkins,mattclark/jenkins,hplatou/jenkins,Wilfred/jenkins,MichaelPranovich/jenkins_sc,damianszczepanik/jenkins,aquarellian/jenkins,evernat/jenkins,abayer/jenkins,guoxu0514/jenkins,gorcz/jenkins,oleg-nenashev/jenkins,recena/jenkins,scoheb/jenkins,chbiel/jenkins,pantheon-systems/jenkins,damianszczepanik/jenkins,mrooney/jenkins,jpbriend/jenkins,iterate/coding-dojo,hashar/jenkins,petermarcoen/jenkins,mrobinet/jenkins,jtnord/jenkins,viqueen/jenkins,jzjzjzj/jenkins,keyurpatankar/hudson,ChrisA89/jenkins,elkingtonmcb/jenkins,aheritier/jenkins,bkmeneguello/jenkins,fbelzunc/jenkins,aldaris/jenkins,elkingtonmcb/jenkins,vvv444/jenkins,gusreiber/jenkins,aquarellian/jenkins,liorhson/jenkins,albers/jenkins,jpbriend/jenkins,svanoort/jenkins,christ66/jenkins,dariver/jenkins,verbitan/jenkins,iqstack/jenkins,liupugong/jenkins,wuwen5/jenkins,damianszczepanik/jenkins,Ykus/jenkins,lvotypko/jenkins2,akshayabd/jenkins,gusreiber/jenkins,stephenc/jenkins,bpzhang/jenkins,lvotypko/jenkins3,sathiya-mit/jenkins,pselle/jenkins,stefanbrausch/hudson-main,nandan4/Jenkins,tastatur/jenkins,duzifang/my-jenkins,olivergondza/jenkins,gusreiber/jenkins,samatdav/jenkins,shahharsh/jenkins,pantheon-systems/jenkins,gorcz/jenkins,yonglehou/jenkins,jhoblitt/jenkins,thomassuckow/jenkins,KostyaSha/jenkins,goldchang/jenkins,ydubreuil/jenkins,1and1/jenkins,patbos/jenkins,wuwen5/jenkins,dariver/jenkins,ikedam/jenkins,seanlin816/jenkins,vijayto/jenkins,evernat/jenkins,duzifang/my-jenkins,arunsingh/jenkins,escoem/jenkins,6WIND/jenkins,Wilfred/jenkins,vjuranek/jenkins,ErikVerheul/jenkins,amuniz/jenkins,lordofthejars/jenkins,amruthsoft9/Jenkis,aheritier/jenkins,everyonce/jenkins,batmat/jenkins,seanlin816/jenkins,jpederzolli/jenkins-1,huybrechts/hudson,arunsingh/jenkins,mdonohue/jenkins,lindzh/jenkins,ydubreuil/jenkins,liupugong/jenkins,stephenc/jenkins,pselle/jenkins,MadsNielsen/jtemp,h4ck3rm1k3/jenkins,1and1/jenkins,christ66/jenkins,alvarolobato/jenkins,jglick/jenkins,bpzhang/jenkins,mrooney/jenkins,abayer/jenkins,dariver/jenkins,Ykus/jenkins,fbelzunc/jenkins,ns163/jenkins,vlajos/jenkins,mrobinet/jenkins,damianszczepanik/jenkins,aduprat/jenkins,viqueen/jenkins,jenkinsci/jenkins,olivergondza/jenkins,MadsNielsen/jtemp,MadsNielsen/jtemp,fbelzunc/jenkins,protazy/jenkins,SenolOzer/jenkins,AustinKwang/jenkins,maikeffi/hudson,MarkEWaite/jenkins,DanielWeber/jenkins,AustinKwang/jenkins,mattclark/jenkins,NehemiahMi/jenkins,mcanthony/jenkins,Krasnyanskiy/jenkins,csimons/jenkins,iterate/coding-dojo,csimons/jenkins,FTG-003/jenkins,recena/jenkins,seanlin816/jenkins,kohsuke/hudson,khmarbaise/jenkins,msrb/jenkins,ikedam/jenkins,nandan4/Jenkins,guoxu0514/jenkins,keyurpatankar/hudson,wangyikai/jenkins,soenter/jenkins,Krasnyanskiy/jenkins,sathiya-mit/jenkins,bkmeneguello/jenkins,hudson/hudson-2.x,morficus/jenkins,godfath3r/jenkins,mrooney/jenkins,yonglehou/jenkins,seanlin816/jenkins,paulwellnerbou/jenkins,mdonohue/jenkins,kzantow/jenkins,patbos/jenkins,lvotypko/jenkins,vivek/hudson,kohsuke/hudson,Vlatombe/jenkins,tastatur/jenkins,MichaelPranovich/jenkins_sc,bkmeneguello/jenkins,MichaelPranovich/jenkins_sc,v1v/jenkins,AustinKwang/jenkins,shahharsh/jenkins,Wilfred/jenkins,elkingtonmcb/jenkins,iterate/coding-dojo,vjuranek/jenkins,khmarbaise/jenkins,olivergondza/jenkins,tastatur/jenkins,batmat/jenkins,daspilker/jenkins,kohsuke/hudson,github-api-test-org/jenkins,keyurpatankar/hudson,daspilker/jenkins,vjuranek/jenkins,ndeloof/jenkins,kohsuke/hudson,DanielWeber/jenkins,everyonce/jenkins,albers/jenkins,alvarolobato/jenkins,damianszczepanik/jenkins,jpbriend/jenkins,Jochen-A-Fuerbacher/jenkins,aldaris/jenkins,olivergondza/jenkins,brunocvcunha/jenkins,varmenise/jenkins,lvotypko/jenkins2,vivek/hudson,iqstack/jenkins,scoheb/jenkins,mcanthony/jenkins,lindzh/jenkins,daspilker/jenkins,rashmikanta-1984/jenkins,lordofthejars/jenkins,verbitan/jenkins,gorcz/jenkins,vijayto/jenkins,DoctorQ/jenkins,MadsNielsen/jtemp,ikedam/jenkins,Krasnyanskiy/jenkins,vvv444/jenkins,pantheon-systems/jenkins,iterate/coding-dojo,MichaelPranovich/jenkins_sc,DoctorQ/jenkins,intelchen/jenkins,jzjzjzj/jenkins,synopsys-arc-oss/jenkins,jpederzolli/jenkins-1,liorhson/jenkins,lilyJi/jenkins,jcsirot/jenkins,ajshastri/jenkins,christ66/jenkins,tfennelly/jenkins,6WIND/jenkins,kzantow/jenkins,MichaelPranovich/jenkins_sc,pjanouse/jenkins,hudson/hudson-2.x,KostyaSha/jenkins,ns163/jenkins,amuniz/jenkins,wuwen5/jenkins,dbroady1/jenkins,NehemiahMi/jenkins,jzjzjzj/jenkins,singh88/jenkins,brunocvcunha/jenkins,rlugojr/jenkins,rsandell/jenkins,liorhson/jenkins,iterate/coding-dojo,6WIND/jenkins,jk47/jenkins,daniel-beck/jenkins,Wilfred/jenkins,andresrc/jenkins,khmarbaise/jenkins,Ykus/jenkins,rashmikanta-1984/jenkins,varmenise/jenkins,akshayabd/jenkins,gitaccountforprashant/gittest,jpederzolli/jenkins-1,paulwellnerbou/jenkins,noikiy/jenkins,CodeShane/jenkins,hemantojhaa/jenkins,abayer/jenkins,lilyJi/jenkins,oleg-nenashev/jenkins,aheritier/jenkins,mpeltonen/jenkins,rlugojr/jenkins,arcivanov/jenkins,jcsirot/jenkins,vlajos/jenkins,bpzhang/jenkins,pantheon-systems/jenkins,soenter/jenkins,aldaris/jenkins,nandan4/Jenkins,dbroady1/jenkins,SebastienGllmt/jenkins,jcsirot/jenkins,MarkEWaite/jenkins,lordofthejars/jenkins,liupugong/jenkins,iqstack/jenkins,godfath3r/jenkins,recena/jenkins,lvotypko/jenkins,hashar/jenkins,brunocvcunha/jenkins,mdonohue/jenkins,mdonohue/jenkins,mdonohue/jenkins,Jochen-A-Fuerbacher/jenkins,maikeffi/hudson,andresrc/jenkins,batmat/jenkins,MadsNielsen/jtemp,tastatur/jenkins,lvotypko/jenkins,stefanbrausch/hudson-main,shahharsh/jenkins,jhoblitt/jenkins,keyurpatankar/hudson,292388900/jenkins,ns163/jenkins,pjanouse/jenkins,wuwen5/jenkins,paulmillar/jenkins,wangyikai/jenkins,maikeffi/hudson,andresrc/jenkins,noikiy/jenkins,lindzh/jenkins,jtnord/jenkins,thomassuckow/jenkins,SenolOzer/jenkins,aduprat/jenkins,jk47/jenkins,hplatou/jenkins,jenkinsci/jenkins,daspilker/jenkins,godfath3r/jenkins,stephenc/jenkins,jcarrothers-sap/jenkins,yonglehou/jenkins,batmat/jenkins,arcivanov/jenkins,petermarcoen/jenkins,wangyikai/jenkins,Vlatombe/jenkins,godfath3r/jenkins,maikeffi/hudson,msrb/jenkins,6WIND/jenkins,csimons/jenkins,ns163/jenkins,hemantojhaa/jenkins,deadmoose/jenkins,dbroady1/jenkins,kzantow/jenkins,Jimilian/jenkins,FTG-003/jenkins,rsandell/jenkins,gitaccountforprashant/gittest,paulwellnerbou/jenkins,godfath3r/jenkins,alvarolobato/jenkins,lvotypko/jenkins,Ykus/jenkins,CodeShane/jenkins,nandan4/Jenkins,ydubreuil/jenkins,ikedam/jenkins,shahharsh/jenkins,SenolOzer/jenkins,ndeloof/jenkins,evernat/jenkins,guoxu0514/jenkins,mcanthony/jenkins,elkingtonmcb/jenkins,svanoort/jenkins,ikedam/jenkins,github-api-test-org/jenkins,soenter/jenkins,mrobinet/jenkins,jhoblitt/jenkins,lvotypko/jenkins3,varmenise/jenkins,Krasnyanskiy/jenkins,escoem/jenkins,stefanbrausch/hudson-main,rlugojr/jenkins,pselle/jenkins,ns163/jenkins,luoqii/jenkins,khmarbaise/jenkins,deadmoose/jenkins,soenter/jenkins,v1v/jenkins,oleg-nenashev/jenkins,jenkinsci/jenkins,mcanthony/jenkins,mrooney/jenkins,singh88/jenkins,escoem/jenkins,hplatou/jenkins,godfath3r/jenkins,dariver/jenkins,Jimilian/jenkins,thomassuckow/jenkins,kohsuke/hudson,deadmoose/jenkins,paulwellnerbou/jenkins,daspilker/jenkins,my7seven/jenkins,guoxu0514/jenkins,ndeloof/jenkins,evernat/jenkins,hplatou/jenkins,NehemiahMi/jenkins,patbos/jenkins,hudson/hudson-2.x,scoheb/jenkins,SebastienGllmt/jenkins,github-api-test-org/jenkins,tangkun75/jenkins,jtnord/jenkins,1and1/jenkins,mcanthony/jenkins,duzifang/my-jenkins,jpbriend/jenkins,msrb/jenkins,MadsNielsen/jtemp,ChrisA89/jenkins,FarmGeek4Life/jenkins,morficus/jenkins,alvarolobato/jenkins,SebastienGllmt/jenkins,MichaelPranovich/jenkins_sc,liorhson/jenkins,CodeShane/jenkins,dennisjlee/jenkins,DoctorQ/jenkins,csimons/jenkins,duzifang/my-jenkins,jk47/jenkins,github-api-test-org/jenkins,vijayto/jenkins,DoctorQ/jenkins,jcsirot/jenkins,vvv444/jenkins,aquarellian/jenkins,jcarrothers-sap/jenkins,gorcz/jenkins,292388900/jenkins,lindzh/jenkins,ajshastri/jenkins,Wilfred/jenkins,noikiy/jenkins,h4ck3rm1k3/jenkins,rlugojr/jenkins,aduprat/jenkins,DanielWeber/jenkins | package hudson.remoting;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
/**
* Manages unique ID for exported objects, and allows look-up from IDs.
*
* @author Kohsuke Kawaguchi
*/
final class ExportTable<T> {
private final Map<Integer,Entry> table = new HashMap<Integer,Entry>();
private final Map<T,Entry> reverse = new HashMap<T,Entry>();
/**
* {@link ExportList}s which are actively recording the current
* export operation.
*/
private final ThreadLocal<List<ExportList>> lists = new ThreadLocal<List<ExportList>>() {
protected List<ExportList> initialValue() {
return new ArrayList<ExportList>();
}
};
/**
* Information about one exporetd object.
*/
private final class Entry {
final int id;
final T object;
/**
* Where was this object first exported?
*/
final Exception allocationTrace;
/**
* Current reference count.
* Access to {@link ExportTable} is guarded by synchronized block,
* so accessing this field requires no further synchronization.
*/
private int referenceCount;
Entry(T object) {
this.id = iota++;
this.object = object;
this.allocationTrace = new Exception();
// force the computation of the stack trace in a Java friendly data structure,
// so that the call stack can be seen from the heap dump after the fact.
allocationTrace.getStackTrace();
addRef();
table.put(id,this);
reverse.put(object,this);
}
void addRef() {
referenceCount++;
}
void release() {
if(--referenceCount==0) {
table.remove(id);
reverse.remove(object);
}
}
}
/**
* Captures the list of export, so that they can be unexported later.
*
* This is tied to a particular thread, so it only records operations
* on the current thread.
*/
public final class ExportList extends ArrayList<Entry> {
void release() {
synchronized(ExportTable.this) {
for (Entry e : this)
e.release();
}
}
void stopRecording() {
synchronized(ExportTable.this) {
lists.get().remove(this);
}
}
}
/**
* Unique ID generator.
*/
private int iota = 1;
/**
* Starts the recording of the export operations
* and returns the list that captures the result.
*
* @see ExportList#stopRecording()
*/
public synchronized ExportList startRecording() {
ExportList el = new ExportList();
lists.get().add(el);
return el;
}
/**
* Exports the given object.
*
* <p>
* Until the object is {@link #unexport(Object) unexported}, it will
* not be subject to GC.
*
* @return
* The assigned 'object ID'. If the object is already exported,
* it will return the ID already assigned to it.
*/
public synchronized int export(T t) {
return export(t,true);
}
/**
* @param notifyListener
* If false, listener will not be notified. This is used to
* create an export that won't get unexported when the call returns.
*/
public synchronized int export(T t, boolean notifyListener) {
if(t==null) return 0; // bootstrap classloader
Entry e = reverse.get(t);
if(e==null)
e = new Entry(t);
else
e.addRef();
if(notifyListener)
for (ExportList list : lists.get())
list.add(e);
return e.id;
}
public synchronized T get(int id) {
Entry e = table.get(id);
if(e!=null) return e.object;
else return null;
}
/**
* Removes the exported object from the table.
*/
public synchronized void unexport(T t) {
if(t==null) return;
Entry e = reverse.get(t);
if(e==null) return; // presumably already unexported
e.release();
}
/**
* Dumps the contents of the table to a file.
*/
public synchronized void dump(PrintWriter w) throws IOException {
for (Entry e : table.values()) {
w.printf("#%d (ref.%d) : %s\n", e.id, e.referenceCount, e.object);
e.allocationTrace.printStackTrace(w);
}
}
}
| remoting/src/main/java/hudson/remoting/ExportTable.java | package hudson.remoting;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
/**
* Manages unique ID for exported objects, and allows look-up from IDs.
*
* @author Kohsuke Kawaguchi
*/
final class ExportTable<T> {
private final Map<Integer,Entry> table = new HashMap<Integer,Entry>();
private final Map<T,Entry> reverse = new HashMap<T,Entry>();
/**
* {@link ExportList}s which are actively recording the current
* export operation.
*/
private final ThreadLocal<List<ExportList>> lists = new ThreadLocal<List<ExportList>>() {
protected List<ExportList> initialValue() {
return new ArrayList<ExportList>();
}
};
/**
* Information about one exporetd object.
*/
private final class Entry {
final int id;
final T object;
/**
* Where was this object first exported?
*/
final Exception allocationTrace;
/**
* Current reference count.
* Access to {@link ExportTable} is guarded by synchronized block,
* so accessing this field requires no further synchronization.
*/
private int referenceCount;
Entry(T object) {
this.id = iota++;
this.object = object;
this.allocationTrace = new Exception();
allocationTrace.fillInStackTrace();
addRef();
table.put(id,this);
reverse.put(object,this);
}
void addRef() {
referenceCount++;
}
void release() {
if(--referenceCount==0) {
table.remove(id);
reverse.remove(object);
}
}
}
/**
* Captures the list of export, so that they can be unexported later.
*
* This is tied to a particular thread, so it only records operations
* on the current thread.
*/
public final class ExportList extends ArrayList<Entry> {
void release() {
synchronized(ExportTable.this) {
for (Entry e : this)
e.release();
}
}
void stopRecording() {
synchronized(ExportTable.this) {
lists.get().remove(this);
}
}
}
/**
* Unique ID generator.
*/
private int iota = 1;
/**
* Starts the recording of the export operations
* and returns the list that captures the result.
*
* @see ExportList#stopRecording()
*/
public synchronized ExportList startRecording() {
ExportList el = new ExportList();
lists.get().add(el);
return el;
}
/**
* Exports the given object.
*
* <p>
* Until the object is {@link #unexport(Object) unexported}, it will
* not be subject to GC.
*
* @return
* The assigned 'object ID'. If the object is already exported,
* it will return the ID already assigned to it.
*/
public synchronized int export(T t) {
return export(t,true);
}
/**
* @param notifyListener
* If false, listener will not be notified. This is used to
* create an export that won't get unexported when the call returns.
*/
public synchronized int export(T t, boolean notifyListener) {
if(t==null) return 0; // bootstrap classloader
Entry e = reverse.get(t);
if(e==null)
e = new Entry(t);
else
e.addRef();
if(notifyListener)
for (ExportList list : lists.get())
list.add(e);
return e.id;
}
public synchronized T get(int id) {
Entry e = table.get(id);
if(e!=null) return e.object;
else return null;
}
/**
* Removes the exported object from the table.
*/
public synchronized void unexport(T t) {
if(t==null) return;
Entry e = reverse.get(t);
if(e==null) return; // presumably already unexported
e.release();
}
/**
* Dumps the contents of the table to a file.
*/
public synchronized void dump(PrintWriter w) throws IOException {
for (Entry e : table.values()) {
w.printf("#%d (ref.%d) : %s\n", e.id, e.referenceCount, e.object);
e.allocationTrace.printStackTrace(w);
}
}
}
| For the allocationTrace to be really useful, its call stack needs to be captured in StackTraceElement[], not in the encoded binary form.
git-svn-id: 28f34f9aa52bc55a5ddd5be9e183c5cccadc6ee4@11799 71c3de6d-444a-0410-be80-ed276b4c234a
| remoting/src/main/java/hudson/remoting/ExportTable.java | For the allocationTrace to be really useful, its call stack needs to be captured in StackTraceElement[], not in the encoded binary form. | <ide><path>emoting/src/main/java/hudson/remoting/ExportTable.java
<ide> this.id = iota++;
<ide> this.object = object;
<ide> this.allocationTrace = new Exception();
<del> allocationTrace.fillInStackTrace();
<add> // force the computation of the stack trace in a Java friendly data structure,
<add> // so that the call stack can be seen from the heap dump after the fact.
<add> allocationTrace.getStackTrace();
<ide> addRef();
<ide>
<ide> table.put(id,this); |
|
Java | mit | 3c30d1ea8b681db7c128607581e12ba94e2ecd94 | 0 | CS2103JAN2017-W09-B2/main,CS2103JAN2017-W09-B2/main | package seedu.typed.logic.parser;
import static seedu.typed.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.typed.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import seedu.typed.logic.commands.AddCommand;
import seedu.typed.logic.commands.ClearCommand;
import seedu.typed.logic.commands.Command;
import seedu.typed.logic.commands.CompleteCommand;
import seedu.typed.logic.commands.DeleteCommand;
import seedu.typed.logic.commands.EditCommand;
import seedu.typed.logic.commands.ExitCommand;
import seedu.typed.logic.commands.FindCommand;
import seedu.typed.logic.commands.HelpCommand;
import seedu.typed.logic.commands.HistoryCommand;
import seedu.typed.logic.commands.IncorrectCommand;
import seedu.typed.logic.commands.ListCommand;
import seedu.typed.logic.commands.RedoCommand;
import seedu.typed.logic.commands.SelectCommand;
import seedu.typed.logic.commands.UndoCommand;
/**
* Parses user input.
*/
public class Parser {
/**
* Used for initial separation of command word and arguments.
*/
private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)");
/**
* Parses user input into command for execution.
*
* @param userInput
* full user input string
* @return the command based on the user input
*/
public Command parseCommand(String userInput) {
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandWord = matcher.group("commandWord");
final String arguments = matcher.group("arguments");
switch (commandWord) {
case AddCommand.COMMAND_WORD:
return new AddCommandParser().parse(arguments);
case CompleteCommand.COMMAND_WORD:
return new CompleteCommandParser().parse(arguments);
case EditCommand.COMMAND_WORD:
return new EditCommandParser().parse(arguments);
case SelectCommand.COMMAND_WORD:
return new SelectCommandParser().parse(arguments);
case DeleteCommand.COMMAND_WORD:
return new DeleteCommandParser().parse(arguments);
case UndoCommand.COMMAND_WORD:
return new UndoCommand();
case RedoCommand.COMMAND_WORD:
return new RedoCommand();
case ClearCommand.COMMAND_WORD:
return new ClearCommand();
case FindCommand.COMMAND_WORD:
return new FindCommandParser().parse(arguments);
case ListCommand.COMMAND_WORD:
return new ListCommand();
case HistoryCommand.COMMAND_WORD:
return new HistoryCommand();
case ExitCommand.COMMAND_WORD:
return new ExitCommand();
case HelpCommand.COMMAND_WORD:
return new HelpCommand();
default:
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
}
}
| src/main/java/seedu/typed/logic/parser/Parser.java | package seedu.typed.logic.parser;
import static seedu.typed.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.typed.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import seedu.typed.logic.commands.AddCommand;
import seedu.typed.logic.commands.ClearCommand;
import seedu.typed.logic.commands.Command;
import seedu.typed.logic.commands.DeleteCommand;
import seedu.typed.logic.commands.EditCommand;
import seedu.typed.logic.commands.ExitCommand;
import seedu.typed.logic.commands.FindCommand;
import seedu.typed.logic.commands.HelpCommand;
import seedu.typed.logic.commands.HistoryCommand;
import seedu.typed.logic.commands.IncorrectCommand;
import seedu.typed.logic.commands.ListCommand;
import seedu.typed.logic.commands.RedoCommand;
import seedu.typed.logic.commands.SelectCommand;
import seedu.typed.logic.commands.UndoCommand;
/**
* Parses user input.
*/
public class Parser {
/**
* Used for initial separation of command word and arguments.
*/
private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)");
/**
* Parses user input into command for execution.
*
* @param userInput
* full user input string
* @return the command based on the user input
*/
public Command parseCommand(String userInput) {
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandWord = matcher.group("commandWord");
final String arguments = matcher.group("arguments");
switch (commandWord) {
case AddCommand.COMMAND_WORD:
return new AddCommandParser().parse(arguments);
case EditCommand.COMMAND_WORD:
return new EditCommandParser().parse(arguments);
case SelectCommand.COMMAND_WORD:
return new SelectCommandParser().parse(arguments);
case DeleteCommand.COMMAND_WORD:
return new DeleteCommandParser().parse(arguments);
case UndoCommand.COMMAND_WORD:
return new UndoCommand();
case RedoCommand.COMMAND_WORD:
return new RedoCommand();
case ClearCommand.COMMAND_WORD:
return new ClearCommand();
case FindCommand.COMMAND_WORD:
return new FindCommandParser().parse(arguments);
case ListCommand.COMMAND_WORD:
return new ListCommand();
case HistoryCommand.COMMAND_WORD:
return new HistoryCommand();
case ExitCommand.COMMAND_WORD:
return new ExitCommand();
case HelpCommand.COMMAND_WORD:
return new HelpCommand();
default:
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
}
}
| Added CompleteCommand in Parser
| src/main/java/seedu/typed/logic/parser/Parser.java | Added CompleteCommand in Parser | <ide><path>rc/main/java/seedu/typed/logic/parser/Parser.java
<ide> import seedu.typed.logic.commands.AddCommand;
<ide> import seedu.typed.logic.commands.ClearCommand;
<ide> import seedu.typed.logic.commands.Command;
<add>import seedu.typed.logic.commands.CompleteCommand;
<ide> import seedu.typed.logic.commands.DeleteCommand;
<ide> import seedu.typed.logic.commands.EditCommand;
<ide> import seedu.typed.logic.commands.ExitCommand;
<ide> case AddCommand.COMMAND_WORD:
<ide> return new AddCommandParser().parse(arguments);
<ide>
<add> case CompleteCommand.COMMAND_WORD:
<add> return new CompleteCommandParser().parse(arguments);
<add>
<ide> case EditCommand.COMMAND_WORD:
<ide> return new EditCommandParser().parse(arguments);
<ide> |
|
Java | mit | 8edd789e63f252df43cca3b8718b6eaa91910def | 0 | jenkinsci/analysis-model,jenkinsci/analysis-model,jenkinsci/analysis-model,jenkinsci/analysis-model | package edu.hm.hafner.analysis.parser;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.json.JSONArray;
import org.json.JSONObject;
import edu.hm.hafner.analysis.Issue;
import edu.hm.hafner.analysis.IssueBuilder;
import edu.hm.hafner.analysis.Report;
import edu.hm.hafner.analysis.Severity;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import j2html.tags.ContainerTag;
import static j2html.TagCreator.*;
/**
* <p>
* Parser for reports of pnpm audit scans.
* </p>
* <p>
* <strong>Usage: </strong>pnpm audit --json > pnpm-audit.json
* </p>
*
* @author Fabian Kaupp - [email protected]
*/
public class PnpmAuditParser extends JsonIssueParser {
private static final String VALUE_NOT_SET = "-";
private static final String UNCATEGORIZED = "Uncategorized";
private static final String PNPM_VULNERABILITY_SEVERITY_INFO = "info";
private static final String PNPM_VULNERABILITY_SEVERITY_LOW = "low";
private static final String PNPM_VULNERABILITY_SEVERITY_MODERATE = "moderate";
private static final String PNPM_VULNERABILITY_SEVERITY_HIGH = "high";
private static final String PNPM_VULNERABILITY_SEVERITY_CRITICAL = "critical";
private static final long serialVersionUID = 4140706319863200922L;
@Override
protected void parseJsonObject(final Report report, final JSONObject jsonReport, final IssueBuilder issueBuilder) {
JSONObject results = jsonReport.optJSONObject("advisories");
if (results != null) {
parseResults(report, results, issueBuilder);
}
}
private void parseResults(final Report report, final JSONObject jsonReport, final IssueBuilder issueBuilder) {
for (String key : jsonReport.keySet()) {
JSONObject vulnerability = (JSONObject) jsonReport.get(key);
if (!vulnerability.isEmpty()) {
report.add(convertToIssue(vulnerability, issueBuilder));
}
}
}
private Issue convertToIssue(final JSONObject vulnerability, final IssueBuilder issueBuilder) {
return issueBuilder.setModuleName(vulnerability.optString("module_name", VALUE_NOT_SET))
.setCategory(formatCategory(vulnerability))
.setSeverity(mapSeverity(vulnerability.optString("severity", "UNKNOWN")))
.setType(mapType(vulnerability))
.setMessage(vulnerability.optString("overview", "UNKNOWN"))
.setDescription(formatDescription(vulnerability))
.buildAndClean();
}
private String mapType(final JSONObject vulnerability) {
final JSONArray cves = vulnerability.optJSONArray("cves");
return cves != null && !cves.isNull(0) ? (String) cves.opt(0) : UNCATEGORIZED;
}
private String formatCategory(final JSONObject vulnerability) {
String moduleName = vulnerability.optString("module_name");
String title = vulnerability.optString("title");
if (moduleName != null && title != null) {
return title.replace(moduleName, "").replace(" in ", "");
}
return VALUE_NOT_SET;
}
@SuppressFBWarnings("IMPROPER_UNICODE")
private Severity mapSeverity(final String string) {
if (PNPM_VULNERABILITY_SEVERITY_INFO.equalsIgnoreCase(string)) {
return Severity.WARNING_LOW;
}
else if (PNPM_VULNERABILITY_SEVERITY_LOW.equalsIgnoreCase(string)) {
return Severity.WARNING_LOW;
}
else if (PNPM_VULNERABILITY_SEVERITY_MODERATE.equalsIgnoreCase(string)) {
return Severity.WARNING_NORMAL;
}
else if (PNPM_VULNERABILITY_SEVERITY_HIGH.equalsIgnoreCase(string)) {
return Severity.WARNING_HIGH;
}
else if (PNPM_VULNERABILITY_SEVERITY_CRITICAL.equalsIgnoreCase(string)) {
return Severity.ERROR;
}
else {
return Severity.WARNING_NORMAL;
}
}
private String formatDescription(final JSONObject vulnerability) {
final List<ContainerTag> vulnerabilityTags = new ArrayList<>();
getValueAsContainerTag(vulnerability, "module_name", "Module").ifPresent(vulnerabilityTags::add);
final JSONArray findings = vulnerability.optJSONArray("findings");
if (findings != null && !findings.isEmpty()) {
final JSONObject firstFinding = (JSONObject) findings.opt(0);
final String installedVersion = firstFinding.optString("version");
getValueAsContainerTag(installedVersion, "Installed Version").ifPresent(vulnerabilityTags::add);
}
getValueAsContainerTag(vulnerability, "vulnerable_versions", "Vulnerable Versions").ifPresent(
vulnerabilityTags::add);
getValueAsContainerTag(vulnerability, "patched_versions", "Patched Versions").ifPresent(vulnerabilityTags::add);
getValueAsContainerTag(vulnerability, "severity", "Severity").ifPresent(vulnerabilityTags::add);
getValueAsContainerTag(vulnerability, "overview").ifPresent(vulnerabilityTags::add);
getValueAsContainerTag(vulnerability, "references", "References").ifPresent(vulnerabilityTags::add);
return join(p(join(vulnerabilityTags.toArray()))).render();
}
private Optional<ContainerTag> getValueAsContainerTag(final JSONObject vulnerability, final String tagOfValue) {
final String value = vulnerability.optString(tagOfValue);
if (value == null || value.isEmpty()) {
return Optional.empty();
}
return Optional.of(p(text(value)));
}
private Optional<ContainerTag> getValueAsContainerTag(final String value, final String label) {
if (value == null || value.isEmpty()) {
return Optional.empty();
}
return Optional.of(div(b(label + ": "), text(value)));
}
private Optional<ContainerTag> getValueAsContainerTag(final JSONObject vulnerability, final String tagOfValue,
final String label) {
final String value = vulnerability.optString(tagOfValue);
if (value == null || value.isEmpty()) {
return Optional.empty();
}
return Optional.of(div(b(label + ": "), text(value)));
}
} | src/main/java/edu/hm/hafner/analysis/parser/PnpmAuditParser.java | package edu.hm.hafner.analysis.parser;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.json.JSONArray;
import org.json.JSONObject;
import edu.hm.hafner.analysis.Issue;
import edu.hm.hafner.analysis.IssueBuilder;
import edu.hm.hafner.analysis.Report;
import edu.hm.hafner.analysis.Severity;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import j2html.tags.ContainerTag;
import static j2html.TagCreator.*;
/**
* <p>
* Parser for reports of pnpm audit scans.
* </p>
* <p>
* <strong>Usage: </strong>pnpm audit --json > pnpm-audit.json
* </p>
*
* @author Fabian Kaupp - [email protected]
*/
public class PnpmAuditParser extends JsonIssueParser {
private static final String VALUE_NOT_SET = "-";
private static final String UNCATEGORIZED = "Uncategorized";
private static final String PNPM_VULNERABILITY_SEVERITY_INFO = "info";
private static final String PNPM_VULNERABILITY_SEVERITY_LOW = "low";
private static final String PNPM_VULNERABILITY_SEVERITY_MODERATE = "moderate";
private static final String PNPM_VULNERABILITY_SEVERITY_HIGH = "high";
private static final String PNPM_VULNERABILITY_SEVERITY_CRITICAL = "critical";
private static final long serialVersionUID = 4140706319863200922L;
@Override
protected void parseJsonObject(final Report report, final JSONObject jsonReport, final IssueBuilder issueBuilder) {
JSONObject results = jsonReport.optJSONObject("advisories");
if (results != null) {
parseResults(report, results, issueBuilder);
}
}
private void parseResults(final Report report, final JSONObject jsonReport, final IssueBuilder issueBuilder) {
for (String key : jsonReport.keySet()) {
JSONObject vulnerability = (JSONObject) jsonReport.get(key);
if (!vulnerability.isEmpty()) {
report.add(convertToIssue(vulnerability, issueBuilder));
}
}
}
private Issue convertToIssue(final JSONObject vulnerability, final IssueBuilder issueBuilder) {
return issueBuilder.setModuleName(vulnerability.optString("module_name", VALUE_NOT_SET))
.setCategory(formatCategory(vulnerability))
.setSeverity(mapSeverity(vulnerability.optString("severity", "UNKNOWN")))
.setType(mapType(vulnerability))
.setMessage(vulnerability.optString("overview", "UNKNOWN"))
.setDescription(formatDescription(vulnerability))
.buildAndClean();
}
private String mapType(final JSONObject vulnerability) {
final JSONArray cves = vulnerability.optJSONArray("cves");
return cves != null && !cves.isNull(0) ? (String) cves.opt(0) : UNCATEGORIZED;
}
private String formatCategory(final JSONObject vulnerability) {
String moduleName = vulnerability.optString("module_name");
String title = vulnerability.optString("title");
if (moduleName != null && title != null) {
return title.replace(moduleName, "").replace(" in ", "");
}
return VALUE_NOT_SET;
}
@SuppressFBWarnings("IMPROPER_UNICODE")
private Severity mapSeverity(final String string) {
if (PNPM_VULNERABILITY_SEVERITY_INFO.equalsIgnoreCase(string)) {
return Severity.WARNING_LOW;
}
else if (PNPM_VULNERABILITY_SEVERITY_LOW.equalsIgnoreCase(string)) {
return Severity.WARNING_LOW;
}
else if (PNPM_VULNERABILITY_SEVERITY_MODERATE.equalsIgnoreCase(string)) {
return Severity.WARNING_NORMAL;
}
else if (PNPM_VULNERABILITY_SEVERITY_HIGH.equalsIgnoreCase(string)) {
return Severity.WARNING_HIGH;
}
else if (PNPM_VULNERABILITY_SEVERITY_CRITICAL.equalsIgnoreCase(string)) {
return Severity.ERROR;
}
else {
return Severity.WARNING_NORMAL;
}
}
private String formatDescription(final JSONObject vulnerability) {
final List<ContainerTag> vulnerabilityTags = new ArrayList<>();
vulnerabilityTags.add(getValueAsContainerTag(vulnerability, "module_name", "Module"));
final JSONArray findings = vulnerability.optJSONArray("findings");
if (findings != null && !findings.isEmpty()) {
final JSONObject firstFinding = (JSONObject) findings.opt(0);
final String installedVersion = firstFinding.optString("version");
vulnerabilityTags.add(getValueAsContainerTag(installedVersion, "Installed Version"));
}
vulnerabilityTags.add(getValueAsContainerTag(vulnerability, "vulnerable_versions", "Vulnerable Versions"));
vulnerabilityTags.add(getValueAsContainerTag(vulnerability, "patched_versions", "Patched Versions"));
vulnerabilityTags.add(getValueAsContainerTag(vulnerability, "severity", "Severity"));
vulnerabilityTags.add(getValueAsContainerTag(vulnerability, "overview"));
vulnerabilityTags.add(getValueAsContainerTag(vulnerability, "references", "References"));
vulnerabilityTags.removeIf(Objects::isNull);
return join(p(join(vulnerabilityTags.toArray()))).render();
}
private ContainerTag getValueAsContainerTag(final JSONObject vulnerability, final String tagOfValue) {
final String value = vulnerability.optString(tagOfValue);
if (value == null || value.isEmpty()) {
return null;
}
return p(text(value));
}
private ContainerTag getValueAsContainerTag(final String value, final String label) {
if (value == null || value.isEmpty()) {
return null;
}
return div(b(label + ": "), text(value));
}
private ContainerTag getValueAsContainerTag(final JSONObject vulnerability, final String tagOfValue,
final String label) {
final String value = vulnerability.optString(tagOfValue);
if (value == null || value.isEmpty()) {
return null;
}
return div(b(label + ": "), text(value));
}
} | refactor: use Optionals instead of nullable values
| src/main/java/edu/hm/hafner/analysis/parser/PnpmAuditParser.java | refactor: use Optionals instead of nullable values | <ide><path>rc/main/java/edu/hm/hafner/analysis/parser/PnpmAuditParser.java
<ide>
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<del>import java.util.Objects;
<add>import java.util.Optional;
<ide>
<ide> import org.json.JSONArray;
<ide> import org.json.JSONObject;
<ide> private String formatDescription(final JSONObject vulnerability) {
<ide> final List<ContainerTag> vulnerabilityTags = new ArrayList<>();
<ide>
<del> vulnerabilityTags.add(getValueAsContainerTag(vulnerability, "module_name", "Module"));
<add> getValueAsContainerTag(vulnerability, "module_name", "Module").ifPresent(vulnerabilityTags::add);
<ide>
<ide> final JSONArray findings = vulnerability.optJSONArray("findings");
<ide> if (findings != null && !findings.isEmpty()) {
<ide> final JSONObject firstFinding = (JSONObject) findings.opt(0);
<ide> final String installedVersion = firstFinding.optString("version");
<ide>
<del> vulnerabilityTags.add(getValueAsContainerTag(installedVersion, "Installed Version"));
<add> getValueAsContainerTag(installedVersion, "Installed Version").ifPresent(vulnerabilityTags::add);
<ide> }
<ide>
<del> vulnerabilityTags.add(getValueAsContainerTag(vulnerability, "vulnerable_versions", "Vulnerable Versions"));
<del> vulnerabilityTags.add(getValueAsContainerTag(vulnerability, "patched_versions", "Patched Versions"));
<del> vulnerabilityTags.add(getValueAsContainerTag(vulnerability, "severity", "Severity"));
<del> vulnerabilityTags.add(getValueAsContainerTag(vulnerability, "overview"));
<del> vulnerabilityTags.add(getValueAsContainerTag(vulnerability, "references", "References"));
<del>
<del> vulnerabilityTags.removeIf(Objects::isNull);
<add> getValueAsContainerTag(vulnerability, "vulnerable_versions", "Vulnerable Versions").ifPresent(
<add> vulnerabilityTags::add);
<add> getValueAsContainerTag(vulnerability, "patched_versions", "Patched Versions").ifPresent(vulnerabilityTags::add);
<add> getValueAsContainerTag(vulnerability, "severity", "Severity").ifPresent(vulnerabilityTags::add);
<add> getValueAsContainerTag(vulnerability, "overview").ifPresent(vulnerabilityTags::add);
<add> getValueAsContainerTag(vulnerability, "references", "References").ifPresent(vulnerabilityTags::add);
<ide>
<ide> return join(p(join(vulnerabilityTags.toArray()))).render();
<ide> }
<ide>
<del> private ContainerTag getValueAsContainerTag(final JSONObject vulnerability, final String tagOfValue) {
<add> private Optional<ContainerTag> getValueAsContainerTag(final JSONObject vulnerability, final String tagOfValue) {
<ide> final String value = vulnerability.optString(tagOfValue);
<ide>
<ide> if (value == null || value.isEmpty()) {
<del> return null;
<add> return Optional.empty();
<ide> }
<ide>
<del> return p(text(value));
<add> return Optional.of(p(text(value)));
<ide> }
<ide>
<del> private ContainerTag getValueAsContainerTag(final String value, final String label) {
<add> private Optional<ContainerTag> getValueAsContainerTag(final String value, final String label) {
<ide> if (value == null || value.isEmpty()) {
<del> return null;
<add> return Optional.empty();
<ide> }
<ide>
<del> return div(b(label + ": "), text(value));
<add> return Optional.of(div(b(label + ": "), text(value)));
<ide> }
<ide>
<del> private ContainerTag getValueAsContainerTag(final JSONObject vulnerability, final String tagOfValue,
<add> private Optional<ContainerTag> getValueAsContainerTag(final JSONObject vulnerability, final String tagOfValue,
<ide> final String label) {
<ide> final String value = vulnerability.optString(tagOfValue);
<ide>
<ide> if (value == null || value.isEmpty()) {
<del> return null;
<add> return Optional.empty();
<ide> }
<ide>
<del> return div(b(label + ": "), text(value));
<add> return Optional.of(div(b(label + ": "), text(value)));
<ide> }
<ide> } |
|
JavaScript | mit | f3cb7672aca9e3174586f095a9920887424c284b | 0 | bigpipe/bigpipe,PatidarWeb/bigpipe,bigpipe/bigpipe,tonybo2006/bigpipe,PatidarWeb/bigpipe,tonybo2006/bigpipe | 'use strict';
//
// This file contains common utilities and functionality that is shared between
// the various of pagelet interfaces. This object is merged in to the prototype
// directly
//
var shared = {
/**
* List of resources that can be used by the pagelets.
*
* @type {object}
* @public
*/
resources: {
value: {},
writable: true,
enumerable: false,
configurable: true
},
/**
* Initialization function that is called when the pagelet is activated. This is
* done AFTER any of the authorization hooks are handled. So your sure that this
* pagelet is allowed for usage.
*
* @type {Function}
* @public
*/
initialize: {
value: function initialize() {},
writable: true,
enumerable: false,
configurable: true
},
/**
* Simple emit wrapper that returns a function that emits an event once it's
* called
*
* ```js
* page.on('close', pagelet.emits('close'));
* ```
*
* @param {String} event Name of the event that we should emit.
* @param {Function} parser Argument parser.
* @api public
*/
emits: {
enumerable: false,
value: function emits(event, parser) {
var self = this;
return function emit(arg) {
self.emit(event, parser ? parser.apply(self, arguments) : arg);
};
}
},
/**
* Mixin objects to form one single object that contains the properties of all
* objects.
*
* @param {Object} target Mix all other object in to this object.
* @returns {Object} target
* @api public
*/
mixin: {
enumerable: false,
value: function mixin(target) {
Array.prototype.slice.call(arguments, 1).forEach(function forEach(o) {
Object.getOwnPropertyNames(o).forEach(function eachAttr(attr) {
Object.defineProperty(target, attr, Object.getOwnPropertyDescriptor(o, attr));
});
});
return target;
}
},
/**
* Access a resource.
*
* @TODO re-use previous initialised resources.
* @param {String} name The resource.
* @api public
*/
resource: {
enumerable: false,
value: function get(name) {
var page = this.page || this
, resource;
if (name in this.resources) resource = new this.resources[name];
else resource = new page.resources[name];
resource.configure(page.req, page.res);
return resource;
}
}
};
/**
* Provide a nice syntax sugar for merging in our shared properties and function
* in to our different instances.
*
* @param {Object} proto The prototype we should merge in to.
* @return {Object} Object.defineProperties compatible Object.
* @api public
*/
exports.mixin = function mixin(proto) {
return shared.mixin.value(Object.create(null), shared, proto);
};
| shared.js | 'use strict';
//
// This file contains common utilities and functionality that is shared between
// the various of pagelet interfaces. This object is merged in to the prototype
// directly
//
var shared = {
/**
* List of resources that can be used by the pagelets.
*
* @type {object}
* @public
*/
resources: {
value: {},
writable: true,
enumerable: false,
configurable: true
},
/**
* Initialization function that is called when the pagelet is activated. This is
* done AFTER any of the authorization hooks are handled. So your sure that this
* pagelet is allowed for usage.
*
* @type {Function}
* @public
*/
initialize: {
value: function initialize() {},
writable: true,
enumerable: false,
configurable: true
},
/**
* Simple emit wrapper that returns a function that emits an event once it's
* called
*
* ```js
* page.on('close', pagelet.emits('close'));
* ```
*
* @param {String} event Name of the event that we should emit.
* @param {Function} parser Argument parser.
* @api public
*/
emits: {
enumerable: false,
value: function emits(event, parser) {
var self = this;
return function emit(arg) {
self.emit(event, parser ? parser.apply(self, arguments) : arg);
};
}
},
/**
* Mixin objects to form one single object that contains the properties of all
* objects.
*
* @param {Object} target Mix all other object in to this object.
* @returns {Object} target
* @api public
*/
mixin: {
enumerable: false,
value: function mixin(target) {
Array.prototype.slice.call(arguments, 1).forEach(function forEach(o) {
Object.getOwnPropertyNames(o).forEach(function eachAttr(attr) {
var getter = Object.getOwnPropertyDescriptor(o, attr).get
, setter = Object.getOwnPropertyDescriptor(o, attr).set;
if (!getter && !setter) {
target[attr] = o[attr];
} else {
Object.defineProperty(target, attr, {
get: getter,
set: setter
});
}
});
});
return target;
}
},
/**
* Access a resource.
*
* @TODO re-use previous initialised resources.
* @param {String} name The resource.
* @api public
*/
resource: {
enumerable: false,
value: function get(name) {
var page = this.page || this
, resource;
if (name in this.resources) resource = new this.resources[name];
else resource = new page.resources[name];
resource.configure(page.req, page.res);
return resource;
}
}
};
/**
* Provide a nice syntax sugar for merging in our shared properties and function
* in to our different instances.
*
* @param {Object} proto The prototype we should merge in to.
* @return {Object} Object.defineProperties compatible Object.
* @api public
*/
exports.mixin = function mixin(proto) {
return shared.mixin.value(Object.create(null), shared, proto);
};
| [fix] Make mixin fixing
| shared.js | [fix] Make mixin fixing | <ide><path>hared.js
<ide> value: function mixin(target) {
<ide> Array.prototype.slice.call(arguments, 1).forEach(function forEach(o) {
<ide> Object.getOwnPropertyNames(o).forEach(function eachAttr(attr) {
<del> var getter = Object.getOwnPropertyDescriptor(o, attr).get
<del> , setter = Object.getOwnPropertyDescriptor(o, attr).set;
<del>
<del> if (!getter && !setter) {
<del> target[attr] = o[attr];
<del> } else {
<del> Object.defineProperty(target, attr, {
<del> get: getter,
<del> set: setter
<del> });
<del> }
<add> Object.defineProperty(target, attr, Object.getOwnPropertyDescriptor(o, attr));
<ide> });
<ide> });
<ide> |
|
Java | agpl-3.0 | aa735ba16abe82c13914e9d49a89ab7cdbc4d0d7 | 0 | OpenLMIS/open-lmis,vimsvarcode/elmis,USAID-DELIVER-PROJECT/elmis,vimsvarcode/elmis,USAID-DELIVER-PROJECT/elmis,USAID-DELIVER-PROJECT/elmis,kelvinmbwilo/vims,vimsvarcode/elmis,OpenLMIS/open-lmis,USAID-DELIVER-PROJECT/elmis,jasolangi/jasolangi.github.io,kelvinmbwilo/vims,joshzamor/open-lmis,vimsvarcode/elmis,joshzamor/open-lmis,OpenLMIS/open-lmis,jasolangi/jasolangi.github.io,OpenLMIS/open-lmis,kelvinmbwilo/vims,joshzamor/open-lmis,vimsvarcode/elmis,joshzamor/open-lmis,jasolangi/jasolangi.github.io,kelvinmbwilo/vims | /*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2013 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses. For additional information contact [email protected].
*/
package org.openlmis.functional;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.openlmis.UiUtils.CaptureScreenshotOnFailureListener;
import org.openlmis.UiUtils.TestCaseHelper;
import org.openlmis.pageobjects.ConfigureEDIPage;
import org.openlmis.pageobjects.ConfigureBudgetPage;
import org.openlmis.pageobjects.HomePage;
import org.openlmis.pageobjects.LoginPage;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.testng.annotations.*;
import static com.thoughtworks.selenium.SeleneseTestBase.assertFalse;
import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue;
import static com.thoughtworks.selenium.SeleneseTestNgHelper.assertEquals;
@TransactionConfiguration(defaultRollback = true)
@Transactional
@Listeners(CaptureScreenshotOnFailureListener.class)
public class ConfigureBudgetTemplate extends TestCaseHelper {
@BeforeMethod(groups = "admin")
@Before
public void setUp() throws Exception {
super.setup();
dbWrapper.setupBudgetFileConfiguration("false");
dbWrapper.defaultSetupBudgetFileColumns();
}
@And("^I access configure budget page$")
public void accessOrderScreen() throws Exception {
HomePage homePage = new HomePage(testWebDriver);
ConfigureEDIPage configureEDIPage = homePage.navigateEdiScreen();
configureEDIPage.navigateConfigureBudgetPage();
}
@And("^I should see default include column headers as \"([^\"]*)\"$")
public void verifyIncludeColumnHeader(String status) throws Exception {
ConfigureBudgetPage configureBudgetPage = new ConfigureBudgetPage(testWebDriver);
assertEquals(String.valueOf(configureBudgetPage.getIncludeHeader()), status);
}
@And("^I verify default checkbox for all data fields$")
public void verifyDefaultDataFieldsCheckBox() throws Exception {
ConfigureBudgetPage configureBudgetPage = new ConfigureBudgetPage(testWebDriver);
configureBudgetPage.verifyDefaultIncludeCheckboxForAllDataFields();
}
@And("^I verify default value of positions$")
public void verifyDefaultPositionValues() throws Exception {
ConfigureBudgetPage configureBudgetPage = new ConfigureBudgetPage(testWebDriver);
configureBudgetPage.verifyDefaultPositionValues();
}
@When("^I save budget file format$")
public void clickSave() throws Exception {
ConfigureBudgetPage configureBudgetPage = new ConfigureBudgetPage(testWebDriver);
configureBudgetPage.clickSaveButton();
}
@Then("^I should see budget successful saved message as \"([^\"]*)\"$")
public void verifySaveSuccessfullyMessage(String message) throws Exception {
ConfigureBudgetPage configureBudgetPage = new ConfigureBudgetPage(testWebDriver);
configureBudgetPage.verifyMessage(message);
}
@Test(groups = {"admin"}, dataProvider = "Data-Provider-Function")
public void testVerifyDefaultSelectionOfPackedDropdown(String user, String password) throws Exception {
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(user, password);
ConfigureEDIPage configureEDIPage = homePage.navigateEdiScreen();
ConfigureBudgetPage configureBudgetPage = configureEDIPage.navigateConfigureBudgetPage();
String packedDate = configureBudgetPage.getSelectedOptionOfPeriodStartDateDropDown();
assertEquals(packedDate, "dd/MM/yy");
}
@Test(groups = {"admin"}, dataProvider = "Data-Provider-Function")
public void testEditPackedDropDown(String user, String password) throws Exception {
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(user, password);
ConfigureEDIPage configureEDIPage = homePage.navigateEdiScreen();
ConfigureBudgetPage configureBudgetPage = configureEDIPage.navigateConfigureBudgetPage();
configureBudgetPage.selectValueFromPeriodStartDateDropDown("MM-dd-yyyy");
configureBudgetPage.clickSaveButton();
configureBudgetPage.verifyMessage("Budget file configuration saved successfully!");
String packedDate = configureBudgetPage.getSelectedOptionOfPeriodStartDateDropDown();
assertEquals(packedDate, "MM-dd-yyyy");
configureBudgetPage.selectValueFromPeriodStartDateDropDown("yyyy/MM/dd");
configureBudgetPage.clickSaveButton();
configureBudgetPage.verifyMessage("Budget file configuration saved successfully!");
packedDate = configureBudgetPage.getSelectedOptionOfPeriodStartDateDropDown();
assertEquals(packedDate, "yyyy/MM/dd");
}
@Test(groups = {"admin"}, dataProvider = "Data-Provider-Function")
public void testVerifyIncludeColumnHeaderONWithAllPositionsAltered(String user, String password) throws Exception {
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(user, password);
ConfigureEDIPage configureEDIPage = homePage.navigateEdiScreen();
ConfigureBudgetPage configureBudgetPage = configureEDIPage.navigateConfigureBudgetPage();
configureBudgetPage.checkIncludeHeader();
configureBudgetPage.setAllocatedBudget("101") ;
configureBudgetPage.setFacilityCode("1022") ;
configureBudgetPage.checkNotesCheckBox();
configureBudgetPage.setNotes("103");
configureBudgetPage.setProgramCode("104");
configureBudgetPage.checkPeriodStartDateCheckBox();
configureBudgetPage.setPeriodStartDate("105");
configureBudgetPage.clickSaveButton();
configureBudgetPage.verifyMessage("Budget file configuration saved successfully!");
assertTrue(configureBudgetPage.getIncludeHeader());
assertEquals("101", configureBudgetPage.getAllocatedBudget());
assertEquals("102", configureBudgetPage.getFacilityCode());
assertEquals("103", configureBudgetPage.getNotes());
assertEquals("104", configureBudgetPage.getProgramCode());
assertEquals("105", configureBudgetPage.getPeriodStartDate());
}
@Test(groups = {"admin"}, dataProvider = "Data-Provider-Function")
public void testVerifyIncludeColumnHeaderOFFWithMandatoryPositionsAltered(String user, String password) throws Exception {
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(user, password);
ConfigureEDIPage configureEDIPage = homePage.navigateEdiScreen();
ConfigureBudgetPage configureBudgetPage = configureEDIPage.navigateConfigureBudgetPage();
configureBudgetPage.unCheckIncludeHeader();
configureBudgetPage.setAllocatedBudget("101") ;
configureBudgetPage.setFacilityCode("102") ;
configureBudgetPage.unCheckCostCheckBox();
configureBudgetPage.setProgramCode("103");
configureBudgetPage.unCheckPeriodStartDateCheckBox();
configureBudgetPage.clickSaveButton();
configureBudgetPage.verifyMessage("Budget file configuration saved successfully!");
assertFalse(configureBudgetPage.getIncludeHeader());
assertEquals(configureBudgetPage.getAllocatedBudget(),"101");
assertEquals(configureBudgetPage.getFacilityCode(),"102");
assertEquals(configureBudgetPage.getNotes(),"5");
assertEquals(configureBudgetPage.getProgramCode(),"103");
assertEquals(configureBudgetPage.getPeriodStartDate(),"3");
configureBudgetPage.clickCancelButton();
assertTrue("User should be redirected to EDI Config page", testWebDriver.getCurrentUrl().contains("public/pages/admin/edi/index.html#/configure-edi-file"));
}
@Test(groups = {"admin"}, dataProvider = "Data-Provider-Function")
public void testVerifyDuplicatePosition(String user, String password) throws Exception {
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(user, password);
ConfigureEDIPage configureEDIPage = homePage.navigateEdiScreen();
ConfigureBudgetPage configureBudgetPage = configureEDIPage.navigateConfigureBudgetPage();
configureBudgetPage.setAllocatedBudget("101") ;
configureBudgetPage.setFacilityCode("101") ;
configureBudgetPage.clickSaveButton();
configureBudgetPage.verifyErrorMessage("Position numbers cannot have duplicate values");
}
@Test(groups = {"admin"}, dataProvider = "Data-Provider-Function")
public void testVerifyZeroPosition(String user, String password) throws Exception {
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(user, password);
ConfigureEDIPage configureEDIPage = homePage.navigateEdiScreen();
ConfigureBudgetPage configureBudgetPage = configureEDIPage.navigateConfigureBudgetPage();
configureBudgetPage.setAllocatedBudget("0") ;
configureBudgetPage.setFacilityCode("101") ;
configureBudgetPage.clickSaveButton();
configureBudgetPage.verifyErrorMessage("Position number cannot be blank or zero for an included field");
}
@Test(groups = {"admin"}, dataProvider = "Data-Provider-Function")
public void testVerifyBlankPosition(String user, String password) throws Exception {
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(user, password);
ConfigureEDIPage configureEDIPage = homePage.navigateEdiScreen();
ConfigureBudgetPage configureBudgetPage = configureEDIPage.navigateConfigureBudgetPage();
configureBudgetPage.setAllocatedBudget("101") ;
configureBudgetPage.setFacilityCode("") ;
configureBudgetPage.clickSaveButton();
configureBudgetPage.verifyErrorMessage("Position number cannot be blank or zero for an included field");
}
@After
@AfterMethod(groups = "admin")
public void tearDown() throws Exception {
testWebDriver.sleep(500);
if (!testWebDriver.getElementById("username").isDisplayed()) {
HomePage homePage = new HomePage(testWebDriver);
homePage.logout(baseUrlGlobal);
dbWrapper.deleteData();
dbWrapper.closeConnection();
}
}
@DataProvider(name = "Data-Provider-Function")
public Object[][] parameterIntTestProviderPositive() {
return new Object[][]{
{"Admin123", "Admin123"}
};
}
}
| test-modules/functional-tests/src/test/java/org/openlmis/functional/ConfigureBudgetTemplate.java | /*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2013 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses. For additional information contact [email protected].
*/
package org.openlmis.functional;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.openlmis.UiUtils.CaptureScreenshotOnFailureListener;
import org.openlmis.UiUtils.TestCaseHelper;
import org.openlmis.pageobjects.ConfigureEDIPage;
import org.openlmis.pageobjects.ConfigureBudgetPage;
import org.openlmis.pageobjects.HomePage;
import org.openlmis.pageobjects.LoginPage;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.testng.annotations.*;
import static com.thoughtworks.selenium.SeleneseTestBase.assertFalse;
import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue;
import static com.thoughtworks.selenium.SeleneseTestNgHelper.assertEquals;
@TransactionConfiguration(defaultRollback = true)
@Transactional
@Listeners(CaptureScreenshotOnFailureListener.class)
public class ConfigureBudgetTemplate extends TestCaseHelper {
@BeforeMethod(groups = "admin")
@Before
public void setUp() throws Exception {
super.setup();
dbWrapper.setupBudgetFileConfiguration("false");
dbWrapper.defaultSetupBudgetFileColumns();
}
@And("^I access configure budget page$")
public void accessOrderScreen() throws Exception {
HomePage homePage = new HomePage(testWebDriver);
ConfigureEDIPage configureEDIPage = homePage.navigateEdiScreen();
configureEDIPage.navigateConfigureBudgetPage();
}
@And("^I should see default include column headers as \"([^\"]*)\"$")
public void verifyIncludeColumnHeader(String status) throws Exception {
ConfigureBudgetPage configureBudgetPage = new ConfigureBudgetPage(testWebDriver);
assertEquals(String.valueOf(configureBudgetPage.getIncludeHeader()), status);
}
@And("^I verify default checkbox for all data fields$")
public void verifyDefaultDataFieldsCheckBox() throws Exception {
ConfigureBudgetPage configureBudgetPage = new ConfigureBudgetPage(testWebDriver);
configureBudgetPage.verifyDefaultIncludeCheckboxForAllDataFields();
}
@And("^I verify default value of positions$")
public void verifyDefaultPositionValues() throws Exception {
ConfigureBudgetPage configureBudgetPage = new ConfigureBudgetPage(testWebDriver);
configureBudgetPage.verifyDefaultPositionValues();
}
@When("^I save budget file format$")
public void clickSave() throws Exception {
ConfigureBudgetPage configureBudgetPage = new ConfigureBudgetPage(testWebDriver);
configureBudgetPage.clickSaveButton();
}
@Then("^I should see budget successfull saved message as \"([^\"]*)\"$")
public void verifySaveSuccessfullyMessage(String message) throws Exception {
ConfigureBudgetPage configureBudgetPage = new ConfigureBudgetPage(testWebDriver);
configureBudgetPage.verifyMessage(message);
}
@Test(groups = {"admin"}, dataProvider = "Data-Provider-Function")
public void testVerifyDefaultSelectionOfPackedDropdown(String user, String password) throws Exception {
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(user, password);
ConfigureEDIPage configureEDIPage = homePage.navigateEdiScreen();
ConfigureBudgetPage configureBudgetPage = configureEDIPage.navigateConfigureBudgetPage();
String packedDate = configureBudgetPage.getSelectedOptionOfPeriodStartDateDropDown();
assertEquals(packedDate, "dd/MM/yy");
}
@Test(groups = {"admin"}, dataProvider = "Data-Provider-Function")
public void testEditPackedDropDown(String user, String password) throws Exception {
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(user, password);
ConfigureEDIPage configureEDIPage = homePage.navigateEdiScreen();
ConfigureBudgetPage configureBudgetPage = configureEDIPage.navigateConfigureBudgetPage();
configureBudgetPage.selectValueFromPeriodStartDateDropDown("MM-dd-yyyy");
configureBudgetPage.clickSaveButton();
configureBudgetPage.verifyMessage("Budget file configuration saved successfully!");
String packedDate = configureBudgetPage.getSelectedOptionOfPeriodStartDateDropDown();
assertEquals(packedDate, "MM-dd-yyyy");
configureBudgetPage.selectValueFromPeriodStartDateDropDown("yyyy/MM/dd");
configureBudgetPage.clickSaveButton();
configureBudgetPage.verifyMessage("Budget file configuration saved successfully!");
packedDate = configureBudgetPage.getSelectedOptionOfPeriodStartDateDropDown();
assertEquals(packedDate, "yyyy/MM/dd");
}
@Test(groups = {"admin"}, dataProvider = "Data-Provider-Function")
public void testVerifyIncludeColumnHeaderONWithAllPositionsAltered(String user, String password) throws Exception {
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(user, password);
ConfigureEDIPage configureEDIPage = homePage.navigateEdiScreen();
ConfigureBudgetPage configureBudgetPage = configureEDIPage.navigateConfigureBudgetPage();
configureBudgetPage.checkIncludeHeader();
configureBudgetPage.setAllocatedBudget("101") ;
configureBudgetPage.setFacilityCode("1022") ;
configureBudgetPage.checkNotesCheckBox();
configureBudgetPage.setNotes("103");
configureBudgetPage.setProgramCode("104");
configureBudgetPage.checkPeriodStartDateCheckBox();
configureBudgetPage.setPeriodStartDate("105");
configureBudgetPage.clickSaveButton();
configureBudgetPage.verifyMessage("Budget file configuration saved successfully!");
assertTrue(configureBudgetPage.getIncludeHeader());
assertEquals("101", configureBudgetPage.getAllocatedBudget());
assertEquals("102", configureBudgetPage.getFacilityCode());
assertEquals("103", configureBudgetPage.getNotes());
assertEquals("104", configureBudgetPage.getProgramCode());
assertEquals("105", configureBudgetPage.getPeriodStartDate());
}
@Test(groups = {"admin"}, dataProvider = "Data-Provider-Function")
public void testVerifyIncludeColumnHeaderOFFWithMandatoryPositionsAltered(String user, String password) throws Exception {
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(user, password);
ConfigureEDIPage configureEDIPage = homePage.navigateEdiScreen();
ConfigureBudgetPage configureBudgetPage = configureEDIPage.navigateConfigureBudgetPage();
configureBudgetPage.unCheckIncludeHeader();
configureBudgetPage.setAllocatedBudget("101") ;
configureBudgetPage.setFacilityCode("102") ;
configureBudgetPage.unCheckCostCheckBox();
configureBudgetPage.setProgramCode("103");
configureBudgetPage.unCheckPeriodStartDateCheckBox();
configureBudgetPage.clickSaveButton();
configureBudgetPage.verifyMessage("Budget file configuration saved successfully!");
assertFalse(configureBudgetPage.getIncludeHeader());
assertEquals(configureBudgetPage.getAllocatedBudget(),"101");
assertEquals(configureBudgetPage.getFacilityCode(),"102");
assertEquals(configureBudgetPage.getNotes(),"5");
assertEquals(configureBudgetPage.getProgramCode(),"103");
assertEquals(configureBudgetPage.getPeriodStartDate(),"3");
configureBudgetPage.clickCancelButton();
assertTrue("User should be redirected to EDI Config page", testWebDriver.getCurrentUrl().contains("public/pages/admin/edi/index.html#/configure-edi-file"));
}
@Test(groups = {"admin"}, dataProvider = "Data-Provider-Function")
public void testVerifyDuplicatePosition(String user, String password) throws Exception {
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(user, password);
ConfigureEDIPage configureEDIPage = homePage.navigateEdiScreen();
ConfigureBudgetPage configureBudgetPage = configureEDIPage.navigateConfigureBudgetPage();
configureBudgetPage.setAllocatedBudget("101") ;
configureBudgetPage.setFacilityCode("101") ;
configureBudgetPage.clickSaveButton();
configureBudgetPage.verifyErrorMessage("Position numbers cannot have duplicate values");
}
@Test(groups = {"admin"}, dataProvider = "Data-Provider-Function")
public void testVerifyZeroPosition(String user, String password) throws Exception {
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(user, password);
ConfigureEDIPage configureEDIPage = homePage.navigateEdiScreen();
ConfigureBudgetPage configureBudgetPage = configureEDIPage.navigateConfigureBudgetPage();
configureBudgetPage.setAllocatedBudget("0") ;
configureBudgetPage.setFacilityCode("101") ;
configureBudgetPage.clickSaveButton();
configureBudgetPage.verifyErrorMessage("Position number cannot be blank or zero for an included field");
}
@Test(groups = {"admin"}, dataProvider = "Data-Provider-Function")
public void testVerifyBlankPosition(String user, String password) throws Exception {
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(user, password);
ConfigureEDIPage configureEDIPage = homePage.navigateEdiScreen();
ConfigureBudgetPage configureBudgetPage = configureEDIPage.navigateConfigureBudgetPage();
configureBudgetPage.setAllocatedBudget("101") ;
configureBudgetPage.setFacilityCode("") ;
configureBudgetPage.clickSaveButton();
configureBudgetPage.verifyErrorMessage("Position number cannot be blank or zero for an included field");
}
@After
@AfterMethod(groups = "admin")
public void tearDown() throws Exception {
testWebDriver.sleep(500);
if (!testWebDriver.getElementById("username").isDisplayed()) {
HomePage homePage = new HomePage(testWebDriver);
homePage.logout(baseUrlGlobal);
dbWrapper.deleteData();
dbWrapper.closeConnection();
}
}
@DataProvider(name = "Data-Provider-Function")
public Object[][] parameterIntTestProviderPositive() {
return new Object[][]{
{"Admin123", "Admin123"}
};
}
}
| Raman - Fixed requisition smoke for missing step
| test-modules/functional-tests/src/test/java/org/openlmis/functional/ConfigureBudgetTemplate.java | Raman - Fixed requisition smoke for missing step | <ide><path>est-modules/functional-tests/src/test/java/org/openlmis/functional/ConfigureBudgetTemplate.java
<ide> configureBudgetPage.clickSaveButton();
<ide> }
<ide>
<del> @Then("^I should see budget successfull saved message as \"([^\"]*)\"$")
<add> @Then("^I should see budget successful saved message as \"([^\"]*)\"$")
<ide> public void verifySaveSuccessfullyMessage(String message) throws Exception {
<ide> ConfigureBudgetPage configureBudgetPage = new ConfigureBudgetPage(testWebDriver);
<ide> configureBudgetPage.verifyMessage(message); |
|
JavaScript | apache-2.0 | f4a858e33d417a8664e8cf8719c1ff074cb9bf83 | 0 | duke-compsci290-spring2016/sakai,whumph/sakai,buckett/sakai-gitflow,colczr/sakai,puramshetty/sakai,bkirschn/sakai,liubo404/sakai,puramshetty/sakai,joserabal/sakai,kwedoff1/sakai,surya-janani/sakai,puramshetty/sakai,noondaysun/sakai,bkirschn/sakai,duke-compsci290-spring2016/sakai,hackbuteer59/sakai,conder/sakai,noondaysun/sakai,buckett/sakai-gitflow,zqian/sakai,conder/sakai,tl-its-umich-edu/sakai,noondaysun/sakai,noondaysun/sakai,surya-janani/sakai,lorenamgUMU/sakai,kingmook/sakai,lorenamgUMU/sakai,zqian/sakai,zqian/sakai,Fudan-University/sakai,duke-compsci290-spring2016/sakai,rodriguezdevera/sakai,puramshetty/sakai,colczr/sakai,whumph/sakai,whumph/sakai,tl-its-umich-edu/sakai,colczr/sakai,rodriguezdevera/sakai,OpenCollabZA/sakai,OpenCollabZA/sakai,surya-janani/sakai,frasese/sakai,hackbuteer59/sakai,wfuedu/sakai,frasese/sakai,bkirschn/sakai,bkirschn/sakai,clhedrick/sakai,pushyamig/sakai,introp-software/sakai,frasese/sakai,liubo404/sakai,bkirschn/sakai,lorenamgUMU/sakai,duke-compsci290-spring2016/sakai,ouit0408/sakai,ktakacs/sakai,colczr/sakai,pushyamig/sakai,rodriguezdevera/sakai,hackbuteer59/sakai,OpenCollabZA/sakai,pushyamig/sakai,Fudan-University/sakai,ouit0408/sakai,buckett/sakai-gitflow,joserabal/sakai,willkara/sakai,joserabal/sakai,lorenamgUMU/sakai,whumph/sakai,duke-compsci290-spring2016/sakai,whumph/sakai,introp-software/sakai,Fudan-University/sakai,Fudan-University/sakai,noondaysun/sakai,ktakacs/sakai,introp-software/sakai,ktakacs/sakai,Fudan-University/sakai,frasese/sakai,ktakacs/sakai,conder/sakai,liubo404/sakai,willkara/sakai,colczr/sakai,duke-compsci290-spring2016/sakai,ktakacs/sakai,bzhouduke123/sakai,bzhouduke123/sakai,clhedrick/sakai,clhedrick/sakai,kwedoff1/sakai,buckett/sakai-gitflow,bkirschn/sakai,liubo404/sakai,buckett/sakai-gitflow,willkara/sakai,wfuedu/sakai,udayg/sakai,udayg/sakai,noondaysun/sakai,liubo404/sakai,udayg/sakai,bzhouduke123/sakai,clhedrick/sakai,conder/sakai,tl-its-umich-edu/sakai,colczr/sakai,wfuedu/sakai,OpenCollabZA/sakai,ktakacs/sakai,zqian/sakai,surya-janani/sakai,bzhouduke123/sakai,bkirschn/sakai,pushyamig/sakai,ouit0408/sakai,pushyamig/sakai,Fudan-University/sakai,wfuedu/sakai,OpenCollabZA/sakai,ouit0408/sakai,kingmook/sakai,rodriguezdevera/sakai,kingmook/sakai,hackbuteer59/sakai,bkirschn/sakai,ktakacs/sakai,kwedoff1/sakai,buckett/sakai-gitflow,buckett/sakai-gitflow,udayg/sakai,wfuedu/sakai,tl-its-umich-edu/sakai,whumph/sakai,rodriguezdevera/sakai,udayg/sakai,frasese/sakai,OpenCollabZA/sakai,zqian/sakai,frasese/sakai,ouit0408/sakai,kingmook/sakai,whumph/sakai,willkara/sakai,kwedoff1/sakai,clhedrick/sakai,tl-its-umich-edu/sakai,bzhouduke123/sakai,surya-janani/sakai,colczr/sakai,udayg/sakai,hackbuteer59/sakai,willkara/sakai,Fudan-University/sakai,wfuedu/sakai,conder/sakai,udayg/sakai,kingmook/sakai,duke-compsci290-spring2016/sakai,buckett/sakai-gitflow,joserabal/sakai,lorenamgUMU/sakai,rodriguezdevera/sakai,puramshetty/sakai,clhedrick/sakai,liubo404/sakai,liubo404/sakai,joserabal/sakai,bzhouduke123/sakai,surya-janani/sakai,noondaysun/sakai,Fudan-University/sakai,willkara/sakai,puramshetty/sakai,kwedoff1/sakai,hackbuteer59/sakai,introp-software/sakai,tl-its-umich-edu/sakai,hackbuteer59/sakai,colczr/sakai,kwedoff1/sakai,pushyamig/sakai,rodriguezdevera/sakai,kwedoff1/sakai,conder/sakai,conder/sakai,tl-its-umich-edu/sakai,willkara/sakai,introp-software/sakai,ouit0408/sakai,frasese/sakai,zqian/sakai,kingmook/sakai,rodriguezdevera/sakai,clhedrick/sakai,lorenamgUMU/sakai,kwedoff1/sakai,zqian/sakai,OpenCollabZA/sakai,bzhouduke123/sakai,joserabal/sakai,pushyamig/sakai,kingmook/sakai,wfuedu/sakai,pushyamig/sakai,clhedrick/sakai,tl-its-umich-edu/sakai,introp-software/sakai,ktakacs/sakai,ouit0408/sakai,wfuedu/sakai,introp-software/sakai,puramshetty/sakai,surya-janani/sakai,puramshetty/sakai,joserabal/sakai,lorenamgUMU/sakai,udayg/sakai,joserabal/sakai,liubo404/sakai,lorenamgUMU/sakai,duke-compsci290-spring2016/sakai,bzhouduke123/sakai,OpenCollabZA/sakai,kingmook/sakai,noondaysun/sakai,zqian/sakai,conder/sakai,willkara/sakai,ouit0408/sakai,whumph/sakai,surya-janani/sakai,frasese/sakai,introp-software/sakai,hackbuteer59/sakai | var serializationChanged = new Boolean(false);
function serialize(s)
{
//kill the unsaved changes message
if (navigator.userAgent.toLowerCase().indexOf("safari") != -1 && window != top) {
top.onbeforeunload = function() { };
}
else {
window.onbeforeunload = function() { };
}
serial = $.SortSerialize(s);
//TODO: replace regexp stuff with a new hidden id item
var pageOrder = serial.hash;
pageOrder = pageOrder.replace(/:&sort1\[\]=content:::page-row::/g, ' ');
pageOrder = pageOrder.replace('sort1[]=content:::page-row::', '');
pageOrder = pageOrder.substring(0, pageOrder.length - 1);
document.getElementById('content:::state-init').value = pageOrder;
}
function doRemovePage(clickedLink) {
var name = $(clickedLink).parent().parent().find(".item_label_box").text();
var conf = confirm($("#del-message").text() + " " + name + "?");
if (conf == true) {
$("#call-results").fadeOut('400');
$("#call-results").load(clickedLink, function() {
var status = $(this).find("div[@id='value']").text();
if (status == "pass") {
var target = $(clickedLink).parent().parent();
$(this).fadeIn('400');
$(target).slideUp('fast', $(target).remove());
}
else if (status == "fail") {
$(this).fadeIn('400');
}
//TODO: refresh available pages, but don't mess up display message
resetFrame();
});
}
return conf;
}
function doShowPage(clickedLink) {
$(clickedLink).parent().parent().find(".item_control.show_link").hide();
$(clickedLink).parent().parent().find(".indicator").show();
$("#call-results").fadeOut('10');
$("#call-results").load(clickedLink, function() {
var status = $("#call-results").find("#value").text();
$(clickedLink).parent().parent().find(".indicator").hide();
if (status == "pass") {
$(clickedLink).parent().parent().find(".item_control.hide_link").show();
$("#call-results").fadeIn('400');
}
else if (status == "fail") {
$(clickedLink).parent().parent().find(".item_control.show_link").show();
$("#call-results").fadeIn('400');
}
});
}
function doHidePage(clickedLink) {
$(clickedLink).parent().parent().find(".item_control.hide_link").hide();
$(clickedLink).parent().parent().find(".indicator").show();
$("#call-results").fadeOut('10');
$("#call-results").load(clickedLink, function() {
var status = $("#call-results").find("#value").text();
$(clickedLink).parent().parent().find(".indicator").hide();
if (status == "pass") {
$(clickedLink).parent().parent().find(".item_control.show_link").show();
$("#call-results").fadeIn('400');
}
else if (status == "fail") {
$(clickedLink).parent().parent().find(".item_control.hide_link").show();
$("#call-results").fadeIn('400');
}
});
}
function doEditPage(clickedLink) {
$("#call-results").load(clickedLink, function() {
var status = $("#call-results").find("#value").text();
if (status == "pass") {
var target = document.getElementById('content:::page-row::' + $("#call-results").find("#pageId").text() + ':');
$("#call-results").fadeIn('500');
}
else if (status == "fail") {
$("#call-results").fadeIn('500');
}
});
}
function showAddPage(clickedLink) {
$("#add-panel").load(clickedLink, function() {
$("#call-results").fadeOut('10');
$("#add-control").fadeOut('10');
$("#call-results").html($(this).find("#message").html());
$(this).find("#message").remove();
$("#list-label").background("#9F9");
$("#option-label").background("#99F");
$(".tool_list").css("border", "1px solid #ccc");
$("#list-label").fadeIn('normal');
$("#add-panel").slideDown('normal', resetFrame());
$("#call-results").fadeIn('500');
});
}
function showEditPage(clickedLink) {
li = $(clickedLink).parent().parent();
$(li).find(".item_label_box").hide();
$(li).find(".item_control_box").hide();
$(li).find(".item_edit_box").fadeIn('normal');
$(li).removeClass("sortable_item");
$(li).addClass("editable_item");
$(li).unbind();
}
function doSaveEdit(clickedLink) {
li = $(clickedLink).parent().parent();
newTitle = $(li).find(".new_title");
newConfig = $(li).find(".new_config");
$("#call-results").load(clickedLink + "&newTitle=" + newTitle.val() + "&newConfig=" + newConfig.val(), function() {
var status = $("#call-results").find("#value").text();
$(li).find(".item_edit_box").hide();
if (status == 'pass') {
newTitle = $("#call-results").find("#pageId strong").html();
$(li).find(".item_label_box").empty();
$(li).find(".item_label_box").append(newTitle);
}
$(li).find(".item_label_box").show();
$(li).find(".item_label_box").attr("style", "display: inline");
$(li).find(".item_control_box").show();
$(li).find(".item_control_box").attr("style", "display: inline");
$(li).addClass("sortable_item");
$(li).removeClass("editable_item");
makeSortable($(li).parent());
});
}
function doCancelEdit(clickedLink) {
li = $(clickedLink).parent().parent();
$(li).find(".item_edit_box").hide();
$(li).find(".item_label_box").show();
$(li).find(".item_label_box").attr("style", "display: inline");
$(li).find(".item_control_box").show();
$(li).find(".item_control_box").attr("style", "display: inline");
$(li).addClass("sortable_item");
$(li).removeClass("editable_item");
$(li).find(".new_title").val($(li).find(".item_label_box").text());
makeSortable($(li).parent());
}
function checkReset() {
var reset = confirm($("#reset-message").text());
if (reset)
return true;
else
return false;
}
function makeSortable(path) {
$(path).Sortable( {
accept : 'sortable_item',
activeclass : 'sortable_active',
hoverclass : 'sortable_hover',
helperclass : 'sort_helper',
opacity: 0.8,
revert: true,
tolerance: 'intersect',
onStop: function () {
if (serializationChanged == false) {
serializationChanged = true;
//Makes the assumption that it is ok to over write the onbeforeexit event on top
//which is a safe assumption *most* of the time and it's only needed for Safari
if (navigator.userAgent.toLowerCase().indexOf("safari") != -1 && window != top) {
top.pageOrderExitMessage = $("#exit-message").text();
top.onbeforeunload = function() { return top.pageOrderExitMessage };
}
else {
window.onbeforeunload = function() { return $("#exit-message").text(); };
}
}
}
});
}
function makeDraggable(path) {
$(path).Draggable( {
revert : true,
onStop: function () {
if ($(this).parent().attr('id') == 'sort1') {
addTool($(this), false);
}
}
});
}
function addTool(draggable, manual) {
if (manual == true) {
// we got fired via the add link not a drag and drop..
// so we need to manually add to the list
$('#sort1').append(draggable);
}
$(draggable).attr("style", "");
//force possitioning so IE displays this right
$(draggable).position("static");
$("#call-results").fadeOut('200');
url = $(draggable).find(".tool_add_url").attr("href");
oldId = $(draggable).id();
$(draggable).empty();
li = $(draggable);
$("#call-results").load(url, function() {
$(li).DraggableDestroy();
$(li).id("content:::" + $("#call-results").find("li").id());
$(li).html($("#call-results").find("li").html());
$(this).find("li").remove();
makeSortable($(li).parent());
});
$("#call-results").fadeIn('200');
resetFrame();
return false;
}
| site-manage/pageorder/tool/src/webapp/content/js/orderUtil.js | var serializationChanged = new Boolean(false);
function serialize(s)
{
//kill the unsaved changes message
if (navigator.userAgent.toLowerCase().indexOf("safari") != -1 && window != top) {
top.onbeforeunload = function() { };
}
else {
window.onbeforeunload = function() { };
}
serial = $.SortSerialize(s);
//TODO: replace regexp stuff with a new hidden id item
var pageOrder = serial.hash;
pageOrder = pageOrder.replace(/:&sort1\[\]=content:::page-row::/g, ' ');
pageOrder = pageOrder.replace('sort1[]=content:::page-row::', '');
pageOrder = pageOrder.substring(0, pageOrder.length - 1);
document.getElementById('content:::state-init').value = pageOrder;
}
function doRemovePage(clickedLink) {
var name = $(clickedLink).parent().parent().find(".item_label_box").text();
var conf = confirm($("#del-message").text() + " " + name + "?");
if (conf == true) {
$("#call-results").fadeOut('400');
$("#call-results").load(clickedLink, function() {
var status = $(this).find("div[@id='value']").text();
if (status == "pass") {
var target = $(clickedLink).parent().parent();
$(this).fadeIn('400');
$(target).slideUp('fast', $(target).remove());
}
else if (status == "fail") {
$(this).fadeIn('400');
}
//TODO: refresh available pages, but don't mess up display message
resetFrame();
});
}
return conf;
}
function doShowPage(clickedLink) {
$(clickedLink).parent().parent().find(".item_control.show_link").hide();
$(clickedLink).parent().parent().find(".indicator").show();
$("#call-results").fadeOut('10');
$("#call-results").load(clickedLink, function() {
var status = $("#call-results").find("#value").text();
$(clickedLink).parent().parent().find(".indicator").hide();
if (status == "pass") {
$(clickedLink).parent().parent().find(".item_control.hide_link").show();
$("#call-results").fadeIn('400');
}
else if (status == "fail") {
$(clickedLink).parent().parent().find(".item_control.show_link").show();
$("#call-results").fadeIn('400');
}
});
}
function doHidePage(clickedLink) {
$(clickedLink).parent().parent().find(".item_control.hide_link").hide();
$(clickedLink).parent().parent().find(".indicator").show();
$("#call-results").fadeOut('10');
$("#call-results").load(clickedLink, function() {
var status = $("#call-results").find("#value").text();
$(clickedLink).parent().parent().find(".indicator").hide();
if (status == "pass") {
$(clickedLink).parent().parent().find(".item_control.show_link").show();
$("#call-results").fadeIn('400');
}
else if (status == "fail") {
$(clickedLink).parent().parent().find(".item_control.hide_link").show();
$("#call-results").fadeIn('400');
}
});
}
function doEditPage(clickedLink) {
$("#call-results").load(clickedLink, function() {
var status = $("#call-results").find("#value").text();
if (status == "pass") {
var target = document.getElementById('content:::page-row::' + $("#call-results").find("#pageId").text() + ':');
$("#call-results").fadeIn('500');
}
else if (status == "fail") {
$("#call-results").fadeIn('500');
}
});
}
function showAddPage(clickedLink) {
$("#add-panel").load(clickedLink, function() {
$("#call-results").fadeOut('10');
$("#add-control").fadeOut('10');
$("#call-results").html($(this).find("#message").html());
$(this).find("#message").remove();
$("#list-label").background("#9F9");
$("#option-label").background("#99F");
$(".tool_list").css("border", "1px solid #ccc");
$("#list-label").fadeIn('normal');
$("#add-panel").slideDown('normal', resetFrame());
$("#call-results").fadeIn('500');
});
}
function showEditPage(clickedLink) {
li = $(clickedLink).parent().parent();
$(li).find(".item_label_box").hide();
$(li).find(".item_control_box").hide();
$(li).find(".item_edit_box").fadeIn('normal');
$(li).removeClass("sortable_item");
$(li).addClass("editable_item");
$(li).unbind();
}
function doSaveEdit(clickedLink) {
li = $(clickedLink).parent().parent();
newTitle = $(li).find(".new_title");
newConfig = $(li).find(".new_config");
$("#call-results").load(clickedLink + "&newTitle=" + newTitle.val() + "&newConfig=" + newConfig.val(), function() {
var status = $("#call-results").find("#value").text();
$(li).find(".item_edit_box").hide();
if (status == 'pass') {
$(li).find(".item_label_box").empty();
$(li).find(".item_label_box").append(newTitle.val());
}
$(li).find(".item_label_box").show();
$(li).find(".item_label_box").attr("style", "display: inline");
$(li).find(".item_control_box").show();
$(li).find(".item_control_box").attr("style", "display: inline");
$(li).addClass("sortable_item");
$(li).removeClass("editable_item");
makeSortable($(li).parent());
});
}
function doCancelEdit(clickedLink) {
li = $(clickedLink).parent().parent();
$(li).find(".item_edit_box").hide();
$(li).find(".item_label_box").show();
$(li).find(".item_label_box").attr("style", "display: inline");
$(li).find(".item_control_box").show();
$(li).find(".item_control_box").attr("style", "display: inline");
$(li).addClass("sortable_item");
$(li).removeClass("editable_item");
$(li).find(".new_title").val($(li).find(".item_label_box").text());
makeSortable($(li).parent());
}
function checkReset() {
var reset = confirm($("#reset-message").text());
if (reset)
return true;
else
return false;
}
function makeSortable(path) {
$(path).Sortable( {
accept : 'sortable_item',
activeclass : 'sortable_active',
hoverclass : 'sortable_hover',
helperclass : 'sort_helper',
opacity: 0.8,
revert: true,
tolerance: 'intersect',
onStop: function () {
if (serializationChanged == false) {
serializationChanged = true;
//Makes the assumption that it is ok to over write the onbeforeexit event on top
//which is a safe assumption *most* of the time and it's only needed for Safari
if (navigator.userAgent.toLowerCase().indexOf("safari") != -1 && window != top) {
top.pageOrderExitMessage = $("#exit-message").text();
top.onbeforeunload = function() { return top.pageOrderExitMessage };
}
else {
window.onbeforeunload = function() { return $("#exit-message").text(); };
}
}
}
});
}
function makeDraggable(path) {
$(path).Draggable( {
revert : true,
onStop: function () {
if ($(this).parent().attr('id') == 'sort1') {
addTool($(this), false);
}
}
});
}
function addTool(draggable, manual) {
if (manual == true) {
// we got fired via the add link not a drag and drop..
// so we need to manually add to the list
$('#sort1').append(draggable);
}
$(draggable).attr("style", "");
//force possitioning so IE displays this right
$(draggable).position("static");
$("#call-results").fadeOut('200');
url = $(draggable).find(".tool_add_url").attr("href");
oldId = $(draggable).id();
$(draggable).empty();
li = $(draggable);
$("#call-results").load(url, function() {
$(li).DraggableDestroy();
$(li).id("content:::" + $("#call-results").find("li").id());
$(li).html($("#call-results").find("li").html());
$(this).find("li").remove();
makeSortable($(li).parent());
});
$("#call-results").fadeIn('200');
resetFrame();
return false;
}
| SAK-9142 using returned new title, processed by FormattedText, which is fully escaped and safe
git-svn-id: 19a9fd284f7506c72ea2840aac2b5d740703d7e8@28439 66ffb92e-73f9-0310-93c1-f5514f145a0a
| site-manage/pageorder/tool/src/webapp/content/js/orderUtil.js | SAK-9142 using returned new title, processed by FormattedText, which is fully escaped and safe | <ide><path>ite-manage/pageorder/tool/src/webapp/content/js/orderUtil.js
<ide> var status = $("#call-results").find("#value").text();
<ide> $(li).find(".item_edit_box").hide();
<ide> if (status == 'pass') {
<add> newTitle = $("#call-results").find("#pageId strong").html();
<ide> $(li).find(".item_label_box").empty();
<del> $(li).find(".item_label_box").append(newTitle.val());
<add> $(li).find(".item_label_box").append(newTitle);
<ide> }
<ide> $(li).find(".item_label_box").show();
<ide> $(li).find(".item_label_box").attr("style", "display: inline");
<ide> resetFrame();
<ide> return false;
<ide> }
<add> |
|
Java | mit | 8156895bce9b56364b28baa34d2c1689779423d1 | 0 | satyan/sugar,mitchyboy9/sugar,dnalves/sugar,RossinesP/sugar,AdamLuptak/Time_MNA,mbag102/sugar,janzoner/sugar | package com.orm.util;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.util.Log;
import com.orm.SugarRecord;
import com.orm.dsl.Ignore;
import com.orm.dsl.Table;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
public class ReflectionUtil {
public static List<Field> getTableFields(Class table) {
List<Field> fieldList = SugarConfig.getFields(table);
if (fieldList != null) return fieldList;
Log.d("Sugar", "Fetching properties");
List<Field> typeFields = new ArrayList<Field>();
getAllFields(typeFields, table);
List<Field> toStore = new ArrayList<Field>();
for (Field field : typeFields) {
if (!field.isAnnotationPresent(Ignore.class) && !Modifier.isStatic(field.getModifiers()) && !Modifier.isTransient(field.getModifiers())) {
toStore.add(field);
}
}
SugarConfig.setFields(table, toStore);
return toStore;
}
private static List<Field> getAllFields(List<Field> fields, Class<?> type) {
Collections.addAll(fields, type.getDeclaredFields());
if (type.getSuperclass() != null) {
fields = getAllFields(fields, type.getSuperclass());
}
return fields;
}
public static void addFieldValueToColumn(ContentValues values, Field column, Object object,
Map<Object, Long> entitiesMap) {
column.setAccessible(true);
Class<?> columnType = column.getType();
try {
String columnName = NamingHelper.toSQLName(column);
Object columnValue = column.get(object);
if (columnType.isAnnotationPresent(Table.class)) {
Field field;
try {
field = columnType.getDeclaredField("id");
field.setAccessible(true);
values.put(columnName,
(field != null)
? String.valueOf(field.get(columnValue)) : "0");
} catch (NoSuchFieldException e) {
if (entitiesMap.containsKey(columnValue)) {
values.put(columnName, entitiesMap.get(columnValue));
}
}
} else if (SugarRecord.class.isAssignableFrom(columnType)) {
values.put(columnName,
(columnValue != null)
? String.valueOf(((SugarRecord) columnValue).getId())
: "0");
} else {
if (columnType.equals(Short.class) || columnType.equals(short.class)) {
values.put(columnName, (Short) columnValue);
} else if (columnType.equals(Integer.class) || columnType.equals(int.class)) {
values.put(columnName, (Integer) columnValue);
} else if (columnType.equals(Long.class) || columnType.equals(long.class)) {
values.put(columnName, (Long) columnValue);
} else if (columnType.equals(Float.class) || columnType.equals(float.class)) {
values.put(columnName, (Float) columnValue);
} else if (columnType.equals(Double.class) || columnType.equals(double.class)) {
values.put(columnName, (Double) columnValue);
} else if (columnType.equals(Boolean.class) || columnType.equals(boolean.class)) {
values.put(columnName, (Boolean) columnValue);
} else if (columnType.equals(BigDecimal.class)) {
try {
values.put(columnName, column.get(object).toString());
} catch (NullPointerException e) {
values.putNull(columnName);
}
} else if (Timestamp.class.equals(columnType)) {
try {
values.put(columnName, ((Timestamp) column.get(object)).getTime());
} catch (NullPointerException e) {
values.put(columnName, (Long) null);
}
} else if (Date.class.equals(columnType)) {
try {
values.put(columnName, ((Date) column.get(object)).getTime());
} catch (NullPointerException e) {
values.put(columnName, (Long) null);
}
} else if (Calendar.class.equals(columnType)) {
try {
values.put(columnName, ((Calendar) column.get(object)).getTimeInMillis());
} catch (NullPointerException e) {
values.put(columnName, (Long) null);
}
} else if (columnType.equals(byte[].class)) {
if (columnValue == null) {
values.put(columnName, "".getBytes());
} else {
values.put(columnName, (byte[]) columnValue);
}
} else {
if (columnValue == null) {
values.putNull(columnName);
} else if (columnType.isEnum()) {
values.put(columnName, ((Enum) columnValue).name());
} else {
values.put(columnName, String.valueOf(columnValue));
}
}
}
} catch (IllegalAccessException e) {
Log.e("Sugar", e.getMessage());
}
}
public static void setFieldValueFromCursor(Cursor cursor, Field field, Object object) {
field.setAccessible(true);
try {
Class fieldType = field.getType();
String colName = NamingHelper.toSQLName(field);
int columnIndex = cursor.getColumnIndex(colName);
//TODO auto upgrade to add new columns
if (columnIndex < 0) {
Log.e("SUGAR", "Invalid colName, you should upgrade database");
return;
}
if (cursor.isNull(columnIndex)) {
return;
}
if (colName.equalsIgnoreCase("id")) {
long cid = cursor.getLong(columnIndex);
field.set(object, Long.valueOf(cid));
} else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) {
field.set(object,
cursor.getLong(columnIndex));
} else if (fieldType.equals(String.class)) {
String val = cursor.getString(columnIndex);
field.set(object, val != null && val.equals("null") ? null : val);
} else if (fieldType.equals(double.class) || fieldType.equals(Double.class)) {
field.set(object,
cursor.getDouble(columnIndex));
} else if (fieldType.equals(boolean.class) || fieldType.equals(Boolean.class)) {
field.set(object,
cursor.getString(columnIndex).equals("1"));
} else if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) {
field.set(object,
cursor.getInt(columnIndex));
} else if (fieldType.equals(float.class) || fieldType.equals(Float.class)) {
field.set(object,
cursor.getFloat(columnIndex));
} else if (fieldType.equals(short.class) || fieldType.equals(Short.class)) {
field.set(object,
cursor.getShort(columnIndex));
} else if (fieldType.equals(BigDecimal.class)) {
String val = cursor.getString(columnIndex);
field.set(object, val != null && val.equals("null") ? null : new BigDecimal(val));
} else if (fieldType.equals(Timestamp.class)) {
long l = cursor.getLong(columnIndex);
field.set(object, new Timestamp(l));
} else if (fieldType.equals(Date.class)) {
long l = cursor.getLong(columnIndex);
field.set(object, new Date(l));
} else if (fieldType.equals(Calendar.class)) {
long l = cursor.getLong(columnIndex);
Calendar c = Calendar.getInstance();
c.setTimeInMillis(l);
field.set(object, c);
} else if (fieldType.equals(byte[].class)) {
byte[] bytes = cursor.getBlob(columnIndex);
if (bytes == null) {
field.set(object, "".getBytes());
} else {
field.set(object, cursor.getBlob(columnIndex));
}
} else if (Enum.class.isAssignableFrom(fieldType)) {
try {
Method valueOf = field.getType().getMethod("valueOf", String.class);
String strVal = cursor.getString(columnIndex);
Object enumVal = valueOf.invoke(field.getType(), strVal);
field.set(object, enumVal);
} catch (Exception e) {
Log.e("Sugar", "Enum cannot be read from Sqlite3 database. Please check the type of field " + field.getName());
}
} else
Log.e("Sugar", "Class cannot be read from Sqlite3 database. Please check the type of field " + field.getName() + "(" + field.getType().getName() + ")");
} catch (IllegalArgumentException e) {
Log.e("field set error", e.getMessage());
} catch (IllegalAccessException e) {
Log.e("field set error", e.getMessage());
}
}
private static Field getDeepField(String fieldName, Class<?> type) throws NoSuchFieldException {
try {
Field field = type.getDeclaredField(fieldName);
return field;
} catch (NoSuchFieldException e) {
Class superclass = type.getSuperclass();
if (superclass != null) {
Field field = getDeepField(fieldName, superclass);
return field;
} else {
throw e;
}
}
}
public static void setFieldValueForId(Object object, Long value) {
try {
Field field = getDeepField("id", object.getClass());
field.setAccessible(true);
field.set(object, value);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
public static List<Class> getDomainClasses(Context context) {
List<Class> domainClasses = new ArrayList<Class>();
try {
for (String className : getAllClasses(context)) {
Class domainClass = getDomainClass(className, context);
if (domainClass != null) domainClasses.add(domainClass);
}
} catch (IOException e) {
Log.e("Sugar", e.getMessage());
} catch (PackageManager.NameNotFoundException e) {
Log.e("Sugar", e.getMessage());
}
return domainClasses;
}
private static Class getDomainClass(String className, Context context) {
Class<?> discoveredClass = null;
try {
discoveredClass = Class.forName(className, true, context.getClass().getClassLoader());
} catch (Throwable e) {
String error = (e.getMessage() == null) ? "getDomainClass " + className + " error" : e.getMessage();
Log.e("Sugar", error);
}
if ((discoveredClass != null) &&
((SugarRecord.class.isAssignableFrom(discoveredClass) &&
!SugarRecord.class.equals(discoveredClass)) ||
discoveredClass.isAnnotationPresent(Table.class)) &&
!Modifier.isAbstract(discoveredClass.getModifiers())) {
Log.i("Sugar", "domain class : " + discoveredClass.getSimpleName());
return discoveredClass;
} else {
return null;
}
}
private static List<String> getAllClasses(Context context) throws PackageManager.NameNotFoundException, IOException {
String packageName = ManifestHelper.getDomainPackageName(context);
List<String> classNames = new ArrayList<String>();
try {
List<String> allClasses = MultiDexHelper.getAllClasses(context);
for (String classString : allClasses) {
if (classString.startsWith(packageName)) classNames.add(classString);
}
} catch (NullPointerException e) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Enumeration<URL> urls = classLoader.getResources("");
while (urls.hasMoreElements()) {
List<String> fileNames = new ArrayList<String>();
String classDirectoryName = urls.nextElement().getFile();
if (classDirectoryName.contains("bin") || classDirectoryName.contains("classes")) {
File classDirectory = new File(classDirectoryName);
for (File filePath : classDirectory.listFiles()) {
populateFiles(filePath, fileNames, "");
}
for (String fileName : fileNames) {
if (fileName.startsWith(packageName)) classNames.add(fileName);
}
}
}
} finally {
// if (null != dexfile) dexfile.close();
}
return classNames;
}
private static void populateFiles(File path, List<String> fileNames, String parent) {
if (path.isDirectory()) {
for (File newPath : path.listFiles()) {
if ("".equals(parent)) {
populateFiles(newPath, fileNames, path.getName());
} else {
populateFiles(newPath, fileNames, parent + "." + path.getName());
}
}
} else {
String pathName = path.getName();
String classSuffix = ".class";
pathName = pathName.endsWith(classSuffix) ?
pathName.substring(0, pathName.length() - classSuffix.length()) : pathName;
if ("".equals(parent)) {
fileNames.add(pathName);
} else {
fileNames.add(parent + "." + pathName);
}
}
}
private static String getSourcePath(Context context) throws PackageManager.NameNotFoundException {
return context.getPackageManager().getApplicationInfo(context.getPackageName(), 0).sourceDir;
}
}
| library/src/main/java/com/orm/util/ReflectionUtil.java | package com.orm.util;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.util.Log;
import com.orm.SugarRecord;
import com.orm.dsl.Ignore;
import com.orm.dsl.Table;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
public class ReflectionUtil {
public static List<Field> getTableFields(Class table) {
List<Field> fieldList = SugarConfig.getFields(table);
if (fieldList != null) return fieldList;
Log.d("Sugar", "Fetching properties");
List<Field> typeFields = new ArrayList<Field>();
getAllFields(typeFields, table);
List<Field> toStore = new ArrayList<Field>();
for (Field field : typeFields) {
if (!field.isAnnotationPresent(Ignore.class) && !Modifier.isStatic(field.getModifiers()) && !Modifier.isTransient(field.getModifiers())) {
toStore.add(field);
}
}
SugarConfig.setFields(table, toStore);
return toStore;
}
private static List<Field> getAllFields(List<Field> fields, Class<?> type) {
Collections.addAll(fields, type.getDeclaredFields());
if (type.getSuperclass() != null) {
fields = getAllFields(fields, type.getSuperclass());
}
return fields;
}
public static void addFieldValueToColumn(ContentValues values, Field column, Object object,
Map<Object, Long> entitiesMap) {
column.setAccessible(true);
Class<?> columnType = column.getType();
try {
String columnName = NamingHelper.toSQLName(column);
Object columnValue = column.get(object);
if (columnType.isAnnotationPresent(Table.class)) {
Field field;
try {
field = columnType.getDeclaredField("id");
field.setAccessible(true);
values.put(columnName,
(field != null)
? String.valueOf(field.get(columnValue)) : "0");
} catch (NoSuchFieldException e) {
if (entitiesMap.containsKey(columnValue)) {
values.put(columnName, entitiesMap.get(columnValue));
}
}
} else if (SugarRecord.class.isAssignableFrom(columnType)) {
values.put(columnName,
(columnValue != null)
? String.valueOf(((SugarRecord) columnValue).getId())
: "0");
} else {
if (columnType.equals(Short.class) || columnType.equals(short.class)) {
values.put(columnName, (Short) columnValue);
} else if (columnType.equals(Integer.class) || columnType.equals(int.class)) {
values.put(columnName, (Integer) columnValue);
} else if (columnType.equals(Long.class) || columnType.equals(long.class)) {
values.put(columnName, (Long) columnValue);
} else if (columnType.equals(Float.class) || columnType.equals(float.class)) {
values.put(columnName, (Float) columnValue);
} else if (columnType.equals(Double.class) || columnType.equals(double.class)) {
values.put(columnName, (Double) columnValue);
} else if (columnType.equals(Boolean.class) || columnType.equals(boolean.class)) {
values.put(columnName, (Boolean) columnValue);
} else if (columnType.equals(BigDecimal.class)) {
try {
values.put(columnName, column.get(object).toString());
} catch (NullPointerException e) {
values.putNull(columnName);
}
} else if (Timestamp.class.equals(columnType)) {
try {
values.put(columnName, ((Timestamp) column.get(object)).getTime());
} catch (NullPointerException e) {
values.put(columnName, (Long) null);
}
} else if (Date.class.equals(columnType)) {
try {
values.put(columnName, ((Date) column.get(object)).getTime());
} catch (NullPointerException e) {
values.put(columnName, (Long) null);
}
} else if (Calendar.class.equals(columnType)) {
try {
values.put(columnName, ((Calendar) column.get(object)).getTimeInMillis());
} catch (NullPointerException e) {
values.put(columnName, (Long) null);
}
} else if (columnType.equals(byte[].class)) {
if (columnValue == null) {
values.put(columnName, "".getBytes());
} else {
values.put(columnName, (byte[]) columnValue);
}
} else {
if (columnValue == null) {
values.putNull(columnName);
} else if (columnType.isEnum()) {
values.put(columnName, ((Enum) columnValue).name());
} else {
values.put(columnName, String.valueOf(columnValue));
}
}
}
} catch (IllegalAccessException e) {
Log.e("Sugar", e.getMessage());
}
}
public static void setFieldValueFromCursor(Cursor cursor, Field field, Object object) {
field.setAccessible(true);
try {
Class fieldType = field.getType();
String colName = NamingHelper.toSQLName(field);
int columnIndex = cursor.getColumnIndex(colName);
//TODO auto upgrade to add new columns
if (columnIndex < 0) {
Log.e("SUGAR", "Invalid colName, you should upgrade database");
return;
}
if (cursor.isNull(columnIndex)) {
return;
}
if (colName.equalsIgnoreCase("id")) {
long cid = cursor.getLong(columnIndex);
field.set(object, Long.valueOf(cid));
} else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) {
field.set(object,
cursor.getLong(columnIndex));
} else if (fieldType.equals(String.class)) {
String val = cursor.getString(columnIndex);
field.set(object, val != null && val.equals("null") ? null : val);
} else if (fieldType.equals(double.class) || fieldType.equals(Double.class)) {
field.set(object,
cursor.getDouble(columnIndex));
} else if (fieldType.equals(boolean.class) || fieldType.equals(Boolean.class)) {
field.set(object,
cursor.getString(columnIndex).equals("1"));
} else if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) {
field.set(object,
cursor.getInt(columnIndex));
} else if (fieldType.equals(float.class) || fieldType.equals(Float.class)) {
field.set(object,
cursor.getFloat(columnIndex));
} else if (fieldType.equals(short.class) || fieldType.equals(Short.class)) {
field.set(object,
cursor.getShort(columnIndex));
} else if (fieldType.equals(BigDecimal.class)) {
String val = cursor.getString(columnIndex);
field.set(object, val != null && val.equals("null") ? null : new BigDecimal(val));
} else if (fieldType.equals(Timestamp.class)) {
long l = cursor.getLong(columnIndex);
field.set(object, new Timestamp(l));
} else if (fieldType.equals(Date.class)) {
long l = cursor.getLong(columnIndex);
field.set(object, new Date(l));
} else if (fieldType.equals(Calendar.class)) {
long l = cursor.getLong(columnIndex);
Calendar c = Calendar.getInstance();
c.setTimeInMillis(l);
field.set(object, c);
} else if (fieldType.equals(byte[].class)) {
byte[] bytes = cursor.getBlob(columnIndex);
if (bytes == null) {
field.set(object, "".getBytes());
} else {
field.set(object, cursor.getBlob(columnIndex));
}
} else if (Enum.class.isAssignableFrom(fieldType)) {
try {
Method valueOf = field.getType().getMethod("valueOf", String.class);
String strVal = cursor.getString(columnIndex);
Object enumVal = valueOf.invoke(field.getType(), strVal);
field.set(object, enumVal);
} catch (Exception e) {
Log.e("Sugar", "Enum cannot be read from Sqlite3 database. Please check the type of field " + field.getName());
}
} else
Log.e("Sugar", "Class cannot be read from Sqlite3 database. Please check the type of field " + field.getName() + "(" + field.getType().getName() + ")");
} catch (IllegalArgumentException e) {
Log.e("field set error", e.getMessage());
} catch (IllegalAccessException e) {
Log.e("field set error", e.getMessage());
}
}
private static Field getDeepField(String fieldName, Class<?> type) throws NoSuchFieldException {
try {
Field field = type.getDeclaredField(fieldName);
return field;
} catch (NoSuchFieldException e) {
Class superclass = type.getSuperclass();
if (superclass != null) {
Field field = getDeepField(fieldName, superclass);
return field;
} else {
throw e;
}
}
}
public static void setFieldValueForId(Object object, Long value) {
try {
Field field = getDeepField("id", object.getClass());
field.setAccessible(true);
field.set(object, value);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
public static List<Class> getDomainClasses(Context context) {
List<Class> domainClasses = new ArrayList<Class>();
try {
for (String className : getAllClasses(context)) {
Class domainClass = getDomainClass(className, context);
if (domainClass != null) domainClasses.add(domainClass);
}
} catch (IOException e) {
Log.e("Sugar", e.getMessage());
} catch (PackageManager.NameNotFoundException e) {
Log.e("Sugar", e.getMessage());
}
return domainClasses;
}
private static Class getDomainClass(String className, Context context) {
Class<?> discoveredClass = null;
try {
discoveredClass = Class.forName(className, true, context.getClass().getClassLoader());
} catch (Throwable e) {
Log.e("Sugar", e.getMessage());
}
if ((discoveredClass != null) &&
((SugarRecord.class.isAssignableFrom(discoveredClass) &&
!SugarRecord.class.equals(discoveredClass)) ||
discoveredClass.isAnnotationPresent(Table.class)) &&
!Modifier.isAbstract(discoveredClass.getModifiers())) {
Log.i("Sugar", "domain class : " + discoveredClass.getSimpleName());
return discoveredClass;
} else {
return null;
}
}
private static List<String> getAllClasses(Context context) throws PackageManager.NameNotFoundException, IOException {
String packageName = ManifestHelper.getDomainPackageName(context);
List<String> classNames = new ArrayList<String>();
try {
List<String> allClasses = MultiDexHelper.getAllClasses(context);
for (String classString : allClasses) {
if (classString.startsWith(packageName)) classNames.add(classString);
}
} catch (NullPointerException e) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Enumeration<URL> urls = classLoader.getResources("");
while (urls.hasMoreElements()) {
List<String> fileNames = new ArrayList<String>();
String classDirectoryName = urls.nextElement().getFile();
if (classDirectoryName.contains("bin") || classDirectoryName.contains("classes")) {
File classDirectory = new File(classDirectoryName);
for (File filePath : classDirectory.listFiles()) {
populateFiles(filePath, fileNames, "");
}
for (String fileName : fileNames) {
if (fileName.startsWith(packageName)) classNames.add(fileName);
}
}
}
} finally {
// if (null != dexfile) dexfile.close();
}
return classNames;
}
private static void populateFiles(File path, List<String> fileNames, String parent) {
if (path.isDirectory()) {
for (File newPath : path.listFiles()) {
if ("".equals(parent)) {
populateFiles(newPath, fileNames, path.getName());
} else {
populateFiles(newPath, fileNames, parent + "." + path.getName());
}
}
} else {
String pathName = path.getName();
String classSuffix = ".class";
pathName = pathName.endsWith(classSuffix) ?
pathName.substring(0, pathName.length() - classSuffix.length()) : pathName;
if ("".equals(parent)) {
fileNames.add(pathName);
} else {
fileNames.add(parent + "." + pathName);
}
}
}
private static String getSourcePath(Context context) throws PackageManager.NameNotFoundException {
return context.getPackageManager().getApplicationInfo(context.getPackageName(), 0).sourceDir;
}
}
| fix satyan/sugar#467
Sometimes Throwable doesn't have a message,
so e.getMessage is NULL and generate a NullPointerException
| library/src/main/java/com/orm/util/ReflectionUtil.java | fix satyan/sugar#467 | <ide><path>ibrary/src/main/java/com/orm/util/ReflectionUtil.java
<ide> try {
<ide> discoveredClass = Class.forName(className, true, context.getClass().getClassLoader());
<ide> } catch (Throwable e) {
<del> Log.e("Sugar", e.getMessage());
<add> String error = (e.getMessage() == null) ? "getDomainClass " + className + " error" : e.getMessage();
<add> Log.e("Sugar", error);
<ide> }
<ide>
<ide> if ((discoveredClass != null) && |
|
Java | apache-2.0 | 2d33c6cc1e9ba38da9c86abd932657068000458d | 0 | mtransitapps/ca-kelowna-regional-transit-system-bus-parser | package org.mtransit.parser.ca_kelowna_regional_transit_system_bus;
import org.apache.commons.lang3.StringUtils;
import org.mtransit.commons.StrategicMappingCommons;
import org.mtransit.parser.CleanUtils;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.MTLog;
import org.mtransit.parser.Pair;
import org.mtransit.parser.SplitUtils;
import org.mtransit.parser.SplitUtils.RouteTripSpec;
import org.mtransit.parser.Utils;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GSpec;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.gtfs.data.GTripStop;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.mt.data.MTrip;
import org.mtransit.parser.mt.data.MTripStop;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Pattern;
// https://www.bctransit.com/open-data
// https://www.bctransit.com/data/gtfs/kelowna.zip
// https://kelowna.mapstrat.com/current/google_transit.zip
public class KelownaRegionalTransitSystemBusAgencyTools extends DefaultAgencyTools {
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-kelowna-regional-transit-system-bus-android/res/raw/";
args[2] = ""; // files-prefix
}
new KelownaRegionalTransitSystemBusAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@SuppressWarnings("FieldCanBeLocal")
private boolean isNext;
@Override
public void start(String[] args) {
MTLog.log("Generating Kelowna Regional TS bus data...");
long start = System.currentTimeMillis();
this.isNext = "next_".equalsIgnoreCase(args[2]);
if (isNext) {
setupNext();
}
this.serviceIds = extractUsefulServiceIds(args, this, true);
super.start(args);
MTLog.log("Generating Kelowna Regional TS bus data... DONE in %s.", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
private void setupNext() {
}
@Override
public boolean excludingAll() {
return this.serviceIds != null && this.serviceIds.isEmpty();
}
private static final String INCLUDE_ONLY_SERVICE_ID_CONTAINS = null;
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
//noinspection ConstantConditions
if (INCLUDE_ONLY_SERVICE_ID_CONTAINS != null
&& !gCalendar.getServiceId().contains(INCLUDE_ONLY_SERVICE_ID_CONTAINS)) {
return true;
}
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
//noinspection ConstantConditions
if (INCLUDE_ONLY_SERVICE_ID_CONTAINS != null
&& !gCalendarDates.getServiceId().contains(INCLUDE_ONLY_SERVICE_ID_CONTAINS)) {
return true;
}
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeRoute(GRoute gRoute) {
return super.excludeRoute(gRoute);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
//noinspection ConstantConditions
if (INCLUDE_ONLY_SERVICE_ID_CONTAINS != null
&& !gTrip.getServiceId().contains(INCLUDE_ONLY_SERVICE_ID_CONTAINS)) {
return true;
}
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, this.serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
@Override
public long getRouteId(GRoute gRoute) { // used by GTFS-RT
return super.getRouteId(gRoute); // used by GTFS-RT
}
@Override
public String getRouteLongName(GRoute gRoute) {
String routeLongName = gRoute.getRouteLongName();
if (StringUtils.isEmpty(routeLongName)) {
routeLongName = gRoute.getRouteDesc();
}
if (StringUtils.isEmpty(routeLongName)) {
MTLog.logFatal("Unexpected route long name for %s!", gRoute);
return null;
}
routeLongName = CleanUtils.cleanSlashes(routeLongName);
routeLongName = CleanUtils.cleanNumbers(routeLongName);
routeLongName = CleanUtils.cleanStreetTypes(routeLongName);
return CleanUtils.cleanLabel(routeLongName);
}
private static final String AGENCY_COLOR_GREEN = "34B233";// GREEN (from PDF Corporate Graphic Standards)
@SuppressWarnings("unused")
private static final String AGENCY_COLOR_BLUE = "002C77"; // BLUE (from PDF Corporate Graphic Standards)
private static final String AGENCY_COLOR = AGENCY_COLOR_GREEN;
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
private static final String COLOR_3FA0D6 = "3FA0D6";
private static final String COLOR_7B9597 = "7B9597";
private static final String COLOR_F17C15 = "F17C15";
@SuppressWarnings("DuplicateBranchesInSwitch")
@Override
public String getRouteColor(GRoute gRoute) {
if (StringUtils.isEmpty(gRoute.getRouteColor())) {
int rsn = Integer.parseInt(gRoute.getRouteShortName());
switch (rsn) {
// @formatter:off
case 1: return COLOR_3FA0D6;
case 2: return COLOR_7B9597;
case 3: return COLOR_7B9597;
case 4: return COLOR_7B9597;
case 5: return COLOR_3FA0D6;
case 6: return COLOR_7B9597;
case 7: return COLOR_3FA0D6;
case 8: return COLOR_3FA0D6;
case 9: return COLOR_7B9597;
case 10: return COLOR_3FA0D6;
case 11: return COLOR_3FA0D6;
case 12: return COLOR_7B9597;
case 13: return COLOR_7B9597;
case 14: return COLOR_7B9597;
case 15: return COLOR_7B9597;
case 16: return COLOR_7B9597;
case 17: return COLOR_7B9597;
case 18: return COLOR_7B9597;
case 19: return COLOR_7B9597;
case 20: return COLOR_7B9597;
case 21: return COLOR_7B9597;
case 22: return COLOR_7B9597;
case 23: return COLOR_3FA0D6;
case 24: return COLOR_7B9597;
case 25: return COLOR_7B9597;
case 27: return COLOR_7B9597;
case 28: return COLOR_7B9597;
case 29: return COLOR_7B9597;
case 32: return COLOR_7B9597;
case 90: return COLOR_7B9597;
case 97: return COLOR_F17C15;
// @formatter:on
default:
MTLog.logFatal("Unexpected route color %s!", gRoute);
return null;
}
}
return super.getRouteColor(gRoute);
}
private static final String EXCH = "Exch";
private static final String BLACK_MOUNTAIN = "Black Mtn";
private static final String SOUTH_PANDOSY = "South Pandosy";
private static final String MISSION_REC_EXCH = "Mission Rec " + EXCH;
private static final String UBCO = "UBCO";
private static final String RUTLAND = "Rutland";
private static final String QUEENSWAY_EXCH = "Queensway " + EXCH;
private static final String OK_COLLEGE = "OK College";
private static final String ORCHARD_PK = "Orchard Pk";
private static final String GLENROSA = "Glenrosa";
private static final String LK_COUNTRY = "Lk Country";
private static final String WESTBANK = "Westbank";
private static final String DOWNTOWN = "Downtown";
private static HashMap<Long, RouteTripSpec> ALL_ROUTE_TRIPS2;
static {
HashMap<Long, RouteTripSpec> map2 = new HashMap<>();
map2.put(2L, new RouteTripSpec(2L, // 2 //
StrategicMappingCommons.CLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, QUEENSWAY_EXCH, //
StrategicMappingCommons.CLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, "Cambridge & Ellis") //
.addTripSort(StrategicMappingCommons.CLOCKWISE_0, //
Arrays.asList(//
Stops.getALL_STOPS().get("102932"), // Cambridge at Ellis (EB) <= CONTINUE
Stops.getALL_STOPS().get("102895"), // ++ Richter at Gaston (SB)
Stops.getALL_STOPS().get("102859") // Queensway Exchange Bay E
)) //
.addTripSort(StrategicMappingCommons.CLOCKWISE_1, //
Arrays.asList(//
Stops.getALL_STOPS().get("102859"), // Queensway Exchange Bay E
Stops.getALL_STOPS().get("102888"), // ++ Ellis at Industrial (NB)
Stops.getALL_STOPS().get("102932") // Cambridge at Ellis (EB) => CONTINUE
)) //
.compileBothTripSort());
map2.put(3L, new RouteTripSpec(3L, // 3 //
StrategicMappingCommons.CLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, ORCHARD_PK, //
StrategicMappingCommons.CLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, "Glenmore @ Summit") //
.addTripSort(StrategicMappingCommons.CLOCKWISE_0, //
Arrays.asList(//
Stops.getALL_STOPS().get("103041"), // Glenmore AT Summit (NB) <= CONTINUE
Stops.getALL_STOPS().get("103168"), // ++ Summit at Dilworth (EB)
Stops.getALL_STOPS().get("103079") // Orchard Park Exchange Bay G
)) //
.addTripSort(StrategicMappingCommons.CLOCKWISE_1, //
Arrays.asList(//
Stops.getALL_STOPS().get("103079"), // Orchard Park Exchange Bay G
Stops.getALL_STOPS().get("103170"), // ++ Summit at Dilworth (WB)
Stops.getALL_STOPS().get("103041") // Glenmore AT Summit (NB) => CONTINUE
)) //
.compileBothTripSort());
map2.put(-1L, new RouteTripSpec(-1L, // 13 //
StrategicMappingCommons.COUNTERCLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, "Country Club", //
StrategicMappingCommons.COUNTERCLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, UBCO) //
.addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_0, //
Arrays.asList(//
Stops.getALL_STOPS().get("140104"), // UBCO Exchange Bay E
Stops.getALL_STOPS().get("104916"), // ++
Stops.getALL_STOPS().get("103858") // Country Club 1740 block
)) //
.addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_1, //
Arrays.asList(//
Stops.getALL_STOPS().get("103858"), // Country Club 1740 block
Stops.getALL_STOPS().get("103851"), // ++ Quail Ridge at Country Club
Stops.getALL_STOPS().get("140104") // UBCO Exchange Bay D
)) //
.compileBothTripSort());
map2.put(12L, new RouteTripSpec(12L, // 15 //
StrategicMappingCommons.COUNTERCLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, "Crawford", //
StrategicMappingCommons.COUNTERCLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, MISSION_REC_EXCH) //
.addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_0, //
Arrays.asList(//
Stops.getALL_STOPS().get("103021"), // Mission Rec Exchange Bay A
Stops.getALL_STOPS().get("103316"), // Dehart at Gordon (EB)
Stops.getALL_STOPS().get("103401") // Westridge at Crawford (SB) => CONTINUE
)) //
.addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_1, //
Arrays.asList(//
Stops.getALL_STOPS().get("103401"), // Westridge at Crawford (SB) <= CONTINUE
Stops.getALL_STOPS().get("103423"), // Westridge at Blueridge (SB)
Stops.getALL_STOPS().get("103021") // Mission Rec Exchange Bay A
)) //
.compileBothTripSort());
map2.put(13L, new RouteTripSpec(13L, // 16 //
StrategicMappingCommons.COUNTERCLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, "Kettle Vly", //
StrategicMappingCommons.COUNTERCLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, MISSION_REC_EXCH) //
.addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_0, //
Arrays.asList(//
Stops.getALL_STOPS().get("103022"), // Mission Rec Exchange Bay B
Stops.getALL_STOPS().get("103319"), // Lakeshore at Dehart (SB)
Stops.getALL_STOPS().get("103808"), // Chute Lake at South Crest (SB)
Stops.getALL_STOPS().get("103562") // Quilchena at Providence (SB) #KettleVly => CONTINUE
)) //
.addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_1, //
Arrays.asList(//
Stops.getALL_STOPS().get("103814"), // South Perimeter at Farron (EB) #KettleVly <= CONTINUE
Stops.getALL_STOPS().get("103809"), // Chute Lake at South Crest (NB)
Stops.getALL_STOPS().get("103317"), // Lakeshore at Dehart (NB)
Stops.getALL_STOPS().get("103022") // Mission Rec Exchange Bay B
)) //
.compileBothTripSort());
map2.put(14L, new RouteTripSpec(14L, // 17
StrategicMappingCommons.CLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, "Southridge", //
StrategicMappingCommons.CLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, MISSION_REC_EXCH) //
.addTripSort(StrategicMappingCommons.CLOCKWISE_0, //
Arrays.asList(//
Stops.getALL_STOPS().get("103022"), // Mission Rec Exchange Bay B
Stops.getALL_STOPS().get("103325"), // Gordon at Dehart (SB)
Stops.getALL_STOPS().get("103191") // South Ridge at Frost (NB) => CONTINUE
)) //
.addTripSort(StrategicMappingCommons.CLOCKWISE_1, //
Arrays.asList(//
Stops.getALL_STOPS().get("103191"), // South Ridge at Frost (NB) <= CONTINUE
Stops.getALL_STOPS().get("103820"), // Gordon at Raymer (NB)
Stops.getALL_STOPS().get("103818"), // Gordon at Tozer (NB)
Stops.getALL_STOPS().get("103022") // Mission Rec Exchange Bay B
)) //
.compileBothTripSort());
map2.put(18L, new RouteTripSpec(18L, // 21
StrategicMappingCommons.COUNTERCLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, GLENROSA, //
StrategicMappingCommons.COUNTERCLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, WESTBANK) //
.addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_0, //
Arrays.asList(//
Stops.getALL_STOPS().get("140006"), // Westbank Exchange Bay C
Stops.getALL_STOPS().get("103624"), // McNair at Webber
Stops.getALL_STOPS().get("103641") // Canary @ Blue Jay
)) //
.addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_1, //
Arrays.asList(//
Stops.getALL_STOPS().get("103641"), // Canary @ Blue Jay
Stops.getALL_STOPS().get("103643"), // Glenrosa at Dunfield
Stops.getALL_STOPS().get("140006") // Westbank Exchange Bay C
)) //
.compileBothTripSort());
map2.put(25L, new RouteTripSpec(25L, // 29 //
StrategicMappingCommons.COUNTERCLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, "Bear Crk", //
StrategicMappingCommons.COUNTERCLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, "Boucherie Mtn") //
.addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_0, //
Arrays.asList(//
Stops.getALL_STOPS().get("140011"), // Boucherie Mountain Exchange Bay E
Stops.getALL_STOPS().get("103115"), // Westlake at Horizon (EB)
Stops.getALL_STOPS().get("103043") // Westside at Bear Creek (SB) => CONTINUE
)) //
.addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_1, //
Arrays.asList(//
Stops.getALL_STOPS().get("103043"), // Westside at Bear Creek (SB) <= CONTINUE
Stops.getALL_STOPS().get("103078"), // Boucherie at Hayman (WB)
Stops.getALL_STOPS().get("140011") // Boucherie Mountain Exchange Bay E
)) //
.compileBothTripSort());
map2.put(26L, new RouteTripSpec(26L, // 32 //
StrategicMappingCommons.CLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, "Main & Grant", //
StrategicMappingCommons.CLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, "Shoreline & Stillwater") //
.addTripSort(StrategicMappingCommons.CLOCKWISE_0, //
Arrays.asList(//
Stops.getALL_STOPS().get("140081"), // Shoreline at Stillwater (NB) <= CONTINUE ?
Stops.getALL_STOPS().get("140088"), // Oceola at Pretty (SB) #LakewoodMall
Stops.getALL_STOPS().get("103472") // Main at Grant Rd (NB)
)) //
.addTripSort(StrategicMappingCommons.CLOCKWISE_1, //
Arrays.asList(//
Stops.getALL_STOPS().get("103472"), // Main at Grant Rd (NB)
Stops.getALL_STOPS().get("103685"), // Oceola at Pretty (NB) #LakewoodMall
Stops.getALL_STOPS().get("140081") // Shoreline at Stillwater (NB) => CONTINUE ?
)) //
.compileBothTripSort());
ALL_ROUTE_TRIPS2 = map2;
}
@Override
public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) {
if (ALL_ROUTE_TRIPS2.containsKey(routeId)) {
return ALL_ROUTE_TRIPS2.get(routeId).compare(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop, this);
}
return super.compareEarly(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop);
}
@Override
public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return ALL_ROUTE_TRIPS2.get(mRoute.getId()).getAllTrips();
}
return super.splitTrip(mRoute, gTrip, gtfs);
}
@Override
public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return SplitUtils.splitTripStop(mRoute, gTrip, gTripStop, routeGTFS, ALL_ROUTE_TRIPS2.get(mRoute.getId()), this);
}
return super.splitTripStop(mRoute, gTrip, gTripStop, splitTrips, routeGTFS);
}
private final HashMap<Long, Long> routeIdToShortName = new HashMap<>();
@Override
public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return; // split
}
final long rsn = Long.parseLong(mRoute.getShortName());
this.routeIdToShortName.put(mRoute.getId(), rsn);
if (rsn == 1L) {
if (gTrip.getDirectionId() == 0) { // Downtown - NORTH
if ("Downtown".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Mission Rec Exch - SOUTH
if (Arrays.asList( //
"Lakeshore to OK College", //
"Lakeshore - To OK College", //
"Lakeshore - To South Pandosy", //
"Lakeshore - Mission Rec Exch" //
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 4L) {
if (gTrip.getDirectionId() == 0) { // UBCO - NORTH
if ("UBCO Express".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Pandosy - SOUTH
if ("Pandosy Express".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 5L) {
if (gTrip.getDirectionId() == 0) { // Downtown - NORTH
if ("Downtown".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Mission Rec Exch - SOUTH
if ("Gordon - Mission Rec Exch".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 6L) {
if (gTrip.getDirectionId() == 0) { // Downtown - INBOUND // Queensway Exch - INBOUND
if ("Downtown".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.INBOUND);
return;
}
} else if (gTrip.getDirectionId() == 1) { // UBCO Exch - OUTBOUND
if ("UBCO".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.OUTBOUND);
return;
}
}
} else if (rsn == 8L) {
if (gTrip.getDirectionId() == 0) { // UBCO - NORTH
if ("University - To UBCO".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "To Orchard Park".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // OK College - SOUTH
if ("OK College".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "University to OK College".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "To Orchard Park".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 9L) {
if (gTrip.getDirectionId() == 0) { // Downtown - WEST
if ("Shopper Shuttle - To Downtown".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Orchard Park - EAST
if ("Shopper Shuttle - To Orchard Park".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (rsn == 10L) {
if (gTrip.getDirectionId() == 0) { // Queensway Exch - WEST
if (Arrays.asList( //
"North Rutland", // <>
"Downtown", //
"To Orchard Park" //
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Rutland - EAST
if ("North Rutland".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (rsn == 11L) {
if (gTrip.getDirectionId() == 0) { // Downtown - WEST
if (Arrays.asList( //
"Downtown", //
"to Orchard Park", //
"To Orchard Park", //
"Rutland to Orchard Park" //
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Rutland - EAST
if (Arrays.asList( //
"Rutland To 14 Black Mtn", //
"To Orchard Park", //
"Rutland" //
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (rsn == 12L) {
if (gTrip.getDirectionId() == 0) { // S.Pandosy Exch - WEST
if ("McCulloch - To Orchard Park".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "McCulloch - To South Pandosy".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "McCulloch to OK College".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // McCulloch - EAST
if ("McCulloch".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (rsn == 14L) {
if (gTrip.getDirectionId() == 0) { // Rutland Exch - NORTH
if (Arrays.asList( //
"Black Mountain", // <>
"Black Mountain - To Rutland", //
"Black Mountain - To Rutland Exch" //
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Black Mountain - SOUTH
if ("Black Mountain".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 18L) {
if (gTrip.getDirectionId() == 0) { // Glenmore - NORTH
if ("Glenmore".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Downtown - SOUTH
if ("Downtown".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 19L) {
if (gTrip.getDirectionId() == 0) { // Glenmore - NORTH
if ("Glenmore".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Orchard Pk - SOUTH
if ("Orchard Park".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 20L) {
if (gTrip.getDirectionId() == 0) { // Westbank - WEST
if ("Lakeview - To Westbank".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Boucherie Mtn - EAST
if ("Lakeview - Boucherie Mtn".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (rsn == 22L) {
if (gTrip.getDirectionId() == 0) { // Westbank - NORTH
if ("Peachland - To Westbank".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "Peachland Exp - To Westbank".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Peachland - SOUTH
if ("Peachland".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 23L) {
if (gTrip.getDirectionId() == 0) { // Lake Country - NORTH
if ("Lake Country".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "Lake Country Via Airport".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "Lake Country - Old Vernon Rd".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // UBCO Exch - SOUTH
if ("UBCO".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "UBCO Via Airport".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "UBCO - Old Vernon Rd".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 24L) {
if (gTrip.getDirectionId() == 0) { // Westbank - WEST
if ("Shannon Lake - To Westbank".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "Shannon Ridge- To Westbank".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Boucherie Mtn - EAST
if ("Shannon Lake - Boucherie Mtn".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "Shannon Ridge - Boucherie Mtn".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (rsn == 25L) {
if (gTrip.getDirectionId() == 0) { // Westbank - WEST
if ("East Boundary - To Westbank".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Boucherie Mtn - EAST
if ("East Boundary - Boucherie Mtn".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (rsn == 26L) {
if (gTrip.getDirectionId() == 0) { // Boucherie Mtn - NORTH
if ("Old Okanagan - Boucherie Mtn".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Westbank - SOUTH
if ("East Boundary - To Westbank".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "Old Okanagan - Westbank Ex.".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 28L) { //
if (gTrip.getDirectionId() == 0) { // Boucherie Mtn - NORTH
if ("Shannon Lake - Boucherie Mtn".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Westbank - SOUTH
if ("Shannon Lake - Westbank".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 88L) { //
if (gTrip.getDirectionId() == 1) { // Boucherie Mtn - OUTBOUND // Special - OUTBOUND
if ("Special".equalsIgnoreCase(gTrip.getTripHeadsign())) {
if ("Special".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString("Boucherie Mtn", StrategicMappingCommons.OUTBOUND);
return;
}
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.OUTBOUND);
return;
}
}
} else if (rsn == 97L) {
if (gTrip.getDirectionId() == 0) { // Westbank - WEST
if ("Westbank".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "To Cooper Stn".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "Downtown".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // UBCO - EAST
if ("UBCO".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "Downtown".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
}
MTLog.logFatal("%s: Unexpected trips head sign for %s!", mTrip.getRouteId(), gTrip);
}
@Override
public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) {
if (MTrip.mergeEmpty(mTrip, mTripToMerge)) {
return true;
}
List<String> headsignsValues = Arrays.asList(mTrip.getHeadsignValue(), mTripToMerge.getHeadsignValue());
final long rsn = this.routeIdToShortName.get(mTrip.getRouteId());
if (rsn == 1L) {
if (Arrays.asList( //
OK_COLLEGE, //
"South Pandosy", //
MISSION_REC_EXCH //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(MISSION_REC_EXCH, mTrip.getHeadsignId());
return true;
}
} else if (rsn == 8L) {
if (Arrays.asList( //
ORCHARD_PK, // <>
OK_COLLEGE //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(OK_COLLEGE, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
ORCHARD_PK, // <>
UBCO //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UBCO, mTrip.getHeadsignId());
return true;
}
} else if (rsn == 10L) {
if (Arrays.asList( //
"North Rutland", // <>
ORCHARD_PK, //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
}
} else if (rsn == 11L) {
if (Arrays.asList( //
ORCHARD_PK, // <>
BLACK_MOUNTAIN, //
RUTLAND //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(RUTLAND, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
ORCHARD_PK, // <>
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
}
} else if (rsn == 12L) {
if (Arrays.asList( //
ORCHARD_PK, //
OK_COLLEGE, //
SOUTH_PANDOSY //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(SOUTH_PANDOSY, mTrip.getHeadsignId());
return true;
}
} else if (rsn == 14L) {
if (Arrays.asList( //
"Black Mtn", // <>
"Rutland Exch" //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Rutland Exch", mTrip.getHeadsignId());
return true;
}
} else if (rsn == 23L) {
if (Arrays.asList( //
"Old Vernon Rd", // <>
LK_COUNTRY //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(LK_COUNTRY, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
"Old Vernon Rd", // <>
UBCO //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UBCO, mTrip.getHeadsignId());
return true;
}
} else if (rsn == 97L) {
if (Arrays.asList( //
DOWNTOWN, // <>
"Cooper Stn", //
WESTBANK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(WESTBANK, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
DOWNTOWN, // <>
UBCO //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UBCO, mTrip.getHeadsignId());
return true;
}
}
MTLog.logFatal("Unexpected trips to merge %s & %s!", mTrip, mTripToMerge);
return false;
}
private static final Pattern EXCHANGE = Pattern.compile("((^|\\W)(exchange|ex)(\\W|$))", Pattern.CASE_INSENSITIVE);
private static final String EXCHANGE_REPLACEMENT = "$2" + EXCH + "$4";
private static final Pattern STARTS_WITH_NUMBER = Pattern.compile("(^[\\d]+[\\S]*)", Pattern.CASE_INSENSITIVE);
private static final Pattern STARTS_WITH_DASH = Pattern.compile("(^.* - )", Pattern.CASE_INSENSITIVE);
private static final Pattern ENDS_WITH_EXPRESS = Pattern.compile("((\\W)(express)($))", Pattern.CASE_INSENSITIVE);
private static final Pattern SPECIAL = Pattern.compile("((^|\\W)(special)(\\W|$))", Pattern.CASE_INSENSITIVE);
@Override
public String cleanTripHeadsign(String tripHeadsign) {
tripHeadsign = CleanUtils.keepToAndRemoveVia(tripHeadsign);
tripHeadsign = EXCHANGE.matcher(tripHeadsign).replaceAll(EXCHANGE_REPLACEMENT);
tripHeadsign = CleanUtils.CLEAN_AND.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT);
tripHeadsign = STARTS_WITH_NUMBER.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = STARTS_WITH_DASH.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = ENDS_WITH_EXPRESS.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = SPECIAL.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = CleanUtils.removePoints(tripHeadsign);
tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign);
tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign);
return CleanUtils.cleanLabel(tripHeadsign);
}
private static final Pattern STARTS_WITH_IMPL = Pattern.compile("(^(\\(-IMPL-\\)))", Pattern.CASE_INSENSITIVE);
@Override
public String cleanStopName(String gStopName) {
gStopName = STARTS_WITH_IMPL.matcher(gStopName).replaceAll(StringUtils.EMPTY);
gStopName = CleanUtils.cleanBounds(gStopName);
gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT);
gStopName = EXCHANGE.matcher(gStopName).replaceAll(EXCHANGE_REPLACEMENT);
gStopName = CleanUtils.cleanStreetTypes(gStopName);
gStopName = CleanUtils.cleanNumbers(gStopName);
return CleanUtils.cleanLabel(gStopName);
}
@Override
public int getStopId(GStop gStop) { // used by GTFS-RT
return super.getStopId(gStop);
}
}
| src/main/java/org/mtransit/parser/ca_kelowna_regional_transit_system_bus/KelownaRegionalTransitSystemBusAgencyTools.java | package org.mtransit.parser.ca_kelowna_regional_transit_system_bus;
import org.apache.commons.lang3.StringUtils;
import org.mtransit.commons.StrategicMappingCommons;
import org.mtransit.parser.CleanUtils;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.MTLog;
import org.mtransit.parser.Pair;
import org.mtransit.parser.SplitUtils;
import org.mtransit.parser.SplitUtils.RouteTripSpec;
import org.mtransit.parser.Utils;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GSpec;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.gtfs.data.GTripStop;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.mt.data.MTrip;
import org.mtransit.parser.mt.data.MTripStop;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Pattern;
// https://www.bctransit.com/open-data
// https://www.bctransit.com/data/gtfs/kelowna.zip
// https://kelowna.mapstrat.com/current/google_transit.zip
public class KelownaRegionalTransitSystemBusAgencyTools extends DefaultAgencyTools {
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-kelowna-regional-transit-system-bus-android/res/raw/";
args[2] = ""; // files-prefix
}
new KelownaRegionalTransitSystemBusAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@SuppressWarnings("FieldCanBeLocal")
private boolean isNext;
@Override
public void start(String[] args) {
MTLog.log("Generating Kelowna Regional TS bus data...");
long start = System.currentTimeMillis();
this.isNext = "next_".equalsIgnoreCase(args[2]);
if (isNext) {
setupNext();
}
this.serviceIds = extractUsefulServiceIds(args, this, true);
super.start(args);
MTLog.log("Generating Kelowna Regional TS bus data... DONE in %s.", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
private void setupNext() {
}
@Override
public boolean excludingAll() {
return this.serviceIds != null && this.serviceIds.isEmpty();
}
private static final String INCLUDE_ONLY_SERVICE_ID_CONTAINS = null;
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
//noinspection ConstantConditions
if (INCLUDE_ONLY_SERVICE_ID_CONTAINS != null
&& !gCalendar.getServiceId().contains(INCLUDE_ONLY_SERVICE_ID_CONTAINS)) {
return true;
}
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
//noinspection ConstantConditions
if (INCLUDE_ONLY_SERVICE_ID_CONTAINS != null
&& !gCalendarDates.getServiceId().contains(INCLUDE_ONLY_SERVICE_ID_CONTAINS)) {
return true;
}
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeRoute(GRoute gRoute) {
return super.excludeRoute(gRoute);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
//noinspection ConstantConditions
if (INCLUDE_ONLY_SERVICE_ID_CONTAINS != null
&& !gTrip.getServiceId().contains(INCLUDE_ONLY_SERVICE_ID_CONTAINS)) {
return true;
}
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, this.serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
@Override
public long getRouteId(GRoute gRoute) { // used by GTFS-RT
return super.getRouteId(gRoute); // used by GTFS-RT
}
@Override
public String getRouteLongName(GRoute gRoute) {
String routeLongName = gRoute.getRouteLongName();
if (StringUtils.isEmpty(routeLongName)) {
routeLongName = gRoute.getRouteDesc();
}
if (StringUtils.isEmpty(routeLongName)) {
MTLog.logFatal("Unexpected route long name for %s!", gRoute);
return null;
}
routeLongName = CleanUtils.cleanSlashes(routeLongName);
routeLongName = CleanUtils.cleanNumbers(routeLongName);
routeLongName = CleanUtils.cleanStreetTypes(routeLongName);
return CleanUtils.cleanLabel(routeLongName);
}
private static final String AGENCY_COLOR_GREEN = "34B233";// GREEN (from PDF Corporate Graphic Standards)
@SuppressWarnings("unused")
private static final String AGENCY_COLOR_BLUE = "002C77"; // BLUE (from PDF Corporate Graphic Standards)
private static final String AGENCY_COLOR = AGENCY_COLOR_GREEN;
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
private static final String COLOR_3FA0D6 = "3FA0D6";
private static final String COLOR_7B9597 = "7B9597";
private static final String COLOR_F17C15 = "F17C15";
@SuppressWarnings("DuplicateBranchesInSwitch")
@Override
public String getRouteColor(GRoute gRoute) {
if (StringUtils.isEmpty(gRoute.getRouteColor())) {
int rsn = Integer.parseInt(gRoute.getRouteShortName());
switch (rsn) {
// @formatter:off
case 1: return COLOR_3FA0D6;
case 2: return COLOR_7B9597;
case 3: return COLOR_7B9597;
case 4: return COLOR_7B9597;
case 5: return COLOR_3FA0D6;
case 6: return COLOR_7B9597;
case 7: return COLOR_3FA0D6;
case 8: return COLOR_3FA0D6;
case 9: return COLOR_7B9597;
case 10: return COLOR_3FA0D6;
case 11: return COLOR_3FA0D6;
case 12: return COLOR_7B9597;
case 13: return COLOR_7B9597;
case 14: return COLOR_7B9597;
case 15: return COLOR_7B9597;
case 16: return COLOR_7B9597;
case 17: return COLOR_7B9597;
case 18: return COLOR_7B9597;
case 19: return COLOR_7B9597;
case 20: return COLOR_7B9597;
case 21: return COLOR_7B9597;
case 22: return COLOR_7B9597;
case 23: return COLOR_3FA0D6;
case 24: return COLOR_7B9597;
case 25: return COLOR_7B9597;
case 27: return COLOR_7B9597;
case 28: return COLOR_7B9597;
case 29: return COLOR_7B9597;
case 32: return COLOR_7B9597;
case 90: return COLOR_7B9597;
case 97: return COLOR_F17C15;
// @formatter:on
default:
MTLog.logFatal("Unexpected route color %s!", gRoute);
return null;
}
}
return super.getRouteColor(gRoute);
}
private static final String EXCH = "Exch";
private static final String BLACK_MOUNTAIN = "Black Mtn";
private static final String SOUTH_PANDOSY = "South Pandosy";
private static final String MISSION_REC_EXCH = "Mission Rec " + EXCH;
private static final String UBCO = "UBCO";
private static final String RUTLAND = "Rutland";
private static final String QUEENSWAY_EXCH = "Queensway " + EXCH;
private static final String OK_COLLEGE = "OK College";
private static final String ORCHARD_PK = "Orchard Pk";
private static final String GLENROSA = "Glenrosa";
private static final String LK_COUNTRY = "Lk Country";
private static final String WESTBANK = "Westbank";
private static final String DOWNTOWN = "Downtown";
private static HashMap<Long, RouteTripSpec> ALL_ROUTE_TRIPS2;
static {
HashMap<Long, RouteTripSpec> map2 = new HashMap<>();
map2.put(2L, new RouteTripSpec(2L, // 2 //
StrategicMappingCommons.CLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, QUEENSWAY_EXCH, //
StrategicMappingCommons.CLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, "Cambridge & Ellis") //
.addTripSort(StrategicMappingCommons.CLOCKWISE_0, //
Arrays.asList(//
Stops.getALL_STOPS().get("102932"), // Cambridge at Ellis (EB) <= CONTINUE
Stops.getALL_STOPS().get("102895"), // ++ Richter at Gaston (SB)
Stops.getALL_STOPS().get("102859") // Queensway Exchange Bay E
)) //
.addTripSort(StrategicMappingCommons.CLOCKWISE_1, //
Arrays.asList(//
Stops.getALL_STOPS().get("102859"), // Queensway Exchange Bay E
Stops.getALL_STOPS().get("102888"), // ++ Ellis at Industrial (NB)
Stops.getALL_STOPS().get("102932") // Cambridge at Ellis (EB) => CONTINUE
)) //
.compileBothTripSort());
map2.put(3L, new RouteTripSpec(3L, // 3 //
StrategicMappingCommons.CLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, ORCHARD_PK, //
StrategicMappingCommons.CLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, "Glenmore @ Summit") //
.addTripSort(StrategicMappingCommons.CLOCKWISE_0, //
Arrays.asList(//
Stops.getALL_STOPS().get("103041"), // Glenmore AT Summit (NB) <= CONTINUE
Stops.getALL_STOPS().get("103168"), // ++ Summit at Dilworth (EB)
Stops.getALL_STOPS().get("103079") // Orchard Park Exchange Bay G
)) //
.addTripSort(StrategicMappingCommons.CLOCKWISE_1, //
Arrays.asList(//
Stops.getALL_STOPS().get("103079"), // Orchard Park Exchange Bay G
Stops.getALL_STOPS().get("103170"), // ++ Summit at Dilworth (WB)
Stops.getALL_STOPS().get("103041") // Glenmore AT Summit (NB) => CONTINUE
)) //
.compileBothTripSort());
map2.put(12L, new RouteTripSpec(12L, // 13 //
StrategicMappingCommons.COUNTERCLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, "Country Club", //
StrategicMappingCommons.COUNTERCLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, UBCO) //
.addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_0, //
Arrays.asList(//
Stops.getALL_STOPS().get("140104"), // UBCO Exchange Bay E
Stops.getALL_STOPS().get("104916"), // ++
Stops.getALL_STOPS().get("103858") // Country Club 1740 block
)) //
.addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_1, //
Arrays.asList(//
Stops.getALL_STOPS().get("103858"), // Country Club 1740 block
Stops.getALL_STOPS().get("103851"), // ++ Quail Ridge at Country Club
Stops.getALL_STOPS().get("140104") // UBCO Exchange Bay D
)) //
.compileBothTripSort());
map2.put(14L, new RouteTripSpec(14L, // 15 //
StrategicMappingCommons.COUNTERCLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, "Crawford", //
StrategicMappingCommons.COUNTERCLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, MISSION_REC_EXCH) //
.addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_0, //
Arrays.asList(//
Stops.getALL_STOPS().get("103021"), // Mission Rec Exchange Bay A
Stops.getALL_STOPS().get("103316"), // Dehart at Gordon (EB)
Stops.getALL_STOPS().get("103401") // Westridge at Crawford (SB) => CONTINUE
)) //
.addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_1, //
Arrays.asList(//
Stops.getALL_STOPS().get("103401"), // Westridge at Crawford (SB) <= CONTINUE
Stops.getALL_STOPS().get("103423"), // Westridge at Blueridge (SB)
Stops.getALL_STOPS().get("103021") // Mission Rec Exchange Bay A
)) //
.compileBothTripSort());
map2.put(15L, new RouteTripSpec(15L, // 16 //
StrategicMappingCommons.COUNTERCLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, "Kettle Vly", //
StrategicMappingCommons.COUNTERCLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, MISSION_REC_EXCH) //
.addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_0, //
Arrays.asList(//
Stops.getALL_STOPS().get("103022"), // Mission Rec Exchange Bay B
Stops.getALL_STOPS().get("103319"), // Lakeshore at Dehart (SB)
Stops.getALL_STOPS().get("103808"), // Chute Lake at South Crest (SB)
Stops.getALL_STOPS().get("103562") // Quilchena at Providence (SB) #KettleVly => CONTINUE
)) //
.addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_1, //
Arrays.asList(//
Stops.getALL_STOPS().get("103814"), // South Perimeter at Farron (EB) #KettleVly <= CONTINUE
Stops.getALL_STOPS().get("103809"), // Chute Lake at South Crest (NB)
Stops.getALL_STOPS().get("103317"), // Lakeshore at Dehart (NB)
Stops.getALL_STOPS().get("103022") // Mission Rec Exchange Bay B
)) //
.compileBothTripSort());
map2.put(16L, new RouteTripSpec(16L, // 17
StrategicMappingCommons.CLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, "Southridge", //
StrategicMappingCommons.CLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, MISSION_REC_EXCH) //
.addTripSort(StrategicMappingCommons.CLOCKWISE_0, //
Arrays.asList(//
Stops.getALL_STOPS().get("103022"), // Mission Rec Exchange Bay B
Stops.getALL_STOPS().get("103325"), // Gordon at Dehart (SB)
Stops.getALL_STOPS().get("103191") // South Ridge at Frost (NB) => CONTINUE
)) //
.addTripSort(StrategicMappingCommons.CLOCKWISE_1, //
Arrays.asList(//
Stops.getALL_STOPS().get("103191"), // South Ridge at Frost (NB) <= CONTINUE
Stops.getALL_STOPS().get("103820"), // Gordon at Raymer (NB)
Stops.getALL_STOPS().get("103818"), // Gordon at Tozer (NB)
Stops.getALL_STOPS().get("103022") // Mission Rec Exchange Bay B
)) //
.compileBothTripSort());
map2.put(20L, new RouteTripSpec(20L, // 21
StrategicMappingCommons.COUNTERCLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, GLENROSA, //
StrategicMappingCommons.COUNTERCLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, WESTBANK) //
.addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_0, //
Arrays.asList(//
Stops.getALL_STOPS().get("140006"), // Westbank Exchange Bay C
Stops.getALL_STOPS().get("103624"), // McNair at Webber
Stops.getALL_STOPS().get("103641") // Canary @ Blue Jay
)) //
.addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_1, //
Arrays.asList(//
Stops.getALL_STOPS().get("103641"), // Canary @ Blue Jay
Stops.getALL_STOPS().get("103643"), // Glenrosa at Dunfield
Stops.getALL_STOPS().get("140006") // Westbank Exchange Bay C
)) //
.compileBothTripSort());
map2.put(27L, new RouteTripSpec(27L, // 29 //
StrategicMappingCommons.COUNTERCLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, "Bear Crk", //
StrategicMappingCommons.COUNTERCLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, "Boucherie Mtn") //
.addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_0, //
Arrays.asList(//
Stops.getALL_STOPS().get("140011"), // Boucherie Mountain Exchange Bay E
Stops.getALL_STOPS().get("103115"), // Westlake at Horizon (EB)
Stops.getALL_STOPS().get("103043") // Westside at Bear Creek (SB) => CONTINUE
)) //
.addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_1, //
Arrays.asList(//
Stops.getALL_STOPS().get("103043"), // Westside at Bear Creek (SB) <= CONTINUE
Stops.getALL_STOPS().get("103078"), // Boucherie at Hayman (WB)
Stops.getALL_STOPS().get("140011") // Boucherie Mountain Exchange Bay E
)) //
.compileBothTripSort());
map2.put(28L, new RouteTripSpec(28L, // 32 //
StrategicMappingCommons.CLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, "Main & Grant", //
StrategicMappingCommons.CLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, "Shoreline & Stillwater") //
.addTripSort(StrategicMappingCommons.CLOCKWISE_0, //
Arrays.asList(//
Stops.getALL_STOPS().get("140081"), // Shoreline at Stillwater (NB) <= CONTINUE ?
Stops.getALL_STOPS().get("140088"), // Oceola at Pretty (SB) #LakewoodMall
Stops.getALL_STOPS().get("103472") // Main at Grant Rd (NB)
)) //
.addTripSort(StrategicMappingCommons.CLOCKWISE_1, //
Arrays.asList(//
Stops.getALL_STOPS().get("103472"), // Main at Grant Rd (NB)
Stops.getALL_STOPS().get("103685"), // Oceola at Pretty (NB) #LakewoodMall
Stops.getALL_STOPS().get("140081") // Shoreline at Stillwater (NB) => CONTINUE ?
)) //
.compileBothTripSort());
ALL_ROUTE_TRIPS2 = map2;
}
@Override
public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) {
if (ALL_ROUTE_TRIPS2.containsKey(routeId)) {
return ALL_ROUTE_TRIPS2.get(routeId).compare(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop, this);
}
return super.compareEarly(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop);
}
@Override
public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return ALL_ROUTE_TRIPS2.get(mRoute.getId()).getAllTrips();
}
return super.splitTrip(mRoute, gTrip, gtfs);
}
@Override
public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return SplitUtils.splitTripStop(mRoute, gTrip, gTripStop, routeGTFS, ALL_ROUTE_TRIPS2.get(mRoute.getId()), this);
}
return super.splitTripStop(mRoute, gTrip, gTripStop, splitTrips, routeGTFS);
}
private final HashMap<Long, Long> routeIdToShortName = new HashMap<>();
@Override
public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return; // split
}
final long rsn = Long.parseLong(mRoute.getShortName());
this.routeIdToShortName.put(mRoute.getId(), rsn);
if (rsn == 1L) {
if (gTrip.getDirectionId() == 0) { // Downtown - NORTH
if ("Downtown".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Mission Rec Exch - SOUTH
if (Arrays.asList( //
"Lakeshore to OK College", //
"Lakeshore - To OK College", //
"Lakeshore - To South Pandosy", //
"Lakeshore - Mission Rec Exch" //
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 4L) {
if (gTrip.getDirectionId() == 0) { // UBCO - NORTH
if ("UBCO Express".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Pandosy - SOUTH
if ("Pandosy Express".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 5L) {
if (gTrip.getDirectionId() == 0) { // Downtown - NORTH
if ("Downtown".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Mission Rec Exch - SOUTH
if ("Gordon - Mission Rec Exch".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 6L) {
if (gTrip.getDirectionId() == 0) { // Downtown - INBOUND // Queensway Exch - INBOUND
if ("Downtown".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.INBOUND);
return;
}
} else if (gTrip.getDirectionId() == 1) { // UBCO Exch - OUTBOUND
if ("UBCO".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.OUTBOUND);
return;
}
}
} else if (rsn == 8L) {
if (gTrip.getDirectionId() == 0) { // UBCO - NORTH
if ("University - To UBCO".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "To Orchard Park".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // OK College - SOUTH
if ("OK College".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "University to OK College".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "To Orchard Park".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 9L) {
if (gTrip.getDirectionId() == 0) { // Downtown - WEST
if ("Shopper Shuttle - To Downtown".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Orchard Park - EAST
if ("Shopper Shuttle - To Orchard Park".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (rsn == 10L) {
if (gTrip.getDirectionId() == 0) { // Queensway Exch - WEST
if (Arrays.asList( //
"North Rutland", // <>
"Downtown", //
"To Orchard Park" //
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Rutland - EAST
if ("North Rutland".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (rsn == 11L) {
if (gTrip.getDirectionId() == 0) { // Downtown - WEST
if (Arrays.asList( //
"Downtown", //
"to Orchard Park", //
"To Orchard Park", //
"Rutland to Orchard Park" //
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Rutland - EAST
if (Arrays.asList( //
"Rutland To 14 Black Mtn", //
"To Orchard Park", //
"Rutland" //
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (rsn == 12L) {
if (gTrip.getDirectionId() == 0) { // S.Pandosy Exch - WEST
if ("McCulloch - To Orchard Park".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "McCulloch - To South Pandosy".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "McCulloch to OK College".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // McCulloch - EAST
if ("McCulloch".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (rsn == 14L) {
if (gTrip.getDirectionId() == 0) { // Rutland Exch - NORTH
if (Arrays.asList( //
"Black Mountain", // <>
"Black Mountain - To Rutland", //
"Black Mountain - To Rutland Exch" //
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Black Mountain - SOUTH
if ("Black Mountain".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 18L) {
if (gTrip.getDirectionId() == 0) { // Glenmore - NORTH
if ("Glenmore".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Downtown - SOUTH
if ("Downtown".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 19L) {
if (gTrip.getDirectionId() == 0) { // Glenmore - NORTH
if ("Glenmore".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Orchard Pk - SOUTH
if ("Orchard Park".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 20L) {
if (gTrip.getDirectionId() == 0) { // Westbank - WEST
if ("Lakeview - To Westbank".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Boucherie Mtn - EAST
if ("Lakeview - Boucherie Mtn".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (rsn == 22L) {
if (gTrip.getDirectionId() == 0) { // Westbank - NORTH
if ("Peachland - To Westbank".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "Peachland Exp - To Westbank".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Peachland - SOUTH
if ("Peachland".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 23L) {
if (gTrip.getDirectionId() == 0) { // Lake Country - NORTH
if ("Lake Country".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "Lake Country Via Airport".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "Lake Country - Old Vernon Rd".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // UBCO Exch - SOUTH
if ("UBCO".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "UBCO Via Airport".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "UBCO - Old Vernon Rd".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 24L) {
if (gTrip.getDirectionId() == 0) { // Westbank - WEST
if ("Shannon Lake - To Westbank".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "Shannon Ridge- To Westbank".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Boucherie Mtn - EAST
if ("Shannon Lake - Boucherie Mtn".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "Shannon Ridge - Boucherie Mtn".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (rsn == 25L) {
if (gTrip.getDirectionId() == 0) { // Westbank - WEST
if ("East Boundary - To Westbank".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Boucherie Mtn - EAST
if ("East Boundary - Boucherie Mtn".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (rsn == 26L) {
if (gTrip.getDirectionId() == 0) { // Boucherie Mtn - NORTH
if ("Old Okanagan - Boucherie Mtn".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Westbank - SOUTH
if ("East Boundary - To Westbank".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "Old Okanagan - Westbank Ex.".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 28L) { //
if (gTrip.getDirectionId() == 0) { // Boucherie Mtn - NORTH
if ("Shannon Lake - Boucherie Mtn".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Westbank - SOUTH
if ("Shannon Lake - Westbank".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (rsn == 88L) { //
if (gTrip.getDirectionId() == 1) { // Boucherie Mtn - OUTBOUND // Special - OUTBOUND
if ("Special".equalsIgnoreCase(gTrip.getTripHeadsign())) {
if ("Special".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString("Boucherie Mtn", StrategicMappingCommons.OUTBOUND);
return;
}
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.OUTBOUND);
return;
}
}
} else if (rsn == 97L) {
if (gTrip.getDirectionId() == 0) { // Westbank - WEST
if ("Westbank".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "To Cooper Stn".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "Downtown".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // UBCO - EAST
if ("UBCO".equalsIgnoreCase(gTrip.getTripHeadsign()) //
|| "Downtown".equalsIgnoreCase(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
}
MTLog.logFatal("%s: Unexpected trips head sign for %s!", mTrip.getRouteId(), gTrip);
}
@Override
public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) {
if (MTrip.mergeEmpty(mTrip, mTripToMerge)) {
return true;
}
List<String> headsignsValues = Arrays.asList(mTrip.getHeadsignValue(), mTripToMerge.getHeadsignValue());
final long rsn = this.routeIdToShortName.get(mTrip.getRouteId());
if (rsn == 1L) {
if (Arrays.asList( //
OK_COLLEGE, //
"South Pandosy", //
MISSION_REC_EXCH //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(MISSION_REC_EXCH, mTrip.getHeadsignId());
return true;
}
} else if (rsn == 8L) {
if (Arrays.asList( //
ORCHARD_PK, // <>
OK_COLLEGE //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(OK_COLLEGE, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
ORCHARD_PK, // <>
UBCO //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UBCO, mTrip.getHeadsignId());
return true;
}
} else if (rsn == 10L) {
if (Arrays.asList( //
"North Rutland", // <>
ORCHARD_PK, //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
}
} else if (rsn == 11L) {
if (Arrays.asList( //
ORCHARD_PK, // <>
BLACK_MOUNTAIN, //
RUTLAND //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(RUTLAND, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
ORCHARD_PK, // <>
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
}
} else if (rsn == 12L) {
if (Arrays.asList( //
ORCHARD_PK, //
OK_COLLEGE, //
SOUTH_PANDOSY //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(SOUTH_PANDOSY, mTrip.getHeadsignId());
return true;
}
} else if (rsn == 14L) {
if (Arrays.asList( //
"Black Mtn", // <>
"Rutland Exch" //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Rutland Exch", mTrip.getHeadsignId());
return true;
}
} else if (rsn == 23L) {
if (Arrays.asList( //
"Old Vernon Rd", // <>
LK_COUNTRY //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(LK_COUNTRY, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
"Old Vernon Rd", // <>
UBCO //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UBCO, mTrip.getHeadsignId());
return true;
}
} else if (rsn == 97L) {
if (Arrays.asList( //
DOWNTOWN, // <>
"Cooper Stn", //
WESTBANK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(WESTBANK, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
DOWNTOWN, // <>
UBCO //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UBCO, mTrip.getHeadsignId());
return true;
}
}
MTLog.logFatal("Unexpected trips to merge %s & %s!", mTrip, mTripToMerge);
return false;
}
private static final Pattern EXCHANGE = Pattern.compile("((^|\\W)(exchange|ex)(\\W|$))", Pattern.CASE_INSENSITIVE);
private static final String EXCHANGE_REPLACEMENT = "$2" + EXCH + "$4";
private static final Pattern STARTS_WITH_NUMBER = Pattern.compile("(^[\\d]+[\\S]*)", Pattern.CASE_INSENSITIVE);
private static final Pattern STARTS_WITH_DASH = Pattern.compile("(^.* - )", Pattern.CASE_INSENSITIVE);
private static final Pattern ENDS_WITH_EXPRESS = Pattern.compile("((\\W)(express)($))", Pattern.CASE_INSENSITIVE);
private static final Pattern SPECIAL = Pattern.compile("((^|\\W)(special)(\\W|$))", Pattern.CASE_INSENSITIVE);
@Override
public String cleanTripHeadsign(String tripHeadsign) {
tripHeadsign = CleanUtils.keepToAndRemoveVia(tripHeadsign);
tripHeadsign = EXCHANGE.matcher(tripHeadsign).replaceAll(EXCHANGE_REPLACEMENT);
tripHeadsign = CleanUtils.CLEAN_AND.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT);
tripHeadsign = STARTS_WITH_NUMBER.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = STARTS_WITH_DASH.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = ENDS_WITH_EXPRESS.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = SPECIAL.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = CleanUtils.removePoints(tripHeadsign);
tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign);
tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign);
return CleanUtils.cleanLabel(tripHeadsign);
}
private static final Pattern STARTS_WITH_IMPL = Pattern.compile("(^(\\(-IMPL-\\)))", Pattern.CASE_INSENSITIVE);
@Override
public String cleanStopName(String gStopName) {
gStopName = STARTS_WITH_IMPL.matcher(gStopName).replaceAll(StringUtils.EMPTY);
gStopName = CleanUtils.cleanBounds(gStopName);
gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT);
gStopName = EXCHANGE.matcher(gStopName).replaceAll(EXCHANGE_REPLACEMENT);
gStopName = CleanUtils.cleanStreetTypes(gStopName);
gStopName = CleanUtils.cleanNumbers(gStopName);
return CleanUtils.cleanLabel(gStopName);
}
@Override
public int getStopId(GStop gStop) { // used by GTFS-RT
return super.getStopId(gStop);
}
}
| April 7 update
| src/main/java/org/mtransit/parser/ca_kelowna_regional_transit_system_bus/KelownaRegionalTransitSystemBusAgencyTools.java | April 7 update | <ide><path>rc/main/java/org/mtransit/parser/ca_kelowna_regional_transit_system_bus/KelownaRegionalTransitSystemBusAgencyTools.java
<ide> Stops.getALL_STOPS().get("103041") // Glenmore AT Summit (NB) => CONTINUE
<ide> )) //
<ide> .compileBothTripSort());
<del> map2.put(12L, new RouteTripSpec(12L, // 13 //
<add> map2.put(-1L, new RouteTripSpec(-1L, // 13 //
<ide> StrategicMappingCommons.COUNTERCLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, "Country Club", //
<ide> StrategicMappingCommons.COUNTERCLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, UBCO) //
<ide> .addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_0, //
<ide> Stops.getALL_STOPS().get("140104") // UBCO Exchange Bay D
<ide> )) //
<ide> .compileBothTripSort());
<del> map2.put(14L, new RouteTripSpec(14L, // 15 //
<add> map2.put(12L, new RouteTripSpec(12L, // 15 //
<ide> StrategicMappingCommons.COUNTERCLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, "Crawford", //
<ide> StrategicMappingCommons.COUNTERCLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, MISSION_REC_EXCH) //
<ide> .addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_0, //
<ide> Stops.getALL_STOPS().get("103021") // Mission Rec Exchange Bay A
<ide> )) //
<ide> .compileBothTripSort());
<del> map2.put(15L, new RouteTripSpec(15L, // 16 //
<add> map2.put(13L, new RouteTripSpec(13L, // 16 //
<ide> StrategicMappingCommons.COUNTERCLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, "Kettle Vly", //
<ide> StrategicMappingCommons.COUNTERCLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, MISSION_REC_EXCH) //
<ide> .addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_0, //
<ide> Stops.getALL_STOPS().get("103022") // Mission Rec Exchange Bay B
<ide> )) //
<ide> .compileBothTripSort());
<del> map2.put(16L, new RouteTripSpec(16L, // 17
<add> map2.put(14L, new RouteTripSpec(14L, // 17
<ide> StrategicMappingCommons.CLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, "Southridge", //
<ide> StrategicMappingCommons.CLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, MISSION_REC_EXCH) //
<ide> .addTripSort(StrategicMappingCommons.CLOCKWISE_0, //
<ide> Stops.getALL_STOPS().get("103022") // Mission Rec Exchange Bay B
<ide> )) //
<ide> .compileBothTripSort());
<del> map2.put(20L, new RouteTripSpec(20L, // 21
<add> map2.put(18L, new RouteTripSpec(18L, // 21
<ide> StrategicMappingCommons.COUNTERCLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, GLENROSA, //
<ide> StrategicMappingCommons.COUNTERCLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, WESTBANK) //
<ide> .addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_0, //
<ide> Stops.getALL_STOPS().get("140006") // Westbank Exchange Bay C
<ide> )) //
<ide> .compileBothTripSort());
<del> map2.put(27L, new RouteTripSpec(27L, // 29 //
<add> map2.put(25L, new RouteTripSpec(25L, // 29 //
<ide> StrategicMappingCommons.COUNTERCLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, "Bear Crk", //
<ide> StrategicMappingCommons.COUNTERCLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, "Boucherie Mtn") //
<ide> .addTripSort(StrategicMappingCommons.COUNTERCLOCKWISE_0, //
<ide> Stops.getALL_STOPS().get("140011") // Boucherie Mountain Exchange Bay E
<ide> )) //
<ide> .compileBothTripSort());
<del> map2.put(28L, new RouteTripSpec(28L, // 32 //
<add> map2.put(26L, new RouteTripSpec(26L, // 32 //
<ide> StrategicMappingCommons.CLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, "Main & Grant", //
<ide> StrategicMappingCommons.CLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, "Shoreline & Stillwater") //
<ide> .addTripSort(StrategicMappingCommons.CLOCKWISE_0, // |
|
JavaScript | mit | ebd2b1f5fcea2c4c83a98735b475d53e34765ce1 | 0 | andreash92/andreasBot,andreash92/andreasBot,andreash92/andreasBot | module.exports = function (robot) {
// 'use strict'
var slackmsg = require("./slackMsgs.js");
var request = require('request');
var rp = require('request-promise');
var Trello = require('node-trello');
var db = require("./mlab-login").db();
// auth
var key = process.env.HUBOT_TRELLO_KEY;
var secret = process.env.HUBOT_TRELLO_OAUTH;
var token = process.env.HUBOT_TRELLO_TOKEN;
var trelloAuth = new Trello(key, token);
var collection = db.collection('trello')
const oauth_secrets = {};
var cb = `https://andreasbot.herokuapp.com/hubot/trello-token`;
var t = new Trello.OAuth(key, secret, cb, 'App Name');
// robot.logger.warning(t);
var tgr = t.getRequestToken(function (err, data) {
robot.logger.warning(data)
oauth_secrets[data.oauth_token] = data.oauth_token_secret;
collection.insertAsync(data)
.then(result => robot.logger.info(result))
.catch(error => robot.logger.error(error));
})
robot.router.get('/hubot/trello-token', function (req, res) {
let args = req.query;
robot.logger.info(oauth_secrets);
collection.find().toArray(function (err, result) {
if (err) throw err;
let index = Object.keys(result).length;
//args = result[index];
console.log(`Result[${index}]: ${args}`);
//args['oauth_token_secret'] = '8852d39c4874774eb737c77fe1ccef0e';
t.getAccessToken(args, function (err, data) {
if (err) throw err;
robot.logger.info(`getAccessToken: ${data}`);
})
});
res.send(`<h2>Token succesfuly received. You can now close the window.</h2>\n
<button onclick=window.close()>close</button>`)
});
// convert node-trello callbacks to promises
const Promise = require("bluebird");
var trello = Promise.promisifyAll(trelloAuth);
robot.hear(/trello hooks/, function (res) {
let boardId = 'BE7seI7e';
let cb_url = 'https://andreasbot.herokuapp.com/hubot/trello-webhooks';
let args = { description: "my test webhook", callbackURL: cb_url, idModel: '59245663c76f54b975558854' };
trello.postAsync('/1/webhooks', args).then(function (data) {
res.send(data)
}).catch(function (err) {
res.send();
robot.logger.error(err.Error)
})
})
robot.on('trello-webhook-event', function (data, res) {
var room = "random";
let payload = data.body;
let type = payload.action.type;
robot.logger.info(type);
switch (type) {
case 'updateList':
robot.messageRoom(room, `updateList`);
break;
default:
robot.messageRoom(room, `trello-webhook-event`);
break;
}
})
/*******************************************************************/
/* Slack Buttons Implementation */
/*******************************************************************/
function sendMessageToSlackResponseURL(responseURL, JSONmessage) {
var postOptions = {
uri: responseURL,
method: 'POST',
headers: {
'Content-type': 'application/json'
},
json: JSONmessage
};
request(postOptions, (error, response, body) => {
if (error) {
// handle errors as you see fit
};
})
}
// trello board
robot.hear(/trello board/i, function (res_r) {
// TODO: fetch the board id from other source (env, redis or mongodb)
let boardId = 'BE7seI7e';
let args = { fields: "name,url,prefs" };
trello.get("/1/board/" + boardId, args, function (err, data) {
if (err) {
res.send('Error: ' + err);
robot.logger.error(err);
return 0;
}
// else !err
let msg = slackmsg.buttons();
msg.attachments[0].title = `<${data.url}|${data.name}>`;
msg.attachments[0].title_url = 'www.google.com'
msg.attachments[0].author_name = 'Board'
msg.attachments[0].callback_id = `trello_board`;
msg.attachments[0].color = `${data.prefs.backgroundColor}`;
// attach the board lists to buttons
let joinBtn = { "name": "join", "text": "Join", "type": "button", "value": "join" };
let subBtn = { "name": "sub", "text": "Subscribe", "type": "button", "value": "sub" };
let starBtn = { "name": "star", "text": "Star", "type": "button", "value": "star" };
let listsBtn = { "name": "lists", "text": "Lists", "type": "button", "value": "lists" };
let doneBtn = { "name": "done", "text": "Done", "type": "button", "value": "done", "style": "danger" };
msg.attachments[0].actions.push(joinBtn);
msg.attachments[0].actions.push(subBtn);
msg.attachments[0].actions.push(starBtn);
msg.attachments[0].actions.push(listsBtn);
msg.attachments[0].actions.push(doneBtn);
res_r.send(msg);
})
})
var slackCB = 'slack:msg_action:';
// responding to 'trello_board' interactive message
robot.on(slackCB + 'trello_board', function (data, res) {
robot.logger.info(`robot.on: ${slackCB}trello_board`);
let btnId = data.actions[0].value;
let btnName = data.actions[0].name;
let response_url = data.response_url;
let msg;
switch (btnId) {
case 'join':
break;
case 'sub':
break;
case 'star':
break;
case 'lists':
res.status(200).end(); // best practice to respond with 200 status
// get board info to fetch lists
let boardId = 'BE7seI7e';
let args = { lists: "all" };
trello.get("1/board/" + boardId, args, function (err, data) {
if (err) {
res.send(err);
robot.logger.error(err);
return;
}
// else if (!err)
// create buttons msg
let msg = slackmsg.buttons();
msg.text = `*${data.name}* board`;
msg.attachments[0].text = `Available lists`;
msg.attachments[0].callback_id = `trello_list`;
let listsNum = Object.keys(data.lists).length;
for (var i = 0; i < listsNum; i++) {
// TODO change value to some id or something similar
let name = data.lists[i].name;
let id = data.lists[i].id;
let list = { "name": name, "text": name, "type": "button", "value": id };
msg.attachments[0].actions.push(list);
}
sendMessageToSlackResponseURL(response_url, msg);
})
break;
case 'done':
//res.status(200).end() // best practice to respond with 200 status
msg = slackmsg.plainText();
res.send(msg);
//sendMessageToSlackResponseURL(response_url, msg);
// res.send(msg);
break;
default:
//Statements executed when none of the values match the value of the expression
break;
}
})
// responding to 'trello_list' interactive message
robot.on(slackCB + 'trello_list', function (data_board, res) {
let response_url = data_board.response_url;
res.status(200).end() // best practice to respond with 200 status
robot.logger.info(`robot.on: ${slackCB}trello_list`);
let listId = data_board.actions[0].value;
let listName = data_board.actions[0].name;
// call function to fetch list - provide list id
let args = { cards: "all" };
trello.get("/1/lists/" + listId, args, function (err, data) {
if (err) {
robot.logger.error(err);
res.send(`Error: ${err}`)
return 0;
}
// else !err
// create buttons msg
let msg = slackmsg.buttons();
msg.text = `*${listName}* list`;
msg.attachments[0].text = `Available Cards`;
msg.attachments[0].callback_id = `trello_list`;
let cardsNum = Object.keys(data.cards).length;
robot.logger.info(`total cards: ${cardsNum}`);
for (var i = 0; i < cardsNum; i++) {
let card = data.cards[i].name;
let cardId = data.cards[i].id;
let item = { "name": card, "text": card, "type": "button", "value": cardId };
msg.attachments[0].actions.push(item);
}
// respond with information for that list
sendMessageToSlackResponseURL(response_url, msg);
})
})
}
| scripts/trello-integration.js | module.exports = function (robot) {
'use strict'
var slackmsg = require("./slackMsgs.js");
var request = require('request');
var rp = require('request-promise');
var Trello = require('node-trello');
var db = require("./mlab-login").db();
// auth
var key = process.env.HUBOT_TRELLO_KEY;
var secret = process.env.HUBOT_TRELLO_OAUTH;
var token = process.env.HUBOT_TRELLO_TOKEN;
var trelloAuth = new Trello(key, token);
var collection = db.collection('trello')
const oauth_secrets = {};
var cb = `https://andreasbot.herokuapp.com/hubot/trello-token`;
var t = new Trello.OAuth(key, secret, cb, 'App Name');
// robot.logger.warning(t);
var tgr = t.getRequestToken(function (err, data) {
robot.logger.warning(data)
oauth_secrets[data.oauth_token] = data.oauth_token_secret;
collection.insertAsync(data)
.then(result => robot.logger.info(result))
.catch(error => robot.logger.error(error));
})
robot.router.get('/hubot/trello-token', function (req, res) {
let args = req.query;
robot.logger.info(oauth_secrets);
collection.find().toArray(function (err, result) {
if (err) throw err;
let index = Object.keys(result).length;
//args = result[index];
console.log(`Result[${index}]: ${args}`);
//args['oauth_token_secret'] = '8852d39c4874774eb737c77fe1ccef0e';
t.getAccessToken(args, function (err, data) {
if (err) throw err;
robot.logger.info(`getAccessToken: ${data}`);
})
});
res.send(`<h2>Token succesfuly received. You can now close the window.</h2>\n
<button onclick=window.close()>close</button>`)
});
// convert node-trello callbacks to promises
const Promise = require("bluebird");
var trello = Promise.promisifyAll(trelloAuth);
robot.hear(/trello hooks/, function (res) {
let boardId = 'BE7seI7e';
let cb_url = 'https://andreasbot.herokuapp.com/hubot/trello-webhooks';
let args = { description: "my test webhook", callbackURL: cb_url, idModel: '59245663c76f54b975558854' };
trello.postAsync('/1/webhooks', args).then(function (data) {
res.send(data)
}).catch(function (err) {
res.send();
robot.logger.error(err.Error)
})
})
robot.on('trello-webhook-event', function (data, res) {
var room = "random";
let payload = data.body;
let type = payload.action.type;
robot.logger.info(type);
switch (type) {
case 'updateList':
robot.messageRoom(room, `updateList`);
break;
default:
robot.messageRoom(room, `trello-webhook-event`);
break;
}
})
/*******************************************************************/
/* Slack Buttons Implementation */
/*******************************************************************/
function sendMessageToSlackResponseURL(responseURL, JSONmessage) {
var postOptions = {
uri: responseURL,
method: 'POST',
headers: {
'Content-type': 'application/json'
},
json: JSONmessage
};
request(postOptions, (error, response, body) => {
if (error) {
// handle errors as you see fit
};
})
}
// trello board
robot.hear(/trello board/i, function (res_r) {
// TODO: fetch the board id from other source (env, redis or mongodb)
let boardId = 'BE7seI7e';
let args = { fields: "name,url,prefs" };
trello.get("/1/board/" + boardId, args, function (err, data) {
if (err) {
res.send('Error: ' + err);
robot.logger.error(err);
return 0;
}
// else !err
let msg = slackmsg.buttons();
msg.attachments[0].title = `<${data.url}|${data.name}>`;
msg.attachments[0].title_url = 'www.google.com'
msg.attachments[0].author_name = 'Board'
msg.attachments[0].callback_id = `trello_board`;
msg.attachments[0].color = `${data.prefs.backgroundColor}`;
// attach the board lists to buttons
let joinBtn = { "name": "join", "text": "Join", "type": "button", "value": "join" };
let subBtn = { "name": "sub", "text": "Subscribe", "type": "button", "value": "sub" };
let starBtn = { "name": "star", "text": "Star", "type": "button", "value": "star" };
let listsBtn = { "name": "lists", "text": "Lists", "type": "button", "value": "lists" };
let doneBtn = { "name": "done", "text": "Done", "type": "button", "value": "done", "style": "danger" };
msg.attachments[0].actions.push(joinBtn);
msg.attachments[0].actions.push(subBtn);
msg.attachments[0].actions.push(starBtn);
msg.attachments[0].actions.push(listsBtn);
msg.attachments[0].actions.push(doneBtn);
res_r.send(msg);
})
})
var slackCB = 'slack:msg_action:';
// responding to 'trello_board' interactive message
robot.on(slackCB + 'trello_board', function (data, res) {
robot.logger.info(`robot.on: ${slackCB}trello_board`);
let btnId = data.actions[0].value;
let btnName = data.actions[0].name;
let response_url = data.response_url;
let msg;
switch (btnId) {
case 'join':
break;
case 'sub':
break;
case 'star':
break;
case 'lists':
res.status(200).end(); // best practice to respond with 200 status
// get board info to fetch lists
let boardId = 'BE7seI7e';
let args = { lists: "all" };
trello.get("1/board/" + boardId, args, function (err, data) {
if (err) {
res.send(err);
robot.logger.error(err);
return;
}
// else if (!err)
// create buttons msg
let msg = slackmsg.buttons();
msg.text = `*${data.name}* board`;
msg.attachments[0].text = `Available lists`;
msg.attachments[0].callback_id = `trello_list`;
let listsNum = Object.keys(data.lists).length;
for (var i = 0; i < listsNum; i++) {
// TODO change value to some id or something similar
let name = data.lists[i].name;
let id = data.lists[i].id;
let list = { "name": name, "text": name, "type": "button", "value": id };
msg.attachments[0].actions.push(list);
}
sendMessageToSlackResponseURL(response_url, msg);
})
break;
case 'done':
//res.status(200).end() // best practice to respond with 200 status
msg = slackmsg.plainText();
res.send(msg);
//sendMessageToSlackResponseURL(response_url, msg);
// res.send(msg);
break;
default:
//Statements executed when none of the values match the value of the expression
break;
}
})
// responding to 'trello_list' interactive message
robot.on(slackCB + 'trello_list', function (data_board, res) {
let response_url = data_board.response_url;
res.status(200).end() // best practice to respond with 200 status
robot.logger.info(`robot.on: ${slackCB}trello_list`);
let listId = data_board.actions[0].value;
let listName = data_board.actions[0].name;
// call function to fetch list - provide list id
let args = { cards: "all" };
trello.get("/1/lists/" + listId, args, function (err, data) {
if (err) {
robot.logger.error(err);
res.send(`Error: ${err}`)
return 0;
}
// else !err
// create buttons msg
let msg = slackmsg.buttons();
msg.text = `*${listName}* list`;
msg.attachments[0].text = `Available Cards`;
msg.attachments[0].callback_id = `trello_list`;
let cardsNum = Object.keys(data.cards).length;
robot.logger.info(`total cards: ${cardsNum}`);
for (var i = 0; i < cardsNum; i++) {
let card = data.cards[i].name;
let cardId = data.cards[i].id;
let item = { "name": card, "text": card, "type": "button", "value": cardId };
msg.attachments[0].actions.push(item);
}
// respond with information for that list
sendMessageToSlackResponseURL(response_url, msg);
})
})
}
| trello token
| scripts/trello-integration.js | trello token | <ide><path>cripts/trello-integration.js
<ide> module.exports = function (robot) {
<del> 'use strict'
<add> // 'use strict'
<ide>
<ide> var slackmsg = require("./slackMsgs.js");
<ide> var request = require('request'); |
|
Java | isc | 50797b4941d983b406ecf8b9f6532f3c857b1030 | 0 | io7m/jparasol,io7m/jparasol | /*
* Copyright © 2014 <[email protected]> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.jparasol.typed;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.io7m.jfunctional.Unit;
import com.io7m.jparasol.CompilerError;
import com.io7m.jparasol.lexer.Position;
import com.io7m.jparasol.lexer.Token.TokenDiscard;
import com.io7m.jparasol.lexer.Token.TokenIdentifierLower;
import com.io7m.jparasol.lexer.Token.TokenIf;
import com.io7m.jparasol.typed.TType.TBoolean;
import com.io7m.jparasol.typed.TType.TConstructor;
import com.io7m.jparasol.typed.TType.TFunctionArgument;
import com.io7m.jparasol.typed.TType.TManifestType;
import com.io7m.jparasol.typed.TType.TRecord;
import com.io7m.jparasol.typed.TType.TRecordField;
import com.io7m.jparasol.typed.TType.TValueType;
import com.io7m.jparasol.typed.TType.TVector4F;
import com.io7m.jparasol.typed.TType.TVectorType;
import com.io7m.jparasol.typed.ast.TASTDeclaration.TASTDShader;
import com.io7m.jparasol.typed.ast.TASTDeclaration.TASTDShaderFragment;
import com.io7m.jparasol.typed.ast.TASTDeclaration.TASTDShaderFragmentInput;
import com.io7m.jparasol.typed.ast.TASTDeclaration.TASTDShaderProgram;
import com.io7m.jparasol.typed.ast.TASTDeclaration.TASTDShaderVertex;
import com.io7m.jparasol.typed.ast.TASTExpression;
import com.io7m.jparasol.typed.ast.TASTShaderVisitorType;
import com.io7m.jparasol.typed.ast.TASTTermName.TASTTermNameLocal;
import com.io7m.jparasol.untyped.ast.resolved.UASTRDeclaration.UASTRDShaderFragmentInput;
import com.io7m.jparasol.untyped.ast.resolved.UASTRDeclaration.UASTRDShaderFragmentOutput;
import com.io7m.jparasol.untyped.ast.resolved.UASTRDeclaration.UASTRDShaderFragmentOutputDepth;
import com.io7m.jparasol.untyped.ast.resolved.UASTRDeclaration.UASTRDShaderVertexInput;
import com.io7m.jparasol.untyped.ast.resolved.UASTRDeclaration.UASTRDShaderVertexOutput;
import com.io7m.jparasol.untyped.ast.resolved.UASTRShaderName;
import com.io7m.jparasol.untyped.ast.resolved.UASTRTermName;
import com.io7m.jparasol.untyped.ast.resolved.UASTRTypeName;
import com.io7m.jparasol.untyped.ast.resolved.UASTRTypeName.UASTRTypeNameBuiltIn;
import com.io7m.jparasol.untyped.ast.resolved.UASTRTypeName.UASTRTypeNameGlobal;
import com.io7m.jparasol.untyped.ast.resolved.UASTRTypeNameVisitorType;
import com.io7m.junreachable.UnreachableCodeException;
/**
* The type of type errors.
*/
public final class TypeCheckerError extends CompilerError
{
/**
* Type error codes.
*/
public static enum Code
{
/**
* Incorrect types for function application.
*/
TYPE_ERROR_EXPRESSION_APPLICATION_BAD_TYPES,
/**
* Attempting to apply a value of a non-function.
*/
TYPE_ERROR_EXPRESSION_APPLICATION_NOT_FUNCTION_TYPE,
/**
* Non-boolean condition on conditional.
*/
TYPE_ERROR_EXPRESSION_CONDITION_NOT_BOOLEAN,
/**
* No available constructor for the given list of expressions.
*/
TYPE_ERROR_EXPRESSION_NEW_NO_APPROPRIATE_CONSTRUCTORS,
/**
* Type has no constructor.
*/
TYPE_ERROR_EXPRESSION_NEW_TYPE_NOT_CONSTRUCTABLE,
/**
* Incorrect record field type.
*/
TYPE_ERROR_EXPRESSION_RECORD_FIELD_BAD_TYPE,
/**
* Unknown record field.
*/
TYPE_ERROR_EXPRESSION_RECORD_FIELD_UNKNOWN,
/**
* Record fields left unassigned.
*/
TYPE_ERROR_EXPRESSION_RECORD_FIELDS_UNASSIGNED,
/**
* Value is not of a record type.
*/
TYPE_ERROR_EXPRESSION_RECORD_NOT_RECORD_TYPE,
/**
* Nonexistent field in record projection.
*/
TYPE_ERROR_EXPRESSION_RECORD_PROJECTION_NO_SUCH_FIELD,
/**
* Target of record projection is not of a record type.
*/
TYPE_ERROR_EXPRESSION_RECORD_PROJECTION_NOT_RECORD,
/**
* Target of swizzle expression is not of a vector type.
*/
TYPE_ERROR_EXPRESSION_SWIZZLE_NOT_VECTOR,
/**
* Too many components in swizzle expression.
*/
TYPE_ERROR_EXPRESSION_SWIZZLE_TOO_MANY_COMPONENTS,
/**
* Unknown component(s) in swizzle expression.
*/
TYPE_ERROR_EXPRESSION_SWIZZLE_UNKNOWN_COMPONENT,
/**
* Returned value incompatible with declared return type.
*/
TYPE_ERROR_FUNCTION_BODY_RETURN_INCOMPATIBLE,
/**
* Record field is of non-manifest type.
*/
TYPE_ERROR_RECORD_FIELD_NOT_MANIFEST,
/**
* Shader value or output assignment of incorrect type.
*/
TYPE_ERROR_SHADER_ASSIGNMENT_BAD_TYPE,
/**
* Shader attribute is of a type that is not allowed by GLSL.
*/
TYPE_ERROR_SHADER_BAD_ATTRIBUTE_TYPE,
/**
* Shader depth output is not a scalar floating point.
*/
TYPE_ERROR_SHADER_DEPTH_NOT_FLOAT,
/**
* Shader discard expression is not boolean.
*/
TYPE_ERROR_SHADER_DISCARD_NOT_BOOLEAN,
/**
* Main shader output is not of an appropriate type.
*/
TYPE_ERROR_SHADER_OUTPUT_MAIN_BAD_TYPE,
/**
* Incorrect type of shader specified (vertex shader where fragment shader
* is required, etc).
*/
TYPE_ERROR_SHADER_WRONG_SHADER_TYPE,
/**
* Vertex and fragment shaders are incompatible.
*/
TYPE_ERROR_SHADERS_INCOMPATIBLE,
/**
* The type ascribed to a value does not match the type of the value.
*/
TYPE_ERROR_VALUE_ASCRIPTION_MISMATCH,
/**
* Non-value type used where a value type is required.
*/
TYPE_ERROR_VALUE_NON_VALUE_TYPE
}
private static final long serialVersionUID = 8186811920948826949L;
/**
* @return A type error
*/
public static TypeCheckerError shaderAssignmentBadType(
final TokenIdentifierLower name,
final TValueType out_type,
final TType type)
{
final StringBuilder m = new StringBuilder();
m.append("The shader output ");
m.append(name.getActual());
m.append(" is of type ");
m.append(out_type.getShowName());
m.append(" but an expression was given of type ");
m.append(type.getShowName());
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
name.getFile(),
name.getPosition(),
Code.TYPE_ERROR_SHADER_ASSIGNMENT_BAD_TYPE,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError shaderDiscardNotBoolean(
final TokenDiscard discard,
final TType type)
{
final StringBuilder m = new StringBuilder();
m.append("A discard expression must be of type ");
m.append(TBoolean.get().getShowName());
m.append(" but an expression was given of type ");
m.append(type.getShowName());
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
discard.getFile(),
discard.getPosition(),
Code.TYPE_ERROR_SHADER_DISCARD_NOT_BOOLEAN,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError shaderFragmentInputBadType(
final UASTRDShaderFragmentInput i)
{
return new TypeCheckerError(
i.getName().getFile(),
i.getName().getPosition(),
Code.TYPE_ERROR_SHADER_BAD_ATTRIBUTE_TYPE,
"An input of a fragment shader cannot be of a record type");
}
/**
* @return A type error
*/
public static TypeCheckerError shaderFragmentOutputBadType(
final UASTRDShaderFragmentOutput o)
{
return new TypeCheckerError(
o.getName().getFile(),
o.getName().getPosition(),
Code.TYPE_ERROR_SHADER_BAD_ATTRIBUTE_TYPE,
"An output of a fragment shader cannot be of a record type");
}
/**
* @return A type error
*/
public static TypeCheckerError shaderFragmentOutputDepthWrongType(
final UASTRDShaderFragmentOutputDepth d)
{
return new TypeCheckerError(
d.getName().getFile(),
d.getName().getPosition(),
Code.TYPE_ERROR_SHADER_DEPTH_NOT_FLOAT,
"The depth output of a fragment shader must be of type float");
}
/**
* @return A type error
*/
public static TypeCheckerError shaderNotFragment(
final UASTRShaderName name,
final TASTDShader shader)
{
final StringBuilder m = new StringBuilder();
m.append("The name ");
m.append(name.show());
m.append(" refers to a ");
shader
.shaderVisitableAccept(new TASTShaderVisitorType<Unit, UnreachableCodeException>() {
@Override public Unit moduleVisitFragmentShader(
final TASTDShaderFragment f)
{
throw new UnreachableCodeException();
}
@Override public Unit moduleVisitProgramShader(
final TASTDShaderProgram p)
{
m.append("program shader");
return Unit.unit();
}
@Override public Unit moduleVisitVertexShader(
final TASTDShaderVertex f)
{
m.append("vertex shader");
return Unit.unit();
}
});
m.append(" but a fragment shader is required");
final String r = m.toString();
assert r != null;
return new TypeCheckerError(name.getName().getFile(), name
.getName()
.getPosition(), Code.TYPE_ERROR_SHADER_WRONG_SHADER_TYPE, r);
}
/**
* @return A type error
*/
public static TypeCheckerError shaderNotVertex(
final UASTRShaderName name,
final TASTDShader shader)
{
final StringBuilder m = new StringBuilder();
m.append("The name ");
m.append(name.show());
m.append(" refers to a ");
shader
.shaderVisitableAccept(new TASTShaderVisitorType<Unit, UnreachableCodeException>() {
@Override public Unit moduleVisitFragmentShader(
final TASTDShaderFragment f)
{
m.append("fragment shader");
return Unit.unit();
}
@Override public Unit moduleVisitProgramShader(
final TASTDShaderProgram p)
{
m.append("program shader");
return Unit.unit();
}
@Override public Unit moduleVisitVertexShader(
final TASTDShaderVertex f)
{
throw new UnreachableCodeException();
}
});
m.append(" but a vertex shader is required");
final String r = m.toString();
assert r != null;
return new TypeCheckerError(name.getName().getFile(), name
.getName()
.getPosition(), Code.TYPE_ERROR_SHADER_WRONG_SHADER_TYPE, r);
}
/**
* @return A type error
*/
public static TypeCheckerError shadersNotCompatible(
final TokenIdentifierLower program,
final TASTDShaderFragment fs,
final Set<String> assigned,
final Map<String, TValueType> wrong_types)
{
final StringBuilder m = new StringBuilder();
m.append("The shaders for program ");
m.append(program.getActual());
m.append("are incompatible.\n");
m.append("Problems with each fragment shader input are indicated:\n");
for (final TASTDShaderFragmentInput f : fs.getInputs()) {
final TASTTermNameLocal fi_name = f.getName();
if (assigned.contains(fi_name.getCurrent()) == false) {
m.append(" ");
m.append(fi_name.getCurrent());
m.append(" : ");
m.append(f.getType().getShowName());
m.append(" has no matching vertex shader output\n");
} else if (wrong_types.containsKey(fi_name.getCurrent())) {
final TValueType type = wrong_types.get(fi_name.getCurrent());
assert type != null;
m.append(" ");
m.append(fi_name.getCurrent());
m.append(" : ");
m.append(f.getType().getShowName());
m.append(" is incompatible with the vertex shader output of type ");
m.append(type.getShowName());
m.append("\n");
}
}
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
program.getFile(),
program.getPosition(),
Code.TYPE_ERROR_SHADERS_INCOMPATIBLE,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError shaderVertexInputBadType(
final UASTRDShaderVertexInput i)
{
return new TypeCheckerError(
i.getName().getFile(),
i.getName().getPosition(),
Code.TYPE_ERROR_SHADER_BAD_ATTRIBUTE_TYPE,
"An input of a vertex shader cannot be of a record type");
}
/**
* @return A type error
*/
public static TypeCheckerError shaderVertexMainOutputBadType(
final UASTRDShaderVertexOutput o,
final TType t)
{
final StringBuilder m = new StringBuilder();
m.append("The main output of a vertex shader must be of type ");
m.append(TVector4F.get().getShowName());
m.append(" but the given output is of type ");
m.append(t.getShowName());
final String r = m.toString();
assert r != null;
return new TypeCheckerError(o.getName().getFile(), o
.getName()
.getPosition(), Code.TYPE_ERROR_SHADER_OUTPUT_MAIN_BAD_TYPE, r);
}
/**
* @return A type error
*/
public static TypeCheckerError shaderVertexOutputBadType(
final UASTRDShaderVertexOutput o)
{
return new TypeCheckerError(
o.getName().getFile(),
o.getName().getPosition(),
Code.TYPE_ERROR_SHADER_BAD_ATTRIBUTE_TYPE,
"An output of a vertex shader cannot be of a record type");
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionApplicationBadTypes(
final UASTRTermName name,
final List<TFunctionArgument> expected,
final List<TASTExpression> got)
{
final StringBuilder m = new StringBuilder();
m.append("Incorrect argument types for application of function ");
m.append(name.getName().getActual());
m.append("\n");
m.append("Expected: ");
m.append(TType.formatFunctionArguments(expected));
m.append("\n");
m.append("Got: ");
m.append(TType.formatTypeExpressionList(got));
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
name.getFile(),
name.getPosition(),
Code.TYPE_ERROR_EXPRESSION_APPLICATION_BAD_TYPES,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionApplicationNotFunctionType(
final UASTRTermName name,
final TType t)
{
final StringBuilder m = new StringBuilder();
m.append("Cannot apply the term ");
m.append(name.getName().getActual());
m.append(" to the given arguments; ");
m.append(name.getName().getActual());
m.append(" is of the non-function type ");
m.append(t.getShowName());
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
name.getFile(),
name.getPosition(),
Code.TYPE_ERROR_EXPRESSION_APPLICATION_NOT_FUNCTION_TYPE,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionNewNoAppropriateConstructors(
final UASTRTypeName name,
final List<TASTExpression> arguments,
final List<TConstructor> constructors)
{
final StringBuilder m = new StringBuilder();
m.append("No appropriate constructor for type ");
m.append(name.getName().getActual());
m.append(" for arguments ");
m.append(TType.formatTypeExpressionList(arguments));
m.append("\n");
m.append("Available constructors are:\n");
for (final TConstructor c : constructors) {
m.append(" ");
m.append(TType.formatTypeList(c.getParameters()));
m.append(" → ");
m.append(name.getName().getActual());
m.append("\n");
}
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
name.getName().getFile(),
name.getName().getPosition(),
Code.TYPE_ERROR_EXPRESSION_NEW_NO_APPROPRIATE_CONSTRUCTORS,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionNewNotConstructable(
final UASTRTypeName name)
{
final TokenIdentifierLower n_name = name.getName();
final StringBuilder m = new StringBuilder();
m.append("The type ");
m.append(n_name);
m.append(" is not constructable");
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
n_name.getFile(),
n_name.getPosition(),
Code.TYPE_ERROR_EXPRESSION_NEW_TYPE_NOT_CONSTRUCTABLE,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionRecordBadFieldType(
final TokenIdentifierLower field_name,
final TManifestType expected_type,
final TType got_type)
{
final StringBuilder m = new StringBuilder();
m.append("The type of field ");
m.append(field_name.getActual());
m.append(" is ");
m.append(expected_type.getShowName());
m.append(" but an expression was given of type ");
m.append(got_type.getShowName());
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
field_name.getFile(),
field_name.getPosition(),
Code.TYPE_ERROR_EXPRESSION_RECORD_FIELD_BAD_TYPE,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionRecordFieldsUnassigned(
final UASTRTypeName name,
final List<TRecordField> unassigned)
{
final TokenIdentifierLower n_name = name.getName();
final StringBuilder m = new StringBuilder();
m
.append("The record expression leaves the following fields unassigned:\n");
for (final TRecordField u : unassigned) {
m.append(" ");
m.append(u.getName());
m.append(" : ");
m.append(u.getType().getShowName());
m.append("\n");
}
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
n_name.getFile(),
n_name.getPosition(),
Code.TYPE_ERROR_EXPRESSION_RECORD_FIELDS_UNASSIGNED,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionRecordNotRecordType(
final UASTRTypeName name)
{
final TokenIdentifierLower n_name = name.getName();
final StringBuilder m = new StringBuilder();
m.append("The type ");
m.append(n_name.getActual());
m
.append(" is not a record type and therefore values cannot be constructed with record expressions");
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
n_name.getFile(),
n_name.getPosition(),
Code.TYPE_ERROR_EXPRESSION_RECORD_NOT_RECORD_TYPE,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionRecordProjectionNoSuchField(
final TRecord tr,
final TokenIdentifierLower field)
{
final StringBuilder m = new StringBuilder();
m.append("The type ");
m.append(tr.getShowName());
m.append(" does not have a field named ");
m.append(field.getActual());
m.append("\n");
m.append("Available fields are:\n");
for (final TRecordField f : tr.getFields()) {
m.append(" ");
m.append(f.getName());
m.append(" : ");
m.append(f.getType().getShowName());
m.append("\n");
}
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
field.getFile(),
field.getPosition(),
Code.TYPE_ERROR_EXPRESSION_RECORD_PROJECTION_NO_SUCH_FIELD,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionRecordProjectionNotRecord(
final TASTExpression body,
final TokenIdentifierLower field)
{
final StringBuilder m = new StringBuilder();
m.append("The type of the given expression is ");
m.append(body.getType().getShowName());
m
.append(", which is not a record type and therefore the expression cannot be the body of a record projection");
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
field.getFile(),
field.getPosition(),
Code.TYPE_ERROR_EXPRESSION_RECORD_PROJECTION_NOT_RECORD,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionRecordUnknownField(
final TokenIdentifierLower field_name,
final TRecord record)
{
final StringBuilder m = new StringBuilder();
m.append("The type ");
m.append(record.getShowName());
m.append(" does not contain a field named ");
m.append(field_name.getActual());
m.append("\n");
m.append("Available fields are:\n");
for (final TRecordField f : record.getFields()) {
m.append(" ");
m.append(f.getName());
m.append(" : ");
m.append(f.getType().getShowName());
m.append("\n");
}
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
field_name.getFile(),
field_name.getPosition(),
Code.TYPE_ERROR_EXPRESSION_RECORD_FIELD_UNKNOWN,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionSwizzleNotVector(
final TASTExpression body,
final TokenIdentifierLower first_field)
{
final StringBuilder m = new StringBuilder();
m
.append("Only expressions of vector types can be swizzled. The given expression is of type ");
m.append(body.getType().getShowName());
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
first_field.getFile(),
first_field.getPosition(),
Code.TYPE_ERROR_EXPRESSION_SWIZZLE_NOT_VECTOR,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionSwizzleTooManyFields(
final TokenIdentifierLower first,
final int size)
{
final StringBuilder m = new StringBuilder();
m.append("Swizzle expressions can contain at most four components (");
m.append(size);
m.append(" were given)");
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
first.getFile(),
first.getPosition(),
Code.TYPE_ERROR_EXPRESSION_SWIZZLE_TOO_MANY_COMPONENTS,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionSwizzleUnknownField(
final TVectorType tv,
final TokenIdentifierLower f)
{
final StringBuilder m = new StringBuilder();
m.append("The type ");
m.append(tv.getShowName());
m.append(" does not have a component named ");
m.append(f.getActual());
m.append("\n");
m.append("Available components are: ");
for (final String name : tv.getComponentNames()) {
m.append(name);
m.append(" ");
}
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
f.getFile(),
f.getPosition(),
Code.TYPE_ERROR_EXPRESSION_SWIZZLE_UNKNOWN_COMPONENT,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termFunctionBodyReturnMismatch(
final TokenIdentifierLower name,
final TType expected,
final TType got)
{
final StringBuilder m = new StringBuilder();
m.append("The body of function ");
m.append(name.getActual());
m.append(" is expected to be of type ");
m.append(expected.getShowName());
m.append(" but an expression was given of type ");
m.append(got.getShowName());
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
name.getFile(),
name.getPosition(),
Code.TYPE_ERROR_FUNCTION_BODY_RETURN_INCOMPATIBLE,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termValueExpressionAscriptionMismatch(
final TokenIdentifierLower name,
final TType expected,
final TType got)
{
final StringBuilder m = new StringBuilder();
m.append("The ascription on value ");
m.append(name.getActual());
m.append(" requires that the type must be ");
m.append(expected.getShowName());
m.append(" but an expression was given of type ");
m.append(got.getShowName());
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
name.getFile(),
name.getPosition(),
Code.TYPE_ERROR_VALUE_ASCRIPTION_MISMATCH,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termValueNotValueType(
final TokenIdentifierLower name,
final TType type)
{
final StringBuilder m = new StringBuilder();
m.append("The body of value ");
m.append(name.getActual());
m.append(" is of a non-value type ");
m.append(type.getShowName());
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
name.getFile(),
name.getPosition(),
Code.TYPE_ERROR_VALUE_NON_VALUE_TYPE,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError typeConditionNotBoolean(
final TokenIf token,
final TASTExpression condition)
{
final StringBuilder m = new StringBuilder();
m
.append("The condition expression of a condition must be of type boolean, but an expression was given here of type ");
m.append(condition.getType().getShowName());
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
token.getFile(),
token.getPosition(),
Code.TYPE_ERROR_EXPRESSION_CONDITION_NOT_BOOLEAN,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError typeRecordFieldNotManifest(
final UASTRTypeName type_name,
final TType ty)
{
final StringBuilder m = new StringBuilder();
m.append("The (non-manifest) type ");
m.append(ty.getShowName());
m.append(" cannot be used as the type of a record field");
return type_name
.typeNameVisitableAccept(new UASTRTypeNameVisitorType<TypeCheckerError, UnreachableCodeException>() {
@SuppressWarnings("synthetic-access") @Override public
TypeCheckerError
typeNameVisitBuiltIn(
final UASTRTypeNameBuiltIn t)
{
final TokenIdentifierLower name = t.getName();
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
name.getFile(),
name.getPosition(),
Code.TYPE_ERROR_RECORD_FIELD_NOT_MANIFEST,
r);
}
@SuppressWarnings("synthetic-access") @Override public
TypeCheckerError
typeNameVisitGlobal(
final UASTRTypeNameGlobal t)
{
final TokenIdentifierLower name = t.getName();
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
name.getFile(),
name.getPosition(),
Code.TYPE_ERROR_RECORD_FIELD_NOT_MANIFEST,
r);
}
});
}
private final Code code;
private TypeCheckerError(
final File file,
final Position position,
final Code in_code,
final String message)
{
super(message, file, position);
this.code = in_code;
}
@Override public String getCategory()
{
return "type-checker";
}
/**
* @return The error code.
*/
public Code getCode()
{
return this.code;
}
}
| io7m-jparasol-compiler-core/src/main/java/com/io7m/jparasol/typed/TypeCheckerError.java | /*
* Copyright © 2014 <[email protected]> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.jparasol.typed;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.io7m.jfunctional.Unit;
import com.io7m.jparasol.CompilerError;
import com.io7m.jparasol.lexer.Position;
import com.io7m.jparasol.lexer.Token.TokenDiscard;
import com.io7m.jparasol.lexer.Token.TokenIdentifierLower;
import com.io7m.jparasol.lexer.Token.TokenIf;
import com.io7m.jparasol.typed.TType.TBoolean;
import com.io7m.jparasol.typed.TType.TConstructor;
import com.io7m.jparasol.typed.TType.TFunctionArgument;
import com.io7m.jparasol.typed.TType.TManifestType;
import com.io7m.jparasol.typed.TType.TRecord;
import com.io7m.jparasol.typed.TType.TRecordField;
import com.io7m.jparasol.typed.TType.TValueType;
import com.io7m.jparasol.typed.TType.TVector4F;
import com.io7m.jparasol.typed.TType.TVectorType;
import com.io7m.jparasol.typed.ast.TASTDeclaration.TASTDShader;
import com.io7m.jparasol.typed.ast.TASTDeclaration.TASTDShaderFragment;
import com.io7m.jparasol.typed.ast.TASTDeclaration.TASTDShaderFragmentInput;
import com.io7m.jparasol.typed.ast.TASTDeclaration.TASTDShaderProgram;
import com.io7m.jparasol.typed.ast.TASTDeclaration.TASTDShaderVertex;
import com.io7m.jparasol.typed.ast.TASTExpression;
import com.io7m.jparasol.typed.ast.TASTShaderVisitorType;
import com.io7m.jparasol.typed.ast.TASTTermName.TASTTermNameLocal;
import com.io7m.jparasol.untyped.ast.resolved.UASTRDeclaration.UASTRDShaderFragmentInput;
import com.io7m.jparasol.untyped.ast.resolved.UASTRDeclaration.UASTRDShaderFragmentOutput;
import com.io7m.jparasol.untyped.ast.resolved.UASTRDeclaration.UASTRDShaderFragmentOutputDepth;
import com.io7m.jparasol.untyped.ast.resolved.UASTRDeclaration.UASTRDShaderVertexInput;
import com.io7m.jparasol.untyped.ast.resolved.UASTRDeclaration.UASTRDShaderVertexOutput;
import com.io7m.jparasol.untyped.ast.resolved.UASTRShaderName;
import com.io7m.jparasol.untyped.ast.resolved.UASTRTermName;
import com.io7m.jparasol.untyped.ast.resolved.UASTRTypeName;
import com.io7m.jparasol.untyped.ast.resolved.UASTRTypeName.UASTRTypeNameBuiltIn;
import com.io7m.jparasol.untyped.ast.resolved.UASTRTypeName.UASTRTypeNameGlobal;
import com.io7m.jparasol.untyped.ast.resolved.UASTRTypeNameVisitorType;
import com.io7m.junreachable.UnreachableCodeException;
/**
* The type of type errors.
*/
public final class TypeCheckerError extends CompilerError
{
/**
* Type error codes.
*/
public static enum Code
{
/**
* Incorrect types for function application.
*/
TYPE_ERROR_EXPRESSION_APPLICATION_BAD_TYPES,
/**
* Attempting to apply a value of a non-function.
*/
TYPE_ERROR_EXPRESSION_APPLICATION_NOT_FUNCTION_TYPE,
/**
* Non-boolean condition on conditional.
*/
TYPE_ERROR_EXPRESSION_CONDITION_NOT_BOOLEAN,
/**
* No available constructor for the given list of expressions.
*/
TYPE_ERROR_EXPRESSION_NEW_NO_APPROPRIATE_CONSTRUCTORS,
/**
* Type has no constructor.
*/
TYPE_ERROR_EXPRESSION_NEW_TYPE_NOT_CONSTRUCTABLE,
/**
* Incorrect record field type.
*/
TYPE_ERROR_EXPRESSION_RECORD_FIELD_BAD_TYPE,
/**
* Unknown record field.
*/
TYPE_ERROR_EXPRESSION_RECORD_FIELD_UNKNOWN,
/**
* Record fields left unassigned.
*/
TYPE_ERROR_EXPRESSION_RECORD_FIELDS_UNASSIGNED,
/**
* Value is not of a record type.
*/
TYPE_ERROR_EXPRESSION_RECORD_NOT_RECORD_TYPE,
/**
* Nonexistent field in record projection.
*/
TYPE_ERROR_EXPRESSION_RECORD_PROJECTION_NO_SUCH_FIELD,
/**
* Target of record projection is not of a record type.
*/
TYPE_ERROR_EXPRESSION_RECORD_PROJECTION_NOT_RECORD,
/**
* Target of swizzle expression is not of a vector type.
*/
TYPE_ERROR_EXPRESSION_SWIZZLE_NOT_VECTOR,
/**
* Too many components in swizzle expression.
*/
TYPE_ERROR_EXPRESSION_SWIZZLE_TOO_MANY_COMPONENTS,
/**
* Unknown component(s) in swizzle expression.
*/
TYPE_ERROR_EXPRESSION_SWIZZLE_UNKNOWN_COMPONENT,
/**
* Returned value incompatible with declared return type.
*/
TYPE_ERROR_FUNCTION_BODY_RETURN_INCOMPATIBLE,
/**
* Record field is of non-manifest type.
*/
TYPE_ERROR_RECORD_FIELD_NOT_MANIFEST,
/**
* Shader value or output assignment of incorrect type.
*/
TYPE_ERROR_SHADER_ASSIGNMENT_BAD_TYPE,
/**
* Shader attribute is of a type that is not allowed by GLSL.
*/
TYPE_ERROR_SHADER_BAD_ATTRIBUTE_TYPE,
/**
* Shader depth output is not a scalar floating point.
*/
TYPE_ERROR_SHADER_DEPTH_NOT_FLOAT,
/**
* Shader discard expression is not boolean.
*/
TYPE_ERROR_SHADER_DISCARD_NOT_BOOLEAN,
/**
* Main shader output is not of an appropriate type.
*/
TYPE_ERROR_SHADER_OUTPUT_MAIN_BAD_TYPE,
/**
* Incorrect type of shader specified (vertex shader where fragment shader
* is required, etc).
*/
TYPE_ERROR_SHADER_WRONG_SHADER_TYPE,
/**
* Vertex and fragment shaders are incompatible.
*/
TYPE_ERROR_SHADERS_INCOMPATIBLE,
/**
* The type ascribed to a value does not match the type of the value.
*/
TYPE_ERROR_VALUE_ASCRIPTION_MISMATCH,
/**
* Non-value type used where a value type is required.
*/
TYPE_ERROR_VALUE_NON_VALUE_TYPE
}
private static final long serialVersionUID = 8186811920948826949L;
/**
* @return A type error
*/
public static TypeCheckerError shaderAssignmentBadType(
final TokenIdentifierLower name,
final TValueType out_type,
final TType type)
{
final StringBuilder m = new StringBuilder();
m.append("The shader output ");
m.append(name.getActual());
m.append(" is of type ");
m.append(out_type.getShowName());
m.append(" but an expression was given of type ");
m.append(type.getShowName());
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
name.getFile(),
name.getPosition(),
Code.TYPE_ERROR_SHADER_ASSIGNMENT_BAD_TYPE,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError shaderDiscardNotBoolean(
final TokenDiscard discard,
final TType type)
{
final StringBuilder m = new StringBuilder();
m.append("A discard expression must be of type ");
m.append(TBoolean.get().getShowName());
m.append(" but an expression was given of type ");
m.append(type.getShowName());
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
discard.getFile(),
discard.getPosition(),
Code.TYPE_ERROR_SHADER_DISCARD_NOT_BOOLEAN,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError shaderFragmentInputBadType(
final UASTRDShaderFragmentInput i)
{
return new TypeCheckerError(
i.getName().getFile(),
i.getName().getPosition(),
Code.TYPE_ERROR_SHADER_BAD_ATTRIBUTE_TYPE,
"An input of a fragment shader cannot be of a record type");
}
/**
* @return A type error
*/
public static TypeCheckerError shaderFragmentOutputBadType(
final UASTRDShaderFragmentOutput o)
{
return new TypeCheckerError(
o.getName().getFile(),
o.getName().getPosition(),
Code.TYPE_ERROR_SHADER_BAD_ATTRIBUTE_TYPE,
"An output of a fragment shader cannot be of a record type");
}
/**
* @return A type error
*/
public static TypeCheckerError shaderFragmentOutputDepthWrongType(
final UASTRDShaderFragmentOutputDepth d)
{
return new TypeCheckerError(
d.getName().getFile(),
d.getName().getPosition(),
Code.TYPE_ERROR_SHADER_DEPTH_NOT_FLOAT,
"The depth output of a fragment shader must be of type float");
}
/**
* @return A type error
*/
public static TypeCheckerError shaderNotFragment(
final UASTRShaderName name,
final TASTDShader shader)
{
final StringBuilder m = new StringBuilder();
m.append("The name ");
m.append(name.show());
m.append(" refers to a ");
shader
.shaderVisitableAccept(new TASTShaderVisitorType<Unit, UnreachableCodeException>() {
@Override public Unit moduleVisitFragmentShader(
final TASTDShaderFragment f)
{
throw new UnreachableCodeException();
}
@Override public Unit moduleVisitProgramShader(
final TASTDShaderProgram p)
{
m.append("program shader");
return Unit.unit();
}
@Override public Unit moduleVisitVertexShader(
final TASTDShaderVertex f)
{
m.append("vertex shader");
return Unit.unit();
}
});
m.append(" but a fragment shader is required");
final String r = m.toString();
assert r != null;
return new TypeCheckerError(name.getName().getFile(), name
.getName()
.getPosition(), Code.TYPE_ERROR_SHADER_WRONG_SHADER_TYPE, r);
}
/**
* @return A type error
*/
public static TypeCheckerError shaderNotVertex(
final UASTRShaderName name,
final TASTDShader shader)
{
final StringBuilder m = new StringBuilder();
m.append("The name ");
m.append(name.show());
m.append(" refers to a ");
shader
.shaderVisitableAccept(new TASTShaderVisitorType<Unit, UnreachableCodeException>() {
@Override public Unit moduleVisitFragmentShader(
final TASTDShaderFragment f)
{
m.append("fragment shader");
return Unit.unit();
}
@Override public Unit moduleVisitProgramShader(
final TASTDShaderProgram p)
{
m.append("program shader");
return Unit.unit();
}
@Override public Unit moduleVisitVertexShader(
final TASTDShaderVertex f)
{
throw new UnreachableCodeException();
}
});
m.append(" but a vertex shader is required");
final String r = m.toString();
assert r != null;
return new TypeCheckerError(name.getName().getFile(), name
.getName()
.getPosition(), Code.TYPE_ERROR_SHADER_WRONG_SHADER_TYPE, r);
}
/**
* @return A type error
*/
public static TypeCheckerError shadersNotCompatible(
final TokenIdentifierLower program,
final TASTDShaderFragment fs,
final Set<String> assigned,
final Map<String, TValueType> wrong_types)
{
final StringBuilder m = new StringBuilder();
m.append("The shaders for program ");
m.append(program.getActual());
m.append("are incompatible.\n");
m.append("Problems with each fragment shader input are indicated:\n");
for (final TASTDShaderFragmentInput f : fs.getInputs()) {
final TASTTermNameLocal fi_name = f.getName();
if (assigned.contains(fi_name.getCurrent()) == false) {
m.append(" ");
m.append(fi_name.getCurrent());
m.append(" : ");
m.append(f.getType().getShowName());
m.append(" has no matching vertex shader output\n");
} else {
assert wrong_types.containsKey(fi_name.getCurrent());
final TValueType type = wrong_types.get(fi_name.getCurrent());
m.append(" ");
m.append(fi_name.getCurrent());
m.append(" : ");
m.append(f.getType().getShowName());
m.append(" is incompatible with the vertex shader output of type ");
m.append(type.getShowName());
m.append("\n");
}
}
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
program.getFile(),
program.getPosition(),
Code.TYPE_ERROR_SHADERS_INCOMPATIBLE,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError shaderVertexInputBadType(
final UASTRDShaderVertexInput i)
{
return new TypeCheckerError(
i.getName().getFile(),
i.getName().getPosition(),
Code.TYPE_ERROR_SHADER_BAD_ATTRIBUTE_TYPE,
"An input of a vertex shader cannot be of a record type");
}
/**
* @return A type error
*/
public static TypeCheckerError shaderVertexMainOutputBadType(
final UASTRDShaderVertexOutput o,
final TType t)
{
final StringBuilder m = new StringBuilder();
m.append("The main output of a vertex shader must be of type ");
m.append(TVector4F.get().getShowName());
m.append(" but the given output is of type ");
m.append(t.getShowName());
final String r = m.toString();
assert r != null;
return new TypeCheckerError(o.getName().getFile(), o
.getName()
.getPosition(), Code.TYPE_ERROR_SHADER_OUTPUT_MAIN_BAD_TYPE, r);
}
/**
* @return A type error
*/
public static TypeCheckerError shaderVertexOutputBadType(
final UASTRDShaderVertexOutput o)
{
return new TypeCheckerError(
o.getName().getFile(),
o.getName().getPosition(),
Code.TYPE_ERROR_SHADER_BAD_ATTRIBUTE_TYPE,
"An output of a vertex shader cannot be of a record type");
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionApplicationBadTypes(
final UASTRTermName name,
final List<TFunctionArgument> expected,
final List<TASTExpression> got)
{
final StringBuilder m = new StringBuilder();
m.append("Incorrect argument types for application of function ");
m.append(name.getName().getActual());
m.append("\n");
m.append("Expected: ");
m.append(TType.formatFunctionArguments(expected));
m.append("\n");
m.append("Got: ");
m.append(TType.formatTypeExpressionList(got));
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
name.getFile(),
name.getPosition(),
Code.TYPE_ERROR_EXPRESSION_APPLICATION_BAD_TYPES,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionApplicationNotFunctionType(
final UASTRTermName name,
final TType t)
{
final StringBuilder m = new StringBuilder();
m.append("Cannot apply the term ");
m.append(name.getName().getActual());
m.append(" to the given arguments; ");
m.append(name.getName().getActual());
m.append(" is of the non-function type ");
m.append(t.getShowName());
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
name.getFile(),
name.getPosition(),
Code.TYPE_ERROR_EXPRESSION_APPLICATION_NOT_FUNCTION_TYPE,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionNewNoAppropriateConstructors(
final UASTRTypeName name,
final List<TASTExpression> arguments,
final List<TConstructor> constructors)
{
final StringBuilder m = new StringBuilder();
m.append("No appropriate constructor for type ");
m.append(name.getName().getActual());
m.append(" for arguments ");
m.append(TType.formatTypeExpressionList(arguments));
m.append("\n");
m.append("Available constructors are:\n");
for (final TConstructor c : constructors) {
m.append(" ");
m.append(TType.formatTypeList(c.getParameters()));
m.append(" → ");
m.append(name.getName().getActual());
m.append("\n");
}
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
name.getName().getFile(),
name.getName().getPosition(),
Code.TYPE_ERROR_EXPRESSION_NEW_NO_APPROPRIATE_CONSTRUCTORS,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionNewNotConstructable(
final UASTRTypeName name)
{
final TokenIdentifierLower n_name = name.getName();
final StringBuilder m = new StringBuilder();
m.append("The type ");
m.append(n_name);
m.append(" is not constructable");
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
n_name.getFile(),
n_name.getPosition(),
Code.TYPE_ERROR_EXPRESSION_NEW_TYPE_NOT_CONSTRUCTABLE,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionRecordBadFieldType(
final TokenIdentifierLower field_name,
final TManifestType expected_type,
final TType got_type)
{
final StringBuilder m = new StringBuilder();
m.append("The type of field ");
m.append(field_name.getActual());
m.append(" is ");
m.append(expected_type.getShowName());
m.append(" but an expression was given of type ");
m.append(got_type.getShowName());
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
field_name.getFile(),
field_name.getPosition(),
Code.TYPE_ERROR_EXPRESSION_RECORD_FIELD_BAD_TYPE,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionRecordFieldsUnassigned(
final UASTRTypeName name,
final List<TRecordField> unassigned)
{
final TokenIdentifierLower n_name = name.getName();
final StringBuilder m = new StringBuilder();
m
.append("The record expression leaves the following fields unassigned:\n");
for (final TRecordField u : unassigned) {
m.append(" ");
m.append(u.getName());
m.append(" : ");
m.append(u.getType().getShowName());
m.append("\n");
}
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
n_name.getFile(),
n_name.getPosition(),
Code.TYPE_ERROR_EXPRESSION_RECORD_FIELDS_UNASSIGNED,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionRecordNotRecordType(
final UASTRTypeName name)
{
final TokenIdentifierLower n_name = name.getName();
final StringBuilder m = new StringBuilder();
m.append("The type ");
m.append(n_name.getActual());
m
.append(" is not a record type and therefore values cannot be constructed with record expressions");
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
n_name.getFile(),
n_name.getPosition(),
Code.TYPE_ERROR_EXPRESSION_RECORD_NOT_RECORD_TYPE,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionRecordProjectionNoSuchField(
final TRecord tr,
final TokenIdentifierLower field)
{
final StringBuilder m = new StringBuilder();
m.append("The type ");
m.append(tr.getShowName());
m.append(" does not have a field named ");
m.append(field.getActual());
m.append("\n");
m.append("Available fields are:\n");
for (final TRecordField f : tr.getFields()) {
m.append(" ");
m.append(f.getName());
m.append(" : ");
m.append(f.getType().getShowName());
m.append("\n");
}
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
field.getFile(),
field.getPosition(),
Code.TYPE_ERROR_EXPRESSION_RECORD_PROJECTION_NO_SUCH_FIELD,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionRecordProjectionNotRecord(
final TASTExpression body,
final TokenIdentifierLower field)
{
final StringBuilder m = new StringBuilder();
m.append("The type of the given expression is ");
m.append(body.getType().getShowName());
m
.append(", which is not a record type and therefore the expression cannot be the body of a record projection");
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
field.getFile(),
field.getPosition(),
Code.TYPE_ERROR_EXPRESSION_RECORD_PROJECTION_NOT_RECORD,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionRecordUnknownField(
final TokenIdentifierLower field_name,
final TRecord record)
{
final StringBuilder m = new StringBuilder();
m.append("The type ");
m.append(record.getShowName());
m.append(" does not contain a field named ");
m.append(field_name.getActual());
m.append("\n");
m.append("Available fields are:\n");
for (final TRecordField f : record.getFields()) {
m.append(" ");
m.append(f.getName());
m.append(" : ");
m.append(f.getType().getShowName());
m.append("\n");
}
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
field_name.getFile(),
field_name.getPosition(),
Code.TYPE_ERROR_EXPRESSION_RECORD_FIELD_UNKNOWN,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionSwizzleNotVector(
final TASTExpression body,
final TokenIdentifierLower first_field)
{
final StringBuilder m = new StringBuilder();
m
.append("Only expressions of vector types can be swizzled. The given expression is of type ");
m.append(body.getType().getShowName());
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
first_field.getFile(),
first_field.getPosition(),
Code.TYPE_ERROR_EXPRESSION_SWIZZLE_NOT_VECTOR,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionSwizzleTooManyFields(
final TokenIdentifierLower first,
final int size)
{
final StringBuilder m = new StringBuilder();
m.append("Swizzle expressions can contain at most four components (");
m.append(size);
m.append(" were given)");
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
first.getFile(),
first.getPosition(),
Code.TYPE_ERROR_EXPRESSION_SWIZZLE_TOO_MANY_COMPONENTS,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termExpressionSwizzleUnknownField(
final TVectorType tv,
final TokenIdentifierLower f)
{
final StringBuilder m = new StringBuilder();
m.append("The type ");
m.append(tv.getShowName());
m.append(" does not have a component named ");
m.append(f.getActual());
m.append("\n");
m.append("Available components are: ");
for (final String name : tv.getComponentNames()) {
m.append(name);
m.append(" ");
}
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
f.getFile(),
f.getPosition(),
Code.TYPE_ERROR_EXPRESSION_SWIZZLE_UNKNOWN_COMPONENT,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termFunctionBodyReturnMismatch(
final TokenIdentifierLower name,
final TType expected,
final TType got)
{
final StringBuilder m = new StringBuilder();
m.append("The body of function ");
m.append(name.getActual());
m.append(" is expected to be of type ");
m.append(expected.getShowName());
m.append(" but an expression was given of type ");
m.append(got.getShowName());
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
name.getFile(),
name.getPosition(),
Code.TYPE_ERROR_FUNCTION_BODY_RETURN_INCOMPATIBLE,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termValueExpressionAscriptionMismatch(
final TokenIdentifierLower name,
final TType expected,
final TType got)
{
final StringBuilder m = new StringBuilder();
m.append("The ascription on value ");
m.append(name.getActual());
m.append(" requires that the type must be ");
m.append(expected.getShowName());
m.append(" but an expression was given of type ");
m.append(got.getShowName());
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
name.getFile(),
name.getPosition(),
Code.TYPE_ERROR_VALUE_ASCRIPTION_MISMATCH,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError termValueNotValueType(
final TokenIdentifierLower name,
final TType type)
{
final StringBuilder m = new StringBuilder();
m.append("The body of value ");
m.append(name.getActual());
m.append(" is of a non-value type ");
m.append(type.getShowName());
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
name.getFile(),
name.getPosition(),
Code.TYPE_ERROR_VALUE_NON_VALUE_TYPE,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError typeConditionNotBoolean(
final TokenIf token,
final TASTExpression condition)
{
final StringBuilder m = new StringBuilder();
m
.append("The condition expression of a condition must be of type boolean, but an expression was given here of type ");
m.append(condition.getType().getShowName());
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
token.getFile(),
token.getPosition(),
Code.TYPE_ERROR_EXPRESSION_CONDITION_NOT_BOOLEAN,
r);
}
/**
* @return A type error
*/
public static TypeCheckerError typeRecordFieldNotManifest(
final UASTRTypeName type_name,
final TType ty)
{
final StringBuilder m = new StringBuilder();
m.append("The (non-manifest) type ");
m.append(ty.getShowName());
m.append(" cannot be used as the type of a record field");
return type_name
.typeNameVisitableAccept(new UASTRTypeNameVisitorType<TypeCheckerError, UnreachableCodeException>() {
@SuppressWarnings("synthetic-access") @Override public
TypeCheckerError
typeNameVisitBuiltIn(
final UASTRTypeNameBuiltIn t)
{
final TokenIdentifierLower name = t.getName();
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
name.getFile(),
name.getPosition(),
Code.TYPE_ERROR_RECORD_FIELD_NOT_MANIFEST,
r);
}
@SuppressWarnings("synthetic-access") @Override public
TypeCheckerError
typeNameVisitGlobal(
final UASTRTypeNameGlobal t)
{
final TokenIdentifierLower name = t.getName();
final String r = m.toString();
assert r != null;
return new TypeCheckerError(
name.getFile(),
name.getPosition(),
Code.TYPE_ERROR_RECORD_FIELD_NOT_MANIFEST,
r);
}
});
}
private final Code code;
private TypeCheckerError(
final File file,
final Position position,
final Code in_code,
final String message)
{
super(message, file, position);
this.code = in_code;
}
@Override public String getCategory()
{
return "type-checker";
}
/**
* @return The error code.
*/
public Code getCode()
{
return this.code;
}
}
| Fix NPE when printing error message. Fixes [49afffdc5f].
| io7m-jparasol-compiler-core/src/main/java/com/io7m/jparasol/typed/TypeCheckerError.java | Fix NPE when printing error message. Fixes [49afffdc5f]. | <ide><path>o7m-jparasol-compiler-core/src/main/java/com/io7m/jparasol/typed/TypeCheckerError.java
<ide> m.append(" : ");
<ide> m.append(f.getType().getShowName());
<ide> m.append(" has no matching vertex shader output\n");
<del> } else {
<del> assert wrong_types.containsKey(fi_name.getCurrent());
<add> } else if (wrong_types.containsKey(fi_name.getCurrent())) {
<ide> final TValueType type = wrong_types.get(fi_name.getCurrent());
<add> assert type != null;
<ide> m.append(" ");
<ide> m.append(fi_name.getCurrent());
<ide> m.append(" : "); |
|
Java | apache-2.0 | 1886368fedc1eb00220cc8658fdd6c197891d850 | 0 | d-ellebasi/ietfsched,d-ellebasi/ietfsched,d-ellebasi/ietfsched | /*
* Copyright 2011 Google Inc.
* Copyright 2011 Isabelle Dalmasso.
*
* 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.ietf.ietfsched.service;
//import org.ietf.ietfsched.R;
import org.ietf.ietfsched.io.LocalExecutor;
import org.ietf.ietfsched.io.RemoteExecutor;
import org.ietf.ietfsched.provider.ScheduleProvider;
//import org.ietf.ietfsched.provider.ScheduleContract;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HttpContext;
import android.app.IntentService;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
//import android.database.Cursor;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.text.format.DateUtils;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.TimeZone;
//import org.apache.http.client.HttpClient;
/**
* Background {@link Service} that synchronizes data living in
* {@link ScheduleProvider}. Reads data from both local {@link Resources} and
* from remote sources, such as a spreadsheet.
*/
public class SyncService extends IntentService {
private static final String TAG = "SyncService";
private static final boolean debbug = false;
public static final String EXTRA_STATUS_RECEIVER = "org.ietf.ietfsched.extra.STATUS_RECEIVER";
public static final int STATUS_RUNNING = 0x1;
public static final int STATUS_ERROR = 0x2;
public static final int STATUS_FINISHED = 0x3;
private static final int SECOND_IN_MILLIS = (int) DateUtils.SECOND_IN_MILLIS;
/** Root worksheet feed for online data source */
// TODO: insert your sessions/speakers/vendors spreadsheet doc URL here.
// private static final String WORKSHEETS_URL = "INSERT_SPREADSHEET_URL_HERE";
private static final String BASE_URL = "https://datatracker.ietf.org/meeting/102/";
private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
private static final String ENCODING_GZIP = "gzip";
private static final int VERSION_NONE = 0;
private static final int VERSION_CURRENT = 47;
private LocalExecutor mLocalExecutor;
private RemoteExecutor mRemoteExecutor;
public SyncService() {
super(TAG);
}
@Override
public void onCreate() {
super.onCreate();
final ContentResolver resolver = getContentResolver();
mLocalExecutor = new LocalExecutor(getResources(), resolver);
final HttpClient httpClient = getHttpClient(this);
mRemoteExecutor = new RemoteExecutor(httpClient);
if (debbug) {
Log.d(TAG, "SyncService OnCreate" + this.hashCode());
String[] tz = TimeZone.getAvailableIDs();
for (String id : tz) {
Log.d(TAG, "Available timezone ids: " + id);
}
}
}
@Override
protected void onHandleIntent(Intent intent) {
final ResultReceiver receiver = intent.getParcelableExtra(EXTRA_STATUS_RECEIVER);
if (debbug) Log.d(TAG, "Receiver is = " + receiver);
if (receiver != null) receiver.send(STATUS_RUNNING, Bundle.EMPTY);
final Context context = this;
final SharedPreferences prefs = getSharedPreferences(Prefs.IETFSCHED_SYNC, Context.MODE_PRIVATE);
final int localVersion = prefs.getInt(Prefs.LOCAL_VERSION, VERSION_NONE);
// final int lastLength = prefs.getInt(Prefs.LAST_LENGTH, VERSION_NONE);
final String lastEtag = prefs.getString(Prefs.LAST_ETAG, "");
// final long startLocal = System.currentTimeMillis();
//boolean localParse = localVersion < VERSION_CURRENT;
boolean localParse = false;
Log.d(TAG, "found localVersion=" + localVersion + " and VERSION_CURRENT=" + VERSION_CURRENT);
boolean remoteParse = true;
// int remoteLength = -1;
String remoteEtag = "";
try {
String htmlURL = BASE_URL + "agenda.csv";
if (debbug) Log.d(TAG, "HEAD " + htmlURL);
remoteEtag = mRemoteExecutor.executeHead(htmlURL);
if (debbug) Log.d(TAG, "HEAD " + htmlURL + " " + remoteEtag);
if (remoteEtag == null) {
Log.d(TAG, "Error connection, cannot retrieve any information from" + htmlURL);
remoteParse = false;
}
else {
remoteParse = !remoteEtag.equals(lastEtag);
}
}
catch (Exception e) {
remoteParse = false;
e.printStackTrace();
}
// HACK FOR TESTS PURPOSES. TO REMOVE
// Log.w(TAG, "For tests purposes, only the local parsing is activated");
// remoteParse = false;
// localParse = true;
// HACK FIN.
if (!remoteParse && !localParse) {
Log.d(TAG, "Already synchronized");
if (receiver != null) receiver.send(STATUS_FINISHED, Bundle.EMPTY);
return;
}
if (remoteParse) {
String csvURL = BASE_URL + "agenda.csv";
try {
if (debbug) Log.d(TAG, csvURL);
InputStream agenda = mRemoteExecutor.executeGet(csvURL);
mLocalExecutor.execute(agenda);
prefs.edit().putString(Prefs.LAST_ETAG, remoteEtag).commit();
prefs.edit().putInt(Prefs.LOCAL_VERSION, VERSION_CURRENT).commit();
localParse = false;
Log.d(TAG, "remote sync finished");
if (receiver != null) receiver.send(STATUS_FINISHED, Bundle.EMPTY);
}
catch (Exception e) {
Log.e(TAG, "Error HTTP request " + csvURL , e);
if (!localParse) {
final Bundle bundle = new Bundle();
bundle.putString(Intent.EXTRA_TEXT, "Connection error. No updates.");
if (receiver != null) {
receiver.send(STATUS_ERROR, bundle);
}
}
}
}
if (localParse) {
try {
mLocalExecutor.execute(context, "agenda-83.csv");
Log.d(TAG, "local sync finished");
prefs.edit().putInt(Prefs.LOCAL_VERSION, VERSION_CURRENT).commit();
if (receiver != null) receiver.send(STATUS_FINISHED, Bundle.EMPTY);
}
catch (Exception e) {
e.printStackTrace();
final Bundle bundle = new Bundle();
bundle.putString(Intent.EXTRA_TEXT, e.toString());
if (receiver != null) {
receiver.send(STATUS_ERROR, bundle);
}
}
}
}
/**
* Generate and return a {@link HttpClient} configured for general use,
* including setting an application-specific user-agent string.
*/
public static HttpClient getHttpClient(Context context) {
final HttpParams params = new BasicHttpParams();
// Use generous timeouts for slow mobile networks
HttpConnectionParams.setConnectionTimeout(params, 20 * SECOND_IN_MILLIS);
HttpConnectionParams.setSoTimeout(params, 20 * SECOND_IN_MILLIS);
HttpConnectionParams.setSocketBufferSize(params, 8192);
HttpProtocolParams.setUserAgent(params, buildUserAgent(context));
final DefaultHttpClient client = new DefaultHttpClient(params);
client.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(HttpRequest request, HttpContext context) {
// Add header to accept gzip content
if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
}
/* Log.d(TAG, "Headers for request");
Header[] headers = request.getAllHeaders();
for (Header h : headers) {
Log.d(TAG, h.getName() + " " + h.getValue());
}
*/
}
});
client.addResponseInterceptor(new HttpResponseInterceptor() {
public void process(HttpResponse response, HttpContext context) {
// Inflate any responses compressed with gzip
final HttpEntity entity = response.getEntity();
final Header encoding = entity != null ? entity.getContentEncoding() : null;
if (encoding != null) {
for (HeaderElement element : encoding.getElements()) {
if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
response.setEntity(new InflatingEntity(response.getEntity()));
break;
}
}
}
}
});
return client;
}
/**
* Build and return a user-agent string that can identify this application
* to remote servers. Contains the package name and version code.
*/
private static String buildUserAgent(Context context) {
try {
final PackageManager manager = context.getPackageManager();
final PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
// Some APIs require "(gzip)" in the user-agent string.
return info.packageName + "/" + info.versionName
+ " (" + info.versionCode + ") (gzip)";
}
catch (NameNotFoundException e) {
return null;
}
}
/**
* Simple {@link HttpEntityWrapper} that inflates the wrapped
* {@link HttpEntity} by passing it through {@link GZIPInputStream}.
*/
private static class InflatingEntity extends HttpEntityWrapper {
public InflatingEntity(HttpEntity wrapped) {
super(wrapped);
}
@Override
public InputStream getContent() throws IOException {
return new GZIPInputStream(wrappedEntity.getContent());
}
@Override
public long getContentLength() {
return -1;
}
}
private interface Prefs {
String LAST_ETAG = "local_etag";
String IETFSCHED_SYNC = "ietfsched_sync";
String LOCAL_VERSION = "local_version";
String LAST_LENGTH = "last_length";
String LAST_SYNC_TIME = "last_stime";
}
}
| app/src/main/java/org/ietf/ietfsched/service/SyncService.java | /*
* Copyright 2011 Google Inc.
* Copyright 2011 Isabelle Dalmasso.
*
* 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.ietf.ietfsched.service;
//import org.ietf.ietfsched.R;
import org.ietf.ietfsched.io.LocalExecutor;
import org.ietf.ietfsched.io.RemoteExecutor;
import org.ietf.ietfsched.provider.ScheduleProvider;
//import org.ietf.ietfsched.provider.ScheduleContract;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HttpContext;
import android.app.IntentService;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
//import android.database.Cursor;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.text.format.DateUtils;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.TimeZone;
//import org.apache.http.client.HttpClient;
/**
* Background {@link Service} that synchronizes data living in
* {@link ScheduleProvider}. Reads data from both local {@link Resources} and
* from remote sources, such as a spreadsheet.
*/
public class SyncService extends IntentService {
private static final String TAG = "SyncService";
private static final boolean debbug = false;
public static final String EXTRA_STATUS_RECEIVER = "org.ietf.ietfsched.extra.STATUS_RECEIVER";
public static final int STATUS_RUNNING = 0x1;
public static final int STATUS_ERROR = 0x2;
public static final int STATUS_FINISHED = 0x3;
private static final int SECOND_IN_MILLIS = (int) DateUtils.SECOND_IN_MILLIS;
/** Root worksheet feed for online data source */
// TODO: insert your sessions/speakers/vendors spreadsheet doc URL here.
// private static final String WORKSHEETS_URL = "INSERT_SPREADSHEET_URL_HERE";
private static final String BASE_URL = "https://datatracker.ietf.org/meeting/101/";
private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
private static final String ENCODING_GZIP = "gzip";
private static final int VERSION_NONE = 0;
private static final int VERSION_CURRENT = 47;
private LocalExecutor mLocalExecutor;
private RemoteExecutor mRemoteExecutor;
public SyncService() {
super(TAG);
}
@Override
public void onCreate() {
super.onCreate();
final ContentResolver resolver = getContentResolver();
mLocalExecutor = new LocalExecutor(getResources(), resolver);
final HttpClient httpClient = getHttpClient(this);
mRemoteExecutor = new RemoteExecutor(httpClient);
if (debbug) {
Log.d(TAG, "SyncService OnCreate" + this.hashCode());
String[] tz = TimeZone.getAvailableIDs();
for (String id : tz) {
Log.d(TAG, "Available timezone ids: " + id);
}
}
}
@Override
protected void onHandleIntent(Intent intent) {
final ResultReceiver receiver = intent.getParcelableExtra(EXTRA_STATUS_RECEIVER);
if (debbug) Log.d(TAG, "Receiver is = " + receiver);
if (receiver != null) receiver.send(STATUS_RUNNING, Bundle.EMPTY);
final Context context = this;
final SharedPreferences prefs = getSharedPreferences(Prefs.IETFSCHED_SYNC, Context.MODE_PRIVATE);
final int localVersion = prefs.getInt(Prefs.LOCAL_VERSION, VERSION_NONE);
// final int lastLength = prefs.getInt(Prefs.LAST_LENGTH, VERSION_NONE);
final String lastEtag = prefs.getString(Prefs.LAST_ETAG, "");
// final long startLocal = System.currentTimeMillis();
//boolean localParse = localVersion < VERSION_CURRENT;
boolean localParse = false;
Log.d(TAG, "found localVersion=" + localVersion + " and VERSION_CURRENT=" + VERSION_CURRENT);
boolean remoteParse = true;
// int remoteLength = -1;
String remoteEtag = "";
try {
String htmlURL = BASE_URL + "agenda.csv";
if (debbug) Log.d(TAG, "HEAD " + htmlURL);
remoteEtag = mRemoteExecutor.executeHead(htmlURL);
if (debbug) Log.d(TAG, "HEAD " + htmlURL + " " + remoteEtag);
if (remoteEtag == null) {
Log.d(TAG, "Error connection, cannot retrieve any information from" + htmlURL);
remoteParse = false;
}
else {
remoteParse = !remoteEtag.equals(lastEtag);
}
}
catch (Exception e) {
remoteParse = false;
e.printStackTrace();
}
// HACK FOR TESTS PURPOSES. TO REMOVE
// Log.w(TAG, "For tests purposes, only the local parsing is activated");
// remoteParse = false;
// localParse = true;
// HACK FIN.
if (!remoteParse && !localParse) {
Log.d(TAG, "Already synchronized");
if (receiver != null) receiver.send(STATUS_FINISHED, Bundle.EMPTY);
return;
}
if (remoteParse) {
String csvURL = BASE_URL + "agenda.csv";
try {
if (debbug) Log.d(TAG, csvURL);
InputStream agenda = mRemoteExecutor.executeGet(csvURL);
mLocalExecutor.execute(agenda);
prefs.edit().putString(Prefs.LAST_ETAG, remoteEtag).commit();
prefs.edit().putInt(Prefs.LOCAL_VERSION, VERSION_CURRENT).commit();
localParse = false;
Log.d(TAG, "remote sync finished");
if (receiver != null) receiver.send(STATUS_FINISHED, Bundle.EMPTY);
}
catch (Exception e) {
Log.e(TAG, "Error HTTP request " + csvURL , e);
if (!localParse) {
final Bundle bundle = new Bundle();
bundle.putString(Intent.EXTRA_TEXT, "Connection error. No updates.");
if (receiver != null) {
receiver.send(STATUS_ERROR, bundle);
}
}
}
}
if (localParse) {
try {
mLocalExecutor.execute(context, "agenda-83.csv");
Log.d(TAG, "local sync finished");
prefs.edit().putInt(Prefs.LOCAL_VERSION, VERSION_CURRENT).commit();
if (receiver != null) receiver.send(STATUS_FINISHED, Bundle.EMPTY);
}
catch (Exception e) {
e.printStackTrace();
final Bundle bundle = new Bundle();
bundle.putString(Intent.EXTRA_TEXT, e.toString());
if (receiver != null) {
receiver.send(STATUS_ERROR, bundle);
}
}
}
}
/**
* Generate and return a {@link HttpClient} configured for general use,
* including setting an application-specific user-agent string.
*/
public static HttpClient getHttpClient(Context context) {
final HttpParams params = new BasicHttpParams();
// Use generous timeouts for slow mobile networks
HttpConnectionParams.setConnectionTimeout(params, 20 * SECOND_IN_MILLIS);
HttpConnectionParams.setSoTimeout(params, 20 * SECOND_IN_MILLIS);
HttpConnectionParams.setSocketBufferSize(params, 8192);
HttpProtocolParams.setUserAgent(params, buildUserAgent(context));
final DefaultHttpClient client = new DefaultHttpClient(params);
client.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(HttpRequest request, HttpContext context) {
// Add header to accept gzip content
if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
}
/* Log.d(TAG, "Headers for request");
Header[] headers = request.getAllHeaders();
for (Header h : headers) {
Log.d(TAG, h.getName() + " " + h.getValue());
}
*/
}
});
client.addResponseInterceptor(new HttpResponseInterceptor() {
public void process(HttpResponse response, HttpContext context) {
// Inflate any responses compressed with gzip
final HttpEntity entity = response.getEntity();
final Header encoding = entity != null ? entity.getContentEncoding() : null;
if (encoding != null) {
for (HeaderElement element : encoding.getElements()) {
if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
response.setEntity(new InflatingEntity(response.getEntity()));
break;
}
}
}
}
});
return client;
}
/**
* Build and return a user-agent string that can identify this application
* to remote servers. Contains the package name and version code.
*/
private static String buildUserAgent(Context context) {
try {
final PackageManager manager = context.getPackageManager();
final PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
// Some APIs require "(gzip)" in the user-agent string.
return info.packageName + "/" + info.versionName
+ " (" + info.versionCode + ") (gzip)";
}
catch (NameNotFoundException e) {
return null;
}
}
/**
* Simple {@link HttpEntityWrapper} that inflates the wrapped
* {@link HttpEntity} by passing it through {@link GZIPInputStream}.
*/
private static class InflatingEntity extends HttpEntityWrapper {
public InflatingEntity(HttpEntity wrapped) {
super(wrapped);
}
@Override
public InputStream getContent() throws IOException {
return new GZIPInputStream(wrappedEntity.getContent());
}
@Override
public long getContentLength() {
return -1;
}
}
private interface Prefs {
String LAST_ETAG = "local_etag";
String IETFSCHED_SYNC = "ietfsched_sync";
String LOCAL_VERSION = "local_version";
String LAST_LENGTH = "last_length";
String LAST_SYNC_TIME = "last_stime";
}
}
| Update for IETF102 - Montreal.
July 14-20.
Set the agenda csv location to 102.
| app/src/main/java/org/ietf/ietfsched/service/SyncService.java | Update for IETF102 - Montreal. July 14-20. | <ide><path>pp/src/main/java/org/ietf/ietfsched/service/SyncService.java
<ide> /** Root worksheet feed for online data source */
<ide> // TODO: insert your sessions/speakers/vendors spreadsheet doc URL here.
<ide> // private static final String WORKSHEETS_URL = "INSERT_SPREADSHEET_URL_HERE";
<del> private static final String BASE_URL = "https://datatracker.ietf.org/meeting/101/";
<add> private static final String BASE_URL = "https://datatracker.ietf.org/meeting/102/";
<ide> private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
<ide> private static final String ENCODING_GZIP = "gzip";
<ide> |
|
JavaScript | mit | 4632a726ac1f7fc4b2eaed5059a094eb606593cc | 0 | HPI-Hackathon/find-my-car,HPI-Hackathon/find-my-car | define(["underscore", "jquery", "app"], function(_, $, app) {
return function (averageCartype) {
var public = {};
var private = {};
private.createObject = function (averageCartype) {
var queryObject = {
c: [],
ecol: [],
sc: null,
p: null,
ll: null
};
// Cartypes
for (var carclass in averageCartype.carclass)
queryObject.c.push(carclass);
// Colors
for (var color in averageCartype.colors)
queryObject.ecol.push(color);
// Seats
var seatsRange = averageCartype.min_seats + ":" + averageCartype.max_seats;
queryObject.sc = seatsRange;
// Price
var priceRange = averageCartype.min_price + ":" + averageCartype.max_price;
queryObject.p = priceRange;
// Location
queryObject.ll = app.userProfile.point;
return queryObject;
};
private.createURL = function (queryObject) {
var url = "http://m.mobile.de/svc/s/?";
var params = $.param(queryObject);
url = url.concat(params);
return url;
};
public.getResults = function (averageCartype) {
var queryObject = private.createObject(averageCartype);
var url = private.createURL(queryObject);
var results = $.getJSON(url, function(json) {
return json;
});
return results;
};
return public;
};
});
| javascripts/service/car_ads_service.js | define(["underscore", "jquery"], function(_, $) {
return function (averageCartype) {
var public = {};
var private = {};
private.createObject = function (averageCartype) {
var queryObject = {
c: [],
sc: null,
p: null,
ecol: []
};
for (var carclass in averageCartype.carclass)
queryObject.c.push(carclass);
for (var color in averageCartype.colors)
queryObject.ecol.push(color);
var seatsRange = averageCartype.min_seats + ":" + averageCartype.max_seats;
queryObject.sc = seatsRange;
var priceRange = averageCartype.min_price + ":" + averageCartype.max_price;
queryObject.p = priceRange;
return queryObject;
};
private.createURL = function (queryObject) {
var url = "http://m.mobile.de/svc/s/?";
var params = $.param(queryObject);
url = url.concat(params);
return url;
};
public.getResults = function (averageCartype) {
var queryObject = private.createObject(averageCartype);
var url = private.createURL(queryObject);
var results = $.getJSON(url, function(json) {
return json;
});
return results;
};
return public;
};
});
| Add params for location based search
| javascripts/service/car_ads_service.js | Add params for location based search | <ide><path>avascripts/service/car_ads_service.js
<del>define(["underscore", "jquery"], function(_, $) {
<add>define(["underscore", "jquery", "app"], function(_, $, app) {
<ide> return function (averageCartype) {
<ide>
<ide> var public = {};
<ide> private.createObject = function (averageCartype) {
<ide> var queryObject = {
<ide> c: [],
<add> ecol: [],
<ide> sc: null,
<ide> p: null,
<del> ecol: []
<add> ll: null
<ide> };
<ide>
<add> // Cartypes
<ide> for (var carclass in averageCartype.carclass)
<ide> queryObject.c.push(carclass);
<ide>
<add> // Colors
<ide> for (var color in averageCartype.colors)
<ide> queryObject.ecol.push(color);
<ide>
<add> // Seats
<ide> var seatsRange = averageCartype.min_seats + ":" + averageCartype.max_seats;
<ide> queryObject.sc = seatsRange;
<ide>
<add> // Price
<ide> var priceRange = averageCartype.min_price + ":" + averageCartype.max_price;
<ide> queryObject.p = priceRange;
<add>
<add> // Location
<add> queryObject.ll = app.userProfile.point;
<ide>
<ide> return queryObject;
<ide> }; |
|
JavaScript | apache-2.0 | d1abfcda238c6c9c8e0e5b27be8e96b216682c26 | 0 | otnt/SimpleUber,otnt/SimpleUber | // Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
'use strict';
var Cluster = require('./cluster.js');
var logger = require('winston');
var parseArgs = require('./parse_args.js');
var express = require('express');
var LEADER_KEY = 'LEADER';
function App(ringpop) {
this.ringpop = ringpop;
this.currentLeader = null;
this.isLeader = false;
}
App.prototype.chooseLeader = function chooseLeader() {
var newLeader = this.ringpop.lookup(LEADER_KEY);
if (!this.currentLeader || newLeader !== this.currentLeader) {
logger.info(this.ringpop.whoami() + ' says new leader is ' + newLeader);
// This app was not a leader, but now is.
if (!this.isLeader && newLeader === this.ringpop.whoami()) {
// Subscribe
this.isLeader = true;
}
// This app was a leader, but now is not.
if (this.isLeader && newLeader !== this.ringpop.whoami()) {
// Unsubscribe
this.isLeader = false;
}
this.currentLeader = newLeader;
}
};
if (require.main === module) {
var cluster = new Cluster(parseArgs());
// Launch cluster. If successful, get individual Ringpop instances (nodes)
// back.
cluster.launch(function onLaunch(err, ringpops) {
if (err) {
logger.error('error:' + err.message);
process.exit(1);
}
// Create an App wrapper around each Ringpop instance. Choose a
// leader upon instantiation and when a ring change is detected.
ringpops.forEach(function each(ringpop) {
var app = new App(ringpop);
app.chooseLeader();
ringpop.on('ringChanged', app.chooseLeader.bind(app));
});
// These HTTP servers will act as the front-end
// for the Ringpop cluster.
ringpops.forEach(function each(ringpop, index) {
var http = express();
// Define a single HTTP endpoint that 'handles' or forwards
http.get('/objects/:id', function onReq(req, res) {
console.log("get req " + req.params);
var key = req.params.id;
if (ringpop.handleOrProxy(key, req, res)) {
console.log('Ringpop ' + ringpop.whoami() + ' handled ' + key);
res.end();
} else {
console.log('Ringpop ' + ringpop.whoami() +
' forwarded ' + key);
}
});
var port = cluster.basePort * 2 + index; // HTTP will need its own port
http.listen(port, function onListen() {
console.log('HTTP is listening on ' + port);
});
});
});
}
| uber/leader_election.js | // Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
'use strict';
var Cluster = require('./cluster.js');
var logger = require('winston');
var parseArgs = require('./parse_args.js');
var express = require('express');
var LEADER_KEY = 'LEADER';
function App(ringpop) {
this.ringpop = ringpop;
this.currentLeader = null;
this.isLeader = false;
}
App.prototype.chooseLeader = function chooseLeader() {
var newLeader = this.ringpop.lookup(LEADER_KEY);
if (!this.currentLeader || newLeader !== this.currentLeader) {
logger.info(this.ringpop.whoami() + ' says new leader is ' + newLeader);
// This app was not a leader, but now is.
if (!this.isLeader && newLeader === this.ringpop.whoami()) {
// Subscribe
this.isLeader = true;
}
// This app was a leader, but now is not.
if (this.isLeader && newLeader !== this.ringpop.whoami()) {
// Unsubscribe
this.isLeader = false;
}
this.currentLeader = newLeader;
}
};
if (require.main === module) {
var cluster = new Cluster(parseArgs());
// Launch cluster. If successful, get individual Ringpop instances (nodes)
// back.
cluster.launch(function onLaunch(err, ringpops) {
if (err) {
logger.error('error:' + err.message);
process.exit(1);
}
// Create an App wrapper around each Ringpop instance. Choose a
// leader upon instantiation and when a ring change is detected.
ringpops.forEach(function each(ringpop) {
var app = new App(ringpop);
app.chooseLeader();
ringpop.on('ringChanged', app.chooseLeader.bind(app));
});
// These HTTP servers will act as the front-end
// for the Ringpop cluster.
ringpops.forEach(function each(ringpop, index) {
var http = express();
// Define a single HTTP endpoint that 'handles' or forwards
http.get('/objects/:id', function onReq(req, res) {
var key = req.params.id;
if (ringpop.handleOrProxy(key, req, res)) {
console.log('Ringpop ' + ringpop.whoami() + ' handled ' + key);
res.end();
} else {
console.log('Ringpop ' + ringpop.whoami() +
' forwarded ' + key);
}
});
var port = cluster.basePort * 2 + index; // HTTP will need its own port
http.listen(port, function onListen() {
console.log('HTTP is listening on ' + port);
});
});
});
}
| --amend
| uber/leader_election.js | --amend | <ide><path>ber/leader_election.js
<ide>
<ide> // Define a single HTTP endpoint that 'handles' or forwards
<ide> http.get('/objects/:id', function onReq(req, res) {
<add> console.log("get req " + req.params);
<ide> var key = req.params.id;
<ide> if (ringpop.handleOrProxy(key, req, res)) {
<ide> console.log('Ringpop ' + ringpop.whoami() + ' handled ' + key); |
|
Java | mit | error: pathspec 'OpERP/src/main/java/devopsdistilled/operp/server/data/entity/stock/Stock.java' did not match any file(s) known to git
| 2d77aa8b32271c26f3c95e495933713dcb31be57 | 1 | njmube/OpERP,DevOpsDistilled/OpERP | package devopsdistilled.operp.server.data.entity.stock;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import devopsdistilled.operp.server.data.entity.Entiti;
import devopsdistilled.operp.server.data.entity.items.Item;
@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = { "itemId",
"warehouseId" }))
public class Stock extends Entiti<Long> {
private static final long serialVersionUID = -7397395555201558401L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long stockId;
private Long quantity;
@ManyToOne
@JoinColumn(name = "itemId")
private Item item;
@ManyToOne
@JoinColumn(name = "warehouseId")
private Warehouse warehouse;
@OneToMany(mappedBy = "stock")
private List<StockKeeper> stockKeepers;
public Long getStockId() {
return stockId;
}
public void setStockId(Long stockId) {
this.stockId = stockId;
}
public Long getQuantity() {
return quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public Warehouse getWarehouse() {
return warehouse;
}
public void setWarehouse(Warehouse warehouse) {
this.warehouse = warehouse;
}
public List<StockKeeper> getStockKeepers() {
return stockKeepers;
}
public void setStockKeepers(List<StockKeeper> stockKeepers) {
this.stockKeepers = stockKeepers;
}
@Override
public Long id() {
return getStockId();
}
@Override
public String toString() {
return new String(getItem().getItemName() + " In "
+ getWarehouse().getWarehouseName());
}
}
| OpERP/src/main/java/devopsdistilled/operp/server/data/entity/stock/Stock.java | Create Stock Entity
OPEN - task 24: Create a stock module
http://github.com/DevOpsDistilled/OpERP/issues/issue/24 | OpERP/src/main/java/devopsdistilled/operp/server/data/entity/stock/Stock.java | Create Stock Entity | <ide><path>pERP/src/main/java/devopsdistilled/operp/server/data/entity/stock/Stock.java
<add>package devopsdistilled.operp.server.data.entity.stock;
<add>
<add>import java.util.List;
<add>
<add>import javax.persistence.Entity;
<add>import javax.persistence.GeneratedValue;
<add>import javax.persistence.GenerationType;
<add>import javax.persistence.Id;
<add>import javax.persistence.JoinColumn;
<add>import javax.persistence.ManyToOne;
<add>import javax.persistence.OneToMany;
<add>import javax.persistence.Table;
<add>import javax.persistence.UniqueConstraint;
<add>
<add>import devopsdistilled.operp.server.data.entity.Entiti;
<add>import devopsdistilled.operp.server.data.entity.items.Item;
<add>
<add>@Entity
<add>@Table(uniqueConstraints = @UniqueConstraint(columnNames = { "itemId",
<add> "warehouseId" }))
<add>public class Stock extends Entiti<Long> {
<add>
<add> private static final long serialVersionUID = -7397395555201558401L;
<add>
<add> @Id
<add> @GeneratedValue(strategy = GenerationType.AUTO)
<add> private Long stockId;
<add>
<add> private Long quantity;
<add>
<add> @ManyToOne
<add> @JoinColumn(name = "itemId")
<add> private Item item;
<add>
<add> @ManyToOne
<add> @JoinColumn(name = "warehouseId")
<add> private Warehouse warehouse;
<add>
<add> @OneToMany(mappedBy = "stock")
<add> private List<StockKeeper> stockKeepers;
<add>
<add> public Long getStockId() {
<add> return stockId;
<add> }
<add>
<add> public void setStockId(Long stockId) {
<add> this.stockId = stockId;
<add> }
<add>
<add> public Long getQuantity() {
<add> return quantity;
<add> }
<add>
<add> public void setQuantity(Long quantity) {
<add> this.quantity = quantity;
<add> }
<add>
<add> public Item getItem() {
<add> return item;
<add> }
<add>
<add> public void setItem(Item item) {
<add> this.item = item;
<add> }
<add>
<add> public Warehouse getWarehouse() {
<add> return warehouse;
<add> }
<add>
<add> public void setWarehouse(Warehouse warehouse) {
<add> this.warehouse = warehouse;
<add> }
<add>
<add> public List<StockKeeper> getStockKeepers() {
<add> return stockKeepers;
<add> }
<add>
<add> public void setStockKeepers(List<StockKeeper> stockKeepers) {
<add> this.stockKeepers = stockKeepers;
<add> }
<add>
<add> @Override
<add> public Long id() {
<add> return getStockId();
<add> }
<add>
<add> @Override
<add> public String toString() {
<add> return new String(getItem().getItemName() + " In "
<add> + getWarehouse().getWarehouseName());
<add> }
<add>
<add>} |
|
Java | mit | 01d6d64048efc8502c4732db8caffa5e86714a86 | 0 | mzmine/mzmine3,mzmine/mzmine3 | /*
* Copyright 2006-2018 The MZmine 2 Development Team
*
* This file is part of MZmine 2.
*
* MZmine 2 is free software; you can redistribute it and/or modify it under the terms of the GNU
* General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* MZmine 2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with MZmine 2; if not,
* write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package net.sf.mzmine.modules.rawdatamethods.rawdataimport.fileformats;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.Date;
import java.util.LinkedList;
import java.util.logging.Logger;
import java.util.zip.DataFormatException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.Duration;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.google.common.base.Strings;
import net.sf.mzmine.datamodel.DataPoint;
import net.sf.mzmine.datamodel.MZmineProject;
import net.sf.mzmine.datamodel.MassSpectrumType;
import net.sf.mzmine.datamodel.PolarityType;
import net.sf.mzmine.datamodel.RawDataFile;
import net.sf.mzmine.datamodel.RawDataFileWriter;
import net.sf.mzmine.datamodel.impl.SimpleDataPoint;
import net.sf.mzmine.datamodel.impl.SimpleScan;
import net.sf.mzmine.taskcontrol.AbstractTask;
import net.sf.mzmine.taskcontrol.TaskStatus;
import net.sf.mzmine.util.CompressionUtils;
import net.sf.mzmine.util.ExceptionUtils;
import net.sf.mzmine.util.scans.ScanUtils;
/**
*
*/
public class MzXMLReadTask extends AbstractTask {
private Logger logger = Logger.getLogger(this.getClass().getName());
private File file;
private MZmineProject project;
private RawDataFileWriter newMZmineFile;
private RawDataFile finalRawDataFile;
private int totalScans = 0, parsedScans;
private int peaksCount = 0;
private StringBuilder charBuffer;
private boolean compressFlag = false;
private DefaultHandler handler = new MzXMLHandler();
private String precision;
// Retention time parser
private DatatypeFactory dataTypeFactory;
/*
* This variables are used to set the number of fragments that one single scan can have. The
* initial size of array is set to 10, but it depends of fragmentation level.
*/
private int parentTreeValue[] = new int[10];
private int msLevelTree = 0;
/*
* This stack stores the current scan and all his fragments until all the information is recover.
* The logic is FIFO at the moment of write into the RawDataFile
*/
private LinkedList<SimpleScan> parentStack;
/*
* This variable hold the present scan or fragment, it is send to the stack when another
* scan/fragment appears as a parser.startElement
*/
private SimpleScan buildingScan;
public MzXMLReadTask(MZmineProject project, File fileToOpen, RawDataFileWriter newMZmineFile) {
// 256 kilo-chars buffer
charBuffer = new StringBuilder(1 << 18);
parentStack = new LinkedList<SimpleScan>();
this.project = project;
this.file = fileToOpen;
this.newMZmineFile = newMZmineFile;
}
/**
* @see net.sf.mzmine.taskcontrol.Task#getFinishedPercentage()
*/
public double getFinishedPercentage() {
return totalScans == 0 ? 0 : (double) parsedScans / totalScans;
}
/**
* @see java.lang.Runnable#run()
*/
public void run() {
setStatus(TaskStatus.PROCESSING);
logger.info("Started parsing file " + file);
// Use the default (non-validating) parser
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
dataTypeFactory = DatatypeFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(file, handler);
// Close file
finalRawDataFile = newMZmineFile.finishWriting();
project.addFile(finalRawDataFile);
} catch (Throwable e) {
e.printStackTrace();
/* we may already have set the status to CANCELED */
if (getStatus() == TaskStatus.PROCESSING) {
setStatus(TaskStatus.ERROR);
setErrorMessage(ExceptionUtils.exceptionToString(e));
}
return;
}
if (isCanceled())
return;
if (parsedScans == 0) {
setStatus(TaskStatus.ERROR);
setErrorMessage("No scans found");
return;
}
logger.info("Finished parsing " + file + ", parsed " + parsedScans + " scans");
setStatus(TaskStatus.FINISHED);
}
public String getTaskDescription() {
return "Opening file " + file;
}
private class MzXMLHandler extends DefaultHandler {
public void startElement(String namespaceURI, String lName, // local
// name
String qName, // qualified name
Attributes attrs) throws SAXException {
if (isCanceled())
throw new SAXException("Parsing Cancelled");
// <msRun>
if (qName.equals("msRun")) {
String s = attrs.getValue("scanCount");
if (s != null)
totalScans = Integer.parseInt(s);
}
// <scan>
if (qName.equalsIgnoreCase("scan")) {
if (buildingScan != null) {
parentStack.addFirst(buildingScan);
buildingScan = null;
}
/*
* Only num, msLevel & peaksCount values are required according with mzxml standard, the
* others are optional
*/
int scanNumber = Integer.parseInt(attrs.getValue("num"));
// mzXML files with empty msLevel attribute do exist, so we use 1 as default
int msLevel = 1;
if (! Strings.isNullOrEmpty(attrs.getValue("msLevel")))
msLevel = Integer.parseInt(attrs.getValue("msLevel"));
String scanType = attrs.getValue("scanType");
String filterLine = attrs.getValue("filterLine");
String scanId = filterLine;
if (Strings.isNullOrEmpty(scanId))
scanId = scanType;
PolarityType polarity;
String polarityAttr = attrs.getValue("polarity");
if ((polarityAttr != null) && (polarityAttr.length() == 1))
polarity = PolarityType.fromSingleChar(polarityAttr);
else
polarity = PolarityType.UNKNOWN;
peaksCount = Integer.parseInt(attrs.getValue("peaksCount"));
// Parse retention time
double retentionTime = 0;
String retentionTimeStr = attrs.getValue("retentionTime");
if (retentionTimeStr != null) {
Date currentDate = new Date();
Duration dur = dataTypeFactory.newDuration(retentionTimeStr);
retentionTime = dur.getTimeInMillis(currentDate) / 1000d / 60d;
} else {
setStatus(TaskStatus.ERROR);
setErrorMessage("This file does not contain retentionTime for scans");
throw new SAXException("Could not read retention time");
}
int parentScan = -1;
if (msLevel > 9) {
setStatus(TaskStatus.ERROR);
setErrorMessage("msLevel value bigger than 10");
throw new SAXException("The value of msLevel is bigger than 10");
}
if (msLevel > 1) {
parentScan = parentTreeValue[msLevel - 1];
for (SimpleScan p : parentStack) {
if (p.getScanNumber() == parentScan) {
p.addFragmentScan(scanNumber);
}
}
}
// Setting the level of fragment of scan and parent scan number
msLevelTree++;
parentTreeValue[msLevel] = scanNumber;
buildingScan = new SimpleScan(null, scanNumber, msLevel, retentionTime, 0, 0, null,
new DataPoint[0], null, polarity, scanId, null);
}
// <peaks>
if (qName.equalsIgnoreCase("peaks")) {
// clean the current char buffer for the new element
charBuffer.setLength(0);
compressFlag = false;
String compressionType = attrs.getValue("compressionType");
if ((compressionType == null) || (compressionType.equals("none")))
compressFlag = false;
else
compressFlag = true;
precision = attrs.getValue("precision");
}
// <precursorMz>
if (qName.equalsIgnoreCase("precursorMz")) {
// clean the current char buffer for the new element
charBuffer.setLength(0);
String precursorCharge = attrs.getValue("precursorCharge");
if (precursorCharge != null)
buildingScan.setPrecursorCharge(Integer.parseInt(precursorCharge));
}
}
/**
* endElement()
*/
public void endElement(String namespaceURI, String sName, // simple name
String qName // qualified name
) throws SAXException {
// </scan>
if (qName.equalsIgnoreCase("scan")) {
msLevelTree--;
/*
* At this point we verify if the scan and his fragments are closed, so we include the
* present scan/fragment into the stack and start to take elements from them (FIFO) for the
* RawDataFile.
*/
if (msLevelTree == 0) {
parentStack.addFirst(buildingScan);
buildingScan = null;
while (!parentStack.isEmpty()) {
SimpleScan currentScan = parentStack.removeLast();
try {
newMZmineFile.addScan(currentScan);
} catch (IOException e) {
e.printStackTrace();
setStatus(TaskStatus.ERROR);
setErrorMessage("IO error: " + e);
throw new SAXException("Parsing error: " + e);
}
parsedScans++;
}
/*
* The scan with all his fragments is in the RawDataFile, now we clean the stack for the
* next scan and fragments.
*/
parentStack.clear();
}
return;
}
// <precursorMz>
if (qName.equalsIgnoreCase("precursorMz")) {
final String textContent = charBuffer.toString();
double precursorMz = 0d;
if (!textContent.isEmpty())
precursorMz = Double.parseDouble(textContent);
buildingScan.setPrecursorMZ(precursorMz);
return;
}
// <peaks>
if (qName.equalsIgnoreCase("peaks")) {
byte[] peakBytes = Base64.getDecoder().decode(charBuffer.toString());
if (compressFlag) {
try {
peakBytes = CompressionUtils.decompress(peakBytes);
} catch (DataFormatException e) {
setStatus(TaskStatus.ERROR);
setErrorMessage("Corrupt compressed peak: " + e.toString());
throw new SAXException("Parsing Cancelled");
}
}
// make a data input stream
DataInputStream peakStream = new DataInputStream(new ByteArrayInputStream(peakBytes));
DataPoint dataPoints[] = new DataPoint[peaksCount];
try {
for (int i = 0; i < dataPoints.length; i++) {
// Always respect this order pairOrder="m/z-int"
double massOverCharge;
double intensity;
if ("64".equals(precision)) {
massOverCharge = peakStream.readDouble();
intensity = peakStream.readDouble();
} else {
massOverCharge = (double) peakStream.readFloat();
intensity = (double) peakStream.readFloat();
}
// Copy m/z and intensity data
dataPoints[i] = new SimpleDataPoint(massOverCharge, intensity);
}
} catch (IOException eof) {
setStatus(TaskStatus.ERROR);
setErrorMessage("Corrupt mzXML file");
throw new SAXException("Parsing Cancelled");
}
// Auto-detect whether this scan is centroided
MassSpectrumType spectrumType = ScanUtils.detectSpectrumType(dataPoints);
// Set the centroided tag
buildingScan.setSpectrumType(spectrumType);
// Set the final data points to the scan
buildingScan.setDataPoints(dataPoints);
return;
}
}
/**
* characters()
*
* @see org.xml.sax.ContentHandler#characters(char[], int, int)
*/
public void characters(char buf[], int offset, int len) throws SAXException {
charBuffer.append(buf, offset, len);
}
}
}
| src/main/java/net/sf/mzmine/modules/rawdatamethods/rawdataimport/fileformats/MzXMLReadTask.java | /*
* Copyright 2006-2018 The MZmine 2 Development Team
*
* This file is part of MZmine 2.
*
* MZmine 2 is free software; you can redistribute it and/or modify it under the terms of the GNU
* General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* MZmine 2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with MZmine 2; if not,
* write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package net.sf.mzmine.modules.rawdatamethods.rawdataimport.fileformats;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.Date;
import java.util.LinkedList;
import java.util.logging.Logger;
import java.util.zip.DataFormatException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.Duration;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.google.common.base.Strings;
import net.sf.mzmine.datamodel.DataPoint;
import net.sf.mzmine.datamodel.MZmineProject;
import net.sf.mzmine.datamodel.MassSpectrumType;
import net.sf.mzmine.datamodel.PolarityType;
import net.sf.mzmine.datamodel.RawDataFile;
import net.sf.mzmine.datamodel.RawDataFileWriter;
import net.sf.mzmine.datamodel.impl.SimpleDataPoint;
import net.sf.mzmine.datamodel.impl.SimpleScan;
import net.sf.mzmine.taskcontrol.AbstractTask;
import net.sf.mzmine.taskcontrol.TaskStatus;
import net.sf.mzmine.util.CompressionUtils;
import net.sf.mzmine.util.ExceptionUtils;
import net.sf.mzmine.util.scans.ScanUtils;
/**
*
*/
public class MzXMLReadTask extends AbstractTask {
private Logger logger = Logger.getLogger(this.getClass().getName());
private File file;
private MZmineProject project;
private RawDataFileWriter newMZmineFile;
private RawDataFile finalRawDataFile;
private int totalScans = 0, parsedScans;
private int peaksCount = 0;
private StringBuilder charBuffer;
private boolean compressFlag = false;
private DefaultHandler handler = new MzXMLHandler();
private String precision;
// Retention time parser
private DatatypeFactory dataTypeFactory;
/*
* This variables are used to set the number of fragments that one single scan can have. The
* initial size of array is set to 10, but it depends of fragmentation level.
*/
private int parentTreeValue[] = new int[10];
private int msLevelTree = 0;
/*
* This stack stores the current scan and all his fragments until all the information is recover.
* The logic is FIFO at the moment of write into the RawDataFile
*/
private LinkedList<SimpleScan> parentStack;
/*
* This variable hold the present scan or fragment, it is send to the stack when another
* scan/fragment appears as a parser.startElement
*/
private SimpleScan buildingScan;
public MzXMLReadTask(MZmineProject project, File fileToOpen, RawDataFileWriter newMZmineFile) {
// 256 kilo-chars buffer
charBuffer = new StringBuilder(1 << 18);
parentStack = new LinkedList<SimpleScan>();
this.project = project;
this.file = fileToOpen;
this.newMZmineFile = newMZmineFile;
}
/**
* @see net.sf.mzmine.taskcontrol.Task#getFinishedPercentage()
*/
public double getFinishedPercentage() {
return totalScans == 0 ? 0 : (double) parsedScans / totalScans;
}
/**
* @see java.lang.Runnable#run()
*/
public void run() {
setStatus(TaskStatus.PROCESSING);
logger.info("Started parsing file " + file);
// Use the default (non-validating) parser
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
dataTypeFactory = DatatypeFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(file, handler);
// Close file
finalRawDataFile = newMZmineFile.finishWriting();
project.addFile(finalRawDataFile);
} catch (Throwable e) {
e.printStackTrace();
/* we may already have set the status to CANCELED */
if (getStatus() == TaskStatus.PROCESSING) {
setStatus(TaskStatus.ERROR);
setErrorMessage(ExceptionUtils.exceptionToString(e));
}
return;
}
if (isCanceled())
return;
if (parsedScans == 0) {
setStatus(TaskStatus.ERROR);
setErrorMessage("No scans found");
return;
}
logger.info("Finished parsing " + file + ", parsed " + parsedScans + " scans");
setStatus(TaskStatus.FINISHED);
}
public String getTaskDescription() {
return "Opening file " + file;
}
private class MzXMLHandler extends DefaultHandler {
public void startElement(String namespaceURI, String lName, // local
// name
String qName, // qualified name
Attributes attrs) throws SAXException {
if (isCanceled())
throw new SAXException("Parsing Cancelled");
// <msRun>
if (qName.equals("msRun")) {
String s = attrs.getValue("scanCount");
if (s != null)
totalScans = Integer.parseInt(s);
}
// <scan>
if (qName.equalsIgnoreCase("scan")) {
if (buildingScan != null) {
parentStack.addFirst(buildingScan);
buildingScan = null;
}
/*
* Only num, msLevel & peaksCount values are required according with mzxml standard, the
* others are optional
*/
int scanNumber = Integer.parseInt(attrs.getValue("num"));
int msLevel = Integer.parseInt(attrs.getValue("msLevel"));
String scanType = attrs.getValue("scanType");
String filterLine = attrs.getValue("filterLine");
String scanId = filterLine;
if (Strings.isNullOrEmpty(scanId))
scanId = scanType;
PolarityType polarity;
String polarityAttr = attrs.getValue("polarity");
if ((polarityAttr != null) && (polarityAttr.length() == 1))
polarity = PolarityType.fromSingleChar(polarityAttr);
else
polarity = PolarityType.UNKNOWN;
peaksCount = Integer.parseInt(attrs.getValue("peaksCount"));
// Parse retention time
double retentionTime = 0;
String retentionTimeStr = attrs.getValue("retentionTime");
if (retentionTimeStr != null) {
Date currentDate = new Date();
Duration dur = dataTypeFactory.newDuration(retentionTimeStr);
retentionTime = dur.getTimeInMillis(currentDate) / 1000d / 60d;
} else {
setStatus(TaskStatus.ERROR);
setErrorMessage("This file does not contain retentionTime for scans");
throw new SAXException("Could not read retention time");
}
int parentScan = -1;
if (msLevel > 9) {
setStatus(TaskStatus.ERROR);
setErrorMessage("msLevel value bigger than 10");
throw new SAXException("The value of msLevel is bigger than 10");
}
if (msLevel > 1) {
parentScan = parentTreeValue[msLevel - 1];
for (SimpleScan p : parentStack) {
if (p.getScanNumber() == parentScan) {
p.addFragmentScan(scanNumber);
}
}
}
// Setting the level of fragment of scan and parent scan number
msLevelTree++;
parentTreeValue[msLevel] = scanNumber;
buildingScan = new SimpleScan(null, scanNumber, msLevel, retentionTime, 0, 0, null,
new DataPoint[0], null, polarity, scanId, null);
}
// <peaks>
if (qName.equalsIgnoreCase("peaks")) {
// clean the current char buffer for the new element
charBuffer.setLength(0);
compressFlag = false;
String compressionType = attrs.getValue("compressionType");
if ((compressionType == null) || (compressionType.equals("none")))
compressFlag = false;
else
compressFlag = true;
precision = attrs.getValue("precision");
}
// <precursorMz>
if (qName.equalsIgnoreCase("precursorMz")) {
// clean the current char buffer for the new element
charBuffer.setLength(0);
String precursorCharge = attrs.getValue("precursorCharge");
if (precursorCharge != null)
buildingScan.setPrecursorCharge(Integer.parseInt(precursorCharge));
}
}
/**
* endElement()
*/
public void endElement(String namespaceURI, String sName, // simple name
String qName // qualified name
) throws SAXException {
// </scan>
if (qName.equalsIgnoreCase("scan")) {
msLevelTree--;
/*
* At this point we verify if the scan and his fragments are closed, so we include the
* present scan/fragment into the stack and start to take elements from them (FIFO) for the
* RawDataFile.
*/
if (msLevelTree == 0) {
parentStack.addFirst(buildingScan);
buildingScan = null;
while (!parentStack.isEmpty()) {
SimpleScan currentScan = parentStack.removeLast();
try {
newMZmineFile.addScan(currentScan);
} catch (IOException e) {
e.printStackTrace();
setStatus(TaskStatus.ERROR);
setErrorMessage("IO error: " + e);
throw new SAXException("Parsing error: " + e);
}
parsedScans++;
}
/*
* The scan with all his fragments is in the RawDataFile, now we clean the stack for the
* next scan and fragments.
*/
parentStack.clear();
}
return;
}
// <precursorMz>
if (qName.equalsIgnoreCase("precursorMz")) {
final String textContent = charBuffer.toString();
double precursorMz = 0d;
if (!textContent.isEmpty())
precursorMz = Double.parseDouble(textContent);
buildingScan.setPrecursorMZ(precursorMz);
return;
}
// <peaks>
if (qName.equalsIgnoreCase("peaks")) {
byte[] peakBytes = Base64.getDecoder().decode(charBuffer.toString());
if (compressFlag) {
try {
peakBytes = CompressionUtils.decompress(peakBytes);
} catch (DataFormatException e) {
setStatus(TaskStatus.ERROR);
setErrorMessage("Corrupt compressed peak: " + e.toString());
throw new SAXException("Parsing Cancelled");
}
}
// make a data input stream
DataInputStream peakStream = new DataInputStream(new ByteArrayInputStream(peakBytes));
DataPoint dataPoints[] = new DataPoint[peaksCount];
try {
for (int i = 0; i < dataPoints.length; i++) {
// Always respect this order pairOrder="m/z-int"
double massOverCharge;
double intensity;
if ("64".equals(precision)) {
massOverCharge = peakStream.readDouble();
intensity = peakStream.readDouble();
} else {
massOverCharge = (double) peakStream.readFloat();
intensity = (double) peakStream.readFloat();
}
// Copy m/z and intensity data
dataPoints[i] = new SimpleDataPoint(massOverCharge, intensity);
}
} catch (IOException eof) {
setStatus(TaskStatus.ERROR);
setErrorMessage("Corrupt mzXML file");
throw new SAXException("Parsing Cancelled");
}
// Auto-detect whether this scan is centroided
MassSpectrumType spectrumType = ScanUtils.detectSpectrumType(dataPoints);
// Set the centroided tag
buildingScan.setSpectrumType(spectrumType);
// Set the final data points to the scan
buildingScan.setDataPoints(dataPoints);
return;
}
}
/**
* characters()
*
* @see org.xml.sax.ContentHandler#characters(char[], int, int)
*/
public void characters(char buf[], int offset, int len) throws SAXException {
charBuffer.append(buf, offset, len);
}
}
}
| Fix for issue #747 | src/main/java/net/sf/mzmine/modules/rawdatamethods/rawdataimport/fileformats/MzXMLReadTask.java | Fix for issue #747 | <ide><path>rc/main/java/net/sf/mzmine/modules/rawdatamethods/rawdataimport/fileformats/MzXMLReadTask.java
<ide> * others are optional
<ide> */
<ide> int scanNumber = Integer.parseInt(attrs.getValue("num"));
<del> int msLevel = Integer.parseInt(attrs.getValue("msLevel"));
<add>
<add> // mzXML files with empty msLevel attribute do exist, so we use 1 as default
<add> int msLevel = 1;
<add> if (! Strings.isNullOrEmpty(attrs.getValue("msLevel")))
<add> msLevel = Integer.parseInt(attrs.getValue("msLevel"));
<add>
<ide> String scanType = attrs.getValue("scanType");
<ide> String filterLine = attrs.getValue("filterLine");
<ide> String scanId = filterLine; |
|
Java | mit | b352bbd2241a4edc017d3ff15156b5e7d30ab3e0 | 0 | validator/validator,YOTOV-LIMITED/validator,takenspc/validator,tripu/validator,YOTOV-LIMITED/validator,validator/validator,tripu/validator,validator/validator,YOTOV-LIMITED/validator,takenspc/validator,sammuelyee/validator,takenspc/validator,YOTOV-LIMITED/validator,sammuelyee/validator,takenspc/validator,sammuelyee/validator,sammuelyee/validator,tripu/validator,tripu/validator,validator/validator,takenspc/validator,sammuelyee/validator,YOTOV-LIMITED/validator,validator/validator,tripu/validator | /*
* Copyright (c) 2008 Mozilla Foundation
*
* 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 nu.validator.svgresearch;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.GZIPInputStream;
import javax.xml.parsers.SAXParserFactory;
import nu.validator.xml.NullEntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
public class SvgAnalyzer {
/**
* @param args
* @throws Exception
* @throws SAXException
*/
public static void main(String[] args) throws SAXException, Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(false);
XMLReader parser = factory.newSAXParser().getXMLReader();
SvgAnalysisHandler analysisHandler = new SvgAnalysisHandler();
parser.setContentHandler(analysisHandler);
parser.setDTDHandler(analysisHandler);
parser.setProperty("http://xml.org/sax/properties/lexical-handler", analysisHandler);
parser.setProperty("http://xml.org/sax/properties/declaration-handler", analysisHandler);
parser.setFeature("http://xml.org/sax/features/string-interning", true);
parser.setEntityResolver(new NullEntityResolver());
parser.setErrorHandler(new ErrorHandler() {
public void error(SAXParseException exception) throws SAXException {
}
public void fatalError(SAXParseException exception)
throws SAXException {
}
public void warning(SAXParseException exception)
throws SAXException {
}});
File dir = new File(args[0]);
File[] list = dir.listFiles();
int nsError = 0;
int encodingErrors = 0;
int otherIllFormed = 0;
double total = (double) list.length;
for (int i = 0; i < list.length; i++) {
File file = list[i];
try {
InputSource is = new InputSource(new FileInputStream(file));
is.setSystemId(file.toURL().toExternalForm());
parser.parse(is);
} catch (SAXParseException e) {
String msg = e.getMessage();
if (msg.startsWith("The prefix ")) {
nsError++;
} else if (msg.contains("Prefixed namespace bindings may not be empty.")) {
nsError++;
} else if (msg.startsWith("Invalid byte ")) {
encodingErrors++;
} else {
otherIllFormed++;
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
System.out.print("NS errors: ");
System.out.println(((double)nsError)/total);
System.out.print("Encoding errors: ");
System.out.println(((double)encodingErrors)/total);
System.out.print("Other WF errors: ");
System.out.println(((double)otherIllFormed)/total);
analysisHandler.print();
}
}
| src/nu/validator/svgresearch/SvgAnalyzer.java | /*
* Copyright (c) 2008 Mozilla Foundation
*
* 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 nu.validator.svgresearch;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.GZIPInputStream;
import javax.xml.parsers.SAXParserFactory;
import nu.validator.xml.NullEntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
public class SvgAnalyzer {
/**
* @param args
* @throws Exception
* @throws SAXException
*/
public static void main(String[] args) throws SAXException, Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(false);
XMLReader parser = factory.newSAXParser().getXMLReader();
SvgAnalysisHandler analysisHandler = new SvgAnalysisHandler();
parser.setContentHandler(analysisHandler);
parser.setDTDHandler(analysisHandler);
parser.setProperty("http://xml.org/sax/properties/lexical-handler", analysisHandler);
parser.setProperty("http://xml.org/sax/properties/declaration-handler", analysisHandler);
parser.setFeature("http://xml.org/sax/features/string-interning", true);
parser.setEntityResolver(new NullEntityResolver());
File dir = new File(args[0]);
File[] list = dir.listFiles();
int nsError = 0;
int encodingErrors = 0;
int otherIllFormed = 0;
double total = (double) list.length;
for (int i = 0; i < list.length; i++) {
File file = list[i];
try {
InputSource is = new InputSource(new FileInputStream(file));
is.setSystemId(file.toURL().toExternalForm());
parser.parse(is);
} catch (SAXParseException e) {
String msg = e.getMessage();
if (msg.startsWith("The prefix ")) {
nsError++;
} else if (msg.contains("Prefixed namespace bindings may not be empty.")) {
nsError++;
} else if (msg.startsWith("Invalid byte ")) {
encodingErrors++;
} else {
otherIllFormed++;
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
System.out.println(((double)i)/total);
}
System.out.print("NS errors: ");
System.out.println(((double)nsError)/total);
System.out.print("Encoding errors: ");
System.out.println(((double)encodingErrors)/total);
System.out.print("Other WF errors: ");
System.out.println(((double)otherIllFormed)/total);
analysisHandler.print();
}
}
| tweak
--HG--
extra : convert_revision : svn%3Ac6dcca6c-c432-0410-a79e-3fbb6554aff1/trunk%40253
| src/nu/validator/svgresearch/SvgAnalyzer.java | tweak | <ide><path>rc/nu/validator/svgresearch/SvgAnalyzer.java
<ide>
<ide> import nu.validator.xml.NullEntityResolver;
<ide>
<add>import org.xml.sax.ErrorHandler;
<ide> import org.xml.sax.InputSource;
<ide> import org.xml.sax.SAXException;
<ide> import org.xml.sax.SAXParseException;
<ide> parser.setProperty("http://xml.org/sax/properties/declaration-handler", analysisHandler);
<ide> parser.setFeature("http://xml.org/sax/features/string-interning", true);
<ide> parser.setEntityResolver(new NullEntityResolver());
<add> parser.setErrorHandler(new ErrorHandler() {
<add>
<add> public void error(SAXParseException exception) throws SAXException {
<add> }
<add>
<add> public void fatalError(SAXParseException exception)
<add> throws SAXException {
<add> }
<add>
<add> public void warning(SAXParseException exception)
<add> throws SAXException {
<add> }});
<ide>
<ide> File dir = new File(args[0]);
<ide> File[] list = dir.listFiles();
<ide> e.printStackTrace();
<ide> System.exit(-1);
<ide> }
<del> System.out.println(((double)i)/total);
<ide> }
<ide>
<ide> System.out.print("NS errors: "); |
|
Java | mit | 87c1630e92c470389f4eb88aff54d221cf80e7d7 | 0 | tedliang/osworkflow,tedliang/osworkflow,tedliang/osworkflow,tedliang/osworkflow | /*
* Copyright (c) 2002-2003 by OpenSymphony
* All rights reserved.
*/
package com.opensymphony.workflow.loader;
import com.opensymphony.workflow.util.XMLizable;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
/**
* User: hani
* Date: May 28, 2003
* Time: 12:44:54 AM
*/
public abstract class AbstractDescriptor implements XMLizable, Serializable {
//~ Instance fields ////////////////////////////////////////////////////////
private AbstractDescriptor parent;
private boolean hasId = false;
private int entityId;
private int id;
//~ Methods ////////////////////////////////////////////////////////////////
public void setEntityId(int entityId) {
this.entityId = entityId;
}
public int getEntityId() {
return entityId;
}
public void setId(int id) {
this.id = id;
hasId = true;
}
public int getId() {
return id;
}
public void setParent(AbstractDescriptor parent) {
this.parent = parent;
}
public AbstractDescriptor getParent() {
return parent;
}
public String asXML() {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
this.writeXML(writer, 0);
writer.close();
return stringWriter.toString();
}
public boolean hasId() {
return hasId;
}
}
| src/java/com/opensymphony/workflow/loader/AbstractDescriptor.java | /*
* Copyright (c) 2002-2003 by OpenSymphony
* All rights reserved.
*/
package com.opensymphony.workflow.loader;
import com.opensymphony.workflow.util.XMLizable;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
/**
* User: hani
* Date: May 28, 2003
* Time: 12:44:54 AM
*/
public abstract class AbstractDescriptor implements XMLizable, Serializable {
//~ Instance fields ////////////////////////////////////////////////////////
private AbstractDescriptor parent;
private boolean hasId = false;
private int id;
//~ Methods ////////////////////////////////////////////////////////////////
public void setId(int id) {
this.id = id;
hasId = true;
}
public int getId() {
return id;
}
public void setParent(AbstractDescriptor parent) {
this.parent = parent;
}
public AbstractDescriptor getParent() {
return parent;
}
public String asXML() {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
this.writeXML(writer, 0);
writer.close();
return stringWriter.toString();
}
public boolean hasId() {
return hasId;
}
}
| Added entityId field for Hibernate persistence
| src/java/com/opensymphony/workflow/loader/AbstractDescriptor.java | Added entityId field for Hibernate persistence | <ide><path>rc/java/com/opensymphony/workflow/loader/AbstractDescriptor.java
<ide>
<ide> private AbstractDescriptor parent;
<ide> private boolean hasId = false;
<add> private int entityId;
<ide> private int id;
<ide>
<ide> //~ Methods ////////////////////////////////////////////////////////////////
<add>
<add> public void setEntityId(int entityId) {
<add> this.entityId = entityId;
<add> }
<add>
<add> public int getEntityId() {
<add> return entityId;
<add> }
<ide>
<ide> public void setId(int id) {
<ide> this.id = id; |
|
Java | bsd-3-clause | a0639ef5515eec3c756cb01c0948e930ef8bb729 | 0 | NCIP/c3pr,NCIP/c3pr,NCIP/c3pr | package edu.duke.cabig.c3pr.domain;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import com.semanticbits.coppa.domain.annotations.RemoteProperty;
// TODO: Auto-generated Javadoc
/**
* The Class ResearchStaff.
*
* @author Priyatam
*/
@Entity
@Table(name = "research_staff")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@GenericGenerator(name = "id-generator", strategy = "native", parameters = { @Parameter(name = "sequence", value = "research_staff_id_seq") })
public abstract class ResearchStaff extends User {
/** The study personnels. */
private List<StudyPersonnel> studyPersonnels = new ArrayList<StudyPersonnel>();
/** The nci identifier. */
private String nciIdentifier;
/** The healthcare site. */
private HealthcareSite healthcareSite;
/** The user based recipient. */
private List<UserBasedRecipient> userBasedRecipient;
/** The external research staff. */
protected List<ResearchStaff> externalResearchStaff = new ArrayList<ResearchStaff>();
/**
* Instantiates a new research staff.
*/
public ResearchStaff() {
super();
}
/**
* Gets the external research staff.
*
* @return the external research staff
*/
@Transient
public List<ResearchStaff> getExternalResearchStaff() {
return externalResearchStaff;
}
/**
* Sets the external research staff.
*
* @param externalResearchStaff the new external research staff
*/
public void setExternalResearchStaff(List<ResearchStaff> externalResearchStaff) {
this.externalResearchStaff = externalResearchStaff;
}
/**
* Adds the external research staff.
*
* @param externalResearchStaff the external research staff
*/
public void addExternalResearchStaff(ResearchStaff externalResearchStaff){
this.getExternalResearchStaff().add(externalResearchStaff);
}
/**
* Adds the study personnel.
*
* @param studyPersonnel the study personnel
*/
public void addStudyPersonnel(StudyPersonnel studyPersonnel) {
getStudyPersonnels().add(studyPersonnel);
}
// / BEAN METHODS
/**
* Gets the study personnels.
*
* @return the study personnels
*/
@OneToMany(mappedBy = "researchStaff")
@Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
public List<StudyPersonnel> getStudyPersonnels() {
return studyPersonnels;
}
/**
* Sets the study personnels.
*
* @param studyPersonnels the new study personnels
*/
public void setStudyPersonnels(List<StudyPersonnel> studyPersonnels) {
this.studyPersonnels = studyPersonnels;
}
/* (non-Javadoc)
* @see edu.duke.cabig.c3pr.domain.Person#getContactMechanisms()
*/
@OneToMany
@Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
@JoinColumn(name = "RS_ID")
@OrderBy("id")
public List<ContactMechanism> getContactMechanisms() {
return contactMechanisms;
}
/* (non-Javadoc)
* @see edu.duke.cabig.c3pr.domain.Person#setContactMechanisms(java.util.List)
*/
public void setContactMechanisms(List<ContactMechanism> contactMechanisms) {
this.contactMechanisms = contactMechanisms;
}
/**
* Gets the healthcare site.
*
* @return the healthcare site
*/
@ManyToOne
@JoinColumn(name = "HCS_ID")
public HealthcareSite getHealthcareSite() {
return healthcareSite;
}
/**
* Sets the healthcare site.
*
* @param healthcareSite the new healthcare site
*/
public void setHealthcareSite(HealthcareSite healthcareSite) {
this.healthcareSite = healthcareSite;
}
/**
* Compare to.
*
* @param o the o
*
* @return the int
*/
public int compareTo(Object o) {
if (this.equals((ResearchStaff) o)) return 0;
else return 1;
}
/* (non-Javadoc)
* @see edu.duke.cabig.c3pr.domain.Person#hashCode()
*/
@Override
public int hashCode() {
final int PRIME = 31;
// int result = super.hashCode();
int result = 1;
result = PRIME * result + ((nciIdentifier == null) ? 0 : nciIdentifier.hashCode());
return result;
}
/* (non-Javadoc)
* @see edu.duke.cabig.c3pr.domain.Person#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (getClass() != obj.getClass()) return false;
final ResearchStaff other = (ResearchStaff) obj;
if (nciIdentifier == null) {
if (other.nciIdentifier != null) return false;
}
else if (!nciIdentifier.equalsIgnoreCase(other.nciIdentifier)) return false;
return true;
}
/**
* Gets the nci identifier.
*
* @return the nci identifier
*/
@RemoteProperty
public String getNciIdentifier() {
return nciIdentifier;
}
/**
* Sets the nci identifier.
*
* @param nciIdentifier the new nci identifier
*/
public void setNciIdentifier(String nciIdentifier) {
this.nciIdentifier = nciIdentifier;
}
/**
* Gets the user based recipient.
*
* @return the user based recipient
*/
@OneToMany
@Cascade(value = { CascadeType.LOCK})
@JoinColumn(name = "research_staff_id")
public List<UserBasedRecipient> getUserBasedRecipient() {
return userBasedRecipient;
}
/**
* Sets the user based recipient.
*
* @param userBasedRecipient the new user based recipient
*/
public void setUserBasedRecipient(List<UserBasedRecipient> userBasedRecipient) {
this.userBasedRecipient = userBasedRecipient;
}
} | codebase/projects/core/src/java/edu/duke/cabig/c3pr/domain/ResearchStaff.java | package edu.duke.cabig.c3pr.domain;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import com.semanticbits.coppa.domain.annotations.RemoteProperty;
/**
* @author Priyatam
*/
@Entity
@Table(name = "research_staff")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@GenericGenerator(name = "id-generator", strategy = "native", parameters = { @Parameter(name = "sequence", value = "research_staff_id_seq") })
public abstract class ResearchStaff extends User {
private List<StudyPersonnel> studyPersonnels = new ArrayList<StudyPersonnel>();
private String nciIdentifier;
private HealthcareSite healthcareSite;
private List<UserBasedRecipient> userBasedRecipient;
protected List<ResearchStaff> externalResearchStaff = new ArrayList<ResearchStaff>();
public ResearchStaff() {
super();
}
@Transient
public List<ResearchStaff> getExternalResearchStaff() {
return externalResearchStaff;
}
public void setExternalResearchStaff(List<ResearchStaff> externalResearchStaff) {
this.externalResearchStaff = externalResearchStaff;
}
public void addExternalResearchStaff(ResearchStaff externalResearchStaff){
this.getExternalResearchStaff().add(externalResearchStaff);
}
public void addStudyPersonnel(StudyPersonnel studyPersonnel) {
getStudyPersonnels().add(studyPersonnel);
}
// / BEAN METHODS
@OneToMany(mappedBy = "researchStaff")
@Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
public List<StudyPersonnel> getStudyPersonnels() {
return studyPersonnels;
}
public void setStudyPersonnels(List<StudyPersonnel> studyPersonnels) {
this.studyPersonnels = studyPersonnels;
}
@OneToMany
@Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
@JoinColumn(name = "RS_ID")
@OrderBy("id")
public List<ContactMechanism> getContactMechanisms() {
return contactMechanisms;
}
public void setContactMechanisms(List<ContactMechanism> contactMechanisms) {
this.contactMechanisms = contactMechanisms;
}
@ManyToOne
@JoinColumn(name = "HCS_ID")
public HealthcareSite getHealthcareSite() {
return healthcareSite;
}
public void setHealthcareSite(HealthcareSite healthcareSite) {
this.healthcareSite = healthcareSite;
}
public int compareTo(Object o) {
if (this.equals((ResearchStaff) o)) return 0;
else return 1;
}
@Override
public int hashCode() {
final int PRIME = 31;
// int result = super.hashCode();
int result = 1;
result = PRIME * result + ((nciIdentifier == null) ? 0 : nciIdentifier.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (getClass() != obj.getClass()) return false;
final ResearchStaff other = (ResearchStaff) obj;
if (nciIdentifier == null) {
if (other.nciIdentifier != null) return false;
}
else if (!nciIdentifier.equalsIgnoreCase(other.nciIdentifier)) return false;
return true;
}
@RemoteProperty
public String getNciIdentifier() {
return nciIdentifier;
}
public void setNciIdentifier(String nciIdentifier) {
this.nciIdentifier = nciIdentifier;
}
@OneToMany
@Cascade(value = { CascadeType.LOCK})
@JoinColumn(name = "research_staff_id")
public List<UserBasedRecipient> getUserBasedRecipient() {
return userBasedRecipient;
}
public void setUserBasedRecipient(List<UserBasedRecipient> userBasedRecipient) {
this.userBasedRecipient = userBasedRecipient;
}
} | added comments for java docs
| codebase/projects/core/src/java/edu/duke/cabig/c3pr/domain/ResearchStaff.java | added comments for java docs | <ide><path>odebase/projects/core/src/java/edu/duke/cabig/c3pr/domain/ResearchStaff.java
<ide>
<ide> import com.semanticbits.coppa.domain.annotations.RemoteProperty;
<ide>
<add>// TODO: Auto-generated Javadoc
<ide> /**
<add> * The Class ResearchStaff.
<add> *
<ide> * @author Priyatam
<ide> */
<ide> @Entity
<ide> @GenericGenerator(name = "id-generator", strategy = "native", parameters = { @Parameter(name = "sequence", value = "research_staff_id_seq") })
<ide> public abstract class ResearchStaff extends User {
<ide>
<add> /** The study personnels. */
<ide> private List<StudyPersonnel> studyPersonnels = new ArrayList<StudyPersonnel>();
<ide>
<add> /** The nci identifier. */
<ide> private String nciIdentifier;
<ide>
<add> /** The healthcare site. */
<ide> private HealthcareSite healthcareSite;
<ide>
<add> /** The user based recipient. */
<ide> private List<UserBasedRecipient> userBasedRecipient;
<ide>
<add> /** The external research staff. */
<ide> protected List<ResearchStaff> externalResearchStaff = new ArrayList<ResearchStaff>();
<ide>
<add> /**
<add> * Instantiates a new research staff.
<add> */
<ide> public ResearchStaff() {
<ide> super();
<ide> }
<ide>
<add> /**
<add> * Gets the external research staff.
<add> *
<add> * @return the external research staff
<add> */
<ide> @Transient
<ide> public List<ResearchStaff> getExternalResearchStaff() {
<ide> return externalResearchStaff;
<ide> }
<ide>
<add> /**
<add> * Sets the external research staff.
<add> *
<add> * @param externalResearchStaff the new external research staff
<add> */
<ide> public void setExternalResearchStaff(List<ResearchStaff> externalResearchStaff) {
<ide> this.externalResearchStaff = externalResearchStaff;
<ide> }
<ide>
<add> /**
<add> * Adds the external research staff.
<add> *
<add> * @param externalResearchStaff the external research staff
<add> */
<ide> public void addExternalResearchStaff(ResearchStaff externalResearchStaff){
<ide> this.getExternalResearchStaff().add(externalResearchStaff);
<ide> }
<ide>
<ide>
<add> /**
<add> * Adds the study personnel.
<add> *
<add> * @param studyPersonnel the study personnel
<add> */
<ide> public void addStudyPersonnel(StudyPersonnel studyPersonnel) {
<ide> getStudyPersonnels().add(studyPersonnel);
<ide> }
<ide>
<ide> // / BEAN METHODS
<ide>
<add> /**
<add> * Gets the study personnels.
<add> *
<add> * @return the study personnels
<add> */
<ide> @OneToMany(mappedBy = "researchStaff")
<ide> @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
<ide> public List<StudyPersonnel> getStudyPersonnels() {
<ide> return studyPersonnels;
<ide> }
<ide>
<add> /**
<add> * Sets the study personnels.
<add> *
<add> * @param studyPersonnels the new study personnels
<add> */
<ide> public void setStudyPersonnels(List<StudyPersonnel> studyPersonnels) {
<ide> this.studyPersonnels = studyPersonnels;
<ide> }
<ide>
<add> /* (non-Javadoc)
<add> * @see edu.duke.cabig.c3pr.domain.Person#getContactMechanisms()
<add> */
<ide> @OneToMany
<ide> @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
<ide> @JoinColumn(name = "RS_ID")
<ide> return contactMechanisms;
<ide> }
<ide>
<add> /* (non-Javadoc)
<add> * @see edu.duke.cabig.c3pr.domain.Person#setContactMechanisms(java.util.List)
<add> */
<ide> public void setContactMechanisms(List<ContactMechanism> contactMechanisms) {
<ide> this.contactMechanisms = contactMechanisms;
<ide> }
<ide>
<add> /**
<add> * Gets the healthcare site.
<add> *
<add> * @return the healthcare site
<add> */
<ide> @ManyToOne
<ide> @JoinColumn(name = "HCS_ID")
<ide> public HealthcareSite getHealthcareSite() {
<ide> return healthcareSite;
<ide> }
<ide>
<add> /**
<add> * Sets the healthcare site.
<add> *
<add> * @param healthcareSite the new healthcare site
<add> */
<ide> public void setHealthcareSite(HealthcareSite healthcareSite) {
<ide> this.healthcareSite = healthcareSite;
<ide> }
<ide>
<add> /**
<add> * Compare to.
<add> *
<add> * @param o the o
<add> *
<add> * @return the int
<add> */
<ide> public int compareTo(Object o) {
<ide> if (this.equals((ResearchStaff) o)) return 0;
<ide> else return 1;
<ide> }
<ide>
<add> /* (non-Javadoc)
<add> * @see edu.duke.cabig.c3pr.domain.Person#hashCode()
<add> */
<ide> @Override
<ide> public int hashCode() {
<ide> final int PRIME = 31;
<ide> return result;
<ide> }
<ide>
<add> /* (non-Javadoc)
<add> * @see edu.duke.cabig.c3pr.domain.Person#equals(java.lang.Object)
<add> */
<ide> @Override
<ide> public boolean equals(Object obj) {
<ide> if (this == obj) return true;
<ide> return true;
<ide> }
<ide>
<add> /**
<add> * Gets the nci identifier.
<add> *
<add> * @return the nci identifier
<add> */
<ide> @RemoteProperty
<ide> public String getNciIdentifier() {
<ide> return nciIdentifier;
<ide> }
<ide>
<add> /**
<add> * Sets the nci identifier.
<add> *
<add> * @param nciIdentifier the new nci identifier
<add> */
<ide> public void setNciIdentifier(String nciIdentifier) {
<ide> this.nciIdentifier = nciIdentifier;
<ide> }
<ide>
<add> /**
<add> * Gets the user based recipient.
<add> *
<add> * @return the user based recipient
<add> */
<ide> @OneToMany
<ide> @Cascade(value = { CascadeType.LOCK})
<ide> @JoinColumn(name = "research_staff_id")
<ide> return userBasedRecipient;
<ide> }
<ide>
<add> /**
<add> * Sets the user based recipient.
<add> *
<add> * @param userBasedRecipient the new user based recipient
<add> */
<ide> public void setUserBasedRecipient(List<UserBasedRecipient> userBasedRecipient) {
<ide> this.userBasedRecipient = userBasedRecipient;
<ide> } |
|
Java | mit | bb7a0358b0d86c653a6706c7e050455d308863e5 | 0 | AlanRosenthal/appinventor-sources,AlanRosenthal/appinventor-sources,AlanRosenthal/appinventor-sources,AlanRosenthal/appinventor-sources,AlanRosenthal/appinventor-sources | package com.google.appinventor.components.runtime;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Handler;
import android.util.Log;
import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.DesignerProperty;
import com.google.appinventor.components.annotations.PropertyCategory;
import com.google.appinventor.components.annotations.SimpleEvent;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.SimpleProperty;
import com.google.appinventor.components.annotations.UsesLibraries;
import com.google.appinventor.components.annotations.UsesPermissions;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.common.PropertyTypeConstants;
import com.google.appinventor.components.common.YaVersion;
import com.google.appinventor.components.runtime.util.AsyncCallbackPair;
import com.google.appinventor.components.runtime.util.AsynchUtil;
import com.google.appinventor.components.runtime.util.YailList;
import edu.uml.cs.isense.api.API;
import edu.uml.cs.isense.objects.RDataSet;
import edu.uml.cs.isense.objects.RPerson;
import edu.uml.cs.isense.objects.RProjectField;
@UsesPermissions(permissionNames = "android.permission.INTERNET")
@UsesLibraries(libraries = "isense.jar, httpmime.jar")
@DesignerComponent(version = YaVersion.ISENSE_PROJECT_VERSION,
description = "A component that provides a high-level interface to iSENSEProject.org",
category = ComponentCategory.SOCIAL,
nonVisible = true,
iconName = "images/isense.png")
@SimpleObject
public class iSENSE extends AndroidNonvisibleComponent implements Component {
private int ProjectID;
private String Email;
private String Password;
private String ContributorKey;
private String YourName;
private API api;
private int LoginType = -1;
private Handler handler;
private boolean InProgress;
public iSENSE(ComponentContainer container) {
super(container.$form());
Log.i("iSENSE", "Starting? " + container.toString());
LoginType(Component.iSENSE_LOGIN_TYPE_EMAIL + "");
api = API.getInstance();
handler = new Handler();
// api.useDev(true);
}
// Block Properties
// ProjectID
@SimpleProperty(description = "iSENSE Project ID", category = PropertyCategory.BEHAVIOR)
public int ProjectID() {
return ProjectID;
}
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING, defaultValue = "")
@SimpleProperty
public void ProjectID(int ProjectID) {
this.ProjectID = ProjectID;
}
// UserName
@SimpleProperty(description = "iSENSE Email", category = PropertyCategory.BEHAVIOR)
public String Email() {
return Email;
}
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING, defaultValue = "")
@SimpleProperty
public void Email(String Email) {
this.Email = Email;
}
// Password
@SimpleProperty(description = "iSENSE Password", category = PropertyCategory.BEHAVIOR)
public String Password() {
return Password;
}
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING, defaultValue = "")
@SimpleProperty
public void Password(String Password) {
this.Password = Password;
}
// Contributor Key
@SimpleProperty(description = "iSENSE Contributor Key", category = PropertyCategory.BEHAVIOR)
public String ContributorKey() {
return ContributorKey;
}
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING, defaultValue = "")
@SimpleProperty
public void ContributorKey(String ContributorKey) {
this.ContributorKey = ContributorKey;
}
// Name
@SimpleProperty(description = "iSENSE Your Name", category = PropertyCategory.BEHAVIOR)
public String YourName() {
return YourName;
}
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING, defaultValue = "")
@SimpleProperty
public void YourName(String YourName) {
this.YourName = YourName;
}
// Login Type
@SimpleProperty(category = PropertyCategory.APPEARANCE,
description = "This selects how you will login to iSENSEProject.org. Either an email or a contributor key")
public int LoginType() {
return LoginType;
}
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_ISENSE_LOGIN_TYPE,
defaultValue = Component.iSENSE_LOGIN_TYPE_EMAIL + "")
@SimpleProperty
public void LoginType(String LoginType) {
this.LoginType = Integer.parseInt(LoginType);
}
// Block Functions
@SimpleFunction(description = "Upload Data Set to iSENSE")
public void UploadDataSet(final String DataSetName, final YailList Fields, final YailList Data) {
AsynchUtil.runAsynchronously(new Runnable() {
public void run() {
// Get fields from project
ArrayList<RProjectField> projectFields = api.getProjectFields(ProjectID);
JSONObject jData = new JSONObject();
for (int i = 0; i < Fields.size(); i++) {
for (int j = 0; j < projectFields.size(); j++) {
if (Fields.get(i + 1).equals(projectFields.get(j).name)) {
try {
String sdata = Data.get(i + 1).toString();
jData.put("" + projectFields.get(j).field_id, new JSONArray().put(sdata));
} catch (JSONException e) {
UploadDataSetResult(-1);
e.printStackTrace();
return;
}
}
}
}
int dataset = -1;
// login with email
if (LoginType == iSENSE_LOGIN_TYPE_EMAIL) {
RPerson user = api.createSession(Email, Password);
if (user == null) {
UploadDataSetResult(-1);
return;
}
dataset = api.uploadDataSet(ProjectID, jData, DataSetName);
// login with contribution key
} else if (LoginType == iSENSE_LOGIN_TYPE_KEY) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd, yyyy HH:mm:ss aaa");
dataset = api.uploadDataSet(ProjectID, DataSetName + " - "
+ sdf.format(cal.getTime()).toString(), jData, ContributorKey, YourName);
}
Log.i("iSENSE", "JSON Upload: " + jData.toString());
Log.i("iSENSE", "Dataset ID: " + dataset);
UploadDataSetResult(dataset);
}
});
}
private void UploadDataSetResult(int dataset) {
AsyncCallbackPair<Integer> myCallback = new AsyncCallbackPair<Integer>() {
public void onSuccess(final Integer result) {
handler.post(new Runnable() {
public void run() {
UploadDataSetSucceeded(result);
}
});
}
public void onFailure(final String message) {
handler.post(new Runnable() {
public void run() {
UploadDataSetFailed();
}
});
}
};
if (dataset == -1) {
myCallback.onFailure("");
} else {
myCallback.onSuccess(dataset);
}
}
@SimpleFunction(description = "Get the Data Sets for the current project")
public YailList GetDataSetsByField(final String Field) {
String FieldID = null;
ArrayList<RDataSet> project_data = api.getDataSets(ProjectID);
ArrayList<RDataSet> rdata = new ArrayList<RDataSet>();
ArrayList<RProjectField> projectFields = api.getProjectFields(ProjectID);
ArrayList<String> fdata = new ArrayList<String>();
for (RProjectField f : projectFields) {
if (f.name.equals(Field)) {
FieldID = f.field_id + "";
}
}
for (RDataSet r : project_data) {
rdata.add(api.getDataSet(r.ds_id));
}
for (RDataSet r : rdata) {
try {
Log.i("iSENSE", "fdata:" + r.data.getString(FieldID));
JSONArray jadata = new JSONArray();
jadata = r.data.getJSONArray(FieldID);
for (int i = 0; i < jadata.length(); i++) {
fdata.add(jadata.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return YailList.makeList(fdata);
}
@SimpleFunction(description = "Gets the current time. It is formated correctly for iSENSE")
public String GetTime() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
return sdf.format(cal.getTime()).toString();
}
// Block Events
@SimpleEvent(description = "iSENSE Upload DataSet Succeeded")
public void UploadDataSetSucceeded(int DataSetID) {
EventDispatcher.dispatchEvent(this, "UploadDataSetSucceeded", DataSetID);
}
@SimpleEvent(description = "iSENSE Upload DataSet Failed")
public void UploadDataSetFailed() {
EventDispatcher.dispatchEvent(this, "UploadDataSetFailed");
}
@SimpleEvent(description = "iSENSE Upload Photo To DataSet Succeeded")
public void UploadPhotoToDataSetSucceeded(int PhotoID) {
EventDispatcher.dispatchEvent(this, "UploadPhotoToDataSetSucceeded", PhotoID);
}
@SimpleEvent(description = "iSENSE Upload Photo To DataSet Failed")
public void UploadPhotoToDataSetFailed() {
EventDispatcher.dispatchEvent(this, "UploadPhotoToDataSetFailed");
}
}
| appinventor/components/src/com/google/appinventor/components/runtime/iSENSE.java | package com.google.appinventor.components.runtime;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Handler;
import android.util.Log;
import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.DesignerProperty;
import com.google.appinventor.components.annotations.PropertyCategory;
import com.google.appinventor.components.annotations.SimpleEvent;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.SimpleProperty;
import com.google.appinventor.components.annotations.UsesLibraries;
import com.google.appinventor.components.annotations.UsesPermissions;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.common.PropertyTypeConstants;
import com.google.appinventor.components.common.YaVersion;
import com.google.appinventor.components.runtime.util.AsyncCallbackPair;
import com.google.appinventor.components.runtime.util.AsynchUtil;
import com.google.appinventor.components.runtime.util.YailList;
import edu.uml.cs.isense.api.API;
import edu.uml.cs.isense.objects.RDataSet;
import edu.uml.cs.isense.objects.RPerson;
import edu.uml.cs.isense.objects.RProjectField;
@UsesPermissions(permissionNames = "android.permission.INTERNET")
@UsesLibraries(libraries = "isense.jar, httpmime.jar")
@DesignerComponent(version = YaVersion.ISENSE_PROJECT_VERSION,
description = "A component that provides a high-level interface to iSENSEProject.org",
category = ComponentCategory.SOCIAL,
nonVisible = true,
iconName = "images/isense.png")
@SimpleObject
public class iSENSE extends AndroidNonvisibleComponent implements Component {
private int ProjectID;
private String Email;
private String Password;
private String ContributorKey;
private String YourName;
private API api;
private int LoginType = -1;
private Handler handler;
private boolean InProgress;
public iSENSE(ComponentContainer container) {
super(container.$form());
Log.i("iSENSE", "Starting? " + container.toString());
LoginType(Component.iSENSE_LOGIN_TYPE_EMAIL + "");
api = API.getInstance();
handler = new Handler();
// api.useDev(true);
}
// Block Properties
// ProjectID
@SimpleProperty(description = "iSENSE Project ID", category = PropertyCategory.BEHAVIOR)
public int ProjectID() {
return ProjectID;
}
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING, defaultValue = "")
@SimpleProperty
public void ProjectID(int ProjectID) {
this.ProjectID = ProjectID;
}
// UserName
@SimpleProperty(description = "iSENSE Email", category = PropertyCategory.BEHAVIOR)
public String Email() {
return Email;
}
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING, defaultValue = "")
@SimpleProperty
public void Email(String Email) {
this.Email = Email;
}
// Password
@SimpleProperty(description = "iSENSE Password", category = PropertyCategory.BEHAVIOR)
public String Password() {
return Password;
}
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING, defaultValue = "")
@SimpleProperty
public void Password(String Password) {
this.Password = Password;
}
// Contributor Key
@SimpleProperty(description = "iSENSE Contributor Key", category = PropertyCategory.BEHAVIOR)
public String ContributorKey() {
return ContributorKey;
}
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING, defaultValue = "")
@SimpleProperty
public void ContributorKey(String ContributorKey) {
this.ContributorKey = ContributorKey;
}
// Name
@SimpleProperty(description = "iSENSE Your Name", category = PropertyCategory.BEHAVIOR)
public String YourName() {
return YourName;
}
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING, defaultValue = "")
@SimpleProperty
public void YourName(String YourName) {
this.YourName = YourName;
}
// Login Type
@SimpleProperty(category = PropertyCategory.APPEARANCE,
description = "This selects how you will login to iSENSEProject.org. Either an email or a contributor key")
public int LoginType() {
return LoginType;
}
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_ISENSE_LOGIN_TYPE,
defaultValue = Component.iSENSE_LOGIN_TYPE_EMAIL + "")
@SimpleProperty
public void LoginType(String LoginType) {
this.LoginType = Integer.parseInt(LoginType);
}
// Block Functions
@SimpleFunction(description = "Upload Data Set to iSENSE")
public void UploadDataSet(final String DataSetName, final YailList Fields, final YailList Data) {
AsynchUtil.runAsynchronously(new Runnable() {
public void run() {
// Get fields from project
ArrayList<RProjectField> projectFields = api.getProjectFields(ProjectID);
JSONObject jData = new JSONObject();
for (int i = 0; i < Fields.size(); i++) {
for (int j = 0; j < projectFields.size(); j++) {
if (Fields.get(i + 1).equals(projectFields.get(j).name)) {
try {
String sdata = SanitizeString(Data.get(i + 1).toString());
jData.put("" + projectFields.get(j).field_id, new JSONArray().put(sdata));
} catch (JSONException e) {
UploadDataSetResult(-1);
e.printStackTrace();
return;
}
}
}
}
int dataset = -1;
// login with email
if (LoginType == iSENSE_LOGIN_TYPE_EMAIL) {
RPerson user = api.createSession(Email, Password);
if (user == null) {
UploadDataSetResult(-1);
return;
}
dataset = api.uploadDataSet(ProjectID, jData, DataSetName);
// login with contribution key
} else if (LoginType == iSENSE_LOGIN_TYPE_KEY) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd, yyyy HH:mm:ss aaa");
dataset = api.uploadDataSet(ProjectID, DataSetName + " - "
+ sdf.format(cal.getTime()).toString(), jData, ContributorKey, YourName);
}
Log.i("iSENSE", "JSON Upload: " + jData.toString());
Log.i("iSENSE", "Dataset ID: " + dataset);
UploadDataSetResult(dataset);
}
});
}
private void UploadDataSetResult(int dataset) {
AsyncCallbackPair<Integer> myCallback = new AsyncCallbackPair<Integer>() {
public void onSuccess(final Integer result) {
handler.post(new Runnable() {
public void run() {
UploadDataSetSucceeded(result);
}
});
}
public void onFailure(final String message) {
handler.post(new Runnable() {
public void run() {
UploadDataSetFailed();
}
});
}
};
if (dataset == -1) {
myCallback.onFailure("");
} else {
myCallback.onSuccess(dataset);
}
}
@SimpleFunction(description = "Get the Data Sets for the current project")
public YailList GetDataSetsByField(final String Field) {
String FieldID = null;
ArrayList<RDataSet> project_data = api.getDataSets(ProjectID);
ArrayList<RDataSet> rdata = new ArrayList<RDataSet>();
ArrayList<RProjectField> projectFields = api.getProjectFields(ProjectID);
ArrayList<String> fdata = new ArrayList<String>();
for (RProjectField f : projectFields) {
if (f.name.equals(Field)) {
FieldID = f.field_id + "";
}
}
for (RDataSet r : project_data) {
rdata.add(api.getDataSet(r.ds_id));
}
for (RDataSet r : rdata) {
try {
Log.i("iSENSE", "fdata:" + r.data.getString(FieldID));
JSONArray jadata = new JSONArray();
jadata = r.data.getJSONArray(FieldID);
for (int i = 0; i < jadata.length(); i++) {
fdata.add(jadata.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return YailList.makeList(fdata);
}
@SimpleFunction(description = "Gets the current time. It is formated correctly for iSENSE")
public String GetTime() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
return sdf.format(cal.getTime()).toString();
}
// Block Events
@SimpleEvent(description = "iSENSE Upload DataSet Succeeded")
public void UploadDataSetSucceeded(int DataSetID) {
EventDispatcher.dispatchEvent(this, "UploadDataSetSucceeded", DataSetID);
}
@SimpleEvent(description = "iSENSE Upload DataSet Failed")
public void UploadDataSetFailed() {
EventDispatcher.dispatchEvent(this, "UploadDataSetFailed");
}
// @SimpleEvent(description = "iSENSE Append DataSet Succeeded")
// public void AppendDataSetSucceeded(int DataSetID) {
// EventDispatcher.dispatchEvent(this, "AppendDataSetSucceeded", DataSetID);
// }
//
// @SimpleEvent(description = "iSENSE Append DataSet Failed")
// public void AppendDataSetFailed() {
// EventDispatcher.dispatchEvent(this, "AppendDataSetFailed");
// }
@SimpleEvent(description = "iSENSE Upload Photo To DataSet Succeeded")
public void UploadPhotoToDataSetSucceeded(int PhotoID) {
EventDispatcher.dispatchEvent(this, "UploadPhotoToDataSetSucceeded", PhotoID);
}
@SimpleEvent(description = "iSENSE Upload Photo To DataSet Failed")
public void UploadPhotoToDataSetFailed() {
EventDispatcher.dispatchEvent(this, "UploadPhotoToDataSetFailed");
}
// Sanitize a string
// fraction gets converted to a number
// string gets returned
private String SanitizeString(final String str) {
return str;
// Log.i("test", "test:" + str);
// Scheme scheme = new Scheme();
// String scheme_str = "(if (number? " + str + ") (exact->inexact " + str + ") \"" + str +
// "\")";
// try {
// return scheme.eval(scheme_str).toString();
// } catch (Throwable e) {
// e.printStackTrace();
// }
// return null;
// }
}
}
| code clean up
| appinventor/components/src/com/google/appinventor/components/runtime/iSENSE.java | code clean up | <ide><path>ppinventor/components/src/com/google/appinventor/components/runtime/iSENSE.java
<ide> for (int j = 0; j < projectFields.size(); j++) {
<ide> if (Fields.get(i + 1).equals(projectFields.get(j).name)) {
<ide> try {
<del> String sdata = SanitizeString(Data.get(i + 1).toString());
<add> String sdata = Data.get(i + 1).toString();
<ide> jData.put("" + projectFields.get(j).field_id, new JSONArray().put(sdata));
<ide> } catch (JSONException e) {
<ide> UploadDataSetResult(-1);
<ide> EventDispatcher.dispatchEvent(this, "UploadDataSetFailed");
<ide> }
<ide>
<del> // @SimpleEvent(description = "iSENSE Append DataSet Succeeded")
<del> // public void AppendDataSetSucceeded(int DataSetID) {
<del> // EventDispatcher.dispatchEvent(this, "AppendDataSetSucceeded", DataSetID);
<del> // }
<del> //
<del> // @SimpleEvent(description = "iSENSE Append DataSet Failed")
<del> // public void AppendDataSetFailed() {
<del> // EventDispatcher.dispatchEvent(this, "AppendDataSetFailed");
<del> // }
<del>
<ide> @SimpleEvent(description = "iSENSE Upload Photo To DataSet Succeeded")
<ide> public void UploadPhotoToDataSetSucceeded(int PhotoID) {
<ide> EventDispatcher.dispatchEvent(this, "UploadPhotoToDataSetSucceeded", PhotoID);
<ide> public void UploadPhotoToDataSetFailed() {
<ide> EventDispatcher.dispatchEvent(this, "UploadPhotoToDataSetFailed");
<ide> }
<del>
<del> // Sanitize a string
<del> // fraction gets converted to a number
<del> // string gets returned
<del> private String SanitizeString(final String str) {
<del> return str;
<del> // Log.i("test", "test:" + str);
<del> // Scheme scheme = new Scheme();
<del> // String scheme_str = "(if (number? " + str + ") (exact->inexact " + str + ") \"" + str +
<del> // "\")";
<del> // try {
<del> // return scheme.eval(scheme_str).toString();
<del> // } catch (Throwable e) {
<del> // e.printStackTrace();
<del> // }
<del> // return null;
<del> // }
<del> }
<ide> } |
|
Java | apache-2.0 | 90b2e46494eea8461523c55fd9cf3fe3d1bf00ce | 0 | apache/commons-io,apache/commons-io,apache/commons-io | /*
* 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.io;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Stack;
/**
* General filename and filepath manipulation utilities.
* <p>
* When dealing with filenames you can hit problems when moving from a Windows
* based development machine to a Unix based production machine.
* This class aims to help avoid those problems.
* <p>
* <b>NOTE</b>: You may be able to avoid using this class entirely simply by
* using JDK {@link java.io.File File} objects and the two argument constructor
* {@link java.io.File#File(java.io.File, java.lang.String) File(File,String)}.
* <p>
* Most methods on this class are designed to work the same on both Unix and Windows.
* Those that don't include 'System', 'Unix' or 'Windows' in their name.
* <p>
* Most methods recognise both separators (forward and back), and both
* sets of prefixes. See the javadoc of each method for details.
* <p>
* This class defines six components within a filename
* (example C:\dev\project\file.txt):
* <ul>
* <li>the prefix - C:\</li>
* <li>the path - dev\project\</li>
* <li>the full path - C:\dev\project\</li>
* <li>the name - file.txt</li>
* <li>the base name - file</li>
* <li>the extension - txt</li>
* </ul>
* Note that this class works best if directory filenames end with a separator.
* If you omit the last separator, it is impossible to determine if the filename
* corresponds to a file or a directory. As a result, we have chosen to say
* it corresponds to a file.
* <p>
* This class only supports Unix and Windows style names.
* Prefixes are matched as follows:
* <pre>
* Windows:
* a\b\c.txt --> "" --> relative
* \a\b\c.txt --> "\" --> current drive absolute
* C:a\b\c.txt --> "C:" --> drive relative
* C:\a\b\c.txt --> "C:\" --> absolute
* \\server\a\b\c.txt --> "\\server\" --> UNC
*
* Unix:
* a/b/c.txt --> "" --> relative
* /a/b/c.txt --> "/" --> absolute
* ~/a/b/c.txt --> "~/" --> current user
* ~ --> "~/" --> current user (slash added)
* ~user/a/b/c.txt --> "~user/" --> named user
* ~user --> "~user/" --> named user (slash added)
* </pre>
* Both prefix styles are matched always, irrespective of the machine that you are
* currently running on.
* <p>
* Origin of code: Excalibur, Alexandria, Tomcat, Commons-Utils.
*
* @since 1.1
*/
public class FilenameUtils {
private static final String EMPTY_STRING = "";
private static final int NOT_FOUND = -1;
/**
* The extension separator character.
* @since 1.4
*/
public static final char EXTENSION_SEPARATOR = '.';
/**
* The extension separator String.
* @since 1.4
*/
public static final String EXTENSION_SEPARATOR_STR = Character.toString(EXTENSION_SEPARATOR);
/**
* The Unix separator character.
*/
private static final char UNIX_SEPARATOR = '/';
/**
* The Windows separator character.
*/
private static final char WINDOWS_SEPARATOR = '\\';
/**
* The system separator character.
*/
private static final char SYSTEM_SEPARATOR = File.separatorChar;
/**
* The separator character that is the opposite of the system separator.
*/
private static final char OTHER_SEPARATOR;
static {
if (isSystemWindows()) {
OTHER_SEPARATOR = UNIX_SEPARATOR;
} else {
OTHER_SEPARATOR = WINDOWS_SEPARATOR;
}
}
/**
* Instances should NOT be constructed in standard programming.
*/
public FilenameUtils() {
super();
}
//-----------------------------------------------------------------------
/**
* Determines if Windows file system is in use.
*
* @return true if the system is Windows
*/
static boolean isSystemWindows() {
return SYSTEM_SEPARATOR == WINDOWS_SEPARATOR;
}
//-----------------------------------------------------------------------
/**
* Checks if the character is a separator.
*
* @param ch the character to check
* @return true if it is a separator character
*/
private static boolean isSeparator(final char ch) {
return ch == UNIX_SEPARATOR || ch == WINDOWS_SEPARATOR;
}
//-----------------------------------------------------------------------
/**
* Normalizes a path, removing double and single dot path steps.
* <p>
* This method normalizes a path to a standard format.
* The input may contain separators in either Unix or Windows format.
* The output will contain separators in the format of the system.
* <p>
* A trailing slash will be retained.
* A double slash will be merged to a single slash (but UNC names are handled).
* A single dot path segment will be removed.
* A double dot will cause that path segment and the one before to be removed.
* If the double dot has no parent path segment to work with, {@code null}
* is returned.
* <p>
* The output will be the same on both Unix and Windows except
* for the separator character.
* <pre>
* /foo// --> /foo/
* /foo/./ --> /foo/
* /foo/../bar --> /bar
* /foo/../bar/ --> /bar/
* /foo/../bar/../baz --> /baz
* //foo//./bar --> /foo/bar
* /../ --> null
* ../foo --> null
* foo/bar/.. --> foo/
* foo/../../bar --> null
* foo/../bar --> bar
* //server/foo/../bar --> //server/bar
* //server/../bar --> null
* C:\foo\..\bar --> C:\bar
* C:\..\bar --> null
* ~/foo/../bar/ --> ~/bar/
* ~/../bar --> null
* </pre>
* (Note the file separator returned will be correct for Windows/Unix)
*
* @param filename the filename to normalize, null returns null
* @return the normalized filename, or null if invalid. Null bytes inside string will be removed
*/
public static String normalize(final String filename) {
return doNormalize(filename, SYSTEM_SEPARATOR, true);
}
/**
* Normalizes a path, removing double and single dot path steps.
* <p>
* This method normalizes a path to a standard format.
* The input may contain separators in either Unix or Windows format.
* The output will contain separators in the format specified.
* <p>
* A trailing slash will be retained.
* A double slash will be merged to a single slash (but UNC names are handled).
* A single dot path segment will be removed.
* A double dot will cause that path segment and the one before to be removed.
* If the double dot has no parent path segment to work with, {@code null}
* is returned.
* <p>
* The output will be the same on both Unix and Windows except
* for the separator character.
* <pre>
* /foo// --> /foo/
* /foo/./ --> /foo/
* /foo/../bar --> /bar
* /foo/../bar/ --> /bar/
* /foo/../bar/../baz --> /baz
* //foo//./bar --> /foo/bar
* /../ --> null
* ../foo --> null
* foo/bar/.. --> foo/
* foo/../../bar --> null
* foo/../bar --> bar
* //server/foo/../bar --> //server/bar
* //server/../bar --> null
* C:\foo\..\bar --> C:\bar
* C:\..\bar --> null
* ~/foo/../bar/ --> ~/bar/
* ~/../bar --> null
* </pre>
* The output will be the same on both Unix and Windows including
* the separator character.
*
* @param filename the filename to normalize, null returns null
* @param unixSeparator {@code true} if a unix separator should
* be used or {@code false} if a windows separator should be used.
* @return the normalized filename, or null if invalid. Null bytes inside string will be removed
* @since 2.0
*/
public static String normalize(final String filename, final boolean unixSeparator) {
final char separator = unixSeparator ? UNIX_SEPARATOR : WINDOWS_SEPARATOR;
return doNormalize(filename, separator, true);
}
//-----------------------------------------------------------------------
/**
* Normalizes a path, removing double and single dot path steps,
* and removing any final directory separator.
* <p>
* This method normalizes a path to a standard format.
* The input may contain separators in either Unix or Windows format.
* The output will contain separators in the format of the system.
* <p>
* A trailing slash will be removed.
* A double slash will be merged to a single slash (but UNC names are handled).
* A single dot path segment will be removed.
* A double dot will cause that path segment and the one before to be removed.
* If the double dot has no parent path segment to work with, {@code null}
* is returned.
* <p>
* The output will be the same on both Unix and Windows except
* for the separator character.
* <pre>
* /foo// --> /foo
* /foo/./ --> /foo
* /foo/../bar --> /bar
* /foo/../bar/ --> /bar
* /foo/../bar/../baz --> /baz
* //foo//./bar --> /foo/bar
* /../ --> null
* ../foo --> null
* foo/bar/.. --> foo
* foo/../../bar --> null
* foo/../bar --> bar
* //server/foo/../bar --> //server/bar
* //server/../bar --> null
* C:\foo\..\bar --> C:\bar
* C:\..\bar --> null
* ~/foo/../bar/ --> ~/bar
* ~/../bar --> null
* </pre>
* (Note the file separator returned will be correct for Windows/Unix)
*
* @param filename the filename to normalize, null returns null
* @return the normalized filename, or null if invalid. Null bytes inside string will be removed
*/
public static String normalizeNoEndSeparator(final String filename) {
return doNormalize(filename, SYSTEM_SEPARATOR, false);
}
/**
* Normalizes a path, removing double and single dot path steps,
* and removing any final directory separator.
* <p>
* This method normalizes a path to a standard format.
* The input may contain separators in either Unix or Windows format.
* The output will contain separators in the format specified.
* <p>
* A trailing slash will be removed.
* A double slash will be merged to a single slash (but UNC names are handled).
* A single dot path segment will be removed.
* A double dot will cause that path segment and the one before to be removed.
* If the double dot has no parent path segment to work with, {@code null}
* is returned.
* <p>
* The output will be the same on both Unix and Windows including
* the separator character.
* <pre>
* /foo// --> /foo
* /foo/./ --> /foo
* /foo/../bar --> /bar
* /foo/../bar/ --> /bar
* /foo/../bar/../baz --> /baz
* //foo//./bar --> /foo/bar
* /../ --> null
* ../foo --> null
* foo/bar/.. --> foo
* foo/../../bar --> null
* foo/../bar --> bar
* //server/foo/../bar --> //server/bar
* //server/../bar --> null
* C:\foo\..\bar --> C:\bar
* C:\..\bar --> null
* ~/foo/../bar/ --> ~/bar
* ~/../bar --> null
* </pre>
*
* @param filename the filename to normalize, null returns null
* @param unixSeparator {@code true} if a unix separator should
* be used or {@code false} if a windows separator should be used.
* @return the normalized filename, or null if invalid. Null bytes inside string will be removed
* @since 2.0
*/
public static String normalizeNoEndSeparator(final String filename, final boolean unixSeparator) {
final char separator = unixSeparator ? UNIX_SEPARATOR : WINDOWS_SEPARATOR;
return doNormalize(filename, separator, false);
}
/**
* Internal method to perform the normalization.
*
* @param filename the filename
* @param separator The separator character to use
* @param keepSeparator true to keep the final separator
* @return the normalized filename. Null bytes inside string will be removed.
*/
private static String doNormalize(final String filename, final char separator, final boolean keepSeparator) {
if (filename == null) {
return null;
}
failIfNullBytePresent(filename);
int size = filename.length();
if (size == 0) {
return filename;
}
final int prefix = getPrefixLength(filename);
if (prefix < 0) {
return null;
}
final char[] array = new char[size + 2]; // +1 for possible extra slash, +2 for arraycopy
filename.getChars(0, filename.length(), array, 0);
// fix separators throughout
final char otherSeparator = separator == SYSTEM_SEPARATOR ? OTHER_SEPARATOR : SYSTEM_SEPARATOR;
for (int i = 0; i < array.length; i++) {
if (array[i] == otherSeparator) {
array[i] = separator;
}
}
// add extra separator on the end to simplify code below
boolean lastIsDirectory = true;
if (array[size - 1] != separator) {
array[size++] = separator;
lastIsDirectory = false;
}
// adjoining slashes
for (int i = prefix + 1; i < size; i++) {
if (array[i] == separator && array[i - 1] == separator) {
System.arraycopy(array, i, array, i - 1, size - i);
size--;
i--;
}
}
// dot slash
for (int i = prefix + 1; i < size; i++) {
if (array[i] == separator && array[i - 1] == '.' &&
(i == prefix + 1 || array[i - 2] == separator)) {
if (i == size - 1) {
lastIsDirectory = true;
}
System.arraycopy(array, i + 1, array, i - 1, size - i);
size -=2;
i--;
}
}
// double dot slash
outer:
for (int i = prefix + 2; i < size; i++) {
if (array[i] == separator && array[i - 1] == '.' && array[i - 2] == '.' &&
(i == prefix + 2 || array[i - 3] == separator)) {
if (i == prefix + 2) {
return null;
}
if (i == size - 1) {
lastIsDirectory = true;
}
int j;
for (j = i - 4 ; j >= prefix; j--) {
if (array[j] == separator) {
// remove b/../ from a/b/../c
System.arraycopy(array, i + 1, array, j + 1, size - i);
size -= i - j;
i = j + 1;
continue outer;
}
}
// remove a/../ from a/../c
System.arraycopy(array, i + 1, array, prefix, size - i);
size -= i + 1 - prefix;
i = prefix + 1;
}
}
if (size <= 0) { // should never be less than 0
return EMPTY_STRING;
}
if (size <= prefix) { // should never be less than prefix
return new String(array, 0, size);
}
if (lastIsDirectory && keepSeparator) {
return new String(array, 0, size); // keep trailing separator
}
return new String(array, 0, size - 1); // lose trailing separator
}
//-----------------------------------------------------------------------
/**
* Concatenates a filename to a base path using normal command line style rules.
* <p>
* The effect is equivalent to resultant directory after changing
* directory to the first argument, followed by changing directory to
* the second argument.
* <p>
* The first argument is the base path, the second is the path to concatenate.
* The returned path is always normalized via {@link #normalize(String)},
* thus <code>..</code> is handled.
* <p>
* If <code>pathToAdd</code> is absolute (has an absolute prefix), then
* it will be normalized and returned.
* Otherwise, the paths will be joined, normalized and returned.
* <p>
* The output will be the same on both Unix and Windows except
* for the separator character.
* <pre>
* /foo/ + bar --> /foo/bar
* /foo + bar --> /foo/bar
* /foo + /bar --> /bar
* /foo + C:/bar --> C:/bar
* /foo + C:bar --> C:bar (*)
* /foo/a/ + ../bar --> foo/bar
* /foo/ + ../../bar --> null
* /foo/ + /bar --> /bar
* /foo/.. + /bar --> /bar
* /foo + bar/c.txt --> /foo/bar/c.txt
* /foo/c.txt + bar --> /foo/c.txt/bar (!)
* </pre>
* (*) Note that the Windows relative drive prefix is unreliable when
* used with this method.
* (!) Note that the first parameter must be a path. If it ends with a name, then
* the name will be built into the concatenated path. If this might be a problem,
* use {@link #getFullPath(String)} on the base path argument.
*
* @param basePath the base path to attach to, always treated as a path
* @param fullFilenameToAdd the filename (or path) to attach to the base
* @return the concatenated path, or null if invalid. Null bytes inside string will be removed
*/
public static String concat(final String basePath, final String fullFilenameToAdd) {
final int prefix = getPrefixLength(fullFilenameToAdd);
if (prefix < 0) {
return null;
}
if (prefix > 0) {
return normalize(fullFilenameToAdd);
}
if (basePath == null) {
return null;
}
final int len = basePath.length();
if (len == 0) {
return normalize(fullFilenameToAdd);
}
final char ch = basePath.charAt(len - 1);
if (isSeparator(ch)) {
return normalize(basePath + fullFilenameToAdd);
}
return normalize(basePath + '/' + fullFilenameToAdd);
}
/**
* Determines whether the {@code parent} directory contains the {@code child} element (a file or directory).
* <p>
* The files names are expected to be normalized.
* </p>
*
* Edge cases:
* <ul>
* <li>A {@code directory} must not be null: if null, throw IllegalArgumentException</li>
* <li>A directory does not contain itself: return false</li>
* <li>A null child file is not contained in any parent: return false</li>
* </ul>
*
* @param canonicalParent
* the file to consider as the parent.
* @param canonicalChild
* the file to consider as the child.
* @return true is the candidate leaf is under by the specified composite. False otherwise.
* @throws IOException
* if an IO error occurs while checking the files.
* @since 2.2
* @see FileUtils#directoryContains(File, File)
*/
public static boolean directoryContains(final String canonicalParent, final String canonicalChild)
throws IOException {
// Fail fast against NullPointerException
if (canonicalParent == null) {
throw new IllegalArgumentException("Directory must not be null");
}
if (canonicalChild == null) {
return false;
}
if (IOCase.SYSTEM.checkEquals(canonicalParent, canonicalChild)) {
return false;
}
return IOCase.SYSTEM.checkStartsWith(canonicalChild, canonicalParent);
}
//-----------------------------------------------------------------------
/**
* Converts all separators to the Unix separator of forward slash.
*
* @param path the path to be changed, null ignored
* @return the updated path
*/
public static String separatorsToUnix(final String path) {
if (path == null || path.indexOf(WINDOWS_SEPARATOR) == NOT_FOUND) {
return path;
}
return path.replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR);
}
/**
* Converts all separators to the Windows separator of backslash.
*
* @param path the path to be changed, null ignored
* @return the updated path
*/
public static String separatorsToWindows(final String path) {
if (path == null || path.indexOf(UNIX_SEPARATOR) == NOT_FOUND) {
return path;
}
return path.replace(UNIX_SEPARATOR, WINDOWS_SEPARATOR);
}
/**
* Converts all separators to the system separator.
*
* @param path the path to be changed, null ignored
* @return the updated path
*/
public static String separatorsToSystem(final String path) {
if (path == null) {
return null;
}
return isSystemWindows() ? separatorsToWindows(path) : separatorsToUnix(path);
}
//-----------------------------------------------------------------------
/**
* Returns the length of the filename prefix, such as <code>C:/</code> or <code>~/</code>.
* <p>
* This method will handle a file in either Unix or Windows format.
* <p>
* The prefix length includes the first slash in the full filename
* if applicable. Thus, it is possible that the length returned is greater
* than the length of the input string.
* <pre>
* Windows:
* a\b\c.txt --> "" --> relative
* \a\b\c.txt --> "\" --> current drive absolute
* C:a\b\c.txt --> "C:" --> drive relative
* C:\a\b\c.txt --> "C:\" --> absolute
* \\server\a\b\c.txt --> "\\server\" --> UNC
* \\\a\b\c.txt --> error, length = -1
*
* Unix:
* a/b/c.txt --> "" --> relative
* /a/b/c.txt --> "/" --> absolute
* ~/a/b/c.txt --> "~/" --> current user
* ~ --> "~/" --> current user (slash added)
* ~user/a/b/c.txt --> "~user/" --> named user
* ~user --> "~user/" --> named user (slash added)
* //server/a/b/c.txt --> "//server/"
* ///a/b/c.txt --> error, length = -1
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on.
* ie. both Unix and Windows prefixes are matched regardless.
*
* Note that a leading // (or \\) is used to indicate a UNC name on Windows.
* These must be followed by a server name, so double-slashes are not collapsed
* to a single slash at the start of the filename.
*
* @param filename the filename to find the prefix in, null returns -1
* @return the length of the prefix, -1 if invalid or null
*/
public static int getPrefixLength(final String filename) {
if (filename == null) {
return NOT_FOUND;
}
final int len = filename.length();
if (len == 0) {
return 0;
}
char ch0 = filename.charAt(0);
if (ch0 == ':') {
return NOT_FOUND;
}
if (len == 1) {
if (ch0 == '~') {
return 2; // return a length greater than the input
}
return isSeparator(ch0) ? 1 : 0;
}
if (ch0 == '~') {
int posUnix = filename.indexOf(UNIX_SEPARATOR, 1);
int posWin = filename.indexOf(WINDOWS_SEPARATOR, 1);
if (posUnix == NOT_FOUND && posWin == NOT_FOUND) {
return len + 1; // return a length greater than the input
}
posUnix = posUnix == NOT_FOUND ? posWin : posUnix;
posWin = posWin == NOT_FOUND ? posUnix : posWin;
return Math.min(posUnix, posWin) + 1;
}
final char ch1 = filename.charAt(1);
if (ch1 == ':') {
ch0 = Character.toUpperCase(ch0);
if (ch0 >= 'A' && ch0 <= 'Z') {
if (len == 2 || isSeparator(filename.charAt(2)) == false) {
return 2;
}
return 3;
} else if (ch0 == UNIX_SEPARATOR) {
return 1;
}
return NOT_FOUND;
} else if (isSeparator(ch0) && isSeparator(ch1)) {
int posUnix = filename.indexOf(UNIX_SEPARATOR, 2);
int posWin = filename.indexOf(WINDOWS_SEPARATOR, 2);
if (posUnix == NOT_FOUND && posWin == NOT_FOUND || posUnix == 2 || posWin == 2) {
return NOT_FOUND;
}
posUnix = posUnix == NOT_FOUND ? posWin : posUnix;
posWin = posWin == NOT_FOUND ? posUnix : posWin;
return Math.min(posUnix, posWin) + 1;
} else {
return isSeparator(ch0) ? 1 : 0;
}
}
/**
* Returns the index of the last directory separator character.
* <p>
* This method will handle a file in either Unix or Windows format.
* The position of the last forward or backslash is returned.
* <p>
* The output will be the same irrespective of the machine that the code is running on.
*
* @param filename the filename to find the last path separator in, null returns -1
* @return the index of the last separator character, or -1 if there
* is no such character
*/
public static int indexOfLastSeparator(final String filename) {
if (filename == null) {
return NOT_FOUND;
}
final int lastUnixPos = filename.lastIndexOf(UNIX_SEPARATOR);
final int lastWindowsPos = filename.lastIndexOf(WINDOWS_SEPARATOR);
return Math.max(lastUnixPos, lastWindowsPos);
}
/**
* Returns the index of the last extension separator character, which is a dot.
* <p>
* This method also checks that there is no directory separator after the last dot. To do this it uses
* {@link #indexOfLastSeparator(String)} which will handle a file in either Unix or Windows format.
* </p>
* <p>
* The output will be the same irrespective of the machine that the code is running on, with the
* exception of a possible {@link IllegalArgumentException} on Windows (see below).
* </p>
* <b>Note:</b> This method used to have a hidden problem for names like "foo.exe:bar.txt".
* In this case, the name wouldn't be the name of a file, but the identifier of an
* alternate data stream (bar.txt) on the file foo.exe. The method used to return
* ".txt" here, which would be misleading. Commons IO 2.7, and later versions, are throwing
* an {@link IllegalArgumentException} for names like this.
*
* @param filename
* the filename to find the last extension separator in, null returns -1
* @return the index of the last extension separator character, or -1 if there is no such character
* @throws IllegalArgumentException <b>Windows only:</b> The filename parameter is, in fact,
* the identifier of an Alternate Data Stream, for example "foo.exe:bar.txt".
*/
public static int indexOfExtension(final String filename) throws IllegalArgumentException {
if (filename == null) {
return NOT_FOUND;
}
if (isSystemWindows()) {
// Special handling for NTFS ADS: Don't accept colon in the filename.
final int offset = filename.indexOf(':', getAdsCriticalOffset(filename));
if (offset != -1) {
throw new IllegalArgumentException("NTFS ADS separator (':') in filename is forbidden.");
}
}
final int extensionPos = filename.lastIndexOf(EXTENSION_SEPARATOR);
final int lastSeparator = indexOfLastSeparator(filename);
return lastSeparator > extensionPos ? NOT_FOUND : extensionPos;
}
//-----------------------------------------------------------------------
/**
* Gets the prefix from a full filename, such as <code>C:/</code>
* or <code>~/</code>.
* <p>
* This method will handle a file in either Unix or Windows format.
* The prefix includes the first slash in the full filename where applicable.
* <pre>
* Windows:
* a\b\c.txt --> "" --> relative
* \a\b\c.txt --> "\" --> current drive absolute
* C:a\b\c.txt --> "C:" --> drive relative
* C:\a\b\c.txt --> "C:\" --> absolute
* \\server\a\b\c.txt --> "\\server\" --> UNC
*
* Unix:
* a/b/c.txt --> "" --> relative
* /a/b/c.txt --> "/" --> absolute
* ~/a/b/c.txt --> "~/" --> current user
* ~ --> "~/" --> current user (slash added)
* ~user/a/b/c.txt --> "~user/" --> named user
* ~user --> "~user/" --> named user (slash added)
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on.
* ie. both Unix and Windows prefixes are matched regardless.
*
* @param filename the filename to query, null returns null
* @return the prefix of the file, null if invalid. Null bytes inside string will be removed
*/
public static String getPrefix(final String filename) {
if (filename == null) {
return null;
}
final int len = getPrefixLength(filename);
if (len < 0) {
return null;
}
if (len > filename.length()) {
failIfNullBytePresent(filename + UNIX_SEPARATOR);
return filename + UNIX_SEPARATOR;
}
final String path = filename.substring(0, len);
failIfNullBytePresent(path);
return path;
}
/**
* Gets the path from a full filename, which excludes the prefix.
* <p>
* This method will handle a file in either Unix or Windows format.
* The method is entirely text based, and returns the text before and
* including the last forward or backslash.
* <pre>
* C:\a\b\c.txt --> a\b\
* ~/a/b/c.txt --> a/b/
* a.txt --> ""
* a/b/c --> a/b/
* a/b/c/ --> a/b/c/
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on.
* <p>
* This method drops the prefix from the result.
* See {@link #getFullPath(String)} for the method that retains the prefix.
*
* @param filename the filename to query, null returns null
* @return the path of the file, an empty string if none exists, null if invalid.
* Null bytes inside string will be removed
*/
public static String getPath(final String filename) {
return doGetPath(filename, 1);
}
/**
* Gets the path from a full filename, which excludes the prefix, and
* also excluding the final directory separator.
* <p>
* This method will handle a file in either Unix or Windows format.
* The method is entirely text based, and returns the text before the
* last forward or backslash.
* <pre>
* C:\a\b\c.txt --> a\b
* ~/a/b/c.txt --> a/b
* a.txt --> ""
* a/b/c --> a/b
* a/b/c/ --> a/b/c
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on.
* <p>
* This method drops the prefix from the result.
* See {@link #getFullPathNoEndSeparator(String)} for the method that retains the prefix.
*
* @param filename the filename to query, null returns null
* @return the path of the file, an empty string if none exists, null if invalid.
* Null bytes inside string will be removed
*/
public static String getPathNoEndSeparator(final String filename) {
return doGetPath(filename, 0);
}
/**
* Does the work of getting the path.
*
* @param filename the filename
* @param separatorAdd 0 to omit the end separator, 1 to return it
* @return the path. Null bytes inside string will be removed
*/
private static String doGetPath(final String filename, final int separatorAdd) {
if (filename == null) {
return null;
}
final int prefix = getPrefixLength(filename);
if (prefix < 0) {
return null;
}
final int index = indexOfLastSeparator(filename);
final int endIndex = index+separatorAdd;
if (prefix >= filename.length() || index < 0 || prefix >= endIndex) {
return EMPTY_STRING;
}
final String path = filename.substring(prefix, endIndex);
failIfNullBytePresent(path);
return path;
}
/**
* Gets the full path from a full filename, which is the prefix + path.
* <p>
* This method will handle a file in either Unix or Windows format.
* The method is entirely text based, and returns the text before and
* including the last forward or backslash.
* <pre>
* C:\a\b\c.txt --> C:\a\b\
* ~/a/b/c.txt --> ~/a/b/
* a.txt --> ""
* a/b/c --> a/b/
* a/b/c/ --> a/b/c/
* C: --> C:
* C:\ --> C:\
* ~ --> ~/
* ~/ --> ~/
* ~user --> ~user/
* ~user/ --> ~user/
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on.
*
* @param filename the filename to query, null returns null
* @return the path of the file, an empty string if none exists, null if invalid
*/
public static String getFullPath(final String filename) {
return doGetFullPath(filename, true);
}
/**
* Gets the full path from a full filename, which is the prefix + path,
* and also excluding the final directory separator.
* <p>
* This method will handle a file in either Unix or Windows format.
* The method is entirely text based, and returns the text before the
* last forward or backslash.
* <pre>
* C:\a\b\c.txt --> C:\a\b
* ~/a/b/c.txt --> ~/a/b
* a.txt --> ""
* a/b/c --> a/b
* a/b/c/ --> a/b/c
* C: --> C:
* C:\ --> C:\
* ~ --> ~
* ~/ --> ~
* ~user --> ~user
* ~user/ --> ~user
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on.
*
* @param filename the filename to query, null returns null
* @return the path of the file, an empty string if none exists, null if invalid
*/
public static String getFullPathNoEndSeparator(final String filename) {
return doGetFullPath(filename, false);
}
/**
* Does the work of getting the path.
*
* @param filename the filename
* @param includeSeparator true to include the end separator
* @return the path
*/
private static String doGetFullPath(final String filename, final boolean includeSeparator) {
if (filename == null) {
return null;
}
final int prefix = getPrefixLength(filename);
if (prefix < 0) {
return null;
}
if (prefix >= filename.length()) {
if (includeSeparator) {
return getPrefix(filename); // add end slash if necessary
}
return filename;
}
final int index = indexOfLastSeparator(filename);
if (index < 0) {
return filename.substring(0, prefix);
}
int end = index + (includeSeparator ? 1 : 0);
if (end == 0) {
end++;
}
return filename.substring(0, end);
}
/**
* Gets the name minus the path from a full filename.
* <p>
* This method will handle a file in either Unix or Windows format.
* The text after the last forward or backslash is returned.
* <pre>
* a/b/c.txt --> c.txt
* a.txt --> a.txt
* a/b/c --> c
* a/b/c/ --> ""
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on.
*
* @param filename the filename to query, null returns null
* @return the name of the file without the path, or an empty string if none exists.
* Null bytes inside string will be removed
*/
public static String getName(final String filename) {
if (filename == null) {
return null;
}
failIfNullBytePresent(filename);
final int index = indexOfLastSeparator(filename);
return filename.substring(index + 1);
}
/**
* Check the input for null bytes, a sign of unsanitized data being passed to to file level functions.
*
* This may be used for poison byte attacks.
* @param path the path to check
*/
private static void failIfNullBytePresent(final String path) {
final int len = path.length();
for (int i = 0; i < len; i++) {
if (path.charAt(i) == 0) {
throw new IllegalArgumentException("Null byte present in file/path name. There are no " +
"known legitimate use cases for such data, but several injection attacks may use it");
}
}
}
/**
* Gets the base name, minus the full path and extension, from a full filename.
* <p>
* This method will handle a file in either Unix or Windows format.
* The text after the last forward or backslash and before the last dot is returned.
* <pre>
* a/b/c.txt --> c
* a.txt --> a
* a/b/c --> c
* a/b/c/ --> ""
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on.
*
* @param filename the filename to query, null returns null
* @return the name of the file without the path, or an empty string if none exists. Null bytes inside string
* will be removed
*/
public static String getBaseName(final String filename) {
return removeExtension(getName(filename));
}
/**
* Gets the extension of a filename.
* <p>
* This method returns the textual part of the filename after the last dot.
* There must be no directory separator after the dot.
* <pre>
* foo.txt --> "txt"
* a/b/c.jpg --> "jpg"
* a/b.txt/c --> ""
* a/b/c --> ""
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on, with the
* exception of a possible {@link IllegalArgumentException} on Windows (see below).
* </p>
* <p>
* <b>Note:</b> This method used to have a hidden problem for names like "foo.exe:bar.txt".
* In this case, the name wouldn't be the name of a file, but the identifier of an
* alternate data stream (bar.txt) on the file foo.exe. The method used to return
* ".txt" here, which would be misleading. Commons IO 2.7, and later versions, are throwing
* an {@link IllegalArgumentException} for names like this.
*
* @param filename the filename to retrieve the extension of.
* @return the extension of the file or an empty string if none exists or {@code null}
* if the filename is {@code null}.
* @throws IllegalArgumentException <b>Windows only:</b> The filename parameter is, in fact,
* the identifier of an Alternate Data Stream, for example "foo.exe:bar.txt".
*/
public static String getExtension(final String filename) throws IllegalArgumentException {
if (filename == null) {
return null;
}
final int index = indexOfExtension(filename);
if (index == NOT_FOUND) {
return EMPTY_STRING;
}
return filename.substring(index + 1);
}
/**
* Special handling for NTFS ADS: Don't accept colon in the filename.
*
* @param filename a file name
* @return ADS offsets.
*/
private static int getAdsCriticalOffset(String filename) {
// Step 1: Remove leading path segments.
int offset1 = filename.lastIndexOf(SYSTEM_SEPARATOR);
int offset2 = filename.lastIndexOf(OTHER_SEPARATOR);
if (offset1 == -1) {
if (offset2 == -1) {
return 0;
}
return offset2 + 1;
}
if (offset2 == -1) {
return offset1 + 1;
}
return Math.max(offset1, offset2) + 1;
}
//-----------------------------------------------------------------------
/**
* Removes the extension from a filename.
* <p>
* This method returns the textual part of the filename before the last dot.
* There must be no directory separator after the dot.
* <pre>
* foo.txt --> foo
* a\b\c.jpg --> a\b\c
* a\b\c --> a\b\c
* a.b\c --> a.b\c
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on.
*
* @param filename the filename to query, null returns null
* @return the filename minus the extension
*/
public static String removeExtension(final String filename) {
if (filename == null) {
return null;
}
failIfNullBytePresent(filename);
final int index = indexOfExtension(filename);
if (index == NOT_FOUND) {
return filename;
}
return filename.substring(0, index);
}
//-----------------------------------------------------------------------
/**
* Checks whether two filenames are equal exactly.
* <p>
* No processing is performed on the filenames other than comparison,
* thus this is merely a null-safe case-sensitive equals.
*
* @param filename1 the first filename to query, may be null
* @param filename2 the second filename to query, may be null
* @return true if the filenames are equal, null equals null
* @see IOCase#SENSITIVE
*/
public static boolean equals(final String filename1, final String filename2) {
return equals(filename1, filename2, false, IOCase.SENSITIVE);
}
/**
* Checks whether two filenames are equal using the case rules of the system.
* <p>
* No processing is performed on the filenames other than comparison.
* The check is case-sensitive on Unix and case-insensitive on Windows.
*
* @param filename1 the first filename to query, may be null
* @param filename2 the second filename to query, may be null
* @return true if the filenames are equal, null equals null
* @see IOCase#SYSTEM
*/
public static boolean equalsOnSystem(final String filename1, final String filename2) {
return equals(filename1, filename2, false, IOCase.SYSTEM);
}
//-----------------------------------------------------------------------
/**
* Checks whether two filenames are equal after both have been normalized.
* <p>
* Both filenames are first passed to {@link #normalize(String)}.
* The check is then performed in a case-sensitive manner.
*
* @param filename1 the first filename to query, may be null
* @param filename2 the second filename to query, may be null
* @return true if the filenames are equal, null equals null
* @see IOCase#SENSITIVE
*/
public static boolean equalsNormalized(final String filename1, final String filename2) {
return equals(filename1, filename2, true, IOCase.SENSITIVE);
}
/**
* Checks whether two filenames are equal after both have been normalized
* and using the case rules of the system.
* <p>
* Both filenames are first passed to {@link #normalize(String)}.
* The check is then performed case-sensitive on Unix and
* case-insensitive on Windows.
*
* @param filename1 the first filename to query, may be null
* @param filename2 the second filename to query, may be null
* @return true if the filenames are equal, null equals null
* @see IOCase#SYSTEM
*/
public static boolean equalsNormalizedOnSystem(final String filename1, final String filename2) {
return equals(filename1, filename2, true, IOCase.SYSTEM);
}
/**
* Checks whether two filenames are equal, optionally normalizing and providing
* control over the case-sensitivity.
*
* @param filename1 the first filename to query, may be null
* @param filename2 the second filename to query, may be null
* @param normalized whether to normalize the filenames
* @param caseSensitivity what case sensitivity rule to use, null means case-sensitive
* @return true if the filenames are equal, null equals null
* @since 1.3
*/
public static boolean equals(
String filename1, String filename2,
final boolean normalized, IOCase caseSensitivity) {
if (filename1 == null || filename2 == null) {
return filename1 == null && filename2 == null;
}
if (normalized) {
filename1 = normalize(filename1);
filename2 = normalize(filename2);
if (filename1 == null || filename2 == null) {
throw new NullPointerException(
"Error normalizing one or both of the file names");
}
}
if (caseSensitivity == null) {
caseSensitivity = IOCase.SENSITIVE;
}
return caseSensitivity.checkEquals(filename1, filename2);
}
//-----------------------------------------------------------------------
/**
* Checks whether the extension of the filename is that specified.
* <p>
* This method obtains the extension as the textual part of the filename
* after the last dot. There must be no directory separator after the dot.
* The extension check is case-sensitive on all platforms.
*
* @param filename the filename to query, null returns false
* @param extension the extension to check for, null or empty checks for no extension
* @return true if the filename has the specified extension
* @throws java.lang.IllegalArgumentException if the supplied filename contains null bytes
*/
public static boolean isExtension(final String filename, final String extension) {
if (filename == null) {
return false;
}
failIfNullBytePresent(filename);
if (extension == null || extension.isEmpty()) {
return indexOfExtension(filename) == NOT_FOUND;
}
final String fileExt = getExtension(filename);
return fileExt.equals(extension);
}
/**
* Checks whether the extension of the filename is one of those specified.
* <p>
* This method obtains the extension as the textual part of the filename
* after the last dot. There must be no directory separator after the dot.
* The extension check is case-sensitive on all platforms.
*
* @param filename the filename to query, null returns false
* @param extensions the extensions to check for, null checks for no extension
* @return true if the filename is one of the extensions
* @throws java.lang.IllegalArgumentException if the supplied filename contains null bytes
*/
public static boolean isExtension(final String filename, final String[] extensions) {
if (filename == null) {
return false;
}
failIfNullBytePresent(filename);
if (extensions == null || extensions.length == 0) {
return indexOfExtension(filename) == NOT_FOUND;
}
final String fileExt = getExtension(filename);
for (final String extension : extensions) {
if (fileExt.equals(extension)) {
return true;
}
}
return false;
}
/**
* Checks whether the extension of the filename is one of those specified.
* <p>
* This method obtains the extension as the textual part of the filename
* after the last dot. There must be no directory separator after the dot.
* The extension check is case-sensitive on all platforms.
*
* @param filename the filename to query, null returns false
* @param extensions the extensions to check for, null checks for no extension
* @return true if the filename is one of the extensions
* @throws java.lang.IllegalArgumentException if the supplied filename contains null bytes
*/
public static boolean isExtension(final String filename, final Collection<String> extensions) {
if (filename == null) {
return false;
}
failIfNullBytePresent(filename);
if (extensions == null || extensions.isEmpty()) {
return indexOfExtension(filename) == NOT_FOUND;
}
final String fileExt = getExtension(filename);
for (final String extension : extensions) {
if (fileExt.equals(extension)) {
return true;
}
}
return false;
}
//-----------------------------------------------------------------------
/**
* Checks a filename to see if it matches the specified wildcard matcher,
* always testing case-sensitive.
* <p>
* The wildcard matcher uses the characters '?' and '*' to represent a
* single or multiple (zero or more) wildcard characters.
* This is the same as often found on Dos/Unix command lines.
* The check is case-sensitive always.
* <pre>
* wildcardMatch("c.txt", "*.txt") --> true
* wildcardMatch("c.txt", "*.jpg") --> false
* wildcardMatch("a/b/c.txt", "a/b/*") --> true
* wildcardMatch("c.txt", "*.???") --> true
* wildcardMatch("c.txt", "*.????") --> false
* </pre>
* N.B. the sequence "*?" does not work properly at present in match strings.
*
* @param filename the filename to match on
* @param wildcardMatcher the wildcard string to match against
* @return true if the filename matches the wildcard string
* @see IOCase#SENSITIVE
*/
public static boolean wildcardMatch(final String filename, final String wildcardMatcher) {
return wildcardMatch(filename, wildcardMatcher, IOCase.SENSITIVE);
}
/**
* Checks a filename to see if it matches the specified wildcard matcher
* using the case rules of the system.
* <p>
* The wildcard matcher uses the characters '?' and '*' to represent a
* single or multiple (zero or more) wildcard characters.
* This is the same as often found on Dos/Unix command lines.
* The check is case-sensitive on Unix and case-insensitive on Windows.
* <pre>
* wildcardMatch("c.txt", "*.txt") --> true
* wildcardMatch("c.txt", "*.jpg") --> false
* wildcardMatch("a/b/c.txt", "a/b/*") --> true
* wildcardMatch("c.txt", "*.???") --> true
* wildcardMatch("c.txt", "*.????") --> false
* </pre>
* N.B. the sequence "*?" does not work properly at present in match strings.
*
* @param filename the filename to match on
* @param wildcardMatcher the wildcard string to match against
* @return true if the filename matches the wildcard string
* @see IOCase#SYSTEM
*/
public static boolean wildcardMatchOnSystem(final String filename, final String wildcardMatcher) {
return wildcardMatch(filename, wildcardMatcher, IOCase.SYSTEM);
}
/**
* Checks a filename to see if it matches the specified wildcard matcher
* allowing control over case-sensitivity.
* <p>
* The wildcard matcher uses the characters '?' and '*' to represent a
* single or multiple (zero or more) wildcard characters.
* N.B. the sequence "*?" does not work properly at present in match strings.
*
* @param filename the filename to match on
* @param wildcardMatcher the wildcard string to match against
* @param caseSensitivity what case sensitivity rule to use, null means case-sensitive
* @return true if the filename matches the wildcard string
* @since 1.3
*/
public static boolean wildcardMatch(final String filename, final String wildcardMatcher, IOCase caseSensitivity) {
if (filename == null && wildcardMatcher == null) {
return true;
}
if (filename == null || wildcardMatcher == null) {
return false;
}
if (caseSensitivity == null) {
caseSensitivity = IOCase.SENSITIVE;
}
final String[] wcs = splitOnTokens(wildcardMatcher);
boolean anyChars = false;
int textIdx = 0;
int wcsIdx = 0;
final Stack<int[]> backtrack = new Stack<>();
// loop around a backtrack stack, to handle complex * matching
do {
if (backtrack.size() > 0) {
final int[] array = backtrack.pop();
wcsIdx = array[0];
textIdx = array[1];
anyChars = true;
}
// loop whilst tokens and text left to process
while (wcsIdx < wcs.length) {
if (wcs[wcsIdx].equals("?")) {
// ? so move to next text char
textIdx++;
if (textIdx > filename.length()) {
break;
}
anyChars = false;
} else if (wcs[wcsIdx].equals("*")) {
// set any chars status
anyChars = true;
if (wcsIdx == wcs.length - 1) {
textIdx = filename.length();
}
} else {
// matching text token
if (anyChars) {
// any chars then try to locate text token
textIdx = caseSensitivity.checkIndexOf(filename, textIdx, wcs[wcsIdx]);
if (textIdx == NOT_FOUND) {
// token not found
break;
}
final int repeat = caseSensitivity.checkIndexOf(filename, textIdx + 1, wcs[wcsIdx]);
if (repeat >= 0) {
backtrack.push(new int[] {wcsIdx, repeat});
}
} else {
// matching from current position
if (!caseSensitivity.checkRegionMatches(filename, textIdx, wcs[wcsIdx])) {
// couldnt match token
break;
}
}
// matched text token, move text index to end of matched token
textIdx += wcs[wcsIdx].length();
anyChars = false;
}
wcsIdx++;
}
// full match
if (wcsIdx == wcs.length && textIdx == filename.length()) {
return true;
}
} while (backtrack.size() > 0);
return false;
}
/**
* Splits a string into a number of tokens.
* The text is split by '?' and '*'.
* Where multiple '*' occur consecutively they are collapsed into a single '*'.
*
* @param text the text to split
* @return the array of tokens, never null
*/
static String[] splitOnTokens(final String text) {
// used by wildcardMatch
// package level so a unit test may run on this
if (text.indexOf('?') == NOT_FOUND && text.indexOf('*') == NOT_FOUND) {
return new String[] { text };
}
final char[] array = text.toCharArray();
final ArrayList<String> list = new ArrayList<>();
final StringBuilder buffer = new StringBuilder();
char prevChar = 0;
for (final char ch : array) {
if (ch == '?' || ch == '*') {
if (buffer.length() != 0) {
list.add(buffer.toString());
buffer.setLength(0);
}
if (ch == '?') {
list.add("?");
} else if (prevChar != '*') {// ch == '*' here; check if previous char was '*'
list.add("*");
}
} else {
buffer.append(ch);
}
prevChar = ch;
}
if (buffer.length() != 0) {
list.add(buffer.toString());
}
return list.toArray( new String[ list.size() ] );
}
}
| src/main/java/org/apache/commons/io/FilenameUtils.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.io;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Stack;
/**
* General filename and filepath manipulation utilities.
* <p>
* When dealing with filenames you can hit problems when moving from a Windows
* based development machine to a Unix based production machine.
* This class aims to help avoid those problems.
* <p>
* <b>NOTE</b>: You may be able to avoid using this class entirely simply by
* using JDK {@link java.io.File File} objects and the two argument constructor
* {@link java.io.File#File(java.io.File, java.lang.String) File(File,String)}.
* <p>
* Most methods on this class are designed to work the same on both Unix and Windows.
* Those that don't include 'System', 'Unix' or 'Windows' in their name.
* <p>
* Most methods recognise both separators (forward and back), and both
* sets of prefixes. See the javadoc of each method for details.
* <p>
* This class defines six components within a filename
* (example C:\dev\project\file.txt):
* <ul>
* <li>the prefix - C:\</li>
* <li>the path - dev\project\</li>
* <li>the full path - C:\dev\project\</li>
* <li>the name - file.txt</li>
* <li>the base name - file</li>
* <li>the extension - txt</li>
* </ul>
* Note that this class works best if directory filenames end with a separator.
* If you omit the last separator, it is impossible to determine if the filename
* corresponds to a file or a directory. As a result, we have chosen to say
* it corresponds to a file.
* <p>
* This class only supports Unix and Windows style names.
* Prefixes are matched as follows:
* <pre>
* Windows:
* a\b\c.txt --> "" --> relative
* \a\b\c.txt --> "\" --> current drive absolute
* C:a\b\c.txt --> "C:" --> drive relative
* C:\a\b\c.txt --> "C:\" --> absolute
* \\server\a\b\c.txt --> "\\server\" --> UNC
*
* Unix:
* a/b/c.txt --> "" --> relative
* /a/b/c.txt --> "/" --> absolute
* ~/a/b/c.txt --> "~/" --> current user
* ~ --> "~/" --> current user (slash added)
* ~user/a/b/c.txt --> "~user/" --> named user
* ~user --> "~user/" --> named user (slash added)
* </pre>
* Both prefix styles are matched always, irrespective of the machine that you are
* currently running on.
* <p>
* Origin of code: Excalibur, Alexandria, Tomcat, Commons-Utils.
*
* @since 1.1
*/
public class FilenameUtils {
private static final String EMPTY_STRING = "";
private static final int NOT_FOUND = -1;
/**
* The extension separator character.
* @since 1.4
*/
public static final char EXTENSION_SEPARATOR = '.';
/**
* The extension separator String.
* @since 1.4
*/
public static final String EXTENSION_SEPARATOR_STR = Character.toString(EXTENSION_SEPARATOR);
/**
* The Unix separator character.
*/
private static final char UNIX_SEPARATOR = '/';
/**
* The Windows separator character.
*/
private static final char WINDOWS_SEPARATOR = '\\';
/**
* The system separator character.
*/
private static final char SYSTEM_SEPARATOR = File.separatorChar;
/**
* The separator character that is the opposite of the system separator.
*/
private static final char OTHER_SEPARATOR;
static {
if (isSystemWindows()) {
OTHER_SEPARATOR = UNIX_SEPARATOR;
} else {
OTHER_SEPARATOR = WINDOWS_SEPARATOR;
}
}
/**
* Instances should NOT be constructed in standard programming.
*/
public FilenameUtils() {
super();
}
//-----------------------------------------------------------------------
/**
* Determines if Windows file system is in use.
*
* @return true if the system is Windows
*/
static boolean isSystemWindows() {
return SYSTEM_SEPARATOR == WINDOWS_SEPARATOR;
}
//-----------------------------------------------------------------------
/**
* Checks if the character is a separator.
*
* @param ch the character to check
* @return true if it is a separator character
*/
private static boolean isSeparator(final char ch) {
return ch == UNIX_SEPARATOR || ch == WINDOWS_SEPARATOR;
}
//-----------------------------------------------------------------------
/**
* Normalizes a path, removing double and single dot path steps.
* <p>
* This method normalizes a path to a standard format.
* The input may contain separators in either Unix or Windows format.
* The output will contain separators in the format of the system.
* <p>
* A trailing slash will be retained.
* A double slash will be merged to a single slash (but UNC names are handled).
* A single dot path segment will be removed.
* A double dot will cause that path segment and the one before to be removed.
* If the double dot has no parent path segment to work with, {@code null}
* is returned.
* <p>
* The output will be the same on both Unix and Windows except
* for the separator character.
* <pre>
* /foo// --> /foo/
* /foo/./ --> /foo/
* /foo/../bar --> /bar
* /foo/../bar/ --> /bar/
* /foo/../bar/../baz --> /baz
* //foo//./bar --> /foo/bar
* /../ --> null
* ../foo --> null
* foo/bar/.. --> foo/
* foo/../../bar --> null
* foo/../bar --> bar
* //server/foo/../bar --> //server/bar
* //server/../bar --> null
* C:\foo\..\bar --> C:\bar
* C:\..\bar --> null
* ~/foo/../bar/ --> ~/bar/
* ~/../bar --> null
* </pre>
* (Note the file separator returned will be correct for Windows/Unix)
*
* @param filename the filename to normalize, null returns null
* @return the normalized filename, or null if invalid. Null bytes inside string will be removed
*/
public static String normalize(final String filename) {
return doNormalize(filename, SYSTEM_SEPARATOR, true);
}
/**
* Normalizes a path, removing double and single dot path steps.
* <p>
* This method normalizes a path to a standard format.
* The input may contain separators in either Unix or Windows format.
* The output will contain separators in the format specified.
* <p>
* A trailing slash will be retained.
* A double slash will be merged to a single slash (but UNC names are handled).
* A single dot path segment will be removed.
* A double dot will cause that path segment and the one before to be removed.
* If the double dot has no parent path segment to work with, {@code null}
* is returned.
* <p>
* The output will be the same on both Unix and Windows except
* for the separator character.
* <pre>
* /foo// --> /foo/
* /foo/./ --> /foo/
* /foo/../bar --> /bar
* /foo/../bar/ --> /bar/
* /foo/../bar/../baz --> /baz
* //foo//./bar --> /foo/bar
* /../ --> null
* ../foo --> null
* foo/bar/.. --> foo/
* foo/../../bar --> null
* foo/../bar --> bar
* //server/foo/../bar --> //server/bar
* //server/../bar --> null
* C:\foo\..\bar --> C:\bar
* C:\..\bar --> null
* ~/foo/../bar/ --> ~/bar/
* ~/../bar --> null
* </pre>
* The output will be the same on both Unix and Windows including
* the separator character.
*
* @param filename the filename to normalize, null returns null
* @param unixSeparator {@code true} if a unix separator should
* be used or {@code false} if a windows separator should be used.
* @return the normalized filename, or null if invalid. Null bytes inside string will be removed
* @since 2.0
*/
public static String normalize(final String filename, final boolean unixSeparator) {
final char separator = unixSeparator ? UNIX_SEPARATOR : WINDOWS_SEPARATOR;
return doNormalize(filename, separator, true);
}
//-----------------------------------------------------------------------
/**
* Normalizes a path, removing double and single dot path steps,
* and removing any final directory separator.
* <p>
* This method normalizes a path to a standard format.
* The input may contain separators in either Unix or Windows format.
* The output will contain separators in the format of the system.
* <p>
* A trailing slash will be removed.
* A double slash will be merged to a single slash (but UNC names are handled).
* A single dot path segment will be removed.
* A double dot will cause that path segment and the one before to be removed.
* If the double dot has no parent path segment to work with, {@code null}
* is returned.
* <p>
* The output will be the same on both Unix and Windows except
* for the separator character.
* <pre>
* /foo// --> /foo
* /foo/./ --> /foo
* /foo/../bar --> /bar
* /foo/../bar/ --> /bar
* /foo/../bar/../baz --> /baz
* //foo//./bar --> /foo/bar
* /../ --> null
* ../foo --> null
* foo/bar/.. --> foo
* foo/../../bar --> null
* foo/../bar --> bar
* //server/foo/../bar --> //server/bar
* //server/../bar --> null
* C:\foo\..\bar --> C:\bar
* C:\..\bar --> null
* ~/foo/../bar/ --> ~/bar
* ~/../bar --> null
* </pre>
* (Note the file separator returned will be correct for Windows/Unix)
*
* @param filename the filename to normalize, null returns null
* @return the normalized filename, or null if invalid. Null bytes inside string will be removed
*/
public static String normalizeNoEndSeparator(final String filename) {
return doNormalize(filename, SYSTEM_SEPARATOR, false);
}
/**
* Normalizes a path, removing double and single dot path steps,
* and removing any final directory separator.
* <p>
* This method normalizes a path to a standard format.
* The input may contain separators in either Unix or Windows format.
* The output will contain separators in the format specified.
* <p>
* A trailing slash will be removed.
* A double slash will be merged to a single slash (but UNC names are handled).
* A single dot path segment will be removed.
* A double dot will cause that path segment and the one before to be removed.
* If the double dot has no parent path segment to work with, {@code null}
* is returned.
* <p>
* The output will be the same on both Unix and Windows including
* the separator character.
* <pre>
* /foo// --> /foo
* /foo/./ --> /foo
* /foo/../bar --> /bar
* /foo/../bar/ --> /bar
* /foo/../bar/../baz --> /baz
* //foo//./bar --> /foo/bar
* /../ --> null
* ../foo --> null
* foo/bar/.. --> foo
* foo/../../bar --> null
* foo/../bar --> bar
* //server/foo/../bar --> //server/bar
* //server/../bar --> null
* C:\foo\..\bar --> C:\bar
* C:\..\bar --> null
* ~/foo/../bar/ --> ~/bar
* ~/../bar --> null
* </pre>
*
* @param filename the filename to normalize, null returns null
* @param unixSeparator {@code true} if a unix separator should
* be used or {@code false} if a windows separator should be used.
* @return the normalized filename, or null if invalid. Null bytes inside string will be removed
* @since 2.0
*/
public static String normalizeNoEndSeparator(final String filename, final boolean unixSeparator) {
final char separator = unixSeparator ? UNIX_SEPARATOR : WINDOWS_SEPARATOR;
return doNormalize(filename, separator, false);
}
/**
* Internal method to perform the normalization.
*
* @param filename the filename
* @param separator The separator character to use
* @param keepSeparator true to keep the final separator
* @return the normalized filename. Null bytes inside string will be removed.
*/
private static String doNormalize(final String filename, final char separator, final boolean keepSeparator) {
if (filename == null) {
return null;
}
failIfNullBytePresent(filename);
int size = filename.length();
if (size == 0) {
return filename;
}
final int prefix = getPrefixLength(filename);
if (prefix < 0) {
return null;
}
final char[] array = new char[size + 2]; // +1 for possible extra slash, +2 for arraycopy
filename.getChars(0, filename.length(), array, 0);
// fix separators throughout
final char otherSeparator = separator == SYSTEM_SEPARATOR ? OTHER_SEPARATOR : SYSTEM_SEPARATOR;
for (int i = 0; i < array.length; i++) {
if (array[i] == otherSeparator) {
array[i] = separator;
}
}
// add extra separator on the end to simplify code below
boolean lastIsDirectory = true;
if (array[size - 1] != separator) {
array[size++] = separator;
lastIsDirectory = false;
}
// adjoining slashes
for (int i = prefix + 1; i < size; i++) {
if (array[i] == separator && array[i - 1] == separator) {
System.arraycopy(array, i, array, i - 1, size - i);
size--;
i--;
}
}
// dot slash
for (int i = prefix + 1; i < size; i++) {
if (array[i] == separator && array[i - 1] == '.' &&
(i == prefix + 1 || array[i - 2] == separator)) {
if (i == size - 1) {
lastIsDirectory = true;
}
System.arraycopy(array, i + 1, array, i - 1, size - i);
size -=2;
i--;
}
}
// double dot slash
outer:
for (int i = prefix + 2; i < size; i++) {
if (array[i] == separator && array[i - 1] == '.' && array[i - 2] == '.' &&
(i == prefix + 2 || array[i - 3] == separator)) {
if (i == prefix + 2) {
return null;
}
if (i == size - 1) {
lastIsDirectory = true;
}
int j;
for (j = i - 4 ; j >= prefix; j--) {
if (array[j] == separator) {
// remove b/../ from a/b/../c
System.arraycopy(array, i + 1, array, j + 1, size - i);
size -= i - j;
i = j + 1;
continue outer;
}
}
// remove a/../ from a/../c
System.arraycopy(array, i + 1, array, prefix, size - i);
size -= i + 1 - prefix;
i = prefix + 1;
}
}
if (size <= 0) { // should never be less than 0
return EMPTY_STRING;
}
if (size <= prefix) { // should never be less than prefix
return new String(array, 0, size);
}
if (lastIsDirectory && keepSeparator) {
return new String(array, 0, size); // keep trailing separator
}
return new String(array, 0, size - 1); // lose trailing separator
}
//-----------------------------------------------------------------------
/**
* Concatenates a filename to a base path using normal command line style rules.
* <p>
* The effect is equivalent to resultant directory after changing
* directory to the first argument, followed by changing directory to
* the second argument.
* <p>
* The first argument is the base path, the second is the path to concatenate.
* The returned path is always normalized via {@link #normalize(String)},
* thus <code>..</code> is handled.
* <p>
* If <code>pathToAdd</code> is absolute (has an absolute prefix), then
* it will be normalized and returned.
* Otherwise, the paths will be joined, normalized and returned.
* <p>
* The output will be the same on both Unix and Windows except
* for the separator character.
* <pre>
* /foo/ + bar --> /foo/bar
* /foo + bar --> /foo/bar
* /foo + /bar --> /bar
* /foo + C:/bar --> C:/bar
* /foo + C:bar --> C:bar (*)
* /foo/a/ + ../bar --> foo/bar
* /foo/ + ../../bar --> null
* /foo/ + /bar --> /bar
* /foo/.. + /bar --> /bar
* /foo + bar/c.txt --> /foo/bar/c.txt
* /foo/c.txt + bar --> /foo/c.txt/bar (!)
* </pre>
* (*) Note that the Windows relative drive prefix is unreliable when
* used with this method.
* (!) Note that the first parameter must be a path. If it ends with a name, then
* the name will be built into the concatenated path. If this might be a problem,
* use {@link #getFullPath(String)} on the base path argument.
*
* @param basePath the base path to attach to, always treated as a path
* @param fullFilenameToAdd the filename (or path) to attach to the base
* @return the concatenated path, or null if invalid. Null bytes inside string will be removed
*/
public static String concat(final String basePath, final String fullFilenameToAdd) {
final int prefix = getPrefixLength(fullFilenameToAdd);
if (prefix < 0) {
return null;
}
if (prefix > 0) {
return normalize(fullFilenameToAdd);
}
if (basePath == null) {
return null;
}
final int len = basePath.length();
if (len == 0) {
return normalize(fullFilenameToAdd);
}
final char ch = basePath.charAt(len - 1);
if (isSeparator(ch)) {
return normalize(basePath + fullFilenameToAdd);
}
return normalize(basePath + '/' + fullFilenameToAdd);
}
/**
* Determines whether the {@code parent} directory contains the {@code child} element (a file or directory).
* <p>
* The files names are expected to be normalized.
* </p>
*
* Edge cases:
* <ul>
* <li>A {@code directory} must not be null: if null, throw IllegalArgumentException</li>
* <li>A directory does not contain itself: return false</li>
* <li>A null child file is not contained in any parent: return false</li>
* </ul>
*
* @param canonicalParent
* the file to consider as the parent.
* @param canonicalChild
* the file to consider as the child.
* @return true is the candidate leaf is under by the specified composite. False otherwise.
* @throws IOException
* if an IO error occurs while checking the files.
* @since 2.2
* @see FileUtils#directoryContains(File, File)
*/
public static boolean directoryContains(final String canonicalParent, final String canonicalChild)
throws IOException {
// Fail fast against NullPointerException
if (canonicalParent == null) {
throw new IllegalArgumentException("Directory must not be null");
}
if (canonicalChild == null) {
return false;
}
if (IOCase.SYSTEM.checkEquals(canonicalParent, canonicalChild)) {
return false;
}
return IOCase.SYSTEM.checkStartsWith(canonicalChild, canonicalParent);
}
//-----------------------------------------------------------------------
/**
* Converts all separators to the Unix separator of forward slash.
*
* @param path the path to be changed, null ignored
* @return the updated path
*/
public static String separatorsToUnix(final String path) {
if (path == null || path.indexOf(WINDOWS_SEPARATOR) == NOT_FOUND) {
return path;
}
return path.replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR);
}
/**
* Converts all separators to the Windows separator of backslash.
*
* @param path the path to be changed, null ignored
* @return the updated path
*/
public static String separatorsToWindows(final String path) {
if (path == null || path.indexOf(UNIX_SEPARATOR) == NOT_FOUND) {
return path;
}
return path.replace(UNIX_SEPARATOR, WINDOWS_SEPARATOR);
}
/**
* Converts all separators to the system separator.
*
* @param path the path to be changed, null ignored
* @return the updated path
*/
public static String separatorsToSystem(final String path) {
if (path == null) {
return null;
}
return isSystemWindows() ? separatorsToWindows(path) : separatorsToUnix(path);
}
//-----------------------------------------------------------------------
/**
* Returns the length of the filename prefix, such as <code>C:/</code> or <code>~/</code>.
* <p>
* This method will handle a file in either Unix or Windows format.
* <p>
* The prefix length includes the first slash in the full filename
* if applicable. Thus, it is possible that the length returned is greater
* than the length of the input string.
* <pre>
* Windows:
* a\b\c.txt --> "" --> relative
* \a\b\c.txt --> "\" --> current drive absolute
* C:a\b\c.txt --> "C:" --> drive relative
* C:\a\b\c.txt --> "C:\" --> absolute
* \\server\a\b\c.txt --> "\\server\" --> UNC
* \\\a\b\c.txt --> error, length = -1
*
* Unix:
* a/b/c.txt --> "" --> relative
* /a/b/c.txt --> "/" --> absolute
* ~/a/b/c.txt --> "~/" --> current user
* ~ --> "~/" --> current user (slash added)
* ~user/a/b/c.txt --> "~user/" --> named user
* ~user --> "~user/" --> named user (slash added)
* //server/a/b/c.txt --> "//server/"
* ///a/b/c.txt --> error, length = -1
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on.
* ie. both Unix and Windows prefixes are matched regardless.
*
* Note that a leading // (or \\) is used to indicate a UNC name on Windows.
* These must be followed by a server name, so double-slashes are not collapsed
* to a single slash at the start of the filename.
*
* @param filename the filename to find the prefix in, null returns -1
* @return the length of the prefix, -1 if invalid or null
*/
public static int getPrefixLength(final String filename) {
if (filename == null) {
return NOT_FOUND;
}
final int len = filename.length();
if (len == 0) {
return 0;
}
char ch0 = filename.charAt(0);
if (ch0 == ':') {
return NOT_FOUND;
}
if (len == 1) {
if (ch0 == '~') {
return 2; // return a length greater than the input
}
return isSeparator(ch0) ? 1 : 0;
}
if (ch0 == '~') {
int posUnix = filename.indexOf(UNIX_SEPARATOR, 1);
int posWin = filename.indexOf(WINDOWS_SEPARATOR, 1);
if (posUnix == NOT_FOUND && posWin == NOT_FOUND) {
return len + 1; // return a length greater than the input
}
posUnix = posUnix == NOT_FOUND ? posWin : posUnix;
posWin = posWin == NOT_FOUND ? posUnix : posWin;
return Math.min(posUnix, posWin) + 1;
}
final char ch1 = filename.charAt(1);
if (ch1 == ':') {
ch0 = Character.toUpperCase(ch0);
if (ch0 >= 'A' && ch0 <= 'Z') {
if (len == 2 || isSeparator(filename.charAt(2)) == false) {
return 2;
}
return 3;
} else if (ch0 == UNIX_SEPARATOR) {
return 1;
}
return NOT_FOUND;
} else if (isSeparator(ch0) && isSeparator(ch1)) {
int posUnix = filename.indexOf(UNIX_SEPARATOR, 2);
int posWin = filename.indexOf(WINDOWS_SEPARATOR, 2);
if (posUnix == NOT_FOUND && posWin == NOT_FOUND || posUnix == 2 || posWin == 2) {
return NOT_FOUND;
}
posUnix = posUnix == NOT_FOUND ? posWin : posUnix;
posWin = posWin == NOT_FOUND ? posUnix : posWin;
return Math.min(posUnix, posWin) + 1;
} else {
return isSeparator(ch0) ? 1 : 0;
}
}
/**
* Returns the index of the last directory separator character.
* <p>
* This method will handle a file in either Unix or Windows format.
* The position of the last forward or backslash is returned.
* <p>
* The output will be the same irrespective of the machine that the code is running on.
*
* @param filename the filename to find the last path separator in, null returns -1
* @return the index of the last separator character, or -1 if there
* is no such character
*/
public static int indexOfLastSeparator(final String filename) {
if (filename == null) {
return NOT_FOUND;
}
final int lastUnixPos = filename.lastIndexOf(UNIX_SEPARATOR);
final int lastWindowsPos = filename.lastIndexOf(WINDOWS_SEPARATOR);
return Math.max(lastUnixPos, lastWindowsPos);
}
/**
* Returns the index of the last extension separator character, which is a dot.
* <p>
* This method also checks that there is no directory separator after the last dot. To do this it uses
* {@link #indexOfLastSeparator(String)} which will handle a file in either Unix or Windows format.
* </p>
* <p>
* The output will be the same irrespective of the machine that the code is running on, with the
* exception of a possible {@link IllegalArgumentException} on Windows (see below).
* </p>
* <b>Note:</b> This method used to have a hidden problem for names like "foo.exe:bar.txt".
* In this case, the name wouldn't be the name of a file, but the identifier of an
* alternate data stream (bar.txt) on the file foo.exe. The method used to return
* ".txt" here, which would be misleading. Commons IO 2.7, and later versions, are throwing
* an {@link IllegalArgumentException} for names like this.
*
* @param filename
* the filename to find the last extension separator in, null returns -1
* @return the index of the last extension separator character, or -1 if there is no such character
* @throws IllegalArgumentException <b>Windows only:</b> The filename parameter is, in fact,
* the identifier of an Alternate Data Stream, for example "foo.exe:bar.txt".
*/
public static int indexOfExtension(final String filename) throws IllegalArgumentException {
if (filename == null) {
return NOT_FOUND;
}
if (isSystemWindows()) {
// Special handling for NTFS ADS: Don't accept colon in the filename.
final int offset = filename.indexOf(':', getAdsCriticalOffset(filename));
if (offset != -1) {
throw new IllegalArgumentException("NTFS ADS separator (':') in filename is forbidden.");
}
}
final int extensionPos = filename.lastIndexOf(EXTENSION_SEPARATOR);
final int lastSeparator = indexOfLastSeparator(filename);
return lastSeparator > extensionPos ? NOT_FOUND : extensionPos;
}
//-----------------------------------------------------------------------
/**
* Gets the prefix from a full filename, such as <code>C:/</code>
* or <code>~/</code>.
* <p>
* This method will handle a file in either Unix or Windows format.
* The prefix includes the first slash in the full filename where applicable.
* <pre>
* Windows:
* a\b\c.txt --> "" --> relative
* \a\b\c.txt --> "\" --> current drive absolute
* C:a\b\c.txt --> "C:" --> drive relative
* C:\a\b\c.txt --> "C:\" --> absolute
* \\server\a\b\c.txt --> "\\server\" --> UNC
*
* Unix:
* a/b/c.txt --> "" --> relative
* /a/b/c.txt --> "/" --> absolute
* ~/a/b/c.txt --> "~/" --> current user
* ~ --> "~/" --> current user (slash added)
* ~user/a/b/c.txt --> "~user/" --> named user
* ~user --> "~user/" --> named user (slash added)
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on.
* ie. both Unix and Windows prefixes are matched regardless.
*
* @param filename the filename to query, null returns null
* @return the prefix of the file, null if invalid. Null bytes inside string will be removed
*/
public static String getPrefix(final String filename) {
if (filename == null) {
return null;
}
final int len = getPrefixLength(filename);
if (len < 0) {
return null;
}
if (len > filename.length()) {
failIfNullBytePresent(filename + UNIX_SEPARATOR);
return filename + UNIX_SEPARATOR;
}
final String path = filename.substring(0, len);
failIfNullBytePresent(path);
return path;
}
/**
* Gets the path from a full filename, which excludes the prefix.
* <p>
* This method will handle a file in either Unix or Windows format.
* The method is entirely text based, and returns the text before and
* including the last forward or backslash.
* <pre>
* C:\a\b\c.txt --> a\b\
* ~/a/b/c.txt --> a/b/
* a.txt --> ""
* a/b/c --> a/b/
* a/b/c/ --> a/b/c/
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on.
* <p>
* This method drops the prefix from the result.
* See {@link #getFullPath(String)} for the method that retains the prefix.
*
* @param filename the filename to query, null returns null
* @return the path of the file, an empty string if none exists, null if invalid.
* Null bytes inside string will be removed
*/
public static String getPath(final String filename) {
return doGetPath(filename, 1);
}
/**
* Gets the path from a full filename, which excludes the prefix, and
* also excluding the final directory separator.
* <p>
* This method will handle a file in either Unix or Windows format.
* The method is entirely text based, and returns the text before the
* last forward or backslash.
* <pre>
* C:\a\b\c.txt --> a\b
* ~/a/b/c.txt --> a/b
* a.txt --> ""
* a/b/c --> a/b
* a/b/c/ --> a/b/c
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on.
* <p>
* This method drops the prefix from the result.
* See {@link #getFullPathNoEndSeparator(String)} for the method that retains the prefix.
*
* @param filename the filename to query, null returns null
* @return the path of the file, an empty string if none exists, null if invalid.
* Null bytes inside string will be removed
*/
public static String getPathNoEndSeparator(final String filename) {
return doGetPath(filename, 0);
}
/**
* Does the work of getting the path.
*
* @param filename the filename
* @param separatorAdd 0 to omit the end separator, 1 to return it
* @return the path. Null bytes inside string will be removed
*/
private static String doGetPath(final String filename, final int separatorAdd) {
if (filename == null) {
return null;
}
final int prefix = getPrefixLength(filename);
if (prefix < 0) {
return null;
}
final int index = indexOfLastSeparator(filename);
final int endIndex = index+separatorAdd;
if (prefix >= filename.length() || index < 0 || prefix >= endIndex) {
return EMPTY_STRING;
}
final String path = filename.substring(prefix, endIndex);
failIfNullBytePresent(path);
return path;
}
/**
* Gets the full path from a full filename, which is the prefix + path.
* <p>
* This method will handle a file in either Unix or Windows format.
* The method is entirely text based, and returns the text before and
* including the last forward or backslash.
* <pre>
* C:\a\b\c.txt --> C:\a\b\
* ~/a/b/c.txt --> ~/a/b/
* a.txt --> ""
* a/b/c --> a/b/
* a/b/c/ --> a/b/c/
* C: --> C:
* C:\ --> C:\
* ~ --> ~/
* ~/ --> ~/
* ~user --> ~user/
* ~user/ --> ~user/
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on.
*
* @param filename the filename to query, null returns null
* @return the path of the file, an empty string if none exists, null if invalid
*/
public static String getFullPath(final String filename) {
return doGetFullPath(filename, true);
}
/**
* Gets the full path from a full filename, which is the prefix + path,
* and also excluding the final directory separator.
* <p>
* This method will handle a file in either Unix or Windows format.
* The method is entirely text based, and returns the text before the
* last forward or backslash.
* <pre>
* C:\a\b\c.txt --> C:\a\b
* ~/a/b/c.txt --> ~/a/b
* a.txt --> ""
* a/b/c --> a/b
* a/b/c/ --> a/b/c
* C: --> C:
* C:\ --> C:\
* ~ --> ~
* ~/ --> ~
* ~user --> ~user
* ~user/ --> ~user
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on.
*
* @param filename the filename to query, null returns null
* @return the path of the file, an empty string if none exists, null if invalid
*/
public static String getFullPathNoEndSeparator(final String filename) {
return doGetFullPath(filename, false);
}
/**
* Does the work of getting the path.
*
* @param filename the filename
* @param includeSeparator true to include the end separator
* @return the path
*/
private static String doGetFullPath(final String filename, final boolean includeSeparator) {
if (filename == null) {
return null;
}
final int prefix = getPrefixLength(filename);
if (prefix < 0) {
return null;
}
if (prefix >= filename.length()) {
if (includeSeparator) {
return getPrefix(filename); // add end slash if necessary
}
return filename;
}
final int index = indexOfLastSeparator(filename);
if (index < 0) {
return filename.substring(0, prefix);
}
int end = index + (includeSeparator ? 1 : 0);
if (end == 0) {
end++;
}
return filename.substring(0, end);
}
/**
* Gets the name minus the path from a full filename.
* <p>
* This method will handle a file in either Unix or Windows format.
* The text after the last forward or backslash is returned.
* <pre>
* a/b/c.txt --> c.txt
* a.txt --> a.txt
* a/b/c --> c
* a/b/c/ --> ""
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on.
*
* @param filename the filename to query, null returns null
* @return the name of the file without the path, or an empty string if none exists.
* Null bytes inside string will be removed
*/
public static String getName(final String filename) {
if (filename == null) {
return null;
}
failIfNullBytePresent(filename);
final int index = indexOfLastSeparator(filename);
return filename.substring(index + 1);
}
/**
* Check the input for null bytes, a sign of unsanitized data being passed to to file level functions.
*
* This may be used for poison byte attacks.
* @param path the path to check
*/
private static void failIfNullBytePresent(final String path) {
final int len = path.length();
for (int i = 0; i < len; i++) {
if (path.charAt(i) == 0) {
throw new IllegalArgumentException("Null byte present in file/path name. There are no " +
"known legitimate use cases for such data, but several injection attacks may use it");
}
}
}
/**
* Gets the base name, minus the full path and extension, from a full filename.
* <p>
* This method will handle a file in either Unix or Windows format.
* The text after the last forward or backslash and before the last dot is returned.
* <pre>
* a/b/c.txt --> c
* a.txt --> a
* a/b/c --> c
* a/b/c/ --> ""
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on.
*
* @param filename the filename to query, null returns null
* @return the name of the file without the path, or an empty string if none exists. Null bytes inside string
* will be removed
*/
public static String getBaseName(final String filename) {
return removeExtension(getName(filename));
}
/**
* Gets the extension of a filename.
* <p>
* This method returns the textual part of the filename after the last dot.
* There must be no directory separator after the dot.
* <pre>
* foo.txt --> "txt"
* a/b/c.jpg --> "jpg"
* a/b.txt/c --> ""
* a/b/c --> ""
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on, with the
* exception of a possible {@link IllegalArgumentException} on Windows (see below).
* </p>
* <p>
* <b>Note:</b> This method used to have a hidden problem for names like "foo.exe:bar.txt".
* In this case, the name wouldn't be the name of a file, but the identifier of an
* alternate data stream (bar.txt) on the file foo.exe. The method used to return
* ".txt" here, which would be misleading. Commons IO 2.7, and later versions, are throwing
* an {@link IllegalArgumentException} for names like this.
*
* @param filename the filename to retrieve the extension of.
* @return the extension of the file or an empty string if none exists or {@code null}
* if the filename is {@code null}.
* @throws IllegalArgumentException <b>Windows only:</b> The filename parameter is, in fact,
* the identifier of an Alternate Data Stream, for example "foo.exe:bar.txt".
*/
public static String getExtension(final String filename) throws IllegalArgumentException {
if (filename == null) {
return null;
}
final int index = indexOfExtension(filename);
if (index == NOT_FOUND) {
return EMPTY_STRING;
}
return filename.substring(index + 1);
}
private static int getAdsCriticalOffset(String filename) {
// Step 1: Remove leading path segments.
int offset1 = filename.lastIndexOf(SYSTEM_SEPARATOR);
int offset2 = filename.lastIndexOf(OTHER_SEPARATOR);
if (offset1 == -1) {
if (offset2 == -1) {
return 0;
}
return offset2 + 1;
}
if (offset2 == -1) {
return offset1 + 1;
}
return Math.max(offset1, offset2) + 1;
}
//-----------------------------------------------------------------------
/**
* Removes the extension from a filename.
* <p>
* This method returns the textual part of the filename before the last dot.
* There must be no directory separator after the dot.
* <pre>
* foo.txt --> foo
* a\b\c.jpg --> a\b\c
* a\b\c --> a\b\c
* a.b\c --> a.b\c
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on.
*
* @param filename the filename to query, null returns null
* @return the filename minus the extension
*/
public static String removeExtension(final String filename) {
if (filename == null) {
return null;
}
failIfNullBytePresent(filename);
final int index = indexOfExtension(filename);
if (index == NOT_FOUND) {
return filename;
}
return filename.substring(0, index);
}
//-----------------------------------------------------------------------
/**
* Checks whether two filenames are equal exactly.
* <p>
* No processing is performed on the filenames other than comparison,
* thus this is merely a null-safe case-sensitive equals.
*
* @param filename1 the first filename to query, may be null
* @param filename2 the second filename to query, may be null
* @return true if the filenames are equal, null equals null
* @see IOCase#SENSITIVE
*/
public static boolean equals(final String filename1, final String filename2) {
return equals(filename1, filename2, false, IOCase.SENSITIVE);
}
/**
* Checks whether two filenames are equal using the case rules of the system.
* <p>
* No processing is performed on the filenames other than comparison.
* The check is case-sensitive on Unix and case-insensitive on Windows.
*
* @param filename1 the first filename to query, may be null
* @param filename2 the second filename to query, may be null
* @return true if the filenames are equal, null equals null
* @see IOCase#SYSTEM
*/
public static boolean equalsOnSystem(final String filename1, final String filename2) {
return equals(filename1, filename2, false, IOCase.SYSTEM);
}
//-----------------------------------------------------------------------
/**
* Checks whether two filenames are equal after both have been normalized.
* <p>
* Both filenames are first passed to {@link #normalize(String)}.
* The check is then performed in a case-sensitive manner.
*
* @param filename1 the first filename to query, may be null
* @param filename2 the second filename to query, may be null
* @return true if the filenames are equal, null equals null
* @see IOCase#SENSITIVE
*/
public static boolean equalsNormalized(final String filename1, final String filename2) {
return equals(filename1, filename2, true, IOCase.SENSITIVE);
}
/**
* Checks whether two filenames are equal after both have been normalized
* and using the case rules of the system.
* <p>
* Both filenames are first passed to {@link #normalize(String)}.
* The check is then performed case-sensitive on Unix and
* case-insensitive on Windows.
*
* @param filename1 the first filename to query, may be null
* @param filename2 the second filename to query, may be null
* @return true if the filenames are equal, null equals null
* @see IOCase#SYSTEM
*/
public static boolean equalsNormalizedOnSystem(final String filename1, final String filename2) {
return equals(filename1, filename2, true, IOCase.SYSTEM);
}
/**
* Checks whether two filenames are equal, optionally normalizing and providing
* control over the case-sensitivity.
*
* @param filename1 the first filename to query, may be null
* @param filename2 the second filename to query, may be null
* @param normalized whether to normalize the filenames
* @param caseSensitivity what case sensitivity rule to use, null means case-sensitive
* @return true if the filenames are equal, null equals null
* @since 1.3
*/
public static boolean equals(
String filename1, String filename2,
final boolean normalized, IOCase caseSensitivity) {
if (filename1 == null || filename2 == null) {
return filename1 == null && filename2 == null;
}
if (normalized) {
filename1 = normalize(filename1);
filename2 = normalize(filename2);
if (filename1 == null || filename2 == null) {
throw new NullPointerException(
"Error normalizing one or both of the file names");
}
}
if (caseSensitivity == null) {
caseSensitivity = IOCase.SENSITIVE;
}
return caseSensitivity.checkEquals(filename1, filename2);
}
//-----------------------------------------------------------------------
/**
* Checks whether the extension of the filename is that specified.
* <p>
* This method obtains the extension as the textual part of the filename
* after the last dot. There must be no directory separator after the dot.
* The extension check is case-sensitive on all platforms.
*
* @param filename the filename to query, null returns false
* @param extension the extension to check for, null or empty checks for no extension
* @return true if the filename has the specified extension
* @throws java.lang.IllegalArgumentException if the supplied filename contains null bytes
*/
public static boolean isExtension(final String filename, final String extension) {
if (filename == null) {
return false;
}
failIfNullBytePresent(filename);
if (extension == null || extension.isEmpty()) {
return indexOfExtension(filename) == NOT_FOUND;
}
final String fileExt = getExtension(filename);
return fileExt.equals(extension);
}
/**
* Checks whether the extension of the filename is one of those specified.
* <p>
* This method obtains the extension as the textual part of the filename
* after the last dot. There must be no directory separator after the dot.
* The extension check is case-sensitive on all platforms.
*
* @param filename the filename to query, null returns false
* @param extensions the extensions to check for, null checks for no extension
* @return true if the filename is one of the extensions
* @throws java.lang.IllegalArgumentException if the supplied filename contains null bytes
*/
public static boolean isExtension(final String filename, final String[] extensions) {
if (filename == null) {
return false;
}
failIfNullBytePresent(filename);
if (extensions == null || extensions.length == 0) {
return indexOfExtension(filename) == NOT_FOUND;
}
final String fileExt = getExtension(filename);
for (final String extension : extensions) {
if (fileExt.equals(extension)) {
return true;
}
}
return false;
}
/**
* Checks whether the extension of the filename is one of those specified.
* <p>
* This method obtains the extension as the textual part of the filename
* after the last dot. There must be no directory separator after the dot.
* The extension check is case-sensitive on all platforms.
*
* @param filename the filename to query, null returns false
* @param extensions the extensions to check for, null checks for no extension
* @return true if the filename is one of the extensions
* @throws java.lang.IllegalArgumentException if the supplied filename contains null bytes
*/
public static boolean isExtension(final String filename, final Collection<String> extensions) {
if (filename == null) {
return false;
}
failIfNullBytePresent(filename);
if (extensions == null || extensions.isEmpty()) {
return indexOfExtension(filename) == NOT_FOUND;
}
final String fileExt = getExtension(filename);
for (final String extension : extensions) {
if (fileExt.equals(extension)) {
return true;
}
}
return false;
}
//-----------------------------------------------------------------------
/**
* Checks a filename to see if it matches the specified wildcard matcher,
* always testing case-sensitive.
* <p>
* The wildcard matcher uses the characters '?' and '*' to represent a
* single or multiple (zero or more) wildcard characters.
* This is the same as often found on Dos/Unix command lines.
* The check is case-sensitive always.
* <pre>
* wildcardMatch("c.txt", "*.txt") --> true
* wildcardMatch("c.txt", "*.jpg") --> false
* wildcardMatch("a/b/c.txt", "a/b/*") --> true
* wildcardMatch("c.txt", "*.???") --> true
* wildcardMatch("c.txt", "*.????") --> false
* </pre>
* N.B. the sequence "*?" does not work properly at present in match strings.
*
* @param filename the filename to match on
* @param wildcardMatcher the wildcard string to match against
* @return true if the filename matches the wildcard string
* @see IOCase#SENSITIVE
*/
public static boolean wildcardMatch(final String filename, final String wildcardMatcher) {
return wildcardMatch(filename, wildcardMatcher, IOCase.SENSITIVE);
}
/**
* Checks a filename to see if it matches the specified wildcard matcher
* using the case rules of the system.
* <p>
* The wildcard matcher uses the characters '?' and '*' to represent a
* single or multiple (zero or more) wildcard characters.
* This is the same as often found on Dos/Unix command lines.
* The check is case-sensitive on Unix and case-insensitive on Windows.
* <pre>
* wildcardMatch("c.txt", "*.txt") --> true
* wildcardMatch("c.txt", "*.jpg") --> false
* wildcardMatch("a/b/c.txt", "a/b/*") --> true
* wildcardMatch("c.txt", "*.???") --> true
* wildcardMatch("c.txt", "*.????") --> false
* </pre>
* N.B. the sequence "*?" does not work properly at present in match strings.
*
* @param filename the filename to match on
* @param wildcardMatcher the wildcard string to match against
* @return true if the filename matches the wildcard string
* @see IOCase#SYSTEM
*/
public static boolean wildcardMatchOnSystem(final String filename, final String wildcardMatcher) {
return wildcardMatch(filename, wildcardMatcher, IOCase.SYSTEM);
}
/**
* Checks a filename to see if it matches the specified wildcard matcher
* allowing control over case-sensitivity.
* <p>
* The wildcard matcher uses the characters '?' and '*' to represent a
* single or multiple (zero or more) wildcard characters.
* N.B. the sequence "*?" does not work properly at present in match strings.
*
* @param filename the filename to match on
* @param wildcardMatcher the wildcard string to match against
* @param caseSensitivity what case sensitivity rule to use, null means case-sensitive
* @return true if the filename matches the wildcard string
* @since 1.3
*/
public static boolean wildcardMatch(final String filename, final String wildcardMatcher, IOCase caseSensitivity) {
if (filename == null && wildcardMatcher == null) {
return true;
}
if (filename == null || wildcardMatcher == null) {
return false;
}
if (caseSensitivity == null) {
caseSensitivity = IOCase.SENSITIVE;
}
final String[] wcs = splitOnTokens(wildcardMatcher);
boolean anyChars = false;
int textIdx = 0;
int wcsIdx = 0;
final Stack<int[]> backtrack = new Stack<>();
// loop around a backtrack stack, to handle complex * matching
do {
if (backtrack.size() > 0) {
final int[] array = backtrack.pop();
wcsIdx = array[0];
textIdx = array[1];
anyChars = true;
}
// loop whilst tokens and text left to process
while (wcsIdx < wcs.length) {
if (wcs[wcsIdx].equals("?")) {
// ? so move to next text char
textIdx++;
if (textIdx > filename.length()) {
break;
}
anyChars = false;
} else if (wcs[wcsIdx].equals("*")) {
// set any chars status
anyChars = true;
if (wcsIdx == wcs.length - 1) {
textIdx = filename.length();
}
} else {
// matching text token
if (anyChars) {
// any chars then try to locate text token
textIdx = caseSensitivity.checkIndexOf(filename, textIdx, wcs[wcsIdx]);
if (textIdx == NOT_FOUND) {
// token not found
break;
}
final int repeat = caseSensitivity.checkIndexOf(filename, textIdx + 1, wcs[wcsIdx]);
if (repeat >= 0) {
backtrack.push(new int[] {wcsIdx, repeat});
}
} else {
// matching from current position
if (!caseSensitivity.checkRegionMatches(filename, textIdx, wcs[wcsIdx])) {
// couldnt match token
break;
}
}
// matched text token, move text index to end of matched token
textIdx += wcs[wcsIdx].length();
anyChars = false;
}
wcsIdx++;
}
// full match
if (wcsIdx == wcs.length && textIdx == filename.length()) {
return true;
}
} while (backtrack.size() > 0);
return false;
}
/**
* Splits a string into a number of tokens.
* The text is split by '?' and '*'.
* Where multiple '*' occur consecutively they are collapsed into a single '*'.
*
* @param text the text to split
* @return the array of tokens, never null
*/
static String[] splitOnTokens(final String text) {
// used by wildcardMatch
// package level so a unit test may run on this
if (text.indexOf('?') == NOT_FOUND && text.indexOf('*') == NOT_FOUND) {
return new String[] { text };
}
final char[] array = text.toCharArray();
final ArrayList<String> list = new ArrayList<>();
final StringBuilder buffer = new StringBuilder();
char prevChar = 0;
for (final char ch : array) {
if (ch == '?' || ch == '*') {
if (buffer.length() != 0) {
list.add(buffer.toString());
buffer.setLength(0);
}
if (ch == '?') {
list.add("?");
} else if (prevChar != '*') {// ch == '*' here; check if previous char was '*'
list.add("*");
}
} else {
buffer.append(ch);
}
prevChar = ch;
}
if (buffer.length() != 0) {
list.add(buffer.toString());
}
return list.toArray( new String[ list.size() ] );
}
}
| Add missing Javadoc for Checkstyle. | src/main/java/org/apache/commons/io/FilenameUtils.java | Add missing Javadoc for Checkstyle. | <ide><path>rc/main/java/org/apache/commons/io/FilenameUtils.java
<ide> return filename.substring(index + 1);
<ide> }
<ide>
<add> /**
<add> * Special handling for NTFS ADS: Don't accept colon in the filename.
<add> *
<add> * @param filename a file name
<add> * @return ADS offsets.
<add> */
<ide> private static int getAdsCriticalOffset(String filename) {
<ide> // Step 1: Remove leading path segments.
<ide> int offset1 = filename.lastIndexOf(SYSTEM_SEPARATOR); |
|
JavaScript | mit | 27a79d098734fd1ffc8ccc9c3ef717275189644a | 0 | phetsims/joist,phetsims/joist,phetsims/joist | // Copyright 2014-2017, University of Colorado Boulder
/**
* General dialog type
*
* @author Jonathan Olson <[email protected]>
* @author Sam Reid (PhET Interactive Simulations)
*/
define( function( require ) {
'use strict';
// modules
var AccessibilityUtil = require( 'SCENERY/accessibility/AccessibilityUtil' );
var Display = require( 'SCENERY/display/Display' );
var FullScreen = require( 'JOIST/FullScreen' );
var inherit = require( 'PHET_CORE/inherit' );
var joist = require( 'JOIST/joist' );
var JoistA11yStrings = require( 'JOIST/JoistA11yStrings' );
var KeyboardUtil = require( 'SCENERY/accessibility/KeyboardUtil' );
var Node = require( 'SCENERY/nodes/Node' );
var Panel = require( 'SUN/Panel' );
var Path = require( 'SCENERY/nodes/Path' );
var RectangularPushButton = require( 'SUN/buttons/RectangularPushButton' );
var Shape = require( 'KITE/Shape' );
var Tandem = require( 'TANDEM/Tandem' );
var DialogIO = require( 'JOIST/DialogIO' );
// strings
var closeString = JoistA11yStrings.close.value;
/**
* @param {Node} content - The content to display inside the dialog (not including the title)
* @param {Object} [options]
* @constructor
*/
function Dialog( content, options ) {
var self = this;
options = _.extend( {
// Dialog-specific options
modal: true, // {boolean} modal dialogs prevent interaction with the rest of the sim while open
title: null, // {Node} title to be displayed at top
titleAlign: 'center', // horizontal alignment of the title: {string} left, right or center
titleSpacing: 20, // {number} how far the title is placed above the content
hasCloseButton: true, // whether to put a close 'X' button is upper-right corner
// {function} which sets the dialog's position in global coordinates. called as
// layoutStrategy( dialog, simBounds, screenBounds, scale )
layoutStrategy: Dialog.DEFAULT_LAYOUT_STRATEGY,
// close button options
closeButtonBaseColor: '#d00',
closeButtonMargin: 5, // {number} how far away should the close button be from the panel border
closeButtonListener: function() { self.hide(); },
// pass through to Panel options
cornerRadius: 10, // {number} radius of the dialog's corners
resize: true, // {boolean} whether to resize if content's size changes
fill: 'white', // {string|Color}
stroke: 'black', // {string|Color}
backgroundPickable: true,
xMargin: 20,
yMargin: 20,
tandem: Tandem.optional,
phetioType: DialogIO,
phetioReadOnly: false, // default to false so it can pass it through to the close button
phetioState: false, // default to false so it can pass it through to the close button
// a11y options
tagName: 'div',
ariaRole: 'dialog',
focusOnCloseNode: null // {Node} receives focus on close, if null focus returns to element that had focus on open
}, options );
// @private (read-only)
this.isModal = options.modal;
// see https://github.com/phetsims/joist/issues/293
assert && assert( this.isModal, 'Non-modal dialogs not currently supported' );
// @private - whether the dialog is showing
this.isShowing = false;
var dialogContent = new Node( {
children: [ content ]
} );
if ( options.title ) {
var titleNode = options.title;
dialogContent.addChild( titleNode );
var updateTitlePosition = function() {
switch( options.titleAlign ) {
case 'center':
titleNode.centerX = content.centerX;
break;
case 'left':
titleNode.left = content.left;
break;
case 'right':
titleNode.right = content.right;
break;
default:
throw new Error( 'unknown titleAlign for Dialog: ' + options.titleAlign );
}
titleNode.bottom = content.top - options.titleSpacing;
};
if ( options.resize ) {
content.on( 'bounds', updateTitlePosition );
titleNode.on( 'localBounds', updateTitlePosition );
}
updateTitlePosition();
}
Panel.call( this, dialogContent, options );
if ( options.hasCloseButton ) {
var crossSize = 10;
var crossNode = new Path( new Shape().moveTo( 0, 0 ).lineTo( crossSize, crossSize ).moveTo( 0, crossSize ).lineTo( crossSize, 0 ), {
stroke: '#fff',
lineWidth: 3
} );
var closeButton = new RectangularPushButton( {
content: crossNode,
baseColor: options.closeButtonBaseColor,
xMargin: 5,
yMargin: 5,
listener: options.closeButtonListener,
accessibleFire: function() {
self.focusActiveElement();
},
tandem: options.tandem.createTandem( 'closeButton' ),
phetioReadOnly: options.phetioReadOnly, // match the readOnly of the Dialog
phetioState: options.phetioState, // match the state transfer of the Dialog
// a11y options
tagName: 'button',
innerContent: closeString
} );
this.addChild( closeButton );
var updateClosePosition = function() {
closeButton.right = dialogContent.right + options.xMargin - options.closeButtonMargin;
closeButton.top = dialogContent.top - options.yMargin + options.closeButtonMargin;
};
if ( options.resize ) {
dialogContent.on( 'bounds', updateClosePosition );
if ( options.title ) {
options.title.on( 'bounds', updateClosePosition );
}
}
updateClosePosition();
}
var sim = window.phet.joist.sim;
// @private
this.updateLayout = function() {
options.layoutStrategy( self, sim.boundsProperty.value, sim.screenBoundsProperty.value, sim.scaleProperty.value );
};
this.updateLayout();
// @private
this.sim = sim;
// a11y - set the order of content for accessibility, title before content
this.accessibleOrder = [ titleNode, dialogContent ];
// a11y - set the aria labelledby and describedby relations so that whenever focus enters the dialog, the title
// and description content are read in full
content.tagName && this.setAriaDescribedByNode( content );
if ( options.title ) {
options.title.tagName && this.setAriaLabelledByNode( options.title );
}
// must be removed on dispose
this.sim.resizedEmitter.addListener( this.updateLayout );
// @private (a11y) - the active element when the dialog is shown, tracked so that focus can be restored on close
this.activeElement = options.focusOnCloseNode || null;
// a11y - close the dialog when pressing "escape"
var escapeListener = this.addAccessibleInputListener( {
keydown: function( event ) {
if ( event.keyCode === KeyboardUtil.KEY_ESCAPE ) {
event.preventDefault();
self.hide();
self.focusActiveElement();
}
else if ( event.keyCode === KeyboardUtil.KEY_TAB && FullScreen.isFullScreen() ) {
// prevent a particular bug in Windows 7/8.1 Firefox where focus gets trapped in the document
// when the navigation bar is hidden and there is only one focusable element in the DOM
// see https://bugzilla.mozilla.org/show_bug.cgi?id=910136
var activeId = Display.focus.trail.getUniqueId();
var noNextFocusable = AccessibilityUtil.getNextFocusable().id === activeId;
var noPreviousFocusable = AccessibilityUtil.getPreviousFocusable().id === activeId;
if ( noNextFocusable && noPreviousFocusable ) {
event.preventDefault();
}
}
}
} );
// @private - to be called on dispose()
this.disposeDialog = function() {
self.sim.resizedEmitter.removeListener( self.updateLayout );
self.removeAccessibleInputListener( escapeListener );
if ( options.hasCloseButton ) {
closeButton.dispose();
if ( options.resize ) {
dialogContent.off( 'bounds', updateClosePosition );
if ( options.title ) {
options.title.off( 'bounds', updateClosePosition );
titleNode.off( 'localBounds', updateTitlePosition );
content.off( 'bounds', updateTitlePosition );
}
}
}
// remove dialog content from scene graph, but don't dispose because Panel
// needs to remove listeners on the content in its dispose()
dialogContent.removeAllChildren();
dialogContent.detach();
};
}
joist.register( 'Dialog', Dialog );
// @private
Dialog.DEFAULT_LAYOUT_STRATEGY = function( dialog, simBounds, screenBounds, scale ) {
// The size is set in the Sim.topLayer, but we need to update the location here
dialog.center = simBounds.center.times( 1.0 / scale );
};
return inherit( Panel, Dialog, {
// @public
show: function() {
if ( !this.isShowing ) {
window.phet.joist.sim.showPopup( this, this.isModal );
this.isShowing = true;
// a11y - store the currently active element before hiding all other accessible content
// so that the active element isn't blurred
this.activeElement = this.activeElement || Display.focusedNode;
this.setAccessibleViewsVisible( false );
// In case the window size has changed since the dialog was hidden, we should try layout out again.
// See https://github.com/phetsims/joist/issues/362
this.updateLayout();
}
},
/**
* Hide the dialog. If you create a new dialog next time you show(), be sure to dispose this
* dialog instead.
* @public
*/
hide: function() {
if ( this.isShowing ) {
window.phet.joist.sim.hidePopup( this, this.isModal );
this.isShowing = false;
// a11y - when the dialog is hidden, make all ScreenView content visible to assistive technology
this.setAccessibleViewsVisible( true );
}
},
/**
* Make eligible for garbage collection.
* @public
*/
dispose: function() {
this.hide();
this.disposeDialog();
Panel.prototype.dispose.call( this );
},
/**
* Hide or show all accessible content related to the sim ScreenViews, navigation bar, and alert content. Instead
* of using setVisible, we have to remove the subtree of accessible content from each view element in order to
* prevent an IE11 bug where content remains invisible in the accessibility tree, see
* https://github.com/phetsims/john-travoltage/issues/247
*
* @param {boolean} visible
*/
setAccessibleViewsVisible: function( visible ) {
for ( var i = 0; i < this.sim.screens.length; i++ ) {
this.sim.screens[ i ].view.accessibleContentDisplayed = visible;
}
this.sim.navigationBar.accessibleContentDisplayed = visible;
this.sim.homeScreen && this.sim.homeScreen.view.setAccessibleContentDisplayed( visible );
// workaround for a strange Edge bug where this child of the navigation bar remains visible,
// see https://github.com/phetsims/a11y-research/issues/30
if ( this.sim.navigationBar.keyboardHelpButton ) {
this.sim.navigationBar.keyboardHelpButton.accessibleVisible = visible;
}
},
/**
* If there is an active element, focus it. Should almost always be closed after the Dialog has been closed.
*
* @public
* @a11y
*/
focusActiveElement: function() {
this.activeElement && this.activeElement.focus();
}
} );
} ); | js/Dialog.js | // Copyright 2014-2017, University of Colorado Boulder
/**
* General dialog type
*
* @author Jonathan Olson <[email protected]>
* @author Sam Reid (PhET Interactive Simulations)
*/
define( function( require ) {
'use strict';
// modules
var AccessibilityUtil = require( 'SCENERY/accessibility/AccessibilityUtil' );
var Display = require( 'SCENERY/display/Display' );
var FullScreen = require( 'JOIST/FullScreen' );
var inherit = require( 'PHET_CORE/inherit' );
var joist = require( 'JOIST/joist' );
var JoistA11yStrings = require( 'JOIST/JoistA11yStrings' );
var KeyboardUtil = require( 'SCENERY/accessibility/KeyboardUtil' );
var Node = require( 'SCENERY/nodes/Node' );
var Panel = require( 'SUN/Panel' );
var Path = require( 'SCENERY/nodes/Path' );
var RectangularPushButton = require( 'SUN/buttons/RectangularPushButton' );
var Shape = require( 'KITE/Shape' );
var Tandem = require( 'TANDEM/Tandem' );
var DialogIO = require( 'JOIST/DialogIO' );
// strings
var closeString = JoistA11yStrings.close.value;
/**
* @param {Node} content - The content to display inside the dialog (not including the title)
* @param {Object} [options]
* @constructor
*/
function Dialog( content, options ) {
var self = this;
options = _.extend( {
// Dialog-specific options
modal: true, // {boolean} modal dialogs prevent interaction with the rest of the sim while open
title: null, // {Node} title to be displayed at top
titleAlign: 'center', // horizontal alignment of the title: {string} left, right or center
titleSpacing: 20, // {number} how far the title is placed above the content
hasCloseButton: true, // whether to put a close 'X' button is upper-right corner
// {function} which sets the dialog's position in global coordinates. called as
// layoutStrategy( dialog, simBounds, screenBounds, scale )
layoutStrategy: Dialog.DEFAULT_LAYOUT_STRATEGY,
// close button options
closeButtonBaseColor: '#d00',
closeButtonMargin: 5, // {number} how far away should the close button be from the panel border
closeButtonListener: function() { self.hide(); },
// pass through to Panel options
cornerRadius: 10, // {number} radius of the dialog's corners
resize: true, // {boolean} whether to resize if content's size changes
fill: 'white', // {string|Color}
stroke: 'black', // {string|Color}
backgroundPickable: true,
xMargin: 20,
yMargin: 20,
tandem: Tandem.optional,
phetioType: DialogIO,
phetioReadOnly: false, // default to false so it can pass it through to the close button
phetioState: false, // default to false so it can pass it through to the close button
// a11y options
tagName: 'div',
ariaRole: 'dialog',
focusOnCloseNode: null // {Node} receives focus on close, if null focus returns to element that had focus on open
}, options );
// @private (read-only)
this.isModal = options.modal;
// see https://github.com/phetsims/joist/issues/293
assert && assert( this.isModal, 'Non-modal dialogs not currently supported' );
// @private - whether the dialog is showing
this.isShowing = false;
var dialogContent = new Node( {
children: [ content ]
} );
if ( options.title ) {
var titleNode = options.title;
dialogContent.addChild( titleNode );
var updateTitlePosition = function() {
switch( options.titleAlign ) {
case 'center':
titleNode.centerX = content.centerX;
break;
case 'left':
titleNode.left = content.left;
break;
case 'right':
titleNode.right = content.right;
break;
default:
throw new Error( 'unknown titleAlign for Dialog: ' + options.titleAlign );
}
titleNode.bottom = content.top - options.titleSpacing;
};
if ( options.resize ) {
content.on( 'bounds', updateTitlePosition );
titleNode.on( 'localBounds', updateTitlePosition );
}
updateTitlePosition();
}
Panel.call( this, dialogContent, options );
if ( options.hasCloseButton ) {
var crossSize = 10;
var crossNode = new Path( new Shape().moveTo( 0, 0 ).lineTo( crossSize, crossSize ).moveTo( 0, crossSize ).lineTo( crossSize, 0 ), {
stroke: '#fff',
lineWidth: 3
} );
var closeButton = new RectangularPushButton( {
content: crossNode,
baseColor: options.closeButtonBaseColor,
xMargin: 5,
yMargin: 5,
listener: options.closeButtonListener,
accessibleFire: function() {
self.focusActiveElement();
},
tandem: options.tandem.createTandem( 'closeButton' ),
phetioReadOnly: options.phetioReadOnly, // match the readOnly of the Dialog
phetioState: options.phetioState, // match the state transfer of the Dialog
// a11y options
tagName: 'button',
innerContent: closeString
} );
this.addChild( closeButton );
var updateClosePosition = function() {
closeButton.right = dialogContent.right + options.xMargin - options.closeButtonMargin;
closeButton.top = dialogContent.top - options.yMargin + options.closeButtonMargin;
};
if ( options.resize ) {
dialogContent.on( 'bounds', updateClosePosition );
if ( options.title ) {
options.title.on( 'bounds', updateClosePosition );
}
}
updateClosePosition();
}
var sim = window.phet.joist.sim;
// @private
this.updateLayout = function() {
options.layoutStrategy( self, sim.boundsProperty.value, sim.screenBoundsProperty.value, sim.scaleProperty.value );
};
this.updateLayout();
// @private
this.sim = sim;
// a11y - set the order of content for accessibility, title before content
this.accessibleOrder = [ titleNode, dialogContent ];
// a11y - set the aria labelledby and describedby relations so that whenever focus enters the dialog, the title
// and description content are read in full
content.tagName && this.setAriaDescribedByNode( content );
if ( options.title ) {
options.title.tagName && this.setAriaLabelledByNode( options.title );
}
// must be removed on dispose
this.sim.resizedEmitter.addListener( this.updateLayout );
// @private (a11y) - the active element when the dialog is shown, tracked so that focus can be restored on close
this.activeElement = options.focusOnCloseNode || null;
// a11y - close the dialog when pressing "escape"
var escapeListener = this.addAccessibleInputListener( {
keydown: function( event ) {
if ( event.keyCode === KeyboardUtil.KEY_ESCAPE ) {
event.preventDefault();
self.hide();
self.focusActiveElement();
}
else if ( event.keyCode === KeyboardUtil.KEY_TAB && FullScreen.isFullScreen() ) {
// prevent a particular bug in Windows 7/8.1 Firefox where focus gets trapped in the document
// when the navigation bar is hidden and there is only one focusable element in the DOM
// see https://bugzilla.mozilla.org/show_bug.cgi?id=910136
var activeId = Display.focus.trail.getUniqueId();
var noNextFocusable = AccessibilityUtil.getNextFocusable().id === activeId;
var noPreviousFocusable = AccessibilityUtil.getPreviousFocusable().id === activeId;
if ( noNextFocusable && noPreviousFocusable ) {
event.preventDefault();
}
}
}
} );
// @private - to be called on dispose()
this.disposeDialog = function() {
self.sim.resizedEmitter.removeListener( self.updateLayout );
self.removeAccessibleInputListener( escapeListener );
if ( options.hasCloseButton ) {
closeButton.dispose();
}
if ( options.resize ) {
dialogContent.off( 'bounds', updateClosePosition );
if ( options.title ) {
options.title.off( 'bounds', updateClosePosition );
titleNode.off( 'localBounds', updateTitlePosition );
content.off( 'bounds', updateTitlePosition );
}
}
// remove dialog content from scene graph, but don't dispose because Panel
// needs to remove listeners on the content in its dispose()
dialogContent.removeAllChildren();
dialogContent.detach();
};
}
joist.register( 'Dialog', Dialog );
// @private
Dialog.DEFAULT_LAYOUT_STRATEGY = function( dialog, simBounds, screenBounds, scale ) {
// The size is set in the Sim.topLayer, but we need to update the location here
dialog.center = simBounds.center.times( 1.0 / scale );
};
return inherit( Panel, Dialog, {
// @public
show: function() {
if ( !this.isShowing ) {
window.phet.joist.sim.showPopup( this, this.isModal );
this.isShowing = true;
// a11y - store the currently active element before hiding all other accessible content
// so that the active element isn't blurred
this.activeElement = this.activeElement || Display.focusedNode;
this.setAccessibleViewsVisible( false );
// In case the window size has changed since the dialog was hidden, we should try layout out again.
// See https://github.com/phetsims/joist/issues/362
this.updateLayout();
}
},
/**
* Hide the dialog. If you create a new dialog next time you show(), be sure to dispose this
* dialog instead.
* @public
*/
hide: function() {
if ( this.isShowing ) {
window.phet.joist.sim.hidePopup( this, this.isModal );
this.isShowing = false;
// a11y - when the dialog is hidden, make all ScreenView content visible to assistive technology
this.setAccessibleViewsVisible( true );
}
},
/**
* Make eligible for garbage collection.
* @public
*/
dispose: function() {
this.hide();
this.disposeDialog();
Panel.prototype.dispose.call( this );
},
/**
* Hide or show all accessible content related to the sim ScreenViews, navigation bar, and alert content. Instead
* of using setVisible, we have to remove the subtree of accessible content from each view element in order to
* prevent an IE11 bug where content remains invisible in the accessibility tree, see
* https://github.com/phetsims/john-travoltage/issues/247
*
* @param {boolean} visible
*/
setAccessibleViewsVisible: function( visible ) {
for ( var i = 0; i < this.sim.screens.length; i++ ) {
this.sim.screens[ i ].view.accessibleContentDisplayed = visible;
}
this.sim.navigationBar.accessibleContentDisplayed = visible;
this.sim.homeScreen && this.sim.homeScreen.view.setAccessibleContentDisplayed( visible );
// workaround for a strange Edge bug where this child of the navigation bar remains visible,
// see https://github.com/phetsims/a11y-research/issues/30
if ( this.sim.navigationBar.keyboardHelpButton ) {
this.sim.navigationBar.keyboardHelpButton.accessibleVisible = visible;
}
},
/**
* If there is an active element, focus it. Should almost always be closed after the Dialog has been closed.
*
* @public
* @a11y
*/
focusActiveElement: function() {
this.activeElement && this.activeElement.focus();
}
} );
} ); | fix dispose bug in Dialog, https://github.com/phetsims/vegas/issues/61
| js/Dialog.js | fix dispose bug in Dialog, https://github.com/phetsims/vegas/issues/61 | <ide><path>s/Dialog.js
<ide>
<ide> if ( options.hasCloseButton ) {
<ide> closeButton.dispose();
<del> }
<del>
<del> if ( options.resize ) {
<del> dialogContent.off( 'bounds', updateClosePosition );
<del> if ( options.title ) {
<del> options.title.off( 'bounds', updateClosePosition );
<del> titleNode.off( 'localBounds', updateTitlePosition );
<del> content.off( 'bounds', updateTitlePosition );
<add>
<add> if ( options.resize ) {
<add> dialogContent.off( 'bounds', updateClosePosition );
<add> if ( options.title ) {
<add> options.title.off( 'bounds', updateClosePosition );
<add> titleNode.off( 'localBounds', updateTitlePosition );
<add> content.off( 'bounds', updateTitlePosition );
<add> }
<ide> }
<ide> }
<ide> |
|
Java | mit | 7ed5bb58c5aeea8564117cfcd87ef5abea7ef7ff | 0 | nmacedo/Pardinus,nmacedo/Pardinus,nmacedo/Pardinus,nmacedo/Pardinus,nmacedo/Pardinus | /*
* Kodkod -- Copyright (c) 2005-present, Emina Torlak
* Pardinus -- Copyright (c) 2013-present, Nuno Macedo, INESC TEC
*
* 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 kodkod.engine.ltl2fol;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import kodkod.ast.BinaryTempFormula;
import kodkod.ast.ConstantExpression;
import kodkod.ast.Expression;
import kodkod.ast.Formula;
import kodkod.ast.Node;
import kodkod.ast.Relation;
import kodkod.ast.RelationPredicate;
import kodkod.ast.TempExpression;
import kodkod.ast.UnaryTempFormula;
import kodkod.ast.Variable;
import kodkod.ast.operator.TemporalOperator;
import kodkod.ast.visitor.AbstractReplacer;
import static kodkod.engine.ltl2fol.TemporalTranslator.L_FIRST;
import static kodkod.engine.ltl2fol.TemporalTranslator.L_LAST;
import static kodkod.engine.ltl2fol.TemporalTranslator.L_PREFIX;
import static kodkod.engine.ltl2fol.TemporalTranslator.LEVEL;
import static kodkod.engine.ltl2fol.TemporalTranslator.FIRST;
import static kodkod.engine.ltl2fol.TemporalTranslator.LAST;
import static kodkod.engine.ltl2fol.TemporalTranslator.LAST_;
import static kodkod.engine.ltl2fol.TemporalTranslator.LOOP;
import static kodkod.engine.ltl2fol.TemporalTranslator.PREFIX;
import static kodkod.engine.ltl2fol.TemporalTranslator.STATE;
import static kodkod.engine.ltl2fol.TemporalTranslator.TRACE;
import static kodkod.engine.ltl2fol.TemporalTranslator.UNROLL_MAP;
import static kodkod.engine.ltl2fol.TemporalTranslator.START;
/**
* Translates an LTL temporal formula into its standard Kodkod FOL
* representation. Assumes that the variable relations have been previously
* expanded into its static version. To do so, it explicitly introduces the time
* elements into the formula, converting the temporal operators into time
* quantifiers and applying the time variable to variable relations. Since
* global temporal quantifications force the trace to be infinite, the formula
* must be in negative normal form to guarantee a correct translation.
*
* As of Pardinus 1.1, traces are assumed to always loop.
*
* @author Eduardo Pessoa, Nuno Macedo // [HASLab] temporal model finding
*/
public class LTL2FOLTranslator extends AbstractReplacer {
private Set<Relation> vars_found;
/** Pre-computed information about the formula, allows optimizations. */
private boolean has_past;
/**
* Translates an LTL temporal formula into its standard Kodkod FOL
* representation, given the extension of the variable relations.
*
* @param has_past
* whether the formula has past operators.
* @param has_loop
* whether the formula is known to force a loop.
*/
private LTL2FOLTranslator(boolean has_past) {
super(new HashSet<Node>());
this.has_past = has_past;
this.vars_found = new HashSet<Relation>();
}
/**
* Converts an LTL temporal formula into a regular Kodkod FOL formula. Uses the
* visitor to convert and adds any trace constraint left at the top level to
* handle nested post operators. It also adds the constraints that define the
* structure of the time relation constants. This is the main method that should
* be called to convert temporal formulas. The formula should be in negative
* normal form in order for the temporal quantifiers to be correctly translated.
* Optimizations will be applied if the the formula is known to force a loop or
* has no past operators.
*
* @param form
* the LTL formula to be converted.
* @param has_past
* whether the formula has past operators.
* @return the resulting FOL formula.
*/
public static Formula translate(Formula form, boolean has_past) {
LTL2FOLTranslator translator = new LTL2FOLTranslator(has_past);
Formula f;
if (TemporalTranslator.ExplicitUnrolls) {
Variable v = Variable.unary("v");
Formula order_unr_trace1 = v.join(PREFIX).one().forAll(v.oneOf(STATE.difference(LAST)));
Formula order_unr_trace2 = PREFIX.join(v).one().forAll(v.oneOf(STATE.difference(FIRST)));
Formula order_unr_trace3 = FIRST.join(PREFIX.reflexiveClosure()).eq(STATE);
Formula order_unr_trace4 = PREFIX.in(STATE.product(STATE));
if (has_past) {
Variable v1 = Variable.unary("v1");
// all s0, s1
order_unr_trace3 = order_unr_trace3.and((v.join(UNROLL_MAP).eq(v1.join(UNROLL_MAP)).implies(v.join(TRACE).join(UNROLL_MAP).eq(v1.join(TRACE).join(UNROLL_MAP)))).forAll(v1.oneOf(LAST_.join(TRACE.reflexiveClosure()))).forAll(v.oneOf(LAST_.join(TRACE.reflexiveClosure()))));
}
Formula loopDecl_unr = LOOP.one();
f = Formula.and(order_unr_trace1, order_unr_trace2, order_unr_trace3, order_unr_trace4, loopDecl_unr);
} else {
// TotalOrder(S/Next,State,S/First,S/Last)
Formula st = PREFIX.totalOrder(STATE, FIRST, LAST);
// TotalOrder(L/Next,Level,L/First,L/Last)
Formula lv = L_PREFIX.totalOrder(LEVEL, L_FIRST, L_LAST);
Formula loopDecl_unr = LOOP.one();
f = Formula.and(st,lv,loopDecl_unr);
}
translator.pushLevel();
translator.pushVariable();
Formula result = form.accept(translator);
Formula hack = Formula.TRUE;
if (!TemporalTranslator.ExplicitUnrolls) {
for (Relation r : translator.vars_found)
// r.(loop.prev) = r.last
hack = hack.and(r.join(LOOP.join(PREFIX.transpose())).eq(r.join(LAST)));
}
return Formula.and(f,result,hack);
}
/**
* Converts an LTL temporal expression into a regular Kodkod FOL expression in a
* concrete time step, counting from the {@link TemporalTranslator#FIRST
* initial} time. Uses the visitor to convert. This is the main method that
* should be called to convert temporal expressions.
*
* @param expr
* the LTL expression to be converted.
* @param state
* the concrete state on which to evaluate the expression.
* @param has_past
* whether the formula has past operators.
* @param has_loop
* whether the formula is known to force a loop.
* @return the resulting static expression.
*/
public static Expression translate(Expression expr, int state, boolean has_past) {
LTL2FOLTranslator translator = new LTL2FOLTranslator(has_past);
translator.pushVariable(state);
Expression result = expr.accept(translator);
return result;
}
@Override
public Expression visit(ConstantExpression constant) {
if (constant.equals(Expression.UNIV))
return constant.difference(STATE);
else if (constant.equals(Expression.IDEN))
return constant.difference(STATE.product(STATE));
else
return constant;
}
@Override
public Expression visit(Relation relation) {
if (relation.isVariable()) {
if (has_past && TemporalTranslator.ExplicitUnrolls)
return relation.getExpansion().join(getVariable().join(UNROLL_MAP));
else {
if (has_past) vars_found.add(relation.getExpansion());
return relation.getExpansion().join(getVariable());
}
} else
return relation;
}
@Override
public Formula visit(RelationPredicate relationPredicate) {
if (TemporalTranslator.isTemporal(relationPredicate))
// // cannot simply expand since it would loose symmetry breaking
// return relationPredicate.toConstraints().always().accept(this);
throw new UnsupportedOperationException("Total orders over variable relations still no supported.");
else
return relationPredicate;
}
@Override
public Formula visit(UnaryTempFormula unaryTempFormula) {
pushOperator(unaryTempFormula.op());
pushLevel();
pushVariable();
Formula e = unaryTempFormula.formula().accept(this);
Formula rt = getQuantifier(getOperator(), e);
popOperator();
popVariable();
popLevel();
return rt;
}
@Override
public Formula visit(BinaryTempFormula binaryTempFormula) {
pushOperator(binaryTempFormula.op());
pushLevel();
pushVariable();
Formula rt, left, right;
switch (binaryTempFormula.op()) {
case UNTIL:
right = binaryTempFormula.right().accept(this);
pushVariable();
left = binaryTempFormula.left().accept(this);
rt = getQuantifierUntil(left, right);
popVariable();
break;
case SINCE:
right = binaryTempFormula.right().accept(this);
pushVariable();
left = binaryTempFormula.left().accept(this);
rt = getQuantifierSince(left, right);
popVariable();
break;
case RELEASE:
Formula rightAlways = binaryTempFormula.right().accept(this);
pushVariable();
left = binaryTempFormula.left().accept(this);
pushLevel();
pushVariable();
right = binaryTempFormula.right().accept(this);
rt = getQuantifierRelease(rightAlways, left, right);
popVariable();
popLevel();
popVariable();
break;
case TRIGGER:
rightAlways = binaryTempFormula.right().accept(this);
pushVariable();
left = binaryTempFormula.left().accept(this);
pushLevel();
pushVariable();
right = binaryTempFormula.right().accept(this);
rt = getQuantifierTrigger(rightAlways, left, right);
popVariable();
popLevel();
popVariable();
break;
default:
throw new UnsupportedOperationException("Unsupported binary temporal operator:" + binaryTempFormula.op());
}
popVariable();
popLevel();
popOperator();
return rt;
}
@Override
public Expression visit(TempExpression tempExpression) {
pushOperator(tempExpression.op());
pushVariable();
Expression localExpression = tempExpression.expression().accept(this);
popOperator();
popVariable();
return localExpression;
}
private Formula getQuantifier(TemporalOperator op, Formula e) {
Variable s1;
Expression s0 = getVariablePrevQuant();
if (TemporalTranslator.ExplicitUnrolls) {
switch (op) {
case ALWAYS:
s1 = (Variable) getVariable();
return e.forAll(s1.oneOf(s0.join(TRACE.reflexiveClosure())));
case EVENTUALLY:
s1 = (Variable) getVariable();
return e.forSome(s1.oneOf(s0.join(TRACE.reflexiveClosure())));
case HISTORICALLY:
s1 = (Variable) getVariable();
return e.forAll(s1.oneOf(s0.join(PREFIX.transpose().reflexiveClosure())));
case ONCE:
s1 = (Variable) getVariable();
return e.forSome(s1.oneOf(s0.join(PREFIX.transpose().reflexiveClosure())));
case PREVIOUS:
Expression v2 = getVariable();
e = v2.some().and(e);
return e;
default:
return e;
}
} else {
Variable l1;
Expression l0 = getLevelPrevQuant();
switch (op) {
case ALWAYS:
s1 = (Variable) getVariable();
l1 = (Variable) getLevel();
Expression rng;
// (l1 = l0 && l1 != last) => s0.*next else State
rng = (l1.eq(l0).and(l1.eq(L_LAST).not())).thenElse(s0.join(PREFIX.reflexiveClosure()),STATE);
// l1.start.*trace & ((l1 = l0 || l1 = last) => s0.*next else State)
rng = rng.intersection(l1.join(START).join(PREFIX.reflexiveClosure()));
// all l1 : l0.*next, s1 : (l1.start.*next & ((l1 = l0 || l1 = last) => s0.*next else State)) | e
return e.forAll(s1.oneOf(rng)).forAll(l1.oneOf(l0.join(L_PREFIX.reflexiveClosure())));
case EVENTUALLY:
s1 = (Variable) getVariable();
l1 = (Variable) getLevel();
// (l1 = l0 && l1 != last) => s0.*next else State
rng = (l1.eq(l0).and(l1.eq(L_LAST).not())).thenElse(s0.join(PREFIX.reflexiveClosure()),STATE);
// l1.start.*trace & ((l1 = l0 || l1 = last) => s0.*next else State)
rng = rng.intersection(l1.join(START).join(PREFIX.reflexiveClosure()));
// some l1 : l0.*next, s1 : (l1.start.*next & ((l1 = l0 || l1 = last) => s0.*next else State)) | e
return e.forSome(s1.oneOf(rng)).forSome(l1.oneOf(l0.join(L_PREFIX.reflexiveClosure())));
case HISTORICALLY:
s1 = (Variable) getVariable();
l1 = (Variable) getLevel();
// l1 = l0 => s0.*prev else State
rng = l1.eq(l0).thenElse(s0.join(PREFIX.transpose().reflexiveClosure()),STATE);
// l1.start.*prev & (l1 = l0 => s0.*prev else State)
rng = rng.intersection(l1.join(START).join(PREFIX.reflexiveClosure()));
// all l1 : l0.*prev, s1 : l1.start.*prev & (l1 = l0 => s0.*prev else State) | e
return e.forAll(s1.oneOf(rng)).forAll(l1.oneOf(l0.join(L_PREFIX.transpose().reflexiveClosure())));
case ONCE:
s1 = (Variable) getVariable();
l1 = (Variable) getLevel();
// l1 = l0 => s0.*prev else State
rng = l1.eq(l0).thenElse(s0.join(PREFIX.transpose().reflexiveClosure()),STATE);
// l1.start.*prev & (l1 = l0 => s0.*prev else State)
rng = rng.intersection(l1.join(START).join(PREFIX.reflexiveClosure()));
// some l1 : l0.*prev, s1 : l1.start.*prev & (l1 = l0 => s0.*prev else State) | e
return e.forSome(s1.oneOf(rng)).forSome(l1.oneOf(l0.join(L_PREFIX.transpose().reflexiveClosure())));
case PREVIOUS:
// (s0 = loop && l0 != first) => last else s0.prev
Expression s0n = getVariable();
// (s0 = loop && l0 != first) => l0.prev else l0
Expression l0n = getLevel();
// some (s0 = loop && l0 != first) => last else s0.prev && e
e = s0n.some().and(e);
return e;
default:
return e;
}
}
}
private Formula getQuantifierUntil(Formula left, Formula right) {
Variable r = getVariableUntil(true);
Variable l = getVariableUntil(false);
Expression prev_l = getVariablePrevQuantUntil(false);
if (TemporalTranslator.ExplicitUnrolls) {
Formula nfleft = left.forAll(l.oneOf(upTo(prev_l, r, true, false)));
nfleft = right.and(nfleft);
return nfleft.forSome(r.oneOf(prev_l.join(TRACE.reflexiveClosure())));
}
else {
Variable vl = getLevelUntil();
Expression prev_vl = getLevelPrevQuantUntil();
Expression rng1 = (vl.eq(prev_vl.join(L_PREFIX))).thenElse(r.join(PREFIX.transpose().closure()), STATE);
Expression rng0 = (vl.eq(prev_vl)).thenElse(upTo(prev_l, r, true, false),prev_l.join(PREFIX.reflexiveClosure()).union((vl.join(START).join(PREFIX.reflexiveClosure()).intersection(rng1))));
Formula nfleft = left.forAll(l.oneOf(rng0));
nfleft = right.and(nfleft);
Expression rng = vl.eq(prev_vl).thenElse(prev_l.join(PREFIX.reflexiveClosure()),STATE);
return nfleft.forSome(r.oneOf(rng.intersection(vl.join(START).join(TRACE.reflexiveClosure())))).forSome(vl.oneOf(prev_vl.join(L_PREFIX.reflexiveClosure())));
}
}
private Formula getQuantifierSince(Formula left, Formula right) {
Variable r = getVariableUntil(true);
Variable l = getVariableUntil(false);
Expression prev_l = getVariablePrevQuantUntil(false);
if (TemporalTranslator.ExplicitUnrolls) {
Formula nfleft = left.forAll(l.oneOf(upTo(r, prev_l, false, true)));
nfleft = right.and(nfleft);
return nfleft
.forSome(r.oneOf(prev_l.join(PREFIX.transpose().reflexiveClosure())));
} else {
Variable vl = getLevelUntil();
Expression prev_vl = getLevelPrevQuantUntil();
Expression rng1 = (prev_vl.eq(vl.join(L_PREFIX))).thenElse(prev_l.join(PREFIX.transpose().reflexiveClosure()), STATE);
Expression rng0 = (vl.eq(prev_vl)).thenElse(upTo(r, prev_l, false, true),r.join(PREFIX.closure()).union((prev_vl.join(START).join(PREFIX.reflexiveClosure()).intersection(rng1))));
Formula nfleft = left.forAll(l.oneOf(rng0));
nfleft = right.and(nfleft);
Expression rng = vl.eq(prev_vl).thenElse(prev_l.join(PREFIX.transpose().reflexiveClosure()),STATE);
return nfleft.forSome(r.oneOf(rng.intersection(vl.join(START).join(PREFIX.reflexiveClosure())))).forSome(vl.oneOf(prev_vl.join(L_PREFIX.transpose().reflexiveClosure())));
}
}
private Formula getQuantifierRelease(Formula always, Formula left, Formula right) {
Variable r = getVariableRelease(true, false);
Variable l = getVariableRelease(false, false);
Variable v = getVariableRelease(false, true);
Formula alw;
Formula nfleft;
Formula nfright;
if (TemporalTranslator.ExplicitUnrolls) {
alw = always.forAll(v.oneOf(getVariablePrevQuantRelease(false, true).join(TRACE.reflexiveClosure())));
nfleft = right.forAll(l.oneOf(upTo(getVariablePrevQuantRelease(false, true), r, true, true)));
nfright = left.and(nfleft);
nfright = nfright
.forSome(r.oneOf(getVariablePrevQuantRelease(false, true).join(TRACE.reflexiveClosure())));
return alw.or(nfright); }
else
throw new UnsupportedOperationException("Releases for alterative past encoding.");
}
private Formula getQuantifierTrigger(Formula always, Formula left, Formula right) {
Variable r = getVariableRelease(true, false);
Variable l = getVariableRelease(false, false);
Variable v = getVariableRelease(false, true);
Formula alw;
Formula nfleft;
Formula nfright;
if (TemporalTranslator.ExplicitUnrolls) {
alw = always.forAll(v.oneOf(getVariablePrevQuantRelease(false, true).join(PREFIX.transpose().closure())));
nfleft = right.forAll(l.oneOf(upTo(getVariablePrevQuantRelease(false, true), r, true, true)));
nfright = left.and(nfleft);
nfright = nfright
.forSome(r.oneOf(getVariablePrevQuantRelease(false, true).join(PREFIX.transpose().closure())));
return alw.or(nfright);
}
else
throw new UnsupportedOperationException("Triggered for alterative past encoding.");
}
/**
* An expression representing all states between two states, considering loops.
*
* @param t1
* the expression representing the lower state
* @param t2
* the expression representing the upper state
* @param inc1
* whether lower inclusive
* @param inc2
* whether upper inclusive
* @return the expression representing the range states
*/
private Expression upTo(Expression t1, Expression t2, boolean inc1, boolean inc2) {
Formula c = t2.in(t1.join(PREFIX.reflexiveClosure()));
Expression exp1 = inc1 ? PREFIX.reflexiveClosure() : PREFIX.closure();
Expression exp2 = inc2 ? PREFIX.reflexiveClosure() : PREFIX.closure();
Expression exp11 = inc1 ? TRACE.reflexiveClosure() : TRACE.closure();
Expression exp12 = inc2 ? TRACE.reflexiveClosure() : TRACE.closure();
Expression e1 = (t1.join(exp1)).intersection(t2.join(exp2.transpose()));
Expression e21 = (t1.join(exp11)).intersection(t2.join(exp12.transpose()));
Expression e22 = (t2.join(exp1)).intersection(t1.join(exp2.transpose()));
Expression e2 = e21.difference(e22);
return c.thenElse(e1, e2);
}
/* Operators Context */
private List<TemporalOperator> operators = new ArrayList<TemporalOperator>();
private void pushOperator(TemporalOperator op) {
operators.add(op);
}
private TemporalOperator getOperator() {
return operators.get(operators.size() - 1);
}
private void popOperator() {
operators.remove(operators.size() - 1);
}
/* Variables */
private List<Expression> variables = new ArrayList<Expression>();
private List<Expression> variables_lvl = new ArrayList<Expression>();
private int vars = 0;
private void pushVariable() {
if (variables.isEmpty()) {
variables.add(FIRST);
return;
}
switch (getOperator()) {
case NEXT:
case PRIME:
if (TemporalTranslator.ExplicitUnrolls)
variables.add(getVariable().join(TRACE));
else
// s0.trace
variables.add(getVariable().join(TRACE));
break;
case PREVIOUS:
if (TemporalTranslator.ExplicitUnrolls)
variables.add(getVariable().join(PREFIX.transpose()));
else
// (s0 = loop && l0 != first) => last else s0.prev
variables.add((getVariable().eq(LOOP).and(getLevelPrevQuant().eq(L_FIRST).not())).thenElse(LAST,getVariable().join(PREFIX.transpose())));
break;
default:
Variable v = Variable.unary("t" + vars);
variables.add(v);
vars++;
}
}
private void pushLevel() {
if (variables_lvl.isEmpty()) {
variables_lvl.add(L_FIRST);
return;
}
switch (getOperator()) {
case NEXT:
case PRIME:
// (s0 = last && l0 != last) => l0.next else l0
variables_lvl.add((getVariable().eq(LAST).and(getLevel().eq(L_LAST).not())).thenElse(getLevel().join(L_PREFIX),getLevel()));
break;
case PREVIOUS:
// (s0 = loop && l0 != first) => l0.prev else l0
variables_lvl.add((getVariable().eq(LOOP).and(getLevel().eq(L_FIRST).not())).thenElse(getLevel().join(L_PREFIX.transpose()),getLevel()));
break;
default:
Variable v = Variable.unary("l" + vars);
variables_lvl.add(v);
}
}
/**
* Used to initialize the translation at a time other than the initial one.
*
* @param state
* the step of the trace in which to start the translation.
*/
private void pushVariable(int state) {
if (variables.isEmpty()) {
Expression s = FIRST;
for (int i = 0; i < state; i++)
s = s.join(TRACE);
variables.add(s);
} else
throw new UnsupportedOperationException("No more vars.");
}
private void popVariable() {
variables.remove(variables.size() - 1);
}
private void popLevel() {
variables_lvl.remove(variables_lvl.size() - 1);
}
private Expression getVariable() {
return variables.get(variables.size() - 1);
}
private Expression getLevel() {
return variables_lvl.get(variables_lvl.size() - 1);
}
private Expression getVariablePrevQuant() {
return variables.get(variables.size() - 2);
}
private Expression getLevelPrevQuant() {
return variables_lvl.get(variables_lvl.size() - 2);
}
private Variable getVariableUntil(boolean sideIsRight) {
if (!sideIsRight) {
return (Variable) variables.get(variables.size() - 1);
} else {
return (Variable) variables.get(variables.size() - 2);
}
}
private Variable getLevelUntil() {
return (Variable) variables_lvl.get(variables_lvl.size() - 1);
}
private Variable getVariableRelease(boolean sideIsRight, boolean isAlways) {
if (isAlways) {
return (Variable) variables.get(variables.size() - 3);
} else {
if (!sideIsRight) {
return (Variable) variables.get(variables.size() - 1);
} else {
return (Variable) variables.get(variables.size() - 2);
}
}
}
private Expression getVariablePrevQuantUntil(boolean sideIsRight) {
if (!sideIsRight) {
return variables.get(variables.size() - 3);
} else {
return variables.get(variables.size() - 2);
}
}
private Expression getLevelPrevQuantUntil() {
return variables_lvl.get(variables_lvl.size() - 2);
}
private Expression getVariablePrevQuantRelease(boolean sideIsRight, boolean isAlways) {
if (isAlways) {
return variables.get(variables.size() - 4);
} else {
if (!sideIsRight) {
return variables.get(variables.size() - 3);
} else {
return variables.get(variables.size() - 2);
}
}
}
}
| src/main/java/kodkod/engine/ltl2fol/LTL2FOLTranslator.java | /*
* Kodkod -- Copyright (c) 2005-present, Emina Torlak
* Pardinus -- Copyright (c) 2013-present, Nuno Macedo, INESC TEC
*
* 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 kodkod.engine.ltl2fol;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import kodkod.ast.BinaryTempFormula;
import kodkod.ast.ConstantExpression;
import kodkod.ast.Expression;
import kodkod.ast.Formula;
import kodkod.ast.Node;
import kodkod.ast.Relation;
import kodkod.ast.RelationPredicate;
import kodkod.ast.TempExpression;
import kodkod.ast.UnaryTempFormula;
import kodkod.ast.Variable;
import kodkod.ast.operator.TemporalOperator;
import kodkod.ast.visitor.AbstractReplacer;
import static kodkod.engine.ltl2fol.TemporalTranslator.L_FIRST;
import static kodkod.engine.ltl2fol.TemporalTranslator.L_LAST;
import static kodkod.engine.ltl2fol.TemporalTranslator.L_PREFIX;
import static kodkod.engine.ltl2fol.TemporalTranslator.LEVEL;
import static kodkod.engine.ltl2fol.TemporalTranslator.FIRST;
import static kodkod.engine.ltl2fol.TemporalTranslator.LAST;
import static kodkod.engine.ltl2fol.TemporalTranslator.LAST_;
import static kodkod.engine.ltl2fol.TemporalTranslator.LOOP;
import static kodkod.engine.ltl2fol.TemporalTranslator.PREFIX;
import static kodkod.engine.ltl2fol.TemporalTranslator.STATE;
import static kodkod.engine.ltl2fol.TemporalTranslator.TRACE;
import static kodkod.engine.ltl2fol.TemporalTranslator.UNROLL_MAP;
import static kodkod.engine.ltl2fol.TemporalTranslator.START;
/**
* Translates an LTL temporal formula into its standard Kodkod FOL
* representation. Assumes that the variable relations have been previously
* expanded into its static version. To do so, it explicitly introduces the time
* elements into the formula, converting the temporal operators into time
* quantifiers and applying the time variable to variable relations. Since
* global temporal quantifications force the trace to be infinite, the formula
* must be in negative normal form to guarantee a correct translation.
*
* As of Pardinus 1.1, traces are assumed to always loop.
*
* @author Eduardo Pessoa, Nuno Macedo // [HASLab] temporal model finding
*/
public class LTL2FOLTranslator extends AbstractReplacer {
private Set<Relation> vars_found;
/** Pre-computed information about the formula, allows optimizations. */
private boolean has_past;
/**
* Translates an LTL temporal formula into its standard Kodkod FOL
* representation, given the extension of the variable relations.
*
* @param has_past
* whether the formula has past operators.
* @param has_loop
* whether the formula is known to force a loop.
*/
private LTL2FOLTranslator(boolean has_past) {
super(new HashSet<Node>());
this.has_past = has_past;
this.vars_found = new HashSet<Relation>();
}
/**
* Converts an LTL temporal formula into a regular Kodkod FOL formula. Uses the
* visitor to convert and adds any trace constraint left at the top level to
* handle nested post operators. It also adds the constraints that define the
* structure of the time relation constants. This is the main method that should
* be called to convert temporal formulas. The formula should be in negative
* normal form in order for the temporal quantifiers to be correctly translated.
* Optimizations will be applied if the the formula is known to force a loop or
* has no past operators.
*
* @param form
* the LTL formula to be converted.
* @param has_past
* whether the formula has past operators.
* @return the resulting FOL formula.
*/
public static Formula translate(Formula form, boolean has_past) {
LTL2FOLTranslator translator = new LTL2FOLTranslator(has_past);
Formula f;
if (TemporalTranslator.ExplicitUnrolls) {
Variable v = Variable.unary("v");
Formula order_unr_trace1 = v.join(PREFIX).one().forAll(v.oneOf(STATE.difference(LAST)));
Formula order_unr_trace2 = PREFIX.join(v).one().forAll(v.oneOf(STATE.difference(FIRST)));
Formula order_unr_trace3 = FIRST.join(PREFIX.reflexiveClosure()).eq(STATE);
Formula order_unr_trace4 = PREFIX.in(STATE.product(STATE));
if (has_past) {
Variable v1 = Variable.unary("v1");
// all s0, s1
order_unr_trace3 = order_unr_trace3.and((v.join(UNROLL_MAP).eq(v1.join(UNROLL_MAP)).implies(v.join(TRACE).join(UNROLL_MAP).eq(v1.join(TRACE).join(UNROLL_MAP)))).forAll(v1.oneOf(LAST_.join(TRACE.reflexiveClosure()))).forAll(v.oneOf(LAST_.join(TRACE.reflexiveClosure()))));
}
Formula loopDecl_unr = LOOP.one();
f = Formula.and(order_unr_trace1, order_unr_trace2, order_unr_trace3, order_unr_trace4, loopDecl_unr);
} else {
// TotalOrder(S/Next,State,S/First,S/Last)
Formula st = PREFIX.totalOrder(STATE, FIRST, LAST);
// TotalOrder(L/Next,Level,L/First,L/Last)
Formula lv = L_PREFIX.totalOrder(LEVEL, L_FIRST, L_LAST);
Formula loopDecl_unr = LOOP.one();
f = Formula.and(st,lv,loopDecl_unr);
}
translator.pushLevel();
translator.pushVariable();
Formula result = form.accept(translator);
Formula hack = Formula.TRUE;
if (!TemporalTranslator.ExplicitUnrolls) {
for (Relation r : translator.vars_found)
// r.(loop.prev) = r.last
hack = hack.and(r.join(LOOP.join(PREFIX.transpose())).eq(r.join(LAST)));
}
return Formula.and(f,result,hack);
}
/**
* Converts an LTL temporal expression into a regular Kodkod FOL expression in a
* concrete time step, counting from the {@link TemporalTranslator#FIRST
* initial} time. Uses the visitor to convert. This is the main method that
* should be called to convert temporal expressions.
*
* @param expr
* the LTL expression to be converted.
* @param state
* the concrete state on which to evaluate the expression.
* @param has_past
* whether the formula has past operators.
* @param has_loop
* whether the formula is known to force a loop.
* @return the resulting static expression.
*/
public static Expression translate(Expression expr, int state, boolean has_past) {
LTL2FOLTranslator translator = new LTL2FOLTranslator(has_past);
translator.pushVariable(state);
Expression result = expr.accept(translator);
return result;
}
@Override
public Expression visit(ConstantExpression constant) {
return constant;
}
@Override
public Expression visit(Relation relation) {
if (relation.isVariable()) {
if (has_past && TemporalTranslator.ExplicitUnrolls)
return relation.getExpansion().join(getVariable().join(UNROLL_MAP));
else {
if (has_past) vars_found.add(relation.getExpansion());
return relation.getExpansion().join(getVariable());
}
} else
return relation;
}
@Override
public Formula visit(RelationPredicate relationPredicate) {
if (TemporalTranslator.isTemporal(relationPredicate))
// // cannot simply expand since it would loose symmetry breaking
// return relationPredicate.toConstraints().always().accept(this);
throw new UnsupportedOperationException("Total orders over variable relations still no supported.");
else
return relationPredicate;
}
@Override
public Formula visit(UnaryTempFormula unaryTempFormula) {
pushOperator(unaryTempFormula.op());
pushLevel();
pushVariable();
Formula e = unaryTempFormula.formula().accept(this);
Formula rt = getQuantifier(getOperator(), e);
popOperator();
popVariable();
popLevel();
return rt;
}
@Override
public Formula visit(BinaryTempFormula binaryTempFormula) {
pushOperator(binaryTempFormula.op());
pushLevel();
pushVariable();
Formula rt, left, right;
switch (binaryTempFormula.op()) {
case UNTIL:
right = binaryTempFormula.right().accept(this);
pushVariable();
left = binaryTempFormula.left().accept(this);
rt = getQuantifierUntil(left, right);
popVariable();
break;
case SINCE:
right = binaryTempFormula.right().accept(this);
pushVariable();
left = binaryTempFormula.left().accept(this);
rt = getQuantifierSince(left, right);
popVariable();
break;
case RELEASE:
Formula rightAlways = binaryTempFormula.right().accept(this);
pushVariable();
left = binaryTempFormula.left().accept(this);
pushLevel();
pushVariable();
right = binaryTempFormula.right().accept(this);
rt = getQuantifierRelease(rightAlways, left, right);
popVariable();
popLevel();
popVariable();
break;
case TRIGGER:
rightAlways = binaryTempFormula.right().accept(this);
pushVariable();
left = binaryTempFormula.left().accept(this);
pushLevel();
pushVariable();
right = binaryTempFormula.right().accept(this);
rt = getQuantifierTrigger(rightAlways, left, right);
popVariable();
popLevel();
popVariable();
break;
default:
throw new UnsupportedOperationException("Unsupported binary temporal operator:" + binaryTempFormula.op());
}
popVariable();
popLevel();
popOperator();
return rt;
}
@Override
public Expression visit(TempExpression tempExpression) {
pushOperator(tempExpression.op());
pushVariable();
Expression localExpression = tempExpression.expression().accept(this);
popOperator();
popVariable();
return localExpression;
}
private Formula getQuantifier(TemporalOperator op, Formula e) {
Variable s1;
Expression s0 = getVariablePrevQuant();
if (TemporalTranslator.ExplicitUnrolls) {
switch (op) {
case ALWAYS:
s1 = (Variable) getVariable();
return e.forAll(s1.oneOf(s0.join(TRACE.reflexiveClosure())));
case EVENTUALLY:
s1 = (Variable) getVariable();
return e.forSome(s1.oneOf(s0.join(TRACE.reflexiveClosure())));
case HISTORICALLY:
s1 = (Variable) getVariable();
return e.forAll(s1.oneOf(s0.join(PREFIX.transpose().reflexiveClosure())));
case ONCE:
s1 = (Variable) getVariable();
return e.forSome(s1.oneOf(s0.join(PREFIX.transpose().reflexiveClosure())));
case PREVIOUS:
Expression v2 = getVariable();
e = v2.some().and(e);
return e;
default:
return e;
}
} else {
Variable l1;
Expression l0 = getLevelPrevQuant();
switch (op) {
case ALWAYS:
s1 = (Variable) getVariable();
l1 = (Variable) getLevel();
Expression rng;
// (l1 = l0 && l1 != last) => s0.*next else State
rng = (l1.eq(l0).and(l1.eq(L_LAST).not())).thenElse(s0.join(PREFIX.reflexiveClosure()),STATE);
// l1.start.*trace & ((l1 = l0 || l1 = last) => s0.*next else State)
rng = rng.intersection(l1.join(START).join(PREFIX.reflexiveClosure()));
// all l1 : l0.*next, s1 : (l1.start.*next & ((l1 = l0 || l1 = last) => s0.*next else State)) | e
return e.forAll(s1.oneOf(rng)).forAll(l1.oneOf(l0.join(L_PREFIX.reflexiveClosure())));
case EVENTUALLY:
s1 = (Variable) getVariable();
l1 = (Variable) getLevel();
// (l1 = l0 && l1 != last) => s0.*next else State
rng = (l1.eq(l0).and(l1.eq(L_LAST).not())).thenElse(s0.join(PREFIX.reflexiveClosure()),STATE);
// l1.start.*trace & ((l1 = l0 || l1 = last) => s0.*next else State)
rng = rng.intersection(l1.join(START).join(PREFIX.reflexiveClosure()));
// some l1 : l0.*next, s1 : (l1.start.*next & ((l1 = l0 || l1 = last) => s0.*next else State)) | e
return e.forSome(s1.oneOf(rng)).forSome(l1.oneOf(l0.join(L_PREFIX.reflexiveClosure())));
case HISTORICALLY:
s1 = (Variable) getVariable();
l1 = (Variable) getLevel();
// l1 = l0 => s0.*prev else State
rng = l1.eq(l0).thenElse(s0.join(PREFIX.transpose().reflexiveClosure()),STATE);
// l1.start.*prev & (l1 = l0 => s0.*prev else State)
rng = rng.intersection(l1.join(START).join(PREFIX.reflexiveClosure()));
// all l1 : l0.*prev, s1 : l1.start.*prev & (l1 = l0 => s0.*prev else State) | e
return e.forAll(s1.oneOf(rng)).forAll(l1.oneOf(l0.join(L_PREFIX.transpose().reflexiveClosure())));
case ONCE:
s1 = (Variable) getVariable();
l1 = (Variable) getLevel();
// l1 = l0 => s0.*prev else State
rng = l1.eq(l0).thenElse(s0.join(PREFIX.transpose().reflexiveClosure()),STATE);
// l1.start.*prev & (l1 = l0 => s0.*prev else State)
rng = rng.intersection(l1.join(START).join(PREFIX.reflexiveClosure()));
// some l1 : l0.*prev, s1 : l1.start.*prev & (l1 = l0 => s0.*prev else State) | e
return e.forSome(s1.oneOf(rng)).forSome(l1.oneOf(l0.join(L_PREFIX.transpose().reflexiveClosure())));
case PREVIOUS:
// (s0 = loop && l0 != first) => last else s0.prev
Expression s0n = getVariable();
// (s0 = loop && l0 != first) => l0.prev else l0
Expression l0n = getLevel();
// some (s0 = loop && l0 != first) => last else s0.prev && e
e = s0n.some().and(e);
return e;
default:
return e;
}
}
}
private Formula getQuantifierUntil(Formula left, Formula right) {
Variable r = getVariableUntil(true);
Variable l = getVariableUntil(false);
Expression prev_l = getVariablePrevQuantUntil(false);
if (TemporalTranslator.ExplicitUnrolls) {
Formula nfleft = left.forAll(l.oneOf(upTo(prev_l, r, true, false)));
nfleft = right.and(nfleft);
return nfleft.forSome(r.oneOf(prev_l.join(TRACE.reflexiveClosure())));
}
else {
Variable vl = getLevelUntil();
Expression prev_vl = getLevelPrevQuantUntil();
Expression rng1 = (vl.eq(prev_vl.join(L_PREFIX))).thenElse(r.join(PREFIX.transpose().closure()), STATE);
Expression rng0 = (vl.eq(prev_vl)).thenElse(upTo(prev_l, r, true, false),prev_l.join(PREFIX.reflexiveClosure()).union((vl.join(START).join(PREFIX.reflexiveClosure()).intersection(rng1))));
Formula nfleft = left.forAll(l.oneOf(rng0));
nfleft = right.and(nfleft);
Expression rng = vl.eq(prev_vl).thenElse(prev_l.join(PREFIX.reflexiveClosure()),STATE);
return nfleft.forSome(r.oneOf(rng.intersection(vl.join(START).join(TRACE.reflexiveClosure())))).forSome(vl.oneOf(prev_vl.join(L_PREFIX.reflexiveClosure())));
}
}
private Formula getQuantifierSince(Formula left, Formula right) {
Variable r = getVariableUntil(true);
Variable l = getVariableUntil(false);
Expression prev_l = getVariablePrevQuantUntil(false);
if (TemporalTranslator.ExplicitUnrolls) {
Formula nfleft = left.forAll(l.oneOf(upTo(r, prev_l, false, true)));
nfleft = right.and(nfleft);
return nfleft
.forSome(r.oneOf(prev_l.join(PREFIX.transpose().reflexiveClosure())));
} else {
Variable vl = getLevelUntil();
Expression prev_vl = getLevelPrevQuantUntil();
Expression rng1 = (prev_vl.eq(vl.join(L_PREFIX))).thenElse(prev_l.join(PREFIX.transpose().reflexiveClosure()), STATE);
Expression rng0 = (vl.eq(prev_vl)).thenElse(upTo(r, prev_l, false, true),r.join(PREFIX.closure()).union((prev_vl.join(START).join(PREFIX.reflexiveClosure()).intersection(rng1))));
Formula nfleft = left.forAll(l.oneOf(rng0));
nfleft = right.and(nfleft);
Expression rng = vl.eq(prev_vl).thenElse(prev_l.join(PREFIX.transpose().reflexiveClosure()),STATE);
return nfleft.forSome(r.oneOf(rng.intersection(vl.join(START).join(PREFIX.reflexiveClosure())))).forSome(vl.oneOf(prev_vl.join(L_PREFIX.transpose().reflexiveClosure())));
}
}
private Formula getQuantifierRelease(Formula always, Formula left, Formula right) {
Variable r = getVariableRelease(true, false);
Variable l = getVariableRelease(false, false);
Variable v = getVariableRelease(false, true);
Formula alw;
Formula nfleft;
Formula nfright;
if (TemporalTranslator.ExplicitUnrolls) {
alw = always.forAll(v.oneOf(getVariablePrevQuantRelease(false, true).join(TRACE.reflexiveClosure())));
nfleft = right.forAll(l.oneOf(upTo(getVariablePrevQuantRelease(false, true), r, true, true)));
nfright = left.and(nfleft);
nfright = nfright
.forSome(r.oneOf(getVariablePrevQuantRelease(false, true).join(TRACE.reflexiveClosure())));
return alw.or(nfright); }
else
throw new UnsupportedOperationException("Releases for alterative past encoding.");
}
private Formula getQuantifierTrigger(Formula always, Formula left, Formula right) {
Variable r = getVariableRelease(true, false);
Variable l = getVariableRelease(false, false);
Variable v = getVariableRelease(false, true);
Formula alw;
Formula nfleft;
Formula nfright;
if (TemporalTranslator.ExplicitUnrolls) {
alw = always.forAll(v.oneOf(getVariablePrevQuantRelease(false, true).join(PREFIX.transpose().closure())));
nfleft = right.forAll(l.oneOf(upTo(getVariablePrevQuantRelease(false, true), r, true, true)));
nfright = left.and(nfleft);
nfright = nfright
.forSome(r.oneOf(getVariablePrevQuantRelease(false, true).join(PREFIX.transpose().closure())));
return alw.or(nfright);
}
else
throw new UnsupportedOperationException("Triggered for alterative past encoding.");
}
/**
* An expression representing all states between two states, considering loops.
*
* @param t1
* the expression representing the lower state
* @param t2
* the expression representing the upper state
* @param inc1
* whether lower inclusive
* @param inc2
* whether upper inclusive
* @return the expression representing the range states
*/
private Expression upTo(Expression t1, Expression t2, boolean inc1, boolean inc2) {
Formula c = t2.in(t1.join(PREFIX.reflexiveClosure()));
Expression exp1 = inc1 ? PREFIX.reflexiveClosure() : PREFIX.closure();
Expression exp2 = inc2 ? PREFIX.reflexiveClosure() : PREFIX.closure();
Expression exp11 = inc1 ? TRACE.reflexiveClosure() : TRACE.closure();
Expression exp12 = inc2 ? TRACE.reflexiveClosure() : TRACE.closure();
Expression e1 = (t1.join(exp1)).intersection(t2.join(exp2.transpose()));
Expression e21 = (t1.join(exp11)).intersection(t2.join(exp12.transpose()));
Expression e22 = (t2.join(exp1)).intersection(t1.join(exp2.transpose()));
Expression e2 = e21.difference(e22);
return c.thenElse(e1, e2);
}
/* Operators Context */
private List<TemporalOperator> operators = new ArrayList<TemporalOperator>();
private void pushOperator(TemporalOperator op) {
operators.add(op);
}
private TemporalOperator getOperator() {
return operators.get(operators.size() - 1);
}
private void popOperator() {
operators.remove(operators.size() - 1);
}
/* Variables */
private List<Expression> variables = new ArrayList<Expression>();
private List<Expression> variables_lvl = new ArrayList<Expression>();
private int vars = 0;
private void pushVariable() {
if (variables.isEmpty()) {
variables.add(FIRST);
return;
}
switch (getOperator()) {
case NEXT:
case PRIME:
if (TemporalTranslator.ExplicitUnrolls)
variables.add(getVariable().join(TRACE));
else
// s0.trace
variables.add(getVariable().join(TRACE));
break;
case PREVIOUS:
if (TemporalTranslator.ExplicitUnrolls)
variables.add(getVariable().join(PREFIX.transpose()));
else
// (s0 = loop && l0 != first) => last else s0.prev
variables.add((getVariable().eq(LOOP).and(getLevelPrevQuant().eq(L_FIRST).not())).thenElse(LAST,getVariable().join(PREFIX.transpose())));
break;
default:
Variable v = Variable.unary("t" + vars);
variables.add(v);
vars++;
}
}
private void pushLevel() {
if (variables_lvl.isEmpty()) {
variables_lvl.add(L_FIRST);
return;
}
switch (getOperator()) {
case NEXT:
case PRIME:
// (s0 = last && l0 != last) => l0.next else l0
variables_lvl.add((getVariable().eq(LAST).and(getLevel().eq(L_LAST).not())).thenElse(getLevel().join(L_PREFIX),getLevel()));
break;
case PREVIOUS:
// (s0 = loop && l0 != first) => l0.prev else l0
variables_lvl.add((getVariable().eq(LOOP).and(getLevel().eq(L_FIRST).not())).thenElse(getLevel().join(L_PREFIX.transpose()),getLevel()));
break;
default:
Variable v = Variable.unary("l" + vars);
variables_lvl.add(v);
}
}
/**
* Used to initialize the translation at a time other than the initial one.
*
* @param state
* the step of the trace in which to start the translation.
*/
private void pushVariable(int state) {
if (variables.isEmpty()) {
Expression s = FIRST;
for (int i = 0; i < state; i++)
s = s.join(TRACE);
variables.add(s);
} else
throw new UnsupportedOperationException("No more vars.");
}
private void popVariable() {
variables.remove(variables.size() - 1);
}
private void popLevel() {
variables_lvl.remove(variables_lvl.size() - 1);
}
private Expression getVariable() {
return variables.get(variables.size() - 1);
}
private Expression getLevel() {
return variables_lvl.get(variables_lvl.size() - 1);
}
private Expression getVariablePrevQuant() {
return variables.get(variables.size() - 2);
}
private Expression getLevelPrevQuant() {
return variables_lvl.get(variables_lvl.size() - 2);
}
private Variable getVariableUntil(boolean sideIsRight) {
if (!sideIsRight) {
return (Variable) variables.get(variables.size() - 1);
} else {
return (Variable) variables.get(variables.size() - 2);
}
}
private Variable getLevelUntil() {
return (Variable) variables_lvl.get(variables_lvl.size() - 1);
}
private Variable getVariableRelease(boolean sideIsRight, boolean isAlways) {
if (isAlways) {
return (Variable) variables.get(variables.size() - 3);
} else {
if (!sideIsRight) {
return (Variable) variables.get(variables.size() - 1);
} else {
return (Variable) variables.get(variables.size() - 2);
}
}
}
private Expression getVariablePrevQuantUntil(boolean sideIsRight) {
if (!sideIsRight) {
return variables.get(variables.size() - 3);
} else {
return variables.get(variables.size() - 2);
}
}
private Expression getLevelPrevQuantUntil() {
return variables_lvl.get(variables_lvl.size() - 2);
}
private Expression getVariablePrevQuantRelease(boolean sideIsRight, boolean isAlways) {
if (isAlways) {
return variables.get(variables.size() - 4);
} else {
if (!sideIsRight) {
return variables.get(variables.size() - 3);
} else {
return variables.get(variables.size() - 2);
}
}
}
}
| fixed bug on temporal expanding constants
| src/main/java/kodkod/engine/ltl2fol/LTL2FOLTranslator.java | fixed bug on temporal expanding constants | <ide><path>rc/main/java/kodkod/engine/ltl2fol/LTL2FOLTranslator.java
<ide>
<ide> @Override
<ide> public Expression visit(ConstantExpression constant) {
<del> return constant;
<add> if (constant.equals(Expression.UNIV))
<add> return constant.difference(STATE);
<add> else if (constant.equals(Expression.IDEN))
<add> return constant.difference(STATE.product(STATE));
<add> else
<add> return constant;
<ide> }
<ide>
<ide> @Override |
|
JavaScript | mit | e099f39ffee5f76e123a61d14f5bcadf3c6db20e | 0 | Mike96Angelo/Bars,Mike96Angelo/Bars | var Generator = require('generate-js');
var utils = require('compileit/lib/utils');
var Context = Generator.generate(function Context(data, props, context, cleanVars) {
var _ = this;
_.data = data;
_.props = props;
_.context = context;
if (cleanVars || !context) {
_.vars = Object.create(null);
} else {
_.vars = Object.create(context.vars);
}
});
Context.definePrototype({
lookup: function lookup(path) {
var _ = this,
i = 0;
if (path[0] === '@') {
if (_.props) {
return _.props[path[1]];
} else {
return void(0);
}
}
if (
path[0] === 'this'
) {
return _.data;
}
if (_.vars && path[0] in _.vars) {
return _.vars[path[0]];
}
return _.data ? _.data[path[0]] : void(0);
},
newContext: function newContext(data, props, cleanVars) {
return new Context(data, props, this, cleanVars);
},
contextWithVars: function contextWithVars(vars) {
var _ = this;
var context = new Context(_.data, _.props, _);
context.setVars(vars);
return context;
},
setVars: function setVars(vars) {
var _ = this;
for (var v in vars) {
if (vars.hasOwnProperty(v)) {
_.vars[v] = vars[v];
}
}
}
});
module.exports = Context;
| lib/runtime/context-n.js | var Generator = require('generate-js');
var utils = require('compileit/lib/utils');
var Context = Generator.generate(function Context(data, props, context, cleanVars) {
var _ = this;
_.data = data;
_.props = props;
_.context = context;
if (cleanVars || !context) {
_.vars = Object.create(null);
} else {
_.vars = Object.create(context.vars);
}
});
Context.definePrototype({
lookup: function lookup(path) {
var _ = this,
i = 0;
if (path[0] === '@') {
if (_.props) {
return _.props[path[1]];
} else {
return void(0);
}
}
if (
path[0] === 'this'
) {
return _.data;
}
if (_.vars && path[0] in _.vars) {
return _.vars[path[0]];
}
return _.data[path[0]];
},
newContext: function newContext(data, props, cleanVars) {
return new Context(data, props, this, cleanVars);
},
contextWithVars: function contextWithVars(vars) {
var _ = this;
var context = new Context(_.data, _.props, _);
context.setVars(vars);
return context;
},
setVars: function setVars(vars) {
var _ = this;
for (var v in vars) {
if (vars.hasOwnProperty(v)) {
_.vars[v] = vars[v];
}
}
}
});
module.exports = Context;
| Return softly on lookup. | lib/runtime/context-n.js | Return softly on lookup. | <ide><path>ib/runtime/context-n.js
<ide> return _.vars[path[0]];
<ide> }
<ide>
<del> return _.data[path[0]];
<add> return _.data ? _.data[path[0]] : void(0);
<ide> },
<ide> newContext: function newContext(data, props, cleanVars) {
<ide> return new Context(data, props, this, cleanVars); |
|
Java | apache-2.0 | 4d2bbb7c75e39b42e053acc0d3e1586135a7b5e7 | 0 | proofpoint/platform,johngmyers/platform,proofpoint/platform,johngmyers/platform,gwittel/platform,gwittel/platform,proofpoint/platform,johngmyers/platform,gwittel/platform | package com.proofpoint.http.client;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.proofpoint.http.client.DynamicBodySource.Writer;
import com.proofpoint.http.client.HttpClient.HttpResponseFuture;
import com.proofpoint.http.client.StatusResponseHandler.StatusResponse;
import com.proofpoint.http.client.StringResponseHandler.StringResponse;
import com.proofpoint.http.client.jetty.JettyHttpClient;
import com.proofpoint.log.Logging;
import com.proofpoint.testing.Assertions;
import com.proofpoint.testing.Closeables;
import com.proofpoint.tracetoken.TraceToken;
import com.proofpoint.units.Duration;
import org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory;
import org.eclipse.jetty.http2.server.HTTP2CServerConnectionFactory;
import org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory;
import org.eclipse.jetty.server.ConnectionFactory;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.gzip.GzipHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.testng.Assert;
import org.testng.SkipException;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UncheckedIOException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.UnresolvedAddressException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static com.google.common.base.Throwables.getStackTraceAsString;
import static com.google.common.base.Throwables.propagateIfPossible;
import static com.google.common.base.Throwables.throwIfUnchecked;
import static com.google.common.net.HttpHeaders.ACCEPT_ENCODING;
import static com.google.common.net.HttpHeaders.CONTENT_TYPE;
import static com.proofpoint.concurrent.Threads.threadsNamed;
import static com.proofpoint.http.client.Request.Builder.prepareDelete;
import static com.proofpoint.http.client.Request.Builder.prepareGet;
import static com.proofpoint.http.client.Request.Builder.preparePost;
import static com.proofpoint.http.client.Request.Builder.preparePut;
import static com.proofpoint.http.client.StatusResponseHandler.createStatusResponseHandler;
import static com.proofpoint.http.client.StringResponseHandler.createStringResponseHandler;
import static com.proofpoint.testing.Assertions.assertGreaterThan;
import static com.proofpoint.testing.Assertions.assertGreaterThanOrEqual;
import static com.proofpoint.testing.Assertions.assertLessThan;
import static com.proofpoint.testing.Closeables.closeQuietly;
import static com.proofpoint.tracetoken.TraceTokenManager.createAndRegisterNewRequestToken;
import static com.proofpoint.tracetoken.TraceTokenManager.getCurrentTraceToken;
import static com.proofpoint.units.Duration.nanosSince;
import static java.lang.Math.toIntExact;
import static java.lang.String.format;
import static java.lang.Thread.currentThread;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
@SuppressWarnings("InputStreamSlowMultibyteRead")
public abstract class AbstractHttpClientTest
{
private static final String THOUSAND_X = Strings.repeat("x", 1000);
protected EchoServlet servlet;
protected Server server;
protected URI baseURI;
private String scheme = "http";
private String host = "127.0.0.1";
private String keystore = null;
protected RequestStats stats;
private SslContextFactory sslContextFactory;
protected AbstractHttpClientTest()
{
}
protected AbstractHttpClientTest(String host, String keystore)
{
scheme = "https";
this.host = host;
this.keystore = keystore;
}
protected abstract HttpClientConfig createClientConfig();
private void executeExceptionRequest(HttpClientConfig config, Request request)
throws Exception
{
try {
executeRequest(config, request, new CaptureExceptionResponseHandler());
fail("expected exception");
}
catch (CapturedException e) {
propagateIfPossible(e.getCause(), Exception.class);
throw new RuntimeException(e.getCause());
}
}
public abstract <T, E extends Exception> T executeRequest(Request request, ResponseHandler<T, E> responseHandler)
throws Exception;
public final <T, E extends Exception> T executeRequest(HttpClientConfig config, Request request, ResponseHandler<T, E> responseHandler)
throws Exception
{
try (ClientTester clientTester = clientTester(config)) {
return clientTester.executeRequest(request, responseHandler);
}
}
public abstract ClientTester clientTester(HttpClientConfig config);
public interface ClientTester
extends Closeable
{
<T, E extends Exception> T executeRequest(Request request, ResponseHandler<T, E> responseHandler)
throws Exception;
}
@BeforeSuite
public void setupSuite()
{
Logging.initialize();
}
@BeforeMethod
public void abstractSetup()
throws Exception
{
servlet = new EchoServlet();
Server server = new Server();
HttpConfiguration httpConfiguration = new HttpConfiguration();
httpConfiguration.setSendServerVersion(false);
httpConfiguration.setSendXPoweredBy(false);
List<ConnectionFactory> connectionFactories = new ArrayList<>();
if (keystore != null) {
boolean isJava8 = System.getProperty("java.version").startsWith("1.8.");
httpConfiguration.addCustomizer(new SecureRequestCustomizer());
sslContextFactory = new SslContextFactory(keystore);
sslContextFactory.setKeyStorePassword("changeit");
connectionFactories.add(new SslConnectionFactory(sslContextFactory, isJava8 ? "http/1.1" : "alpn"));
if (!isJava8) {
connectionFactories.add(new ALPNServerConnectionFactory("h2", "http/1.1"));
connectionFactories.add(new HTTP2ServerConnectionFactory(httpConfiguration));
}
connectionFactories.add(new HttpConnectionFactory(httpConfiguration));
}
else {
connectionFactories.add(new HttpConnectionFactory(httpConfiguration));
connectionFactories.add(new HTTP2CServerConnectionFactory(httpConfiguration));
}
ServerConnector connector = new ServerConnector(server, connectionFactories.toArray(new ConnectionFactory[]{}));
connector.setIdleTimeout(30000);
connector.setName(scheme);
server.addConnector(connector);
ServletHolder servletHolder = new ServletHolder(servlet);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
context.addServlet(servletHolder, "/*");
HandlerCollection handlers = new HandlerCollection();
handlers.addHandler(context);
server.setHandler(handlers);
this.server = server;
server.start();
baseURI = new URI(scheme, null, host, connector.getLocalPort(), null, null, null);
}
@AfterMethod(alwaysRun = true)
public void abstractTeardown()
throws Exception
{
if (server != null) {
server.setStopTimeout(3000);
server.stop();
}
Logging.resetLogTesters();
}
@Test(enabled = false, description = "This takes over a minute to run")
public void test100kGets()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere?query");
Request request = prepareGet()
.setUri(uri)
.addHeader("foo", "bar")
.addHeader("dupe", "first")
.addHeader("dupe", "second")
.build();
for (int i = 0; i < 100_000; i++) {
try {
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
}
catch (Exception e) {
throw new Exception("Error on request " + i, e);
}
}
}
// Disabled because it is too flaky
@Test(timeOut = 4000, enabled = false)
public void testConnectTimeout()
throws Exception
{
try (BackloggedServer server = new BackloggedServer()) {
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, MILLISECONDS));
config.setIdleTimeout(new Duration(2, SECONDS));
Request request = prepareGet()
.setUri(new URI(scheme, null, host, server.getPort(), "/", null, null))
.build();
long start = System.nanoTime();
try {
executeRequest(config, request, new CaptureExceptionResponseHandler());
fail("expected exception");
}
catch (CapturedException e) {
Throwable t = e.getCause();
if (!(isConnectTimeout(t) || t instanceof ClosedChannelException)) {
fail(format("unexpected exception: [%s]", getStackTraceAsString(t)));
}
assertLessThan(nanosSince(start), new Duration(300, MILLISECONDS));
}
}
}
@Test(expectedExceptions = {ConnectException.class, SocketTimeoutException.class})
public void testConnectionRefused()
throws Exception
{
int port = findUnusedPort();
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, SECONDS));
Request request = prepareGet()
.setUri(new URI(scheme, null, host, port, "/", null, null))
.build();
executeExceptionRequest(config, request);
}
@Test
public void testConnectionRefusedWithDefaultingResponseExceptionHandler()
throws Exception
{
int port = findUnusedPort();
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, MILLISECONDS));
Request request = prepareGet()
.setUri(new URI(scheme, null, host, port, "/", null, null))
.build();
Object expected = new Object();
assertEquals(executeRequest(config, request, new DefaultOnExceptionResponseHandler(expected)), expected);
}
@Test(expectedExceptions = {UnknownHostException.class, UnresolvedAddressException.class}, timeOut = 10000)
public void testUnresolvableHost()
throws Exception
{
String invalidHost = "nonexistent.invalid";
assertUnknownHost(invalidHost);
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, SECONDS));
Request request = prepareGet()
.setUri(URI.create("http://" + invalidHost))
.build();
executeExceptionRequest(config, request);
}
@Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = ".*port out of range.*")
public void testBadPort()
throws Exception
{
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, MILLISECONDS));
Request request = prepareGet()
.setUri(new URI(scheme, null, host, 70_000, "/", null, null))
.build();
executeExceptionRequest(config, request);
}
@Test
public void testDeleteMethod()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere");
Request request = prepareDelete()
.setUri(uri)
.addHeader("foo", "bar")
.addHeader("dupe", "first")
.addHeader("dupe", "second")
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "DELETE");
assertEquals(servlet.getRequestUri(), uri);
assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar"));
assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second"));
assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value"));
}
@Test
public void testErrorResponseBody()
throws Exception
{
servlet.setResponseStatusCode(500);
servlet.setResponseBody("body text");
Request request = prepareGet()
.setUri(baseURI)
.build();
StringResponse response = executeRequest(request, createStringResponseHandler());
assertEquals(response.getStatusCode(), 500);
assertEquals(response.getBody(), "body text");
}
@Test
public void testGetMethod()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere?query");
Request request = prepareGet()
.setUri(uri)
.addHeader("foo", "bar")
.addHeader("dupe", "first")
.addHeader("dupe", "second")
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "GET");
if (servlet.getRequestUri().toString().endsWith("=")) {
// todo jetty client rewrites the uri string for some reason
assertEquals(servlet.getRequestUri(), new URI(uri + "="));
}
else {
assertEquals(servlet.getRequestUri(), uri);
}
assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar"));
assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second"));
assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value"));
}
@Test
public void testResponseHeadersCaseInsensitive()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere");
Request request = prepareGet()
.setUri(uri)
.build();
Response response = executeRequest(request, new PassThroughResponseHandler());
assertNotNull(response.getHeader("date"));
assertNotNull(response.getHeader("DATE"));
assertEquals(response.getHeaders("date").size(), 1);
assertEquals(response.getHeaders("DATE").size(), 1);
}
@Test
public void testKeepAlive()
throws Exception
{
URI uri = URI.create(baseURI.toASCIIString() + "/?remotePort=");
Request request = prepareGet()
.setUri(uri)
.build();
StatusResponse response1 = executeRequest(request, createStatusResponseHandler());
Thread.sleep(1000);
StatusResponse response2 = executeRequest(request, createStatusResponseHandler());
Thread.sleep(1000);
StatusResponse response3 = executeRequest(request, createStatusResponseHandler());
assertNotNull(response1.getHeader("remotePort"));
assertNotNull(response2.getHeader("remotePort"));
assertNotNull(response3.getHeader("remotePort"));
int port1 = Integer.parseInt(response1.getHeader("remotePort"));
int port2 = Integer.parseInt(response2.getHeader("remotePort"));
int port3 = Integer.parseInt(response3.getHeader("remotePort"));
assertEquals(port2, port1);
assertEquals(port3, port1);
Assertions.assertBetweenInclusive(port1, 1024, 65535);
}
@Test
public void testPostMethod()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere");
Request request = preparePost()
.setUri(uri)
.addHeader("foo", "bar")
.addHeader("dupe", "first")
.addHeader("dupe", "second")
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "POST");
assertEquals(servlet.getRequestUri(), uri);
assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar"));
assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second"));
assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value"));
}
@Test
public void testPutMethod()
throws Exception
{
servlet.setResponseBody("response");
URI uri = baseURI.resolve("/road/to/nowhere");
Request request = preparePut()
.setUri(uri)
.addHeader("foo", "bar")
.addHeader("dupe", "first")
.addHeader("dupe", "second")
.build();
int statusCode = executeRequest(request, createStringResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "PUT");
assertEquals(servlet.getRequestUri(), uri);
assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar"));
assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second"));
assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value"));
assertEquals(stats.getWrittenBytes().getAllTime().getTotal(), 0.0);
}
@Test
public void testPutMethodWithStaticBodyGenerator()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere");
byte[] body = {1, 2, 5};
Request request = preparePut()
.setUri(uri)
.addHeader("foo", "bar")
.addHeader("dupe", "first")
.addHeader("dupe", "second")
.setBodyGenerator(StaticBodyGenerator.createStaticBodyGenerator(body))
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "PUT");
assertEquals(servlet.getRequestUri(), uri);
assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar"));
assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second"));
assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value"));
assertEquals(servlet.getRequestBytes(), body);
assertEquals(stats.getWrittenBytes().getAllTime().getTotal(), 3.0);
}
@Test
public void testPutMethodWithInputStreamBodySource()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere");
Request request = preparePut()
.setUri(uri)
.addHeader("foo", "bar")
.addHeader("dupe", "first")
.addHeader("dupe", "second")
.setBodySource(new InputStreamBodySource(new InputStream()
{
AtomicInteger invocation = new AtomicInteger(0);
@Override
public int read()
throws IOException
{
throw new UnsupportedOperationException();
}
@Override
public int read(byte[] b)
throws IOException
{
switch (invocation.getAndIncrement()) {
case 0:
assertEquals(b.length, 8123);
b[0] = 1;
return 1;
case 1:
b[0] = 2;
b[1] = 5;
return 2;
case 2:
return -1;
default:
fail("unexpected invocation of write()");
return -1;
}
}
}, 8123))
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "PUT");
assertEquals(servlet.getRequestUri(), uri);
assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar"));
assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second"));
assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value"));
assertEquals(servlet.getRequestBytes(), new byte[]{1, 2, 5});
assertEquals(stats.getWrittenBytes().getAllTime().getTotal(), 3.0);
}
@Test
public void testPutMethodWithInputStreamBodySourceContentLength()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere");
Request request = preparePut()
.setUri(uri)
.setBodySource(new InputStreamBodySource(new InputStream()
{
AtomicInteger invocation = new AtomicInteger(0);
@Override
public int read()
throws IOException
{
throw new UnsupportedOperationException();
}
@Override
public int read(byte[] b)
throws IOException
{
switch (invocation.getAndIncrement()) {
case 0:
assertEquals(b.length, 8123);
b[0] = 1;
return 1;
case 1:
b[0] = 2;
b[1] = 3;
return 2;
case 2:
return -1;
default:
fail("unexpected invocation of write()");
return -1;
}
}
}, 8123) {
@Override
public long getLength()
{
return 3;
}
})
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "PUT");
assertEquals(servlet.getRequestUri(), uri);
assertEquals(servlet.getRequestHeaders("Content-Length"), ImmutableList.of("3"));
assertEquals(servlet.getRequestBytes(), new byte[]{1, 2, 3});
assertEquals(stats.getWrittenBytes().getAllTime().getTotal(), 3.0);
}
@Test
public void testPutMethodWithDynamicBodySource()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere");
Request request = preparePut()
.setUri(uri)
.addHeader("foo", "bar")
.addHeader("dupe", "first")
.addHeader("dupe", "second")
.setBodySource((DynamicBodySource) out -> new Writer()
{
AtomicInteger invocation = new AtomicInteger(0);
@Override
public void write()
throws Exception
{
switch (invocation.getAndIncrement()) {
case 0:
out.write(1);
break;
case 1:
byte[] bytes = {2, 5};
out.write(bytes);
bytes[0] = 9;
out.close();
break;
default:
fail("unexpected invocation of write()");
}
}
})
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "PUT");
assertEquals(servlet.getRequestUri(), uri);
assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar"));
assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second"));
assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value"));
assertEquals(servlet.getRequestBytes(), new byte[]{1, 2, 5});
assertEquals(stats.getWrittenBytes().getAllTime().getTotal(), 3.0);
}
@Test
public void testPutMethodWithDynamicBodySourceEdgeCases()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere");
final AtomicBoolean closed = new AtomicBoolean(false);
Request request = preparePut()
.setUri(uri)
.addHeader("foo", "bar")
.addHeader("dupe", "first")
.addHeader("dupe", "second")
.setBodySource((DynamicBodySource) out -> {
out.write(1);
return new EdgeCaseTestWriter(out, closed);
})
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "PUT");
assertEquals(servlet.getRequestUri(), uri);
assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar"));
assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second"));
assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value"));
assertEquals(servlet.getRequestBytes(), createByteArray(1, 15008));
assertTrue(closed.get(), "Writer was closed");
assertEquals(stats.getWrittenBytes().getAllTime().getTotal(), 15008.0);
}
private static class EdgeCaseTestWriter
implements Writer, AutoCloseable
{
AtomicInteger invocation = new AtomicInteger(0);
private final OutputStream out;
private final AtomicBoolean closed;
EdgeCaseTestWriter(OutputStream out, AtomicBoolean closed)
{
this.out = out;
this.closed = closed;
}
@Override
public void write()
throws Exception
{
switch (invocation.getAndIncrement()) {
case 0:
break;
case 1:
byte[] bytes = {2, 3};
out.write(bytes);
bytes[0] = 9;
break;
case 2:
out.write(createByteArray(4, 2));
out.write(6);
out.write(createByteArray(7, 2));
out.write(createByteArray(9, 5000));
byte[] lastArray = createByteArray(5009, 10_000);
out.write(lastArray);
lastArray[0] = 0;
lastArray[1] = 0;
break;
case 3:
out.close();
break;
default:
fail("unexpected invocation of write()");
}
}
@Override
public void close()
{
closed.set(true);
}
}
private static byte[] createByteArray(int firstValue, int length)
{
byte[] bytes = new byte[length];
for (int i = 0; i < length; i++) {
bytes[i] = (byte)firstValue++;
}
return bytes;
}
@Test
public void testPutMethodWithDynamicBodySourceContentLength()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere");
Request request = preparePut()
.setUri(uri)
.setBodySource(new DynamicBodySource()
{
@Override
public long getLength()
{
return 3;
}
@Override
public Writer start(OutputStream out)
throws Exception
{
return new Writer()
{
AtomicInteger invocation = new AtomicInteger(0);
@Override
public void write()
throws Exception
{
switch (invocation.getAndIncrement()) {
case 0:
out.write(1);
break;
case 1:
byte[] bytes = {2, 5};
out.write(bytes);
out.close();
break;
default:
fail("unexpected invocation of write()");
}
}
};
}
})
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "PUT");
assertEquals(servlet.getRequestUri(), uri);
assertEquals(servlet.getRequestHeaders("Content-Length"), ImmutableList.of("3"));
assertEquals(servlet.getRequestBytes(), new byte[]{1, 2, 5});
assertEquals(stats.getWrittenBytes().getAllTime().getTotal(), 3.0);
}
@Test
public void testDynamicBodySourceSeesTraceToken()
throws Exception
{
createAndRegisterNewRequestToken("somekey", "somevalue");
TraceToken token = getCurrentTraceToken();
AtomicReference<TraceToken> writeToken = new AtomicReference<>();
CountDownLatch closeLatch = new CountDownLatch(1);
AtomicReference<TraceToken> closeToken = new AtomicReference<>();
URI uri = baseURI.resolve("/road/to/nowhere");
Request request = preparePut()
.setUri(uri)
.addHeader("foo", "bar")
.addHeader("dupe", "first")
.addHeader("dupe", "second")
.setBodySource((DynamicBodySource) out -> {
assertEquals(getCurrentTraceToken(), token);
return new TraceTokenTestWriter(out, writeToken, closeLatch, closeToken);
})
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "PUT");
assertEquals(servlet.getRequestUri(), uri);
assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar"));
assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second"));
assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value"));
assertEquals(servlet.getRequestBytes(), new byte[] {});
assertEquals(writeToken.get(), token);
assertTrue(closeLatch.await(1, SECONDS));
assertEquals(closeToken.get(), token);
}
private static class TraceTokenTestWriter
implements Writer, AutoCloseable
{
private final OutputStream out;
private final AtomicReference<TraceToken> writeToken;
private final CountDownLatch closeLatch;
private final AtomicReference<TraceToken> closeToken;
TraceTokenTestWriter(OutputStream out, AtomicReference<TraceToken> writeToken, CountDownLatch closeLatch, AtomicReference<TraceToken> closeToken)
{
this.out = out;
this.writeToken = writeToken;
this.closeLatch = closeLatch;
this.closeToken = closeToken;
}
@Override
public void write()
throws Exception
{
writeToken.set(getCurrentTraceToken());
out.close();
}
@Override
public void close()
{
closeToken.set(getCurrentTraceToken());
closeLatch.countDown();
}
}
@Test
public void testResponseHandlerExceptionSeesTraceToken()
throws Exception
{
createAndRegisterNewRequestToken("somekey", "somevalue");
TraceToken token = getCurrentTraceToken();
int port = findUnusedPort();
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, MILLISECONDS));
Request request = prepareGet()
.setUri(new URI(scheme, null, host, port, "/", null, null))
.build();
executeRequest(request, new ResponseHandler<Void, RuntimeException>()
{
@Override
public Void handleException(Request request, Exception exception)
throws RuntimeException
{
assertEquals(getCurrentTraceToken(), token);
return null;
}
@Override
public Void handle(Request request, Response response)
throws RuntimeException
{
fail("unexpected response");
return null;
}
});
}
@Test
public void testResponseHandlerResponseSeesTraceToken()
throws Exception
{
createAndRegisterNewRequestToken("somekey", "somevalue");
TraceToken token = getCurrentTraceToken();
Request request = prepareGet()
.setUri(baseURI)
.build();
executeRequest(request, new ResponseHandler<Void, RuntimeException>()
{
@Override
public Void handleException(Request request, Exception exception)
throws RuntimeException
{
fail("unexpected request exception", exception);
return null;
}
@Override
public Void handle(Request request, Response response)
throws RuntimeException
{
assertEquals(getCurrentTraceToken(), token);
return null;
}
});
}
@Test
public void testNoFollowRedirect()
throws Exception
{
servlet.setResponseStatusCode(302);
servlet.setResponseBody("body text");
servlet.addResponseHeader("Location", "http://127.0.0.1:1");
Request request = prepareGet()
.setUri(baseURI)
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 302);
}
@Test
public void testFollowRedirect()
throws Exception
{
EchoServlet destinationServlet = new EchoServlet();
int port;
try (ServerSocket socket = new ServerSocket()) {
socket.bind(new InetSocketAddress(0));
port = socket.getLocalPort();
}
Server server = new Server();
HttpConfiguration httpConfiguration = new HttpConfiguration();
httpConfiguration.setSendServerVersion(false);
httpConfiguration.setSendXPoweredBy(false);
HttpConnectionFactory http1 = new HttpConnectionFactory(httpConfiguration);
HTTP2CServerConnectionFactory http2c = new HTTP2CServerConnectionFactory(httpConfiguration);
ServerConnector connector = new ServerConnector(server, null, null, null, -1, -1, http1, http2c);
connector.setIdleTimeout(30000);
connector.setName("http");
connector.setPort(port);
server.addConnector(connector);
ServletHolder servletHolder = new ServletHolder(destinationServlet);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
context.addServlet(servletHolder, "/redirect");
HandlerCollection handlers = new HandlerCollection();
handlers.addHandler(context);
server.setHandler(handlers);
try {
server.start();
servlet.setResponseStatusCode(302);
servlet.setResponseBody("body text");
servlet.addResponseHeader("Location", format("http://127.0.0.1:%d/redirect", port));
Request request = prepareGet()
.setUri(baseURI)
.setFollowRedirects(true)
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
}
finally {
server.stop();
}
}
@Test(expectedExceptions = {SocketTimeoutException.class, TimeoutException.class})
public void testReadTimeout()
throws Exception
{
HttpClientConfig config = createClientConfig()
.setIdleTimeout(new Duration(500, MILLISECONDS));
URI uri = URI.create(baseURI.toASCIIString() + "/?sleep=1000");
Request request = prepareGet()
.setUri(uri)
.build();
executeRequest(config, request, new ExceptionResponseHandler());
}
@Test
public void testResponseBody()
throws Exception
{
servlet.setResponseBody("body text");
Request request = prepareGet()
.setUri(baseURI)
.build();
StringResponse response = executeRequest(request, createStringResponseHandler());
assertEquals(response.getStatusCode(), 200);
assertEquals(response.getBody(), "body text");
}
@Test
public void testResponseBodyEmpty()
throws Exception
{
Request request = prepareGet()
.setUri(baseURI)
.build();
String body = executeRequest(request, createStringResponseHandler()).getBody();
assertEquals(body, "");
}
@Test
public void testResponseHeader()
throws Exception
{
servlet.addResponseHeader("foo", "bar");
servlet.addResponseHeader("dupe", "first");
servlet.addResponseHeader("dupe", "second");
Request request = prepareGet()
.setUri(baseURI)
.build();
StatusResponse response = executeRequest(request, createStatusResponseHandler());
assertEquals(response.getHeaders("foo"), ImmutableList.of("bar"));
assertEquals(response.getHeaders("dupe"), ImmutableList.of("first", "second"));
}
@Test
public void testResponseStatusCode()
throws Exception
{
servlet.setResponseStatusCode(543);
Request request = prepareGet()
.setUri(baseURI)
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 543);
}
@Test
public void testResponseStatusMessage()
throws Exception
{
servlet.setResponseStatusMessage("message");
Request request = prepareGet()
.setUri(baseURI)
.build();
String statusMessage = executeRequest(request, createStatusResponseHandler()).getStatusMessage();
if (createClientConfig().isHttp2Enabled()) {
// reason phrases are not supported in HTTP/2
assertNull(statusMessage);
}
else {
assertEquals(statusMessage, "message");
}
}
@Test(expectedExceptions = UnexpectedResponseException.class)
public void testThrowsUnexpectedResponseException()
throws Exception
{
servlet.setResponseStatusCode(543);
Request request = prepareGet()
.setUri(baseURI)
.build();
executeRequest(request, new UnexpectedResponseStatusCodeHandler(200));
}
@Test
public void testCompressionIsDisabled()
throws Exception
{
Request request = prepareGet()
.setUri(baseURI)
.build();
String body = executeRequest(request, createStringResponseHandler()).getBody();
assertEquals(body, "");
Assert.assertFalse(servlet.getRequestHeaders().containsKey(HeaderName.of(ACCEPT_ENCODING)));
String json = "{\"foo\":\"bar\",\"hello\":\"world\"}";
assertGreaterThanOrEqual(json.length(), GzipHandler.DEFAULT_MIN_GZIP_SIZE);
servlet.setResponseBody(json);
servlet.addResponseHeader(CONTENT_TYPE, "application/json");
StringResponse response = executeRequest(request, createStringResponseHandler());
assertEquals(response.getHeader(CONTENT_TYPE), "application/json");
assertEquals(response.getBody(), json);
}
private ExecutorService executor;
@BeforeClass
public final void setUp()
throws Exception
{
executor = Executors.newCachedThreadPool(threadsNamed("test-%s"));
}
@AfterClass
public final void tearDown()
throws Exception
{
if (executor != null) {
executor.shutdownNow();
}
}
@Test(expectedExceptions = {IOException.class, TimeoutException.class})
public void testConnectNoRead()
throws Exception
{
try (FakeServer fakeServer = new FakeServer(scheme, host, 0, null, false)) {
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, SECONDS));
config.setIdleTimeout(new Duration(10, MILLISECONDS));
executeRequest(fakeServer, config);
}
}
@Test(expectedExceptions = IOException.class)
public void testConnectNoReadClose()
throws Exception
{
try (FakeServer fakeServer = new FakeServer(scheme, host, 0, null, true)) {
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, SECONDS));
config.setIdleTimeout(new Duration(5, SECONDS));
executeRequest(fakeServer, config);
}
}
@Test(expectedExceptions = {IOException.class, TimeoutException.class})
public void testConnectReadIncomplete()
throws Exception
{
try (FakeServer fakeServer = new FakeServer(scheme, host, 10, null, false)) {
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, SECONDS));
config.setIdleTimeout(new Duration(10, MILLISECONDS));
executeRequest(fakeServer, config);
}
}
@Test(expectedExceptions = {IOException.class, TimeoutException.class})
public void testConnectReadIncompleteClose()
throws Exception
{
try (FakeServer fakeServer = new FakeServer(scheme, host, 10, null, true)) {
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(500, MILLISECONDS));
config.setIdleTimeout(new Duration(500, MILLISECONDS));
executeRequest(fakeServer, config);
}
}
@Test(expectedExceptions = IOException.class)
public void testConnectReadRequestClose()
throws Exception
{
try (FakeServer fakeServer = new FakeServer(scheme, host, Long.MAX_VALUE, null, true)) {
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, SECONDS));
config.setIdleTimeout(new Duration(5, SECONDS));
executeRequest(fakeServer, config);
}
}
@Test(expectedExceptions = Exception.class)
public void testConnectReadRequestWriteJunkHangup()
throws Exception
{
try (FakeServer fakeServer = new FakeServer(scheme, host, 10, "THIS\nIS\nJUNK\n\n".getBytes(UTF_8), false)) {
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, SECONDS));
config.setIdleTimeout(new Duration(5, SECONDS));
executeRequest(fakeServer, config);
}
}
@Test(expectedExceptions = IOException.class)
public void testDynamicBodySourceConnectWriteRequestClose()
throws Exception
{
try (FakeServer fakeServer = new FakeServer(scheme, host, 1024, null, true)) {
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, SECONDS));
config.setIdleTimeout(new Duration(5, SECONDS));
// kick the fake server
executor.execute(fakeServer);
// timing based check to assure we don't hang
long start = System.nanoTime();
final AtomicInteger invocation = new AtomicInteger(0);
try {
Request request = preparePut()
.setUri(fakeServer.getUri())
.setBodySource((DynamicBodySource) out -> () -> {
if (invocation.getAndIncrement() < 100) {
out.write(new byte[1024]);
}
else {
out.close();
}
})
.build();
executeRequest(config, request, new ExceptionResponseHandler());
}
finally {
if (!createClientConfig().isHttp2Enabled()) {
// Jetty behavior for HTTP/2 changed in 9.4.12
assertGreaterThan(invocation.get(), 0);
}
assertLessThan(nanosSince(start), new Duration(1, SECONDS), "Expected request to finish quickly");
}
}
}
@Test(expectedExceptions = CustomError.class)
public void testHandlesUndeclaredThrowable()
throws Exception
{
Request request = prepareGet()
.setUri(baseURI)
.build();
executeRequest(request, new ThrowErrorResponseHandler());
}
@Test
public void testResponseHandlerThrowsBeforeReadingBody()
throws Exception
{
if (createClientConfig().isHttp2Enabled()) {
// Too difficult to test with HTTP/2
return;
}
try (LargeResponseServer largeResponseServer = new LargeResponseServer(scheme, host)) {
RuntimeException expectedException = new RuntimeException();
// kick the fake server
executor.execute(largeResponseServer);
Request request = prepareGet()
.setUri(largeResponseServer.getUri())
.build();
try {
executeRequest(request, new ResponseHandler<Void, RuntimeException>()
{
@Override
public Void handleException(Request request, Exception exception)
{
if (exception instanceof ResponseTooLargeException) {
throw expectedException;
}
fail("Unexpected request failure", exception);
return null;
}
@Override
public Void handle(Request request, Response response)
{
throw expectedException;
}
});
fail("Expected to get an exception");
}
catch (RuntimeException e) {
assertEquals(e, expectedException);
}
largeResponseServer.assertCompleted();
}
}
private void executeRequest(FakeServer fakeServer, HttpClientConfig config)
throws Exception
{
// kick the fake server
executor.execute(fakeServer);
// timing based check to assure we don't hang
long start = System.nanoTime();
try {
Request request = prepareGet()
.setUri(fakeServer.getUri())
.build();
executeRequest(config, request, new ExceptionResponseHandler());
}
finally {
assertLessThan(nanosSince(start), new Duration(1, SECONDS), "Expected request to finish quickly");
}
}
private static class FakeServer
implements Closeable, Runnable
{
private final ServerSocket serverSocket;
private final long readBytes;
private final byte[] writeBuffer;
private final boolean closeConnectionImmediately;
private final AtomicReference<Socket> connectionSocket = new AtomicReference<>();
private final String scheme;
private final String host;
private FakeServer(String scheme, String host, long readBytes, byte[] writeBuffer, boolean closeConnectionImmediately)
throws Exception
{
this.scheme = scheme;
this.host = host;
this.writeBuffer = writeBuffer;
this.readBytes = readBytes;
this.serverSocket = new ServerSocket(0, 50, InetAddress.getByName(host));
this.closeConnectionImmediately = closeConnectionImmediately;
}
public URI getUri()
{
try {
return new URI(scheme, null, host, serverSocket.getLocalPort(), "/", null, null);
}
catch (URISyntaxException e) {
throw new IllegalStateException(e);
}
}
@Override
public void run()
{
try {
Socket connectionSocket = serverSocket.accept();
this.connectionSocket.set(connectionSocket);
if (readBytes > 0) {
connectionSocket.setSoTimeout(500);
long bytesRead = 0;
try {
InputStream inputStream = connectionSocket.getInputStream();
while (bytesRead < readBytes) {
inputStream.read();
bytesRead++;
}
}
catch (SocketTimeoutException ignored) {
}
}
if (writeBuffer != null) {
connectionSocket.getOutputStream().write(writeBuffer);
}
// todo sleep here maybe
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
finally {
if (closeConnectionImmediately) {
closeQuietly(connectionSocket.get());
}
}
}
@Override
public void close()
throws IOException
{
closeQuietly(connectionSocket.get());
serverSocket.close();
}
}
private class LargeResponseServer
implements Closeable, Runnable
{
private final ServerSocket serverSocket;
private final AtomicReference<Socket> connectionSocket = new AtomicReference<>();
private final String scheme;
private final String host;
private final CountDownLatch completed = new CountDownLatch(1);
private LargeResponseServer(String scheme, String host)
throws Exception
{
this.scheme = scheme;
this.host = host;
if (sslContextFactory != null) {
this.serverSocket = sslContextFactory.newSslServerSocket(null, 0, 5);
}
else {
this.serverSocket = new ServerSocket(0, 50, InetAddress.getByName(host));
}
}
public URI getUri()
{
try {
return new URI(scheme, null, host, serverSocket.getLocalPort(), "/", null, null);
}
catch (URISyntaxException e) {
throw new IllegalStateException(e);
}
}
public void assertCompleted() {
try {
assertTrue(completed.await(10, SECONDS), "LargeResponseServer completed");
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override
public void run()
{
try {
Socket connectionSocket = serverSocket.accept();
this.connectionSocket.set(connectionSocket);
BufferedReader reader = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream(), UTF_8));
String line;
do {
line = reader.readLine();
} while (!line.isEmpty());
OutputStreamWriter writer = new OutputStreamWriter(connectionSocket.getOutputStream(), UTF_8);
writer.write("HTTP/1.1 200 OK\r\n" +
"Content-Type: application/octet-stream\r\n" +
"Content-Length: 100000000\r\n" +
"\r\n");
for (int i = 0; i < 100_000; i++) {
writer.write(THOUSAND_X);
}
writer.write("\r\n");
writer.flush();
}
catch (IOException ignored) {
}
finally {
completed.countDown();
}
}
@Override
public void close()
throws IOException
{
closeQuietly(connectionSocket.get());
serverSocket.close();
}
}
public static class ExceptionResponseHandler
implements ResponseHandler<Void, Exception>
{
@Override
public Void handleException(Request request, Exception exception)
throws Exception
{
throw exception;
}
@Override
public Void handle(Request request, Response response)
throws Exception
{
throw new UnsupportedOperationException();
}
}
private static class PassThroughResponseHandler
implements ResponseHandler<Response, RuntimeException>
{
@Override
public Response handleException(Request request, Exception exception)
{
throw ResponseHandlerUtils.propagate(request, exception);
}
@Override
public Response handle(Request request, Response response)
{
return response;
}
}
private static class UnexpectedResponseStatusCodeHandler
implements ResponseHandler<Integer, RuntimeException>
{
private final int expectedStatusCode;
UnexpectedResponseStatusCodeHandler(int expectedStatusCode)
{
this.expectedStatusCode = expectedStatusCode;
}
@Override
public Integer handleException(Request request, Exception exception)
{
throw ResponseHandlerUtils.propagate(request, exception);
}
@Override
public Integer handle(Request request, Response response)
throws RuntimeException
{
if (response.getStatusCode() != expectedStatusCode) {
throw new UnexpectedResponseException(request, response);
}
return response.getStatusCode();
}
}
public static class CaptureExceptionResponseHandler
implements ResponseHandler<String, CapturedException>
{
@Override
public String handleException(Request request, Exception exception)
throws CapturedException
{
throw new CapturedException(exception);
}
@Override
public String handle(Request request, Response response)
throws CapturedException
{
throw new UnsupportedOperationException();
}
}
public static class ThrowErrorResponseHandler
implements ResponseHandler<String, Exception>
{
@Override
public String handleException(Request request, Exception exception)
{
throw new UnsupportedOperationException("not yet implemented", exception);
}
@Override
public String handle(Request request, Response response)
{
throw new CustomError();
}
}
private static class CustomError
extends Error {
}
protected static class CapturedException
extends Exception
{
public CapturedException(Exception exception)
{
super(exception);
}
}
private static class DefaultOnExceptionResponseHandler
implements ResponseHandler<Object, RuntimeException>
{
private final Object defaultObject;
public DefaultOnExceptionResponseHandler(Object defaultObject)
{
this.defaultObject = defaultObject;
}
@Override
public Object handleException(Request request, Exception exception)
throws RuntimeException
{
return defaultObject;
}
@Override
public Object handle(Request request, Response response)
throws RuntimeException
{
throw new UnsupportedOperationException();
}
}
protected static int findUnusedPort()
throws IOException
{
try (ServerSocket socket = new ServerSocket(0)) {
return socket.getLocalPort();
}
}
@SuppressWarnings("SocketOpenedButNotSafelyClosed")
private static class BackloggedServer
implements Closeable
{
private final List<Socket> clientSockets = new ArrayList<>();
private final ServerSocket serverSocket;
private final SocketAddress localSocketAddress;
private BackloggedServer()
throws IOException
{
this.serverSocket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"));
localSocketAddress = serverSocket.getLocalSocketAddress();
// some systems like Linux have a large minimum backlog
int i = 0;
while (i <= 256) {
if (!connect()) {
return;
}
i++;
}
throw new SkipException(format("socket backlog is too large (%s connections accepted)", i));
}
@Override
public void close()
{
clientSockets.forEach(Closeables::closeQuietly);
closeQuietly(serverSocket);
}
private int getPort()
{
return serverSocket.getLocalPort();
}
private boolean connect()
throws IOException
{
Socket socket = new Socket();
clientSockets.add(socket);
try {
socket.connect(localSocketAddress, 5);
return true;
}
catch (IOException e) {
if (isConnectTimeout(e)) {
return false;
}
throw e;
}
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private static void assertUnknownHost(String host)
{
try {
InetAddress.getByName(host);
fail("Expected UnknownHostException for host " + host);
}
catch (UnknownHostException e) {
// expected
}
}
private static boolean isConnectTimeout(Throwable t)
{
// Linux refuses connections immediately rather than queuing them
return (t instanceof SocketTimeoutException) || (t instanceof SocketException);
}
public static <T, E extends Exception> T executeAsync(JettyHttpClient client, Request request, ResponseHandler<T, E> responseHandler)
throws E
{
HttpResponseFuture<T> future = null;
try {
future = client.executeAsync(request, responseHandler);
}
catch (Exception e) {
fail("Unexpected exception", e);
}
try {
return future.get();
}
catch (InterruptedException e) {
currentThread().interrupt();
throw new RuntimeException(e);
}
catch (ExecutionException e) {
throwIfUnchecked(e.getCause());
if (e.getCause() instanceof Exception) {
// the HTTP client and ResponseHandler interface enforces this
throw AbstractHttpClientTest.<E>castThrowable(e.getCause());
}
// e.getCause() is some direct subclass of throwable
throw new RuntimeException(e.getCause());
}
}
@SuppressWarnings("unchecked")
private static <E extends Exception> E castThrowable(Throwable t)
{
return (E) t;
}
}
| http-client/src/test/java/com/proofpoint/http/client/AbstractHttpClientTest.java | package com.proofpoint.http.client;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.proofpoint.http.client.DynamicBodySource.Writer;
import com.proofpoint.http.client.HttpClient.HttpResponseFuture;
import com.proofpoint.http.client.StatusResponseHandler.StatusResponse;
import com.proofpoint.http.client.StringResponseHandler.StringResponse;
import com.proofpoint.http.client.jetty.JettyHttpClient;
import com.proofpoint.log.Logging;
import com.proofpoint.testing.Assertions;
import com.proofpoint.testing.Closeables;
import com.proofpoint.tracetoken.TraceToken;
import com.proofpoint.units.Duration;
import org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http2.server.HTTP2CServerConnectionFactory;
import org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory;
import org.eclipse.jetty.server.ConnectionFactory;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.gzip.GzipHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.testng.Assert;
import org.testng.SkipException;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UncheckedIOException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.nio.channels.UnresolvedAddressException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.Deflater;
import static com.google.common.base.Throwables.getStackTraceAsString;
import static com.google.common.base.Throwables.propagateIfPossible;
import static com.google.common.base.Throwables.throwIfUnchecked;
import static com.google.common.net.HttpHeaders.ACCEPT_ENCODING;
import static com.google.common.net.HttpHeaders.CONTENT_TYPE;
import static com.proofpoint.concurrent.Threads.threadsNamed;
import static com.proofpoint.http.client.HttpUriBuilder.uriBuilderFrom;
import static com.proofpoint.http.client.Request.Builder.prepareDelete;
import static com.proofpoint.http.client.Request.Builder.prepareGet;
import static com.proofpoint.http.client.Request.Builder.preparePost;
import static com.proofpoint.http.client.Request.Builder.preparePut;
import static com.proofpoint.http.client.StatusResponseHandler.createStatusResponseHandler;
import static com.proofpoint.http.client.StringResponseHandler.createStringResponseHandler;
import static com.proofpoint.testing.Assertions.assertGreaterThan;
import static com.proofpoint.testing.Assertions.assertGreaterThanOrEqual;
import static com.proofpoint.testing.Assertions.assertLessThan;
import static com.proofpoint.testing.Closeables.closeQuietly;
import static com.proofpoint.tracetoken.TraceTokenManager.createAndRegisterNewRequestToken;
import static com.proofpoint.tracetoken.TraceTokenManager.getCurrentTraceToken;
import static com.proofpoint.units.Duration.nanosSince;
import static java.lang.Math.toIntExact;
import static java.lang.String.format;
import static java.lang.Thread.currentThread;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.concurrent.Executors.newFixedThreadPool;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
@SuppressWarnings("InputStreamSlowMultibyteRead")
public abstract class AbstractHttpClientTest
{
private static final String THOUSAND_X = Strings.repeat("x", 1000);
protected EchoServlet servlet;
protected Server server;
protected URI baseURI;
private String scheme = "http";
private String host = "127.0.0.1";
private String keystore = null;
protected RequestStats stats;
private SslContextFactory sslContextFactory;
protected AbstractHttpClientTest()
{
}
protected AbstractHttpClientTest(String host, String keystore)
{
scheme = "https";
this.host = host;
this.keystore = keystore;
}
protected abstract HttpClientConfig createClientConfig();
private void executeExceptionRequest(HttpClientConfig config, Request request)
throws Exception
{
try {
executeRequest(config, request, new CaptureExceptionResponseHandler());
fail("expected exception");
}
catch (CapturedException e) {
propagateIfPossible(e.getCause(), Exception.class);
throw new RuntimeException(e.getCause());
}
}
public abstract <T, E extends Exception> T executeRequest(Request request, ResponseHandler<T, E> responseHandler)
throws Exception;
public final <T, E extends Exception> T executeRequest(HttpClientConfig config, Request request, ResponseHandler<T, E> responseHandler)
throws Exception
{
try (ClientTester clientTester = clientTester(config)) {
return clientTester.executeRequest(request, responseHandler);
}
}
public abstract ClientTester clientTester(HttpClientConfig config);
public interface ClientTester
extends Closeable
{
<T, E extends Exception> T executeRequest(Request request, ResponseHandler<T, E> responseHandler)
throws Exception;
}
@BeforeSuite
public void setupSuite()
{
Logging.initialize();
}
@BeforeMethod
public void abstractSetup()
throws Exception
{
servlet = new EchoServlet();
Server server = new Server();
HttpConfiguration httpConfiguration = new HttpConfiguration();
httpConfiguration.setSendServerVersion(false);
httpConfiguration.setSendXPoweredBy(false);
List<ConnectionFactory> connectionFactories = new ArrayList<>();
if (keystore != null) {
boolean isJava8 = System.getProperty("java.version").startsWith("1.8.");
httpConfiguration.addCustomizer(new SecureRequestCustomizer());
sslContextFactory = new SslContextFactory(keystore);
sslContextFactory.setKeyStorePassword("changeit");
connectionFactories.add(new SslConnectionFactory(sslContextFactory, isJava8 ? "http/1.1" : "alpn"));
if (!isJava8) {
connectionFactories.add(new ALPNServerConnectionFactory("h2", "http/1.1"));
connectionFactories.add(new HTTP2ServerConnectionFactory(httpConfiguration));
}
connectionFactories.add(new HttpConnectionFactory(httpConfiguration));
}
else {
connectionFactories.add(new HttpConnectionFactory(httpConfiguration));
connectionFactories.add(new HTTP2CServerConnectionFactory(httpConfiguration));
}
ServerConnector connector = new ServerConnector(server, connectionFactories.toArray(new ConnectionFactory[]{}));
connector.setIdleTimeout(30000);
connector.setName(scheme);
server.addConnector(connector);
ServletHolder servletHolder = new ServletHolder(servlet);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
context.addServlet(servletHolder, "/*");
HandlerCollection handlers = new HandlerCollection();
handlers.addHandler(context);
server.setHandler(handlers);
this.server = server;
server.start();
baseURI = new URI(scheme, null, host, connector.getLocalPort(), null, null, null);
}
@AfterMethod(alwaysRun = true)
public void abstractTeardown()
throws Exception
{
if (server != null) {
server.setStopTimeout(3000);
server.stop();
}
Logging.resetLogTesters();
}
@Test(enabled = false, description = "This takes over a minute to run")
public void test100kGets()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere?query");
Request request = prepareGet()
.setUri(uri)
.addHeader("foo", "bar")
.addHeader("dupe", "first")
.addHeader("dupe", "second")
.build();
for (int i = 0; i < 100_000; i++) {
try {
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
}
catch (Exception e) {
throw new Exception("Error on request " + i, e);
}
}
}
// Disabled because it is too flaky
@Test(timeOut = 4000, enabled = false)
public void testConnectTimeout()
throws Exception
{
try (BackloggedServer server = new BackloggedServer()) {
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, MILLISECONDS));
config.setIdleTimeout(new Duration(2, SECONDS));
Request request = prepareGet()
.setUri(new URI(scheme, null, host, server.getPort(), "/", null, null))
.build();
long start = System.nanoTime();
try {
executeRequest(config, request, new CaptureExceptionResponseHandler());
fail("expected exception");
}
catch (CapturedException e) {
Throwable t = e.getCause();
if (!isConnectTimeout(t)) {
fail(format("unexpected exception: [%s]", getStackTraceAsString(t)));
}
assertLessThan(nanosSince(start), new Duration(300, MILLISECONDS));
}
}
}
@Test(expectedExceptions = {ConnectException.class, SocketTimeoutException.class})
public void testConnectionRefused()
throws Exception
{
int port = findUnusedPort();
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, SECONDS));
Request request = prepareGet()
.setUri(new URI(scheme, null, host, port, "/", null, null))
.build();
executeExceptionRequest(config, request);
}
@Test
public void testConnectionRefusedWithDefaultingResponseExceptionHandler()
throws Exception
{
int port = findUnusedPort();
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, MILLISECONDS));
Request request = prepareGet()
.setUri(new URI(scheme, null, host, port, "/", null, null))
.build();
Object expected = new Object();
assertEquals(executeRequest(config, request, new DefaultOnExceptionResponseHandler(expected)), expected);
}
@Test(expectedExceptions = {UnknownHostException.class, UnresolvedAddressException.class}, timeOut = 10000)
public void testUnresolvableHost()
throws Exception
{
String invalidHost = "nonexistent.invalid";
assertUnknownHost(invalidHost);
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, SECONDS));
Request request = prepareGet()
.setUri(URI.create("http://" + invalidHost))
.build();
executeExceptionRequest(config, request);
}
@Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = ".*port out of range.*")
public void testBadPort()
throws Exception
{
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, MILLISECONDS));
Request request = prepareGet()
.setUri(new URI(scheme, null, host, 70_000, "/", null, null))
.build();
executeExceptionRequest(config, request);
}
@Test
public void testDeleteMethod()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere");
Request request = prepareDelete()
.setUri(uri)
.addHeader("foo", "bar")
.addHeader("dupe", "first")
.addHeader("dupe", "second")
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "DELETE");
assertEquals(servlet.getRequestUri(), uri);
assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar"));
assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second"));
assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value"));
}
@Test
public void testErrorResponseBody()
throws Exception
{
servlet.setResponseStatusCode(500);
servlet.setResponseBody("body text");
Request request = prepareGet()
.setUri(baseURI)
.build();
StringResponse response = executeRequest(request, createStringResponseHandler());
assertEquals(response.getStatusCode(), 500);
assertEquals(response.getBody(), "body text");
}
@Test
public void testGetMethod()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere?query");
Request request = prepareGet()
.setUri(uri)
.addHeader("foo", "bar")
.addHeader("dupe", "first")
.addHeader("dupe", "second")
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "GET");
if (servlet.getRequestUri().toString().endsWith("=")) {
// todo jetty client rewrites the uri string for some reason
assertEquals(servlet.getRequestUri(), new URI(uri + "="));
}
else {
assertEquals(servlet.getRequestUri(), uri);
}
assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar"));
assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second"));
assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value"));
}
@Test
public void testResponseHeadersCaseInsensitive()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere");
Request request = prepareGet()
.setUri(uri)
.build();
Response response = executeRequest(request, new PassThroughResponseHandler());
assertNotNull(response.getHeader("date"));
assertNotNull(response.getHeader("DATE"));
assertEquals(response.getHeaders("date").size(), 1);
assertEquals(response.getHeaders("DATE").size(), 1);
}
@Test
public void testKeepAlive()
throws Exception
{
URI uri = URI.create(baseURI.toASCIIString() + "/?remotePort=");
Request request = prepareGet()
.setUri(uri)
.build();
StatusResponse response1 = executeRequest(request, createStatusResponseHandler());
Thread.sleep(1000);
StatusResponse response2 = executeRequest(request, createStatusResponseHandler());
Thread.sleep(1000);
StatusResponse response3 = executeRequest(request, createStatusResponseHandler());
assertNotNull(response1.getHeader("remotePort"));
assertNotNull(response2.getHeader("remotePort"));
assertNotNull(response3.getHeader("remotePort"));
int port1 = Integer.parseInt(response1.getHeader("remotePort"));
int port2 = Integer.parseInt(response2.getHeader("remotePort"));
int port3 = Integer.parseInt(response3.getHeader("remotePort"));
assertEquals(port2, port1);
assertEquals(port3, port1);
Assertions.assertBetweenInclusive(port1, 1024, 65535);
}
@Test
public void testPostMethod()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere");
Request request = preparePost()
.setUri(uri)
.addHeader("foo", "bar")
.addHeader("dupe", "first")
.addHeader("dupe", "second")
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "POST");
assertEquals(servlet.getRequestUri(), uri);
assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar"));
assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second"));
assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value"));
}
@Test
public void testPutMethod()
throws Exception
{
servlet.setResponseBody("response");
URI uri = baseURI.resolve("/road/to/nowhere");
Request request = preparePut()
.setUri(uri)
.addHeader("foo", "bar")
.addHeader("dupe", "first")
.addHeader("dupe", "second")
.build();
int statusCode = executeRequest(request, createStringResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "PUT");
assertEquals(servlet.getRequestUri(), uri);
assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar"));
assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second"));
assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value"));
assertEquals(stats.getWrittenBytes().getAllTime().getTotal(), 0.0);
}
@Test
public void testPutMethodWithStaticBodyGenerator()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere");
byte[] body = {1, 2, 5};
Request request = preparePut()
.setUri(uri)
.addHeader("foo", "bar")
.addHeader("dupe", "first")
.addHeader("dupe", "second")
.setBodyGenerator(StaticBodyGenerator.createStaticBodyGenerator(body))
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "PUT");
assertEquals(servlet.getRequestUri(), uri);
assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar"));
assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second"));
assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value"));
assertEquals(servlet.getRequestBytes(), body);
assertEquals(stats.getWrittenBytes().getAllTime().getTotal(), 3.0);
}
@Test
public void testPutMethodWithInputStreamBodySource()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere");
Request request = preparePut()
.setUri(uri)
.addHeader("foo", "bar")
.addHeader("dupe", "first")
.addHeader("dupe", "second")
.setBodySource(new InputStreamBodySource(new InputStream()
{
AtomicInteger invocation = new AtomicInteger(0);
@Override
public int read()
throws IOException
{
throw new UnsupportedOperationException();
}
@Override
public int read(byte[] b)
throws IOException
{
switch (invocation.getAndIncrement()) {
case 0:
assertEquals(b.length, 8123);
b[0] = 1;
return 1;
case 1:
b[0] = 2;
b[1] = 5;
return 2;
case 2:
return -1;
default:
fail("unexpected invocation of write()");
return -1;
}
}
}, 8123))
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "PUT");
assertEquals(servlet.getRequestUri(), uri);
assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar"));
assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second"));
assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value"));
assertEquals(servlet.getRequestBytes(), new byte[]{1, 2, 5});
assertEquals(stats.getWrittenBytes().getAllTime().getTotal(), 3.0);
}
@Test
public void testPutMethodWithInputStreamBodySourceContentLength()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere");
Request request = preparePut()
.setUri(uri)
.setBodySource(new InputStreamBodySource(new InputStream()
{
AtomicInteger invocation = new AtomicInteger(0);
@Override
public int read()
throws IOException
{
throw new UnsupportedOperationException();
}
@Override
public int read(byte[] b)
throws IOException
{
switch (invocation.getAndIncrement()) {
case 0:
assertEquals(b.length, 8123);
b[0] = 1;
return 1;
case 1:
b[0] = 2;
b[1] = 3;
return 2;
case 2:
return -1;
default:
fail("unexpected invocation of write()");
return -1;
}
}
}, 8123) {
@Override
public long getLength()
{
return 3;
}
})
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "PUT");
assertEquals(servlet.getRequestUri(), uri);
assertEquals(servlet.getRequestHeaders("Content-Length"), ImmutableList.of("3"));
assertEquals(servlet.getRequestBytes(), new byte[]{1, 2, 3});
assertEquals(stats.getWrittenBytes().getAllTime().getTotal(), 3.0);
}
@Test
public void testPutMethodWithDynamicBodySource()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere");
Request request = preparePut()
.setUri(uri)
.addHeader("foo", "bar")
.addHeader("dupe", "first")
.addHeader("dupe", "second")
.setBodySource((DynamicBodySource) out -> new Writer()
{
AtomicInteger invocation = new AtomicInteger(0);
@Override
public void write()
throws Exception
{
switch (invocation.getAndIncrement()) {
case 0:
out.write(1);
break;
case 1:
byte[] bytes = {2, 5};
out.write(bytes);
bytes[0] = 9;
out.close();
break;
default:
fail("unexpected invocation of write()");
}
}
})
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "PUT");
assertEquals(servlet.getRequestUri(), uri);
assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar"));
assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second"));
assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value"));
assertEquals(servlet.getRequestBytes(), new byte[]{1, 2, 5});
assertEquals(stats.getWrittenBytes().getAllTime().getTotal(), 3.0);
}
@Test
public void testPutMethodWithDynamicBodySourceEdgeCases()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere");
final AtomicBoolean closed = new AtomicBoolean(false);
Request request = preparePut()
.setUri(uri)
.addHeader("foo", "bar")
.addHeader("dupe", "first")
.addHeader("dupe", "second")
.setBodySource((DynamicBodySource) out -> {
out.write(1);
return new EdgeCaseTestWriter(out, closed);
})
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "PUT");
assertEquals(servlet.getRequestUri(), uri);
assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar"));
assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second"));
assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value"));
assertEquals(servlet.getRequestBytes(), createByteArray(1, 15008));
assertTrue(closed.get(), "Writer was closed");
assertEquals(stats.getWrittenBytes().getAllTime().getTotal(), 15008.0);
}
private static class EdgeCaseTestWriter
implements Writer, AutoCloseable
{
AtomicInteger invocation = new AtomicInteger(0);
private final OutputStream out;
private final AtomicBoolean closed;
EdgeCaseTestWriter(OutputStream out, AtomicBoolean closed)
{
this.out = out;
this.closed = closed;
}
@Override
public void write()
throws Exception
{
switch (invocation.getAndIncrement()) {
case 0:
break;
case 1:
byte[] bytes = {2, 3};
out.write(bytes);
bytes[0] = 9;
break;
case 2:
out.write(createByteArray(4, 2));
out.write(6);
out.write(createByteArray(7, 2));
out.write(createByteArray(9, 5000));
byte[] lastArray = createByteArray(5009, 10_000);
out.write(lastArray);
lastArray[0] = 0;
lastArray[1] = 0;
break;
case 3:
out.close();
break;
default:
fail("unexpected invocation of write()");
}
}
@Override
public void close()
{
closed.set(true);
}
}
private static byte[] createByteArray(int firstValue, int length)
{
byte[] bytes = new byte[length];
for (int i = 0; i < length; i++) {
bytes[i] = (byte)firstValue++;
}
return bytes;
}
@Test
public void testPutMethodWithDynamicBodySourceContentLength()
throws Exception
{
URI uri = baseURI.resolve("/road/to/nowhere");
Request request = preparePut()
.setUri(uri)
.setBodySource(new DynamicBodySource()
{
@Override
public long getLength()
{
return 3;
}
@Override
public Writer start(OutputStream out)
throws Exception
{
return new Writer()
{
AtomicInteger invocation = new AtomicInteger(0);
@Override
public void write()
throws Exception
{
switch (invocation.getAndIncrement()) {
case 0:
out.write(1);
break;
case 1:
byte[] bytes = {2, 5};
out.write(bytes);
out.close();
break;
default:
fail("unexpected invocation of write()");
}
}
};
}
})
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "PUT");
assertEquals(servlet.getRequestUri(), uri);
assertEquals(servlet.getRequestHeaders("Content-Length"), ImmutableList.of("3"));
assertEquals(servlet.getRequestBytes(), new byte[]{1, 2, 5});
assertEquals(stats.getWrittenBytes().getAllTime().getTotal(), 3.0);
}
@Test
public void testDynamicBodySourceSeesTraceToken()
throws Exception
{
createAndRegisterNewRequestToken("somekey", "somevalue");
TraceToken token = getCurrentTraceToken();
AtomicReference<TraceToken> writeToken = new AtomicReference<>();
CountDownLatch closeLatch = new CountDownLatch(1);
AtomicReference<TraceToken> closeToken = new AtomicReference<>();
URI uri = baseURI.resolve("/road/to/nowhere");
Request request = preparePut()
.setUri(uri)
.addHeader("foo", "bar")
.addHeader("dupe", "first")
.addHeader("dupe", "second")
.setBodySource((DynamicBodySource) out -> {
assertEquals(getCurrentTraceToken(), token);
return new TraceTokenTestWriter(out, writeToken, closeLatch, closeToken);
})
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
assertEquals(servlet.getRequestMethod(), "PUT");
assertEquals(servlet.getRequestUri(), uri);
assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar"));
assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second"));
assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value"));
assertEquals(servlet.getRequestBytes(), new byte[] {});
assertEquals(writeToken.get(), token);
assertTrue(closeLatch.await(1, SECONDS));
assertEquals(closeToken.get(), token);
}
private static class TraceTokenTestWriter
implements Writer, AutoCloseable
{
private final OutputStream out;
private final AtomicReference<TraceToken> writeToken;
private final CountDownLatch closeLatch;
private final AtomicReference<TraceToken> closeToken;
TraceTokenTestWriter(OutputStream out, AtomicReference<TraceToken> writeToken, CountDownLatch closeLatch, AtomicReference<TraceToken> closeToken)
{
this.out = out;
this.writeToken = writeToken;
this.closeLatch = closeLatch;
this.closeToken = closeToken;
}
@Override
public void write()
throws Exception
{
writeToken.set(getCurrentTraceToken());
out.close();
}
@Override
public void close()
{
closeToken.set(getCurrentTraceToken());
closeLatch.countDown();
}
}
@Test
public void testResponseHandlerExceptionSeesTraceToken()
throws Exception
{
createAndRegisterNewRequestToken("somekey", "somevalue");
TraceToken token = getCurrentTraceToken();
int port = findUnusedPort();
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, MILLISECONDS));
Request request = prepareGet()
.setUri(new URI(scheme, null, host, port, "/", null, null))
.build();
executeRequest(request, new ResponseHandler<Void, RuntimeException>()
{
@Override
public Void handleException(Request request, Exception exception)
throws RuntimeException
{
assertEquals(getCurrentTraceToken(), token);
return null;
}
@Override
public Void handle(Request request, Response response)
throws RuntimeException
{
fail("unexpected response");
return null;
}
});
}
@Test
public void testResponseHandlerResponseSeesTraceToken()
throws Exception
{
createAndRegisterNewRequestToken("somekey", "somevalue");
TraceToken token = getCurrentTraceToken();
Request request = prepareGet()
.setUri(baseURI)
.build();
executeRequest(request, new ResponseHandler<Void, RuntimeException>()
{
@Override
public Void handleException(Request request, Exception exception)
throws RuntimeException
{
fail("unexpected request exception", exception);
return null;
}
@Override
public Void handle(Request request, Response response)
throws RuntimeException
{
assertEquals(getCurrentTraceToken(), token);
return null;
}
});
}
@Test
public void testNoFollowRedirect()
throws Exception
{
servlet.setResponseStatusCode(302);
servlet.setResponseBody("body text");
servlet.addResponseHeader("Location", "http://127.0.0.1:1");
Request request = prepareGet()
.setUri(baseURI)
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 302);
}
@Test
public void testFollowRedirect()
throws Exception
{
EchoServlet destinationServlet = new EchoServlet();
int port;
try (ServerSocket socket = new ServerSocket()) {
socket.bind(new InetSocketAddress(0));
port = socket.getLocalPort();
}
Server server = new Server();
HttpConfiguration httpConfiguration = new HttpConfiguration();
httpConfiguration.setSendServerVersion(false);
httpConfiguration.setSendXPoweredBy(false);
HttpConnectionFactory http1 = new HttpConnectionFactory(httpConfiguration);
HTTP2CServerConnectionFactory http2c = new HTTP2CServerConnectionFactory(httpConfiguration);
ServerConnector connector = new ServerConnector(server, null, null, null, -1, -1, http1, http2c);
connector.setIdleTimeout(30000);
connector.setName("http");
connector.setPort(port);
server.addConnector(connector);
ServletHolder servletHolder = new ServletHolder(destinationServlet);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
context.addServlet(servletHolder, "/redirect");
HandlerCollection handlers = new HandlerCollection();
handlers.addHandler(context);
server.setHandler(handlers);
try {
server.start();
servlet.setResponseStatusCode(302);
servlet.setResponseBody("body text");
servlet.addResponseHeader("Location", format("http://127.0.0.1:%d/redirect", port));
Request request = prepareGet()
.setUri(baseURI)
.setFollowRedirects(true)
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 200);
}
finally {
server.stop();
}
}
@Test(expectedExceptions = {SocketTimeoutException.class, TimeoutException.class})
public void testReadTimeout()
throws Exception
{
HttpClientConfig config = createClientConfig()
.setIdleTimeout(new Duration(500, MILLISECONDS));
URI uri = URI.create(baseURI.toASCIIString() + "/?sleep=1000");
Request request = prepareGet()
.setUri(uri)
.build();
executeRequest(config, request, new ExceptionResponseHandler());
}
@Test
public void testResponseBody()
throws Exception
{
servlet.setResponseBody("body text");
Request request = prepareGet()
.setUri(baseURI)
.build();
StringResponse response = executeRequest(request, createStringResponseHandler());
assertEquals(response.getStatusCode(), 200);
assertEquals(response.getBody(), "body text");
}
@Test
public void testResponseBodyEmpty()
throws Exception
{
Request request = prepareGet()
.setUri(baseURI)
.build();
String body = executeRequest(request, createStringResponseHandler()).getBody();
assertEquals(body, "");
}
@Test
public void testResponseHeader()
throws Exception
{
servlet.addResponseHeader("foo", "bar");
servlet.addResponseHeader("dupe", "first");
servlet.addResponseHeader("dupe", "second");
Request request = prepareGet()
.setUri(baseURI)
.build();
StatusResponse response = executeRequest(request, createStatusResponseHandler());
assertEquals(response.getHeaders("foo"), ImmutableList.of("bar"));
assertEquals(response.getHeaders("dupe"), ImmutableList.of("first", "second"));
}
@Test
public void testResponseStatusCode()
throws Exception
{
servlet.setResponseStatusCode(543);
Request request = prepareGet()
.setUri(baseURI)
.build();
int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode();
assertEquals(statusCode, 543);
}
@Test
public void testResponseStatusMessage()
throws Exception
{
servlet.setResponseStatusMessage("message");
Request request = prepareGet()
.setUri(baseURI)
.build();
String statusMessage = executeRequest(request, createStatusResponseHandler()).getStatusMessage();
if (createClientConfig().isHttp2Enabled()) {
// reason phrases are not supported in HTTP/2
assertNull(statusMessage);
}
else {
assertEquals(statusMessage, "message");
}
}
@Test(expectedExceptions = UnexpectedResponseException.class)
public void testThrowsUnexpectedResponseException()
throws Exception
{
servlet.setResponseStatusCode(543);
Request request = prepareGet()
.setUri(baseURI)
.build();
executeRequest(request, new UnexpectedResponseStatusCodeHandler(200));
}
@Test
public void testCompressionIsDisabled()
throws Exception
{
Request request = prepareGet()
.setUri(baseURI)
.build();
String body = executeRequest(request, createStringResponseHandler()).getBody();
assertEquals(body, "");
Assert.assertFalse(servlet.getRequestHeaders().containsKey(HeaderName.of(ACCEPT_ENCODING)));
String json = "{\"foo\":\"bar\",\"hello\":\"world\"}";
assertGreaterThanOrEqual(json.length(), GzipHandler.DEFAULT_MIN_GZIP_SIZE);
servlet.setResponseBody(json);
servlet.addResponseHeader(CONTENT_TYPE, "application/json");
StringResponse response = executeRequest(request, createStringResponseHandler());
assertEquals(response.getHeader(CONTENT_TYPE), "application/json");
assertEquals(response.getBody(), json);
}
private ExecutorService executor;
@BeforeClass
public final void setUp()
throws Exception
{
executor = Executors.newCachedThreadPool(threadsNamed("test-%s"));
}
@AfterClass
public final void tearDown()
throws Exception
{
if (executor != null) {
executor.shutdownNow();
}
}
@Test(expectedExceptions = {IOException.class, TimeoutException.class})
public void testConnectNoRead()
throws Exception
{
try (FakeServer fakeServer = new FakeServer(scheme, host, 0, null, false)) {
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, SECONDS));
config.setIdleTimeout(new Duration(10, MILLISECONDS));
executeRequest(fakeServer, config);
}
}
@Test(expectedExceptions = IOException.class)
public void testConnectNoReadClose()
throws Exception
{
try (FakeServer fakeServer = new FakeServer(scheme, host, 0, null, true)) {
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, SECONDS));
config.setIdleTimeout(new Duration(5, SECONDS));
executeRequest(fakeServer, config);
}
}
@Test(expectedExceptions = {IOException.class, TimeoutException.class})
public void testConnectReadIncomplete()
throws Exception
{
try (FakeServer fakeServer = new FakeServer(scheme, host, 10, null, false)) {
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, SECONDS));
config.setIdleTimeout(new Duration(10, MILLISECONDS));
executeRequest(fakeServer, config);
}
}
@Test(expectedExceptions = {IOException.class, TimeoutException.class})
public void testConnectReadIncompleteClose()
throws Exception
{
try (FakeServer fakeServer = new FakeServer(scheme, host, 10, null, true)) {
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(500, MILLISECONDS));
config.setIdleTimeout(new Duration(500, MILLISECONDS));
executeRequest(fakeServer, config);
}
}
@Test(expectedExceptions = IOException.class)
public void testConnectReadRequestClose()
throws Exception
{
try (FakeServer fakeServer = new FakeServer(scheme, host, Long.MAX_VALUE, null, true)) {
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, SECONDS));
config.setIdleTimeout(new Duration(5, SECONDS));
executeRequest(fakeServer, config);
}
}
@Test(expectedExceptions = Exception.class)
public void testConnectReadRequestWriteJunkHangup()
throws Exception
{
try (FakeServer fakeServer = new FakeServer(scheme, host, 10, "THIS\nIS\nJUNK\n\n".getBytes(UTF_8), false)) {
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, SECONDS));
config.setIdleTimeout(new Duration(5, SECONDS));
executeRequest(fakeServer, config);
}
}
@Test(expectedExceptions = IOException.class)
public void testDynamicBodySourceConnectWriteRequestClose()
throws Exception
{
try (FakeServer fakeServer = new FakeServer(scheme, host, 1024, null, true)) {
HttpClientConfig config = createClientConfig();
config.setConnectTimeout(new Duration(5, SECONDS));
config.setIdleTimeout(new Duration(5, SECONDS));
// kick the fake server
executor.execute(fakeServer);
// timing based check to assure we don't hang
long start = System.nanoTime();
final AtomicInteger invocation = new AtomicInteger(0);
try {
Request request = preparePut()
.setUri(fakeServer.getUri())
.setBodySource((DynamicBodySource) out -> () -> {
if (invocation.getAndIncrement() < 100) {
out.write(new byte[1024]);
}
else {
out.close();
}
})
.build();
executeRequest(config, request, new ExceptionResponseHandler());
}
finally {
if (!createClientConfig().isHttp2Enabled()) {
// Jetty behavior for HTTP/2 changed in 9.4.12
assertGreaterThan(invocation.get(), 0);
}
assertLessThan(nanosSince(start), new Duration(1, SECONDS), "Expected request to finish quickly");
}
}
}
@Test(expectedExceptions = CustomError.class)
public void testHandlesUndeclaredThrowable()
throws Exception
{
Request request = prepareGet()
.setUri(baseURI)
.build();
executeRequest(request, new ThrowErrorResponseHandler());
}
@Test
public void testResponseHandlerThrowsBeforeReadingBody()
throws Exception
{
if (createClientConfig().isHttp2Enabled()) {
// Too difficult to test with HTTP/2
return;
}
try (LargeResponseServer largeResponseServer = new LargeResponseServer(scheme, host)) {
RuntimeException expectedException = new RuntimeException();
// kick the fake server
executor.execute(largeResponseServer);
Request request = prepareGet()
.setUri(largeResponseServer.getUri())
.build();
try {
executeRequest(request, new ResponseHandler<Void, RuntimeException>()
{
@Override
public Void handleException(Request request, Exception exception)
{
if (exception instanceof ResponseTooLargeException) {
throw expectedException;
}
fail("Unexpected request failure", exception);
return null;
}
@Override
public Void handle(Request request, Response response)
{
throw expectedException;
}
});
fail("Expected to get an exception");
}
catch (RuntimeException e) {
assertEquals(e, expectedException);
}
largeResponseServer.assertCompleted();
}
}
private void executeRequest(FakeServer fakeServer, HttpClientConfig config)
throws Exception
{
// kick the fake server
executor.execute(fakeServer);
// timing based check to assure we don't hang
long start = System.nanoTime();
try {
Request request = prepareGet()
.setUri(fakeServer.getUri())
.build();
executeRequest(config, request, new ExceptionResponseHandler());
}
finally {
assertLessThan(nanosSince(start), new Duration(1, SECONDS), "Expected request to finish quickly");
}
}
private static class FakeServer
implements Closeable, Runnable
{
private final ServerSocket serverSocket;
private final long readBytes;
private final byte[] writeBuffer;
private final boolean closeConnectionImmediately;
private final AtomicReference<Socket> connectionSocket = new AtomicReference<>();
private final String scheme;
private final String host;
private FakeServer(String scheme, String host, long readBytes, byte[] writeBuffer, boolean closeConnectionImmediately)
throws Exception
{
this.scheme = scheme;
this.host = host;
this.writeBuffer = writeBuffer;
this.readBytes = readBytes;
this.serverSocket = new ServerSocket(0, 50, InetAddress.getByName(host));
this.closeConnectionImmediately = closeConnectionImmediately;
}
public URI getUri()
{
try {
return new URI(scheme, null, host, serverSocket.getLocalPort(), "/", null, null);
}
catch (URISyntaxException e) {
throw new IllegalStateException(e);
}
}
@Override
public void run()
{
try {
Socket connectionSocket = serverSocket.accept();
this.connectionSocket.set(connectionSocket);
if (readBytes > 0) {
connectionSocket.setSoTimeout(500);
long bytesRead = 0;
try {
InputStream inputStream = connectionSocket.getInputStream();
while (bytesRead < readBytes) {
inputStream.read();
bytesRead++;
}
}
catch (SocketTimeoutException ignored) {
}
}
if (writeBuffer != null) {
connectionSocket.getOutputStream().write(writeBuffer);
}
// todo sleep here maybe
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
finally {
if (closeConnectionImmediately) {
closeQuietly(connectionSocket.get());
}
}
}
@Override
public void close()
throws IOException
{
closeQuietly(connectionSocket.get());
serverSocket.close();
}
}
private class LargeResponseServer
implements Closeable, Runnable
{
private final ServerSocket serverSocket;
private final AtomicReference<Socket> connectionSocket = new AtomicReference<>();
private final String scheme;
private final String host;
private final CountDownLatch completed = new CountDownLatch(1);
private LargeResponseServer(String scheme, String host)
throws Exception
{
this.scheme = scheme;
this.host = host;
if (sslContextFactory != null) {
this.serverSocket = sslContextFactory.newSslServerSocket(null, 0, 5);
}
else {
this.serverSocket = new ServerSocket(0, 50, InetAddress.getByName(host));
}
}
public URI getUri()
{
try {
return new URI(scheme, null, host, serverSocket.getLocalPort(), "/", null, null);
}
catch (URISyntaxException e) {
throw new IllegalStateException(e);
}
}
public void assertCompleted() {
try {
assertTrue(completed.await(10, SECONDS), "LargeResponseServer completed");
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override
public void run()
{
try {
Socket connectionSocket = serverSocket.accept();
this.connectionSocket.set(connectionSocket);
BufferedReader reader = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream(), UTF_8));
String line;
do {
line = reader.readLine();
} while (!line.isEmpty());
OutputStreamWriter writer = new OutputStreamWriter(connectionSocket.getOutputStream(), UTF_8);
writer.write("HTTP/1.1 200 OK\r\n" +
"Content-Type: application/octet-stream\r\n" +
"Content-Length: 100000000\r\n" +
"\r\n");
for (int i = 0; i < 100_000; i++) {
writer.write(THOUSAND_X);
}
writer.write("\r\n");
writer.flush();
}
catch (IOException ignored) {
}
finally {
completed.countDown();
}
}
@Override
public void close()
throws IOException
{
closeQuietly(connectionSocket.get());
serverSocket.close();
}
}
public static class ExceptionResponseHandler
implements ResponseHandler<Void, Exception>
{
@Override
public Void handleException(Request request, Exception exception)
throws Exception
{
throw exception;
}
@Override
public Void handle(Request request, Response response)
throws Exception
{
throw new UnsupportedOperationException();
}
}
private static class PassThroughResponseHandler
implements ResponseHandler<Response, RuntimeException>
{
@Override
public Response handleException(Request request, Exception exception)
{
throw ResponseHandlerUtils.propagate(request, exception);
}
@Override
public Response handle(Request request, Response response)
{
return response;
}
}
private static class UnexpectedResponseStatusCodeHandler
implements ResponseHandler<Integer, RuntimeException>
{
private final int expectedStatusCode;
UnexpectedResponseStatusCodeHandler(int expectedStatusCode)
{
this.expectedStatusCode = expectedStatusCode;
}
@Override
public Integer handleException(Request request, Exception exception)
{
throw ResponseHandlerUtils.propagate(request, exception);
}
@Override
public Integer handle(Request request, Response response)
throws RuntimeException
{
if (response.getStatusCode() != expectedStatusCode) {
throw new UnexpectedResponseException(request, response);
}
return response.getStatusCode();
}
}
public static class CaptureExceptionResponseHandler
implements ResponseHandler<String, CapturedException>
{
@Override
public String handleException(Request request, Exception exception)
throws CapturedException
{
throw new CapturedException(exception);
}
@Override
public String handle(Request request, Response response)
throws CapturedException
{
throw new UnsupportedOperationException();
}
}
public static class ThrowErrorResponseHandler
implements ResponseHandler<String, Exception>
{
@Override
public String handleException(Request request, Exception exception)
{
throw new UnsupportedOperationException("not yet implemented", exception);
}
@Override
public String handle(Request request, Response response)
{
throw new CustomError();
}
}
private static class CustomError
extends Error {
}
protected static class CapturedException
extends Exception
{
public CapturedException(Exception exception)
{
super(exception);
}
}
private static class DefaultOnExceptionResponseHandler
implements ResponseHandler<Object, RuntimeException>
{
private final Object defaultObject;
public DefaultOnExceptionResponseHandler(Object defaultObject)
{
this.defaultObject = defaultObject;
}
@Override
public Object handleException(Request request, Exception exception)
throws RuntimeException
{
return defaultObject;
}
@Override
public Object handle(Request request, Response response)
throws RuntimeException
{
throw new UnsupportedOperationException();
}
}
protected static int findUnusedPort()
throws IOException
{
try (ServerSocket socket = new ServerSocket(0)) {
return socket.getLocalPort();
}
}
@SuppressWarnings("SocketOpenedButNotSafelyClosed")
private static class BackloggedServer
implements Closeable
{
private final List<Socket> clientSockets = new ArrayList<>();
private final ServerSocket serverSocket;
private final SocketAddress localSocketAddress;
private BackloggedServer()
throws IOException
{
this.serverSocket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"));
localSocketAddress = serverSocket.getLocalSocketAddress();
// some systems like Linux have a large minimum backlog
int i = 0;
while (i <= 256) {
if (!connect()) {
return;
}
i++;
}
throw new SkipException(format("socket backlog is too large (%s connections accepted)", i));
}
@Override
public void close()
{
clientSockets.forEach(Closeables::closeQuietly);
closeQuietly(serverSocket);
}
private int getPort()
{
return serverSocket.getLocalPort();
}
private boolean connect()
throws IOException
{
Socket socket = new Socket();
clientSockets.add(socket);
try {
socket.connect(localSocketAddress, 5);
return true;
}
catch (IOException e) {
if (isConnectTimeout(e)) {
return false;
}
throw e;
}
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private static void assertUnknownHost(String host)
{
try {
InetAddress.getByName(host);
fail("Expected UnknownHostException for host " + host);
}
catch (UnknownHostException e) {
// expected
}
}
private static boolean isConnectTimeout(Throwable t)
{
// Linux refuses connections immediately rather than queuing them
return (t instanceof SocketTimeoutException) || (t instanceof SocketException);
}
public static <T, E extends Exception> T executeAsync(JettyHttpClient client, Request request, ResponseHandler<T, E> responseHandler)
throws E
{
HttpResponseFuture<T> future = null;
try {
future = client.executeAsync(request, responseHandler);
}
catch (Exception e) {
fail("Unexpected exception", e);
}
try {
return future.get();
}
catch (InterruptedException e) {
currentThread().interrupt();
throw new RuntimeException(e);
}
catch (ExecutionException e) {
throwIfUnchecked(e.getCause());
if (e.getCause() instanceof Exception) {
// the HTTP client and ResponseHandler interface enforces this
throw AbstractHttpClientTest.<E>castThrowable(e.getCause());
}
// e.getCause() is some direct subclass of throwable
throw new RuntimeException(e.getCause());
}
}
@SuppressWarnings("unchecked")
private static <E extends Exception> E castThrowable(Throwable t)
{
return (E) t;
}
}
| Fix AbstractHttpClientTest.testConnectTimeout
The request sent in this test can also fail with a ClosedChannelException
for HTTP/2.
| http-client/src/test/java/com/proofpoint/http/client/AbstractHttpClientTest.java | Fix AbstractHttpClientTest.testConnectTimeout | <ide><path>ttp-client/src/test/java/com/proofpoint/http/client/AbstractHttpClientTest.java
<ide> import com.proofpoint.tracetoken.TraceToken;
<ide> import com.proofpoint.units.Duration;
<ide> import org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory;
<del>import org.eclipse.jetty.http.HttpField;
<del>import org.eclipse.jetty.http.HttpHeader;
<ide> import org.eclipse.jetty.http2.server.HTTP2CServerConnectionFactory;
<ide> import org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory;
<ide> import org.eclipse.jetty.server.ConnectionFactory;
<ide> import java.net.URI;
<ide> import java.net.URISyntaxException;
<ide> import java.net.UnknownHostException;
<add>import java.nio.channels.ClosedChannelException;
<ide> import java.nio.channels.UnresolvedAddressException;
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide> import java.util.concurrent.ExecutionException;
<ide> import java.util.concurrent.ExecutorService;
<ide> import java.util.concurrent.Executors;
<del>import java.util.concurrent.RejectedExecutionException;
<ide> import java.util.concurrent.TimeoutException;
<ide> import java.util.concurrent.atomic.AtomicBoolean;
<ide> import java.util.concurrent.atomic.AtomicInteger;
<ide> import java.util.concurrent.atomic.AtomicReference;
<del>import java.util.zip.Deflater;
<ide>
<ide> import static com.google.common.base.Throwables.getStackTraceAsString;
<ide> import static com.google.common.base.Throwables.propagateIfPossible;
<ide> import static com.google.common.net.HttpHeaders.ACCEPT_ENCODING;
<ide> import static com.google.common.net.HttpHeaders.CONTENT_TYPE;
<ide> import static com.proofpoint.concurrent.Threads.threadsNamed;
<del>import static com.proofpoint.http.client.HttpUriBuilder.uriBuilderFrom;
<ide> import static com.proofpoint.http.client.Request.Builder.prepareDelete;
<ide> import static com.proofpoint.http.client.Request.Builder.prepareGet;
<ide> import static com.proofpoint.http.client.Request.Builder.preparePost;
<ide> import static java.lang.String.format;
<ide> import static java.lang.Thread.currentThread;
<ide> import static java.nio.charset.StandardCharsets.UTF_8;
<del>import static java.util.concurrent.Executors.newFixedThreadPool;
<ide> import static java.util.concurrent.TimeUnit.MILLISECONDS;
<ide> import static java.util.concurrent.TimeUnit.SECONDS;
<ide> import static org.testng.Assert.assertEquals;
<ide> }
<ide> catch (CapturedException e) {
<ide> Throwable t = e.getCause();
<del> if (!isConnectTimeout(t)) {
<add> if (!(isConnectTimeout(t) || t instanceof ClosedChannelException)) {
<ide> fail(format("unexpected exception: [%s]", getStackTraceAsString(t)));
<ide> }
<ide> assertLessThan(nanosSince(start), new Duration(300, MILLISECONDS)); |
|
JavaScript | agpl-3.0 | 3fd8340e836d0082ac2d10f00f41b5b8b31b9d51 | 0 | avpreserve/avcc,avpreserve/avcc,avpreserve/avcc,avpreserve/avcc | /**
* Class of managing Filtering and displaying of records.
*
* @returns {Records}
*/
function Records() {
/**
* Object of datatable.
*/
// this.oTable = null;
/**
* URL for managing calls of datatable
* @type {string}
*/
var ajaxSource = null;
var pageUrl = null;
var selfObj = this;
var Filters = new Object();
var customFieldName = 'All';
var customColumnName = 'all';
var checkEvent = false;
/**
* Set the ajax URL of datatable.
* @param {string} source
*
*/
this.setAjaxSource = function (source) {
ajaxSource = source;
}
/**
* Set the page url.
* @param {string} url
*
*/
this.setPageUrl = function (url) {
pageUrl = url;
}
/**
* Initialize the datatable.
*
*/
this.initDataTable = function () {
// check the existence of table on which we are going to apply datatable.
if ($('#records').length > 0)
{
// Modify css for managing view.
// $('#container').removeClass('container');
// $('#container').css('margin', '20px');
var selected = [];
oTable =
$('#records').dataTable(
{
"dom": '<"top"p><"clear">tir<"bottom"p>',
"bProcessing": true,
"bServerSide": true,
retrieve: true,
destroy: true,
"language": {
"info": "Showing _START_ - _END_ of _MAX_",
"infoFiltered": ''
},
"aoColumnDefs": [
{"bSortable": false, "aTargets": [0]}
],
"aaSorting": [],
"sAjaxSource": ajaxSource,
"bStateSave": true,
// "fnInitComplete": function () {
// this.oTable.fnAdjustColumnSizing();
// },
"fnServerData": function (sSource, aoData, fnCallback) {
jQuery.getJSON(sSource, aoData, function (json) {
fnCallback(json);
});
},
"rowCallback": function (row, data) {
if ($.inArray(data.DT_RowId, selected) !== -1) {
$(row).addClass('selected');
}
}
});
$('#records tbody').on('click', '.checkboxes', function () {
var id = this.id;
var index = $.inArray(id, selected);
console.log(id);
if (index === -1) {
selected.push(id);
} else {
selected.splice(index, 1);
}
$(this).toggleClass('selected');
});
}
}
/**
*
* @returns {Boolean}
*/
this.bindEvents = function () {
selfObj.isAnySearch();
$('input[name="mediaType[]"]').click(function () {
checkParentFacet('media_type', $(this).prop("checked"));
});
$('input[name="commercial[]"]').click(function () {
checkParentFacet('commercial', $(this).prop('checked'));
});
$('input[name="format[]"]').click(function () {
checkParentFacet('format', $(this).prop('checked'));
});
$('input[name="base[]"]').click(function () {
checkParentFacet('base', $(this).prop('checked'));
});
$('input[name="recordingStandard[]"]').click(function () {
checkParentFacet('recordingStandard', $(this).prop('checked'));
});
$('input[name="printType[]"]').click(function () {
checkParentFacet('printType', $(this).prop('checked'));
});
$('input[name="project[]"]').click(function () {
checkParentFacet('project', $(this).prop('checked'));
});
$('input[name="reelDiameter[]"]').click(function () {
checkParentFacet('reelDiameter', $(this).prop('checked'));
});
$('input[name="discDiameter[]"]').click(function () {
checkParentFacet('discDiameter', $(this).prop('checked'));
});
$('input[name="acidDetection[]"]').click(function () {
checkParentFacet('acidDetection', $(this).prop('checked'));
});
$('input[name="collectionName[]"]').click(function () {
checkParentFacet('collectionName', $(this).prop('checked'));
});
initTriStateCheckBox('is_review_check', 'is_review_check_state', true);
$('#is_review_check').click(function () {
var totalChecked = $('#total_checked').val();
var containerId = $(this).attr('id');
var currentVal = $('#' + containerId + '_state').val();
if (currentVal > 0 && totalChecked == 0)
{
totalChecked++;
$('#parent_facet').val(containerId);
$('#total_checked').val(totalChecked);
}
if (currentVal == 0 && $('#parent_facet').val() == containerId) {
totalChecked--;
$('#parent_facet').val('');
$('#total_checked').val(totalChecked);
}
filterRecords();
});
$('#reset_all').click(function () {
selfObj.resetAll();
});
selfObj.addCustomToken();
selfObj.addKeyword();
selfObj.removeFilter();
selfObj.removeKeywordFilter();
return true;
}
/**
*
* @param {type} type
* @param {type} isChecked
* @returns {undefined}
*/
var checkParentFacet = function (type, isChecked) {
//todo need to update function
var totalChecked = $('#total_checked').val();
var total = $('#facet_sidebar input:checked').length;
if (total == 0)
totalChecked = 0;
if (isChecked)
totalChecked++;
else
totalChecked--;
if (totalChecked < 0)
totalChecked = 0;
$('#total_checked').val(totalChecked);
if ($('#parent_facet').val() == '' && totalChecked == 1)
$('#parent_facet').val(type);
else if (totalChecked == 0)
$('#parent_facet').val('');
filterRecords();
}
/**
*
* @returns {undefined}
*/
var filterRecords = function () {
$.blockUI({
message: 'Please wait...',
css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
opacity: .5,
color: '#fff',
zIndex: 999999
}
});
$.ajax({
type: 'GET',
url: pageUrl,
data: $('#formSearch').serialize(),
dataType: 'json',
success: function (response)
{
$("#recordsContainer").html(response.html);
var source = $('#metro-js').attr('src');
var script = document.createElement("script");
script.type = "text/javascript";
script.src = source;
script.id = "metro-js";
$("#recordsContainer").append(script);
selfObj.initDataTable();
selfObj.bindEvents();
$('body').scrollTop(0);
$.unblockUI();
}
});
}
/**
*
* @returns {undefined}
*/
this.addCustomToken = function () {
$('.customToken').click(function () {
customFieldName = $(this).attr('data-fieldName');
customColumnName = $(this).attr('data-columnName');
$('#limit_field_text').html(customFieldName);
});
}
this.addKeyword = function () {
$('#addKeyword').click(function () {
checkEvent = true;
});
$('#keywordSearch').keypress(function (e) {
if (e.which == 13) {
checkEvent = true;
}
});
console.log(checkEvent);
if (checkEvent == true && $('#keywordSearch').val() != '') {
if ($('#facet_keyword_search').val() != '' && $('#facet_keyword_search').val() != '""') {
Filters = JSON.parse($('#facet_keyword_search').val());
}
else {
Filters = new Array();
}
for (x in Filters) {
if (Filters[x].value == $('#keywordSearch').val()) {
alert($('#keywordSearch').val() + " filter is already applied.");
return false;
}
}
var temp = {};
temp.value = $('#keywordSearch').val();
temp.type = customColumnName;
Filters.push(temp);
$('#facet_keyword_search').val(JSON.stringify(Filters));
customFieldName = 'All';
customColumnName = 'all';
filterRecords();
}
}
this.removeFilter = function () {
$('.delFilter').click(function () {
elementID = $(this).attr('data-elementId');
type = $(this).attr('data-type');
$('#' + elementID).prop('checked', false);
checkParentFacet(type);
});
}
this.removeKeywordFilter = function () {
$('.deleteKeyword').click(function () {
var index = $.trim($(this).data().index);
Filters = JSON.parse($('#facet_keyword_search').val());
delete (Filters[index]);
Filters.splice(index, 1);
$('#facet_keyword_search').val(JSON.stringify(Filters));
filterRecords();
});
}
this.resetAll = function () {
$('#formSearch').find('input:hidden, input:text, select').val('');
$('#formSearch').find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
filterRecords();
}
this.isAnySearch = function () {
if ($('.search_keys').length > 0) {
$('#reset_all').show();
}
else {
$('#reset_all').hide();
}
}
}
| web/js/records.js | /**
* Class of managing Filtering and displaying of records.
*
* @returns {Records}
*/
function Records() {
/**
* Object of datatable.
*/
// this.oTable = null;
/**
* URL for managing calls of datatable
* @type {string}
*/
var ajaxSource = null;
var pageUrl = null;
var selfObj = this;
var Filters = new Object();
var customFieldName = 'All';
var customColumnName = 'all';
var checkEvent = false;
/**
* Set the ajax URL of datatable.
* @param {string} source
*
*/
this.setAjaxSource = function (source) {
ajaxSource = source;
}
/**
* Set the page url.
* @param {string} url
*
*/
this.setPageUrl = function (url) {
pageUrl = url;
}
/**
* Initialize the datatable.
*
*/
this.initDataTable = function () {
// check the existence of table on which we are going to apply datatable.
if ($('#records').length > 0)
{
// Modify css for managing view.
// $('#container').removeClass('container');
// $('#container').css('margin', '20px');
var selected = [];
oTable =
$('#records').dataTable(
{
"dom": '<"top"p><"clear">tir<"bottom"p>',
"bProcessing": true,
"bServerSide": true,
retrieve: true,
destroy: true,
"language": {
"info": "Showing _START_ - _END_ of _MAX_",
"infoFiltered": ''
},
"aoColumnDefs": [
{"bSortable": false, "aTargets": [0]}
],
"aaSorting": [],
"sAjaxSource": ajaxSource,
"bStateSave": true,
// "fnInitComplete": function () {
// this.oTable.fnAdjustColumnSizing();
// },
"fnServerData": function (sSource, aoData, fnCallback) {
jQuery.getJSON(sSource, aoData, function (json) {
fnCallback(json);
});
},
"rowCallback": function (row, data) {
if ($.inArray(data.DT_RowId, selected) !== -1) {
$(row).addClass('selected');
}
}
});
$('#records tbody').on('click', '.checkboxes', function () {
var id = this.id;
var index = $.inArray(id, selected);
if (index === -1) {
selected.push(id);
} else {
selected.splice(index, 1);
}
$(this).toggleClass('selected');
});
}
}
/**
*
* @returns {Boolean}
*/
this.bindEvents = function () {
selfObj.isAnySearch();
$('input[name="mediaType[]"]').click(function () {
checkParentFacet('media_type', $(this).prop("checked"));
});
$('input[name="commercial[]"]').click(function () {
checkParentFacet('commercial', $(this).prop('checked'));
});
$('input[name="format[]"]').click(function () {
checkParentFacet('format', $(this).prop('checked'));
});
$('input[name="base[]"]').click(function () {
checkParentFacet('base', $(this).prop('checked'));
});
$('input[name="recordingStandard[]"]').click(function () {
checkParentFacet('recordingStandard', $(this).prop('checked'));
});
$('input[name="printType[]"]').click(function () {
checkParentFacet('printType', $(this).prop('checked'));
});
$('input[name="project[]"]').click(function () {
checkParentFacet('project', $(this).prop('checked'));
});
$('input[name="reelDiameter[]"]').click(function () {
checkParentFacet('reelDiameter', $(this).prop('checked'));
});
$('input[name="discDiameter[]"]').click(function () {
checkParentFacet('discDiameter', $(this).prop('checked'));
});
$('input[name="acidDetection[]"]').click(function () {
checkParentFacet('acidDetection', $(this).prop('checked'));
});
$('input[name="collectionName[]"]').click(function () {
checkParentFacet('collectionName', $(this).prop('checked'));
});
initTriStateCheckBox('is_review_check', 'is_review_check_state', true);
$('#is_review_check').click(function () {
var totalChecked = $('#total_checked').val();
var containerId = $(this).attr('id');
var currentVal = $('#' + containerId + '_state').val();
if (currentVal > 0 && totalChecked == 0)
{
totalChecked++;
$('#parent_facet').val(containerId);
$('#total_checked').val(totalChecked);
}
if (currentVal == 0 && $('#parent_facet').val() == containerId) {
totalChecked--;
$('#parent_facet').val('');
$('#total_checked').val(totalChecked);
}
filterRecords();
});
$('#reset_all').click(function () {
selfObj.resetAll();
});
selfObj.addCustomToken();
selfObj.addKeyword();
selfObj.removeFilter();
selfObj.removeKeywordFilter();
return true;
}
/**
*
* @param {type} type
* @param {type} isChecked
* @returns {undefined}
*/
var checkParentFacet = function (type, isChecked) {
//todo need to update function
var totalChecked = $('#total_checked').val();
var total = $('#facet_sidebar input:checked').length;
if (total == 0)
totalChecked = 0;
if (isChecked)
totalChecked++;
else
totalChecked--;
if (totalChecked < 0)
totalChecked = 0;
$('#total_checked').val(totalChecked);
if ($('#parent_facet').val() == '' && totalChecked == 1)
$('#parent_facet').val(type);
else if (totalChecked == 0)
$('#parent_facet').val('');
filterRecords();
}
/**
*
* @returns {undefined}
*/
var filterRecords = function () {
$.blockUI({
message: 'Please wait...',
css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
opacity: .5,
color: '#fff',
zIndex: 999999
}
});
$.ajax({
type: 'GET',
url: pageUrl,
data: $('#formSearch').serialize(),
dataType: 'json',
success: function (response)
{
$("#recordsContainer").html(response.html);
var source = $('#metro-js').attr('src');
var script = document.createElement("script");
script.type = "text/javascript";
script.src = source;
script.id = "metro-js";
$("#recordsContainer").append(script);
selfObj.initDataTable();
selfObj.bindEvents();
$('body').scrollTop(0);
$.unblockUI();
}
});
}
/**
*
* @returns {undefined}
*/
this.addCustomToken = function () {
$('.customToken').click(function () {
customFieldName = $(this).attr('data-fieldName');
customColumnName = $(this).attr('data-columnName');
$('#limit_field_text').html(customFieldName);
});
}
this.addKeyword = function () {
$('#addKeyword').click(function () {
checkEvent = true;
});
$('#keywordSearch').keypress(function (e) {
if (e.which == 13) {
checkEvent = true;
}
});
console.log(checkEvent);
if (checkEvent == true && $('#keywordSearch').val() != '') {
if ($('#facet_keyword_search').val() != '' && $('#facet_keyword_search').val() != '""') {
Filters = JSON.parse($('#facet_keyword_search').val());
}
else {
Filters = new Array();
}
for (x in Filters) {
if (Filters[x].value == $('#keywordSearch').val()) {
alert($('#keywordSearch').val() + " filter is already applied.");
return false;
}
}
var temp = {};
temp.value = $('#keywordSearch').val();
temp.type = customColumnName;
Filters.push(temp);
$('#facet_keyword_search').val(JSON.stringify(Filters));
customFieldName = 'All';
customColumnName = 'all';
filterRecords();
}
}
this.removeFilter = function () {
$('.delFilter').click(function () {
elementID = $(this).attr('data-elementId');
type = $(this).attr('data-type');
$('#' + elementID).prop('checked', false);
checkParentFacet(type);
});
}
this.removeKeywordFilter = function () {
$('.deleteKeyword').click(function () {
var index = $.trim($(this).data().index);
Filters = JSON.parse($('#facet_keyword_search').val());
delete (Filters[index]);
Filters.splice(index, 1);
$('#facet_keyword_search').val(JSON.stringify(Filters));
filterRecords();
});
}
this.resetAll = function () {
$('#formSearch').find('input:hidden, input:text, select').val('');
$('#formSearch').find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
filterRecords();
}
this.isAnySearch = function () {
if ($('.search_keys').length > 0) {
$('#reset_all').show();
}
else {
$('#reset_all').hide();
}
}
}
| keyword input box
| web/js/records.js | keyword input box | <ide><path>eb/js/records.js
<ide> $('#records tbody').on('click', '.checkboxes', function () {
<ide> var id = this.id;
<ide> var index = $.inArray(id, selected);
<del>
<add>console.log(id);
<ide> if (index === -1) {
<ide> selected.push(id);
<ide> } else { |
|
Java | epl-1.0 | b76b2c89c0a5c90d36ce1bcbf7860545616865e4 | 0 | mdoninger/egit,SmithAndr/egit,blizzy78/egit,wdliu/egit,paulvi/egit,SmithAndr/egit,collaborative-modeling/egit,wdliu/egit,paulvi/egit,collaborative-modeling/egit,chalstrick/egit | /*******************************************************************************
* Copyright (C) 2012, Markus Duft <[email protected]>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.egit.ui.internal.components;
import java.util.Collections;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.egit.ui.UIText;
import org.eclipse.egit.ui.UIUtils;
import org.eclipse.egit.ui.UIUtils.IRefListProvider;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.jgit.lib.BranchTrackingStatus;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
/**
* A page that allows to select a target branch for a push operation.
*/
public class SimplePushSpecPage extends WizardPage {
private boolean forceUpdate;
private Text remoteRefName;
private String sourceName;
private Repository repository;
/**
* the content assist provider for the {@link Ref}s
*/
protected RefContentAssistProvider assist;
/**
* Creates a new wizard page that allows selection of the target
*
* @param niceSourceName
* the nice displayable name of the source to be pushed.
* @param repo
* source repository
*/
public SimplePushSpecPage(String niceSourceName, Repository repo) {
super(UIText.SimplePushSpecPage_title);
setTitle(UIText.SimplePushSpecPage_title);
setMessage(NLS.bind(UIText.SimplePushSpecPage_message, niceSourceName));
this.sourceName = niceSourceName;
this.repository = repo;
}
public void createControl(Composite parent) {
Composite main = new Composite(parent, SWT.NONE);
GridDataFactory.fillDefaults().grab(true, true).applyTo(main);
main.setLayout(new GridLayout(1, false));
Composite inputPanel = new Composite(main, SWT.NONE);
GridDataFactory.fillDefaults().grab(true, false).applyTo(inputPanel);
inputPanel.setLayout(new GridLayout(2, false));
final Label lblRemote = new Label(inputPanel, SWT.NONE);
lblRemote.setText(UIText.SimplePushSpecPage_TargetRefName);
remoteRefName = new Text(inputPanel, SWT.BORDER);
GridDataFactory.fillDefaults().grab(true, false).applyTo(remoteRefName);
remoteRefName.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
setPageComplete(isPageComplete());
}
});
UIUtils.addRefContentProposalToText(remoteRefName, repository,
new IRefListProvider() {
public List<Ref> getRefList() {
if (assist != null)
return assist.getRefsForContentAssist(false, true);
return Collections.emptyList();
}
});
final Button forceButton = new Button(main, SWT.CHECK);
forceButton.setText(UIText.RefSpecDialog_ForceUpdateCheckbox);
GridDataFactory.fillDefaults().grab(true, false).applyTo(forceButton);
forceButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
forceUpdate = forceButton.getSelection();
}
});
setControl(main);
}
/**
* pre-fills the destination box with a remote ref name if one exists that
* matches the local branch name.
*/
protected void updateDestinationField() {
setMessage(NLS.bind(UIText.SimplePushSpecPage_message, sourceName));
String checkRemote = sourceName;
if (sourceName.startsWith(Constants.R_HEADS)) {
try {
BranchTrackingStatus status = BranchTrackingStatus.of(
repository,
sourceName.substring(Constants.R_HEADS.length()));
if (status != null) {
// calculate the name of the branch on the other side.
checkRemote = status.getRemoteTrackingBranch();
checkRemote = Constants.R_HEADS
+ checkRemote.substring(checkRemote.indexOf('/',
Constants.R_REMOTES.length() + 1) + 1);
setMessage(NLS.bind(
UIText.SimplePushSpecPage_pushAheadInfo,
new Object[] { sourceName,
Integer.valueOf(status.getAheadCount()),
status.getRemoteTrackingBranch() }),
IStatus.INFO);
}
} catch (Exception e) {
// ignore and continue...
}
if (assist == null) {
if (checkRemote != null)
remoteRefName.setText(checkRemote);
return;
}
if (checkRemote == null)
checkRemote = sourceName;
for (Ref ref : assist.getRefsForContentAssist(false, true))
if (ref.getName().equals(checkRemote))
remoteRefName.setText(checkRemote);
}
}
@Override
public boolean isPageComplete() {
return remoteRefName.getText() != null
&& remoteRefName.getText().length() > 0;
}
/**
* Whether the user wants to force pushing.
*
* @return whether to force the push
*/
public boolean isForceUpdate() {
return forceUpdate;
}
/**
* Retrieves the target name to push to.
*
* @return the target name.
*/
public String getTargetRef() {
return remoteRefName.getText();
}
}
| org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/components/SimplePushSpecPage.java | /*******************************************************************************
* Copyright (C) 2012, Markus Duft <[email protected]>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.egit.ui.internal.components;
import java.util.Collections;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.egit.ui.UIText;
import org.eclipse.egit.ui.UIUtils;
import org.eclipse.egit.ui.UIUtils.IRefListProvider;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.jgit.lib.BranchTrackingStatus;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
/**
* A page that allows to select a target branch for a push operation.
*/
public class SimplePushSpecPage extends WizardPage {
private boolean forceUpdate;
private Text remoteRefName;
private String sourceName;
private Repository repository;
/**
* the content assist provider for the {@link Ref}s
*/
protected RefContentAssistProvider assist;
/**
* Creates a new wizard page that allows selection of the target
*
* @param niceSourceName
* the nice displayable name of the source to be pushed.
* @param repo
* source repository
*/
public SimplePushSpecPage(String niceSourceName, Repository repo) {
super(UIText.SimplePushSpecPage_title);
setTitle(UIText.SimplePushSpecPage_title);
setMessage(NLS.bind(UIText.SimplePushSpecPage_message, niceSourceName));
this.sourceName = niceSourceName;
this.repository = repo;
}
public void createControl(Composite parent) {
Composite main = new Composite(parent, SWT.NONE);
GridDataFactory.fillDefaults().grab(true, true).applyTo(main);
main.setLayout(new GridLayout(1, false));
Composite inputPanel = new Composite(main, SWT.NONE);
GridDataFactory.fillDefaults().grab(true, false).applyTo(inputPanel);
inputPanel.setLayout(new GridLayout(2, false));
final Label lblRemote = new Label(inputPanel, SWT.NONE);
lblRemote.setText(UIText.SimplePushSpecPage_TargetRefName);
remoteRefName = new Text(inputPanel, SWT.BORDER);
GridDataFactory.fillDefaults().grab(true, false).applyTo(remoteRefName);
remoteRefName.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
setPageComplete(isPageComplete());
}
});
UIUtils.addRefContentProposalToText(remoteRefName, repository,
new IRefListProvider() {
public List<Ref> getRefList() {
if (assist != null)
return assist.getRefsForContentAssist(false, true);
return Collections.emptyList();
}
});
final Button forceButton = new Button(main, SWT.CHECK);
forceButton.setText(UIText.RefSpecDialog_ForceUpdateCheckbox);
GridDataFactory.fillDefaults().grab(true, false).applyTo(forceButton);
forceButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
forceUpdate = forceButton.getSelection();
}
});
setControl(main);
}
/**
* pre-fills the destination box with a remote ref name if one exists that
* matches the local branch name.
*/
protected void updateDestinationField() {
setMessage(NLS.bind(UIText.SimplePushSpecPage_message, sourceName));
String checkRemote = sourceName;
if (sourceName.startsWith(Constants.R_HEADS)) {
try {
BranchTrackingStatus status = BranchTrackingStatus.of(
repository,
sourceName.substring(Constants.R_HEADS.length()));
if (status != null) {
// calculate the name of the branch on the other side.
checkRemote = status.getRemoteTrackingBranch();
checkRemote = Constants.R_HEADS
+ checkRemote.substring(checkRemote.indexOf('/',
Constants.R_REMOTES.length() + 1) + 1);
setMessage(NLS.bind(
UIText.SimplePushSpecPage_pushAheadInfo,
new Object[] { sourceName,
Integer.valueOf(status.getAheadCount()),
status.getRemoteTrackingBranch() }),
IStatus.INFO);
}
} catch (Exception e) {
// ignore and continue...
}
if (assist == null) {
if (checkRemote != null)
remoteRefName.setText(checkRemote);
return;
}
if (checkRemote == null)
checkRemote = sourceName;
for (Ref ref : assist.getRefsForContentAssist(false, true))
if (ref.getName().equals(checkRemote))
remoteRefName.setText(checkRemote);
}
}
@Override
public boolean isPageComplete() {
return !remoteRefName.getText().isEmpty();
}
/**
* Whether the user wants to force pushing.
*
* @return whether to force the push
*/
public boolean isForceUpdate() {
return forceUpdate;
}
/**
* Retrieves the target name to push to.
*
* @return the target name.
*/
public String getTargetRef() {
return remoteRefName.getText();
}
}
| SimplePushSpecPage: isEmpty() is undefined for the type String in Java 5
Change-Id: I8ca1437882864fe344deed0602ef13162ec98bfe
| org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/components/SimplePushSpecPage.java | SimplePushSpecPage: isEmpty() is undefined for the type String in Java 5 | <ide><path>rg.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/components/SimplePushSpecPage.java
<ide>
<ide> @Override
<ide> public boolean isPageComplete() {
<del> return !remoteRefName.getText().isEmpty();
<add> return remoteRefName.getText() != null
<add> && remoteRefName.getText().length() > 0;
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | 56df0274a4a5ab8f37789eabaec0a419a4aed98a | 0 | leogong/guava,pwz3n0/guava,cklsoft/guava,0359xiaodong/guava,eidehua/guava,tailorlala/guava-libraries,lijunhuayc/guava,jakubmalek/guava,RoliMG/guava,jamesbrowder/guava-libraries,xasx/guava,codershamo/guava,mway08/guava,DaveAKing/guava-libraries,yanyongshan/guava,paplorinc/guava,zcwease/guava-libraries,aditya-chaturvedi/guava,kucci/guava-libraries,mway08/guava,jankill/guava,aditya-chaturvedi/guava,paddx01/guava-src,eidehua/guava,SyllaJay/guava,weihungliu/guava,licheng-xd/guava,leesir/guava,kaoudis/guava,rgoldberg/guava,mengdiwang/guava-libraries,Haus1/guava-libraries,fengshao0907/guava,marstianna/guava,KengoTODA/guava-libraries,mosoft521/guava,sebadiaz/guava,EdwardLee03/guava,tunzao/guava,lgscofield/guava,allalizaki/guava-libraries,seanli310/guava,hannespernpeintner/guava,renchunxiao/guava,fengshao0907/guava-libraries,r4-keisuke/guava,elijah513/guava,xueyin87/guava-libraries,VikingDen/guava,lisb/guava,google/guava,ChengLong/guava,Balzanka/guava-libraries,fengshao0907/guava-libraries,mgedigian/guava-bloom-filter,Yijtx/guava,qingsong-xu/guava,janus-project/guava.janusproject.io,marstianna/guava,chen870647924/guava-libraries,codershamo/guava,Akshay77/guava,EdwardLee03/guava,dpursehouse/guava,Ariloum/guava,njucslqq/guava,rcpoison/guava,mengdiwang/guava-libraries,VikingDen/guava,uschindler/guava,yuan232007/guava,flowbywind/guava,mohanaraosv/guava,xasx/guava,google/guava,ben-manes/guava,mohanaraosv/guava,sunbeansoft/guava,norru/guava,tobecrazy/guava,Overruler/guava-libraries,dnrajugade/guava-libraries,jsnchen/guava,tli2/guava,monokurobo/guava,rgoldberg/guava,yangxu998/guava-libraries,lisb/guava,taoguan/guava,npvincent/guava,XiWenRen/guava,DavesMan/guava,lijunhuayc/guava,yigubigu/guava,mkodekar/guava-libraries,qingsong-xu/guava,jiteshmohan/guava,baratali/guava,leesir/guava,manolama/guava,sensui/guava-libraries,tunzao/guava,juneJuly/guava,DucQuang1/guava,KengoTODA/guava,anigeorge/guava,jakubmalek/guava,GabrielNicolasAvellaneda/guava,mbarbero/guava-libraries,HarveyTvT/guava,nulakasatish/guava-libraries,kgislsompo/guava-libraries,r4-keisuke/guava,Overruler/guava-libraries,paddx01/guava-src,allenprogram/guava,manolama/guava,anigeorge/guava,scr/guava,yigubigu/guava,google/guava,jackyglony/guava,zcwease/guava-libraries,typetools/guava,10045125/guava,xueyin87/guava-libraries,Balzanka/guava-libraries,janus-project/guava.janusproject.io,jackyglony/guava,GabrielNicolasAvellaneda/guava,levenhdu/guava,dubu/guava-libraries,5A68656E67/guava,DavesMan/guava,DaveAKing/guava-libraries,levenhdu/guava,seanli310/guava,ningg/guava,nulakasatish/guava-libraries,aiyanbo/guava,aiyanbo/guava,juneJuly/guava,SaintBacchus/guava,KengoTODA/guava-libraries,jamesbrowder/guava-libraries,0359xiaodong/guava,allenprogram/guava,kaoudis/guava,gvikei/guava-libraries,rob3ns/guava,BollyCheng/guava,ChengLong/guava,BollyCheng/guava,norru/guava,HarveyTvT/guava,Ariloum/guava,berndhopp/guava,leogong/guava,mgalushka/guava,XiWenRen/guava,Xaerxess/guava,tailorlala/guava-libraries,mgalushka/guava,okaywit/guava-libraries,AnselQiao/guava,tobecrazy/guava,AnselQiao/guava,witekcc/guava,ceosilvajr/guava,monokurobo/guava,yuan232007/guava,renchunxiao/guava,dushmis/guava,huangsihuan/guava,thinker-fang/guava,npvincent/guava,jiteshmohan/guava,sensui/guava-libraries,dmi3aleks/guava,cogitate/guava-libraries,liyazhou/guava,cgdecker/guava,5A68656E67/guava,cogitate/guava-libraries,disc99/guava,yanyongshan/guava,sebadiaz/guava,mbarbero/guava-libraries,GitHub4Lgfei/guava,njucslqq/guava,tli2/guava,sunbeansoft/guava,weihungliu/guava,easyfmxu/guava,abel-von/guava,abel-von/guava,liyazhou/guava,Yijtx/guava,montycheese/guava,sarvex/guava,typetools/guava,paplorinc/guava,GitHub4Lgfei/guava,maidh91/guava-libraries,sander120786/guava-libraries,SaintBacchus/guava,yf0994/guava-libraries,RoliMG/guava,chen870647924/guava-libraries,jedyang/guava,fengshao0907/guava,ningg/guava,dpursehouse/guava,dubu/guava-libraries,kucci/guava-libraries,Kevin2030/guava,m3n78am/guava,berndhopp/guava,ignaciotcrespo/guava,ignaciotcrespo/guava,danielnorberg/guava-libraries,binhvu7/guava,mkodekar/guava-libraries,hannespernpeintner/guava,Ranjodh-Singh/ranjodh87-guavalib,kingland/guava,Xaerxess/guava,pwz3n0/guava,taoguan/guava,witekcc/guava,Ranjodh-Singh/ranjodh87-guavalib,huangsihuan/guava,flowbywind/guava,clcron/guava-libraries,lgscofield/guava,SyllaJay/guava,Kevin2030/guava,allalizaki/guava-libraries,mosoft521/guava,jayhetee/guava,sander120786/guava-libraries,kgislsompo/guava-libraries,disc99/guava,thinker-fang/guava,okaywit/guava-libraries,mosoft521/guava,Akshay77/guava,cklsoft/guava,yf0994/guava-libraries,KengoTODA/guava,gmaes/guava,jedyang/guava,baratali/guava,DucQuang1/guava,dnrajugade/guava-libraries,gvikei/guava-libraries,Haus1/guava-libraries,yangxu998/guava-libraries,jsnchen/guava,jankill/guava,m3n78am/guava,scr/guava,montycheese/guava,rcpoison/guava,elijah513/guava,easyfmxu/guava,clcron/guava-libraries,jayhetee/guava,1yvT0s/guava,maidh91/guava-libraries,dushmis/guava,gmaes/guava,1yvT0s/guava,rob3ns/guava,kingland/guava,licheng-xd/guava | /*
* Copyright (C) 2009 The Guava 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 com.google.common.collect;
import static com.google.common.base.Objects.firstNonNull;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.MapMakerInternalMap.Strength.SOFT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Ascii;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Throwables;
import com.google.common.base.Ticker;
import com.google.common.collect.MapMakerInternalMap.Strength;
import java.io.Serializable;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
/**
* <p>A builder of {@link ConcurrentMap} instances having any combination of the following features:
*
* <ul>
* <li>keys or values automatically wrapped in {@linkplain WeakReference weak} or {@linkplain
* SoftReference soft} references
* <li>notification of evicted (or otherwise removed) entries
* <li>on-demand computation of values for keys not already present
* </ul>
*
* <p>Usage example: <pre> {@code
*
* ConcurrentMap<Request, Stopwatch> timers = new MapMaker()
* .concurrencyLevel(4)
* .weakKeys()
* .makeMap();}</pre>
*
* These features are all optional; {@code new MapMaker().makeMap()} returns a valid concurrent map
* that behaves similarly to a {@link ConcurrentHashMap}.
*
* <p>The returned map is implemented as a hash table with similar performance characteristics to
* {@link ConcurrentHashMap}. It supports all optional operations of the {@code ConcurrentMap}
* interface. It does not permit null keys or values.
*
* <p><b>Note:</b> by default, the returned map uses equality comparisons (the {@link Object#equals
* equals} method) to determine equality for keys or values. However, if {@link #weakKeys} was
* specified, the map uses identity ({@code ==}) comparisons instead for keys. Likewise, if {@link
* #weakValues} or {@link #softValues} was specified, the map uses identity comparisons for values.
*
* <p>The view collections of the returned map have <i>weakly consistent iterators</i>. This means
* that they are safe for concurrent use, but if other threads modify the map after the iterator is
* created, it is undefined which of these changes, if any, are reflected in that iterator. These
* iterators never throw {@link ConcurrentModificationException}.
*
* <p>If soft or weak references were requested, it is possible for a key or value present in the
* map to be reclaimed by the garbage collector. If this happens, the entry automatically
* disappears from the map. A partially-reclaimed entry is never exposed to the user. Any {@link
* java.util.Map.Entry} instance retrieved from the map's {@linkplain Map#entrySet entry set} is a
* snapshot of that entry's state at the time of retrieval; such entries do, however, support {@link
* java.util.Map.Entry#setValue}, which simply calls {@link Map#put} on the entry's key.
*
* <p>The maps produced by {@code MapMaker} are serializable, and the deserialized maps retain all
* the configuration properties of the original map. During deserialization, if the original map had
* used soft or weak references, the entries are reconstructed as they were, but it's not unlikely
* they'll be quickly garbage-collected before they are ever accessed.
*
* <p>{@code new MapMaker().weakKeys().makeMap()} is a recommended replacement for {@link
* java.util.WeakHashMap}, but note that it compares keys using object identity whereas {@code
* WeakHashMap} uses {@link Object#equals}.
*
* @author Bob Lee
* @author Charles Fry
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class MapMaker extends GenericMapMaker<Object, Object> {
private static final int DEFAULT_INITIAL_CAPACITY = 16;
private static final int DEFAULT_CONCURRENCY_LEVEL = 4;
private static final int DEFAULT_EXPIRATION_NANOS = 0;
static final int UNSET_INT = -1;
// TODO(kevinb): dispense with this after benchmarking
boolean useCustomMap;
int initialCapacity = UNSET_INT;
int concurrencyLevel = UNSET_INT;
int maximumSize = UNSET_INT;
Strength keyStrength;
Strength valueStrength;
long expireAfterWriteNanos = UNSET_INT;
long expireAfterAccessNanos = UNSET_INT;
RemovalCause nullRemovalCause;
Equivalence<Object> keyEquivalence;
Ticker ticker;
/**
* Constructs a new {@code MapMaker} instance with default settings, including strong keys, strong
* values, and no automatic eviction of any kind.
*/
public MapMaker() {}
/**
* Sets a custom {@code Equivalence} strategy for comparing keys.
*
* <p>By default, the map uses {@link Equivalence#identity} to determine key equality when {@link
* #weakKeys} is specified, and {@link Equivalence#equals()} otherwise. The only place this is
* used is in {@link Interners.WeakInterner}.
*/
@GwtIncompatible("To be supported")
@Override
MapMaker keyEquivalence(Equivalence<Object> equivalence) {
checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence);
keyEquivalence = checkNotNull(equivalence);
this.useCustomMap = true;
return this;
}
Equivalence<Object> getKeyEquivalence() {
return firstNonNull(keyEquivalence, getKeyStrength().defaultEquivalence());
}
/**
* Sets the minimum total size for the internal hash tables. For example, if the initial capacity
* is {@code 60}, and the concurrency level is {@code 8}, then eight segments are created, each
* having a hash table of size eight. Providing a large enough estimate at construction time
* avoids the need for expensive resizing operations later, but setting this value unnecessarily
* high wastes memory.
*
* @throws IllegalArgumentException if {@code initialCapacity} is negative
* @throws IllegalStateException if an initial capacity was already set
*/
@Override
public MapMaker initialCapacity(int initialCapacity) {
checkState(this.initialCapacity == UNSET_INT, "initial capacity was already set to %s",
this.initialCapacity);
checkArgument(initialCapacity >= 0);
this.initialCapacity = initialCapacity;
return this;
}
int getInitialCapacity() {
return (initialCapacity == UNSET_INT) ? DEFAULT_INITIAL_CAPACITY : initialCapacity;
}
/**
* Specifies the maximum number of entries the map may contain. Note that the map <b>may evict an
* entry before this limit is exceeded</b>. As the map size grows close to the maximum, the map
* evicts entries that are less likely to be used again. For example, the map may evict an entry
* because it hasn't been used recently or very often.
*
* <p>When {@code size} is zero, elements can be successfully added to the map, but are evicted
* immediately. This has the same effect as invoking {@link #expireAfterWrite
* expireAfterWrite}{@code (0, unit)} or {@link #expireAfterAccess expireAfterAccess}{@code (0,
* unit)}. It can be useful in testing, or to disable caching temporarily without a code change.
*
* <p>Caching functionality in {@code MapMaker} has been moved to
* {@link com.google.common.cache.CacheBuilder}.
*
* @param size the maximum size of the map
* @throws IllegalArgumentException if {@code size} is negative
* @throws IllegalStateException if a maximum size was already set
* @deprecated Caching functionality in {@code MapMaker} has been moved to
* {@link com.google.common.cache.CacheBuilder}, with {@link #maximumSize} being
* replaced by {@link com.google.common.cache.CacheBuilder#maximumSize}. Note that {@code
* CacheBuilder} is simply an enhanced API for an implementation which was branched from
* {@code MapMaker}.
*/
@Deprecated
@Override
MapMaker maximumSize(int size) {
checkState(this.maximumSize == UNSET_INT, "maximum size was already set to %s",
this.maximumSize);
checkArgument(size >= 0, "maximum size must not be negative");
this.maximumSize = size;
this.useCustomMap = true;
if (maximumSize == 0) {
// SIZE trumps EXPIRED
this.nullRemovalCause = RemovalCause.SIZE;
}
return this;
}
/**
* Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The
* table is internally partitioned to try to permit the indicated number of concurrent updates
* without contention. Because assignment of entries to these partitions is not necessarily
* uniform, the actual concurrency observed may vary. Ideally, you should choose a value to
* accommodate as many threads as will ever concurrently modify the table. Using a significantly
* higher value than you need can waste space and time, and a significantly lower value can lead
* to thread contention. But overestimates and underestimates within an order of magnitude do not
* usually have much noticeable impact. A value of one permits only one thread to modify the map
* at a time, but since read operations can proceed concurrently, this still yields higher
* concurrency than full synchronization. Defaults to 4.
*
* <p><b>Note:</b> Prior to Guava release 9.0, the default was 16. It is possible the default will
* change again in the future. If you care about this value, you should always choose it
* explicitly.
*
* @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive
* @throws IllegalStateException if a concurrency level was already set
*/
@Override
public MapMaker concurrencyLevel(int concurrencyLevel) {
checkState(this.concurrencyLevel == UNSET_INT, "concurrency level was already set to %s",
this.concurrencyLevel);
checkArgument(concurrencyLevel > 0);
this.concurrencyLevel = concurrencyLevel;
return this;
}
int getConcurrencyLevel() {
return (concurrencyLevel == UNSET_INT) ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel;
}
/**
* Specifies that each key (not value) stored in the map should be wrapped in a {@link
* WeakReference} (by default, strong references are used).
*
* <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==})
* comparison to determine equality of keys, which is a technical violation of the {@link Map}
* specification, and may not be what you expect.
*
* @throws IllegalStateException if the key strength was already set
* @see WeakReference
*/
@GwtIncompatible("java.lang.ref.WeakReference")
@Override
public MapMaker weakKeys() {
return setKeyStrength(Strength.WEAK);
}
MapMaker setKeyStrength(Strength strength) {
checkState(keyStrength == null, "Key strength was already set to %s", keyStrength);
keyStrength = checkNotNull(strength);
checkArgument(keyStrength != SOFT, "Soft keys are not supported");
if (strength != Strength.STRONG) {
// STRONG could be used during deserialization.
useCustomMap = true;
}
return this;
}
Strength getKeyStrength() {
return firstNonNull(keyStrength, Strength.STRONG);
}
/**
* Specifies that each value (not key) stored in the map should be wrapped in a
* {@link WeakReference} (by default, strong references are used).
*
* <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor
* candidate for caching; consider {@link #softValues} instead.
*
* <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==})
* comparison to determine equality of values. This technically violates the specifications of
* the methods {@link Map#containsValue containsValue},
* {@link ConcurrentMap#remove(Object, Object) remove(Object, Object)} and
* {@link ConcurrentMap#replace(Object, Object, Object) replace(K, V, V)}, and may not be what you
* expect.
*
* @throws IllegalStateException if the value strength was already set
* @see WeakReference
*/
@GwtIncompatible("java.lang.ref.WeakReference")
@Override
public MapMaker weakValues() {
return setValueStrength(Strength.WEAK);
}
/**
* Specifies that each value (not key) stored in the map should be wrapped in a
* {@link SoftReference} (by default, strong references are used). Softly-referenced objects will
* be garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory
* demand.
*
* <p><b>Warning:</b> in most circumstances it is better to set a per-cache {@linkplain
* #maximumSize maximum size} instead of using soft references. You should only use this method if
* you are well familiar with the practical consequences of soft references.
*
* <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==})
* comparison to determine equality of values. This technically violates the specifications of
* the methods {@link Map#containsValue containsValue},
* {@link ConcurrentMap#remove(Object, Object) remove(Object, Object)} and
* {@link ConcurrentMap#replace(Object, Object, Object) replace(K, V, V)}, and may not be what you
* expect.
*
* @throws IllegalStateException if the value strength was already set
* @see SoftReference
* @deprecated Caching functionality in {@code MapMaker} has been moved to {@link
* com.google.common.cache.CacheBuilder}, with {@link #softValues} being replaced by {@link
* com.google.common.cache.CacheBuilder#softValues}. Note that {@code CacheBuilder} is simply
* an enhanced API for an implementation which was branched from {@code MapMaker}. <b>This
* method is scheduled for deletion in September 2014.</b>
*/
@Deprecated
@GwtIncompatible("java.lang.ref.SoftReference")
@Override
public MapMaker softValues() {
return setValueStrength(Strength.SOFT);
}
MapMaker setValueStrength(Strength strength) {
checkState(valueStrength == null, "Value strength was already set to %s", valueStrength);
valueStrength = checkNotNull(strength);
if (strength != Strength.STRONG) {
// STRONG could be used during deserialization.
useCustomMap = true;
}
return this;
}
Strength getValueStrength() {
return firstNonNull(valueStrength, Strength.STRONG);
}
/**
* Specifies that each entry should be automatically removed from the map once a fixed duration
* has elapsed after the entry's creation, or the most recent replacement of its value.
*
* <p>When {@code duration} is zero, elements can be successfully added to the map, but are
* evicted immediately. This has a very similar effect to invoking {@link #maximumSize
* maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without
* a code change.
*
* <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or
* write operations. Expired entries are currently cleaned up during write operations, or during
* occasional read operations in the absense of writes; though this behavior may change in the
* future.
*
* @param duration the length of time after an entry is created that it should be automatically
* removed
* @param unit the unit that {@code duration} is expressed in
* @throws IllegalArgumentException if {@code duration} is negative
* @throws IllegalStateException if the time to live or time to idle was already set
* @deprecated Caching functionality in {@code MapMaker} has been moved to
* {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterWrite} being
* replaced by {@link com.google.common.cache.CacheBuilder#expireAfterWrite}. Note that {@code
* CacheBuilder} is simply an enhanced API for an implementation which was branched from
* {@code MapMaker}.
*/
@Deprecated
@Override
MapMaker expireAfterWrite(long duration, TimeUnit unit) {
checkExpiration(duration, unit);
this.expireAfterWriteNanos = unit.toNanos(duration);
if (duration == 0 && this.nullRemovalCause == null) {
// SIZE trumps EXPIRED
this.nullRemovalCause = RemovalCause.EXPIRED;
}
useCustomMap = true;
return this;
}
private void checkExpiration(long duration, TimeUnit unit) {
checkState(expireAfterWriteNanos == UNSET_INT, "expireAfterWrite was already set to %s ns",
expireAfterWriteNanos);
checkState(expireAfterAccessNanos == UNSET_INT, "expireAfterAccess was already set to %s ns",
expireAfterAccessNanos);
checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
}
long getExpireAfterWriteNanos() {
return (expireAfterWriteNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterWriteNanos;
}
/**
* Specifies that each entry should be automatically removed from the map once a fixed duration
* has elapsed after the entry's last read or write access.
*
* <p>When {@code duration} is zero, elements can be successfully added to the map, but are
* evicted immediately. This has a very similar effect to invoking {@link #maximumSize
* maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without
* a code change.
*
* <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or
* write operations. Expired entries are currently cleaned up during write operations, or during
* occasional read operations in the absense of writes; though this behavior may change in the
* future.
*
* @param duration the length of time after an entry is last accessed that it should be
* automatically removed
* @param unit the unit that {@code duration} is expressed in
* @throws IllegalArgumentException if {@code duration} is negative
* @throws IllegalStateException if the time to idle or time to live was already set
* @deprecated Caching functionality in {@code MapMaker} has been moved to
* {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterAccess} being
* replaced by {@link com.google.common.cache.CacheBuilder#expireAfterAccess}. Note that
* {@code CacheBuilder} is simply an enhanced API for an implementation which was branched
* from {@code MapMaker}.
*/
@Deprecated
@GwtIncompatible("To be supported")
@Override
MapMaker expireAfterAccess(long duration, TimeUnit unit) {
checkExpiration(duration, unit);
this.expireAfterAccessNanos = unit.toNanos(duration);
if (duration == 0 && this.nullRemovalCause == null) {
// SIZE trumps EXPIRED
this.nullRemovalCause = RemovalCause.EXPIRED;
}
useCustomMap = true;
return this;
}
long getExpireAfterAccessNanos() {
return (expireAfterAccessNanos == UNSET_INT)
? DEFAULT_EXPIRATION_NANOS : expireAfterAccessNanos;
}
Ticker getTicker() {
return firstNonNull(ticker, Ticker.systemTicker());
}
/**
* Specifies a listener instance, which all maps built using this {@code MapMaker} will notify
* each time an entry is removed from the map by any means.
*
* <p>Each map built by this map maker after this method is called invokes the supplied listener
* after removing an element for any reason (see removal causes in {@link RemovalCause}). It will
* invoke the listener during invocations of any of that map's public methods (even read-only
* methods).
*
* <p><b>Important note:</b> Instead of returning <i>this</i> as a {@code MapMaker} instance,
* this method returns {@code GenericMapMaker<K, V>}. From this point on, either the original
* reference or the returned reference may be used to complete configuration and build the map,
* but only the "generic" one is type-safe. That is, it will properly prevent you from building
* maps whose key or value types are incompatible with the types accepted by the listener already
* provided; the {@code MapMaker} type cannot do this. For best results, simply use the standard
* method-chaining idiom, as illustrated in the documentation at top, configuring a {@code
* MapMaker} and building your {@link Map} all in a single statement.
*
* <p><b>Warning:</b> if you ignore the above advice, and use this {@code MapMaker} to build a map
* or cache whose key or value type is incompatible with the listener, you will likely experience
* a {@link ClassCastException} at some <i>undefined</i> point in the future.
*
* @throws IllegalStateException if a removal listener was already set
* @deprecated Caching functionality in {@code MapMaker} has been moved to
* {@link com.google.common.cache.CacheBuilder}, with {@link #removalListener} being
* replaced by {@link com.google.common.cache.CacheBuilder#removalListener}. Note that {@code
* CacheBuilder} is simply an enhanced API for an implementation which was branched from
* {@code MapMaker}.
*/
@Deprecated
@GwtIncompatible("To be supported")
<K, V> GenericMapMaker<K, V> removalListener(RemovalListener<K, V> listener) {
checkState(this.removalListener == null);
// safely limiting the kinds of maps this can produce
@SuppressWarnings("unchecked")
GenericMapMaker<K, V> me = (GenericMapMaker<K, V>) this;
me.removalListener = checkNotNull(listener);
useCustomMap = true;
return me;
}
/**
* Builds a thread-safe map, without on-demand computation of values. This method does not alter
* the state of this {@code MapMaker} instance, so it can be invoked again to create multiple
* independent maps.
*
* <p>The bulk operations {@code putAll}, {@code equals}, and {@code clear} are not guaranteed to
* be performed atomically on the returned map. Additionally, {@code size} and {@code
* containsValue} are implemented as bulk read operations, and thus may fail to observe concurrent
* writes.
*
* @return a serializable concurrent map having the requested features
*/
@Override
public <K, V> ConcurrentMap<K, V> makeMap() {
if (!useCustomMap) {
return new ConcurrentHashMap<K, V>(getInitialCapacity(), 0.75f, getConcurrencyLevel());
}
return (nullRemovalCause == null)
? new MapMakerInternalMap<K, V>(this)
: new NullConcurrentMap<K, V>(this);
}
/**
* Returns a MapMakerInternalMap for the benefit of internal callers that use features of
* that class not exposed through ConcurrentMap.
*/
@Override
@GwtIncompatible("MapMakerInternalMap")
<K, V> MapMakerInternalMap<K, V> makeCustomMap() {
return new MapMakerInternalMap<K, V>(this);
}
/**
* Builds a map that supports atomic, on-demand computation of values. {@link Map#get} either
* returns an already-computed value for the given key, atomically computes it using the supplied
* function, or, if another thread is currently computing the value for this key, simply waits for
* that thread to finish and returns its computed value. Note that the function may be executed
* concurrently by multiple threads, but only for distinct keys.
*
* <p>New code should use {@link com.google.common.cache.CacheBuilder}, which supports
* {@linkplain com.google.common.cache.CacheStats statistics} collection, introduces the
* {@link com.google.common.cache.CacheLoader} interface for loading entries into the cache
* (allowing checked exceptions to be thrown in the process), and more cleanly separates
* computation from the cache's {@code Map} view.
*
* <p>If an entry's value has not finished computing yet, query methods besides {@code get} return
* immediately as if an entry doesn't exist. In other words, an entry isn't externally visible
* until the value's computation completes.
*
* <p>{@link Map#get} on the returned map will never return {@code null}. It may throw:
*
* <ul>
* <li>{@link NullPointerException} if the key is null or the computing function returns a null
* result
* <li>{@link ComputationException} if an exception was thrown by the computing function. If that
* exception is already of type {@link ComputationException} it is propagated directly; otherwise
* it is wrapped.
* </ul>
*
* <p><b>Note:</b> Callers of {@code get} <i>must</i> ensure that the key argument is of type
* {@code K}. The {@code get} method accepts {@code Object}, so the key type is not checked at
* compile time. Passing an object of a type other than {@code K} can result in that object being
* unsafely passed to the computing function as type {@code K}, and unsafely stored in the map.
*
* <p>If {@link Map#put} is called before a computation completes, other threads waiting on the
* computation will wake up and return the stored value.
*
* <p>This method does not alter the state of this {@code MapMaker} instance, so it can be invoked
* again to create multiple independent maps.
*
* <p>Insertion, removal, update, and access operations on the returned map safely execute
* concurrently by multiple threads. Iterators on the returned map are weakly consistent,
* returning elements reflecting the state of the map at some point at or since the creation of
* the iterator. They do not throw {@link ConcurrentModificationException}, and may proceed
* concurrently with other operations.
*
* <p>The bulk operations {@code putAll}, {@code equals}, and {@code clear} are not guaranteed to
* be performed atomically on the returned map. Additionally, {@code size} and {@code
* containsValue} are implemented as bulk read operations, and thus may fail to observe concurrent
* writes.
*
* @param computingFunction the function used to compute new values
* @return a serializable concurrent map having the requested features
* @deprecated Caching functionality in {@code MapMaker} has been moved to
* {@link com.google.common.cache.CacheBuilder}, with {@link #makeComputingMap} being replaced
* by {@link com.google.common.cache.CacheBuilder#build}. See the
* <a href="http://code.google.com/p/guava-libraries/wiki/MapMakerMigration">MapMaker
* Migration Guide</a> for more details.
*/
@Deprecated
@Override
<K, V> ConcurrentMap<K, V> makeComputingMap(
Function<? super K, ? extends V> computingFunction) {
return (nullRemovalCause == null)
? new MapMaker.ComputingMapAdapter<K, V>(this, computingFunction)
: new NullComputingConcurrentMap<K, V>(this, computingFunction);
}
/**
* Returns a string representation for this MapMaker instance. The exact form of the returned
* string is not specificed.
*/
@Override
public String toString() {
Objects.ToStringHelper s = Objects.toStringHelper(this);
if (initialCapacity != UNSET_INT) {
s.add("initialCapacity", initialCapacity);
}
if (concurrencyLevel != UNSET_INT) {
s.add("concurrencyLevel", concurrencyLevel);
}
if (maximumSize != UNSET_INT) {
s.add("maximumSize", maximumSize);
}
if (expireAfterWriteNanos != UNSET_INT) {
s.add("expireAfterWrite", expireAfterWriteNanos + "ns");
}
if (expireAfterAccessNanos != UNSET_INT) {
s.add("expireAfterAccess", expireAfterAccessNanos + "ns");
}
if (keyStrength != null) {
s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString()));
}
if (valueStrength != null) {
s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString()));
}
if (keyEquivalence != null) {
s.addValue("keyEquivalence");
}
if (removalListener != null) {
s.addValue("removalListener");
}
return s.toString();
}
/**
* An object that can receive a notification when an entry is removed from a map. The removal
* resulting in notification could have occured to an entry being manually removed or replaced, or
* due to eviction resulting from timed expiration, exceeding a maximum size, or garbage
* collection.
*
* <p>An instance may be called concurrently by multiple threads to process different entries.
* Implementations of this interface should avoid performing blocking calls or synchronizing on
* shared resources.
*
* @param <K> the most general type of keys this listener can listen for; for
* example {@code Object} if any key is acceptable
* @param <V> the most general type of values this listener can listen for; for
* example {@code Object} if any key is acceptable
*/
interface RemovalListener<K, V> {
/**
* Notifies the listener that a removal occurred at some point in the past.
*/
void onRemoval(RemovalNotification<K, V> notification);
}
/**
* A notification of the removal of a single entry. The key or value may be null if it was already
* garbage collected.
*
* <p>Like other {@code Map.Entry} instances associated with MapMaker, this class holds strong
* references to the key and value, regardless of the type of references the map may be using.
*/
static final class RemovalNotification<K, V> extends ImmutableEntry<K, V> {
private static final long serialVersionUID = 0;
private final RemovalCause cause;
RemovalNotification(@Nullable K key, @Nullable V value, RemovalCause cause) {
super(key, value);
this.cause = cause;
}
/**
* Returns the cause for which the entry was removed.
*/
public RemovalCause getCause() {
return cause;
}
/**
* Returns {@code true} if there was an automatic removal due to eviction (the cause is neither
* {@link RemovalCause#EXPLICIT} nor {@link RemovalCause#REPLACED}).
*/
public boolean wasEvicted() {
return cause.wasEvicted();
}
}
/**
* The reason why an entry was removed.
*/
enum RemovalCause {
/**
* The entry was manually removed by the user. This can result from the user invoking
* {@link Map#remove}, {@link ConcurrentMap#remove}, or {@link java.util.Iterator#remove}.
*/
EXPLICIT {
@Override
boolean wasEvicted() {
return false;
}
},
/**
* The entry itself was not actually removed, but its value was replaced by the user. This can
* result from the user invoking {@link Map#put}, {@link Map#putAll},
* {@link ConcurrentMap#replace(Object, Object)}, or
* {@link ConcurrentMap#replace(Object, Object, Object)}.
*/
REPLACED {
@Override
boolean wasEvicted() {
return false;
}
},
/**
* The entry was removed automatically because its key or value was garbage-collected. This can
* occur when using {@link #softValues}, {@link #weakKeys}, or {@link #weakValues}.
*/
COLLECTED {
@Override
boolean wasEvicted() {
return true;
}
},
/**
* The entry's expiration timestamp has passed. This can occur when using {@link
* #expireAfterWrite} or {@link #expireAfterAccess}.
*/
EXPIRED {
@Override
boolean wasEvicted() {
return true;
}
},
/**
* The entry was evicted due to size constraints. This can occur when using {@link
* #maximumSize}.
*/
SIZE {
@Override
boolean wasEvicted() {
return true;
}
};
/**
* Returns {@code true} if there was an automatic removal due to eviction (the cause is neither
* {@link #EXPLICIT} nor {@link #REPLACED}).
*/
abstract boolean wasEvicted();
}
/** A map that is always empty and evicts on insertion. */
static class NullConcurrentMap<K, V> extends AbstractMap<K, V>
implements ConcurrentMap<K, V>, Serializable {
private static final long serialVersionUID = 0;
private final RemovalListener<K, V> removalListener;
private final RemovalCause removalCause;
NullConcurrentMap(MapMaker mapMaker) {
removalListener = mapMaker.getRemovalListener();
removalCause = mapMaker.nullRemovalCause;
}
// implements ConcurrentMap
@Override
public boolean containsKey(@Nullable Object key) {
return false;
}
@Override
public boolean containsValue(@Nullable Object value) {
return false;
}
@Override
public V get(@Nullable Object key) {
return null;
}
void notifyRemoval(K key, V value) {
RemovalNotification<K, V> notification =
new RemovalNotification<K, V>(key, value, removalCause);
removalListener.onRemoval(notification);
}
@Override
public V put(K key, V value) {
checkNotNull(key);
checkNotNull(value);
notifyRemoval(key, value);
return null;
}
@Override
public V putIfAbsent(K key, V value) {
return put(key, value);
}
@Override
public V remove(@Nullable Object key) {
return null;
}
@Override
public boolean remove(@Nullable Object key, @Nullable Object value) {
return false;
}
@Override
public V replace(K key, V value) {
checkNotNull(key);
checkNotNull(value);
return null;
}
@Override
public boolean replace(K key, @Nullable V oldValue, V newValue) {
checkNotNull(key);
checkNotNull(newValue);
return false;
}
@Override
public Set<Entry<K, V>> entrySet() {
return Collections.emptySet();
}
}
/** Computes on retrieval and evicts the result. */
static final class NullComputingConcurrentMap<K, V> extends NullConcurrentMap<K, V> {
private static final long serialVersionUID = 0;
final Function<? super K, ? extends V> computingFunction;
NullComputingConcurrentMap(
MapMaker mapMaker, Function<? super K, ? extends V> computingFunction) {
super(mapMaker);
this.computingFunction = checkNotNull(computingFunction);
}
@SuppressWarnings("unchecked") // unsafe, which is why Cache is preferred
@Override
public V get(Object k) {
K key = (K) k;
V value = compute(key);
checkNotNull(value, computingFunction + " returned null for key " + key + ".");
notifyRemoval(key, value);
return value;
}
private V compute(K key) {
checkNotNull(key);
try {
return computingFunction.apply(key);
} catch (ComputationException e) {
throw e;
} catch (Throwable t) {
throw new ComputationException(t);
}
}
}
/**
* Overrides get() to compute on demand. Also throws an exception when {@code null} is returned
* from a computation.
*/
/*
* This might make more sense in ComputingConcurrentHashMap, but it causes a javac crash in some
* cases there: http://code.google.com/p/guava-libraries/issues/detail?id=950
*/
static final class ComputingMapAdapter<K, V>
extends ComputingConcurrentHashMap<K, V> implements Serializable {
private static final long serialVersionUID = 0;
ComputingMapAdapter(MapMaker mapMaker,
Function<? super K, ? extends V> computingFunction) {
super(mapMaker, computingFunction);
}
@SuppressWarnings("unchecked") // unsafe, which is one advantage of Cache over Map
@Override
public V get(Object key) {
V value;
try {
value = getOrCompute((K) key);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
Throwables.propagateIfInstanceOf(cause, ComputationException.class);
throw new ComputationException(cause);
}
if (value == null) {
throw new NullPointerException(computingFunction + " returned null for key " + key + ".");
}
return value;
}
}
}
| guava/src/com/google/common/collect/MapMaker.java | /*
* Copyright (C) 2009 The Guava 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 com.google.common.collect;
import static com.google.common.base.Objects.firstNonNull;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.MapMakerInternalMap.Strength.SOFT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Ascii;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Throwables;
import com.google.common.base.Ticker;
import com.google.common.collect.MapMakerInternalMap.Strength;
import java.io.Serializable;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
/**
* <p>A builder of {@link ConcurrentMap} instances having any combination of the following features:
*
* <ul>
* <li>keys or values automatically wrapped in {@linkplain WeakReference weak} or {@linkplain
* SoftReference soft} references
* <li>notification of evicted (or otherwise removed) entries
* <li>on-demand computation of values for keys not already present
* </ul>
*
* <p>Usage example: <pre> {@code
*
* ConcurrentMap<Request, Stopwatch> timers = new MapMaker()
* .concurrencyLevel(4)
* .weakKeys()
* .makeMap();}</pre>
*
* These features are all optional; {@code new MapMaker().makeMap()} returns a valid concurrent map
* that behaves similarly to a {@link ConcurrentHashMap}.
*
* <p>The returned map is implemented as a hash table with similar performance characteristics to
* {@link ConcurrentHashMap}. It supports all optional operations of the {@code ConcurrentMap}
* interface. It does not permit null keys or values.
*
* <p><b>Note:</b> by default, the returned map uses equality comparisons (the {@link Object#equals
* equals} method) to determine equality for keys or values. However, if {@link #weakKeys} was
* specified, the map uses identity ({@code ==}) comparisons instead for keys. Likewise, if {@link
* #weakValues} or {@link #softValues} was specified, the map uses identity comparisons for values.
*
* <p>The view collections of the returned map have <i>weakly consistent iterators</i>. This means
* that they are safe for concurrent use, but if other threads modify the map after the iterator is
* created, it is undefined which of these changes, if any, are reflected in that iterator. These
* iterators never throw {@link ConcurrentModificationException}.
*
* <p>If soft or weak references were requested, it is possible for a key or value present in the
* map to be reclaimed by the garbage collector. If this happens, the entry automatically
* disappears from the map. A partially-reclaimed entry is never exposed to the user. Any {@link
* java.util.Map.Entry} instance retrieved from the map's {@linkplain Map#entrySet entry set} is a
* snapshot of that entry's state at the time of retrieval; such entries do, however, support {@link
* java.util.Map.Entry#setValue}, which simply calls {@link Map#put} on the entry's key.
*
* <p>The maps produced by {@code MapMaker} are serializable, and the deserialized maps retain all
* the configuration properties of the original map. During deserialization, if the original map had
* used soft or weak references, the entries are reconstructed as they were, but it's not unlikely
* they'll be quickly garbage-collected before they are ever accessed.
*
* <p>{@code new MapMaker().weakKeys().makeMap()} is a recommended replacement for {@link
* java.util.WeakHashMap}, but note that it compares keys using object identity whereas {@code
* WeakHashMap} uses {@link Object#equals}.
*
* @author Bob Lee
* @author Charles Fry
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class MapMaker extends GenericMapMaker<Object, Object> {
private static final int DEFAULT_INITIAL_CAPACITY = 16;
private static final int DEFAULT_CONCURRENCY_LEVEL = 4;
private static final int DEFAULT_EXPIRATION_NANOS = 0;
static final int UNSET_INT = -1;
// TODO(kevinb): dispense with this after benchmarking
boolean useCustomMap;
int initialCapacity = UNSET_INT;
int concurrencyLevel = UNSET_INT;
int maximumSize = UNSET_INT;
Strength keyStrength;
Strength valueStrength;
long expireAfterWriteNanos = UNSET_INT;
long expireAfterAccessNanos = UNSET_INT;
RemovalCause nullRemovalCause;
Equivalence<Object> keyEquivalence;
Ticker ticker;
/**
* Constructs a new {@code MapMaker} instance with default settings, including strong keys, strong
* values, and no automatic eviction of any kind.
*/
public MapMaker() {}
/**
* Sets a custom {@code Equivalence} strategy for comparing keys.
*
* <p>By default, the map uses {@link Equivalence#identity} to determine key equality when {@link
* #weakKeys} is specified, and {@link Equivalence#equals()} otherwise. The only place this is
* used is in {@link Interners.WeakInterner}.
*/
@GwtIncompatible("To be supported")
@Override
MapMaker keyEquivalence(Equivalence<Object> equivalence) {
checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence);
keyEquivalence = checkNotNull(equivalence);
this.useCustomMap = true;
return this;
}
Equivalence<Object> getKeyEquivalence() {
return firstNonNull(keyEquivalence, getKeyStrength().defaultEquivalence());
}
/**
* Sets the minimum total size for the internal hash tables. For example, if the initial capacity
* is {@code 60}, and the concurrency level is {@code 8}, then eight segments are created, each
* having a hash table of size eight. Providing a large enough estimate at construction time
* avoids the need for expensive resizing operations later, but setting this value unnecessarily
* high wastes memory.
*
* @throws IllegalArgumentException if {@code initialCapacity} is negative
* @throws IllegalStateException if an initial capacity was already set
*/
@Override
public MapMaker initialCapacity(int initialCapacity) {
checkState(this.initialCapacity == UNSET_INT, "initial capacity was already set to %s",
this.initialCapacity);
checkArgument(initialCapacity >= 0);
this.initialCapacity = initialCapacity;
return this;
}
int getInitialCapacity() {
return (initialCapacity == UNSET_INT) ? DEFAULT_INITIAL_CAPACITY : initialCapacity;
}
/**
* Specifies the maximum number of entries the map may contain. Note that the map <b>may evict an
* entry before this limit is exceeded</b>. As the map size grows close to the maximum, the map
* evicts entries that are less likely to be used again. For example, the map may evict an entry
* because it hasn't been used recently or very often.
*
* <p>When {@code size} is zero, elements can be successfully added to the map, but are evicted
* immediately. This has the same effect as invoking {@link #expireAfterWrite
* expireAfterWrite}{@code (0, unit)} or {@link #expireAfterAccess expireAfterAccess}{@code (0,
* unit)}. It can be useful in testing, or to disable caching temporarily without a code change.
*
* <p>Caching functionality in {@code MapMaker} has been moved to
* {@link com.google.common.cache.CacheBuilder}.
*
* @param size the maximum size of the map
* @throws IllegalArgumentException if {@code size} is negative
* @throws IllegalStateException if a maximum size was already set
* @deprecated Caching functionality in {@code MapMaker} has been moved to
* {@link com.google.common.cache.CacheBuilder}, with {@link #maximumSize} being
* replaced by {@link com.google.common.cache.CacheBuilder#maximumSize}. Note that {@code
* CacheBuilder} is simply an enhanced API for an implementation which was branched from
* {@code MapMaker}.
*/
@Deprecated
@Override
MapMaker maximumSize(int size) {
checkState(this.maximumSize == UNSET_INT, "maximum size was already set to %s",
this.maximumSize);
checkArgument(size >= 0, "maximum size must not be negative");
this.maximumSize = size;
this.useCustomMap = true;
if (maximumSize == 0) {
// SIZE trumps EXPIRED
this.nullRemovalCause = RemovalCause.SIZE;
}
return this;
}
/**
* Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The
* table is internally partitioned to try to permit the indicated number of concurrent updates
* without contention. Because assignment of entries to these partitions is not necessarily
* uniform, the actual concurrency observed may vary. Ideally, you should choose a value to
* accommodate as many threads as will ever concurrently modify the table. Using a significantly
* higher value than you need can waste space and time, and a significantly lower value can lead
* to thread contention. But overestimates and underestimates within an order of magnitude do not
* usually have much noticeable impact. A value of one permits only one thread to modify the map
* at a time, but since read operations can proceed concurrently, this still yields higher
* concurrency than full synchronization. Defaults to 4.
*
* <p><b>Note:</b> Prior to Guava release 9.0, the default was 16. It is possible the default will
* change again in the future. If you care about this value, you should always choose it
* explicitly.
*
* @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive
* @throws IllegalStateException if a concurrency level was already set
*/
@Override
public MapMaker concurrencyLevel(int concurrencyLevel) {
checkState(this.concurrencyLevel == UNSET_INT, "concurrency level was already set to %s",
this.concurrencyLevel);
checkArgument(concurrencyLevel > 0);
this.concurrencyLevel = concurrencyLevel;
return this;
}
int getConcurrencyLevel() {
return (concurrencyLevel == UNSET_INT) ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel;
}
/**
* Specifies that each key (not value) stored in the map should be wrapped in a {@link
* WeakReference} (by default, strong references are used).
*
* <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==})
* comparison to determine equality of keys, which is a technical violation of the {@link Map}
* specification, and may not be what you expect.
*
* @throws IllegalStateException if the key strength was already set
* @see WeakReference
*/
@GwtIncompatible("java.lang.ref.WeakReference")
@Override
public MapMaker weakKeys() {
return setKeyStrength(Strength.WEAK);
}
MapMaker setKeyStrength(Strength strength) {
checkState(keyStrength == null, "Key strength was already set to %s", keyStrength);
keyStrength = checkNotNull(strength);
checkArgument(keyStrength != SOFT, "Soft keys are not supported");
if (strength != Strength.STRONG) {
// STRONG could be used during deserialization.
useCustomMap = true;
}
return this;
}
Strength getKeyStrength() {
return firstNonNull(keyStrength, Strength.STRONG);
}
/**
* Specifies that each value (not key) stored in the map should be wrapped in a
* {@link WeakReference} (by default, strong references are used).
*
* <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor
* candidate for caching; consider {@link #softValues} instead.
*
* <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==})
* comparison to determine equality of values. This technically violates the specifications of
* the methods {@link Map#containsValue containsValue},
* {@link ConcurrentMap#remove(Object, Object) remove(Object, Object)} and
* {@link ConcurrentMap#replace(Object, Object, Object) replace(K, V, V)}, and may not be what you
* expect.
*
* @throws IllegalStateException if the value strength was already set
* @see WeakReference
*/
@GwtIncompatible("java.lang.ref.WeakReference")
@Override
public MapMaker weakValues() {
return setValueStrength(Strength.WEAK);
}
/**
* Specifies that each value (not key) stored in the map should be wrapped in a
* {@link SoftReference} (by default, strong references are used). Softly-referenced objects will
* be garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory
* demand.
*
* <p><b>Warning:</b> in most circumstances it is better to set a per-cache {@linkplain
* #maximumSize maximum size} instead of using soft references. You should only use this method if
* you are well familiar with the practical consequences of soft references.
*
* <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==})
* comparison to determine equality of values. This technically violates the specifications of
* the methods {@link Map#containsValue containsValue},
* {@link ConcurrentMap#remove(Object, Object) remove(Object, Object)} and
* {@link ConcurrentMap#replace(Object, Object, Object) replace(K, V, V)}, and may not be what you
* expect.
*
* @throws IllegalStateException if the value strength was already set
* @see SoftReference
* @deprecated Caching functionality in {@code MapMaker} has been moved to {@link
* com.google.common.cache.CacheBuilder}, with {@link #softValues} being replaced by {@link
* com.google.common.cache.CacheBuilder#softValues}. Note that {@code CacheBuilder} is simply
* an enhanced API for an implementation which was branched from {@code MapMaker}. <b>This
* method is scheduled for deletion in August 2014.</b>
*/
@Deprecated
@GwtIncompatible("java.lang.ref.SoftReference")
@Override
public MapMaker softValues() {
return setValueStrength(Strength.SOFT);
}
MapMaker setValueStrength(Strength strength) {
checkState(valueStrength == null, "Value strength was already set to %s", valueStrength);
valueStrength = checkNotNull(strength);
if (strength != Strength.STRONG) {
// STRONG could be used during deserialization.
useCustomMap = true;
}
return this;
}
Strength getValueStrength() {
return firstNonNull(valueStrength, Strength.STRONG);
}
/**
* Specifies that each entry should be automatically removed from the map once a fixed duration
* has elapsed after the entry's creation, or the most recent replacement of its value.
*
* <p>When {@code duration} is zero, elements can be successfully added to the map, but are
* evicted immediately. This has a very similar effect to invoking {@link #maximumSize
* maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without
* a code change.
*
* <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or
* write operations. Expired entries are currently cleaned up during write operations, or during
* occasional read operations in the absense of writes; though this behavior may change in the
* future.
*
* @param duration the length of time after an entry is created that it should be automatically
* removed
* @param unit the unit that {@code duration} is expressed in
* @throws IllegalArgumentException if {@code duration} is negative
* @throws IllegalStateException if the time to live or time to idle was already set
* @deprecated Caching functionality in {@code MapMaker} has been moved to
* {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterWrite} being
* replaced by {@link com.google.common.cache.CacheBuilder#expireAfterWrite}. Note that {@code
* CacheBuilder} is simply an enhanced API for an implementation which was branched from
* {@code MapMaker}.
*/
@Deprecated
@Override
MapMaker expireAfterWrite(long duration, TimeUnit unit) {
checkExpiration(duration, unit);
this.expireAfterWriteNanos = unit.toNanos(duration);
if (duration == 0 && this.nullRemovalCause == null) {
// SIZE trumps EXPIRED
this.nullRemovalCause = RemovalCause.EXPIRED;
}
useCustomMap = true;
return this;
}
private void checkExpiration(long duration, TimeUnit unit) {
checkState(expireAfterWriteNanos == UNSET_INT, "expireAfterWrite was already set to %s ns",
expireAfterWriteNanos);
checkState(expireAfterAccessNanos == UNSET_INT, "expireAfterAccess was already set to %s ns",
expireAfterAccessNanos);
checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
}
long getExpireAfterWriteNanos() {
return (expireAfterWriteNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterWriteNanos;
}
/**
* Specifies that each entry should be automatically removed from the map once a fixed duration
* has elapsed after the entry's last read or write access.
*
* <p>When {@code duration} is zero, elements can be successfully added to the map, but are
* evicted immediately. This has a very similar effect to invoking {@link #maximumSize
* maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without
* a code change.
*
* <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or
* write operations. Expired entries are currently cleaned up during write operations, or during
* occasional read operations in the absense of writes; though this behavior may change in the
* future.
*
* @param duration the length of time after an entry is last accessed that it should be
* automatically removed
* @param unit the unit that {@code duration} is expressed in
* @throws IllegalArgumentException if {@code duration} is negative
* @throws IllegalStateException if the time to idle or time to live was already set
* @deprecated Caching functionality in {@code MapMaker} has been moved to
* {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterAccess} being
* replaced by {@link com.google.common.cache.CacheBuilder#expireAfterAccess}. Note that
* {@code CacheBuilder} is simply an enhanced API for an implementation which was branched
* from {@code MapMaker}.
*/
@Deprecated
@GwtIncompatible("To be supported")
@Override
MapMaker expireAfterAccess(long duration, TimeUnit unit) {
checkExpiration(duration, unit);
this.expireAfterAccessNanos = unit.toNanos(duration);
if (duration == 0 && this.nullRemovalCause == null) {
// SIZE trumps EXPIRED
this.nullRemovalCause = RemovalCause.EXPIRED;
}
useCustomMap = true;
return this;
}
long getExpireAfterAccessNanos() {
return (expireAfterAccessNanos == UNSET_INT)
? DEFAULT_EXPIRATION_NANOS : expireAfterAccessNanos;
}
Ticker getTicker() {
return firstNonNull(ticker, Ticker.systemTicker());
}
/**
* Specifies a listener instance, which all maps built using this {@code MapMaker} will notify
* each time an entry is removed from the map by any means.
*
* <p>Each map built by this map maker after this method is called invokes the supplied listener
* after removing an element for any reason (see removal causes in {@link RemovalCause}). It will
* invoke the listener during invocations of any of that map's public methods (even read-only
* methods).
*
* <p><b>Important note:</b> Instead of returning <i>this</i> as a {@code MapMaker} instance,
* this method returns {@code GenericMapMaker<K, V>}. From this point on, either the original
* reference or the returned reference may be used to complete configuration and build the map,
* but only the "generic" one is type-safe. That is, it will properly prevent you from building
* maps whose key or value types are incompatible with the types accepted by the listener already
* provided; the {@code MapMaker} type cannot do this. For best results, simply use the standard
* method-chaining idiom, as illustrated in the documentation at top, configuring a {@code
* MapMaker} and building your {@link Map} all in a single statement.
*
* <p><b>Warning:</b> if you ignore the above advice, and use this {@code MapMaker} to build a map
* or cache whose key or value type is incompatible with the listener, you will likely experience
* a {@link ClassCastException} at some <i>undefined</i> point in the future.
*
* @throws IllegalStateException if a removal listener was already set
* @deprecated Caching functionality in {@code MapMaker} has been moved to
* {@link com.google.common.cache.CacheBuilder}, with {@link #removalListener} being
* replaced by {@link com.google.common.cache.CacheBuilder#removalListener}. Note that {@code
* CacheBuilder} is simply an enhanced API for an implementation which was branched from
* {@code MapMaker}.
*/
@Deprecated
@GwtIncompatible("To be supported")
<K, V> GenericMapMaker<K, V> removalListener(RemovalListener<K, V> listener) {
checkState(this.removalListener == null);
// safely limiting the kinds of maps this can produce
@SuppressWarnings("unchecked")
GenericMapMaker<K, V> me = (GenericMapMaker<K, V>) this;
me.removalListener = checkNotNull(listener);
useCustomMap = true;
return me;
}
/**
* Builds a thread-safe map, without on-demand computation of values. This method does not alter
* the state of this {@code MapMaker} instance, so it can be invoked again to create multiple
* independent maps.
*
* <p>The bulk operations {@code putAll}, {@code equals}, and {@code clear} are not guaranteed to
* be performed atomically on the returned map. Additionally, {@code size} and {@code
* containsValue} are implemented as bulk read operations, and thus may fail to observe concurrent
* writes.
*
* @return a serializable concurrent map having the requested features
*/
@Override
public <K, V> ConcurrentMap<K, V> makeMap() {
if (!useCustomMap) {
return new ConcurrentHashMap<K, V>(getInitialCapacity(), 0.75f, getConcurrencyLevel());
}
return (nullRemovalCause == null)
? new MapMakerInternalMap<K, V>(this)
: new NullConcurrentMap<K, V>(this);
}
/**
* Returns a MapMakerInternalMap for the benefit of internal callers that use features of
* that class not exposed through ConcurrentMap.
*/
@Override
@GwtIncompatible("MapMakerInternalMap")
<K, V> MapMakerInternalMap<K, V> makeCustomMap() {
return new MapMakerInternalMap<K, V>(this);
}
/**
* Builds a map that supports atomic, on-demand computation of values. {@link Map#get} either
* returns an already-computed value for the given key, atomically computes it using the supplied
* function, or, if another thread is currently computing the value for this key, simply waits for
* that thread to finish and returns its computed value. Note that the function may be executed
* concurrently by multiple threads, but only for distinct keys.
*
* <p>New code should use {@link com.google.common.cache.CacheBuilder}, which supports
* {@linkplain com.google.common.cache.CacheStats statistics} collection, introduces the
* {@link com.google.common.cache.CacheLoader} interface for loading entries into the cache
* (allowing checked exceptions to be thrown in the process), and more cleanly separates
* computation from the cache's {@code Map} view.
*
* <p>If an entry's value has not finished computing yet, query methods besides {@code get} return
* immediately as if an entry doesn't exist. In other words, an entry isn't externally visible
* until the value's computation completes.
*
* <p>{@link Map#get} on the returned map will never return {@code null}. It may throw:
*
* <ul>
* <li>{@link NullPointerException} if the key is null or the computing function returns a null
* result
* <li>{@link ComputationException} if an exception was thrown by the computing function. If that
* exception is already of type {@link ComputationException} it is propagated directly; otherwise
* it is wrapped.
* </ul>
*
* <p><b>Note:</b> Callers of {@code get} <i>must</i> ensure that the key argument is of type
* {@code K}. The {@code get} method accepts {@code Object}, so the key type is not checked at
* compile time. Passing an object of a type other than {@code K} can result in that object being
* unsafely passed to the computing function as type {@code K}, and unsafely stored in the map.
*
* <p>If {@link Map#put} is called before a computation completes, other threads waiting on the
* computation will wake up and return the stored value.
*
* <p>This method does not alter the state of this {@code MapMaker} instance, so it can be invoked
* again to create multiple independent maps.
*
* <p>Insertion, removal, update, and access operations on the returned map safely execute
* concurrently by multiple threads. Iterators on the returned map are weakly consistent,
* returning elements reflecting the state of the map at some point at or since the creation of
* the iterator. They do not throw {@link ConcurrentModificationException}, and may proceed
* concurrently with other operations.
*
* <p>The bulk operations {@code putAll}, {@code equals}, and {@code clear} are not guaranteed to
* be performed atomically on the returned map. Additionally, {@code size} and {@code
* containsValue} are implemented as bulk read operations, and thus may fail to observe concurrent
* writes.
*
* @param computingFunction the function used to compute new values
* @return a serializable concurrent map having the requested features
* @deprecated Caching functionality in {@code MapMaker} has been moved to
* {@link com.google.common.cache.CacheBuilder}, with {@link #makeComputingMap} being replaced
* by {@link com.google.common.cache.CacheBuilder#build}. See the
* <a href="http://code.google.com/p/guava-libraries/wiki/MapMakerMigration">MapMaker
* Migration Guide</a> for more details.
*/
@Deprecated
@Override
<K, V> ConcurrentMap<K, V> makeComputingMap(
Function<? super K, ? extends V> computingFunction) {
return (nullRemovalCause == null)
? new MapMaker.ComputingMapAdapter<K, V>(this, computingFunction)
: new NullComputingConcurrentMap<K, V>(this, computingFunction);
}
/**
* Returns a string representation for this MapMaker instance. The exact form of the returned
* string is not specificed.
*/
@Override
public String toString() {
Objects.ToStringHelper s = Objects.toStringHelper(this);
if (initialCapacity != UNSET_INT) {
s.add("initialCapacity", initialCapacity);
}
if (concurrencyLevel != UNSET_INT) {
s.add("concurrencyLevel", concurrencyLevel);
}
if (maximumSize != UNSET_INT) {
s.add("maximumSize", maximumSize);
}
if (expireAfterWriteNanos != UNSET_INT) {
s.add("expireAfterWrite", expireAfterWriteNanos + "ns");
}
if (expireAfterAccessNanos != UNSET_INT) {
s.add("expireAfterAccess", expireAfterAccessNanos + "ns");
}
if (keyStrength != null) {
s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString()));
}
if (valueStrength != null) {
s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString()));
}
if (keyEquivalence != null) {
s.addValue("keyEquivalence");
}
if (removalListener != null) {
s.addValue("removalListener");
}
return s.toString();
}
/**
* An object that can receive a notification when an entry is removed from a map. The removal
* resulting in notification could have occured to an entry being manually removed or replaced, or
* due to eviction resulting from timed expiration, exceeding a maximum size, or garbage
* collection.
*
* <p>An instance may be called concurrently by multiple threads to process different entries.
* Implementations of this interface should avoid performing blocking calls or synchronizing on
* shared resources.
*
* @param <K> the most general type of keys this listener can listen for; for
* example {@code Object} if any key is acceptable
* @param <V> the most general type of values this listener can listen for; for
* example {@code Object} if any key is acceptable
*/
interface RemovalListener<K, V> {
/**
* Notifies the listener that a removal occurred at some point in the past.
*/
void onRemoval(RemovalNotification<K, V> notification);
}
/**
* A notification of the removal of a single entry. The key or value may be null if it was already
* garbage collected.
*
* <p>Like other {@code Map.Entry} instances associated with MapMaker, this class holds strong
* references to the key and value, regardless of the type of references the map may be using.
*/
static final class RemovalNotification<K, V> extends ImmutableEntry<K, V> {
private static final long serialVersionUID = 0;
private final RemovalCause cause;
RemovalNotification(@Nullable K key, @Nullable V value, RemovalCause cause) {
super(key, value);
this.cause = cause;
}
/**
* Returns the cause for which the entry was removed.
*/
public RemovalCause getCause() {
return cause;
}
/**
* Returns {@code true} if there was an automatic removal due to eviction (the cause is neither
* {@link RemovalCause#EXPLICIT} nor {@link RemovalCause#REPLACED}).
*/
public boolean wasEvicted() {
return cause.wasEvicted();
}
}
/**
* The reason why an entry was removed.
*/
enum RemovalCause {
/**
* The entry was manually removed by the user. This can result from the user invoking
* {@link Map#remove}, {@link ConcurrentMap#remove}, or {@link java.util.Iterator#remove}.
*/
EXPLICIT {
@Override
boolean wasEvicted() {
return false;
}
},
/**
* The entry itself was not actually removed, but its value was replaced by the user. This can
* result from the user invoking {@link Map#put}, {@link Map#putAll},
* {@link ConcurrentMap#replace(Object, Object)}, or
* {@link ConcurrentMap#replace(Object, Object, Object)}.
*/
REPLACED {
@Override
boolean wasEvicted() {
return false;
}
},
/**
* The entry was removed automatically because its key or value was garbage-collected. This can
* occur when using {@link #softValues}, {@link #weakKeys}, or {@link #weakValues}.
*/
COLLECTED {
@Override
boolean wasEvicted() {
return true;
}
},
/**
* The entry's expiration timestamp has passed. This can occur when using {@link
* #expireAfterWrite} or {@link #expireAfterAccess}.
*/
EXPIRED {
@Override
boolean wasEvicted() {
return true;
}
},
/**
* The entry was evicted due to size constraints. This can occur when using {@link
* #maximumSize}.
*/
SIZE {
@Override
boolean wasEvicted() {
return true;
}
};
/**
* Returns {@code true} if there was an automatic removal due to eviction (the cause is neither
* {@link #EXPLICIT} nor {@link #REPLACED}).
*/
abstract boolean wasEvicted();
}
/** A map that is always empty and evicts on insertion. */
static class NullConcurrentMap<K, V> extends AbstractMap<K, V>
implements ConcurrentMap<K, V>, Serializable {
private static final long serialVersionUID = 0;
private final RemovalListener<K, V> removalListener;
private final RemovalCause removalCause;
NullConcurrentMap(MapMaker mapMaker) {
removalListener = mapMaker.getRemovalListener();
removalCause = mapMaker.nullRemovalCause;
}
// implements ConcurrentMap
@Override
public boolean containsKey(@Nullable Object key) {
return false;
}
@Override
public boolean containsValue(@Nullable Object value) {
return false;
}
@Override
public V get(@Nullable Object key) {
return null;
}
void notifyRemoval(K key, V value) {
RemovalNotification<K, V> notification =
new RemovalNotification<K, V>(key, value, removalCause);
removalListener.onRemoval(notification);
}
@Override
public V put(K key, V value) {
checkNotNull(key);
checkNotNull(value);
notifyRemoval(key, value);
return null;
}
@Override
public V putIfAbsent(K key, V value) {
return put(key, value);
}
@Override
public V remove(@Nullable Object key) {
return null;
}
@Override
public boolean remove(@Nullable Object key, @Nullable Object value) {
return false;
}
@Override
public V replace(K key, V value) {
checkNotNull(key);
checkNotNull(value);
return null;
}
@Override
public boolean replace(K key, @Nullable V oldValue, V newValue) {
checkNotNull(key);
checkNotNull(newValue);
return false;
}
@Override
public Set<Entry<K, V>> entrySet() {
return Collections.emptySet();
}
}
/** Computes on retrieval and evicts the result. */
static final class NullComputingConcurrentMap<K, V> extends NullConcurrentMap<K, V> {
private static final long serialVersionUID = 0;
final Function<? super K, ? extends V> computingFunction;
NullComputingConcurrentMap(
MapMaker mapMaker, Function<? super K, ? extends V> computingFunction) {
super(mapMaker);
this.computingFunction = checkNotNull(computingFunction);
}
@SuppressWarnings("unchecked") // unsafe, which is why Cache is preferred
@Override
public V get(Object k) {
K key = (K) k;
V value = compute(key);
checkNotNull(value, computingFunction + " returned null for key " + key + ".");
notifyRemoval(key, value);
return value;
}
private V compute(K key) {
checkNotNull(key);
try {
return computingFunction.apply(key);
} catch (ComputationException e) {
throw e;
} catch (Throwable t) {
throw new ComputationException(t);
}
}
}
/**
* Overrides get() to compute on demand. Also throws an exception when {@code null} is returned
* from a computation.
*/
/*
* This might make more sense in ComputingConcurrentHashMap, but it causes a javac crash in some
* cases there: http://code.google.com/p/guava-libraries/issues/detail?id=950
*/
static final class ComputingMapAdapter<K, V>
extends ComputingConcurrentHashMap<K, V> implements Serializable {
private static final long serialVersionUID = 0;
ComputingMapAdapter(MapMaker mapMaker,
Function<? super K, ? extends V> computingFunction) {
super(mapMaker, computingFunction);
}
@SuppressWarnings("unchecked") // unsafe, which is one advantage of Cache over Map
@Override
public V get(Object key) {
V value;
try {
value = getOrCompute((K) key);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
Throwables.propagateIfInstanceOf(cause, ComputationException.class);
throw new ComputationException(cause);
}
if (value == null) {
throw new NullPointerException(computingFunction + " returned null for key " + key + ".");
}
return value;
}
}
}
| 18 months from Guava 15 will be September, not August.
We'll see if we end up needing to bump it to October because *somebody* doesn't get his Escapers work done in time for a March release ;)
-------------
Created by MOE: http://code.google.com/p/moe-java
MOE_MIGRATED_REVID=43398394
| guava/src/com/google/common/collect/MapMaker.java | 18 months from Guava 15 will be September, not August. We'll see if we end up needing to bump it to October because *somebody* doesn't get his Escapers work done in time for a March release ;) ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=43398394 | <ide><path>uava/src/com/google/common/collect/MapMaker.java
<ide> * com.google.common.cache.CacheBuilder}, with {@link #softValues} being replaced by {@link
<ide> * com.google.common.cache.CacheBuilder#softValues}. Note that {@code CacheBuilder} is simply
<ide> * an enhanced API for an implementation which was branched from {@code MapMaker}. <b>This
<del> * method is scheduled for deletion in August 2014.</b>
<add> * method is scheduled for deletion in September 2014.</b>
<ide> */
<ide> @Deprecated
<ide> @GwtIncompatible("java.lang.ref.SoftReference") |
|
Java | apache-2.0 | 2bf15cfe94cc65a2de3512390b0f6c69926e6cb2 | 0 | DarkPhoenixs/message-queue-client-framework | package org.darkphoenixs.kafka.core;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import kafka.admin.TopicCommand;
import kafka.server.KafkaConfig;
import kafka.server.KafkaServer;
import kafka.utils.MockTime;
import kafka.utils.TestUtils;
import kafka.utils.Time;
import kafka.utils.ZkUtils;
import kafka.zk.EmbeddedZookeeper;
import org.I0Itec.zkclient.ZkClient;
import org.apache.kafka.common.protocol.SecurityProtocol;
import org.apache.kafka.common.security.JaasUtils;
import org.darkphoenixs.kafka.pool.KafkaMessageReceiverPool;
import org.darkphoenixs.kafka.pool.KafkaMessageSenderPool;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import scala.Option;
public class KafkaMessageReceiverImplTest {
private int brokerId = 0;
private String topic = "QUEUE.TEST";
private String zkConnect;
private EmbeddedZookeeper zkServer;
private ZkClient zkClient;
private KafkaServer kafkaServer;
private int port = 9999;
private Properties kafkaProps;
@Before
public void before() {
zkServer = new EmbeddedZookeeper();
zkConnect = String.format("localhost:%d", zkServer.port());
ZkUtils zkUtils = ZkUtils.apply(zkConnect, 30000, 30000,
JaasUtils.isZkSecurityEnabled());
zkClient = zkUtils.zkClient();
final Option<java.io.File> noFile = scala.Option.apply(null);
final Option<SecurityProtocol> noInterBrokerSecurityProtocol = scala.Option
.apply(null);
kafkaProps = TestUtils.createBrokerConfig(brokerId, zkConnect, false,
false, port, noInterBrokerSecurityProtocol, noFile, true,
false, TestUtils.RandomPort(), false, TestUtils.RandomPort(),
false, TestUtils.RandomPort());
kafkaProps.setProperty("auto.create.topics.enable", "true");
kafkaProps.setProperty("num.partitions", "1");
// We *must* override this to use the port we allocated (Kafka currently
// allocates one port
// that it always uses for ZK
kafkaProps.setProperty("zookeeper.connect", this.zkConnect);
kafkaProps.setProperty("host.name", "localhost");
kafkaProps.setProperty("port", port + "");
Properties kafkaProps2 = TestUtils.createBrokerConfig(brokerId + 1,
zkConnect, false, false, (port - 1),
noInterBrokerSecurityProtocol, noFile, true, false,
TestUtils.RandomPort(), false, TestUtils.RandomPort(), false,
TestUtils.RandomPort());
kafkaProps2.setProperty("auto.create.topics.enable", "true");
kafkaProps2.setProperty("num.partitions", "1");
// We *must* override this to use the port we allocated (Kafka currently
// allocates one port
// that it always uses for ZK
kafkaProps2.setProperty("zookeeper.connect", this.zkConnect);
kafkaProps2.setProperty("host.name", "localhost");
kafkaProps2.setProperty("port", (port - 1) + "");
KafkaConfig config = new KafkaConfig(kafkaProps);
KafkaConfig config2 = new KafkaConfig(kafkaProps2);
Time mock = new MockTime();
Time mock2 = new MockTime();
kafkaServer = TestUtils.createServer(config, mock);
KafkaServer kafkaServer2 = TestUtils.createServer(config2, mock2);
// create topic
TopicCommand.TopicCommandOptions options = new TopicCommand.TopicCommandOptions(
new String[] { "--create", "--topic", topic,
"--replication-factor", "2", "--partitions", "2" });
TopicCommand.createTopic(zkUtils, options);
List<KafkaServer> servers = new ArrayList<KafkaServer>();
servers.add(kafkaServer);
servers.add(kafkaServer2);
TestUtils.waitUntilMetadataIsPropagated(
scala.collection.JavaConversions.asScalaBuffer(servers), topic,
0, 5000);
}
@After
public void after() {
kafkaServer.shutdown();
zkClient.close();
zkServer.shutdown();
}
@Test
public void test() throws Exception {
KafkaMessageSenderPool<byte[], byte[]> sendPool = new KafkaMessageSenderPool<byte[], byte[]>();
sendPool.setProps(TestUtils.getProducerConfig("localhost:" + port
+ ",localhost:" + (port - 1)));
sendPool.init();
Properties properties = TestUtils.getProducerConfig("localhost:" + port
+ ",localhost:" + (port - 1));
KafkaMessageSenderImpl<byte[], byte[]> sender = new KafkaMessageSenderImpl<byte[], byte[]>(
properties, sendPool);
Assert.assertEquals(sendPool, sender.getPool());
sender.setPool(sendPool);
Assert.assertNotNull(sender.getProducer());
sender.setProducer(sender.getProducer());
sender.send(topic, "test".getBytes());
sender.sendWithKey(topic, "key".getBytes(), "value".getBytes());
sender.close();
sender.shutDown();
sendPool.destroy();
Properties consumerProps = TestUtils.createConsumerProperties(
zkConnect, "group_1", "consumer_1", 1000);
KafkaMessageReceiverPool<byte[], byte[]> recePool = new KafkaMessageReceiverPool<byte[], byte[]>();
recePool.setProps(consumerProps);
recePool.setPoolSize(10);
recePool.setClientId("test1");
KafkaMessageReceiverImpl<byte[], byte[]> receiver = new KafkaMessageReceiverImpl<byte[], byte[]>(
consumerProps, recePool);
Assert.assertNotNull(receiver.getProps());
receiver.setProps(receiver.getProps());
Assert.assertNotNull(receiver.getPool());
receiver.setPool(receiver.getPool());
Assert.assertNull(receiver.getConsumer());
receiver.setConsumer(receiver.getConsumer());
receiver.getEarliestOffset(topic, -1);
receiver.getLatestOffset(topic, -1);
receiver.getEarliestOffset(topic, 0);
receiver.getLatestOffset(topic, 0);
receiver.receive(topic, 0, 0, 1);
receiver.receive(topic, 0, 0, 2);
receiver.receive(topic, 0, 1, 2);
receiver.receive(topic, 1, 0, 2);
receiver.receiveWithKey(topic, 0, 1, 1);
receiver.receiveWithKey(topic, 0, 1, 2);
receiver.receiveWithKey(topic, 0, 2, 2);
receiver.receiveWithKey(topic, 1, 1, 2);
receiver.close();
try {
receiver.getEarliestOffset("test", 0);
} catch (Exception e) {
}
try {
receiver.getLatestOffset("test", 0);
} catch (Exception e) {
}
try {
receiver.getEarliestOffset(topic, 2);
} catch (Exception e) {
}
try {
receiver.getLatestOffset(topic, 2);
} catch (Exception e) {
}
try {
receiver.receive(topic, 2, 0, 1);
} catch (Exception e) {
}
try {
receiver.receive("test", 0, 0, 1);
} catch (Exception e) {
}
try {
receiver.receiveWithKey(topic, 2, 1, 1);
} catch (Exception e) {
}
try {
receiver.receiveWithKey("test", 0, 1, 1);
} catch (Exception e) {
}
receiver.close();
KafkaMessageReceiver.logger.info("test");
}
}
| src/test/java/org/darkphoenixs/kafka/core/KafkaMessageReceiverImplTest.java | package org.darkphoenixs.kafka.core;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import kafka.admin.TopicCommand;
import kafka.server.KafkaConfig;
import kafka.server.KafkaServer;
import kafka.utils.MockTime;
import kafka.utils.TestUtils;
import kafka.utils.Time;
import kafka.utils.ZkUtils;
import kafka.zk.EmbeddedZookeeper;
import org.I0Itec.zkclient.ZkClient;
import org.apache.kafka.common.protocol.SecurityProtocol;
import org.apache.kafka.common.security.JaasUtils;
import org.darkphoenixs.kafka.pool.KafkaMessageReceiverPool;
import org.darkphoenixs.kafka.pool.KafkaMessageSenderPool;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import scala.Option;
public class KafkaMessageReceiverImplTest {
private int brokerId = 0;
private String topic = "QUEUE.TEST";
private String zkConnect;
private EmbeddedZookeeper zkServer;
private ZkClient zkClient;
private KafkaServer kafkaServer;
private int port = 9999;
private Properties kafkaProps;
@Before
public void before() {
zkServer = new EmbeddedZookeeper();
zkConnect = String.format("localhost:%d", zkServer.port());
ZkUtils zkUtils = ZkUtils.apply(zkConnect, 30000, 30000,
JaasUtils.isZkSecurityEnabled());
zkClient = zkUtils.zkClient();
final Option<java.io.File> noFile = scala.Option.apply(null);
final Option<SecurityProtocol> noInterBrokerSecurityProtocol = scala.Option
.apply(null);
kafkaProps = TestUtils.createBrokerConfig(brokerId, zkConnect, false,
false, port, noInterBrokerSecurityProtocol, noFile, true,
false, TestUtils.RandomPort(), false, TestUtils.RandomPort(),
false, TestUtils.RandomPort());
kafkaProps.setProperty("auto.create.topics.enable", "true");
kafkaProps.setProperty("num.partitions", "1");
// We *must* override this to use the port we allocated (Kafka currently
// allocates one port
// that it always uses for ZK
kafkaProps.setProperty("zookeeper.connect", this.zkConnect);
kafkaProps.setProperty("host.name", "localhost");
kafkaProps.setProperty("port", port + "");
Properties kafkaProps2 = TestUtils.createBrokerConfig(brokerId + 1,
zkConnect, false, false, (port - 1),
noInterBrokerSecurityProtocol, noFile, true, false,
TestUtils.RandomPort(), false, TestUtils.RandomPort(), false,
TestUtils.RandomPort());
kafkaProps2.setProperty("auto.create.topics.enable", "true");
kafkaProps2.setProperty("num.partitions", "1");
// We *must* override this to use the port we allocated (Kafka currently
// allocates one port
// that it always uses for ZK
kafkaProps2.setProperty("zookeeper.connect", this.zkConnect);
kafkaProps2.setProperty("host.name", "localhost");
kafkaProps2.setProperty("port", (port - 1) + "");
KafkaConfig config = new KafkaConfig(kafkaProps);
KafkaConfig config2 = new KafkaConfig(kafkaProps2);
Time mock = new MockTime();
Time mock2 = new MockTime();
kafkaServer = TestUtils.createServer(config, mock);
KafkaServer kafkaServer2 = TestUtils.createServer(config2, mock2);
// create topic
TopicCommand.TopicCommandOptions options = new TopicCommand.TopicCommandOptions(
new String[] { "--create", "--topic", topic,
"--replication-factor", "2", "--partitions", "2" });
TopicCommand.createTopic(zkUtils, options);
List<KafkaServer> servers = new ArrayList<KafkaServer>();
servers.add(kafkaServer);
servers.add(kafkaServer2);
TestUtils.waitUntilMetadataIsPropagated(
scala.collection.JavaConversions.asScalaBuffer(servers), topic,
0, 5000);
}
@After
public void after() {
kafkaServer.shutdown();
zkClient.close();
zkServer.shutdown();
}
@Test
public void test() throws Exception {
KafkaMessageSenderPool<byte[], byte[]> sendPool = new KafkaMessageSenderPool<byte[], byte[]>();
sendPool.setProps(TestUtils.getProducerConfig("localhost:" + port));
sendPool.init();
Properties properties = TestUtils
.getProducerConfig("localhost:" + port);
KafkaMessageSenderImpl<byte[], byte[]> sender = new KafkaMessageSenderImpl<byte[], byte[]>(
properties, sendPool);
Assert.assertEquals(sendPool, sender.getPool());
sender.setPool(sendPool);
Assert.assertNotNull(sender.getProducer());
sender.setProducer(sender.getProducer());
sender.send(topic, "test".getBytes());
sender.sendWithKey(topic, "key".getBytes(), "value".getBytes());
sender.close();
sender.shutDown();
sendPool.destroy();
Properties consumerProps = TestUtils.createConsumerProperties(
zkConnect, "group_1", "consumer_1", 1000);
KafkaMessageReceiverPool<byte[], byte[]> recePool = new KafkaMessageReceiverPool<byte[], byte[]>();
recePool.setProps(consumerProps);
recePool.setPoolSize(10);
recePool.setClientId("test1");
KafkaMessageReceiverImpl<byte[], byte[]> receiver = new KafkaMessageReceiverImpl<byte[], byte[]>(
consumerProps, recePool);
Assert.assertNotNull(receiver.getProps());
receiver.setProps(receiver.getProps());
Assert.assertNotNull(receiver.getPool());
receiver.setPool(receiver.getPool());
Assert.assertNull(receiver.getConsumer());
receiver.setConsumer(receiver.getConsumer());
receiver.getEarliestOffset(topic, -1);
receiver.getLatestOffset(topic, -1);
receiver.getEarliestOffset(topic, 0);
receiver.getLatestOffset(topic, 0);
receiver.receive(topic, 0, 0, 1);
receiver.receive(topic, 0, 0, 2);
receiver.receive(topic, 0, 1, 2);
receiver.receive(topic, 1, 0, 2);
receiver.receiveWithKey(topic, 0, 1, 1);
receiver.receiveWithKey(topic, 0, 1, 2);
receiver.receiveWithKey(topic, 0, 2, 2);
receiver.receiveWithKey(topic, 1, 1, 2);
receiver.close();
try {
receiver.getEarliestOffset("test", 0);
} catch (Exception e) {
}
try {
receiver.getLatestOffset("test", 0);
} catch (Exception e) {
}
try {
receiver.getEarliestOffset(topic, 2);
} catch (Exception e) {
}
try {
receiver.getLatestOffset(topic, 2);
} catch (Exception e) {
}
try {
receiver.receive(topic, 2, 0, 1);
} catch (Exception e) {
}
try {
receiver.receive("test", 0, 0, 1);
} catch (Exception e) {
}
try {
receiver.receiveWithKey(topic, 2, 1, 1);
} catch (Exception e) {
}
try {
receiver.receiveWithKey("test", 0, 1, 1);
} catch (Exception e) {
}
receiver.close();
KafkaMessageReceiver.logger.info("test");
}
}
| fix testcase. | src/test/java/org/darkphoenixs/kafka/core/KafkaMessageReceiverImplTest.java | fix testcase. | <ide><path>rc/test/java/org/darkphoenixs/kafka/core/KafkaMessageReceiverImplTest.java
<ide>
<ide> KafkaMessageSenderPool<byte[], byte[]> sendPool = new KafkaMessageSenderPool<byte[], byte[]>();
<ide>
<del> sendPool.setProps(TestUtils.getProducerConfig("localhost:" + port));
<add> sendPool.setProps(TestUtils.getProducerConfig("localhost:" + port
<add> + ",localhost:" + (port - 1)));
<ide>
<ide> sendPool.init();
<ide>
<del> Properties properties = TestUtils
<del> .getProducerConfig("localhost:" + port);
<add> Properties properties = TestUtils.getProducerConfig("localhost:" + port
<add> + ",localhost:" + (port - 1));
<ide>
<ide> KafkaMessageSenderImpl<byte[], byte[]> sender = new KafkaMessageSenderImpl<byte[], byte[]>(
<ide> properties, sendPool);
<ide> receiver.receiveWithKey(topic, 0, 2, 2);
<ide>
<ide> receiver.receiveWithKey(topic, 1, 1, 2);
<del>
<add>
<ide> receiver.close();
<ide>
<ide> try { |
|
Java | lgpl-2.1 | 596869f04b2a03c7dd1c0e497c8bb61cb2d0904a | 0 | hendriks73/jipes | /*
* =================================================
* Copyright 2010 tagtraum industries incorporated
* All rights reserved.
* =================================================
*/
package com.tagtraum.jipes.audio;
import com.tagtraum.jipes.SignalSource;
import org.junit.Test;
import javax.sound.sampled.AudioFormat;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/**
* TestMono.
*
* @author <a href="mailto:[email protected]">Hendrik Schreiber</a>
*/
public class TestMono {
private SignalSource<AudioBuffer> monoSource = new SignalSource<AudioBuffer>() {
public void reset() {
}
public AudioBuffer read() throws IOException {
return new RealAudioBuffer(
0, new float[]{
10, 10, 10, 10, 10,
10, 10, 10, 10, 10,
}, new AudioFormat(10000, 8, 1, true, true)
);
}
};
private SignalSource<AudioBuffer> stereoSource = new SignalSource<AudioBuffer>() {
public void reset() {
}
public AudioBuffer read() throws IOException {
return new RealAudioBuffer(
0, new float[]{
10, 20, 10, 20,
10, 20, 10, 20
}, new AudioFormat(10000, 8, 2, true, true)
);
}
};
@Test
public void testMonoGenerator() throws IOException {
final Mono mono = new Mono();
mono.connectTo(monoSource);
assertEquals(1, mono.read().getAudioFormat().getChannels());
final float[] floats = mono.read().getData();
final float[] bytes = monoSource.read().getData();
for (int i = 0; i < floats.length; i++) {
assertEquals(bytes[i], floats[i], 0.01);
}
}
@Test
public void testStereoGenerator() throws IOException {
final Mono mono = new Mono();
mono.connectTo(stereoSource);
assertEquals(1, mono.read().getAudioFormat().getChannels());
final float[] floats = mono.read().getData();
final float[] bytes = stereoSource.read().getData();
assertEquals(bytes.length, floats.length * 2);
for (final float f : floats) {
assertEquals(15.0, f, 0.00001);
}
}
@Test
public void testNullGenerator() throws IOException {
final Mono processor = new Mono();
processor.connectTo(new NullAudioBufferSource());
assertNull(processor.read());
}
}
| src/test/java/com/tagtraum/jipes/audio/TestMono.java | /*
* =================================================
* Copyright 2010 tagtraum industries incorporated
* All rights reserved.
* =================================================
*/
package com.tagtraum.jipes.audio;
import com.tagtraum.jipes.SignalSource;
import junit.framework.TestCase;
import javax.sound.sampled.AudioFormat;
import java.io.IOException;
/**
* TestMono.
* <p/>
* Date: Jul 23, 2010
* Time: 9:58:37 AM
*
* @author <a href="mailto:[email protected]">Hendrik Schreiber</a>
*/
public class TestMono extends TestCase {
private SignalSource<AudioBuffer> monoSource = new SignalSource<AudioBuffer>() {
public void reset() {
}
public AudioBuffer read() throws IOException {
return new RealAudioBuffer(
0, new float[]{
10, 10, 10, 10, 10,
10, 10, 10, 10, 10,
}, new AudioFormat(10000, 8, 1, true, true)
);
}
};
private SignalSource<AudioBuffer> stereoSource = new SignalSource<AudioBuffer>() {
public void reset() {
}
public AudioBuffer read() throws IOException {
return new RealAudioBuffer(
0, new float[]{
10, 20, 10, 20,
10, 20, 10, 20
}, new AudioFormat(10000, 8, 2, true, true)
);
}
};
public void testMonoGenerator() throws IOException {
final Mono mono = new Mono();
mono.connectTo(monoSource);
assertEquals(1, mono.read().getAudioFormat().getChannels());
final float[] floats = mono.read().getData();
final float[] bytes = monoSource.read().getData();
for (int i = 0; i < floats.length; i++) {
assertEquals(bytes[i], floats[i], 0.01);
}
}
public void testStereoGenerator() throws IOException {
final Mono mono = new Mono();
mono.connectTo(stereoSource);
assertEquals(1, mono.read().getAudioFormat().getChannels());
final float[] floats = mono.read().getData();
final float[] bytes = stereoSource.read().getData();
assertEquals(bytes.length, floats.length * 2);
for (final float f : floats) {
assertEquals(15.0, f, 0.00001);
}
}
public void testNullGenerator() throws IOException {
final Mono processor = new Mono();
processor.connectTo(new NullAudioBufferSource());
assertNull(processor.read());
}
}
| Migrated to @Test annotations.
| src/test/java/com/tagtraum/jipes/audio/TestMono.java | Migrated to @Test annotations. | <ide><path>rc/test/java/com/tagtraum/jipes/audio/TestMono.java
<ide> package com.tagtraum.jipes.audio;
<ide>
<ide> import com.tagtraum.jipes.SignalSource;
<del>import junit.framework.TestCase;
<add>import org.junit.Test;
<ide>
<ide> import javax.sound.sampled.AudioFormat;
<ide> import java.io.IOException;
<ide>
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertNull;
<add>
<ide> /**
<ide> * TestMono.
<del> * <p/>
<del> * Date: Jul 23, 2010
<del> * Time: 9:58:37 AM
<ide> *
<ide> * @author <a href="mailto:[email protected]">Hendrik Schreiber</a>
<ide> */
<del>public class TestMono extends TestCase {
<add>public class TestMono {
<ide>
<ide> private SignalSource<AudioBuffer> monoSource = new SignalSource<AudioBuffer>() {
<ide>
<ide> };
<ide>
<ide>
<add> @Test
<ide> public void testMonoGenerator() throws IOException {
<ide> final Mono mono = new Mono();
<ide> mono.connectTo(monoSource);
<ide> }
<ide> }
<ide>
<add> @Test
<ide> public void testStereoGenerator() throws IOException {
<ide> final Mono mono = new Mono();
<ide> mono.connectTo(stereoSource);
<ide> }
<ide> }
<ide>
<add> @Test
<ide> public void testNullGenerator() throws IOException {
<ide> final Mono processor = new Mono();
<ide> processor.connectTo(new NullAudioBufferSource()); |
|
Java | apache-2.0 | 41c80330f3a66d22ffc06f89e2e74297f0c079c6 | 0 | Sanne/JGroups,Sanne/JGroups,tristantarrant/JGroups,slaskawi/JGroups,belaban/JGroups,ibrahimshbat/JGroups,TarantulaTechnology/JGroups,danberindei/JGroups,dimbleby/JGroups,tristantarrant/JGroups,vjuranek/JGroups,rhusar/JGroups,belaban/JGroups,danberindei/JGroups,kedzie/JGroups,ibrahimshbat/JGroups,kedzie/JGroups,pruivo/JGroups,deepnarsay/JGroups,pferraro/JGroups,TarantulaTechnology/JGroups,rhusar/JGroups,slaskawi/JGroups,dimbleby/JGroups,deepnarsay/JGroups,pferraro/JGroups,Sanne/JGroups,slaskawi/JGroups,ligzy/JGroups,dimbleby/JGroups,rpelisse/JGroups,ligzy/JGroups,rpelisse/JGroups,rhusar/JGroups,rvansa/JGroups,TarantulaTechnology/JGroups,pruivo/JGroups,pferraro/JGroups,ibrahimshbat/JGroups,rvansa/JGroups,pruivo/JGroups,ibrahimshbat/JGroups,vjuranek/JGroups,ligzy/JGroups,danberindei/JGroups,rpelisse/JGroups,belaban/JGroups,vjuranek/JGroups,kedzie/JGroups,deepnarsay/JGroups | package org.jgroups.blocks;
import org.jgroups.Global;
import org.jgroups.JChannel;
import org.jgroups.View;
import org.jgroups.Address;
import org.jgroups.tests.ChannelTestBase;
import org.jgroups.util.*;
import org.testng.annotations.*;
import java.util.List;
import java.util.Arrays;
/**
* @author Bela Ban
* @version $Id: RpcDispatcherUnitTest.java,v 1.2 2010/04/21 10:51:41 belaban Exp $
*/
@Test(groups=Global.STACK_DEPENDENT,sequential=true)
public class RpcDispatcherUnitTest extends ChannelTestBase {
private RpcDispatcher d1, d2, d3;
private JChannel c1, c2, c3;
private ServerObject o1, o2, o3;
private Address a1, a2, a3;
private List<Address> members;
@BeforeClass
protected void setUp() throws Exception {
o1=new ServerObject();
o2=new ServerObject();
o3=new ServerObject();
c1=createChannel(true, 3);
c1.setName("A");
final String GROUP="RpcDispatcherUnitTest";
d1=new RpcDispatcher(c1, null, null, o1);
c1.connect(GROUP);
c2=createChannel(c1);
c2.setName("B");
d2=new RpcDispatcher(c2, null, null, o2);
c2.connect(GROUP);
c3=createChannel(c1);
c3.setName("C");
d3=new RpcDispatcher(c3, null, null, o3);
c3.connect(GROUP);
System.out.println("c1.view=" + c1.getView() + "\nc2.view=" + c2.getView() + "\nc3.view=" + c3.getView());
View view=c3.getView();
assert view.size() == 3 : "view=" + view;
a1=c1.getAddress();
a2=c2.getAddress();
a3=c3.getAddress();
members=Arrays.asList(a1, a2, a3);
}
@BeforeMethod
protected void reset() {
o1.reset();
o2.reset();
o3.reset();
}
@AfterClass
protected void tearDown() throws Exception {
d3.stop();
d2.stop();
d1.stop();
Util.close(c3, c2, c1);
}
public void testInvocationOnEntireGroup() {
RspList rsps=d1.callRemoteMethods(null, "foo", null, null, RequestOptions.SYNC);
System.out.println("rsps:\n" + rsps);
assert rsps.size() == 3;
assert o1.wasCalled() && o2.wasCalled() && o3.wasCalled();
}
public void testInvocationOnEntireGroupWithTargetList() {
RspList rsps=d1.callRemoteMethods(members, "foo", null, null, RequestOptions.SYNC);
System.out.println("rsps:\n" + rsps);
assert rsps.size() == 3;
assert o1.wasCalled() && o2.wasCalled() && o3.wasCalled();
}
/** Invoke a method on all but myself */
public void testInvocationWithExclusionOfSelf() {
RequestOptions options=new RequestOptions(Request.GET_ALL, 5000).setExclusionList(a1);
RspList rsps=d1.callRemoteMethods(null, "foo", null, null, options);
Util.sleep(500);
System.out.println("rsps:\n" + rsps);
assert rsps.size() == 2;
assert rsps.containsKey(a2) && rsps.containsKey(a3);
assert !o1.wasCalled() && o2.wasCalled() && o3.wasCalled();
}
public void testInvocationWithExclusionOfTwo() {
RequestOptions options=new RequestOptions(Request.GET_ALL, 5000).setExclusionList(a2, a3);
RspList rsps=d1.callRemoteMethods(null, "foo", null, null, options);
Util.sleep(500);
System.out.println("rsps:\n" + rsps);
assert rsps.size() == 1;
assert rsps.containsKey(a1);
assert o1.wasCalled() && !o2.wasCalled() && !o3.wasCalled();
}
public void testInvocationOnEmptyTargetSet() {
RequestOptions options=new RequestOptions(Request.GET_ALL, 5000).setExclusionList(a1, a2, a3);
RspList rsps=d1.callRemoteMethods(null, "foo", null, null, options);
Util.sleep(500);
System.out.println("rsps:\n" + rsps);
assert rsps.isEmpty();
assert !o1.wasCalled() && !o2.wasCalled() && !o3.wasCalled();
}
private static class ServerObject {
boolean called=false;
public boolean wasCalled() {
return called;
}
public void reset() {
called=false;
}
public boolean foo() {
called=true;
return called;
}
}
} | tests/junit/org/jgroups/blocks/RpcDispatcherUnitTest.java | package org.jgroups.blocks;
import org.jgroups.Global;
import org.jgroups.JChannel;
import org.jgroups.View;
import org.jgroups.Address;
import org.jgroups.tests.ChannelTestBase;
import org.jgroups.util.*;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.List;
import java.util.Arrays;
/**
* @author Bela Ban
* @version $Id: RpcDispatcherUnitTest.java,v 1.1 2010/04/21 07:52:00 belaban Exp $
*/
@Test(groups=Global.STACK_DEPENDENT,sequential=true)
public class RpcDispatcherUnitTest extends ChannelTestBase {
private RpcDispatcher d1, d2, d3;
private JChannel c1, c2, c3;
private ServerObject o1, o2, o3;
private List<Address> members;
@BeforeMethod
protected void setUp() throws Exception {
o1=new ServerObject();
o2=new ServerObject();
o3=new ServerObject();
c1=createChannel(true, 3);
c1.setName("A");
final String GROUP="RpcDispatcherUnitTest";
d1=new RpcDispatcher(c1, null, null, o1);
c1.connect(GROUP);
c2=createChannel(c1);
c2.setName("B");
d2=new RpcDispatcher(c2, null, null, o2);
c2.connect(GROUP);
c3=createChannel(c1);
c3.setName("C");
d3=new RpcDispatcher(c3, null, null, o3);
c3.connect(GROUP);
System.out.println("c1.view=" + c1.getView() + "\nc2.view=" + c2.getView() + "\nc3.view=" + c3.getView());
View view=c3.getView();
assert view.size() == 3 : "view=" + view;
members=Arrays.asList(c1.getAddress(), c2.getAddress(), c3.getAddress());
}
@AfterMethod
protected void tearDown() throws Exception {
d3.stop();
d2.stop();
d1.stop();
Util.close(c3, c2, c1);
}
public void testInvocationOnEntireGroup() {
RspList rsps=d1.callRemoteMethods(null, "foo", null, null, RequestOptions.SYNC);
System.out.println("rsps:\n" + rsps);
assert rsps.size() == 3;
assert o1.wasCalled() && o2.wasCalled() && o3.wasCalled();
}
public void testInvocationOnEntireGroupWithTargetList() {
RspList rsps=d1.callRemoteMethods(members, "foo", null, null, RequestOptions.SYNC);
System.out.println("rsps:\n" + rsps);
assert rsps.size() == 3;
assert o1.wasCalled() && o2.wasCalled() && o3.wasCalled();
}
private static class ServerObject {
boolean called=false;
public boolean wasCalled() {
return called;
}
public boolean foo() {
called=true;
return called;
}
}
} | tests for RPCs with exclusion list (https://jira.jboss.org/jira/browse/JGRP-1192)
| tests/junit/org/jgroups/blocks/RpcDispatcherUnitTest.java | tests for RPCs with exclusion list (https://jira.jboss.org/jira/browse/JGRP-1192) | <ide><path>ests/junit/org/jgroups/blocks/RpcDispatcherUnitTest.java
<ide> import org.jgroups.Address;
<ide> import org.jgroups.tests.ChannelTestBase;
<ide> import org.jgroups.util.*;
<del>import org.testng.annotations.AfterMethod;
<del>import org.testng.annotations.BeforeMethod;
<del>import org.testng.annotations.Test;
<add>import org.testng.annotations.*;
<ide>
<ide> import java.util.List;
<ide> import java.util.Arrays;
<ide>
<ide> /**
<ide> * @author Bela Ban
<del> * @version $Id: RpcDispatcherUnitTest.java,v 1.1 2010/04/21 07:52:00 belaban Exp $
<add> * @version $Id: RpcDispatcherUnitTest.java,v 1.2 2010/04/21 10:51:41 belaban Exp $
<ide> */
<ide> @Test(groups=Global.STACK_DEPENDENT,sequential=true)
<ide> public class RpcDispatcherUnitTest extends ChannelTestBase {
<ide> private RpcDispatcher d1, d2, d3;
<ide> private JChannel c1, c2, c3;
<ide> private ServerObject o1, o2, o3;
<add> private Address a1, a2, a3;
<ide> private List<Address> members;
<ide>
<ide>
<del> @BeforeMethod
<add> @BeforeClass
<ide> protected void setUp() throws Exception {
<ide> o1=new ServerObject();
<ide> o2=new ServerObject();
<ide> View view=c3.getView();
<ide> assert view.size() == 3 : "view=" + view;
<ide>
<del> members=Arrays.asList(c1.getAddress(), c2.getAddress(), c3.getAddress());
<add> a1=c1.getAddress();
<add> a2=c2.getAddress();
<add> a3=c3.getAddress();
<add> members=Arrays.asList(a1, a2, a3);
<ide> }
<ide>
<del> @AfterMethod
<add> @BeforeMethod
<add> protected void reset() {
<add> o1.reset();
<add> o2.reset();
<add> o3.reset();
<add> }
<add>
<add> @AfterClass
<ide> protected void tearDown() throws Exception {
<ide> d3.stop();
<ide> d2.stop();
<ide> }
<ide>
<ide>
<add> /** Invoke a method on all but myself */
<add> public void testInvocationWithExclusionOfSelf() {
<add> RequestOptions options=new RequestOptions(Request.GET_ALL, 5000).setExclusionList(a1);
<add> RspList rsps=d1.callRemoteMethods(null, "foo", null, null, options);
<add> Util.sleep(500);
<add> System.out.println("rsps:\n" + rsps);
<add> assert rsps.size() == 2;
<add> assert rsps.containsKey(a2) && rsps.containsKey(a3);
<add> assert !o1.wasCalled() && o2.wasCalled() && o3.wasCalled();
<add> }
<add>
<add> public void testInvocationWithExclusionOfTwo() {
<add> RequestOptions options=new RequestOptions(Request.GET_ALL, 5000).setExclusionList(a2, a3);
<add> RspList rsps=d1.callRemoteMethods(null, "foo", null, null, options);
<add> Util.sleep(500);
<add> System.out.println("rsps:\n" + rsps);
<add> assert rsps.size() == 1;
<add> assert rsps.containsKey(a1);
<add> assert o1.wasCalled() && !o2.wasCalled() && !o3.wasCalled();
<add> }
<add>
<add> public void testInvocationOnEmptyTargetSet() {
<add> RequestOptions options=new RequestOptions(Request.GET_ALL, 5000).setExclusionList(a1, a2, a3);
<add> RspList rsps=d1.callRemoteMethods(null, "foo", null, null, options);
<add> Util.sleep(500);
<add> System.out.println("rsps:\n" + rsps);
<add> assert rsps.isEmpty();
<add> assert !o1.wasCalled() && !o2.wasCalled() && !o3.wasCalled();
<add> }
<add>
<add>
<ide>
<ide> private static class ServerObject {
<ide> boolean called=false;
<ide>
<ide> public boolean wasCalled() {
<ide> return called;
<add> }
<add>
<add> public void reset() {
<add> called=false;
<ide> }
<ide>
<ide> public boolean foo() { |
|
Java | epl-1.0 | 81584f3fb7d04f6361e3992134270bbcdc171188 | 0 | Beagle-PSE/Beagle,Beagle-PSE/Beagle,Beagle-PSE/Beagle | package de.uka.ipd.sdq.beagle.core.measurement;
import de.uka.ipd.sdq.beagle.core.CodeSection;
import de.uka.ipd.sdq.beagle.core.ExternalCallParameter;
import de.uka.ipd.sdq.beagle.core.MeasurableSeffElement;
import de.uka.ipd.sdq.beagle.core.ResourceDemandingInternalAction;
import de.uka.ipd.sdq.beagle.core.SeffBranch;
import de.uka.ipd.sdq.beagle.core.SeffLoop;
import de.uka.ipd.sdq.beagle.core.measurement.order.CodeSectionEnteredEvent;
import de.uka.ipd.sdq.beagle.core.measurement.order.CodeSectionLeftEvent;
import de.uka.ipd.sdq.beagle.core.measurement.order.MeasurementEvent;
import de.uka.ipd.sdq.beagle.core.measurement.order.MeasurementEventVisitor;
import de.uka.ipd.sdq.beagle.core.measurement.order.ResourceDemandCapturedEvent;
import org.apache.commons.collections4.IteratorUtils;
import org.apache.commons.lang3.Validate;
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 java.util.Stack;
/**
* Parses {@linkplain MeasurementEvent MeasurementEvents} in order to generate
* {@linkplain ParameterisationDependentMeasurementResult
* ParameterisationDependentMeasurementResults} out of them. It is created for a sequence
* of events that occurred while measuring software (the “input events”). The parsed
* results can be obtained by querying with
*
* {@linkplain MeasurableSeffElement MeasurableSeffElements} which will return all
* measurement results found for that element.
*
* @author Joshua Gleitze
* @author Roman Langrehr
*/
public class MeasurementEventParser {
/**
* All measurement events in chronological order.
*/
private final List<MeasurementEvent> measurementEvents;
/**
* Maps for each code sections to all occurrences of measurement events for this code
* section in {@link #measurementEvents}.
*/
private Map<CodeSection, Set<Integer>> codeSectionMapping = new HashMap<>();
/**
* Creates a parser to parse {@code events}. The events must be provided in
* chronological order, starting with the event that occurred first.
*
* @param events The events to be parsed. Must not be {@code null} and all contained
* events must not be {@code null}.
*/
public MeasurementEventParser(final MeasurementEvent... events) {
Validate.noNullElements(events);
this.measurementEvents = Arrays.asList(events);
this.createCodeSectionMapping();
}
/**
* Creates a parser to parse {@code events}. The events must be provided in
* chronological order, starting with the event that occurred first.
*
* @param events The events to be parsed. Must not be {@code null} and all contained
* events must not be {@code null}.
*/
public MeasurementEventParser(final Iterable<MeasurementEvent> events) {
Validate.noNullElements(events);
this.measurementEvents = IteratorUtils.toList(events.iterator());
this.createCodeSectionMapping();
}
/**
* Generates a new {@link #codeSectionMapping} for the {@link #measurementEvents}.
*/
private void createCodeSectionMapping() {
for (int i = 0; i < this.measurementEvents.size(); i++) {
final CodeSection currentCodeSection = this.measurementEvents.get(i).getCodeSection();
if (!this.codeSectionMapping.containsKey(currentCodeSection)) {
this.codeSectionMapping.put(currentCodeSection, new HashSet<>());
}
this.codeSectionMapping.get(currentCodeSection).add(i);
}
}
/**
* Gets all results that could be parsed from the input events for {@code rdia}.
*
* @param resourceDemandingInternalAction A resource demanding internal action to get
* the measurement results of. Must not be {@code null} .
* @return All measurement results parsed for {@code rdia}. Is never {@code null}.
* Contains never {@code null} elements.
*/
public Set<ResourceDemandMeasurementResult> getMeasurementResultsFor(
final ResourceDemandingInternalAction resourceDemandingInternalAction) {
Validate.notNull(resourceDemandingInternalAction);
final Set<ResourceDemandMeasurementResult> resourceDemandMeasurementResults = new HashSet<>();
final ResourceDemandingInternalActionMeasurementEventVisitor resourceDemandingInternalActionMeasurementEventVisitor =
new ResourceDemandingInternalActionMeasurementEventVisitor(resourceDemandingInternalAction,
resourceDemandMeasurementResults);
final Set<Integer> indices = this.codeSectionMapping.get(resourceDemandingInternalAction.getAction());
if (indices != null) {
for (final Integer index : indices) {
final MeasurementEvent measurementEvent = this.measurementEvents.get(index);
measurementEvent.receive(resourceDemandingInternalActionMeasurementEventVisitor);
}
}
return resourceDemandMeasurementResults;
}
/**
* Gets all results that could be parsed from the input events for {@code branch}.
*
* @param branch A SEFF Branch to get the measurement results of. Must not be
* {@code null} .
* @return All measurement results parsed for {@code branch}. Is never {@code null}.
* Contains never {@code null} elements.
*/
public Set<BranchDecisionMeasurementResult> getMeasurementResultsFor(final SeffBranch branch) {
final Set<BranchDecisionMeasurementResult> branchDecisionMeasurementResults = new HashSet<>();
// Assemble all measurement events, that could fit for this branch according to
// their code section.
final Set<MeasurementEvent> codeSectionEventsForThisBranch = new HashSet<>();
for (final CodeSection possibilyPickedBranch : branch.getBranches()) {
final Set<Integer> indices = this.codeSectionMapping.get(possibilyPickedBranch);
if (indices != null) {
for (final Integer index : indices) {
codeSectionEventsForThisBranch.add(this.measurementEvents.get(index));
}
}
}
final SeffBranchMeasurementEventVisitor seffBranchMeasurementEventVisitor =
new SeffBranchMeasurementEventVisitor(branch, branchDecisionMeasurementResults);
for (final MeasurementEvent measurementEvent : codeSectionEventsForThisBranch) {
measurementEvent.receive(seffBranchMeasurementEventVisitor);
}
return branchDecisionMeasurementResults;
}
/**
* Gets all results that could be parsed from the input events for {@code loop}.
*
* @param loop A SEFF Loop to get the measurement results of. Must not be {@code null}
* .
* @return All measurement results parsed for {@code loop}. Is never {@code null}.
* Contains never {@code null} elements.
*/
public Set<LoopRepetitionCountMeasurementResult> getMeasurementResultsFor(final SeffLoop loop) {
final Set<LoopRepetitionCountMeasurementResult> loopRepetitionCountMeasurementResults = new HashSet<>();
final SeffLoopMeasurementEventVisitor seffLoopMeasurementEventVisitor =
new SeffLoopMeasurementEventVisitor(loopRepetitionCountMeasurementResults);
final Set<Integer> indices = this.codeSectionMapping.get(loop.getLoopBody());
if (indices != null) {
for (final Integer index : indices) {
this.measurementEvents.get(index).receive(seffLoopMeasurementEventVisitor);
}
}
seffLoopMeasurementEventVisitor.finalise();
return loopRepetitionCountMeasurementResults;
}
/**
* Note: this method is out of our projects scope and not yet implemented. Gets all
* results that could be parsed from the input events for
* {@code externalCallParameter}.
*
* @param externalCallParameter An external parameter to get the measurement results
* of. Must not be {@code null}.
* @return All measurement results parsed for {@code externalCallParameter}. Is never
* {@code null}. Contains never {@code null} elements.
*/
public Set<ParameterChangeMeasurementResult> getMeasurementResultsFor(
final ExternalCallParameter externalCallParameter) {
return new HashSet<>();
}
/**
* A {@link MeasurementEventVisitor} for a specific
* {@link ResourceDemandingInternalAction}.
*
* <p>Only {@linkplain MeasurementEvent MeasurementEvents} with the correct
* {@link CodeSection} may be visited with this visitor.
*
* @author Roman Langrehr
*/
private class ResourceDemandingInternalActionMeasurementEventVisitor extends AbstractMeasurementEventVisitor {
/**
* The {@link ResourceDemandingInternalAction} where we want to know the new
* measurement results.
*/
private final ResourceDemandingInternalAction resourceDemandingInternalAction;
/**
* The set, where the {@link ResourceDemandMeasurementResult} should be added.
*/
private final Set<ResourceDemandMeasurementResult> resourceDemandMeasurementResults;
/**
* Creates a visitor for a specific {@link ResourceDemandingInternalAction}.
*
* @param resourceDemandingInternalAction The
* {@link ResourceDemandingInternalAction} where we want to know the
* new measurement results.
* @param resourceDemandMeasurementResults The set, where the
* {@link ResourceDemandMeasurementResult} should be added.
*/
ResourceDemandingInternalActionMeasurementEventVisitor(
final ResourceDemandingInternalAction resourceDemandingInternalAction,
final Set<ResourceDemandMeasurementResult> resourceDemandMeasurementResults) {
this.resourceDemandingInternalAction = resourceDemandingInternalAction;
this.resourceDemandMeasurementResults = resourceDemandMeasurementResults;
}
@Override
public void visit(final ResourceDemandCapturedEvent resourceDemandCapturedEvent) {
// Check if this measurement event is for the correct resource type.
if (resourceDemandCapturedEvent.getType() == this.resourceDemandingInternalAction.getResourceType()) {
this.resourceDemandMeasurementResults
.add(new ResourceDemandMeasurementResult(resourceDemandCapturedEvent.getValue()));
}
}
}
/**
* A {@link MeasurementEventVisitor} for a specific {@link SeffBranch}.
*
* @author Roman Langrehr
*/
private class SeffBranchMeasurementEventVisitor extends AbstractMeasurementEventVisitor {
/**
* The {@link SeffBranch} where we want to know the new measurement results.
*/
private final SeffBranch branch;
/**
* The set, where the {@linkplain ResourceDemandMeasurementResult
* ResourceDemandMeasurementResults} should be added.
*/
private final Set<BranchDecisionMeasurementResult> branchDecisionMeasurementResults;
/**
* Creates a visitor for a specific {@link SeffBranch}.
*
* @param branch The {@link SeffBranch} where we want to know the new measurement
* results.
* @param branchDecisionMeasurementResults The set, where the
* {@linkplain BranchDecisionMeasurementResult
* BranchDecisionMeasurementResults} should be added.
*/
SeffBranchMeasurementEventVisitor(final SeffBranch branch,
final Set<BranchDecisionMeasurementResult> branchDecisionMeasurementResults) {
this.branch = branch;
this.branchDecisionMeasurementResults = branchDecisionMeasurementResults;
}
@Override
public void visit(final CodeSectionEnteredEvent codeSectionExecutedEvent) {
final int branchIndex = this.branch.getBranches().indexOf(codeSectionExecutedEvent.getCodeSection());
this.branchDecisionMeasurementResults.add(new BranchDecisionMeasurementResult(branchIndex));
}
// We don't care about CodeSectionLeftEvents, because we defined a SeffBranch to
// be executed, exactly when it was entered.
}
/**
* A {@link MeasurementEventVisitor} for a specific {@link SeffLoop}.
*
* <p>You must call {@linkplain MeasurementEvent#receive(MeasurementEventVisitor)
* receive} on the {@linkplain MeasurementEvent MeasurementEvents} in the correct
* order!
*
* @author Roman Langrehr
*/
private class SeffLoopMeasurementEventVisitor extends AbstractMeasurementEventVisitor {
/**
* The set, where the {@linkplain ResourceDemandMeasurementResult
* ResourceDemandMeasurementResults} should be added.
*/
private final Set<LoopRepetitionCountMeasurementResult> loopRepetitionCountMeasurementResults;
/**
* The number of loops measured in the current sequence of measurement events for
* one loop body. The stack contains all
*/
private Stack<LoopExecutionCounter> currentLoopCounts;
/**
* Creates a visitor for a specific {@link SeffLoop}.
*
* @param loopRepetitionCountMeasurementResults The set, where the
* {@linkplain BranchDecisionMeasurementResult
* BranchDecisionMeasurementResults} should be added.
*/
SeffLoopMeasurementEventVisitor(
final Set<LoopRepetitionCountMeasurementResult> loopRepetitionCountMeasurementResults) {
this.loopRepetitionCountMeasurementResults = loopRepetitionCountMeasurementResults;
this.currentLoopCounts = new Stack<>();
}
@Override
public void visit(final CodeSectionEnteredEvent codeSectionEnteredEvent) {
if (this.currentLoopCounts.isEmpty() || this.currentLoopCounts.peek().isOpen) {
// The current branch was not finished before a this, so we have a
// recursive call, or there is no current execution of this loop.
this.currentLoopCounts.push(new LoopExecutionCounter());
}
assert !this.currentLoopCounts.peek().isOpen;
if (!(this.currentLoopCounts.peek().lastCodeSectionLeftEventIndex == -1
|| this.currentLoopCounts.peek().lastCodeSectionLeftEventIndex
+ 1 == MeasurementEventParser.this.measurementEvents.indexOf(codeSectionEnteredEvent))) {
// We have not continuous loop body executions, so we create a new
// execution event.
this.loopFinished();
this.currentLoopCounts.push(new LoopExecutionCounter());
}
this.currentLoopCounts.peek().numberOfExecutions++;
this.currentLoopCounts.peek().isOpen = true;
}
@Override
public void visit(final CodeSectionLeftEvent codeSectionLeftEvent) {
if (!this.currentLoopCounts.isEmpty()) {
if (this.currentLoopCounts.peek().isOpen) {
// The current execution is finished.
this.currentLoopCounts.peek().isOpen = false;
this.currentLoopCounts.peek().lastCodeSectionLeftEventIndex =
MeasurementEventParser.this.measurementEvents.indexOf(codeSectionLeftEvent);
} else {
// The current execution is already finished, so we need to close
// the one "below" that.
// The actual closing
this.loopFinished();
if (!this.currentLoopCounts.isEmpty()) {
// The invariant for this stack
assert this.currentLoopCounts.peek().isOpen;
// allows us to just close the next layer.
this.currentLoopCounts.peek().isOpen = false;
this.currentLoopCounts.peek().lastCodeSectionLeftEventIndex =
MeasurementEventParser.this.measurementEvents.indexOf(codeSectionLeftEvent);
}
}
}
// If the currentLoopCounts stack is empty, we have a CodeSectionLeftEvent
// event without an CodeSectionEnteredEvent and ignore this.
}
/**
* This method must be called after the last measurement event was visited,
* because otherwise the resulting {@code loopRepetitionCountMeasurementResults}
* may be incomplete.
*/
public void finalise() {
// Close all open executions. There {@link CodeSectionLeftEvent} is missing.
while (!this.currentLoopCounts.isEmpty()) {
this.loopFinished();
}
}
/**
* Pops the top of {@link #currentLoopCounts} and adds the
* {@link LoopRepetitionCountMeasurementResult} for this execution.
*/
private void loopFinished() {
this.loopRepetitionCountMeasurementResults
.add(new LoopRepetitionCountMeasurementResult(this.currentLoopCounts.pop().numberOfExecutions));
}
/**
* Container for the information needed to save the state of an loop execution.
*
* @author Roman Langrehr
*/
private class LoopExecutionCounter {
/**
* How many times the loop was executed.
*/
private int numberOfExecutions;
/**
* Whether the last execution of the loop body was not finished. (An
* {@link CodeSectionEnteredEvent} was parsed, but not the corresponding
* {@link CodeSectionLeftEvent}.
*/
private boolean isOpen;
/**
* If {@link #isOpen} is {@code false}, this field is the index of the last
* CodeSectionLeftEvent of an loop body for this branch or {@code -1}, if no
* CodeSectionLeftEvent was parsed for this loop execution.
*/
private int lastCodeSectionLeftEventIndex;
/**
* Creates a new, empty LoopExecutionCounter.
*/
LoopExecutionCounter() {
this.numberOfExecutions = 0;
this.isOpen = false;
this.lastCodeSectionLeftEventIndex = -1;
}
}
}
}
| Core/src/main/java/de/uka/ipd/sdq/beagle/core/measurement/MeasurementEventParser.java | package de.uka.ipd.sdq.beagle.core.measurement;
import de.uka.ipd.sdq.beagle.core.CodeSection;
import de.uka.ipd.sdq.beagle.core.ExternalCallParameter;
import de.uka.ipd.sdq.beagle.core.MeasurableSeffElement;
import de.uka.ipd.sdq.beagle.core.ResourceDemandingInternalAction;
import de.uka.ipd.sdq.beagle.core.SeffBranch;
import de.uka.ipd.sdq.beagle.core.SeffLoop;
import de.uka.ipd.sdq.beagle.core.measurement.order.CodeSectionEnteredEvent;
import de.uka.ipd.sdq.beagle.core.measurement.order.CodeSectionLeftEvent;
import de.uka.ipd.sdq.beagle.core.measurement.order.MeasurementEvent;
import de.uka.ipd.sdq.beagle.core.measurement.order.MeasurementEventVisitor;
import de.uka.ipd.sdq.beagle.core.measurement.order.ResourceDemandCapturedEvent;
import org.apache.commons.collections4.IteratorUtils;
import org.apache.commons.lang3.Validate;
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 java.util.Stack;
/**
* Parses {@linkplain MeasurementEvent MeasurementEvents} in order to generate
* {@linkplain ParameterisationDependentMeasurementResult
* ParameterisationDependentMeasurementResults} out of them. It is created for a sequence
* of events that occurred while measuring software (the “input events”). The parsed
* results can be obtained by querying with
*
* {@linkplain MeasurableSeffElement MeasurableSeffElements} which will return all
* measurement results found for that element.
*
* @author Joshua Gleitze
* @author Roman Langrehr
*/
public class MeasurementEventParser {
/**
* All measurement events in chronological order.
*/
private final List<MeasurementEvent> measurementEvents;
/**
* Maps for each code sections to all occurrences of measurement events for this code
* section in {@link #measurementEvents}.
*/
private Map<CodeSection, Set<Integer>> codeSectionMapping = new HashMap<>();
/**
* Creates a parser to parse {@code events}. The events must be provided in
* chronological order, starting with the event that occurred first.
*
* @param events The events to be parsed. Must not be {@code null} and all contained
* events must not be {@code null}.
*/
public MeasurementEventParser(final MeasurementEvent... events) {
Validate.noNullElements(events);
this.measurementEvents = Arrays.asList(events);
this.createCodeSectionMapping();
}
/**
* Creates a parser to parse {@code events}. The events must be provided in
* chronological order, starting with the event that occurred first.
*
* @param events The events to be parsed. Must not be {@code null} and all contained
* events must not be {@code null}.
*/
public MeasurementEventParser(final Iterable<MeasurementEvent> events) {
Validate.noNullElements(events);
this.measurementEvents = IteratorUtils.toList(events.iterator());
this.createCodeSectionMapping();
}
/**
* Generates a new {@link #codeSectionMapping} for the {@link #measurementEvents}.
*/
private void createCodeSectionMapping() {
for (int i = 0; i < this.measurementEvents.size(); i++) {
final CodeSection currentCodeSection = this.measurementEvents.get(i).getCodeSection();
if (!this.codeSectionMapping.containsKey(currentCodeSection)) {
this.codeSectionMapping.put(currentCodeSection, new HashSet<>());
}
this.codeSectionMapping.get(currentCodeSection).add(i);
}
}
/**
* Gets all results that could be parsed from the input events for {@code rdia}.
*
* @param resourceDemandingInternalAction A resource demanding internal action to get
* the measurement results of. Must not be {@code null} .
* @return All measurement results parsed for {@code rdia}. Is never {@code null}.
* Contains never {@code null} elements.
*/
public Set<ResourceDemandMeasurementResult> getMeasurementResultsFor(
final ResourceDemandingInternalAction resourceDemandingInternalAction) {
Validate.notNull(resourceDemandingInternalAction);
final Set<ResourceDemandMeasurementResult> resourceDemandMeasurementResults = new HashSet<>();
final ResourceDemandingInternalActionMeasurementEventVisitor resourceDemandingInternalActionMeasurementEventVisitor =
new ResourceDemandingInternalActionMeasurementEventVisitor(resourceDemandingInternalAction,
resourceDemandMeasurementResults);
final Set<Integer> indices = this.codeSectionMapping.get(resourceDemandingInternalAction.getAction());
if (indices != null) {
for (final Integer index : indices) {
final MeasurementEvent measurementEvent = this.measurementEvents.get(index);
measurementEvent.receive(resourceDemandingInternalActionMeasurementEventVisitor);
}
}
return resourceDemandMeasurementResults;
}
/**
* Gets all results that could be parsed from the input events for {@code branch}.
*
* @param branch A SEFF Branch to get the measurement results of. Must not be
* {@code null} .
* @return All measurement results parsed for {@code branch}. Is never {@code null}.
* Contains never {@code null} elements.
*/
public Set<BranchDecisionMeasurementResult> getMeasurementResultsFor(final SeffBranch branch) {
final Set<BranchDecisionMeasurementResult> branchDecisionMeasurementResults = new HashSet<>();
// Assemble all measurement events, that could fit for this branch according to
// their code section.
final Set<MeasurementEvent> codeSectionEventsForThisBranch = new HashSet<>();
for (final CodeSection possibilyPickedBranch : branch.getBranches()) {
final Set<Integer> indices = this.codeSectionMapping.get(possibilyPickedBranch);
if (indices != null) {
for (final Integer index : indices) {
codeSectionEventsForThisBranch.add(this.measurementEvents.get(index));
}
}
}
final SeffBranchMeasurementEventVisitor seffBranchMeasurementEventVisitor =
new SeffBranchMeasurementEventVisitor(branch, branchDecisionMeasurementResults);
for (final MeasurementEvent measurementEvent : codeSectionEventsForThisBranch) {
measurementEvent.receive(seffBranchMeasurementEventVisitor);
}
return branchDecisionMeasurementResults;
}
/**
* Gets all results that could be parsed from the input events for {@code loop}.
*
* @param loop A SEFF Loop to get the measurement results of. Must not be {@code null}
* .
* @return All measurement results parsed for {@code loop}. Is never {@code null}.
* Contains never {@code null} elements.
*/
public Set<LoopRepetitionCountMeasurementResult> getMeasurementResultsFor(final SeffLoop loop) {
final Set<LoopRepetitionCountMeasurementResult> loopRepetitionCountMeasurementResults = new HashSet<>();
final SeffLoopMeasurementEventVisitor seffLoopMeasurementEventVisitor =
new SeffLoopMeasurementEventVisitor(loop, loopRepetitionCountMeasurementResults);
final Set<Integer> indices = this.codeSectionMapping.get(loop.getLoopBody());
if (indices != null) {
for (final Integer index : indices) {
this.measurementEvents.get(index).receive(seffLoopMeasurementEventVisitor);
}
}
seffLoopMeasurementEventVisitor.finalise();
return loopRepetitionCountMeasurementResults;
}
/**
* Note: this method is out of our projects scope and not yet implemented. Gets all
* results that could be parsed from the input events for
* {@code externalCallParameter}.
*
* @param externalCallParameter An external parameter to get the measurement results
* of. Must not be {@code null}.
* @return All measurement results parsed for {@code externalCallParameter}. Is never
* {@code null}. Contains never {@code null} elements.
*/
public Set<ParameterChangeMeasurementResult> getMeasurementResultsFor(
final ExternalCallParameter externalCallParameter) {
return new HashSet<>();
}
/**
* A {@link MeasurementEventVisitor} for a specific
* {@link ResourceDemandingInternalAction}.
*
* <p>Only {@linkplain MeasurementEvent MeasurementEvents} with the correct
* {@link CodeSection} may be visited with this visitor.
*
* @author Roman Langrehr
*/
private class ResourceDemandingInternalActionMeasurementEventVisitor extends AbstractMeasurementEventVisitor {
/**
* The {@link ResourceDemandingInternalAction} where we want to know the new
* measurement results.
*/
private final ResourceDemandingInternalAction resourceDemandingInternalAction;
/**
* The set, where the {@link ResourceDemandMeasurementResult} should be added.
*/
private final Set<ResourceDemandMeasurementResult> resourceDemandMeasurementResults;
/**
* Creates a visitor for a specific {@link ResourceDemandingInternalAction}.
*
* @param resourceDemandingInternalAction The
* {@link ResourceDemandingInternalAction} where we want to know the
* new measurement results.
* @param resourceDemandMeasurementResults The set, where the
* {@link ResourceDemandMeasurementResult} should be added.
*/
ResourceDemandingInternalActionMeasurementEventVisitor(
final ResourceDemandingInternalAction resourceDemandingInternalAction,
final Set<ResourceDemandMeasurementResult> resourceDemandMeasurementResults) {
this.resourceDemandingInternalAction = resourceDemandingInternalAction;
this.resourceDemandMeasurementResults = resourceDemandMeasurementResults;
}
@Override
public void visit(final ResourceDemandCapturedEvent resourceDemandCapturedEvent) {
// Check if this measurement event is for the correct resource type.
if (resourceDemandCapturedEvent.getType() == this.resourceDemandingInternalAction.getResourceType()) {
this.resourceDemandMeasurementResults
.add(new ResourceDemandMeasurementResult(resourceDemandCapturedEvent.getValue()));
}
}
}
/**
* A {@link MeasurementEventVisitor} for a specific {@link SeffBranch}.
*
* @author Roman Langrehr
*/
private class SeffBranchMeasurementEventVisitor extends AbstractMeasurementEventVisitor {
/**
* The {@link SeffBranch} where we want to know the new measurement results.
*/
private final SeffBranch branch;
/**
* The set, where the {@linkplain ResourceDemandMeasurementResult
* ResourceDemandMeasurementResults} should be added.
*/
private final Set<BranchDecisionMeasurementResult> branchDecisionMeasurementResults;
/**
* Creates a visitor for a specific {@link SeffBranch}.
*
* @param branch The {@link SeffBranch} where we want to know the new measurement
* results.
* @param branchDecisionMeasurementResults The set, where the
* {@linkplain BranchDecisionMeasurementResult
* BranchDecisionMeasurementResults} should be added.
*/
SeffBranchMeasurementEventVisitor(final SeffBranch branch,
final Set<BranchDecisionMeasurementResult> branchDecisionMeasurementResults) {
this.branch = branch;
this.branchDecisionMeasurementResults = branchDecisionMeasurementResults;
}
@Override
public void visit(final CodeSectionEnteredEvent codeSectionExecutedEvent) {
final int branchIndex = this.branch.getBranches().indexOf(codeSectionExecutedEvent.getCodeSection());
this.branchDecisionMeasurementResults.add(new BranchDecisionMeasurementResult(branchIndex));
}
// We don't care about CodeSectionLeftEvents, because we defined a SeffBranch to
// be executed, exactly when it was entered.
}
/**
* A {@link MeasurementEventVisitor} for a specific {@link SeffLoop}.
*
* <p>You must call {@linkplain MeasurementEvent#receive(MeasurementEventVisitor)
* receive} on the {@linkplain MeasurementEvent MeasurementEvents} in the correct
* order!
*
* @author Roman Langrehr
*/
private class SeffLoopMeasurementEventVisitor extends AbstractMeasurementEventVisitor {
/**
* The {@link SeffBranch} where we want to know the new measurement results.
*/
private final SeffLoop loop;
/**
* The set, where the {@linkplain ResourceDemandMeasurementResult
* ResourceDemandMeasurementResults} should be added.
*/
private final Set<LoopRepetitionCountMeasurementResult> loopRepetitionCountMeasurementResults;
/**
* The number of loops measured in the current sequence of measurement events for
* one loop body. The stack contains all
*/
private Stack<LoopExecutionCounter> currentLoopCounts;
/**
* Creates a visitor for a specific {@link SeffLoop}.
*
* @param loop The {@link SeffLoop} where we want to know the new measurement
* results.
* @param loopRepetitionCountMeasurementResults The set, where the
* {@linkplain BranchDecisionMeasurementResult
* BranchDecisionMeasurementResults} should be added.
*/
SeffLoopMeasurementEventVisitor(final SeffLoop loop,
final Set<LoopRepetitionCountMeasurementResult> loopRepetitionCountMeasurementResults) {
this.loop = loop;
this.loopRepetitionCountMeasurementResults = loopRepetitionCountMeasurementResults;
this.currentLoopCounts = new Stack<>();
}
@Override
public void visit(final CodeSectionEnteredEvent codeSectionEnteredEvent) {
if (this.currentLoopCounts.isEmpty() || this.currentLoopCounts.peek().isOpen) {
// The current branch was not finished before a this, so we have a
// recursive call, or there is no current execution of this loop.
this.currentLoopCounts.push(new LoopExecutionCounter());
}
assert !this.currentLoopCounts.peek().isOpen;
if (!(this.currentLoopCounts.peek().lastCodeSectionLeftEventIndex == -1
|| this.currentLoopCounts.peek().lastCodeSectionLeftEventIndex
+ 1 == MeasurementEventParser.this.measurementEvents.indexOf(codeSectionEnteredEvent))) {
// We have not continuous loop body executions, so we create a new
// execution event.
this.loopFinished();
this.currentLoopCounts.push(new LoopExecutionCounter());
}
this.currentLoopCounts.peek().numberOfExecutions++;
this.currentLoopCounts.peek().isOpen = true;
}
@Override
public void visit(final CodeSectionLeftEvent codeSectionLeftEvent) {
if (!this.currentLoopCounts.isEmpty()) {
if (this.currentLoopCounts.peek().isOpen) {
// The current execution is finished.
this.currentLoopCounts.peek().isOpen = false;
this.currentLoopCounts.peek().lastCodeSectionLeftEventIndex =
MeasurementEventParser.this.measurementEvents.indexOf(codeSectionLeftEvent);
} else {
// The current execution is already finished, so we need to close
// the one "below" that.
// The actual closing
this.loopFinished();
if (!this.currentLoopCounts.isEmpty()) {
// The invariant for this stack
assert this.currentLoopCounts.peek().isOpen;
// allows us to just close the next layer.
this.currentLoopCounts.peek().isOpen = false;
this.currentLoopCounts.peek().lastCodeSectionLeftEventIndex =
MeasurementEventParser.this.measurementEvents.indexOf(codeSectionLeftEvent);
}
}
}
// If the currentLoopCounts stack is empty, we have a CodeSectionLeftEvent
// event without an CodeSectionEnteredEvent and ignore this.
}
/**
* This method must be called after the last measurement event was visited,
* because otherwise the resulting {@code loopRepetitionCountMeasurementResults}
* may be incomplete.
*/
public void finalise() {
// Close all open executions. There {@link CodeSectionLeftEvent} is missing.
while (!this.currentLoopCounts.isEmpty()) {
this.loopFinished();
}
}
/**
* Pops the top of {@link #currentLoopCounts} and adds the
* {@link LoopRepetitionCountMeasurementResult} for this execution.
*/
private void loopFinished() {
this.loopRepetitionCountMeasurementResults
.add(new LoopRepetitionCountMeasurementResult(this.currentLoopCounts.pop().numberOfExecutions));
}
/**
* Container for the information needed to save the state of an loop execution.
*
* @author Roman Langrehr
*/
private class LoopExecutionCounter {
/**
* How many times the loop was executed.
*/
private int numberOfExecutions;
/**
* Whether the last execution of the loop body was not finished. (An
* {@link CodeSectionEnteredEvent} was parsed, but not the corresponding
* {@link CodeSectionLeftEvent}.
*/
private boolean isOpen;
/**
* If {@link #isOpen} is {@code false}, this field is the index of the last
* CodeSectionLeftEvent of an loop body for this branch or {@code -1}, if no
* CodeSectionLeftEvent was parsed for this loop execution.
*/
private int lastCodeSectionLeftEventIndex;
/**
* Creates a new, empty LoopExecutionCounter.
*/
LoopExecutionCounter() {
this.numberOfExecutions = 0;
this.isOpen = false;
this.lastCodeSectionLeftEventIndex = -1;
}
}
}
}
| Removed unnecassry field.
| Core/src/main/java/de/uka/ipd/sdq/beagle/core/measurement/MeasurementEventParser.java | Removed unnecassry field. | <ide><path>ore/src/main/java/de/uka/ipd/sdq/beagle/core/measurement/MeasurementEventParser.java
<ide> public Set<LoopRepetitionCountMeasurementResult> getMeasurementResultsFor(final SeffLoop loop) {
<ide> final Set<LoopRepetitionCountMeasurementResult> loopRepetitionCountMeasurementResults = new HashSet<>();
<ide> final SeffLoopMeasurementEventVisitor seffLoopMeasurementEventVisitor =
<del> new SeffLoopMeasurementEventVisitor(loop, loopRepetitionCountMeasurementResults);
<add> new SeffLoopMeasurementEventVisitor(loopRepetitionCountMeasurementResults);
<ide> final Set<Integer> indices = this.codeSectionMapping.get(loop.getLoopBody());
<ide> if (indices != null) {
<ide> for (final Integer index : indices) {
<ide> private class SeffLoopMeasurementEventVisitor extends AbstractMeasurementEventVisitor {
<ide>
<ide> /**
<del> * The {@link SeffBranch} where we want to know the new measurement results.
<del> */
<del> private final SeffLoop loop;
<del>
<del> /**
<ide> * The set, where the {@linkplain ResourceDemandMeasurementResult
<ide> * ResourceDemandMeasurementResults} should be added.
<ide> */
<ide> /**
<ide> * Creates a visitor for a specific {@link SeffLoop}.
<ide> *
<del> * @param loop The {@link SeffLoop} where we want to know the new measurement
<del> * results.
<ide> * @param loopRepetitionCountMeasurementResults The set, where the
<ide> * {@linkplain BranchDecisionMeasurementResult
<ide> * BranchDecisionMeasurementResults} should be added.
<ide> */
<del> SeffLoopMeasurementEventVisitor(final SeffLoop loop,
<add> SeffLoopMeasurementEventVisitor(
<ide> final Set<LoopRepetitionCountMeasurementResult> loopRepetitionCountMeasurementResults) {
<del> this.loop = loop;
<ide> this.loopRepetitionCountMeasurementResults = loopRepetitionCountMeasurementResults;
<ide> this.currentLoopCounts = new Stack<>();
<ide> } |
|
Java | apache-2.0 | 0ffc5854c752c0bd183afc7e482d9dbbfba6564c | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | /*
* Copyright 2003-2017 Dave Griffith, Bas Leijdekkers
*
* 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.siyeh.ig.controlflow;
import com.intellij.codeInspection.AbstractBaseJavaLocalInspectionTool;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.fixes.CreateDefaultBranchFix;
import com.siyeh.ig.psiutils.SwitchUtils;
import one.util.streamex.StreamEx;
import org.intellij.lang.annotations.Pattern;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.util.List;
import java.util.Set;
public class SwitchStatementsWithoutDefaultInspection extends AbstractBaseJavaLocalInspectionTool {
@SuppressWarnings("PublicField")
public boolean m_ignoreFullyCoveredEnums = true;
@Override
@NotNull
public String getDisplayName() {
return InspectionGadgetsBundle.message("switch.statements.without.default.display.name");
}
@Pattern(VALID_ID_PATTERN)
@Override
@NotNull
public String getID() {
return "SwitchStatementWithoutDefaultBranch";
}
@Override
public JComponent createOptionsPanel() {
return new SingleCheckboxOptionsPanel(InspectionGadgetsBundle.message("switch.statement.without.default.ignore.option"),
this, "m_ignoreFullyCoveredEnums");
}
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
return new JavaElementVisitor() {
// handling switch expression seems unnecessary here as non-exhaustive switch expression
// without default is a compilation error
@Override
public void visitSwitchStatement(@NotNull PsiSwitchStatement statement) {
super.visitSwitchStatement(statement);
final int count = SwitchUtils.calculateBranchCount(statement);
if (count < 0 || statement.getBody() == null) {
return;
}
boolean infoMode = false;
if (count == 0 || m_ignoreFullyCoveredEnums && switchStatementIsFullyCoveredEnum(statement)) {
if (!isOnTheFly) return;
infoMode = true;
}
String message = InspectionGadgetsBundle.message("switch.statements.without.default.problem.descriptor");
if (infoMode || (isOnTheFly && InspectionProjectProfileManager.isInformationLevel(getShortName(), statement))) {
holder.registerProblem(statement, message, ProblemHighlightType.INFORMATION, new CreateDefaultBranchFix(statement));
} else {
holder.registerProblem(statement.getFirstChild(), message, new CreateDefaultBranchFix(statement));
}
}
private boolean switchStatementIsFullyCoveredEnum(PsiSwitchStatement statement) {
final PsiExpression expression = statement.getExpression();
if (expression == null) {
return true; // don't warn on incomplete code
}
final PsiClass aClass = PsiUtil.resolveClassInClassTypeOnly(expression.getType());
if (aClass == null || !aClass.isEnum()) return false;
List<PsiSwitchLabelStatementBase> labels = PsiTreeUtil.getChildrenOfTypeAsList(statement.getBody(), PsiSwitchLabelStatementBase.class);
Set<PsiEnumConstant> constants = StreamEx.of(labels).flatCollection(SwitchUtils::findEnumConstants).toSet();
for (PsiField field : aClass.getFields()) {
if (field instanceof PsiEnumConstant && !constants.remove(field)) {
return false;
}
}
return true;
}
};
}
} | plugins/InspectionGadgets/src/com/siyeh/ig/controlflow/SwitchStatementsWithoutDefaultInspection.java | /*
* Copyright 2003-2017 Dave Griffith, Bas Leijdekkers
*
* 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.siyeh.ig.controlflow;
import com.intellij.codeInspection.AbstractBaseJavaLocalInspectionTool;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.fixes.CreateDefaultBranchFix;
import com.siyeh.ig.psiutils.SwitchUtils;
import one.util.streamex.StreamEx;
import org.intellij.lang.annotations.Pattern;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.util.List;
import java.util.Set;
public class SwitchStatementsWithoutDefaultInspection extends AbstractBaseJavaLocalInspectionTool {
@SuppressWarnings("PublicField")
public boolean m_ignoreFullyCoveredEnums = true;
@Override
@NotNull
public String getDisplayName() {
return InspectionGadgetsBundle.message("switch.statements.without.default.display.name");
}
@Pattern(VALID_ID_PATTERN)
@Override
@NotNull
public String getID() {
return "SwitchStatementWithoutDefaultBranch";
}
@Override
public JComponent createOptionsPanel() {
return new SingleCheckboxOptionsPanel(InspectionGadgetsBundle.message("switch.statement.without.default.ignore.option"),
this, "m_ignoreFullyCoveredEnums");
}
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
return new JavaElementVisitor() {
@Override
public void visitSwitchStatement(@NotNull PsiSwitchStatement statement) {
super.visitSwitchStatement(statement);
final int count = SwitchUtils.calculateBranchCount(statement);
if (count < 0 || statement.getBody() == null) {
return;
}
boolean infoMode = false;
if (count == 0 || m_ignoreFullyCoveredEnums && switchStatementIsFullyCoveredEnum(statement)) {
if (!isOnTheFly) return;
infoMode = true;
}
String message = InspectionGadgetsBundle.message("switch.statements.without.default.problem.descriptor");
if (infoMode || (isOnTheFly && InspectionProjectProfileManager.isInformationLevel(getShortName(), statement))) {
holder.registerProblem(statement, message, ProblemHighlightType.INFORMATION, new CreateDefaultBranchFix(statement));
} else {
holder.registerProblem(statement.getFirstChild(), message, new CreateDefaultBranchFix(statement));
}
}
private boolean switchStatementIsFullyCoveredEnum(PsiSwitchStatement statement) {
final PsiExpression expression = statement.getExpression();
if (expression == null) {
return true; // don't warn on incomplete code
}
final PsiClass aClass = PsiUtil.resolveClassInClassTypeOnly(expression.getType());
if (aClass == null || !aClass.isEnum()) return false;
List<PsiSwitchLabelStatementBase> labels = PsiTreeUtil.getChildrenOfTypeAsList(statement.getBody(), PsiSwitchLabelStatementBase.class);
Set<PsiEnumConstant> constants = StreamEx.of(labels).flatCollection(SwitchUtils::findEnumConstants).toSet();
for (PsiField field : aClass.getFields()) {
if (field instanceof PsiEnumConstant && !constants.remove(field)) {
return false;
}
}
return true;
}
};
}
} | SwitchStatementsWithoutDefaultInspection: a comment added regarding switch expressions
| plugins/InspectionGadgets/src/com/siyeh/ig/controlflow/SwitchStatementsWithoutDefaultInspection.java | SwitchStatementsWithoutDefaultInspection: a comment added regarding switch expressions | <ide><path>lugins/InspectionGadgets/src/com/siyeh/ig/controlflow/SwitchStatementsWithoutDefaultInspection.java
<ide> @Override
<ide> public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
<ide> return new JavaElementVisitor() {
<add> // handling switch expression seems unnecessary here as non-exhaustive switch expression
<add> // without default is a compilation error
<ide> @Override
<ide> public void visitSwitchStatement(@NotNull PsiSwitchStatement statement) {
<ide> super.visitSwitchStatement(statement); |
|
Java | mit | f7b0cff9cc7dcf9f41eccda1cd19233eef597713 | 0 | ragnraok/MonoReader,ragnraok/MonoReader | package cn.ragnarok.monoreader.app.ui.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.VolleyError;
import java.util.Collection;
import cn.ragnarok.monoreader.api.base.APIRequestFinishListener;
import cn.ragnarok.monoreader.api.object.ListArticleObject;
import cn.ragnarok.monoreader.api.service.SiteService;
import cn.ragnarok.monoreader.app.R;
import cn.ragnarok.monoreader.app.ui.adapter.TimelineListAdapter;
import cn.ragnarok.monoreader.app.ui.fragment.TimelineFragment;
import cn.ragnarok.monoreader.app.util.Utils;
import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.Options;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
public class SiteArticleListActivity extends Activity {
public static final String TAG = "Mono.SiteArticleListActivity";
public static final String SITE_ID = "SITE_ID";
public static final String SITE_TITLE = "SITE_TITLE";
private static final int PRE_LOAD_ITEM_OFFSET = 2;
private int mSiteId = -1;
private String mSiteTitle = null;
private SiteService mSiteService;
private PullToRefreshLayout mPtrLayout;
private ListView mArticleListView;
private ProgressBar mProgressBar;
private int mPage = 1;
private TimelineListAdapter mArticleListAdapter;
private APIRequestFinishListener<Collection<ListArticleObject>> mArticleListRequestListener;
private boolean mIsLoadingMore;
private boolean mIsLastPage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_site_article_list);
mSiteId = getIntent().getIntExtra(SITE_ID, -1);
mSiteTitle = getIntent().getStringExtra(SITE_TITLE);
if (mSiteTitle != null) {
setTitle(mSiteTitle);
}
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
mSiteService = new SiteService();
mArticleListAdapter = new TimelineListAdapter(this, false);
initView();
initRequestListener();
}
private void initRequestListener() {
mArticleListRequestListener = new APIRequestFinishListener<Collection<ListArticleObject>>() {
@Override
public void onRequestSuccess() {
mPtrLayout.setRefreshComplete();
}
@Override
public void onRequestFail(VolleyError error) {
Toast.makeText(SiteArticleListActivity.this, R.string.connection_failed, Toast.LENGTH_SHORT).show();
Log.d(TAG, "get article list faied: " + error.toString() + ", page: " + mPage);
mPtrLayout.setRefreshComplete();
mArticleListAdapter.setLoadingMore(false);
}
@Override
public void onGetResult(Collection<ListArticleObject> result) {
mArticleListAdapter.appendData(result);
mProgressBar.setVisibility(View.GONE);
mArticleListView.setVisibility(View.VISIBLE);
if (result.size() == 0) {
mIsLastPage = true;
}
mIsLoadingMore = false;
mArticleListAdapter.setLoadingMore(false);
Log.d(TAG, "successfully get article list, result.size: " + result.size() + ", page: " + mPage);
}
};
}
private void initView() {
mPtrLayout = (PullToRefreshLayout) findViewById(R.id.ptr_layout);
mArticleListView = (ListView) findViewById(R.id.article_list);
mProgressBar = (ProgressBar) findViewById(R.id.loading_progress);
mArticleListView.setAdapter(mArticleListAdapter);
mArticleListView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView absListView, int state) {
if (state == SCROLL_STATE_IDLE) {
mArticleListAdapter.setOnFling(false);
mArticleListAdapter.notifyDataSetChanged();
} else {
mArticleListAdapter.setOnFling(true);
}
}
@Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount == totalItemCount - PRE_LOAD_ITEM_OFFSET && totalItemCount > 0
&& !mIsLoadingMore && !mIsLastPage) {
mIsLoadingMore = true;
loadMoreArticleList();
}
}
});
mArticleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ListArticleObject article = (ListArticleObject) mArticleListAdapter.getItem(i);
Intent articleIntent = new Intent(SiteArticleListActivity.this, ArticleActivity.class);
articleIntent.putExtra(ArticleActivity.ARTICLE_ID, article.articleId);
startActivity(articleIntent);
}
});
initPtrLayout();
}
private void initPtrLayout() {
Options.Builder ptrOptions = Options.create();
ptrOptions.refreshOnUp(true);
ptrOptions.scrollDistance(0.4f);
ActionBarPullToRefresh.from(this).theseChildrenArePullable(R.id.article_list, R.id.loading_layout).options(ptrOptions.build()).
listener(new OnRefreshListener() {
@Override
public void onRefreshStarted(View view) {
resetArticleList();
}
}).setup(mPtrLayout);
}
private void resetArticleList() {
if (!Utils.isNetworkConnected(this)) {
Toast.makeText(SiteArticleListActivity.this, R.string.connection_failed, Toast.LENGTH_SHORT).show();
}
mProgressBar.setVisibility(View.VISIBLE);
mArticleListView.setVisibility(View.GONE);
mArticleListAdapter.clearData();
mPage = 1;
mIsLastPage = false;
mIsLoadingMore = false;
mPtrLayout.setRefreshing(true);
mSiteService.loadSiteArticleList(mSiteId, mPage, mArticleListRequestListener);
}
private void loadMoreArticleList() {
if (!Utils.isNetworkConnected(this)) {
Toast.makeText(SiteArticleListActivity.this, R.string.connection_failed, Toast.LENGTH_SHORT).show();
}
mIsLoadingMore = true;
mPage++;
mArticleListAdapter.setLoadingMore(true);
mSiteService.loadSiteArticleList(mSiteId, mPage, mArticleListRequestListener);
}
@Override
protected void onResume() {
super.onResume();
resetArticleList();
}
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.site_article_list, menu);
// return true;
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// // Handle action bar item clicks here. The action bar will
// // automatically handle clicks on the Home/Up button, so long
// // as you specify a parent activity in AndroidManifest.xml.
// int id = item.getItemId();
// if (id == android.R.id.home) {
// super.onBackPressed();
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
}
| monoandroid/MonoReader/app/src/main/java/cn/ragnarok/monoreader/app/ui/activity/SiteArticleListActivity.java | package cn.ragnarok.monoreader.app.ui.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.VolleyError;
import java.util.Collection;
import cn.ragnarok.monoreader.api.base.APIRequestFinishListener;
import cn.ragnarok.monoreader.api.object.ListArticleObject;
import cn.ragnarok.monoreader.api.service.SiteService;
import cn.ragnarok.monoreader.app.R;
import cn.ragnarok.monoreader.app.ui.adapter.TimelineListAdapter;
import cn.ragnarok.monoreader.app.ui.fragment.TimelineFragment;
import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.Options;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
public class SiteArticleListActivity extends Activity {
public static final String TAG = "Mono.SiteArticleListActivity";
public static final String SITE_ID = "SITE_ID";
public static final String SITE_TITLE = "SITE_TITLE";
private static final int PRE_LOAD_ITEM_OFFSET = 2;
private int mSiteId = -1;
private String mSiteTitle = null;
private SiteService mSiteService;
private PullToRefreshLayout mPtrLayout;
private ListView mArticleListView;
private ProgressBar mProgressBar;
private int mPage = 1;
private TimelineListAdapter mArticleListAdapter;
private APIRequestFinishListener<Collection<ListArticleObject>> mArticleListRequestListener;
private boolean mIsLoadingMore;
private boolean mIsLastPage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_site_article_list);
mSiteId = getIntent().getIntExtra(SITE_ID, -1);
mSiteTitle = getIntent().getStringExtra(SITE_TITLE);
if (mSiteTitle != null) {
setTitle(mSiteTitle);
}
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
mSiteService = new SiteService();
mArticleListAdapter = new TimelineListAdapter(this, false);
initView();
initRequestListener();
resetArticleList();
resetArticleList();
}
private void initRequestListener() {
mArticleListRequestListener = new APIRequestFinishListener<Collection<ListArticleObject>>() {
@Override
public void onRequestSuccess() {
}
@Override
public void onRequestFail(VolleyError error) {
Toast.makeText(SiteArticleListActivity.this, R.string.connection_failed, Toast.LENGTH_SHORT).show();
Log.d(TAG, "get article list faied: " + error.toString() + ", page: " + mPage);
mArticleListAdapter.setLoadingMore(false);
}
@Override
public void onGetResult(Collection<ListArticleObject> result) {
mPtrLayout.setRefreshComplete();
mArticleListAdapter.appendData(result);
mProgressBar.setVisibility(View.GONE);
mArticleListView.setVisibility(View.VISIBLE);
if (result.size() == 0) {
mIsLastPage = true;
}
mIsLoadingMore = false;
mArticleListAdapter.setLoadingMore(false);
Log.d(TAG, "successfully get article list, result.size: " + result.size() + ", page: " + mPage);
}
};
}
private void initView() {
mPtrLayout = (PullToRefreshLayout) findViewById(R.id.ptr_layout);
mArticleListView = (ListView) findViewById(R.id.article_list);
mProgressBar = (ProgressBar) findViewById(R.id.loading_progress);
mArticleListView.setAdapter(mArticleListAdapter);
mArticleListView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView absListView, int state) {
if (state == SCROLL_STATE_IDLE) {
mArticleListAdapter.setOnFling(false);
mArticleListAdapter.notifyDataSetChanged();
} else {
mArticleListAdapter.setOnFling(true);
}
}
@Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount == totalItemCount - PRE_LOAD_ITEM_OFFSET && totalItemCount > 0
&& !mIsLoadingMore && !mIsLastPage) {
mIsLoadingMore = true;
loadMoreArticleList();
}
}
});
mArticleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ListArticleObject article = (ListArticleObject) mArticleListAdapter.getItem(i);
Intent articleIntent = new Intent(SiteArticleListActivity.this, ArticleActivity.class);
articleIntent.putExtra(ArticleActivity.ARTICLE_ID, article.articleId);
//startActivity(articleIntent);
startActivityForResult(articleIntent, ArticleActivity.FAV_SET);
}
});
initPtrLayout();
}
private void initPtrLayout() {
Options.Builder ptrOptions = Options.create();
ptrOptions.refreshOnUp(true);
ptrOptions.scrollDistance(0.4f);
ActionBarPullToRefresh.from(this).theseChildrenArePullable(R.id.article_list, R.id.loading_layout).options(ptrOptions.build()).
listener(new OnRefreshListener() {
@Override
public void onRefreshStarted(View view) {
resetArticleList();
}
}).setup(mPtrLayout);
}
private void resetArticleList() {
mProgressBar.setVisibility(View.VISIBLE);
mArticleListView.setVisibility(View.GONE);
mArticleListAdapter.clearData();
mPage = 1;
mIsLastPage = false;
mIsLoadingMore = false;
mPtrLayout.setRefreshing(true);
mSiteService.loadSiteArticleList(mSiteId, mPage, mArticleListRequestListener);
}
private void loadMoreArticleList() {
mIsLoadingMore = true;
mPage++;
mArticleListAdapter.setLoadingMore(true);
mSiteService.loadSiteArticleList(mSiteId, mPage, mArticleListRequestListener);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.site_article_list, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == android.R.id.home) {
super.onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| little fixed
| monoandroid/MonoReader/app/src/main/java/cn/ragnarok/monoreader/app/ui/activity/SiteArticleListActivity.java | little fixed | <ide><path>onoandroid/MonoReader/app/src/main/java/cn/ragnarok/monoreader/app/ui/activity/SiteArticleListActivity.java
<ide> import cn.ragnarok.monoreader.app.R;
<ide> import cn.ragnarok.monoreader.app.ui.adapter.TimelineListAdapter;
<ide> import cn.ragnarok.monoreader.app.ui.fragment.TimelineFragment;
<add>import cn.ragnarok.monoreader.app.util.Utils;
<ide> import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
<ide> import uk.co.senab.actionbarpulltorefresh.library.Options;
<ide> import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
<ide>
<ide> initView();
<ide> initRequestListener();
<del> resetArticleList();
<del>
<del> resetArticleList();
<add>
<ide> }
<ide>
<ide> private void initRequestListener() {
<ide> mArticleListRequestListener = new APIRequestFinishListener<Collection<ListArticleObject>>() {
<ide> @Override
<ide> public void onRequestSuccess() {
<del>
<add> mPtrLayout.setRefreshComplete();
<ide> }
<ide>
<ide> @Override
<ide> public void onRequestFail(VolleyError error) {
<ide> Toast.makeText(SiteArticleListActivity.this, R.string.connection_failed, Toast.LENGTH_SHORT).show();
<ide> Log.d(TAG, "get article list faied: " + error.toString() + ", page: " + mPage);
<add> mPtrLayout.setRefreshComplete();
<ide> mArticleListAdapter.setLoadingMore(false);
<ide> }
<ide>
<ide> @Override
<ide> public void onGetResult(Collection<ListArticleObject> result) {
<del> mPtrLayout.setRefreshComplete();
<add>
<ide> mArticleListAdapter.appendData(result);
<ide> mProgressBar.setVisibility(View.GONE);
<ide> mArticleListView.setVisibility(View.VISIBLE);
<ide> }
<ide> mIsLoadingMore = false;
<ide> mArticleListAdapter.setLoadingMore(false);
<add>
<ide> Log.d(TAG, "successfully get article list, result.size: " + result.size() + ", page: " + mPage);
<ide> }
<ide> };
<ide> ListArticleObject article = (ListArticleObject) mArticleListAdapter.getItem(i);
<ide> Intent articleIntent = new Intent(SiteArticleListActivity.this, ArticleActivity.class);
<ide> articleIntent.putExtra(ArticleActivity.ARTICLE_ID, article.articleId);
<del> //startActivity(articleIntent);
<del> startActivityForResult(articleIntent, ArticleActivity.FAV_SET);
<add> startActivity(articleIntent);
<add>
<ide> }
<ide> });
<ide>
<ide>
<ide>
<ide> private void resetArticleList() {
<add> if (!Utils.isNetworkConnected(this)) {
<add> Toast.makeText(SiteArticleListActivity.this, R.string.connection_failed, Toast.LENGTH_SHORT).show();
<add> }
<ide> mProgressBar.setVisibility(View.VISIBLE);
<ide> mArticleListView.setVisibility(View.GONE);
<ide> mArticleListAdapter.clearData();
<ide> }
<ide>
<ide> private void loadMoreArticleList() {
<add> if (!Utils.isNetworkConnected(this)) {
<add> Toast.makeText(SiteArticleListActivity.this, R.string.connection_failed, Toast.LENGTH_SHORT).show();
<add> }
<ide> mIsLoadingMore = true;
<ide> mPage++;
<ide> mArticleListAdapter.setLoadingMore(true);
<ide> @Override
<ide> protected void onResume() {
<ide> super.onResume();
<del> }
<del>
<del> @Override
<del> public boolean onCreateOptionsMenu(Menu menu) {
<del> // Inflate the menu; this adds items to the action bar if it is present.
<del> getMenuInflater().inflate(R.menu.site_article_list, menu);
<del> return true;
<del> }
<del>
<del> @Override
<del> public boolean onOptionsItemSelected(MenuItem item) {
<del> // Handle action bar item clicks here. The action bar will
<del> // automatically handle clicks on the Home/Up button, so long
<del> // as you specify a parent activity in AndroidManifest.xml.
<del> int id = item.getItemId();
<del> if (id == android.R.id.home) {
<del> super.onBackPressed();
<del> return true;
<del> }
<del> return super.onOptionsItemSelected(item);
<del> }
<add> resetArticleList();
<add> }
<add>
<add>// @Override
<add>// public boolean onCreateOptionsMenu(Menu menu) {
<add>// // Inflate the menu; this adds items to the action bar if it is present.
<add>// getMenuInflater().inflate(R.menu.site_article_list, menu);
<add>// return true;
<add>// }
<add>//
<add>// @Override
<add>// public boolean onOptionsItemSelected(MenuItem item) {
<add>// // Handle action bar item clicks here. The action bar will
<add>// // automatically handle clicks on the Home/Up button, so long
<add>// // as you specify a parent activity in AndroidManifest.xml.
<add>// int id = item.getItemId();
<add>// if (id == android.R.id.home) {
<add>// super.onBackPressed();
<add>// return true;
<add>// }
<add>// return super.onOptionsItemSelected(item);
<add>// }
<ide> } |
|
JavaScript | apache-2.0 | 86b92db08a6b7db2d464acdf9a05804a8f643fdd | 0 | michaelliao/itranswarp.js,michaelliao/itranswarp.js,michaelliao/itranswarp.js | // itranswarp.js
function add_sponsor(selector, width, height, name, img_src, link) {
var
stl = 'width:' + width + 'px;height:' + height + 'px;',
s = '<div style="float:left;margin:0 1px 1px 0;' + stl + '">';
if (arguments.length === 4) {
s = s + name;
} else {
s = s + '<a target="_blank" href="' + link + '">';
s = s + '<img src="' + img_src + '">';
s = s + '</a>';
}
s = s + '</div>';
$(selector).append(s);
}
function deleteTopic(id) {
if (confirm('Delete this topic?')) {
postJSON('/api/topics/' + id + '/delete', function (err, result) {
if (err) {
alert(err.message || err);
} else {
location.assign('/discuss');
}
});
}
}
function deleteReply(id) {
if (confirm('Delete this reply?')) {
postJSON('/api/replies/' + id + '/delete', function (err, result) {
if (err) {
alert(err.message || err);
} else {
refresh();
}
});
}
}
function getCookie(key) {
var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
return keyValue ? keyValue[2] : null;
}
function setCookie(key, value, maxAgeInSec) {
var d = new Date(new Date().getTime() + maxAgeInSec * 1000);
document.cookie = key + '=' + value + ';path=/;expires=' + d.toGMTString() + (location.protocol === 'https' ? ';secure' : '');
}
function deleteCookie(key) {
var d = new Date(0);
document.cookie = key + '=deleted;path=/;expires=' + d.toGMTString() + (location.protocol === 'https' ? ';secure' : '');
}
function message(title, msg, isHtml, autoClose) {
if ($('#modal-message').length==0) {
$('body').append('<div id="modal-message" class="uk-modal"><div class="uk-modal-dialog">' +
'<button type="button" class="uk-modal-close uk-close"></button>' +
'<div class="uk-modal-header"></div>' +
'<p class="x-message">msg</p>' +
'</div></div>');
}
var $m = $('#modal-message');
$m.find('div.uk-modal-header').text(title || 'Message');
if (isHtml) {
$m.find('p.x-message').html(msg || '');
}
else {
$m.find('p.x-message').text(msg || '');
}
var modal = UIkit.modal('#modal-message');
modal.show();
}
function _get_code(tid) {
var
$pre = $('#pre-' + tid),
$post = $('#post-' + tid),
$textarea = $('#textarea-' + tid);
return $pre.text() + $textarea.val() + '\n' + ($post.length === 0 ? '' : $post.text());
}
function run_javascript(tid, btn) {
var code = _get_code(tid);
(function () {
try {
eval('(function() {\n' + code + '\n})();');
}
catch (e) {
message('错误', '<p>JavaScript代码执行出错:</p><pre>' + String(e) + '</pre>', true, true);
}
})();
}
function run_html(tid, btn) {
var code = _get_code(tid);
(function () {
var w = window.open('about:blank', 'Online Practice', 'width=640,height=480,resizeable=1,scrollbars=1');
w.document.write(code);
w.document.close();
})();
}
function run_sql(tid, btn) {
if (typeof alasql === undefined) {
message('错误', '<p>JavaScript嵌入式SQL引擎尚未加载完成,请稍后再试或者刷新页面!</p>', true, true);
return;
}
var code = _get_code(tid);
var genTable = function (arr) {
if (arr.length === 0) {
return 'Empty result set';
}
var ths = _.keys(arr[0]);
var trs = _.map(arr, function (obj) {
return _.map(ths, function (key) {
return obj[key];
});
});
return '<table class="uk-table"><thead><tr>'
+ $.map(ths, function (th) {
var n = th.indexOf('_');
if (n > 1) {
th = th.substring(n+1);
}
return '<th>' + encodeHtml(th) + '</th>';
}).join('') + '</tr></thead><tbody>'
+ $.map(trs, function (tr) {
return '<tr>' + $.map(tr, function (td) {
if (td === undefined) {
td = 'NULL';
}
return '<td>' + encodeHtml(td) + '</td>';
}).join('') + '</tr>';
}).join('') + '</tbody></table>';
};
var showSqlResult = function (result) {
var $r = $(btn).next('div.x-sql-result');
if ($r.get(0) === undefined) {
$(btn).after('<div class="x-sql-result x-code uk-alert"></div>');
$r = $(btn).next('div.x-sql-result');
}
$r.removeClass('uk-alert-danger');
if (Array.isArray(result)) {
$r.html(genTable(result));
} else if (result && result.error) {
$r.addClass('uk-alert-danger');
$r.html($.map(result.message.split('\n'), function (s) {
return '<p>' + encodeHtml(s) + '</p>';
}).join(''));
} else {
$r.text(result);
}
};
(function () {
var
i, result, s = '',
lines = code.split('\n');
lines = _.map(lines, function (line) {
var n = line.indexOf('--');
if (n >= 0) {
line = line.substring(0, n);
}
return line;
});
lines = _.filter(lines, function (line) {
return line.trim() !== '';
});
// join:
for (i=0; i<lines.length; i++) {
s = s + lines[i] + '\n';
}
// split by ;
lines = _.filter(s.trim().split(';'), function (line) {
return line.trim() !== '';
});
// run each sql:
result = null;
for (i=0; i<lines.length; i++) {
s = lines[i];
try {
result = alasql(s);
} catch (e) {
result = {
error: true,
message: 'ERROR when execute SQL: ' + s + '\n' + String(e)
}
break;
}
}
showSqlResult(result);
})();
}
function run_python3(tid, btn) {
var
$pre = $('#pre-' + tid),
$post = $('#post-' + tid),
$textarea = $('#textarea-' + tid),
$button = $(btn),
$i = $button.find('i'),
code = $pre.text() + $textarea.val() + '\n' + ($post.length === 0 ? '' : $post.text());
$button.attr('disabled', 'disabled');
$i.addClass('uk-icon-spinner');
$i.addClass('uk-icon-spin');
$.post('http://local.liaoxuefeng.com:39093/run', $.param({
code: code
})).done(function (r) {
var output = '<pre style="word-break: break-all; word-wrap: break-word; white-space: pre-wrap;"><code>' + (r.output || '(空)').replace(/</g, '<').replace(/>/g, '>') + '</pre></code>';
message(r.error || 'Result', output, true);
}).fail(function (r) {
message('错误', '无法连接到Python代码运行助手。请检查<a target="_blank" href="/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432523496782e0946b0f454549c0888d05959b99860f000">本机的设置</a>。', true, true);
}).always(function () {
$i.removeClass('uk-icon-spinner');
$i.removeClass('uk-icon-spin');
$button.removeAttr('disabled');
});
}
function adjustTextareaHeight(t) {
var
$t = $(t),
lines = $t.val().split('\n').length;
if (lines < 9) {
lines = 9;
}
$t.attr('rows', '' + (lines + 1));
}
$(function() {
var tid = 0;
var trimCode = function (code) {
var ch;
while (code.length > 0) {
ch = code[0];
if (ch === '\n' || ch === '\r') {
code = code.substring(1);
}
else {
break;
}
}
while (code.length > 0) {
ch = code[code.length-1];
if (ch === '\n' || ch === '\r') {
code = code.substring(0, code.length-1);
}
else {
break;
}
}
return code + '\n';
};
var initPre = function (pre, fn_run) {
tid ++;
var
theId = 'online-run-code-' + tid,
$pre = $(pre),
$post = null,
codes = $pre.text().split('----', 3);
$pre.attr('id', 'pre-' + theId);
$pre.css('font-size', '14px');
$pre.css('margin-bottom', '0');
$pre.css('border-bottom', 'none');
$pre.css('padding', '6px');
$pre.css('border-bottom-left-radius', '0');
$pre.css('border-bottom-right-radius', '0');
$pre.wrap('<form class="uk-form uk-form-stack" action="#0"></form>');
$pre.after('<button type="button" onclick="' + fn_run + '(\'' + theId + '\', this)" class="uk-button uk-button-primary" style="margin-top:15px;"><i class="uk-icon-play"></i> Run</button>');
if (codes.length > 1) {
$pre.text(trimCode(codes[0]))
if (codes.length === 3) {
// add post:
$pre.after('<pre id="post-' + theId + '" style="font-size: 14px; margin-top: 0; border-top: 0; padding: 6px; border-top-left-radius: 0; border-top-right-radius: 0;"></pre>');
$post = $('#post-' + theId);
$post.text(trimCode(codes[2]));
}
}
$pre.after('<textarea id="textarea-' + theId + '" onkeyup="adjustTextareaHeight(this)" class="uk-width-1-1 x-codearea" rows="10" style="overflow: scroll; border-top-left-radius: 0; border-top-right-radius: 0;' + ($post === null ? '' : 'border-bottom-left-radius: 0; border-bottom-right-radius: 0;') + '"></textarea>');
if (codes.length > 1) {
$('#textarea-' + theId).val(trimCode(codes[1]));
adjustTextareaHeight($('#textarea-' + theId).get(0));
}
};
$('pre.x-javascript').each(function () {
initPre(this, 'run_javascript');
});
$('pre.x-html').each(function () {
initPre(this, 'run_html');
});
$('pre.x-sql').each(function () {
initPre(this, 'run_sql');
});
$('pre.x-python3').each(function () {
initPre(this, 'run_python3');
});
});
function initCommentArea(ref_type, ref_id, tag) {
$('#x-comment-area').html($('#tplCommentArea').html());
var $makeComment = $('#comment-make-button');
var $commentForm = $('#comment-form');
var $postComment = $commentForm.find('button[type=submit]');
var $cancelComment = $commentForm.find('button.x-cancel');
$makeComment.click(function () {
$commentForm.showFormError();
$commentForm.show();
$commentForm.find('div.x-textarea').html('<textarea></textarea>');
var htmleditor = UIkit.htmleditor($commentForm.find('textarea').get(0), {
mode: 'split',
maxsplitsize: 600,
markdown: true
});
$makeComment.hide();
});
$cancelComment.click(function () {
$commentForm.find('div.x-textarea').html('');
$commentForm.hide();
$makeComment.show();
});
$commentForm.submit(function (e) {
e.preventDefault();
$commentForm.postJSON('/api/comments/' + ref_type + '/' + ref_id, {
tag: tag,
name: $commentForm.find('input[name=name]').val(),
content: $commentForm.find('textarea').val()
}, function (err, result) {
if (err) {
return;
}
refresh('#comments');
});
});
}
var signinModal = null;
function showSignin(forceModal) {
if (g_signins.length === 1 && !forceModal) {
return authFrom(g_signins[0].id);
}
if (signinModal === null) {
signinModal = UIkit.modal('#modal-signin', {
bgclose: false,
center: true
});
}
signinModal.show();
}
// JS Template:
function Template(tpl) {
var
fn,
match,
code = ['var r=[];\nvar _html = function (str) { return str.replace(/&/g, \'&\').replace(/"/g, \'"\').replace(/\'/g, \''\').replace(/</g, \'<\').replace(/>/g, \'>\'); };'],
re = /\{\s*([a-zA-Z\.\_0-9()]+)(\s*\|\s*safe)?\s*\}/m,
addLine = function (text) {
code.push('r.push(\'' + text.replace(/\'/g, '\\\'').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '\');');
};
while (match = re.exec(tpl)) {
if (match.index > 0) {
addLine(tpl.slice(0, match.index));
}
if (match[2]) {
code.push('r.push(String(this.' + match[1] + '));');
}
else {
code.push('r.push(_html(String(this.' + match[1] + ')));');
}
tpl = tpl.substring(match.index + match[0].length);
}
addLine(tpl);
code.push('return r.join(\'\');');
fn = new Function(code.join('\n'));
this.render = function (model) {
return fn.apply(model);
};
}
// load topics as comments:
var
tplComment = null,
tplCommentReply = null,
tplCommentInfo = null;
function buildComments(data) {
if (tplComment === null) {
tplComment = new Template($('#tplComment').html());
}
if (tplCommentReply === null) {
tplCommentReply = new Template($('#tplCommentReply').html());
}
if (tplCommentInfo === null) {
tplCommentInfo = new Template($('#tplCommentInfo').html());
}
if (data.topics.length === 0) {
return '<p>No comment yet.</p>';
}
var i, j, topic, reply, s, L = [], page = data.page;
for (i=0; i<data.topics.length; i++) {
topic = data.topics[i];
L.push('<li>');
L.push(tplComment.render(topic));
L.push('<ul>')
if (topic.replies.length > 0) {
for (j=0; j<topic.replies.length; j++) {
reply = topic.replies[j];
L.push('<li>');
L.push(tplCommentReply.render(reply));
L.push('</li>');
}
}
L.push(tplCommentInfo.render(topic));
L.push('</ul>');
L.push('</li>');
}
return L.join('');
}
function ajaxLoadComments(insertIntoId, ref_id, page_index) {
var errorHtml = 'Error when loading. <a href="#0" onclick="ajaxLoadComments(\'' + insertIntoId + '\', \'' + ref_id + '\', ' + page_index + ')">Retry</a>';
$insertInto = $('#' + insertIntoId);
$insertInto.html('<i class="uk-icon-spinner uk-icon-spin"></i> Loading...');
$.getJSON('/api/ref/' + ref_id + '/topics?page=' + page_index).done(function(data) {
if (data.error) {
$insertInto.html(errorHtml);
return;
}
// build comment list:
$insertInto.html(buildComments(data));
$insertInto.find('.x-auto-content').each(function () {
makeCollapsable(this, 400);
});
}).fail(function() {
$insertInto.html(errorHtml);
});
}
var tmp_collapse = 1;
function makeCollapsable(obj, max_height) {
var $o = $(obj);
if ($o.height() <= (max_height + 60)) {
$o.show();
return;
}
var maxHeight = max_height + 'px';
$o.css('max-height', maxHeight);
$o.css('overflow', 'hidden');
$o.after('<p style="padding-left: 75px">' +
'<a href="#0"><i class="uk-icon-chevron-down"></i> Read More</a>' +
'<a href="#0" style="display:none"><i class="uk-icon-chevron-up"></i> Collapse</a>' +
'</p>');
var aName = 'COLLAPSE-' + tmp_collapse;
tmp_collapse ++;
$o.parent().before('<div class="x-anchor"><a name="' + aName + '"></a></div>')
var $p = $o.next();
var $aDown = $p.find('a:first');
var $aUp = $p.find('a:last');
$aDown.click(function () {
$o.css('max-height', 'none');
$aDown.hide();
$aUp.show();
});
$aUp.click(function () {
$o.css('max-height', maxHeight);
$aUp.hide();
$aDown.show();
location.assign('#' + aName);
});
$o.show();
}
function loadComments(ref_id) {
$(function () {
var
isCommentsLoaded = false,
$window = $(window),
targetOffset = $('#x-comment-list').get(0).offsetTop,
checkOffset = function () {
if (!isCommentsLoaded && (window.pageYOffset + window.innerHeight >= targetOffset)) {
isCommentsLoaded = true;
$window.off('scroll', checkOffset);
ajaxLoadComments('x-comment-list', ref_id, 1);
}
};
$window.scroll(checkOffset);
checkOffset();
});
}
$(function() {
$('.x-auto-content').each(function () {
makeCollapsable(this, 300);
});
});
if (! window.console) {
window.console = {
log: function(s) {
}
};
}
if (! String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
if (! Number.prototype.toDateTime) {
var replaces = {
'yyyy': function(dt) {
return dt.getFullYear().toString();
},
'yy': function(dt) {
return (dt.getFullYear() % 100).toString();
},
'MM': function(dt) {
var m = dt.getMonth() + 1;
return m < 10 ? '0' + m : m.toString();
},
'M': function(dt) {
var m = dt.getMonth() + 1;
return m.toString();
},
'dd': function(dt) {
var d = dt.getDate();
return d < 10 ? '0' + d : d.toString();
},
'd': function(dt) {
var d = dt.getDate();
return d.toString();
},
'hh': function(dt) {
var h = dt.getHours();
return h < 10 ? '0' + h : h.toString();
},
'h': function(dt) {
var h = dt.getHours();
return h.toString();
},
'mm': function(dt) {
var m = dt.getMinutes();
return m < 10 ? '0' + m : m.toString();
},
'm': function(dt) {
var m = dt.getMinutes();
return m.toString();
},
'ss': function(dt) {
var s = dt.getSeconds();
return s < 10 ? '0' + s : s.toString();
},
's': function(dt) {
var s = dt.getSeconds();
return s.toString();
},
'a': function(dt) {
var h = dt.getHours();
return h < 12 ? 'AM' : 'PM';
}
};
var token = /([a-zA-Z]+)/;
Number.prototype.toDateTime = function(format) {
var fmt = format || 'yyyy-MM-dd hh:mm:ss'
var dt = new Date(this);
var arr = fmt.split(token);
for (var i=0; i<arr.length; i++) {
var s = arr[i];
if (s && s in replaces) {
arr[i] = replaces[s](dt);
}
}
return arr.join('');
};
Number.prototype.toSmartDate = function () {
return toSmartDate(this);
};
}
function encodeHtml(str) {
return String(str)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
function toSmartDate(timestamp) {
if (typeof(timestamp)==='string') {
timestamp = parseInt(timestamp);
}
if (isNaN(timestamp)) {
return '';
}
var
today = new Date(g_time),
now = today.getTime(),
s = '1分钟前',
t = now - timestamp;
if (t > 604800000) {
// 1 week ago:
var that = new Date(timestamp);
var
y = that.getFullYear(),
m = that.getMonth() + 1,
d = that.getDate(),
hh = that.getHours(),
mm = that.getMinutes();
s = y===today.getFullYear() ? '' : y + '-';
s = s + m + '-' + d + ' ' + hh + ':' + (mm < 10 ? '0' : '') + mm;
}
else if (t >= 86400000) {
// 1-6 days ago:
s = Math.floor(t / 86400000) + '天前';
}
else if (t >= 3600000) {
// 1-23 hours ago:
s = Math.floor(t / 3600000) + '小时前';
}
else if (t >= 60000) {
s = Math.floor(t / 60000) + '分钟前';
}
return s;
}
// parse query string as object:
function parseQueryString() {
var
q = location.search,
r = {},
i, pos, s, qs;
if (q && q.charAt(0)==='?') {
qs = q.substring(1).split('&');
for (i=0; i<qs.length; i++) {
s = qs[i];
pos = s.indexOf('=');
if (pos <= 0) {
continue;
}
r[s.substring(0, pos)] = decodeURIComponent(s.substring(pos+1)).replace(/\+/g, ' ');
}
}
return r;
}
function gotoPage(i) {
var r = parseQueryString();
r.page = i;
location.assign('?' + $.param(r));
}
function refresh(anchor) {
var r = parseQueryString();
r.t = new Date().getTime();
location.assign('?' + $.param(r) + (anchor ? anchor : ''));
}
// extends jQuery.form:
$(function () {
$.fn.extend({
showFormError: function (err) {
return this.each(function () {
var
$form = $(this),
$alert = $form && $form.find('.uk-alert-danger'),
fieldName = err && err.data;
if (! $form.is('form')) {
console.error('Cannot call showFormError() on non-form object.');
return;
}
$form.find('input').removeClass('uk-form-danger');
$form.find('select').removeClass('uk-form-danger');
$form.find('textarea').removeClass('uk-form-danger');
if ($alert.length === 0) {
console.warn('Cannot find .uk-alert-danger element.');
return;
}
if (err) {
$alert.text(err.message ? err.message : (err.error ? err.error : err)).removeClass('uk-hidden').show();
if (($alert.offset().top - 60) < $(window).scrollTop()) {
$('html,body').animate({ scrollTop: $alert.offset().top - 60 });
}
if (fieldName) {
$form.find('[name=' + fieldName + ']').addClass('uk-form-danger');
}
}
else {
$alert.addClass('uk-hidden').hide();
$form.find('.uk-form-danger').removeClass('uk-form-danger');
}
});
},
showFormLoading: function (isLoading) {
return this.each(function () {
var
$form = $(this),
$submit = $form && $form.find('button[type=submit]'),
$buttons = $form && $form.find('button');
$i = $submit && $submit.find('i'),
iconClass = $i && $i.attr('class');
if (! $form.is('form')) {
console.error('Cannot call showFormLoading() on non-form object.');
return;
}
if (!iconClass || iconClass.indexOf('uk-icon') < 0) {
console.warn('Icon <i class="uk-icon-*>" not found.');
return;
}
if (isLoading) {
$buttons.attr('disabled', 'disabled');
$i && $i.addClass('uk-icon-spinner').addClass('uk-icon-spin');
}
else {
$buttons.removeAttr('disabled');
$i && $i.removeClass('uk-icon-spinner').removeClass('uk-icon-spin');
}
});
},
postJSON: function (url, data, callback) {
if (arguments.length===2) {
callback = data;
data = {};
}
return this.each(function () {
var $form = $(this);
$form.showFormError();
$form.showFormLoading(true);
_httpJSON('POST', url, data, function (err, r) {
if (err) {
$form.showFormError(err);
$form.showFormLoading(false);
}
if (callback) {
if (callback(err, r)) {
$form.showFormLoading(false);
}
}
});
});
}
});
});
// ajax submit form:
function _httpJSON(method, url, data, callback) {
var opt = {
type: method,
dataType: 'json'
};
if (method==='GET') {
opt.url = url + '?' + data;
}
if (method==='POST') {
opt.url = url;
opt.data = JSON.stringify(data || {});
opt.contentType = 'application/json';
}
$.ajax(opt).done(function (r) {
if (r && r.error) {
return callback(r);
}
return callback(null, r);
}).fail(function (jqXHR, textStatus) {
return callback({'error': 'http_bad_response', 'data': '' + jqXHR.status, 'message': '网络好像出问题了 (HTTP ' + jqXHR.status + ')'});
});
}
function getJSON(url, data, callback) {
if (arguments.length===2) {
callback = data;
data = {};
}
if (typeof (data)==='object') {
var arr = [];
$.each(data, function (k, v) {
arr.push(k + '=' + encodeURIComponent(v));
});
data = arr.join('&');
}
_httpJSON('GET', url, data, callback);
}
function postJSON(url, data, callback) {
if (arguments.length===2) {
callback = data;
data = {};
}
_httpJSON('POST', url, data, callback);
}
$(function() {
// activate navigation menu:
var xnav = $('meta[property="x-nav"]').attr('content');
xnav && xnav.trim() && $('#ul-navbar li a[href="' + xnav.trim() + '"]').parent().addClass('uk-active');
// init scroll:
var $window = $(window);
var $body = $('body');
var $gotoTop = $('div.x-goto-top');
// lazy load:
var lazyImgs = _.map($('img[data-src]').get(), function (i) {
return $(i);
});
var onScroll = function() {
var wtop = $window.scrollTop();
if (wtop > 1600) {
$gotoTop.show();
}
else {
$gotoTop.hide();
}
if (lazyImgs.length > 0) {
var wheight = $window.height();
var loadedIndex = [];
_.each(lazyImgs, function ($i, index) {
if ($i.offset().top - wtop < wheight) {
$i.attr('src', $i.attr('data-src'));
loadedIndex.unshift(index);
}
});
_.each(loadedIndex, function (index) {
lazyImgs.splice(index, 1);
});
}
};
$window.scroll(onScroll);
onScroll();
// go-top:
$gotoTop.click(function() {
$('html, body').animate({scrollTop: 0}, 1000);
});
// smart date:
$('.x-smartdate').each(function() {
var f = parseInt($(this).attr('date'));
$(this).text(toSmartDate(f));
});
// search query:
// var input_search = $('input.search-query');
// var old_width = input_search.css('width');
// input_search.bind('focusin', function() {
// input_search.animate({'width': '160px'}, 500);
// }).bind('focusout', function() {
// input_search.animate({'width': old_width}, 500);
// });
$('pre>code').each(function(i, block) {
if (! $(block).hasClass('lang-ascii')) {
hljs.highlightBlock(block);
}
});
/*
* set ascii style for markdown:
*
* ```ascii
* bla bla bla...
* ```
*/
$('code.lang-ascii').css('font-family', '"Courier New",Consolas,monospace').parent('pre').css('font-size', '12px').css('line-height', '12px').css('border', 'none').css('background-color', 'transparent');
// END
});
// signin with oauth:
var isDesktop = (function() {
var ua = navigator.userAgent.toLowerCase();
return ua.indexOf('windows nt')>=0 || ua.indexOf('macintosh')>=0;
})();
function onAuthCallback(err, user) {
if (signinModal !== null) {
signinModal.hide();
}
if (err) {
// handle error...
return;
}
g_user = {
id: user.id,
name: user.name,
image_url: user.image_url
};
// update user info:
$('.x-user-name').text(g_user.name);
// update css:
$('#x-doc-style').text('.x-display-if-signin {}\n.x-display-if-not-signin { display: none; }\n');
// reload if neccessary:
if (typeof(g_reload_after_signin) !== 'undefined' && g_reload_after_signin === true) {
location.reload();
}
else {
if (typeof(onAuthSuccess) === 'function') {
onAuthSuccess();
}
}
}
function authFrom(provider) {
var
url = '/auth/from/' + provider,
popupId = location.hostname.replace(/\./g, '_');
if (isDesktop) {
var w = window.open(url + '?jscallback=onAuthCallback', popupId, 'top=200,left=400,width=600,height=380,directories=no,menubar=no,toolbar=no,resizable=no');
}
else {
location.assign(url);
}
}
| www/static/themes/default/js/theme.js | // itranswarp.js
function add_sponsor(selector, width, height, name, img_src, link) {
var
stl = 'width:' + width + 'px;height:' + height + 'px;',
s = '<div style="float:left;margin:0 1px 1px 0;' + stl + '">';
if (arguments.length === 4) {
s = s + name;
} else {
s = s + '<a target="_blank" href="' + link + '">';
s = s + '<img src="' + img_src + '">';
s = s + '</a>';
}
s = s + '</div>';
$(selector).append(s);
}
function deleteTopic(id) {
if (confirm('Delete this topic?')) {
postJSON('/api/topics/' + id + '/delete', function (err, result) {
if (err) {
alert(err.message || err);
} else {
location.assign('/discuss');
}
});
}
}
function deleteReply(id) {
if (confirm('Delete this reply?')) {
postJSON('/api/replies/' + id + '/delete', function (err, result) {
if (err) {
alert(err.message || err);
} else {
refresh();
}
});
}
}
function getCookie(key) {
var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
return keyValue ? keyValue[2] : null;
}
function setCookie(key, value, maxAgeInSec) {
var d = new Date(new Date().getTime() + maxAgeInSec * 1000);
document.cookie = key + '=' + value + ';path=/;expires=' + d.toGMTString() + (location.protocol === 'https' ? ';secure' : '');
}
function deleteCookie(key) {
var d = new Date(0);
document.cookie = key + '=deleted;path=/;expires=' + d.toGMTString() + (location.protocol === 'https' ? ';secure' : '');
}
function message(title, msg, isHtml, autoClose) {
if ($('#modal-message').length==0) {
$('body').append('<div id="modal-message" class="uk-modal"><div class="uk-modal-dialog">' +
'<button type="button" class="uk-modal-close uk-close"></button>' +
'<div class="uk-modal-header"></div>' +
'<p class="x-message">msg</p>' +
'</div></div>');
}
var $m = $('#modal-message');
$m.find('div.uk-modal-header').text(title || 'Message');
if (isHtml) {
$m.find('p.x-message').html(msg || '');
}
else {
$m.find('p.x-message').text(msg || '');
}
var modal = UIkit.modal('#modal-message');
modal.show();
}
function _get_code(tid) {
var
$pre = $('#pre-' + tid),
$post = $('#post-' + tid),
$textarea = $('#textarea-' + tid);
return $pre.text() + $textarea.val() + '\n' + ($post.length === 0 ? '' : $post.text());
}
function run_javascript(tid, btn) {
var code = _get_code(tid);
(function () {
try {
eval('(function() {\n' + code + '\n})();');
}
catch (e) {
message('错误', '<p>JavaScript代码执行出错:</p><pre>' + String(e) + '</pre>', true, true);
}
})();
}
function run_html(tid, btn) {
var code = _get_code(tid);
(function () {
var w = window.open('about:blank', 'Online Practice', 'width=640,height=480,resizeable=1,scrollbars=1');
w.document.write(code);
w.document.close();
})();
}
function run_sql(tid, btn) {
if (typeof alasql === undefined) {
message('错误', '<p>JavaScript嵌入式SQL引擎尚未加载完成,请稍后再试或者刷新页面!</p>', true, true);
return;
}
var code = _get_code(tid);
var genTable = function (arr) {
if (arr.length === 0) {
return 'Empty result set';
}
var ths = _.keys(arr[0]);
var trs = _.map(arr, function (obj) {
return _.map(ths, function (key) {
return obj[key];
});
});
return '<table class="uk-table"><thead><tr>'
+ $.map(ths, function (th) {
var n = th.indexOf('_');
if (n > 1) {
th = th.substring(n+1);
}
return '<th>' + encodeHtml(th) + '</th>';
}).join('') + '</tr></thead><tbody>'
+ $.map(trs, function (tr) {
return '<tr>' + $.map(tr, function (td) {
if (td === undefined) {
td = 'NULL';
}
return '<td>' + encodeHtml(td) + '</td>';
}).join('') + '</tr>';
}).join('') + '</tbody></table>';
};
var showSqlResult = function (result) {
var $r = $(btn).next('div.x-sql-result');
if ($r.get(0) === undefined) {
$(btn).after('<div class="x-sql-result x-code uk-alert"></div>');
$r = $(btn).next('div.x-sql-result');
}
$r.removeClass('uk-alert-danger');
if (Array.isArray(result)) {
$r.html(genTable(result));
} else if (result && result.error) {
$r.addClass('uk-alert-danger');
$r.html($.map(result.message.split('\n'), function (s) {
return '<p>' + encodeHtml(s) + '</p>';
}).join(''));
} else {
$r.text(result);
}
};
(function () {
var
i, result, s = '',
lines = code.split('\n');
lines = _.map(lines, function (line) {
var n = line.indexOf('--');
if (n >= 0) {
line = line.substring(0, n);
}
return line;
});
lines = _.filter(lines, function (line) {
return line.trim() !== '';
});
// join:
for (i=0; i<lines.length; i++) {
s = s + lines[i] + '\n';
}
// split by ;
lines = _.filter(s.trim().split(';'), function (line) {
return line.trim() !== '';
});
// run each sql:
result = null;
for (i=0; i<lines.length; i++) {
s = lines[i];
try {
result = alasql(s);
} catch (e) {
result = {
error: true,
message: 'ERROR when execute SQL: ' + s + '\n' + String(e)
}
break;
}
}
showSqlResult(result);
})();
}
function run_python3(tid, btn) {
var
$pre = $('#pre-' + tid),
$post = $('#post-' + tid),
$textarea = $('#textarea-' + tid),
$button = $(btn),
$i = $button.find('i'),
code = $pre.text() + $textarea.val() + '\n' + ($post.length === 0 ? '' : $post.text());
$button.attr('disabled', 'disabled');
$i.addClass('uk-icon-spinner');
$i.addClass('uk-icon-spin');
$.post('http://local.liaoxuefeng.com:39093/run', $.param({
code: code
})).done(function (r) {
var output = '<pre style="word-break: break-all; word-wrap: break-word; white-space: pre-wrap;"><code>' + (r.output || '(空)').replace(/</g, '<').replace(/>/g, '>') + '</pre></code>';
message(r.error || 'Result', output, true);
}).fail(function (r) {
message('错误', '无法连接到Python代码运行助手。请检查<a target="_blank" href="/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432523496782e0946b0f454549c0888d05959b99860f000">本机的设置</a>。', true, true);
}).always(function () {
$i.removeClass('uk-icon-spinner');
$i.removeClass('uk-icon-spin');
$button.removeAttr('disabled');
});
}
function adjustTextareaHeight(t) {
var
$t = $(t),
lines = $t.val().split('\n').length;
if (lines < 9) {
lines = 9;
}
$t.attr('rows', '' + (lines + 1));
}
$(function() {
var tid = 0;
var trimCode = function (code) {
var ch;
while (code.length > 0) {
ch = code[0];
if (ch === '\n' || ch === '\r') {
code = code.substring(1);
}
else {
break;
}
}
while (code.length > 0) {
ch = code[code.length-1];
if (ch === '\n' || ch === '\r') {
code = code.substring(0, code.length-1);
}
else {
break;
}
}
return code + '\n';
};
var initPre = function (pre, fn_run) {
tid ++;
var
theId = 'online-run-code-' + tid,
$pre = $(pre),
$post = null,
codes = $pre.text().split('----', 3);
$pre.attr('id', 'pre-' + theId);
$pre.css('font-size', '14px');
$pre.css('margin-bottom', '0');
$pre.css('border-bottom', 'none');
$pre.css('padding', '6px');
$pre.css('border-bottom-left-radius', '0');
$pre.css('border-bottom-right-radius', '0');
$pre.wrap('<form class="uk-form uk-form-stack" action="#0"></form>');
$pre.after('<button type="button" onclick="' + fn_run + '(\'' + theId + '\', this)" class="uk-button uk-button-primary" style="margin-top:15px;"><i class="uk-icon-play"></i> Run</button>');
if (codes.length > 1) {
$pre.text(trimCode(codes[0]))
if (codes.length === 3) {
// add post:
$pre.after('<pre id="post-' + theId + '" style="font-size: 14px; margin-top: 0; border-top: 0; padding: 6px; border-top-left-radius: 0; border-top-right-radius: 0;"></pre>');
$post = $('#post-' + theId);
$post.text(trimCode(codes[2]));
}
}
$pre.after('<textarea id="textarea-' + theId + '" onkeyup="adjustTextareaHeight(this)" class="uk-width-1-1 x-codearea" rows="10" style="overflow: scroll; border-top-left-radius: 0; border-top-right-radius: 0;' + ($post === null ? '' : 'border-bottom-left-radius: 0; border-bottom-right-radius: 0;') + '"></textarea>');
if (codes.length > 1) {
$('#textarea-' + theId).val(trimCode(codes[1]));
adjustTextareaHeight($('#textarea-' + theId).get(0));
}
};
$('pre.x-javascript').each(function () {
initPre(this, 'run_javascript');
});
$('pre.x-html').each(function () {
initPre(this, 'run_html');
});
$('pre.x-sql').each(function () {
initPre(this, 'run_sql');
});
$('pre.x-python3').each(function () {
initPre(this, 'run_python3');
});
});
function initCommentArea(ref_type, ref_id, tag) {
$('#x-comment-area').html($('#tplCommentArea').html());
var $makeComment = $('#comment-make-button');
var $commentForm = $('#comment-form');
var $postComment = $commentForm.find('button[type=submit]');
var $cancelComment = $commentForm.find('button.x-cancel');
$makeComment.click(function () {
$commentForm.showFormError();
$commentForm.show();
$commentForm.find('div.x-textarea').html('<textarea></textarea>');
var htmleditor = UIkit.htmleditor($commentForm.find('textarea').get(0), {
mode: 'split',
maxsplitsize: 600,
markdown: true
});
$makeComment.hide();
});
$cancelComment.click(function () {
$commentForm.find('div.x-textarea').html('');
$commentForm.hide();
$makeComment.show();
});
$commentForm.submit(function (e) {
e.preventDefault();
$commentForm.postJSON('/api/comments/' + ref_type + '/' + ref_id, {
tag: tag,
name: $commentForm.find('input[name=name]').val(),
content: $commentForm.find('textarea').val()
}, function (err, result) {
if (err) {
return;
}
refresh('#comments');
});
});
}
var signinModal = null;
function showSignin(forceModal) {
if (g_signins.length === 1 && !forceModal) {
return authFrom(g_signins[0].id);
}
if (signinModal === null) {
signinModal = UIkit.modal('#modal-signin', {
bgclose: false,
center: true
});
}
signinModal.show();
}
// JS Template:
function Template(tpl) {
var
fn,
match,
code = ['var r=[];\nvar _html = function (str) { return str.replace(/&/g, \'&\').replace(/"/g, \'"\').replace(/\'/g, \''\').replace(/</g, \'<\').replace(/>/g, \'>\'); };'],
re = /\{\s*([a-zA-Z\.\_0-9()]+)(\s*\|\s*safe)?\s*\}/m,
addLine = function (text) {
code.push('r.push(\'' + text.replace(/\'/g, '\\\'').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '\');');
};
while (match = re.exec(tpl)) {
if (match.index > 0) {
addLine(tpl.slice(0, match.index));
}
if (match[2]) {
code.push('r.push(String(this.' + match[1] + '));');
}
else {
code.push('r.push(_html(String(this.' + match[1] + ')));');
}
tpl = tpl.substring(match.index + match[0].length);
}
addLine(tpl);
code.push('return r.join(\'\');');
fn = new Function(code.join('\n'));
this.render = function (model) {
return fn.apply(model);
};
}
// load topics as comments:
var
tplComment = null,
tplCommentReply = null,
tplCommentInfo = null;
function buildComments(data) {
if (tplComment === null) {
tplComment = new Template($('#tplComment').html());
}
if (tplCommentReply === null) {
tplCommentReply = new Template($('#tplCommentReply').html());
}
if (tplCommentInfo === null) {
tplCommentInfo = new Template($('#tplCommentInfo').html());
}
if (data.topics.length === 0) {
return '<p>No comment yet.</p>';
}
var i, j, topic, reply, s, L = [], page = data.page;
for (i=0; i<data.topics.length; i++) {
topic = data.topics[i];
L.push('<li>');
L.push(tplComment.render(topic));
L.push('<ul>')
if (topic.replies.length > 0) {
for (j=0; j<topic.replies.length; j++) {
reply = topic.replies[j];
L.push('<li>');
L.push(tplCommentReply.render(reply));
L.push('</li>');
}
}
L.push(tplCommentInfo.render(topic));
L.push('</ul>');
L.push('</li>');
}
return L.join('');
}
function ajaxLoadComments(insertIntoId, ref_id, page_index) {
var errorHtml = 'Error when loading. <a href="#0" onclick="ajaxLoadComments(\'' + insertIntoId + '\', \'' + ref_id + '\', ' + page_index + ')">Retry</a>';
$insertInto = $('#' + insertIntoId);
$insertInto.html('<i class="uk-icon-spinner uk-icon-spin"></i> Loading...');
$.getJSON('/api/ref/' + ref_id + '/topics?page=' + page_index).done(function(data) {
if (data.error) {
$insertInto.html(errorHtml);
return;
}
// build comment list:
$insertInto.html(buildComments(data));
$insertInto.find('.x-auto-content').each(function () {
makeCollapsable(this, 400);
});
}).fail(function() {
$insertInto.html(errorHtml);
});
}
var tmp_collapse = 1;
function makeCollapsable(obj, max_height) {
var $o = $(obj);
if ($o.height() <= (max_height + 60)) {
$o.show();
return;
}
var maxHeight = max_height + 'px';
$o.css('max-height', maxHeight);
$o.css('overflow', 'hidden');
$o.after('<p style="padding-left: 75px">' +
'<a href="#0"><i class="uk-icon-chevron-down"></i> Read More</a>' +
'<a href="#0" style="display:none"><i class="uk-icon-chevron-up"></i> Collapse</a>' +
'</p>');
var aName = 'COLLAPSE-' + tmp_collapse;
tmp_collapse ++;
$o.parent().before('<div class="x-anchor"><a name="' + aName + '"></a></div>')
var $p = $o.next();
var $aDown = $p.find('a:first');
var $aUp = $p.find('a:last');
$aDown.click(function () {
$o.css('max-height', 'none');
$aDown.hide();
$aUp.show();
});
$aUp.click(function () {
$o.css('max-height', maxHeight);
$aUp.hide();
$aDown.show();
location.assign('#' + aName);
});
$o.show();
}
function loadComments(ref_id) {
$(function () {
var
isCommentsLoaded = false,
$window = $(window),
targetOffset = $('#x-comment-list').get(0).offsetTop,
checkOffset = function () {
if (!isCommentsLoaded && (window.pageYOffset + window.innerHeight >= targetOffset)) {
isCommentsLoaded = true;
$window.off('scroll', checkOffset);
ajaxLoadComments('x-comment-list', ref_id, 1);
}
};
$window.scroll(checkOffset);
checkOffset();
});
}
$(function() {
$('.x-auto-content').each(function () {
makeCollapsable(this, 300);
});
});
if (! window.console) {
window.console = {
log: function(s) {
}
};
}
if (! String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
if (! Number.prototype.toDateTime) {
var replaces = {
'yyyy': function(dt) {
return dt.getFullYear().toString();
},
'yy': function(dt) {
return (dt.getFullYear() % 100).toString();
},
'MM': function(dt) {
var m = dt.getMonth() + 1;
return m < 10 ? '0' + m : m.toString();
},
'M': function(dt) {
var m = dt.getMonth() + 1;
return m.toString();
},
'dd': function(dt) {
var d = dt.getDate();
return d < 10 ? '0' + d : d.toString();
},
'd': function(dt) {
var d = dt.getDate();
return d.toString();
},
'hh': function(dt) {
var h = dt.getHours();
return h < 10 ? '0' + h : h.toString();
},
'h': function(dt) {
var h = dt.getHours();
return h.toString();
},
'mm': function(dt) {
var m = dt.getMinutes();
return m < 10 ? '0' + m : m.toString();
},
'm': function(dt) {
var m = dt.getMinutes();
return m.toString();
},
'ss': function(dt) {
var s = dt.getSeconds();
return s < 10 ? '0' + s : s.toString();
},
's': function(dt) {
var s = dt.getSeconds();
return s.toString();
},
'a': function(dt) {
var h = dt.getHours();
return h < 12 ? 'AM' : 'PM';
}
};
var token = /([a-zA-Z]+)/;
Number.prototype.toDateTime = function(format) {
var fmt = format || 'yyyy-MM-dd hh:mm:ss'
var dt = new Date(this);
var arr = fmt.split(token);
for (var i=0; i<arr.length; i++) {
var s = arr[i];
if (s && s in replaces) {
arr[i] = replaces[s](dt);
}
}
return arr.join('');
};
Number.prototype.toSmartDate = function () {
return toSmartDate(this);
};
}
function encodeHtml(str) {
return String(str)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
function toSmartDate(timestamp) {
if (typeof(timestamp)==='string') {
timestamp = parseInt(timestamp);
}
if (isNaN(timestamp)) {
return '';
}
var
today = new Date(g_time),
now = today.getTime(),
s = '1分钟前',
t = now - timestamp;
if (t > 604800000) {
// 1 week ago:
var that = new Date(timestamp);
var
y = that.getFullYear(),
m = that.getMonth() + 1,
d = that.getDate(),
hh = that.getHours(),
mm = that.getMinutes();
s = y===today.getFullYear() ? '' : y + '-';
s = s + m + '-' + d + ' ' + hh + ':' + (mm < 10 ? '0' : '') + mm;
}
else if (t >= 86400000) {
// 1-6 days ago:
s = Math.floor(t / 86400000) + '天前';
}
else if (t >= 3600000) {
// 1-23 hours ago:
s = Math.floor(t / 3600000) + '小时前';
}
else if (t >= 60000) {
s = Math.floor(t / 60000) + '分钟前';
}
return s;
}
// parse query string as object:
function parseQueryString() {
var
q = location.search,
r = {},
i, pos, s, qs;
if (q && q.charAt(0)==='?') {
qs = q.substring(1).split('&');
for (i=0; i<qs.length; i++) {
s = qs[i];
pos = s.indexOf('=');
if (pos <= 0) {
continue;
}
r[s.substring(0, pos)] = decodeURIComponent(s.substring(pos+1)).replace(/\+/g, ' ');
}
}
return r;
}
function gotoPage(i) {
var r = parseQueryString();
r.page = i;
location.assign('?' + $.param(r));
}
function refresh(anchor) {
var r = parseQueryString();
r.t = new Date().getTime();
location.assign('?' + $.param(r) + (anchor ? anchor : ''));
}
// extends jQuery.form:
$(function () {
$.fn.extend({
showFormError: function (err) {
return this.each(function () {
var
$form = $(this),
$alert = $form && $form.find('.uk-alert-danger'),
fieldName = err && err.data;
if (! $form.is('form')) {
console.error('Cannot call showFormError() on non-form object.');
return;
}
$form.find('input').removeClass('uk-form-danger');
$form.find('select').removeClass('uk-form-danger');
$form.find('textarea').removeClass('uk-form-danger');
if ($alert.length === 0) {
console.warn('Cannot find .uk-alert-danger element.');
return;
}
if (err) {
$alert.text(err.message ? err.message : (err.error ? err.error : err)).removeClass('uk-hidden').show();
if (($alert.offset().top - 60) < $(window).scrollTop()) {
$('html,body').animate({ scrollTop: $alert.offset().top - 60 });
}
if (fieldName) {
$form.find('[name=' + fieldName + ']').addClass('uk-form-danger');
}
}
else {
$alert.addClass('uk-hidden').hide();
$form.find('.uk-form-danger').removeClass('uk-form-danger');
}
});
},
showFormLoading: function (isLoading) {
return this.each(function () {
var
$form = $(this),
$submit = $form && $form.find('button[type=submit]'),
$buttons = $form && $form.find('button');
$i = $submit && $submit.find('i'),
iconClass = $i && $i.attr('class');
if (! $form.is('form')) {
console.error('Cannot call showFormLoading() on non-form object.');
return;
}
if (!iconClass || iconClass.indexOf('uk-icon') < 0) {
console.warn('Icon <i class="uk-icon-*>" not found.');
return;
}
if (isLoading) {
$buttons.attr('disabled', 'disabled');
$i && $i.addClass('uk-icon-spinner').addClass('uk-icon-spin');
}
else {
$buttons.removeAttr('disabled');
$i && $i.removeClass('uk-icon-spinner').removeClass('uk-icon-spin');
}
});
},
postJSON: function (url, data, callback) {
if (arguments.length===2) {
callback = data;
data = {};
}
return this.each(function () {
var $form = $(this);
$form.showFormError();
$form.showFormLoading(true);
_httpJSON('POST', url, data, function (err, r) {
if (err) {
$form.showFormError(err);
$form.showFormLoading(false);
}
if (callback) {
if (callback(err, r)) {
$form.showFormLoading(false);
}
}
});
});
}
});
});
// ajax submit form:
function _httpJSON(method, url, data, callback) {
var opt = {
type: method,
dataType: 'json'
};
if (method==='GET') {
opt.url = url + '?' + data;
}
if (method==='POST') {
opt.url = url;
opt.data = JSON.stringify(data || {});
opt.contentType = 'application/json';
}
$.ajax(opt).done(function (r) {
if (r && r.error) {
return callback(r);
}
return callback(null, r);
}).fail(function (jqXHR, textStatus) {
return callback({'error': 'http_bad_response', 'data': '' + jqXHR.status, 'message': '网络好像出问题了 (HTTP ' + jqXHR.status + ')'});
});
}
function getJSON(url, data, callback) {
if (arguments.length===2) {
callback = data;
data = {};
}
if (typeof (data)==='object') {
var arr = [];
$.each(data, function (k, v) {
arr.push(k + '=' + encodeURIComponent(v));
});
data = arr.join('&');
}
_httpJSON('GET', url, data, callback);
}
function postJSON(url, data, callback) {
if (arguments.length===2) {
callback = data;
data = {};
}
_httpJSON('POST', url, data, callback);
}
$(function() {
// activate navigation menu:
var xnav = $('meta[property="x-nav"]').attr('content');
xnav && xnav.trim() && $('#ul-navbar li a[href="' + xnav.trim() + '"]').parent().addClass('uk-active');
// init scroll:
var $window = $(window);
var $body = $('body');
var $gotoTop = $('div.x-goto-top');
// lazy load:
var lazyImgs = _.map($('img[data-src]').get(), function (i) {
return $(i);
});
var onScroll = function() {
var wtop = $window.scrollTop();
if (wtop > 1600) {
$gotoTop.show();
}
else {
$gotoTop.hide();
}
if (lazyImgs.length > 0) {
var wheight = $window.height();
var loadedIndex = [];
_.each(lazyImgs, function ($i, index) {
if ($i.offset().top - wtop < wheight) {
$i.attr('src', $i.attr('data-src'));
loadedIndex.unshift(index);
}
});
_.each(loadedIndex, function (index) {
lazyImgs.splice(index, 1);
});
}
};
$window.scroll(onScroll);
onScroll();
// go-top:
$gotoTop.click(function() {
$('html, body').animate({scrollTop: 0}, 1000);
});
// smart date:
$('.x-smartdate').each(function() {
var f = parseInt($(this).attr('date'));
$(this).text(toSmartDate(f));
});
// search query:
// var input_search = $('input.search-query');
// var old_width = input_search.css('width');
// input_search.bind('focusin', function() {
// input_search.animate({'width': '160px'}, 500);
// }).bind('focusout', function() {
// input_search.animate({'width': old_width}, 500);
// });
hljs.initHighlighting();
/*
* set ascii style for markdown:
*
* ```ascii
* bla bla bla...
* ```
*/
$('code.lang-ascii').css('font-family', '"Courier New",Consolas,monospace').parent('pre').css('font-size', '12px').css('line-height', '12px').css('border', 'none').css('background-color', 'transparent');
// END
});
// signin with oauth:
var isDesktop = (function() {
var ua = navigator.userAgent.toLowerCase();
return ua.indexOf('windows nt')>=0 || ua.indexOf('macintosh')>=0;
})();
function onAuthCallback(err, user) {
if (signinModal !== null) {
signinModal.hide();
}
if (err) {
// handle error...
return;
}
g_user = {
id: user.id,
name: user.name,
image_url: user.image_url
};
// update user info:
$('.x-user-name').text(g_user.name);
// update css:
$('#x-doc-style').text('.x-display-if-signin {}\n.x-display-if-not-signin { display: none; }\n');
// reload if neccessary:
if (typeof(g_reload_after_signin) !== 'undefined' && g_reload_after_signin === true) {
location.reload();
}
else {
if (typeof(onAuthSuccess) === 'function') {
onAuthSuccess();
}
}
}
function authFrom(provider) {
var
url = '/auth/from/' + provider,
popupId = location.hostname.replace(/\./g, '_');
if (isDesktop) {
var w = window.open(url + '?jscallback=onAuthCallback', popupId, 'top=200,left=400,width=600,height=380,directories=no,menubar=no,toolbar=no,resizable=no');
}
else {
location.assign(url);
}
}
| disable highlight when use ascii
| www/static/themes/default/js/theme.js | disable highlight when use ascii | <ide><path>ww/static/themes/default/js/theme.js
<ide> // input_search.animate({'width': old_width}, 500);
<ide> // });
<ide>
<del> hljs.initHighlighting();
<add> $('pre>code').each(function(i, block) {
<add> if (! $(block).hasClass('lang-ascii')) {
<add> hljs.highlightBlock(block);
<add> }
<add> });
<ide>
<ide> /*
<ide> * set ascii style for markdown: |
|
JavaScript | apache-2.0 | edb90a8f438d09b1e4386ae465def30e68430f8b | 0 | ccwalkerjm/ironrockweb,ccwalkerjm/ironrockweb,ccwalkerjm/ironrockweb,ccwalkerjm/ironrockweb,ccwalkerjm/ironrockweb,ccwalkerjm/ironrockweb | "use strict";
var doc;
const standardYgap = 5;
const gapBelowHeader = 10;
const startingXPoint = 20;
const startingYPoint = 20;
const startingYFirstPagePoint = 50;
function CreatePDF(resp) {
console.log(resp);
doc = new jsPDF();
doc.setFontSize(12);
if (resp.insuranceType === 'motor') {
doc.text(20, 40, 'Motor Vehicle Insurance Proposal');
} else {
doc.text(20, 40, 'Home Insurance Proposal');
}
var logoCanvas = document.getElementById("canvas-logo");
var imgLogoData = logoCanvas.toDataURL('image/jpeg', 1.0);
doc.addImage(imgLogoData, 'JPG', 2, 2, 100, 30);
doc.setFontSize(10);
doc.setFont("times");
doc.setFontType("normal");
doc.text(150, 35, "Start date: " + resp.startDate);
doc.text(150, 40, 'Quote No: ' + resp.applicantQuoteNo);
//doc.text(startingXPoint, 30, 'Insurance for ' + resp.insuranceType);
doc.text(20, 80, 'Surname:');
doc.text(20, 85, 'First Name:');
doc.text(20, 90, 'Middle Name:');
doc.text(20, 95, 'Title:');
doc.text(20, 100, 'Occupation:');
doc.text(100, 80, 'Mothers Maiden Name: ');
doc.text(100, 85, 'Other Names/Aliases: ');
doc.text(100, 90, 'ID Type: ');
doc.text(100, 95, 'ID Number: ');
doc.text(100, 100, 'Expiration Date: ');
doc.text(100, 105, 'Source of Funds: ');
doc.text(20, 115, 'Street Number and Name: ');
doc.text(20, 125, 'City/Town/Postal Zone: ');
doc.text(20, 135, 'Parish: ');
doc.text(100, 115, 'TRN: ');
doc.text(100, 120, 'Email Address: ');
doc.text(100, 125, 'Mobile Number: ');
doc.text(100, 130, 'Home Number: ');
doc.text(100, 135, 'Work Number: ');
doc.text(20, 145, 'Street Number and Name: ');
doc.text(20, 155, 'City/Town/Postal Zone: ');
doc.text(20, 165, 'Parish ');
doc.text(100, 145, 'Date of Birth: ');
doc.text(100, 150, 'Place of Birth: ');
doc.text(100, 155, 'Nationality: ');
doc.text(20, 175, 'Company Name:');
doc.text(100, 175, 'Street Number and Name:');
doc.text(100, 185, 'Town');
doc.text(100, 190, 'Parish');
doc.setFontType("italic");
doc.text(50, 80, resp.applicantSurname);
doc.text(50, 85, resp.applicantFirstName);
doc.text(50, 90, resp.applicantMiddleName);
doc.text(50, 95, resp.applicantTitle);
doc.text(50, 100, resp.applicantOccupation);
doc.text(150, 80, resp.applicantMothersMaidenName);
doc.text(150, 85, resp.applicantAlias);
doc.text(150, 90, resp.applicantIDType);
doc.text(150, 95, resp.applicantIDnumber);
doc.text(150, 100, resp.applicationIDExpirationDate);
doc.text(150, 105, resp.SourceOfFunds);
doc.text(20, 120, resp.applicantHomeStreetName);
doc.text(20, 130, resp.applicantHomeTown);
doc.text(50, 135, resp.applicantHomeParish);
doc.text(150, 115, resp.applicantIDnumber);
doc.text(150, 120, resp.applicantEmailAddress);
doc.text(150, 125, resp.applicantMobileNumber);
doc.text(150, 130, resp.applicantHomeNumber);
doc.text(150, 135, resp.applicantWorkNumber);
if(resp.mailingAddressSame=="yes"){
doc.text(20, 150, resp.applicantHomeStreetName);
}else{
doc.text(20, 150, resp.applicantMailStreetName);
}
if(resp.mailingAddressSame=="yes"){
doc.text(20, 160, resp.applicantHomeTown);
}else{
doc.text(20, 160, resp.applicantMailTown);
}
if(resp.mailingAddressSame=="yes"){
doc.text(50, 165, resp.applicantHomeParish);
}else{
doc.text(50, 165, resp.applicantMailParish);
}
doc.text(20, 160, resp.applicantMailTown);
doc.text(50, 165, resp.applicantMailParish);
doc.text(150, 145, resp.applicantDateOfBirth);
doc.text(150, 150, resp.applicantPlaceOfBirth);
doc.text(150, 155, resp.applicantNationality);
doc.text(50, 175, resp.employerName);
doc.text(100, 180, resp.employerStreetName);
doc.text(150, 185, resp.employerTown);
doc.text(150, 190, resp.employerParish);
doc.setFontType("bold");
doc.setFontSize("10");
doc.text(20, 75, 'Name');
doc.text(20, 110, 'Home Address');
doc.text(20, 140, 'Mailing Address');
doc.text(20, 170, 'Employer Details');
doc.setFontSize("10");
doc.setFontType("bold");
doc.text(20, 195, "NB: Please submit the following:");
doc.setFontType("bold");
doc.text(20, 200, "** A power of attorney or a letter duly notarized");
doc.text(20, 205, "Proof of Address");
doc.text(20, 210, "Picture Identification(Insured an agent, where applicable)");
doc.text(20, 215, "TRN(if a driver's license is not being used)");
doc.text(20, 245, "Relation");
doc.text(60, 245, "Name of Relative");
doc.text(110, 245, "Address");
doc.setFontType("normal");
doc.text(20, 220, "Have you or any relative or close associate been entrusted with prominent public functions (e.g. Member of Parliament, ");
doc.text(20, 223, "Senate or Mayor, Senior Government Official, Judiciary, security forces)?");
doc.text(20, 230, "If yes, state the type of public office:");
doc.text(20, 240, "If yes to the above, please give the name and address of spouse and children");
if (resp.applicantRelativeInPublicOfficeName0) {
doc.text(20, 248, resp.applicantRelativeInPublicOfficeRelation0 ? resp.applicantRelativeInPublicOfficeRelation0 : "");
doc.text(60, 248, resp.applicantRelativeInPublicOfficeName0 ? resp.applicantRelativeInPublicOfficeName0 : "");
doc.text(150, 248, resp.applicantRelativeInPublicOfficeAddress0 ? resp.applicantRelativeInPublicOfficeAddress0 : "");
}
if (resp.vehicleRegistrationNo1) {
doc.text(20, 251, resp.applicantRelativeInPublicOfficeRelation ? resp.applicantRelativeInPublicOfficeRelation0 : "");
doc.text(60, 251, resp.applicantRelativeInPublicOfficeName0 ? resp.applicantRelativeInPublicOfficeName0 : "");
doc.text(110, 251, resp.applicantRelativeInPublicOfficeAddress0 ? resp.applicantRelativeInPublicOfficeAddress0 : "");
}
if (resp.vehicleRegistrationNo2) {
doc.text(20, 254, resp.applicantRelativeInPublicOfficeRelation ? resp.applicantRelativeInPublicOfficeRelation0 : "");
doc.text(60, 254, resp.applicantRelativeInPublicOfficeName0 ? resp.applicantRelativeInPublicOfficeName0 : "");
doc.text(110, 254, resp.applicantRelativeInPublicOfficeAddress0 ? resp.applicantRelativeInPublicOfficeAddress0 : "");
}
doc.setFontType("italic");
doc.text(20, 226, resp.applicantRelativeInPublicOffice ? resp.applicantRelativeInPublicOffice : "");
doc.text(20, 235, resp.applicantRelativeTypePublicOffice0 ? resp.applicantRelativeTypePublicOffice0 : "");
doc.setFontSize("8");
doc.setFontType("bold");
doc.text(20, 45, "DUTY TO DISCLOSE. This proposal must be completed, dated and signed by the proposer. When answering the questions on this form,");
doc.text(20, 48, " you must be honest and truthful. You have a duty under law to tell us anything known to you which is material to the questions asked as ");
doc.text(20, 51, "those answers will guide us in deciding whether to insure you or anyone else to be insured under the policy and on what terms. ");
doc.text(20, 54, "If you are in doubt as to whether a fact is relevant, you should state it. Your duty to make full and frank discourse occurs: (1) at the time ");
doc.text(20, 57, "of the time of proposing for insurance. (2) during the currency of the policy, if there are any changes or variations in the information given ");
doc.text(20, 60, "and (3) at each renewal.");
doc.text(20, 65, "FAILURE TO DISCLOSE. If you do not comply with these duties and answer our questions honestly, the company will be at liberty to ");
doc.text(20, 68, "treat your Policy as if it never existed and refuse to pay any claims you make under it.");
doc.addPage();
if (resp.insuranceType === 'motor') {
setMotorVehiclePages(resp);
} else {
setHomePropertyPages(resp);
}
lastPage(resp);
//doc.output('datauri');
doc.output('dataurlnewwindow');
//doc.save('Proposal' + resp.applicantQuoteNo + '.pdf');
}
function setMotorVehiclePages(resp) {
doc.setFontSize("10");
doc.setFontType("bold");
doc.text(20, 20, "Particulars Of Vehicles to Be Insured");
doc.setFontSize("7");
doc.text(20, 25, "Registration No.");
doc.text(42, 25, "Make and Model");
doc.text(62, 25, "SChassis & Engine No.");
doc.text(90, 25, "Year of Make");
doc.text(105, 25, "C.C. Rating");
doc.text(122, 25, "Seating");
doc.text(142, 25, "Type Of Body");
doc.text(162, 25, "Sum Insured");
doc.setFontType("normal")
if (resp.vehicleRegistrationNo0) {
doc.text(20, 30, resp.vehicleRegistrationNo0 ? resp.vehicleRegistrationNo0 : "");
doc.text(42, 30, resp.vehicleMake0 ? resp.vehicleMake0 : "");
doc.text(62, 30, resp.vehicleChassisNo0 ? resp.vehicleChassisNo0 : "");
doc.text(90, 30, resp.vehicleYear0 ? resp.vehicleYear0 : "");
doc.text(105, 30, "");
doc.text(122, 30, resp.vehicleBody0 ? resp.vehicleBody0 : "");
doc.text(142, 30, resp.vehicleType0 ? resp.vehicleType0 : "");
doc.text(162, 30, resp.QueryVehicleSumInsured ? resp.QueryVehicleSumInsured : "");
}
if (resp.vehicleRegistrationNo1) {
doc.text(20, 35, resp.vehicleRegistrationNo1 ? resp.vehicleRegistrationNo1 : "");
doc.text(42, 35, resp.vehicleMake1 ? resp.vehicleMake1 : "");
doc.text(62, 35, resp.vehicleChassisNo1 ? resp.vehicleChassisNo1 : "");
doc.text(90, 35, resp.vehicleYear1 ? resp.vehicleYear1 : "");
doc.text(105, 35, " ");
doc.text(122, 35, resp.vehicleBody1 ? resp.vehicleBody1 : "");
doc.text(142, 35, resp.vehicleType1 ? resp.vehicleType1 : "");
doc.text(162, 35, resp.QueryVehicleSumInsured ? resp.QueryVehicleSumInsured : "");
}
if (resp.vehicleRegistrationNo2) {
doc.text(20, 40, resp.vehicleRegistrationNo2 ? resp.vehicleRegistrationNo2 : "");
doc.text(42, 40, resp.vehicleMake2 ? resp.vehicleMake2 : "");
doc.text(62, 40, resp.vehicleChassisNo2 ? resp.vehicleChassisNo2 : "");
doc.text(90, 40, resp.vehicleYear2 ? resp.vehicleYear2 : "");
doc.text(105, 40, " ");
doc.text(122, 40, resp.vehicleBody2 ? resp.vehicleBody2 : "");
doc.text(142, 40, resp.vehicleType2 ? resp.vehicleType2 : "");
doc.text(162, 40, resp.QueryVehicleSumInsured ? resp.QueryVehicleSumInsured : "");
}
doc.setFontSize("8");
doc.setFontType("bold");
doc.text(20, 75, "NOTE: You are required to ensure that the Sum Insured is revised annually to reflect the current market value. ");
doc.text(20, 78, "Claims will be settled based on the market value at the time of the loss. For total losses you will be paid based in");
doc.text(20, 81, "time of the loss. For total losses you will be paid based on the market value or Policy Sum Insured whichever is lesser.");
doc.setFontSize("10");
doc.setFontType("bold");
doc.text(20, 85, "Lien Holder");
doc.text(20, 110, "Select cover required");
doc.setFontType("normal");
doc.text(20, 45, "Are you the owner of the vehicle(s) and is/are/they registered in your name?");
doc.text(20, 55, "If not, state the name and address of the owner:");
doc.text(20, 65, "Will a trailer be used?");
doc.text(20, 90, "Name in Full:");
doc.text(100, 90, "Street Number and Name:");
doc.text(100, 100, "Town:");
doc.text(100, 105, "Parish:");
doc.text(20, 120, "Please indicate if the vehicle is to be used as:");
doc.text(20, 130, "Is the vehicle fitted with an anti-theft device?");
doc.text(20, 140, "If yes, state the name, type of device and name of provider");
doc.text(20, 150, "Will you have regular custody of the vehicle?");
doc.text(20, 160, "If not, please provide details");
doc.text(20, 170, "Is the vehicle garaged at the Proposer's home address?");
doc.text(20, 180, "If not, please state where:");
doc.text(20, 190, "Is the vehicle kept in?");
doc.setFontType("italic");
doc.text(20, 50, resp.isOwnerOfVehicle);
doc.text(20, 60, resp.nameAddressOfOwner);
doc.text(20, 70, resp.trailerUsed);
doc.text(50, 90, resp.lienHolderNameInFull);
doc.text(100, 95, resp.lienHolderStreetName);
doc.text(150, 100, resp.lienHolderTown);
doc.text(150, 105, resp.lienHolderParish);
doc.text(20, 115, resp.insuranceCoverage);
doc.text(20, 125, resp.vehicleUsedAs);
doc.text(20, 135, resp.vehicleAntiTheftDevice);
doc.text(20, 145, resp.vehicleAntiTheftDeviceName + " " + resp.vehicleAntiTheftDeviceType + " " + resp.vehicleAntiTheftDeviceNameOfProvider);
doc.text(20, 155, resp.vehicleRegularCustody ? resp.vehicleRegularCustody : "");
doc.text(20, 165, resp.vehicleRegularCustodyDetails ? resp.vehicleRegularCustodyDetails : "");
doc.text(20, 175, resp.vehicleGaragedAtProposersHome ? resp.vehicleGaragedAtProposersHome : "");
doc.text(20, 185, resp.vehicleGaragedAtProposersHomeDetails ? resp.vehicleGaragedAtProposersHomeDetails : "");
doc.text(20, 195, resp.vehicleKeptIn ? resp.vehicleKeptIn : "");
doc.addPage();
doc.setFontSize("10");
doc.setFontType("normal");
doc.text(20, 20, "Is the proposer now insured or was previously insured in respect of any vehicle(s)");
doc.text(20, 30, "If yes, state the name and address of the Insurance Company:");
doc.text(20, 40, "Is the proposer entitled to No Claim Discount from previous Insurer(s) In respect of any vehicle(s) described in the ");
doc.text(20, 43, "proposal?");
doc.text(20, 50, "If yes, please attach proof of No Claim Discount Letter or Renewal Notice.");
doc.text(20, 60, "Do you have any other Insurance(s) with IronRock Insurance Company Ltd.?");
doc.text(20, 70, "If yes, please state type(s):");
doc.text(20, 80, "Has any Insurer(s) in respect of the Proposer or any other Person who will regularly drive ever?");
doc.text(20, 90, "If yes, please indicate above and give details:");
doc.text(20, 100, "Type of Authorized Driver Clause:");
doc.setFontType("italic");
doc.text(20, 25, resp.proposerInsured ? resp.proposerInsured : "");
doc.text(20, 35, resp.proposerInsuranceDetails ? resp.proposerInsuranceDetails : "");
doc.text(20, 46, resp.proposerEntitledToNOClaimDiscount ? resp.proposerEntitledToNOClaimDiscount : "");
doc.text(20, 65, resp.applicantOtherInsurer ? resp.applicantOtherInsurer : "");
doc.text(20, 75, resp.applicantOtherInsurerType ? resp.applicantOtherInsurerType : "");
doc.text(20, 85, resp.applicantPreviouslyInsured ? resp.applicantPreviouslyInsured : "");
doc.text(20, 95, resp.ApplicantPreviouslyInsuredDetails ? resp.ApplicantPreviouslyInsuredDetails : "");
doc.text(20, 105, resp.typeOfAuthorizedDriver ? resp.typeOfAuthorizedDriver : "");
doc.setFontType("normal");
doc.text(20, 110, "Will anyone driving your motor vehicle:");
doc.text(20, 115, "In respect of PRIVATE CARS:");
doc.text(20, 125, "In respect of PRIVATE COMMERCIAL:");
doc.text(20, 135, "In respect of GENERAL CARTAGE:");
doc.text(20, 145, "If yes, please give particulars of drivers below:");
doc.setFontSize("7");
doc.setFontType("bold");
doc.text(20, 150, "Name(s)");
doc.text(50, 150, "Occupation(s)");
doc.text(80, 150, "Date of Birth");
doc.text(100, 150, "Drivers License No.");
doc.text(130, 150, "Original Date of Issue");
doc.text(160, 150, "Relationship to Proposer");
doc.setFontType("normal");
if (resp.vehicleRegistrationNo0) {
doc.text(20, 155, resp.regularDriversName0 ? resp.regularDriversName0 : "");
doc.text(50, 155, resp.regularDriversOccupation0 ? resp.regularDriversOccupation0 : "");
doc.text(80, 155, resp.regularDriversDateOfBirth0 ? resp.regularDriversDateOfBirth0 : "");
doc.text(100, 155, resp.regularDriversDL0 ? resp.regularDriversDL0 : "");
doc.text(130, 155, resp.regularDriversDLOriginalDateOfIssue0 ? resp.regularDriversDLOriginalDateOfIssue0 : "");
doc.text(160, 155, resp.regularDriversDLExpirationDate0 ? resp.regularDriversDLExpirationDate0 : "");
}
if (resp.vehicleRegistrationNo1) {
doc.text(20, 160, resp.regularDriversName1 ? resp.regularDriversName1 : "");
doc.text(50, 160, resp.regularDriversOccupation1 ? resp.regularDriversOccupation1 : "");
doc.text(80, 160, resp.regularDriversDateOfBirth1 ? resp.regularDriversDateOfBirth1 : "");
doc.text(100, 160, resp.regularDriversDL1 ? resp.regularDriversDL1 : "");
doc.text(130, 160, resp.regularDriversDLOriginalDateOfIssue1 ? resp.regularDriversDLOriginalDateOfIssue1 : "");
doc.text(160, 160, resp.regularDriversDLExpirationDate1 ? resp.regularDriversDLExpirationDate1 : "");
}
if (resp.vehicleRegistrationNo2) {
doc.text(20, 165, resp.regularDriversName2 ? resp.regularDriversName2 : "");
doc.text(50, 165, resp.regularDriversOccupation2 ? resp.regularDriversOccupation2 : "");
doc.text(80, 165, resp.regularDriversDateOfBirth2 ? resp.regularDriversDateOfBirth2 : "");
doc.text(100, 165, resp.regularDriversDL2 ? resp.regularDriversDL2 : "");
doc.text(130, 165, resp.regularDriversDLOriginalDateOfIssue2 ? resp.regularDriversDLOriginalDateOfIssue2 : "");
doc.text(160, 165, resp.regularDriversDLExpirationDate2 ? resp.regularDriversDLExpirationDate2 : "");
}
doc.addPage();
doc.setFontSize("10");
doc.setFontType("normal");
doc.text(20, 20, "Have you or any regular drivers had any accidents or losses during the past three(3) years (whether insured ");
doc.text(20, 23, "or not in respect of all vehicles)");
doc.text(20, 26, "I. Owned by you, whether or not you were the driver at the material time?");
doc.text(20, 29, "II. Not owned by you, but driven by you or in your custody at the material time?");
doc.text(20, 37, "If yes, please give details below");
doc.setFontType("bold");
doc.setFontSize("8");
doc.text(20, 40, "Date of Accident");
doc.text(50, 40, "Cost(Paid or Estimated)");
doc.text(90, 40, "Driver");
doc.text(120, 40, "Brief details of Accidents, Incident or losses");
doc.setFontType("normal");
if (resp.involvedInAccident) {
doc.text(20, 45, resp.accidentMonth0 ? resp.accidentMonth0 : "");
doc.text(50, 45, resp.accidentCost0 ? resp.accidentCost0 : "");
doc.text(90, 45, resp.accidentDriver0 ? resp.accidentDriver0 : "");
doc.text(120, 45, resp.accidentBrief0 ? resp.accidentBrief0 : "");
}
if (resp.involvedInAccident) {
doc.text(20, 50, resp.accidentMonth1 ? resp.accidentMonth1 : "");
doc.text(50, 50, resp.accidentCost1 ? resp.accidentCost1 : "");
doc.text(90, 50, resp.accidentDriver1 ? resp.accidentDriver1 : "");
doc.text(120, 50, resp.accidentBrief1 ? resp.accidentBrief1 : "");
}
if (resp.involvedInAccident) {
doc.text(20, 55, resp.accidentMonth2 ? resp.accidentMonth2 : "");
doc.text(50, 55, resp.accidentCost2 ? resp.accidentCost2 : "");
doc.text(90, 55, resp.accidentDriver2 ? resp.accidentDriver2 : "");
doc.text(120, 55, resp.accidentBrief2 ? resp.accidentBrief2 : "");
}
doc.setFontSize("10");
doc.text(20, 60, "To the best of your knowledge and belief have you, or any person who to your knowledge will drive have suffered");
doc.text(20, 63, " from, or now suffer from:");
doc.text(20, 70, "If yes, please indicate above and give details:");
doc.text(20, 80, "Have you or any person who to your knowledge will drive received any traffic ticket(s) and");
doc.text(20, 83, "or have been convicted of any offence in connection with the driving of any motor vehicle within the ");
doc.text(20, 86, "last three (3) years?");
doc.text(20, 95, "If yes, please give details:");
doc.text(20, 105, "Has the vehicle been modified or converted from maker's standard specification or do you intend to do so?");
doc.text(20, 115, "If yes, please give details:");
doc.text(20, 135, "Do you require increased limits (in excess of the Standard Limits)?");
doc.text(110, 145, "Limits");
doc.text(20, 150, "Protection and Removal (Wrecker Fee)");
doc.text(20, 155, "Medical Expenses (Including Passengers)");
doc.text(20, 160, "Manslaughter Defense Costs");
doc.text(20, 165, "Third Party Limits(Bodily Injury and Property Damage)");
doc.setFontType("italic");
doc.text(20, 32, resp.involvedInAccident);
doc.text(20, 75, resp.driverSufferFromDetails ? resp.driverSufferFromDetails : "");
doc.text(20, 90, resp.driverTrafficTicket ? resp.driverTrafficTicket : "");
doc.text(20, 100, resp.driverTrafficTicketDate);
doc.text(100, 100, resp.driverTrafficTicketDetails ? resp.driverTrafficTicketDetails : "");
doc.text(20, 110, resp.vehicleModified ? resp.vehicleModified : "");
doc.text(20, 120, resp.vehicleModifiedDetails ? resp.vehicleModifiedDetails : "");
doc.text(20, 140, resp.increasedLimits ? resp.increasedLimits : "");
doc.text(110, 150, resp.wreckerFee ? resp.wreckerFee : "");
doc.text(110, 155, resp.medicalExpenses ? resp.medicalExpenses : "");
doc.text(110, 160, resp.manslaughterDefenceCosts ? resp.manslaughterDefenceCosts : "");
doc.text(110, 165, resp.thirdPartyLimit ? resp.thirdPartyLimit : "");
}
function lastPage(resp) {
doc.addPage();
doc.setFontSize("8");
doc.setFontType("bold");
doc.text(20, 20, "Disclaimer");
doc.setFontType("normal");
doc.text(20, 23, "The liability of the Company does not commence until the acceptance of the proposal has been formally acknowledged by the Company")
doc.text(20, 26, " premium or deposit has been paid, except as provided by an Official Cover Note issued by the Company.");
doc.text(20, 31, "I declare that the information given above has been verified by original documents to ensure the veracity of the information given.");
doc.setFontType("bold");
doc.text(20, 60, "Customer service Representative");
doc.text(20, 130, "**THE SECTION BELOW IS ONLY APPLICABLE IF AN AGENT IS COMPLETING THE FORM ON BEHALF OF THE CLIENT.");
doc.setFontType("normal");
doc.text(20, 63, "I/We declare that the above answers are true and that all particulars affecting the assessment of the risk have been disclosed.");
doc.text(20, 142, "Surname:");
doc.text(20, 145, "First Name:");
doc.text(20, 148, "Middle Name:");
doc.text(20, 151, "Date of Birth:");
doc.text(20, 154, "Nationality:");
doc.text(20, 157, "TRN No.:");
doc.text(20, 160, "Address:");
doc.setFontType("bold");
doc.text(20, 139, "Agent Details");
doc.text(20, 70, "Proposer's Signature/Date");
doc.text(20, 100, "Joint Proposer's Signature Date");
doc.text(20, 163, "Agent Signature Date");
if (resp.signatureBytes) {
//print signature
var svgSignature = document.getElementById('svg-signature').innerHTML; //atob(resp.signatureBytes);
svgSignature = svgSignature.replace(/\r?\n|\r/g, '').trim();
var canvasSignature = document.getElementById('canvas-signature');
var contextSignature = canvasSignature.getContext('2d');
contextSignature.clearRect(0, 0, canvasSignature.width, canvasSignature.height);
canvg(canvasSignature, svgSignature);
var imgSignatureData = canvasSignature.toDataURL('image/JPEG');
$('#testimg').attr('src', imgSignatureData);
doc.addImage(imgSignatureData, 'JPG', 20, 75, 100, 20);
}
doc.setFontType("italic");
}
function setHomePropertyPages(resp) {
doc.setFontType("bold");
doc.setFontSize(10);
doc.setFont("times");
doc.text(20, 20, "Particulars Of Home To Be Insured");
doc.text(20, 45, "Construction of Dwelling");
doc.text(20, 65, "Garages or Out Buildings?");
doc.setFontType("normal");
doc.text(20, 25, "Risk Address:");
doc.text(20, 35, "Is the home:");
doc.text(20, 50, "External Walls:");
doc.text(100, 50, "Roof:");
doc.text(20, 60, "Internal Walls:");
doc.text(20, 70, "External walls:");
doc.text(20, 80, "Internal Walls:");
doc.text(100, 70, "Roof:");
doc.text(20, 90, "Are the buildings in good state of repairs and will be so maintained?");
doc.text(20, 100, "Is the Dwelling occupied solely by you, your family and domestic employees?");
doc.text(20, 110, "If no, give the details of other occupants:");
doc.text(20, 120, "Is any part of the Dwelling or Outbuilding used for any income-earning activity?");
doc.text(20, 130, "If yes, give details:");
doc.text(20, 140, "Are all externally communicating doors, windows and other openings grilled?");
doc.text(20, 150, "If no, describe the security arrangements in place:");
doc.text(20, 160, "Does any institution or individual have a financial interest in the Property:");
doc.text(20, 170, "If yes, state their name and address:");
doc.text(20, 180, "Are there any Waterside Structures i.e. docks, jetties, piers, sea walls and any other structure abutting the sea, a ");
doc.text(20, 183, "river or any other body of water?")
doc.text(20, 193, "If yes, please describe:");
doc.setFontType("italic");
doc.text(20, 30, resp.homeRiskAddressStreetNo + " " + resp.homeRiskAddressStreetName + ", " + resp.homeRiskAddressTown + ", " + resp.homeRiskAddressParish);
doc.text(20, 40, resp.homeType ? resp.homeType : "");
doc.text(50, 50, resp.constructionExternalWalls);
doc.text(120, 50, resp.constructionRoof);
doc.text(70, 65, resp.garageOutBuildingExists);
doc.text(50, 70, resp.garageExternalWalls);
doc.text(120, 70, resp.garageRoof);
doc.text(20, 95, resp.homeInGoodState);
doc.text(20, 105, resp.homeOccupiedByApplicantFamily);
doc.text(20, 115, resp.homeOccupiedByApplicantFamilyIfNo);
doc.text(20, 125, resp.homeUsedForIncomeActivity);
doc.text(20, 135, resp.homeUsedForIncomeActivityDetails);
doc.text(20, 165, resp.homeHaveInterestFromIndividual);
doc.text(20, 175, resp.homeHaveInterestFromIndividualDetails);
doc.text(20, 188, resp.homeHasWatersideStructure);
doc.text(20, 198, resp.homeHasWatersideStructureDetails);
doc.addPage();
doc.setFontType("bold");
doc.setFontSize("12");
doc.text(20, 20, "DETAILS OF PROPERTY TO BE INSURED");
doc.setFontSize("10");
doc.text(20, 30, "BUILDINGS AND OTHER STRUCTURES");
doc.text(20, 90, "CONTENTS");
doc.setFontType("normal");
doc.setFontSize("8");
doc.text(20, 35, "IMPORTANT NOTE: The SUMS TO BE INSURED must represent the FULL NEW REPLACEMENT COST of the property and should include");
doc.text(20, 38, " adequate provision for demolition and debris removal costs in the event of major damage as well as professional fees that would be incurred in");
doc.text(20, 41, " reinstatement. As the Company will pay up to 10% of the Sum Insured in respect of Rent lost or reasonable costs of alternative accomodation");
doc.text(20, 44, " if damage by an Insured Peril renders the home uninhabitable, provision for this should also be included in your Sums Insured.");
doc.setFontType("bold");
doc.text(130, 50, " Specified Items");
doc.text(160, 50, "Sums to be Insured");
doc.text(160, 140, "Sums to be Insured");
doc.setFontType("normal");
doc.text(20, 53, "The Buildings of the private dwelling together with its garages and outbuildings, including ");
doc.text(20, 56, "landlord's fixtures and fittings together with patios, driveways and other paved areas, walls");
doc.text(20, 59, " gates and fences, underground water pipes and cables providing services to and from the home");
doc.text(20, 62, " fixed water storage tanks and sewage disposal systems.(NB. Swimming Pools and Waterside");
doc.text(20, 65, " structures are not included in the above item)");
if (resp.homeInsurancePropertyItem0) {
doc.text(130, 53, "a." + resp.homeInsurancePropertyItem0 ? resp.homeInsurancePropertyItem0 : "");
doc.text(160, 53, "$" + resp.homeInsurancePropertyItemValue0 ? resp.homeInsurancePropertyItemValue0 : "");
}
if (resp.homeInsurancePropertyItem1) {
doc.text(130, 56, "b." + resp.homeInsurancePropertyItem1 ? resp.homeInsurancePropertyItem1 : "");
doc.text(160, 56, "$" + resp.homeInsurancePropertyItemValue1 ? resp.homeInsurancePropertyItemValue1 : "");
}
if (resp.homeInsurancePropertyItem2) {
doc.text(130, 59, "c." + resp.homeInsurancePropertyItem2 ? resp.homeInsurancePropertyItem2 : "");
doc.text(160, 59, "$" + resp.homeInsurancePropertyItemValue2 ? resp.homeInsurancePropertyItemValue2 : "");
}
doc.text(20, 70, "Swimming Pools: permanent pool structures together with pump-houses and permanently");
doc.text(20, 73, " installed pool equipment and accessories including all related pipes and cables.");
doc.text(160, 73, "$" + resp.homeInsurancePropertySwimmingPoolValue);
doc.setFontType("bold");
doc.text(20, 78, "The Total Sum Insured under the Buildings and Other Structures Section of the Policy");
doc.text(130, 78, "TOTAL SI:");
doc.text(20, 183, "The Total Sum Insured under the Contents Section of the policy");
doc.text(130, 183, "TOTAL SI:");
doc.setFontType("normal");
doc.text(160, 78, resp.homeInsurancePropertySum);
doc.text(20, 95, "IMPORTANT NOTES");
doc.text(20, 100, "The SUMS TO BE INSURED must represent the FULL COST of replacing all the contents insured with NEW articles of similar size, style");
doc.text(20, 103, " and specification. As the Company will pay up to 10% of the Sum Insured in respect of reasonable costs of alternative accomodation ");
doc.text(20, 106, "if damage by an Insured Peril renders the home uninhabitable, provision for this should be included in your Sum Insured.");
doc.text(20, 111, "Do not include in your Contents Sum Insured any Article which is to be insured under the All Risks Section");
doc.text(20, 116, "Unspecified Valuables:");
doc.text(50, 116, "Coverage is limited to one-third of the Total Sum Insured on Contents with coverage on individual articles limited to 5%");
doc.text(50, 119, " of such Total Sum Insured. Individual articles worth more than 5% of the Total Sum Insured to be insured be insured");
doc.text(50, 122, " separately specified below.");
doc.text(20, 130, "Valuables include jewellery and other articles of gold, silver and or other precious metal, clocks, watches, cameras, camcorders, and other photographic");
doc.text(20, 133, " equipment, electronic equipment(other than domestic appliances), furs, pictures, and other works of art, curios, licensed fire-arms, collections of stamps");
doc.text(20, 136, " coins or other valuable objects.");
doc.text(20, 145, "Contents: Household Goods, Personal Effects and Fixtures and Fittings which belong to or are the legal ");
doc.text(20, 148, "responsibility of any member of your household, including personal effects of non-paying guests temporarily ");
doc.text(20, 151, "staying with you but excluding Variables which are to be individually specified.");
doc.text(160, 151, "$" + resp.amountHouseholdGoods);
doc.text(20, 156, "Valuables to be individually specified(Please attach a list of these articles giving detailes descriptions");
doc.text(20, 159, " including model and serial numbers where appropriate and individual values)");
doc.text(160, 159, "$" + resp.amountValuables);
doc.text(20, 165, "Does the total value of your Valuables excluding those listed above and those which you will be insuring under the All Risk Section exceed one-third");
doc.text(20, 168, " of the Total Sum to be insured?");
doc.text(20, 173, "");
doc.text(20, 178, "If yes, what is the total value of such valuables");
doc.text(160, 178, "$" + resp.HomeInsuranceOtherValuableAmount);
doc.text(160, 183, "$" + resp.HomeInsuranceContentTotalAmount);
doc.addPage();
doc.setFontType("bold");
doc.setFontSize("10");
doc.text(20, 20, "ALL RISKS INSURANCE IN RESPECT OF PERSONAL POSSESSIONS");
doc.setFontType("normal");
doc.setFontSize("8");
doc.text(20, 25, "IMPORTANT NOTE: Valuation Reports or Receipts in respect of all Articles to be insured should be attached to this Form.");
doc.text(20, 30, "Full Description of Article(s) to be insured");
doc.setFontType("bold");
doc.text(20, 35, "Items List");
doc.text(160, 35, "Sum Insured");
doc.text(20, 50, "The Total Sum Insured under the All Risks Section of the Policy");
doc.setFontType("italic");
if (resp.HomeAllRiskArticleDescription0) {
doc.text(20, 38, resp.HomeAllRiskArticleDescription0 ? resp.HomeAllRiskArticleDescription0 : "");
doc.text(160, 38, "$" + resp.HomeAllRiskArticleValue0 ? resp.HomeAllRiskArticleValue0 : "");
}
if (resp.HomeAllRiskArticleDescription1) {
doc.text(20, 41, resp.HomeAllRiskArticleDescription1 ? resp.HomeAllRiskArticleDescription1 : "");
doc.text(160, 41, "$" + resp.HomeAllRiskArticleValue1 ? resp.HomeAllRiskArticleValue1 : "");
}
if (resp.HomeAllRiskArticleDescription2) {
doc.text(20, 44, resp.HomeAllRiskArticleDescription2 ? resp.HomeAllRiskArticleDescription2 : "");
doc.text(160, 44, "$" + resp.HomeAllRiskArticleValue2 ? resp.HomeAllRiskArticleValue2 : "");
}
if (resp.HomeAllRiskArticleDescription3) {
doc.text(20, 47, resp.HomeAllRiskArticleDescription3 ? resp.HomeAllRiskArticleDescription3 : "");
doc.text(160, 47, "$" + resp.HomeAllRiskArticleValue3 ? resp.HomeAllRiskArticleValue3 : "");
}
doc.setFontType("normal");
doc.text(20, 55, "Select Territorial Limits Required");
doc.text(160, 65, "Details");
doc.text(20, 70, "Do you currently have in force any policy whether with us or with any other company or Insurer ");
doc.text(20, 73, "covering any of the Property to be Insured");
doc.text(20, 78, "Has any Company or Insurer, in respect of any of the Perils to which this Proposal applies, ever:");
doc.text(20, 81, "Declined to insure you?");
doc.text(20, 84, "Required special terms to insure you?");
doc.text(20, 87, "Cancelled or refused to renew your policy?");
doc.text(20, 90, "Increased your premium on renewal");
doc.text(20, 95, "Have the Building and/or Contents of the Home to which this Proposal relates ever suffered");
doc.text(20, 98, " damage by Hurricane, Earthquake or Flood");
doc.text(20, 103, "Have you ever sustained loss from any Perils to which this Proposal would apply?");
doc.setFontType("italic");
doc.text(160, 50, "$" + resp.HomeAllRiskTotalAmount);
doc.text(20, 60, resp.territorialLimit)
doc.text(140, 70, resp.currentPolicyWithCompanyOrInsurer);
doc.text(180, 70, resp.currentPolicyWithCompanyOrInsurerDetails);
doc.text(140, 81, resp.HomeInsuranceDeclined);
doc.text(150, 81, resp.HomeInsuranceDeclinedDetails);
doc.text(140, 84, resp.HomeInsuranceRequiredSpecialTerm);
doc.text(150, 84, resp.HomeInsuranceRequiredSpecialTermDetails);
doc.text(140, 87, resp.HomeInsuranceCancelled);
doc.text(150, 87, resp.HomeInsuranceCancelledDetails);
doc.text(140, 90, resp.HomeInsuranceIncreasedPremium);
doc.text(150, 90, resp.HomeInsuranceIncreasedPremiumDetails);
doc.text(140, 95, resp.HomeInsurancePerilsSuffer);
doc.text(150, 95, resp.HomeInsurancePerilsSufferDetails);
doc.text(140, 103, resp.HomeInsuranceSufferLoss);
doc.text(150, 103, resp.HomeInsuranceSufferLossDetails);
} | aws/pdfconvertor.js | "use strict";
var doc;
const standardYgap = 5;
const gapBelowHeader = 10;
const startingXPoint = 20;
const startingYPoint = 20;
const startingYFirstPagePoint = 50;
function CreatePDF(resp) {
console.log(resp);
doc = new jsPDF();
doc.setFontSize(12);
if (resp.insuranceType === 'motor') {
doc.text(20, 40, 'Motor Vehicle Insurance Proposal');
} else {
doc.text(20, 40, 'Home Insurance Proposal');
}
var logoCanvas = document.getElementById("canvas-logo");
var imgLogoData = logoCanvas.toDataURL('image/jpeg', 1.0);
doc.addImage(imgLogoData, 'JPG', 2, 2, 100, 30);
doc.setFontSize(10);
doc.setFont("times");
doc.setFontType("normal");
doc.text(150, 35, "Start date: " + resp.startDate);
doc.text(150, 40, 'Quote No: ' + resp.applicantQuoteNo);
//doc.text(startingXPoint, 30, 'Insurance for ' + resp.insuranceType);
doc.text(20, 80, 'Surname:');
doc.text(20, 85, 'First Name:');
doc.text(20, 90, 'Middle Name:');
doc.text(20, 95, 'Title:');
doc.text(20, 100, 'Occupation:');
doc.text(100, 80, 'Mothers Maiden Name: ');
doc.text(100, 85, 'Other Names/Aliases: ');
doc.text(100, 90, 'ID Type: ');
doc.text(100, 95, 'ID Number: ');
doc.text(100, 100, 'Expiration Date: ');
doc.text(100, 105, 'Source of Funds: ');
doc.text(20, 115, 'Street Number and Name: ');
doc.text(20, 125, 'City/Town/Postal Zone: ');
doc.text(20, 135, 'Parish: ');
doc.text(100, 115, 'TRN: ');
doc.text(100, 120, 'Email Address: ');
doc.text(100, 125, 'Mobile Number: ');
doc.text(100, 130, 'Home Number: ');
doc.text(100, 135, 'Work Number: ');
doc.text(20, 145, 'Street Number and Name: ');
doc.text(20, 155, 'City/Town/Postal Zone: ');
doc.text(20, 165, 'Parish ');
doc.text(100, 145, 'Date of Birth: ');
doc.text(100, 150, 'Place of Birth: ');
doc.text(100, 155, 'Nationality: ');
doc.text(20, 175, 'Company Name:');
doc.text(100, 175, 'Street Number and Name:');
doc.text(100, 185, 'Town');
doc.text(100, 190, 'Parish');
doc.setFontType("italic");
doc.text(50, 80, resp.applicantSurname);
doc.text(50, 85, resp.applicantFirstName);
doc.text(50, 90, resp.applicantMiddleName);
doc.text(50, 95, resp.applicantTitle);
doc.text(50, 100, resp.applicantOccupation);
doc.text(150, 80, resp.applicantMothersMaidenName);
doc.text(150, 85, resp.applicantAlias);
doc.text(150, 90, resp.applicantIDType);
doc.text(150, 95, resp.applicantIDnumber);
doc.text(150, 100, resp.applicationIDExpirationDate);
doc.text(150, 105, resp.SourceOfFunds);
doc.text(20, 120, resp.applicantHomeStreetName);
doc.text(20, 130, resp.applicantHomeTown);
doc.text(50, 135, resp.applicantHomeParish);
//doc.text(150, 115, resp.applicantTRN);
doc.text(150, 120, resp.applicantEmailAddress);
doc.text(150, 125, resp.applicantMobileNumber);
doc.text(150, 130, resp.applicantHomeNumber);
doc.text(150, 135, resp.applicantWorkNumber);
/* doc.text(20, 150, resp.applicantMailStreetName); */
doc.text(20, 160, resp.applicantMailTown);
doc.text(50, 165, resp.applicantMailParish);
doc.text(150, 145, resp.applicantDateOfBirth);
doc.text(150, 150, resp.applicantPlaceOfBirth);
doc.text(150, 155, resp.applicantNationality);
doc.text(50, 175, resp.employerName);
doc.text(100, 180, resp.employerStreetName);
doc.text(150, 185, resp.employerTown);
doc.text(150, 190, resp.employerParish);
doc.setFontType("bold");
doc.setFontSize("10");
doc.text(20, 75, 'Name');
doc.text(20, 110, 'Home Address');
doc.text(20, 140, 'Mailing Address');
doc.text(20, 170, 'Employer Details');
doc.setFontSize("10");
doc.setFontType("bold");
doc.text(20, 195, "NB: Please submit the following:");
doc.setFontType("bold");
doc.text(20, 200, "** A power of attorney or a letter duly notarized");
doc.text(20, 205, "Proof of Address");
doc.text(20, 210, "Picture Identification(Insured an agent, where applicable)");
doc.text(20, 215, "TRN(if a driver's license is not being used)");
doc.text(20, 245, "Relation");
doc.text(60, 245, "Name of Relative");
doc.text(110, 245, "Address");
doc.setFontType("normal");
doc.text(20, 220, "Have you or any relative or close associate been entrusted with prominent public functions (e.g. Member of Parliament, ");
doc.text(20, 223, "Senate or Mayor, Senior Government Official, Judiciary, security forces)?");
doc.text(20, 230, "If yes, state the type of public office:");
doc.text(20, 240, "If yes to the above, please give the name and address of spouse and children");
if (resp.applicantRelativeInPublicOfficeName0) {
doc.text(20, 248, resp.applicantRelativeInPublicOfficeRelation0 ? resp.applicantRelativeInPublicOfficeRelation0 : "");
doc.text(60, 248, resp.applicantRelativeInPublicOfficeName0 ? resp.applicantRelativeInPublicOfficeName0 : "");
doc.text(150, 248, resp.applicantRelativeInPublicOfficeAddress0 ? resp.applicantRelativeInPublicOfficeAddress0 : "");
}
if (resp.vehicleRegistrationNo1) {
doc.text(20, 251, resp.applicantRelativeInPublicOfficeRelation ? resp.applicantRelativeInPublicOfficeRelation0 : "");
doc.text(60, 251, resp.applicantRelativeInPublicOfficeName0 ? resp.applicantRelativeInPublicOfficeName0 : "");
doc.text(110, 251, resp.applicantRelativeInPublicOfficeAddress0 ? resp.applicantRelativeInPublicOfficeAddress0 : "");
}
if (resp.vehicleRegistrationNo2) {
doc.text(20, 254, resp.applicantRelativeInPublicOfficeRelation ? resp.applicantRelativeInPublicOfficeRelation0 : "");
doc.text(60, 254, resp.applicantRelativeInPublicOfficeName0 ? resp.applicantRelativeInPublicOfficeName0 : "");
doc.text(110, 254, resp.applicantRelativeInPublicOfficeAddress0 ? resp.applicantRelativeInPublicOfficeAddress0 : "");
}
doc.setFontType("italic");
doc.text(20, 226, resp.applicantRelativeInPublicOffice ? resp.applicantRelativeInPublicOffice : "");
doc.text(20, 235, resp.applicantRelativeTypePublicOffice0 ? resp.applicantRelativeTypePublicOffice0 : "");
doc.setFontSize("8");
doc.setFontType("bold");
doc.text(20, 45, "DUTY TO DISCLOSE. This proposal must be completed, dated and signed by the proposer. When answering the questions on this form,");
doc.text(20, 48, " you must be honest and truthful. You have a duty under law to tell us anything known to you which is material to the questions asked as ");
doc.text(20, 51, "those answers will guide us in deciding whether to insure you or anyone else to be insured under the policy and on what terms. ");
doc.text(20, 54, "If you are in doubt as to whether a fact is relevant, you should state it. Your duty to make full and frank discourse occurs: (1) at the time ");
doc.text(20, 57, "of the time of proposing for insurance. (2) during the currency of the policy, if there are any changes or variations in the information given ");
doc.text(20, 60, "and (3) at each renewal.");
doc.text(20, 65, "FAILURE TO DISCLOSE. If you do not comply with these duties and answer our questions honestly, the company will be at liberty to ");
doc.text(20, 68, "treat your Policy as if it never existed and refuse to pay any claims you make under it.");
doc.addPage();
if (resp.insuranceType === 'motor') {
setMotorVehiclePages(resp);
} else {
setHomePropertyPages(resp);
}
lastPage(resp);
//doc.output('datauri');
doc.output('dataurlnewwindow');
//doc.save('Proposal' + resp.applicantQuoteNo + '.pdf');
}
function setMotorVehiclePages(resp) {
doc.setFontSize("10");
doc.setFontType("bold");
doc.text(20, 20, "Particulars Of Vehicles to Be Insured");
doc.setFontSize("7");
doc.text(20, 25, "Registration No.");
doc.text(42, 25, "Make and Model");
doc.text(62, 25, "SChassis & Engine No.");
doc.text(90, 25, "Year of Make");
doc.text(105, 25, "C.C. Rating");
doc.text(122, 25, "Seating");
doc.text(142, 25, "Type Of Body");
doc.text(162, 25, "Sum Insured");
doc.setFontType("normal")
if (resp.vehicleRegistrationNo0) {
doc.text(20, 30, resp.vehicleRegistrationNo0 ? resp.vehicleRegistrationNo0 : "");
doc.text(42, 30, resp.vehicleMake0 ? resp.vehicleMake0 : "");
doc.text(62, 30, resp.vehicleChassisNo0 ? resp.vehicleChassisNo0 : "");
doc.text(90, 30, resp.vehicleYear0 ? resp.vehicleYear0 : "");
doc.text(105, 30, "");
doc.text(122, 30, resp.vehicleBody0 ? resp.vehicleBody0 : "");
doc.text(142, 30, resp.vehicleType0 ? resp.vehicleType0 : "");
doc.text(162, 30, resp.QueryVehicleSumInsured ? resp.QueryVehicleSumInsured : "");
}
if (resp.vehicleRegistrationNo1) {
doc.text(20, 35, resp.vehicleRegistrationNo1 ? resp.vehicleRegistrationNo1 : "");
doc.text(42, 35, resp.vehicleMake1 ? resp.vehicleMake1 : "");
doc.text(62, 35, resp.vehicleChassisNo1 ? resp.vehicleChassisNo1 : "");
doc.text(90, 35, resp.vehicleYear1 ? resp.vehicleYear1 : "");
doc.text(105, 35, " ");
doc.text(122, 35, resp.vehicleBody1 ? resp.vehicleBody1 : "");
doc.text(142, 35, resp.vehicleType1 ? resp.vehicleType1 : "");
doc.text(162, 35, resp.QueryVehicleSumInsured ? resp.QueryVehicleSumInsured : "");
}
if (resp.vehicleRegistrationNo2) {
doc.text(20, 40, resp.vehicleRegistrationNo2 ? resp.vehicleRegistrationNo2 : "");
doc.text(42, 40, resp.vehicleMake2 ? resp.vehicleMake2 : "");
doc.text(62, 40, resp.vehicleChassisNo2 ? resp.vehicleChassisNo2 : "");
doc.text(90, 40, resp.vehicleYear2 ? resp.vehicleYear2 : "");
doc.text(105, 40, " ");
doc.text(122, 40, resp.vehicleBody2 ? resp.vehicleBody2 : "");
doc.text(142, 40, resp.vehicleType2 ? resp.vehicleType2 : "");
doc.text(162, 40, resp.QueryVehicleSumInsured ? resp.QueryVehicleSumInsured : "");
}
doc.setFontSize("8");
doc.setFontType("bold");
doc.text(20, 75, "NOTE: You are required to ensure that the Sum Insured is revised annually to reflect the current market value. ");
doc.text(20, 78, "Claims will be settled based on the market value at the time of the loss. For total losses you will be paid based in");
doc.text(20, 81, "time of the loss. For total losses you will be paid based on the market value or Policy Sum Insured whichever is lesser.");
doc.setFontSize("10");
doc.setFontType("bold");
doc.text(20, 85, "Lien Holder");
doc.text(20, 110, "Select cover required(tick the appropriate box)");
doc.setFontType("normal");
doc.text(20, 45, "Are you the owner of the vehicle(s) and is/are/they registered in your name?");
doc.text(20, 55, "If not, state the name and address of the owner:");
doc.text(20, 65, "Will a trailer be used?");
doc.text(20, 90, "Name in Full:");
doc.text(100, 90, "Street Number and Name:");
doc.text(100, 100, "Town:");
doc.text(100, 105, "Parish:");
doc.text(20, 120, "Please indicate if the vehicle is to be used as:");
doc.text(20, 130, "Is the vehicle fitted with an anti-theft device?");
doc.text(20, 140, "If yes, state the name, type of device and name of provider");
doc.text(20, 150, "Will you have regular custody of the vehicle?");
doc.text(20, 160, "If not, please provide details");
doc.text(20, 170, "Is the vehicle garaged at the Proposer's home address?");
doc.text(20, 180, "If not, please state where:");
doc.text(20, 190, "Is the vehicle kept in?");
doc.setFontType("italic");
doc.text(20, 50, resp.isOwnerOfVehicle);
doc.text(20, 60, resp.nameAddressOfOwner);
doc.text(20, 70, resp.trailerUsed);
doc.text(50, 90, resp.lienHolderNameInFull);
doc.text(100, 95, resp.lienHolderStreetName);
doc.text(150, 100, resp.lienHolderTown);
doc.text(150, 105, resp.lienHolderParish);
doc.text(20, 125, resp.vehicleUsedAs);
/* doc.text(20, 135, resp.vehicleAntiTheftDevice); */
doc.text(20, 145, resp.vehicleAntiTheftDeviceName + " " + resp.vehicleAntiTheftDeviceType + " " + resp.vehicleAntiTheftDeviceNameOfProvider);
doc.text(20, 155, resp.vehicleRegularCustody ? resp.vehicleRegularCustody : "");
doc.text(20, 165, resp.vehicleRegularCustodyDetails ? resp.vehicleRegularCustodyDetails : "");
doc.text(20, 175, resp.vehicleGaragedAtProposersHome ? resp.vehicleGaragedAtProposersHome : "");
doc.text(20, 185, resp.vehicleGaragedAtProposersHomeDetails ? resp.vehicleGaragedAtProposersHomeDetails : "");
doc.text(20, 195, resp.vehicleKeptIn ? resp.vehicleKeptIn : "");
doc.addPage();
doc.setFontSize("10");
doc.setFontType("normal");
doc.text(20, 20, "Is the proposer now insured or was previously insured in respect of any vehicle(s)");
doc.text(20, 30, "If yes, state the name and address of the Insurance Company:");
doc.text(20, 40, "Is the proposer entitled to No Claim Discount from previous Insurer(s) In respect of any vehicle(s) described in the ");
doc.text(20, 43, "proposal?");
doc.text(20, 50, "If yes, please attach proof of No Claim Discount Letter or Renewal Notice.");
doc.text(20, 60, "Do you have any other Insurance(s) with IronRock Insurance Company Ltd.?");
doc.text(20, 70, "If yes, please state type(s):");
doc.text(20, 80, "Has any Insurer(s) in respect of the Proposer or any other Person who will regularly drive ever?");
doc.text(20, 90, "If yes, please indicate above and give details:");
doc.text(20, 100, "Type of Authorized Driver Clause:");
doc.setFontType("italic");
doc.text(20, 25, resp.proposerInsured ? resp.proposerInsured : "");
doc.text(20, 35, resp.proposerInsuranceDetails ? resp.proposerInsuranceDetails : "");
doc.text(20, 46, resp.proposerEntitledToNOClaimDiscount ? resp.proposerEntitledToNOClaimDiscount : "");
doc.text(20, 65, resp.applicantOtherInsurer ? resp.applicantOtherInsurer : "");
doc.text(20, 75, resp.applicantOtherInsurerType ? resp.applicantOtherInsurerType : "");
doc.text(20, 85, resp.applicantPreviouslyInsured ? resp.applicantPreviouslyInsured : "");
doc.text(20, 95, resp.ApplicantPreviouslyInsuredDetails ? resp.ApplicantPreviouslyInsuredDetails : "");
doc.text(20, 105, resp.typeOfAuthorizedDriver ? resp.typeOfAuthorizedDriver : "");
doc.setFontType("normal");
doc.text(20, 110, "Will anyone driving your motor vehicle:");
doc.text(20, 115, "In respect of PRIVATE CARS:");
doc.text(20, 125, "In respect of PRIVATE COMMERCIAL:");
doc.text(20, 135, "In respect of GENERAL CARTAGE:");
doc.text(20, 145, "If yes, please give particulars of drivers below:");
doc.setFontSize("7");
doc.setFontType("bold");
doc.text(20, 150, "Name(s)");
doc.text(50, 150, "Occupation(s)");
doc.text(80, 150, "Date of Birth");
doc.text(100, 150, "Drivers License No.");
doc.text(130, 150, "Original Date of Issue");
doc.text(160, 150, "Relationship to Proposer");
doc.setFontType("normal");
if (resp.vehicleRegistrationNo0) {
doc.text(20, 155, resp.regularDriversName0 ? resp.regularDriversName0 : "");
doc.text(50, 155, resp.regularDriversOccupation0 ? resp.regularDriversOccupation0 : "");
doc.text(80, 155, resp.regularDriversDateOfBirth0 ? resp.regularDriversDateOfBirth0 : "");
doc.text(100, 155, resp.regularDriversDL0 ? resp.regularDriversDL0 : "");
doc.text(130, 155, resp.regularDriversDLOriginalDateOfIssue0 ? resp.regularDriversDLOriginalDateOfIssue0 : "");
doc.text(160, 155, resp.regularDriversDLExpirationDate0 ? resp.regularDriversDLExpirationDate0 : "");
}
if (resp.vehicleRegistrationNo1) {
doc.text(20, 160, resp.regularDriversName1 ? resp.regularDriversName1 : "");
doc.text(50, 160, resp.regularDriversOccupation1 ? resp.regularDriversOccupation1 : "");
doc.text(80, 160, resp.regularDriversDateOfBirth1 ? resp.regularDriversDateOfBirth1 : "");
doc.text(100, 160, resp.regularDriversDL1 ? resp.regularDriversDL1 : "");
doc.text(130, 160, resp.regularDriversDLOriginalDateOfIssue1 ? resp.regularDriversDLOriginalDateOfIssue1 : "");
doc.text(160, 160, resp.regularDriversDLExpirationDate1 ? resp.regularDriversDLExpirationDate1 : "");
}
if (resp.vehicleRegistrationNo2) {
doc.text(20, 165, resp.regularDriversName2 ? resp.regularDriversName2 : "");
doc.text(50, 165, resp.regularDriversOccupation2 ? resp.regularDriversOccupation2 : "");
doc.text(80, 165, resp.regularDriversDateOfBirth2 ? resp.regularDriversDateOfBirth2 : "");
doc.text(100, 165, resp.regularDriversDL2 ? resp.regularDriversDL2 : "");
doc.text(130, 165, resp.regularDriversDLOriginalDateOfIssue2 ? resp.regularDriversDLOriginalDateOfIssue2 : "");
doc.text(160, 165, resp.regularDriversDLExpirationDate2 ? resp.regularDriversDLExpirationDate2 : "");
}
doc.addPage();
doc.setFontSize("10");
doc.setFontType("normal");
doc.text(20, 20, "Have you or any regular drivers had any accidents or losses during the past three(3) years (whether insured ");
doc.text(20, 23, "or not in respect of all vehicles)");
doc.text(20, 26, "I. Owned by you, whether or not you were the driver at the material time?");
doc.text(20, 29, "II. Not owned by you, but driven by you or in your custody at the material time?");
doc.text(20, 37, "If yes, please give details below");
doc.setFontType("bold");
doc.setFontSize("8");
doc.text(20, 40, "Date of Accident");
doc.text(50, 40, "Cost(Paid or Estimated)");
doc.text(90, 40, "Driver");
doc.text(120, 40, "Brief details of Accidents, Incident or losses");
doc.setFontType("normal");
if (resp.involvedInAccident) {
doc.text(20, 45, resp.accidentMonth0 ? resp.accidentMonth0 : "");
doc.text(50, 45, resp.accidentCost0 ? resp.accidentCost0 : "");
doc.text(90, 45, resp.accidentDriver0 ? resp.accidentDriver0 : "");
doc.text(120, 45, resp.accidentBrief0 ? resp.accidentBrief0 : "");
}
if (resp.involvedInAccident) {
doc.text(20, 50, resp.accidentMonth1 ? resp.accidentMonth1 : "");
doc.text(50, 50, resp.accidentCost1 ? resp.accidentCost1 : "");
doc.text(90, 50, resp.accidentDriver1 ? resp.accidentDriver1 : "");
doc.text(120, 50, resp.accidentBrief1 ? resp.accidentBrief1 : "");
}
if (resp.involvedInAccident) {
doc.text(20, 55, resp.accidentMonth2 ? resp.accidentMonth2 : "");
doc.text(50, 55, resp.accidentCost2 ? resp.accidentCost2 : "");
doc.text(90, 55, resp.accidentDriver2 ? resp.accidentDriver2 : "");
doc.text(120, 55, resp.accidentBrief2 ? resp.accidentBrief2 : "");
}
doc.setFontSize("10");
doc.text(20, 60, "To the best of your knowledge and belief have you, or any person who to your knowledge will drive have suffered");
doc.text(20, 63, " from, or now suffer from:");
doc.text(20, 70, "If yes, please indicate above and give details:");
doc.text(20, 80, "Have you or any person who to your knowledge will drive received any traffic ticket(s) and");
doc.text(20, 83, "or have been convicted of any offence in connection with the driving of any motor vehicle within the ");
doc.text(20, 86, "last three (3) years?");
doc.text(20, 95, "If yes, please give details:");
doc.text(20, 105, "Has the vehicle been modified or converted from maker's standard specification or do you intend to do so?");
doc.text(20, 115, "If yes, please give details:");
doc.text(20, 135, "Do you require increased limits (in excess of the Standard Limits)?");
doc.text(110, 145, "Limits");
doc.text(20, 150, "Protection and Removal (Wrecker Fee)");
doc.text(20, 155, "Medical Expenses (Including Passengers)");
doc.text(20, 160, "Manslaughter Defense Costs");
doc.text(20, 165, "Third Party Limits(Bodily Injury and Property Damage)");
doc.setFontType("italic");
doc.text(20, 32, resp.involvedInAccident);
doc.text(20, 75, resp.driverSufferFromDetails ? resp.driverSufferFromDetails : "");
doc.text(20, 90, resp.driverTrafficTicket ? resp.driverTrafficTicket : "");
doc.text(20, 100, resp.driverTrafficTicketDate);
doc.text(100, 100, resp.driverTrafficTicketDetails ? resp.driverTrafficTicketDetails : "");
doc.text(20, 110, resp.vehicleModified ? resp.vehicleModified : "");
doc.text(20, 120, resp.vehicleModifiedDetails ? resp.vehicleModifiedDetails : "");
doc.text(20, 140, resp.increasedLimits ? resp.increasedLimits : "");
doc.text(110, 150, resp.wreckerFee ? resp.wreckerFee : "");
doc.text(110, 155, resp.medicalExpenses ? resp.medicalExpenses : "");
doc.text(110, 160, resp.manslaughterDefenceCosts ? resp.manslaughterDefenceCosts : "");
doc.text(110, 165, resp.thirdPartyLimit ? resp.thirdPartyLimit : "");
}
function lastPage(resp) {
doc.addPage();
doc.setFontSize("8");
doc.setFontType("bold");
doc.text(20, 20, "Disclaimer");
doc.setFontType("normal");
doc.text(20, 23, "The liability of the Company does not commence until the acceptance of the proposal has been formally acknowledged by the Company")
doc.text(20, 26, " premium or deposit has been paid, except as provided by an Official Cover Note issued by the Company.");
doc.text(20, 31, "I declare that the information given above has been verified by original");
doc.text(20, 33, "documents to ensure the veracity of the information given.");
doc.setFontType("bold");
doc.text(20, 60, "Customer service Representative");
doc.text(110, 33, "**THE SECTION BELOW IS ONLY APPLICABLE IF AN AGENT");
doc.text(110, 36, "IS COMPLETING THE FORM ON BEHALF OF THE CLIENT.");
doc.setFontType("normal");
doc.text(20, 63, "I/We declare that the above answers are true and that all particulars ");
doc.text(20, 66, "affecting the assessment of the risk have been disclosed.");
doc.text(110, 43, "Surname:");
doc.text(110, 46, "First Name:");
doc.text(110, 49, "Middle Name:");
doc.text(110, 52, "Date of Birth:");
doc.text(110, 55, "Nationality:");
doc.text(110, 58, "TRN No.:");
doc.text(110, 61, "Address:");
doc.setFontType("bold");
doc.text(110, 40, "Agent Details");
doc.text(20, 70, "Proposer's Signature/Date");
doc.text(20, 100, "Joint Proposer's Signature Date");
doc.text(160, 40, "Agent Signature Date");
if (resp.signatureBytes) {
//print signature
var svgSignature = document.getElementById('svg-signature').innerHTML; //atob(resp.signatureBytes);
svgSignature = svgSignature.replace(/\r?\n|\r/g, '').trim();
var canvasSignature = document.getElementById('canvas-signature');
var contextSignature = canvasSignature.getContext('2d');
contextSignature.clearRect(0, 0, canvasSignature.width, canvasSignature.height);
canvg(canvasSignature, svgSignature);
var imgSignatureData = canvasSignature.toDataURL('image/JPEG');
$('#testimg').attr('src', imgSignatureData);
doc.addImage(imgSignatureData, 'JPG', 20, 75, 100, 20);
}
doc.setFontType("italic");
}
function setHomePropertyPages(resp) {
doc.setFontType("bold");
doc.setFontSize(10);
doc.setFont("times");
doc.text(20, 20, "Particulars Of Home To Be Insured");
doc.text(20, 45, "Construction of Dwelling");
doc.text(20, 65, "Garages or Out Buildings?");
doc.setFontType("normal");
doc.text(20, 25, "Risk Address:");
doc.text(20, 35, "Is the home:");
doc.text(20, 50, "External Walls:");
doc.text(100, 50, "Roof:");
doc.text(20, 60, "Internal Walls:");
doc.text(20, 70, "External walls:");
doc.text(20, 80, "Internal Walls:");
doc.text(100, 70, "Roof:");
doc.text(20, 90, "Are the buildings in good state of repairs and will be so maintained?");
doc.text(20, 100, "Is the Dwelling occupied solely by you, your family and domestic employees?");
doc.text(20, 110, "If no, give the details of other occupants:");
doc.text(20, 120, "Is any part of the Dwelling or Outbuilding used for any income-earning activity?");
doc.text(20, 130, "If yes, give details:");
doc.text(20, 140, "Are all externally communicating doors, windows and other openings grilled?");
doc.text(20, 150, "If no, describe the security arrangements in place:");
doc.text(20, 160, "Does any institution or individual have a financial interest in the Property:");
doc.text(20, 170, "If yes, state their name and address:");
doc.text(20, 180, "Are there any Waterside Structures i.e. docks, jetties, piers, sea walls and any other structure abutting the sea, a ");
doc.text(20, 183, "river or any other body of water?")
doc.text(20, 193, "If yes, please describe:");
doc.setFontType("italic");
doc.text(20, 30, resp.homeRiskAddressStreetNo + " " + resp.homeRiskAddressStreetName + ", " + resp.homeRiskAddressTown + ", " + resp.homeRiskAddressParish);
doc.text(20, 40, resp.homeType ? resp.homeType : "");
doc.text(50, 50, resp.constructionExternalWalls);
doc.text(120, 50, resp.constructionRoof);
doc.text(70, 65, resp.garageOutBuildingExists);
doc.text(50, 70, resp.garageExternalWalls);
doc.text(120, 70, resp.garageRoof);
doc.text(20, 95, resp.homeInGoodState);
doc.text(20, 105, resp.homeOccupiedByApplicantFamily);
doc.text(20, 115, resp.homeOccupiedByApplicantFamilyIfNo);
doc.text(20, 125, resp.homeUsedForIncomeActivity);
doc.text(20, 135, resp.homeUsedForIncomeActivityDetails);
doc.text(20, 165, resp.homeHaveInterestFromIndividual);
doc.text(20, 175, resp.homeHaveInterestFromIndividualDetails);
doc.text(20, 188, resp.homeHasWatersideStructure);
doc.text(20, 198, resp.homeHasWatersideStructureDetails);
doc.addPage();
doc.setFontType("bold");
doc.setFontSize("12");
doc.text(20, 20, "DETAILS OF PROPERTY TO BE INSURED");
doc.setFontSize("10");
doc.text(20, 30, "BUILDINGS AND OTHER STRUCTURES");
doc.text(20, 90, "CONTENTS");
doc.setFontType("normal");
doc.setFontSize("8");
doc.text(20, 35, "IMPORTANT NOTE: The SUMS TO BE INSURED must represent the FULL NEW REPLACEMENT COST of the property and should include");
doc.text(20, 38, " adequate provision for demolition and debris removal costs in the event of major damage as well as professional fees that would be incurred in");
doc.text(20, 41, " reinstatement. As the Company will pay up to 10% of the Sum Insured in respect of Rent lost or reasonable costs of alternative accomodation");
doc.text(20, 44, " if damage by an Insured Peril renders the home uninhabitable, provision for this should also be included in your Sums Insured.");
doc.setFontType("bold");
doc.text(130, 50, " Specified Items");
doc.text(160, 50, "Sums to be Insured");
doc.text(160, 140, "Sums to be Insured");
doc.setFontType("normal");
doc.text(20, 53, "The Buildings of the private dwelling together with its garages and outbuildings, including ");
doc.text(20, 56, "landlord's fixtures and fittings together with patios, driveways and other paved areas, walls");
doc.text(20, 59, " gates and fences, underground water pipes and cables providing services to and from the home");
doc.text(20, 62, " fixed water storage tanks and sewage disposal systems.(NB. Swimming Pools and Waterside");
doc.text(20, 65, " structures are not included in the above item)");
if (resp.homeInsurancePropertyItem0) {
doc.text(130, 53, "a." + resp.homeInsurancePropertyItem0 ? resp.homeInsurancePropertyItem0 : "");
doc.text(160, 53, "$" + resp.homeInsurancePropertyItemValue0 ? resp.homeInsurancePropertyItemValue0 : "");
}
if (resp.homeInsurancePropertyItem1) {
doc.text(130, 56, "b." + resp.homeInsurancePropertyItem1 ? resp.homeInsurancePropertyItem1 : "");
doc.text(160, 56, "$" + resp.homeInsurancePropertyItemValue1 ? resp.homeInsurancePropertyItemValue1 : "");
}
if (resp.homeInsurancePropertyItem2) {
doc.text(130, 59, "c." + resp.homeInsurancePropertyItem2 ? resp.homeInsurancePropertyItem2 : "");
doc.text(160, 59, "$" + resp.homeInsurancePropertyItemValue2 ? resp.homeInsurancePropertyItemValue2 : "");
}
doc.text(20, 70, "Swimming Pools: permanent pool structures together with pump-houses and permanently");
doc.text(20, 73, " installed pool equipment and accessories including all related pipes and cables.");
doc.text(160, 73, "$" + resp.homeInsurancePropertySwimmingPoolValue);
doc.setFontType("bold");
doc.text(20, 78, "The Total Sum Insured under the Buildings and Other Structures Section of the Policy");
doc.text(130, 78, "TOTAL SI:");
doc.text(20, 183, "The Total Sum Insured under the Contents Section of the policy");
doc.text(130, 183, "TOTAL SI:");
doc.setFontType("normal");
doc.text(160, 78, resp.homeInsurancePropertySum);
doc.text(20, 95, "IMPORTANT NOTES");
doc.text(20, 100, "The SUMS TO BE INSURED must represent the FULL COST of replacing all the contents insured with NEW articles of similar size, style");
doc.text(20, 103, " and specification. As the Company will pay up to 10% of the Sum Insured in respect of reasonable costs of alternative accomodation ");
doc.text(20, 106, "if damage by an Insured Peril renders the home uninhabitable, provision for this should be included in your Sum Insured.");
doc.text(20, 111, "Do not include in your Contents Sum Insured any Article which is to be insured under the All Risks Section");
doc.text(20, 116, "Unspecified Valuables:");
doc.text(50, 116, "Coverage is limited to one-third of the Total Sum Insured on Contents with coverage on individual articles limited to 5%");
doc.text(50, 119, " of such Total Sum Insured. Individual articles worth more than 5% of the Total Sum Insured to be insured be insured");
doc.text(50, 122, " separately specified below.");
doc.text(20, 130, "Valuables include jewellery and other articles of gold, silver and or other precious metal, clocks, watches, cameras, camcorders, and other photographic");
doc.text(20, 133, " equipment, electronic equipment(other than domestic appliances), furs, pictures, and other works of art, curios, licensed fire-arms, collections of stamps");
doc.text(20, 136, " coins or other valuable objects.");
doc.text(20, 145, "Contents: Household Goods, Personal Effects and Fixtures and Fittings which belong to or are the legal ");
doc.text(20, 148, "responsibility of any member of your household, including personal effects of non-paying guests temporarily ");
doc.text(20, 151, "staying with you but excluding Variables which are to be individually specified.");
doc.text(160, 151, "$" + resp.amountHouseholdGoods);
doc.text(20, 156, "Valuables to be individually specified(Please attach a list of these articles giving detailes descriptions");
doc.text(20, 159, " including model and serial numbers where appropriate and individual values)");
doc.text(160, 159, "$" + resp.amountValuables);
doc.text(20, 165, "Does the total value of your Valuables excluding those listed above and those which you will be insuring under the All Risk Section exceed one-third");
doc.text(20, 168, " of the Total Sum to be insured?");
doc.text(20, 173, "");
doc.text(20, 178, "If yes, what is the total value of such valuables");
doc.text(160, 178, "$" + resp.HomeInsuranceOtherValuableAmount);
doc.text(160, 183, "$" + resp.HomeInsuranceContentTotalAmount);
doc.addPage();
doc.setFontType("bold");
doc.setFontSize("10");
doc.text(20, 20, "ALL RISKS INSURANCE IN RESPECT OF PERSONAL POSSESSIONS");
doc.setFontType("normal");
doc.setFontSize("8");
doc.text(20, 25, "IMPORTANT NOTE: Valuation Reports or Receipts in respect of all Articles to be insured should be attached to this Form.");
doc.text(20, 30, "Full Description of Article(s) to be insured");
doc.setFontType("bold");
doc.text(20, 35, "Items List");
doc.text(160, 35, "Sum Insured");
doc.text(20, 50, "The Total Sum Insured under the All Risks Section of the Policy");
doc.setFontType("italic");
if (resp.HomeAllRiskArticleDescription0) {
doc.text(20, 38, resp.HomeAllRiskArticleDescription0 ? resp.HomeAllRiskArticleDescription0 : "");
doc.text(160, 38, "$" + resp.HomeAllRiskArticleValue0 ? resp.HomeAllRiskArticleValue0 : "");
}
if (resp.HomeAllRiskArticleDescription1) {
doc.text(20, 41, resp.HomeAllRiskArticleDescription1 ? resp.HomeAllRiskArticleDescription1 : "");
doc.text(160, 41, "$" + resp.HomeAllRiskArticleValue1 ? resp.HomeAllRiskArticleValue1 : "");
}
if (resp.HomeAllRiskArticleDescription2) {
doc.text(20, 44, resp.HomeAllRiskArticleDescription2 ? resp.HomeAllRiskArticleDescription2 : "");
doc.text(160, 44, "$" + resp.HomeAllRiskArticleValue2 ? resp.HomeAllRiskArticleValue2 : "");
}
if (resp.HomeAllRiskArticleDescription3) {
doc.text(20, 47, resp.HomeAllRiskArticleDescription3 ? resp.HomeAllRiskArticleDescription3 : "");
doc.text(160, 47, "$" + resp.HomeAllRiskArticleValue3 ? resp.HomeAllRiskArticleValue3 : "");
}
doc.setFontType("normal");
doc.text(20, 55, "Select Territorial Limits Required");
doc.text(160, 65, "Details");
doc.text(20, 70, "Do you currently have in force any policy whether with us or with any other company or Insurer ");
doc.text(20, 73, "covering any of the Property to be Insured");
doc.text(20, 78, "Has any Company or Insurer, in respect of any of the Perils to which this Proposal applies, ever:");
doc.text(20, 81, "Declined to insure you?");
doc.text(20, 84, "Required special terms to insure you?");
doc.text(20, 87, "Cancelled or refused to renew your policy?");
doc.text(20, 90, "Increased your premium on renewal");
doc.text(20, 95, "Have the Building and/or Contents of the Home to which this Proposal relates ever suffered");
doc.text(20, 98, " damage by Hurricane, Earthquake or Flood");
doc.text(20, 103, "Have you ever sustained loss from any Perils to which this Proposal would apply?");
doc.setFontType("italic");
doc.text(160, 50, "$" + resp.HomeAllRiskTotalAmount);
doc.text(20, 60, resp.territorialLimit)
doc.text(140, 70, resp.currentPolicyWithCompanyOrInsurer);
doc.text(180, 70, resp.currentPolicyWithCompanyOrInsurerDetails);
doc.text(140, 81, resp.HomeInsuranceDeclined);
doc.text(150, 81, resp.HomeInsuranceDeclinedDetails);
doc.text(140, 84, resp.HomeInsuranceRequiredSpecialTerm);
doc.text(150, 84, resp.HomeInsuranceRequiredSpecialTermDetails);
doc.text(140, 87, resp.HomeInsuranceCancelled);
doc.text(150, 87, resp.HomeInsuranceCancelledDetails);
doc.text(140, 90, resp.HomeInsuranceIncreasedPremium);
doc.text(150, 90, resp.HomeInsuranceIncreasedPremiumDetails);
doc.text(140, 95, resp.HomeInsurancePerilsSuffer);
doc.text(150, 95, resp.HomeInsurancePerilsSufferDetails);
doc.text(140, 103, resp.HomeInsuranceSufferLoss);
doc.text(150, 103, resp.HomeInsuranceSufferLossDetails);
} | pdf changes
| aws/pdfconvertor.js | pdf changes | <ide><path>ws/pdfconvertor.js
<ide> doc.text(20, 120, resp.applicantHomeStreetName);
<ide> doc.text(20, 130, resp.applicantHomeTown);
<ide> doc.text(50, 135, resp.applicantHomeParish);
<del> //doc.text(150, 115, resp.applicantTRN);
<add> doc.text(150, 115, resp.applicantIDnumber);
<ide> doc.text(150, 120, resp.applicantEmailAddress);
<ide> doc.text(150, 125, resp.applicantMobileNumber);
<ide>
<ide> doc.text(150, 130, resp.applicantHomeNumber);
<ide> doc.text(150, 135, resp.applicantWorkNumber);
<del> /* doc.text(20, 150, resp.applicantMailStreetName); */
<add> if(resp.mailingAddressSame=="yes"){
<add> doc.text(20, 150, resp.applicantHomeStreetName);
<add> }else{
<add> doc.text(20, 150, resp.applicantMailStreetName);
<add> }
<add>
<add> if(resp.mailingAddressSame=="yes"){
<add> doc.text(20, 160, resp.applicantHomeTown);
<add> }else{
<add> doc.text(20, 160, resp.applicantMailTown);
<add> }
<add>
<add> if(resp.mailingAddressSame=="yes"){
<add> doc.text(50, 165, resp.applicantHomeParish);
<add> }else{
<add> doc.text(50, 165, resp.applicantMailParish);
<add> }
<add>
<ide> doc.text(20, 160, resp.applicantMailTown);
<ide> doc.text(50, 165, resp.applicantMailParish);
<ide> doc.text(150, 145, resp.applicantDateOfBirth);
<ide> doc.setFontType("bold");
<ide> doc.text(20, 85, "Lien Holder");
<ide>
<del> doc.text(20, 110, "Select cover required(tick the appropriate box)");
<add> doc.text(20, 110, "Select cover required");
<ide>
<ide> doc.setFontType("normal");
<ide> doc.text(20, 45, "Are you the owner of the vehicle(s) and is/are/they registered in your name?");
<ide> doc.text(150, 100, resp.lienHolderTown);
<ide>
<ide> doc.text(150, 105, resp.lienHolderParish);
<add>
<add> doc.text(20, 115, resp.insuranceCoverage);
<ide>
<ide> doc.text(20, 125, resp.vehicleUsedAs);
<ide>
<del> /* doc.text(20, 135, resp.vehicleAntiTheftDevice); */
<add> doc.text(20, 135, resp.vehicleAntiTheftDevice);
<ide>
<ide> doc.text(20, 145, resp.vehicleAntiTheftDeviceName + " " + resp.vehicleAntiTheftDeviceType + " " + resp.vehicleAntiTheftDeviceNameOfProvider);
<ide>
<ide>
<ide> doc.text(20, 26, " premium or deposit has been paid, except as provided by an Official Cover Note issued by the Company.");
<ide>
<del> doc.text(20, 31, "I declare that the information given above has been verified by original");
<del>
<del> doc.text(20, 33, "documents to ensure the veracity of the information given.");
<add> doc.text(20, 31, "I declare that the information given above has been verified by original documents to ensure the veracity of the information given.");
<add>
<add>
<ide>
<ide> doc.setFontType("bold");
<ide> doc.text(20, 60, "Customer service Representative");
<ide>
<del> doc.text(110, 33, "**THE SECTION BELOW IS ONLY APPLICABLE IF AN AGENT");
<del> doc.text(110, 36, "IS COMPLETING THE FORM ON BEHALF OF THE CLIENT.");
<del>
<del> doc.setFontType("normal");
<del>
<del> doc.text(20, 63, "I/We declare that the above answers are true and that all particulars ");
<del> doc.text(20, 66, "affecting the assessment of the risk have been disclosed.");
<del>
<del> doc.text(110, 43, "Surname:");
<del>
<del> doc.text(110, 46, "First Name:");
<del>
<del> doc.text(110, 49, "Middle Name:");
<del>
<del> doc.text(110, 52, "Date of Birth:");
<del>
<del> doc.text(110, 55, "Nationality:");
<del>
<del> doc.text(110, 58, "TRN No.:");
<del>
<del> doc.text(110, 61, "Address:");
<del>
<del> doc.setFontType("bold");
<del>
<del> doc.text(110, 40, "Agent Details");
<add> doc.text(20, 130, "**THE SECTION BELOW IS ONLY APPLICABLE IF AN AGENT IS COMPLETING THE FORM ON BEHALF OF THE CLIENT.");
<add>
<add>
<add> doc.setFontType("normal");
<add>
<add> doc.text(20, 63, "I/We declare that the above answers are true and that all particulars affecting the assessment of the risk have been disclosed.");
<add>
<add>
<add> doc.text(20, 142, "Surname:");
<add>
<add> doc.text(20, 145, "First Name:");
<add>
<add> doc.text(20, 148, "Middle Name:");
<add>
<add> doc.text(20, 151, "Date of Birth:");
<add>
<add> doc.text(20, 154, "Nationality:");
<add>
<add> doc.text(20, 157, "TRN No.:");
<add>
<add> doc.text(20, 160, "Address:");
<add>
<add> doc.setFontType("bold");
<add>
<add> doc.text(20, 139, "Agent Details");
<ide>
<ide> doc.text(20, 70, "Proposer's Signature/Date");
<ide>
<ide> doc.text(20, 100, "Joint Proposer's Signature Date");
<ide>
<del> doc.text(160, 40, "Agent Signature Date");
<add> doc.text(20, 163, "Agent Signature Date");
<ide>
<ide>
<ide> if (resp.signatureBytes) { |
|
Java | apache-2.0 | 2722c0f74c2537003b610262cf16164594f5b8d8 | 0 | Governance/dtgov,Governance/dtgov,Governance/dtgov | /*
* Copyright 2013 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.sramp.governance.services;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.jboss.downloads.overlord.sramp._2013.auditing.AuditEntry;
import org.jboss.downloads.overlord.sramp._2013.auditing.AuditItemType;
import org.oasis_open.docs.s_ramp.ns.s_ramp_v1.BaseArtifactType;
import org.overlord.dtgov.common.Target;
import org.overlord.dtgov.server.i18n.Messages;
import org.overlord.dtgov.services.deploy.Deployer;
import org.overlord.dtgov.services.deploy.DeployerFactory;
import org.overlord.sramp.atom.err.SrampAtomException;
import org.overlord.sramp.client.SrampAtomApiClient;
import org.overlord.sramp.client.query.QueryResultSet;
import org.overlord.sramp.common.ArtifactType;
import org.overlord.sramp.common.SrampModelUtils;
import org.overlord.sramp.common.audit.AuditUtils;
import org.overlord.sramp.governance.Governance;
import org.overlord.sramp.governance.GovernanceConstants;
import org.overlord.sramp.governance.SlashDecoder;
import org.overlord.sramp.governance.SrampAtomApiClientFactory;
import org.overlord.sramp.governance.ValueEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The JAX-RS resource that handles deployment specific tasks.
*/
@Path("/deploy")
public class DeploymentResource {
private static Logger logger = LoggerFactory.getLogger(DeploymentResource.class);
/**
* Constructor.
*/
public DeploymentResource() {
}
/**
* The deployment endpoint - processes can invoke this endpoint to deploy
* a deployment based on configuration of the provided target.
* @param request
* @param targetRef
* @param uuid
* @throws Exception
*/
@POST
@Path("{target}/{uuid}")
@Produces("application/xml")
public Map<String,ValueEntity> deploy(@Context HttpServletRequest request,
@PathParam("target") String targetRef,
@PathParam("uuid") String uuid) throws Exception {
Governance governance = new Governance();
Map<String, ValueEntity> results = new HashMap<String,ValueEntity>();
// 0. run the decoder on the arguments
targetRef = SlashDecoder.decode(targetRef);
uuid = SlashDecoder.decode(uuid);
// get the artifact from the repo
////////////////////////////////////////////
SrampAtomApiClient client = SrampAtomApiClientFactory.createAtomApiClient();
BaseArtifactType artifact = client.getArtifactMetaData(uuid);
// get the deployment environment settings
////////////////////////////////////////////
Target target = governance.getTargets().get(targetRef);
if (target == null) {
logger.error(Messages.i18n.format("DeploymentResource.NoTarget", targetRef)); //$NON-NLS-1$
throw new SrampAtomException(Messages.i18n.format("DeploymentResource.NoTarget", targetRef)); //$NON-NLS-1$
}
// get the previous version of the deployment (so we can undeploy it)
////////////////////////////////////////////
BaseArtifactType prevVersionArtifact = getCurrentlyDeployedVersion(client, artifact, target);
Deployer deployer = DeployerFactory.createDeployer(target.getType().name());
if (deployer == null) {
throw new Exception(Messages.i18n.format(
"DeploymentResource.TargetTypeNotFound", target.getType())); //$NON-NLS-1$
}
if (prevVersionArtifact != null) {
undeploy(request, client, prevVersionArtifact, target, deployer);
}
// deploy the artifact (delegate based on target type)
////////////////////////////////////////////
String deploymentTarget = target.getType().toString() + ":"; //$NON-NLS-1$
try {
deploymentTarget += deployer.deploy(artifact, target, client);
} catch (Exception e) {
logger.error(e.getMessage(), e);
results.put(GovernanceConstants.STATUS, new ValueEntity("fail")); //$NON-NLS-1$
results.put(GovernanceConstants.MESSAGE, new ValueEntity(e.getMessage()));
return results;
}
// update the artifact meta-data to set the classifier
////////////////////////////////////////////
String deploymentClassifier = target.getClassifier();
try {
// refresh the artifact meta-data in case something changed since we originally retrieved it
artifact = client.getArtifactMetaData(uuid);
artifact.getClassifiedBy().add(deploymentClassifier);
client.updateArtifactMetaData(artifact);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
// Add a custom audit record to the artifact
////////////////////////////////////////////
try {
AuditEntry auditEntry = new AuditEntry();
auditEntry.setType("deploy:deploy"); //$NON-NLS-1$
DatatypeFactory dtFactory = DatatypeFactory.newInstance();
XMLGregorianCalendar now = dtFactory.newXMLGregorianCalendar((GregorianCalendar)Calendar.getInstance());
auditEntry.setWhen(now);
auditEntry.setWho(request.getRemoteUser());
AuditItemType item = AuditUtils.getOrCreateAuditItem(auditEntry, "deploy:info"); //$NON-NLS-1$
AuditUtils.setAuditItemProperty(item, "target", target.getName()); //$NON-NLS-1$
AuditUtils.setAuditItemProperty(item, "classifier", target.getClassifier()); //$NON-NLS-1$
client.addAuditEntry(uuid, auditEntry);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
results.put(GovernanceConstants.STATUS, new ValueEntity("success")); //$NON-NLS-1$
results.put(GovernanceConstants.TARGET, new ValueEntity(deploymentTarget));
return results;
}
/**
* Finds the currently deployed version of the given artifact. This basically needs to
* return the version of the artifact that is currently deployed to the given target.
* This is important so that we can undeploy that old version prior to deploying the
* new version.
* @param client
* @param artifact
* @param target
* @throws Exception
*/
protected BaseArtifactType getCurrentlyDeployedVersion(SrampAtomApiClient client,
BaseArtifactType artifact, Target target) throws Exception {
BaseArtifactType currentVersionArtifact = null;
// Let's try to find the currently deployed version.
String classifier = target.getClassifier();
// Try to find a currently deployed version of this artifact based on maven information.
String mavenArtifactId = SrampModelUtils.getCustomProperty(artifact, "maven.artifactId"); //$NON-NLS-1$
String mavenGroupId = SrampModelUtils.getCustomProperty(artifact, "maven.groupId"); //$NON-NLS-1$
if (mavenArtifactId != null && mavenGroupId != null) {
QueryResultSet resultSet = client.buildQuery("/s-ramp[@maven.artifactId = ? and @maven.groupId = ? and s-ramp:exactlyClassifiedByAllOf(., ?)]") //$NON-NLS-1$
.parameter(mavenArtifactId).parameter(mavenGroupId).parameter(classifier).count(2).query();
if (resultSet.size() == 2) {
throw new Exception(Messages.i18n.format("DeploymentResource.MultipleMavenDeployments", target.getName(), artifact.getName())); //$NON-NLS-1$
}
if (resultSet.size() == 1) {
// Found a previous maven version deployed to the target
currentVersionArtifact = client.getArtifactMetaData(resultSet.get(0));
}
}
// Try to find a currently deployed version of this artifact based on a simple deployment name match.
if (currentVersionArtifact == null) {
String name = artifact.getName();
QueryResultSet resultSet = client.buildQuery("/s-ramp[@name = ? and s-ramp:exactlyClassifiedByAllOf(., ?)]") //$NON-NLS-1$
.parameter(name).parameter(classifier).count(2).query();
if (resultSet.size() == 2) {
throw new Exception(Messages.i18n.format("DeploymentResource.MultipleSimpleDeployments", target.getName(), artifact.getName())); //$NON-NLS-1$
}
if (resultSet.size() == 1) {
// Found a previous maven version deployed to the target
currentVersionArtifact = client.getArtifactMetaData(resultSet.get(0));
}
}
// Try to find a currently deployed version of this artifact based on a simple deployment name match.
if (currentVersionArtifact == null) {
// TODO: try to find currently deployed version of this artifact based on some form of versioning (TBD)
}
return currentVersionArtifact;
}
/**
* Undeploys the given artifact. Uses information recorded when that artifact was originally
* deployed (see {@link #recordUndeploymentInfo(BaseArtifactType, Target, Map, SrampAtomApiClient)}).
* @param request
* @param client
* @param prevVersionArtifact
* @param target
* @param deployer
* @throws Exception
*/
protected void undeploy(HttpServletRequest request, SrampAtomApiClient client,
BaseArtifactType prevVersionArtifact, Target target, Deployer deployer) throws Exception {
// Find the undeployment information for the artifact
QueryResultSet resultSet = client.buildQuery("/s-ramp/ext/UndeploymentInformation[describesDeployment[@uuid = ?] and @deploy.target = ?]") //$NON-NLS-1$
.parameter(prevVersionArtifact.getUuid()).parameter(target.getName()).count(2).query();
if (resultSet.size() == 1) {
// Found it
BaseArtifactType undeployInfo = client.getArtifactMetaData(resultSet.get(0));
deployer.undeploy(prevVersionArtifact, undeployInfo, target, client);
String deploymentClassifier = SrampModelUtils.getCustomProperty(undeployInfo, "deploy.classifier"); //$NON-NLS-1$
// re-fetch the artifact to get the latest meta-data
prevVersionArtifact = client.getArtifactMetaData(ArtifactType.valueOf(prevVersionArtifact), prevVersionArtifact.getUuid());
// remove the deployment classifier from the deployment
prevVersionArtifact.getClassifiedBy().remove(deploymentClassifier);
client.updateArtifactMetaData(prevVersionArtifact);
// remove the undeployment information (no longer needed)
client.deleteArtifact(undeployInfo.getUuid(), ArtifactType.valueOf(undeployInfo));
// Add a custom audit record to the artifact
////////////////////////////////////////////
try {
AuditEntry auditEntry = new AuditEntry();
auditEntry.setType("deploy:undeploy"); //$NON-NLS-1$
DatatypeFactory dtFactory = DatatypeFactory.newInstance();
XMLGregorianCalendar now = dtFactory.newXMLGregorianCalendar((GregorianCalendar)Calendar.getInstance());
auditEntry.setWhen(now);
auditEntry.setWho(request.getRemoteUser());
AuditItemType item = AuditUtils.getOrCreateAuditItem(auditEntry, "deploy:info"); //$NON-NLS-1$
AuditUtils.setAuditItemProperty(item, "target", target.getName()); //$NON-NLS-1$
AuditUtils.setAuditItemProperty(item, "classifier", target.getClassifier()); //$NON-NLS-1$
client.addAuditEntry(prevVersionArtifact.getUuid(), auditEntry);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
} else {
logger.warn(Messages.i18n.format("DeploymentResource.UndeploymentInfoNotFound", prevVersionArtifact.getName())); //$NON-NLS-1$
}
}
}
| dtgov-war/src/main/java/org/overlord/sramp/governance/services/DeploymentResource.java | /*
* Copyright 2013 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.sramp.governance.services;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import org.oasis_open.docs.s_ramp.ns.s_ramp_v1.BaseArtifactType;
import org.overlord.dtgov.common.Target;
import org.overlord.dtgov.server.i18n.Messages;
import org.overlord.dtgov.services.deploy.Deployer;
import org.overlord.dtgov.services.deploy.DeployerFactory;
import org.overlord.sramp.atom.err.SrampAtomException;
import org.overlord.sramp.client.SrampAtomApiClient;
import org.overlord.sramp.client.query.QueryResultSet;
import org.overlord.sramp.common.ArtifactType;
import org.overlord.sramp.common.SrampModelUtils;
import org.overlord.sramp.governance.Governance;
import org.overlord.sramp.governance.GovernanceConstants;
import org.overlord.sramp.governance.SlashDecoder;
import org.overlord.sramp.governance.SrampAtomApiClientFactory;
import org.overlord.sramp.governance.ValueEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The JAX-RS resource that handles deployment specific tasks.
*/
@Path("/deploy")
public class DeploymentResource {
private static Logger logger = LoggerFactory.getLogger(DeploymentResource.class);
/**
* Constructor.
*/
public DeploymentResource() {
}
/**
* The deployment endpoint - processes can invoke this endpoint to deploy
* a deployment based on configuration of the provided target.
* @param request
* @param targetRef
* @param uuid
* @throws Exception
*/
@POST
@Path("{target}/{uuid}")
@Produces("application/xml")
public Map<String,ValueEntity> deploy(@Context HttpServletRequest request,
@PathParam("target") String targetRef,
@PathParam("uuid") String uuid) throws Exception {
Governance governance = new Governance();
Map<String, ValueEntity> results = new HashMap<String,ValueEntity>();
// 0. run the decoder on the arguments
targetRef = SlashDecoder.decode(targetRef);
uuid = SlashDecoder.decode(uuid);
// get the artifact from the repo
////////////////////////////////////////////
SrampAtomApiClient client = SrampAtomApiClientFactory.createAtomApiClient();
BaseArtifactType artifact = client.getArtifactMetaData(uuid);
// get the deployment environment settings
////////////////////////////////////////////
Target target = governance.getTargets().get(targetRef);
if (target == null) {
logger.error(Messages.i18n.format("DeploymentResource.NoTarget", targetRef)); //$NON-NLS-1$
throw new SrampAtomException(Messages.i18n.format("DeploymentResource.NoTarget", targetRef)); //$NON-NLS-1$
}
// get the previous version of the deployment (so we can undeploy it)
////////////////////////////////////////////
BaseArtifactType prevVersionArtifact = getCurrentlyDeployedVersion(client, artifact, target);
Deployer deployer = DeployerFactory.createDeployer(target.getType().name());
if (deployer == null) {
throw new Exception(Messages.i18n.format(
"DeploymentResource.TargetTypeNotFound", target.getType())); //$NON-NLS-1$
}
if (prevVersionArtifact != null) {
undeploy(client, prevVersionArtifact, target, deployer);
}
// deploy the artifact (delegate based on target type)
////////////////////////////////////////////
String deploymentTarget = target.getType().toString() + ":"; //$NON-NLS-1$
try {
deploymentTarget += deployer.deploy(artifact, target, client);
} catch (Exception e) {
logger.error(e.getMessage(), e);
results.put(GovernanceConstants.STATUS, new ValueEntity("fail")); //$NON-NLS-1$
results.put(GovernanceConstants.MESSAGE, new ValueEntity(e.getMessage()));
return results;
}
// update the artifact meta-data to set the classifier
////////////////////////////////////////////
String deploymentClassifier = target.getClassifier();
try {
// refresh the artifact meta-data in case something changed since we originally retrieved it
artifact = client.getArtifactMetaData(uuid);
artifact.getClassifiedBy().add(deploymentClassifier);
client.updateArtifactMetaData(artifact);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
results.put(GovernanceConstants.STATUS, new ValueEntity("success")); //$NON-NLS-1$
results.put(GovernanceConstants.TARGET, new ValueEntity(deploymentTarget));
return results;
}
/**
* Finds the currently deployed version of the given artifact. This basically needs to
* return the version of the artifact that is currently deployed to the given target.
* This is important so that we can undeploy that old version prior to deploying the
* new version.
* @param client
* @param artifact
* @param target
* @throws Exception
*/
protected BaseArtifactType getCurrentlyDeployedVersion(SrampAtomApiClient client,
BaseArtifactType artifact, Target target) throws Exception {
BaseArtifactType currentVersionArtifact = null;
// Let's try to find the currently deployed version.
String classifier = target.getClassifier();
// Try to find a currently deployed version of this artifact based on maven information.
String mavenArtifactId = SrampModelUtils.getCustomProperty(artifact, "maven.artifactId"); //$NON-NLS-1$
String mavenGroupId = SrampModelUtils.getCustomProperty(artifact, "maven.groupId"); //$NON-NLS-1$
if (mavenArtifactId != null && mavenGroupId != null) {
QueryResultSet resultSet = client.buildQuery("/s-ramp[@maven.artifactId = ? and @maven.groupId = ? and s-ramp:exactlyClassifiedByAllOf(., ?)]") //$NON-NLS-1$
.parameter(mavenArtifactId).parameter(mavenGroupId).parameter(classifier).count(2).query();
if (resultSet.size() == 2) {
throw new Exception(Messages.i18n.format("DeploymentResource.MultipleMavenDeployments", target.getName(), artifact.getName())); //$NON-NLS-1$
}
if (resultSet.size() == 1) {
// Found a previous maven version deployed to the target
currentVersionArtifact = client.getArtifactMetaData(resultSet.get(0));
}
}
// Try to find a currently deployed version of this artifact based on a simple deployment name match.
if (currentVersionArtifact == null) {
String name = artifact.getName();
QueryResultSet resultSet = client.buildQuery("/s-ramp[@name = ? and s-ramp:exactlyClassifiedByAllOf(., ?)]") //$NON-NLS-1$
.parameter(name).parameter(classifier).count(2).query();
if (resultSet.size() == 2) {
throw new Exception(Messages.i18n.format("DeploymentResource.MultipleSimpleDeployments", target.getName(), artifact.getName())); //$NON-NLS-1$
}
if (resultSet.size() == 1) {
// Found a previous maven version deployed to the target
currentVersionArtifact = client.getArtifactMetaData(resultSet.get(0));
}
}
// Try to find a currently deployed version of this artifact based on a simple deployment name match.
if (currentVersionArtifact == null) {
// TODO: try to find currently deployed version of this artifact based on some form of versioning (TBD)
}
return currentVersionArtifact;
}
/**
* Undeploys the given artifact. Uses information recorded when that artifact was originally
* deployed (see {@link #recordUndeploymentInfo(BaseArtifactType, Target, Map, SrampAtomApiClient)}).
* @param client
* @param prevVersionArtifact
* @param target
* @throws Exception
*/
protected void undeploy(SrampAtomApiClient client, BaseArtifactType prevVersionArtifact, Target target,
Deployer deployer)
throws Exception {
// Find the undeployment information for the artifact
QueryResultSet resultSet = client.buildQuery("/s-ramp/ext/UndeploymentInformation[describesDeployment[@uuid = ?] and @deploy.target = ?]") //$NON-NLS-1$
.parameter(prevVersionArtifact.getUuid()).parameter(target.getName()).count(2).query();
if (resultSet.size() == 1) {
// Found it
BaseArtifactType undeployInfo = client.getArtifactMetaData(resultSet.get(0));
deployer.undeploy(prevVersionArtifact, undeployInfo, target, client);
String deploymentClassifier = SrampModelUtils.getCustomProperty(undeployInfo, "deploy.classifier"); //$NON-NLS-1$
// re-fetch the artifact to get the latest meta-data
prevVersionArtifact = client.getArtifactMetaData(ArtifactType.valueOf(prevVersionArtifact), prevVersionArtifact.getUuid());
// remove the deployment classifier from the deployment
prevVersionArtifact.getClassifiedBy().remove(deploymentClassifier);
client.updateArtifactMetaData(prevVersionArtifact);
// remove the undeployment information (no longer needed)
client.deleteArtifact(undeployInfo.getUuid(), ArtifactType.valueOf(undeployInfo));
} else {
logger.warn(Messages.i18n.format("DeploymentResource.UndeploymentInfoNotFound", prevVersionArtifact.getName())); //$NON-NLS-1$
}
}
}
| Fix for: https://issues.jboss.org/browse/DTGOV-63
| dtgov-war/src/main/java/org/overlord/sramp/governance/services/DeploymentResource.java | Fix for: https://issues.jboss.org/browse/DTGOV-63 | <ide><path>tgov-war/src/main/java/org/overlord/sramp/governance/services/DeploymentResource.java
<ide> */
<ide> package org.overlord.sramp.governance.services;
<ide>
<add>import java.util.Calendar;
<add>import java.util.GregorianCalendar;
<ide> import java.util.HashMap;
<ide> import java.util.Map;
<ide>
<ide> import javax.ws.rs.PathParam;
<ide> import javax.ws.rs.Produces;
<ide> import javax.ws.rs.core.Context;
<del>
<add>import javax.xml.datatype.DatatypeFactory;
<add>import javax.xml.datatype.XMLGregorianCalendar;
<add>
<add>import org.jboss.downloads.overlord.sramp._2013.auditing.AuditEntry;
<add>import org.jboss.downloads.overlord.sramp._2013.auditing.AuditItemType;
<ide> import org.oasis_open.docs.s_ramp.ns.s_ramp_v1.BaseArtifactType;
<ide> import org.overlord.dtgov.common.Target;
<ide> import org.overlord.dtgov.server.i18n.Messages;
<ide> import org.overlord.sramp.client.query.QueryResultSet;
<ide> import org.overlord.sramp.common.ArtifactType;
<ide> import org.overlord.sramp.common.SrampModelUtils;
<add>import org.overlord.sramp.common.audit.AuditUtils;
<ide> import org.overlord.sramp.governance.Governance;
<ide> import org.overlord.sramp.governance.GovernanceConstants;
<ide> import org.overlord.sramp.governance.SlashDecoder;
<ide> }
<ide>
<ide> if (prevVersionArtifact != null) {
<del> undeploy(client, prevVersionArtifact, target, deployer);
<add> undeploy(request, client, prevVersionArtifact, target, deployer);
<ide> }
<ide>
<ide> // deploy the artifact (delegate based on target type)
<ide> } catch (Exception e) {
<ide> logger.error(e.getMessage(), e);
<ide> }
<add>
<add> // Add a custom audit record to the artifact
<add> ////////////////////////////////////////////
<add> try {
<add> AuditEntry auditEntry = new AuditEntry();
<add> auditEntry.setType("deploy:deploy"); //$NON-NLS-1$
<add> DatatypeFactory dtFactory = DatatypeFactory.newInstance();
<add> XMLGregorianCalendar now = dtFactory.newXMLGregorianCalendar((GregorianCalendar)Calendar.getInstance());
<add> auditEntry.setWhen(now);
<add> auditEntry.setWho(request.getRemoteUser());
<add> AuditItemType item = AuditUtils.getOrCreateAuditItem(auditEntry, "deploy:info"); //$NON-NLS-1$
<add> AuditUtils.setAuditItemProperty(item, "target", target.getName()); //$NON-NLS-1$
<add> AuditUtils.setAuditItemProperty(item, "classifier", target.getClassifier()); //$NON-NLS-1$
<add> client.addAuditEntry(uuid, auditEntry);
<add> } catch (Exception e) {
<add> logger.error(e.getMessage(), e);
<add> }
<ide>
<ide> results.put(GovernanceConstants.STATUS, new ValueEntity("success")); //$NON-NLS-1$
<ide> results.put(GovernanceConstants.TARGET, new ValueEntity(deploymentTarget));
<ide> /**
<ide> * Undeploys the given artifact. Uses information recorded when that artifact was originally
<ide> * deployed (see {@link #recordUndeploymentInfo(BaseArtifactType, Target, Map, SrampAtomApiClient)}).
<add> * @param request
<ide> * @param client
<ide> * @param prevVersionArtifact
<ide> * @param target
<add> * @param deployer
<ide> * @throws Exception
<ide> */
<del> protected void undeploy(SrampAtomApiClient client, BaseArtifactType prevVersionArtifact, Target target,
<del> Deployer deployer)
<del> throws Exception {
<add> protected void undeploy(HttpServletRequest request, SrampAtomApiClient client,
<add> BaseArtifactType prevVersionArtifact, Target target, Deployer deployer) throws Exception {
<ide> // Find the undeployment information for the artifact
<ide> QueryResultSet resultSet = client.buildQuery("/s-ramp/ext/UndeploymentInformation[describesDeployment[@uuid = ?] and @deploy.target = ?]") //$NON-NLS-1$
<ide> .parameter(prevVersionArtifact.getUuid()).parameter(target.getName()).count(2).query();
<ide> client.updateArtifactMetaData(prevVersionArtifact);
<ide> // remove the undeployment information (no longer needed)
<ide> client.deleteArtifact(undeployInfo.getUuid(), ArtifactType.valueOf(undeployInfo));
<add>
<add> // Add a custom audit record to the artifact
<add> ////////////////////////////////////////////
<add> try {
<add> AuditEntry auditEntry = new AuditEntry();
<add> auditEntry.setType("deploy:undeploy"); //$NON-NLS-1$
<add> DatatypeFactory dtFactory = DatatypeFactory.newInstance();
<add> XMLGregorianCalendar now = dtFactory.newXMLGregorianCalendar((GregorianCalendar)Calendar.getInstance());
<add> auditEntry.setWhen(now);
<add> auditEntry.setWho(request.getRemoteUser());
<add> AuditItemType item = AuditUtils.getOrCreateAuditItem(auditEntry, "deploy:info"); //$NON-NLS-1$
<add> AuditUtils.setAuditItemProperty(item, "target", target.getName()); //$NON-NLS-1$
<add> AuditUtils.setAuditItemProperty(item, "classifier", target.getClassifier()); //$NON-NLS-1$
<add> client.addAuditEntry(prevVersionArtifact.getUuid(), auditEntry);
<add> } catch (Exception e) {
<add> logger.error(e.getMessage(), e);
<add> }
<add>
<ide> } else {
<ide> logger.warn(Messages.i18n.format("DeploymentResource.UndeploymentInfoNotFound", prevVersionArtifact.getName())); //$NON-NLS-1$
<ide> } |
|
Java | apache-2.0 | f2c560c5eb44b0325e68e73120d7944d0beccd0d | 0 | sangupta/outline | /**
*
* outline - command line argument parser
* Copyright (c) 2015-2016, Sandeep Gupta
*
* http://sangupta.com/projects/outline
*
* 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.sangupta.outline.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used to capture one single argument at a time.
*
* @author sangupta
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface Argument {
int order() default 0;
/**
* Title for the argument - by which it will show up in help
*/
String title() default "";
/**
* A description of the argument - details on what it does
*/
String description() default "";
/**
* Whether this arguments are required.
*/
boolean required() default false;
}
| src/main/java/com/sangupta/outline/annotations/Argument.java | /**
*
* outline - command line argument parser
* Copyright (c) 2015-2016, Sandeep Gupta
*
* http://sangupta.com/projects/outline
*
* 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.sangupta.outline.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used to capture one single argument at a time.
*
* @author sangupta
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface Argument {
int order() default 0;
/**
* Title for the argument - by which it will show up in help
*/
String title() default "";
/**
* A description of the argument - details on what it does
*/
String description() default "";
/**
* Argument usage for help.
*/
String usage() default "";
/**
* Whether this arguments are required.
*/
boolean required() default false;
}
| Argument.usage() in duplicate of Argument.title() | src/main/java/com/sangupta/outline/annotations/Argument.java | Argument.usage() in duplicate of Argument.title() | <ide><path>rc/main/java/com/sangupta/outline/annotations/Argument.java
<ide> String description() default "";
<ide>
<ide> /**
<del> * Argument usage for help.
<del> */
<del> String usage() default "";
<del>
<del> /**
<ide> * Whether this arguments are required.
<ide> */
<ide> boolean required() default false; |
|
Java | lgpl-2.1 | cf935cf276e559f2c41e2915541dfe6e7429fe90 | 0 | Nuchaz/carpentersblocks,Mineshopper/carpentersblocks,Techern/carpentersblocks,burpingdog1/carpentersblocks | package com.carpentersblocks.block;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import com.carpentersblocks.data.Collapsible;
import com.carpentersblocks.tileentity.TEBase;
import com.carpentersblocks.util.BlockProperties;
import com.carpentersblocks.util.collapsible.CollapsibleUtil;
import com.carpentersblocks.util.handler.EventHandler;
import com.carpentersblocks.util.registry.BlockRegistry;
import com.carpentersblocks.util.registry.ItemRegistry;
public class BlockCarpentersCollapsibleBlock extends BlockCoverable {
private static Collapsible data = new Collapsible();
public BlockCarpentersCollapsibleBlock(Material material)
{
super(material);
}
@Override
/**
* Raise quadrant of block.
*/
protected boolean onHammerLeftClick(TEBase TE, EntityPlayer entityPlayer)
{
int quad = Collapsible.getQuad(EventHandler.hitX, EventHandler.hitZ);
int quadHeight = Collapsible.getQuadHeight(TE, quad);
Collapsible.setQuadHeight(TE, quad, --quadHeight);
smoothAdjacentCollapsibles(TE, quad);
return true;
}
@Override
/**
* Lower quadrant of block.
*/
protected boolean onHammerRightClick(TEBase TE, EntityPlayer entityPlayer)
{
int quad = Collapsible.getQuad(EventHandler.hitX, EventHandler.hitZ);
int quadHeight = Collapsible.getQuadHeight(TE, quad);
Collapsible.setQuadHeight(TE, quad, ++quadHeight);
smoothAdjacentCollapsibles(TE, quad);
return true;
}
@Override
/**
* Damages hammer with a chance to not damage.
*/
protected void damageItemWithChance(World world, EntityPlayer entityPlayer)
{
if (world.rand.nextFloat() <= ItemRegistry.itemHammerDamageChanceFromCollapsible) {
super.damageItemWithChance(world, entityPlayer);
}
}
/**
* Will attempt to smooth transitions to any adjacent collapsible blocks
* given a TE and source quadrant.
*/
private void smoothAdjacentCollapsibles(TEBase TE, int src_quadrant)
{
World world = TE.getWorldObj();
TEBase TE_XN = getTileEntity(world, TE.xCoord - 1, TE.yCoord, TE.zCoord);
TEBase TE_XP = getTileEntity(world, TE.xCoord + 1, TE.yCoord, TE.zCoord);
TEBase TE_ZN = getTileEntity(world, TE.xCoord, TE.yCoord, TE.zCoord - 1);
TEBase TE_ZP = getTileEntity(world, TE.xCoord, TE.yCoord, TE.zCoord + 1);
TEBase TE_XZNN = getTileEntity(world, TE.xCoord - 1, TE.yCoord, TE.zCoord - 1);
TEBase TE_XZNP = getTileEntity(world, TE.xCoord - 1, TE.yCoord, TE.zCoord + 1);
TEBase TE_XZPN = getTileEntity(world, TE.xCoord + 1, TE.yCoord, TE.zCoord - 1);
TEBase TE_XZPP = getTileEntity(world, TE.xCoord + 1, TE.yCoord, TE.zCoord + 1);
int height = Collapsible.getQuadHeight(TE, src_quadrant);
switch (src_quadrant)
{
case Collapsible.QUAD_XZNN:
if (TE_ZN != null) {
Collapsible.setQuadHeight(TE_ZN, Collapsible.QUAD_XZNP, height);
}
if (TE_XZNN != null) {
Collapsible.setQuadHeight(TE_XZNN, Collapsible.QUAD_XZPP, height);
}
if (TE_XN != null) {
Collapsible.setQuadHeight(TE_XN, Collapsible.QUAD_XZPN, height);
}
break;
case Collapsible.QUAD_XZNP:
if (TE_XN != null) {
Collapsible.setQuadHeight(TE_XN, Collapsible.QUAD_XZPP, height);
}
if (TE_XZNP != null) {
Collapsible.setQuadHeight(TE_XZNP, Collapsible.QUAD_XZPN, height);
}
if (TE_ZP != null) {
Collapsible.setQuadHeight(TE_ZP, Collapsible.QUAD_XZNN, height);
}
break;
case Collapsible.QUAD_XZPN:
if (TE_XP != null) {
Collapsible.setQuadHeight(TE_XP, Collapsible.QUAD_XZNN, height);
}
if (TE_XZPN != null) {
Collapsible.setQuadHeight(TE_XZPN, Collapsible.QUAD_XZNP, height);
}
if (TE_ZN != null) {
Collapsible.setQuadHeight(TE_ZN, Collapsible.QUAD_XZPP, height);
}
break;
case Collapsible.QUAD_XZPP:
if (TE_ZP != null) {
Collapsible.setQuadHeight(TE_ZP, Collapsible.QUAD_XZPN, height);
}
if (TE_XZPP != null) {
Collapsible.setQuadHeight(TE_XZPP, Collapsible.QUAD_XZNN, height);
}
if (TE_XP != null) {
Collapsible.setQuadHeight(TE_XP, Collapsible.QUAD_XZNP, height);
}
break;
}
}
@Override
/**
* Updates the blocks bounds based on its current state. Args: world, x, y, z
*/
public void setBlockBoundsBasedOnState(IBlockAccess world, int x, int y, int z)
{
TEBase TE = getTileEntity(world, x, y, z);
float maxHeight = CollapsibleUtil.getBoundsMaxHeight(TE);
if (maxHeight != 1.0F) {
setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, maxHeight, 1.0F);
}
}
@Override
/**
* Checks if the block is a solid face on the given side, used by placement logic.
*/
public boolean isSideSolid(IBlockAccess world, int x, int y, int z, ForgeDirection side)
{
TEBase TE = getTileEntity(world, x, y, z);
if (TE != null) {
if (isBlockSolid(world, x, y, z)) {
switch (side) {
case UP:
return BlockProperties.getMetadata(TE) == 0;
case NORTH:
return Collapsible.getQuadHeight(TE, Collapsible.QUAD_XZNN) + Collapsible.getQuadHeight(TE, Collapsible.QUAD_XZPN) == 32;
case SOUTH:
return Collapsible.getQuadHeight(TE, Collapsible.QUAD_XZNP) + Collapsible.getQuadHeight(TE, Collapsible.QUAD_XZPP) == 32;
case WEST:
return Collapsible.getQuadHeight(TE, Collapsible.QUAD_XZNP) + Collapsible.getQuadHeight(TE, Collapsible.QUAD_XZNN) == 32;
case EAST:
return Collapsible.getQuadHeight(TE, Collapsible.QUAD_XZPN) + Collapsible.getQuadHeight(TE, Collapsible.QUAD_XZPP) == 32;
default:
return true;
}
}
}
return false;
}
/**
* Returns true if a slope should end at the given coords
*/
private boolean isSlopeBoundary(World world, int x, int y, int z)
{
TEBase TE = getTileEntity(world, x, y, z);
if (TE != null) {
return true;
}
return world.getBlock(x, y, z).getMaterial().blocksMovement() || !world.getBlock(x, y - 1, z).getMaterial().blocksMovement();
}
/**
* Scan X axis for slopes
*/
private int scanX(World world, int x, int y, int z, int dir, int maxDist)
{
for (int nx = x + dir; nx != x + maxDist * dir; nx += dir) {
if (isSlopeBoundary(world, nx, y, z)) {
return nx;
}
}
return x + dir;
}
/**
* Scan Z axis for slopes
*/
private int scanZ(World world, int x, int y, int z, int dir, int maxDist)
{
for (int nz = z + dir; nz != z + maxDist * dir; nz += dir) {
if (isSlopeBoundary(world, x, y, nz)) {
return nz;
}
}
return z + dir;
}
/**
* Returns block height
*/
private static int getBlockHeight(IBlockAccess world, int x, int y, int z)
{
Block block = world.getBlock(x, y, z);
if (!block.getMaterial().blocksMovement()) {
return 1;
}
return (int) (block.getBlockBoundsMaxY() * 15.0 + 1.0);
}
@Override
/**
* Called when the block is placed in the world.
*/
public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entityLiving, ItemStack itemStack)
{
/* If shift key is down, skip auto-setting quadrant heights. */
if (!entityLiving.isSneaking()) {
TEBase TE = getTileEntity(world, x, y, z);
if (TE != null) {
/* Create a linear slope from neighbor blocks and collapsible quadrants. */
/* Mininum and maximum height of quadrants */
final int MIN_HEIGHT = 1;
final int MAX_HEIGHT = 16;
/* find slopes in landscape */
int xn = scanX(world, x, y, z, -1, MAX_HEIGHT);
int xp = scanX(world, x, y, z, 1, MAX_HEIGHT);
int zn = scanZ(world, x, y, z, -1, MAX_HEIGHT);
int zp = scanZ(world, x, y, z, 1, MAX_HEIGHT);
TEBase TE_XN = getTileEntity(world, xn, y, z);
TEBase TE_XP = getTileEntity(world, xp, y, z);
TEBase TE_ZN = getTileEntity(world, x, y, zn);
TEBase TE_ZP = getTileEntity(world, x, y, zp);
int height_XZNN = MIN_HEIGHT, height_XZPN = MIN_HEIGHT, height_XZPP = MIN_HEIGHT, height_XZNP = MIN_HEIGHT;
int hxn1, hxn2;
if(TE_XN != null) {
hxn1 = Collapsible.getQuadHeight(TE_XN, Collapsible.QUAD_XZPN);
hxn2 = Collapsible.getQuadHeight(TE_XN, Collapsible.QUAD_XZPP);
} else {
hxn1 = hxn2 = getBlockHeight(world, xn, y, z);
}
int hxp1, hxp2;
if(TE_XP != null) {
hxp1 = Collapsible.getQuadHeight(TE_XP, Collapsible.QUAD_XZNN);
hxp2 = Collapsible.getQuadHeight(TE_XP, Collapsible.QUAD_XZNP);
} else {
hxp1 = hxp2 = getBlockHeight(world, xp, y, z);
}
int hzn1, hzn2;
if(TE_ZN != null) {
hzn1 = Collapsible.getQuadHeight(TE_ZN, Collapsible.QUAD_XZNP);
hzn2 = Collapsible.getQuadHeight(TE_ZN, Collapsible.QUAD_XZPP);
} else {
hzn1 = hzn2 = getBlockHeight(world, x, y, zn);
}
int hzp1, hzp2;
if(TE_ZP != null) {
hzp1 = Collapsible.getQuadHeight(TE_ZP, Collapsible.QUAD_XZNN);
hzp2 = Collapsible.getQuadHeight(TE_ZP, Collapsible.QUAD_XZPN);
} else {
hzp1 = hzp2 = getBlockHeight(world, x, y, zp);
}
/* lerp between heights, create smooth slope */
int xdist = x - xn;
double dx1 = (double)(hxp1 - hxn1) / (xp - xn - 1);
double dx2 = (double)(hxp2 - hxn2) / (xp - xn - 1);
height_XZNN = Math.max(height_XZNN, (int)(hxn1 + dx1 * (xdist - 1)));
height_XZNP = Math.max(height_XZNP, (int)(hxn2 + dx2 * (xdist - 1)));
height_XZPN = Math.max(height_XZPN, (int)(hxn1 + dx1 * xdist));
height_XZPP = Math.max(height_XZPP, (int)(hxn2 + dx2 * xdist));
int zdist = z - zn;
double dz1 = (double)(hzp1 - hzn1) / (zp - zn - 1);
double dz2 = (double)(hzp2 - hzn2) / (zp - zn - 1);
height_XZNN = Math.max(height_XZNN, (int)(hzn1 + dz1 * (zdist - 1)));
height_XZNP = Math.max(height_XZNP, (int)(hzn1 + dz1 * zdist));
height_XZPN = Math.max(height_XZPN, (int)(hzn2 + dz2 * (zdist - 1)));
height_XZPP = Math.max(height_XZPP, (int)(hzn2 + dz2 * zdist));
Collapsible.setQuadHeight(TE, Collapsible.QUAD_XZNN, height_XZNN);
Collapsible.setQuadHeight(TE, Collapsible.QUAD_XZNP, height_XZNP);
Collapsible.setQuadHeight(TE, Collapsible.QUAD_XZPP, height_XZPP);
Collapsible.setQuadHeight(TE, Collapsible.QUAD_XZPN, height_XZPN);
for (int quad = 0; quad < 4; ++quad) {
smoothAdjacentCollapsibles(TE, quad);
}
}
}
super.onBlockPlacedBy(world, x, y, z, entityLiving, itemStack);
}
@Override
/**
* Adds all intersecting collision boxes to a list. (Be sure to only add boxes to the list if they intersect the
* mask.) Parameters: World, X, Y, Z, mask, list, colliding entity
*/
public void addCollisionBoxesToList(World world, int x, int y, int z, AxisAlignedBB axisAlignedBB, List list, Entity entity)
{
TEBase TE = getTileEntity(world, x, y, z);
if (TE != null) {
AxisAlignedBB colBox = null;
for (int quad = 0; quad < 4; ++quad)
{
float[] bounds = CollapsibleUtil.genBounds(TE, quad);
colBox = AxisAlignedBB.getBoundingBox(x + bounds[0], y + bounds[1], z + bounds[2], x + bounds[3], y + bounds[4], z + bounds[5]);
if (axisAlignedBB.intersectsWith(colBox)) {
list.add(colBox);
}
}
}
}
@Override
/**
* Ray traces through the blocks collision from start vector to end vector returning a ray trace hit. Args: world,
* x, y, z, startVec, endVec
*/
public MovingObjectPosition collisionRayTrace(World world, int x, int y, int z, Vec3 startVec, Vec3 endVec)
{
TEBase TE = getTileEntity(world, x, y, z);
MovingObjectPosition finalTrace = null;
if (TE != null) {
double currDist = 0.0D;
double maxDist = 0.0D;
// Determine if ray trace is a hit on block
for (int quad = 0; quad < 4; ++quad)
{
float[] bounds = CollapsibleUtil.genBounds(TE, quad);
setBlockBounds(bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]);
MovingObjectPosition traceResult = super.collisionRayTrace(world, x, y, z, startVec, endVec);
if (traceResult != null)
{
currDist = traceResult.hitVec.squareDistanceTo(endVec);
if (currDist > maxDist) {
finalTrace = traceResult;
maxDist = currDist;
}
}
}
/* Determine true face hit since it's built of quadrants. */
if (finalTrace != null) {
setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
finalTrace = super.collisionRayTrace(world, x, y, z, startVec, endVec);
}
}
return finalTrace;
}
@Override
/**
* Returns whether sides share faces based on sloping property and face shape.
*/
protected boolean shareFaces(TEBase TE_adj, TEBase TE_src, ForgeDirection side_adj, ForgeDirection side_src)
{
if (TE_adj.getBlockType() == this) {
switch (side_adj) {
case NORTH:
return data.getQuadHeight(TE_adj, data.QUAD_XZNN) == data.getQuadHeight(TE_src, data.QUAD_XZNP) &&
data.getQuadHeight(TE_adj, data.QUAD_XZPN) == data.getQuadHeight(TE_src, data.QUAD_XZPP);
case SOUTH:
return data.getQuadHeight(TE_adj, data.QUAD_XZNP) == data.getQuadHeight(TE_src, data.QUAD_XZNN) &&
data.getQuadHeight(TE_adj, data.QUAD_XZPP) == data.getQuadHeight(TE_src, data.QUAD_XZPN);
case WEST:
return data.getQuadHeight(TE_adj, data.QUAD_XZNP) == data.getQuadHeight(TE_src, data.QUAD_XZPP) &&
data.getQuadHeight(TE_adj, data.QUAD_XZNN) == data.getQuadHeight(TE_src, data.QUAD_XZPN);
case EAST:
return data.getQuadHeight(TE_adj, data.QUAD_XZPP) == data.getQuadHeight(TE_src, data.QUAD_XZNP) &&
data.getQuadHeight(TE_adj, data.QUAD_XZPN) == data.getQuadHeight(TE_src, data.QUAD_XZNN);
default: {}
}
}
return super.shareFaces(TE_adj, TE_src, side_adj, side_src);
}
@Override
/**
* The type of render function that is called for this block
*/
public int getRenderType()
{
return BlockRegistry.carpentersCollapsibleBlockRenderID;
}
}
| src/main/java/com/carpentersblocks/block/BlockCarpentersCollapsibleBlock.java | package com.carpentersblocks.block;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import com.carpentersblocks.data.Collapsible;
import com.carpentersblocks.tileentity.TEBase;
import com.carpentersblocks.util.BlockProperties;
import com.carpentersblocks.util.collapsible.CollapsibleUtil;
import com.carpentersblocks.util.handler.EventHandler;
import com.carpentersblocks.util.registry.BlockRegistry;
import com.carpentersblocks.util.registry.ItemRegistry;
public class BlockCarpentersCollapsibleBlock extends BlockCoverable {
public BlockCarpentersCollapsibleBlock(Material material)
{
super(material);
}
@Override
/**
* Raise quadrant of block.
*/
protected boolean onHammerLeftClick(TEBase TE, EntityPlayer entityPlayer)
{
int quad = Collapsible.getQuad(EventHandler.hitX, EventHandler.hitZ);
int quadHeight = Collapsible.getQuadHeight(TE, quad);
Collapsible.setQuadHeight(TE, quad, --quadHeight);
smoothAdjacentCollapsibles(TE, quad);
return true;
}
@Override
/**
* Lower quadrant of block.
*/
protected boolean onHammerRightClick(TEBase TE, EntityPlayer entityPlayer)
{
int quad = Collapsible.getQuad(EventHandler.hitX, EventHandler.hitZ);
int quadHeight = Collapsible.getQuadHeight(TE, quad);
Collapsible.setQuadHeight(TE, quad, ++quadHeight);
smoothAdjacentCollapsibles(TE, quad);
return true;
}
@Override
/**
* Damages hammer with a chance to not damage.
*/
protected void damageItemWithChance(World world, EntityPlayer entityPlayer)
{
if (world.rand.nextFloat() <= ItemRegistry.itemHammerDamageChanceFromCollapsible) {
super.damageItemWithChance(world, entityPlayer);
}
}
/**
* Will attempt to smooth transitions to any adjacent collapsible blocks
* given a TE and source quadrant.
*/
private void smoothAdjacentCollapsibles(TEBase TE, int src_quadrant)
{
World world = TE.getWorldObj();
TEBase TE_XN = getTileEntity(world, TE.xCoord - 1, TE.yCoord, TE.zCoord);
TEBase TE_XP = getTileEntity(world, TE.xCoord + 1, TE.yCoord, TE.zCoord);
TEBase TE_ZN = getTileEntity(world, TE.xCoord, TE.yCoord, TE.zCoord - 1);
TEBase TE_ZP = getTileEntity(world, TE.xCoord, TE.yCoord, TE.zCoord + 1);
TEBase TE_XZNN = getTileEntity(world, TE.xCoord - 1, TE.yCoord, TE.zCoord - 1);
TEBase TE_XZNP = getTileEntity(world, TE.xCoord - 1, TE.yCoord, TE.zCoord + 1);
TEBase TE_XZPN = getTileEntity(world, TE.xCoord + 1, TE.yCoord, TE.zCoord - 1);
TEBase TE_XZPP = getTileEntity(world, TE.xCoord + 1, TE.yCoord, TE.zCoord + 1);
int height = Collapsible.getQuadHeight(TE, src_quadrant);
switch (src_quadrant)
{
case Collapsible.QUAD_XZNN:
if (TE_ZN != null) {
Collapsible.setQuadHeight(TE_ZN, Collapsible.QUAD_XZNP, height);
}
if (TE_XZNN != null) {
Collapsible.setQuadHeight(TE_XZNN, Collapsible.QUAD_XZPP, height);
}
if (TE_XN != null) {
Collapsible.setQuadHeight(TE_XN, Collapsible.QUAD_XZPN, height);
}
break;
case Collapsible.QUAD_XZNP:
if (TE_XN != null) {
Collapsible.setQuadHeight(TE_XN, Collapsible.QUAD_XZPP, height);
}
if (TE_XZNP != null) {
Collapsible.setQuadHeight(TE_XZNP, Collapsible.QUAD_XZPN, height);
}
if (TE_ZP != null) {
Collapsible.setQuadHeight(TE_ZP, Collapsible.QUAD_XZNN, height);
}
break;
case Collapsible.QUAD_XZPN:
if (TE_XP != null) {
Collapsible.setQuadHeight(TE_XP, Collapsible.QUAD_XZNN, height);
}
if (TE_XZPN != null) {
Collapsible.setQuadHeight(TE_XZPN, Collapsible.QUAD_XZNP, height);
}
if (TE_ZN != null) {
Collapsible.setQuadHeight(TE_ZN, Collapsible.QUAD_XZPP, height);
}
break;
case Collapsible.QUAD_XZPP:
if (TE_ZP != null) {
Collapsible.setQuadHeight(TE_ZP, Collapsible.QUAD_XZPN, height);
}
if (TE_XZPP != null) {
Collapsible.setQuadHeight(TE_XZPP, Collapsible.QUAD_XZNN, height);
}
if (TE_XP != null) {
Collapsible.setQuadHeight(TE_XP, Collapsible.QUAD_XZNP, height);
}
break;
}
}
@Override
/**
* Updates the blocks bounds based on its current state. Args: world, x, y, z
*/
public void setBlockBoundsBasedOnState(IBlockAccess world, int x, int y, int z)
{
TEBase TE = getTileEntity(world, x, y, z);
float maxHeight = CollapsibleUtil.getBoundsMaxHeight(TE);
if (maxHeight != 1.0F) {
setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, maxHeight, 1.0F);
}
}
@Override
/**
* Checks if the block is a solid face on the given side, used by placement logic.
*/
public boolean isSideSolid(IBlockAccess world, int x, int y, int z, ForgeDirection side)
{
TEBase TE = getTileEntity(world, x, y, z);
if (TE != null) {
if (isBlockSolid(world, x, y, z)) {
switch (side) {
case UP:
return BlockProperties.getMetadata(TE) == 0;
case NORTH:
return Collapsible.getQuadHeight(TE, Collapsible.QUAD_XZNN) + Collapsible.getQuadHeight(TE, Collapsible.QUAD_XZPN) == 32;
case SOUTH:
return Collapsible.getQuadHeight(TE, Collapsible.QUAD_XZNP) + Collapsible.getQuadHeight(TE, Collapsible.QUAD_XZPP) == 32;
case WEST:
return Collapsible.getQuadHeight(TE, Collapsible.QUAD_XZNP) + Collapsible.getQuadHeight(TE, Collapsible.QUAD_XZNN) == 32;
case EAST:
return Collapsible.getQuadHeight(TE, Collapsible.QUAD_XZPN) + Collapsible.getQuadHeight(TE, Collapsible.QUAD_XZPP) == 32;
default:
return true;
}
}
}
return false;
}
/**
* Returns true if a slope should end at the given coords
*/
private boolean isSlopeBoundary(World world, int x, int y, int z)
{
TEBase TE = getTileEntity(world, x, y, z);
if (TE != null) {
return true;
}
return world.getBlock(x, y, z).getMaterial().blocksMovement() || !world.getBlock(x, y - 1, z).getMaterial().blocksMovement();
}
/**
* Scan X axis for slopes
*/
private int scanX(World world, int x, int y, int z, int dir, int maxDist)
{
for (int nx = x + dir; nx != x + maxDist * dir; nx += dir) {
if (isSlopeBoundary(world, nx, y, z)) {
return nx;
}
}
return x + dir;
}
/**
* Scan Z axis for slopes
*/
private int scanZ(World world, int x, int y, int z, int dir, int maxDist)
{
for (int nz = z + dir; nz != z + maxDist * dir; nz += dir) {
if (isSlopeBoundary(world, x, y, nz)) {
return nz;
}
}
return z + dir;
}
/**
* Returns block height
*/
private static int getBlockHeight(IBlockAccess world, int x, int y, int z)
{
Block block = world.getBlock(x, y, z);
if (!block.getMaterial().blocksMovement()) {
return 1;
}
return (int) (block.getBlockBoundsMaxY() * 15.0 + 1.0);
}
@Override
/**
* Called when the block is placed in the world.
*/
public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entityLiving, ItemStack itemStack)
{
/* If shift key is down, skip auto-setting quadrant heights. */
if (!entityLiving.isSneaking()) {
TEBase TE = getTileEntity(world, x, y, z);
if (TE != null) {
/* Create a linear slope from neighbor blocks and collapsible quadrants. */
/* Mininum and maximum height of quadrants */
final int MIN_HEIGHT = 1;
final int MAX_HEIGHT = 16;
/* find slopes in landscape */
int xn = scanX(world, x, y, z, -1, MAX_HEIGHT);
int xp = scanX(world, x, y, z, 1, MAX_HEIGHT);
int zn = scanZ(world, x, y, z, -1, MAX_HEIGHT);
int zp = scanZ(world, x, y, z, 1, MAX_HEIGHT);
TEBase TE_XN = getTileEntity(world, xn, y, z);
TEBase TE_XP = getTileEntity(world, xp, y, z);
TEBase TE_ZN = getTileEntity(world, x, y, zn);
TEBase TE_ZP = getTileEntity(world, x, y, zp);
int height_XZNN = MIN_HEIGHT, height_XZPN = MIN_HEIGHT, height_XZPP = MIN_HEIGHT, height_XZNP = MIN_HEIGHT;
int hxn1, hxn2;
if(TE_XN != null) {
hxn1 = Collapsible.getQuadHeight(TE_XN, Collapsible.QUAD_XZPN);
hxn2 = Collapsible.getQuadHeight(TE_XN, Collapsible.QUAD_XZPP);
} else {
hxn1 = hxn2 = getBlockHeight(world, xn, y, z);
}
int hxp1, hxp2;
if(TE_XP != null) {
hxp1 = Collapsible.getQuadHeight(TE_XP, Collapsible.QUAD_XZNN);
hxp2 = Collapsible.getQuadHeight(TE_XP, Collapsible.QUAD_XZNP);
} else {
hxp1 = hxp2 = getBlockHeight(world, xp, y, z);
}
int hzn1, hzn2;
if(TE_ZN != null) {
hzn1 = Collapsible.getQuadHeight(TE_ZN, Collapsible.QUAD_XZNP);
hzn2 = Collapsible.getQuadHeight(TE_ZN, Collapsible.QUAD_XZPP);
} else {
hzn1 = hzn2 = getBlockHeight(world, x, y, zn);
}
int hzp1, hzp2;
if(TE_ZP != null) {
hzp1 = Collapsible.getQuadHeight(TE_ZP, Collapsible.QUAD_XZNN);
hzp2 = Collapsible.getQuadHeight(TE_ZP, Collapsible.QUAD_XZPN);
} else {
hzp1 = hzp2 = getBlockHeight(world, x, y, zp);
}
/* lerp between heights, create smooth slope */
int xdist = x - xn;
double dx1 = (double)(hxp1 - hxn1) / (xp - xn - 1);
double dx2 = (double)(hxp2 - hxn2) / (xp - xn - 1);
height_XZNN = Math.max(height_XZNN, (int)(hxn1 + dx1 * (xdist - 1)));
height_XZNP = Math.max(height_XZNP, (int)(hxn2 + dx2 * (xdist - 1)));
height_XZPN = Math.max(height_XZPN, (int)(hxn1 + dx1 * xdist));
height_XZPP = Math.max(height_XZPP, (int)(hxn2 + dx2 * xdist));
int zdist = z - zn;
double dz1 = (double)(hzp1 - hzn1) / (zp - zn - 1);
double dz2 = (double)(hzp2 - hzn2) / (zp - zn - 1);
height_XZNN = Math.max(height_XZNN, (int)(hzn1 + dz1 * (zdist - 1)));
height_XZNP = Math.max(height_XZNP, (int)(hzn1 + dz1 * zdist));
height_XZPN = Math.max(height_XZPN, (int)(hzn2 + dz2 * (zdist - 1)));
height_XZPP = Math.max(height_XZPP, (int)(hzn2 + dz2 * zdist));
Collapsible.setQuadHeight(TE, Collapsible.QUAD_XZNN, height_XZNN);
Collapsible.setQuadHeight(TE, Collapsible.QUAD_XZNP, height_XZNP);
Collapsible.setQuadHeight(TE, Collapsible.QUAD_XZPP, height_XZPP);
Collapsible.setQuadHeight(TE, Collapsible.QUAD_XZPN, height_XZPN);
for (int quad = 0; quad < 4; ++quad) {
smoothAdjacentCollapsibles(TE, quad);
}
}
}
super.onBlockPlacedBy(world, x, y, z, entityLiving, itemStack);
}
@Override
/**
* Adds all intersecting collision boxes to a list. (Be sure to only add boxes to the list if they intersect the
* mask.) Parameters: World, X, Y, Z, mask, list, colliding entity
*/
public void addCollisionBoxesToList(World world, int x, int y, int z, AxisAlignedBB axisAlignedBB, List list, Entity entity)
{
TEBase TE = getTileEntity(world, x, y, z);
if (TE != null) {
AxisAlignedBB colBox = null;
for (int quad = 0; quad < 4; ++quad)
{
float[] bounds = CollapsibleUtil.genBounds(TE, quad);
colBox = AxisAlignedBB.getBoundingBox(x + bounds[0], y + bounds[1], z + bounds[2], x + bounds[3], y + bounds[4], z + bounds[5]);
if (axisAlignedBB.intersectsWith(colBox)) {
list.add(colBox);
}
}
}
}
@Override
/**
* Ray traces through the blocks collision from start vector to end vector returning a ray trace hit. Args: world,
* x, y, z, startVec, endVec
*/
public MovingObjectPosition collisionRayTrace(World world, int x, int y, int z, Vec3 startVec, Vec3 endVec)
{
TEBase TE = getTileEntity(world, x, y, z);
MovingObjectPosition finalTrace = null;
if (TE != null) {
double currDist = 0.0D;
double maxDist = 0.0D;
// Determine if ray trace is a hit on block
for (int quad = 0; quad < 4; ++quad)
{
float[] bounds = CollapsibleUtil.genBounds(TE, quad);
setBlockBounds(bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]);
MovingObjectPosition traceResult = super.collisionRayTrace(world, x, y, z, startVec, endVec);
if (traceResult != null)
{
currDist = traceResult.hitVec.squareDistanceTo(endVec);
if (currDist > maxDist) {
finalTrace = traceResult;
maxDist = currDist;
}
}
}
/* Determine true face hit since it's built of quadrants. */
if (finalTrace != null) {
setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
finalTrace = super.collisionRayTrace(world, x, y, z, startVec, endVec);
}
}
return finalTrace;
}
@Override
/**
* The type of render function that is called for this block
*/
public int getRenderType()
{
return BlockRegistry.carpentersCollapsibleBlockRenderID;
}
}
| Add proper side render checks for collapsible block.
| src/main/java/com/carpentersblocks/block/BlockCarpentersCollapsibleBlock.java | Add proper side render checks for collapsible block. | <ide><path>rc/main/java/com/carpentersblocks/block/BlockCarpentersCollapsibleBlock.java
<ide>
<ide> public class BlockCarpentersCollapsibleBlock extends BlockCoverable {
<ide>
<add> private static Collapsible data = new Collapsible();
<add>
<ide> public BlockCarpentersCollapsibleBlock(Material material)
<ide> {
<ide> super(material);
<ide>
<ide> @Override
<ide> /**
<add> * Returns whether sides share faces based on sloping property and face shape.
<add> */
<add> protected boolean shareFaces(TEBase TE_adj, TEBase TE_src, ForgeDirection side_adj, ForgeDirection side_src)
<add> {
<add> if (TE_adj.getBlockType() == this) {
<add> switch (side_adj) {
<add> case NORTH:
<add> return data.getQuadHeight(TE_adj, data.QUAD_XZNN) == data.getQuadHeight(TE_src, data.QUAD_XZNP) &&
<add> data.getQuadHeight(TE_adj, data.QUAD_XZPN) == data.getQuadHeight(TE_src, data.QUAD_XZPP);
<add> case SOUTH:
<add> return data.getQuadHeight(TE_adj, data.QUAD_XZNP) == data.getQuadHeight(TE_src, data.QUAD_XZNN) &&
<add> data.getQuadHeight(TE_adj, data.QUAD_XZPP) == data.getQuadHeight(TE_src, data.QUAD_XZPN);
<add> case WEST:
<add> return data.getQuadHeight(TE_adj, data.QUAD_XZNP) == data.getQuadHeight(TE_src, data.QUAD_XZPP) &&
<add> data.getQuadHeight(TE_adj, data.QUAD_XZNN) == data.getQuadHeight(TE_src, data.QUAD_XZPN);
<add> case EAST:
<add> return data.getQuadHeight(TE_adj, data.QUAD_XZPP) == data.getQuadHeight(TE_src, data.QUAD_XZNP) &&
<add> data.getQuadHeight(TE_adj, data.QUAD_XZPN) == data.getQuadHeight(TE_src, data.QUAD_XZNN);
<add> default: {}
<add> }
<add> }
<add>
<add> return super.shareFaces(TE_adj, TE_src, side_adj, side_src);
<add> }
<add>
<add> @Override
<add> /**
<ide> * The type of render function that is called for this block
<ide> */
<ide> public int getRenderType() |
|
Java | apache-2.0 | a2f52d7810607c9505704533eed2665368e1cfa8 | 0 | alter-ego/androidbound,alter-ego/androidbound | package solutions.alterego.androidbound.android.adapters;
import android.support.v4.util.Pair;
import android.support.v7.util.DiffUtil;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.SparseArray;
import android.view.ViewGroup;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.disposables.Disposables;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import solutions.alterego.androidbound.interfaces.IViewBinder;
import static android.support.v7.util.DiffUtil.calculateDiff;
@Accessors(prefix = "m")
public class BindableRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final IViewBinder mViewBinder;
@Getter
private int mItemTemplate;
@Getter
private Map<Class<?>, Integer> mTemplatesForObjects = new HashMap<>();
@Getter
private List mItemsSource = new ArrayList<>();
private SparseArray<Class<?>> mObjectIndex;
@Getter
@Setter
private RecyclerView.LayoutManager mLayoutManager;
private Disposable mSetValuesDisposable = Disposables.disposed();
private Disposable mRemoveItemsDisposable = Disposables.disposed();
private Queue<List<?>> pendingUpdates =
new ArrayDeque<>();
private Disposable mAddValueDisposable = Disposables.disposed();
public BindableRecyclerViewAdapter(IViewBinder vb, int itemTemplate) {
mViewBinder = vb;
mItemTemplate = itemTemplate;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Class<?> clazz = mObjectIndex.get(viewType);
int layoutRes = mItemTemplate;
if (clazz != null && mTemplatesForObjects.containsKey(clazz)) {
layoutRes = mTemplatesForObjects.get(clazz);
mViewBinder.getLogger().verbose(
"BindableRecyclerViewAdapter creating VH for viewType = " + viewType + " i.e. class = " + clazz
+ " using layoutRes = "
+ layoutRes);
} else if (layoutRes != 0) {
mViewBinder.getLogger().verbose("BindableRecyclerViewAdapter creating VH using layoutRes = " + layoutRes);
} else {
mViewBinder.getLogger().error("BindableRecyclerViewAdapter cannot find templates for class = " + clazz
+ ": did you call setTemplatesForObjects or set itemTemplate in XML?");
}
return new BindableRecyclerViewItemViewHolder(
mViewBinder.inflate(parent.getContext(), null, layoutRes, parent, false), mViewBinder, parent);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof BindableRecyclerViewItemViewHolder) {
if (getLayoutManager() != null) {
((BindableRecyclerViewItemViewHolder) holder)
.onBindViewHolder(getItemsSource().get(position), getLayoutManager());
} else {
((BindableRecyclerViewItemViewHolder) holder).onBindViewHolder(getItemsSource().get(position));
}
}
}
@Override
public int getItemCount() {
return getItemsSource() != null ? getItemsSource().size() : 0;
}
@Override
public int getItemViewType(int position) {
Object obj = getItemsSource().get(position);
int viewType = mObjectIndex.indexOfValue(obj.getClass());
mViewBinder.getLogger().verbose(
"BindableRecyclerViewAdapter getItemViewType viewType = " + viewType + " i.e. class = " + obj.getClass()
.toString() + " for position = " + position);
return viewType;
}
public void setItemsSource(final List<?> value) {
final List<?> oldItems = new ArrayList<>(mItemsSource);
mSetValuesDisposable.dispose();
mSetValuesDisposable = Observable.just(value)
.subscribeOn(Schedulers.computation())
.map(new Function<List<?>, Pair<List<?>, DiffUtil.DiffResult>>() {
@Override
public Pair<List<?>, DiffUtil.DiffResult> apply(List<?> newList) throws Exception {
return new Pair<List<?>, DiffUtil.DiffResult>(newList, calculateDiff(new ItemSourceDiffCallback(oldItems, value)));
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Pair<List<?>, DiffUtil.DiffResult>>() {
@Override
public void accept(Pair<List<?>, DiffUtil.DiffResult> resultPair) throws Exception {
applyDiffResult(resultPair);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
throwable.printStackTrace();
}
});
}
private void applyDiffResult(Pair<List<?>, DiffUtil.DiffResult> resultPair) {
boolean firstStart = true;
if (!pendingUpdates.isEmpty()) {
pendingUpdates.remove();
}
if (mItemsSource.size() > 0) {
mItemsSource.clear();
firstStart = false;
}
if (resultPair.first != null) {
mItemsSource.addAll(new ArrayList<>(resultPair.first));
}
//if we call DiffUtil.DiffResult.dispatchUpdatesTo() on an empty adapter, it will crash - we have to call notifyDataSetChanged()!
if (firstStart) {
notifyDataSetChanged();
} else {
resultPair.second.dispatchUpdatesTo(this);
}
if (pendingUpdates.size() > 0) {
setItemsSource(pendingUpdates.peek());
}
}
public void addItemsSource(List<?> values) {
if (values == null) {
if (mItemsSource != null) {
int size = mItemsSource.size();
mItemsSource = null;
postNotifyItemRangeRemoved(0, size);
}
return;
}
if (mItemsSource == null) {
mItemsSource = new ArrayList<>();
}
mAddValueDisposable.dispose();
mAddValueDisposable = Observable.fromIterable(values)
.filter(new Predicate<Object>() {
@Override
public boolean test(Object value) throws Exception {
return value != null;
}
})
.subscribe(new Consumer<Object>() {
@Override
public void accept(Object value) throws Exception {
boolean contains = mItemsSource.contains(value);
if (contains) {
int index = mItemsSource.indexOf(value);
mItemsSource.set(index, value);
notifyItemChanged(index);
} else if (mItemsSource.add(value)) {
notifyItemInserted(mItemsSource.size() - 1);
}
}
});
}
/* to prevent Cannot call this method in a scroll callback. Scroll callbacks might be run during a measure
& layout pass where you cannot change the RecyclerView data. Any method call that might change the structure
of the RecyclerView or the adapter contents should be postponed to the next frame.*/
private void postNotifyItemRangeRemoved(final int start, final int itemCount) {
AndroidSchedulers.mainThread().createWorker().schedule(new Runnable() {
@Override
public void run() {
notifyItemRangeRemoved(start, itemCount);
}
});
}
public void setTemplatesForObjects(Map<Class<?>, Integer> templatesForObjects) {
if (mTemplatesForObjects == null) {
return;
}
mTemplatesForObjects = templatesForObjects;
mObjectIndex = new SparseArray<>();
Class<?>[] classes = mTemplatesForObjects.keySet().toArray(new Class[mTemplatesForObjects.keySet().size()]);
for (int index = 0; index < classes.length; index++) {
mObjectIndex.put(index, classes[index]);
}
if (mItemsSource != null) {
notifyDataSetChanged();
}
}
public void removeItems(final List<?> value) {
if (mItemsSource == null) {
return;
}
List<?> tmp = new ArrayList<>(mItemsSource);
mRemoveItemsDisposable.dispose();
mRemoveItemsDisposable = Observable.just(tmp)
.subscribeOn(Schedulers.computation())
.map(new Function<List<?>, List<?>>() {
@Override
public List<?> apply(List<?> list) throws Exception {
list.removeAll(value);
return list;
}
})
.map(new Function<List<?>, Pair<List, DiffUtil.DiffResult>>() {
@Override
public Pair<List, DiffUtil.DiffResult> apply(List<?> list) throws Exception {
return new Pair<List, DiffUtil.DiffResult>(list,
calculateDiff(new ItemSourceDiffCallback(mItemsSource, list), true));
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Pair<List, DiffUtil.DiffResult>>() {
@Override
public void accept(Pair<List, DiffUtil.DiffResult> pair) throws Exception {
if (pair.first != null && mItemsSource != null) {
mItemsSource.clear();
mItemsSource.addAll(pair.first);
}
pair.second.dispatchUpdatesTo(BindableRecyclerViewAdapter.this);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
notifyDataSetChanged();
}
});
}
@Override
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
mRemoveItemsDisposable.dispose();
mSetValuesDisposable.dispose();
mAddValueDisposable.dispose();
}
}
| AndroidBound/src/main/java/solutions/alterego/androidbound/android/adapters/BindableRecyclerViewAdapter.java | package solutions.alterego.androidbound.android.adapters;
import android.support.v4.util.Pair;
import android.support.v7.util.DiffUtil;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.SparseArray;
import android.view.ViewGroup;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.disposables.Disposables;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import solutions.alterego.androidbound.interfaces.IViewBinder;
import static android.support.v7.util.DiffUtil.calculateDiff;
@Accessors(prefix = "m")
public class BindableRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final IViewBinder mViewBinder;
@Getter
private int mItemTemplate;
@Getter
private Map<Class<?>, Integer> mTemplatesForObjects = new HashMap<>();
@Getter
private List mItemsSource = new ArrayList<>();
private SparseArray<Class<?>> mObjectIndex;
@Getter
@Setter
private RecyclerView.LayoutManager mLayoutManager;
private Disposable mSetValuesDisposable = Disposables.disposed();
private Disposable mRemoveItemsDisposable = Disposables.disposed();
private Queue<List<?>> pendingUpdates =
new ArrayDeque<>();
private Disposable mAddValueDisposable = Disposables.disposed();
public BindableRecyclerViewAdapter(IViewBinder vb, int itemTemplate) {
mViewBinder = vb;
mItemTemplate = itemTemplate;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Class<?> clazz = mObjectIndex.get(viewType);
int layoutRes = mItemTemplate;
if (clazz != null && mTemplatesForObjects.containsKey(clazz)) {
layoutRes = mTemplatesForObjects.get(clazz);
mViewBinder.getLogger().verbose(
"BindableRecyclerViewAdapter creating VH for viewType = " + viewType + " i.e. class = " + clazz
+ " using layoutRes = "
+ layoutRes);
} else if (layoutRes != 0) {
mViewBinder.getLogger().verbose("BindableRecyclerViewAdapter creating VH using layoutRes = " + layoutRes);
} else {
mViewBinder.getLogger().error("BindableRecyclerViewAdapter cannot find templates for class = " + clazz
+ ": did you call setTemplatesForObjects or set itemTemplate in XML?");
}
return new BindableRecyclerViewItemViewHolder(
mViewBinder.inflate(parent.getContext(), null, layoutRes, parent, false), mViewBinder, parent);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof BindableRecyclerViewItemViewHolder) {
if (getLayoutManager() instanceof StaggeredGridLayoutManager) {
((BindableRecyclerViewItemViewHolder) holder)
.onBindViewHolder(getItemsSource().get(position), getLayoutManager());
} else {
((BindableRecyclerViewItemViewHolder) holder).onBindViewHolder(getItemsSource().get(position));
}
}
}
@Override
public int getItemCount() {
return getItemsSource() != null ? getItemsSource().size() : 0;
}
@Override
public int getItemViewType(int position) {
Object obj = getItemsSource().get(position);
int viewType = mObjectIndex.indexOfValue(obj.getClass());
mViewBinder.getLogger().verbose(
"BindableRecyclerViewAdapter getItemViewType viewType = " + viewType + " i.e. class = " + obj.getClass()
.toString() + " for position = " + position);
return viewType;
}
public void setItemsSource(final List<?> value) {
final List<?> oldItems = new ArrayList<>(mItemsSource);
mSetValuesDisposable.dispose();
mSetValuesDisposable = Observable.just(value)
.subscribeOn(Schedulers.computation())
.map(new Function<List<?>, Pair<List<?>, DiffUtil.DiffResult>>() {
@Override
public Pair<List<?>, DiffUtil.DiffResult> apply(List<?> newList) throws Exception {
return new Pair<List<?>, DiffUtil.DiffResult>(newList, calculateDiff(new ItemSourceDiffCallback(oldItems, value)));
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Pair<List<?>, DiffUtil.DiffResult>>() {
@Override
public void accept(Pair<List<?>, DiffUtil.DiffResult> resultPair) throws Exception {
applyDiffResult(resultPair);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
throwable.printStackTrace();
}
});
}
private void applyDiffResult(Pair<List<?>, DiffUtil.DiffResult> resultPair) {
boolean firstStart = true;
if (!pendingUpdates.isEmpty()) {
pendingUpdates.remove();
}
if (mItemsSource.size() > 0) {
mItemsSource.clear();
firstStart = false;
}
if (resultPair.first != null) {
mItemsSource.addAll(new ArrayList<>(resultPair.first));
}
//if we call DiffUtil.DiffResult.dispatchUpdatesTo() on an empty adapter, it will crash - we have to call notifyDataSetChanged()!
if (firstStart) {
notifyDataSetChanged();
} else {
resultPair.second.dispatchUpdatesTo(this);
}
if (pendingUpdates.size() > 0) {
setItemsSource(pendingUpdates.peek());
}
}
public void addItemsSource(List<?> values) {
if (values == null) {
if (mItemsSource != null) {
int size = mItemsSource.size();
mItemsSource = null;
postNotifyItemRangeRemoved(0, size);
}
return;
}
if (mItemsSource == null) {
mItemsSource = new ArrayList<>();
}
mAddValueDisposable.dispose();
mAddValueDisposable = Observable.fromIterable(values)
.filter(new Predicate<Object>() {
@Override
public boolean test(Object value) throws Exception {
return value != null;
}
})
.subscribe(new Consumer<Object>() {
@Override
public void accept(Object value) throws Exception {
boolean contains = mItemsSource.contains(value);
if (contains) {
int index = mItemsSource.indexOf(value);
mItemsSource.set(index, value);
notifyItemChanged(index);
} else if (mItemsSource.add(value)) {
notifyItemInserted(mItemsSource.size() - 1);
}
}
});
}
/* to prevent Cannot call this method in a scroll callback. Scroll callbacks might be run during a measure
& layout pass where you cannot change the RecyclerView data. Any method call that might change the structure
of the RecyclerView or the adapter contents should be postponed to the next frame.*/
private void postNotifyItemRangeRemoved(final int start, final int itemCount) {
AndroidSchedulers.mainThread().createWorker().schedule(new Runnable() {
@Override
public void run() {
notifyItemRangeRemoved(start, itemCount);
}
});
}
public void setTemplatesForObjects(Map<Class<?>, Integer> templatesForObjects) {
if (mTemplatesForObjects == null) {
return;
}
mTemplatesForObjects = templatesForObjects;
mObjectIndex = new SparseArray<>();
Class<?>[] classes = mTemplatesForObjects.keySet().toArray(new Class[mTemplatesForObjects.keySet().size()]);
for (int index = 0; index < classes.length; index++) {
mObjectIndex.put(index, classes[index]);
}
if (mItemsSource != null) {
notifyDataSetChanged();
}
}
public void removeItems(final List<?> value) {
if (mItemsSource == null) {
return;
}
List<?> tmp = new ArrayList<>(mItemsSource);
mRemoveItemsDisposable.dispose();
mRemoveItemsDisposable = Observable.just(tmp)
.subscribeOn(Schedulers.computation())
.map(new Function<List<?>, List<?>>() {
@Override
public List<?> apply(List<?> list) throws Exception {
list.removeAll(value);
return list;
}
})
.map(new Function<List<?>, Pair<List, DiffUtil.DiffResult>>() {
@Override
public Pair<List, DiffUtil.DiffResult> apply(List<?> list) throws Exception {
return new Pair<List, DiffUtil.DiffResult>(list,
calculateDiff(new ItemSourceDiffCallback(mItemsSource, list), true));
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Pair<List, DiffUtil.DiffResult>>() {
@Override
public void accept(Pair<List, DiffUtil.DiffResult> pair) throws Exception {
if (pair.first != null && mItemsSource != null) {
mItemsSource.clear();
mItemsSource.addAll(pair.first);
}
pair.second.dispatchUpdatesTo(BindableRecyclerViewAdapter.this);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
notifyDataSetChanged();
}
});
}
@Override
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
mRemoveItemsDisposable.dispose();
mSetValuesDisposable.dispose();
mAddValueDisposable.dispose();
}
}
| now also using LLM for getting parent LP in BindableRecyclerViewAdapter
| AndroidBound/src/main/java/solutions/alterego/androidbound/android/adapters/BindableRecyclerViewAdapter.java | now also using LLM for getting parent LP in BindableRecyclerViewAdapter | <ide><path>ndroidBound/src/main/java/solutions/alterego/androidbound/android/adapters/BindableRecyclerViewAdapter.java
<ide> @Override
<ide> public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
<ide> if (holder instanceof BindableRecyclerViewItemViewHolder) {
<del> if (getLayoutManager() instanceof StaggeredGridLayoutManager) {
<add> if (getLayoutManager() != null) {
<ide> ((BindableRecyclerViewItemViewHolder) holder)
<ide> .onBindViewHolder(getItemsSource().get(position), getLayoutManager());
<ide> } else { |
|
Java | apache-2.0 | 5e69fcdc5fc16b8b25f54ad86a9ed8f458d8abc2 | 0 | SingingTree/hapi-fhir,SingingTree/hapi-fhir,jamesagnew/hapi-fhir,aemay2/hapi-fhir,jamesagnew/hapi-fhir,aemay2/hapi-fhir,aemay2/hapi-fhir,SingingTree/hapi-fhir,SingingTree/hapi-fhir,aemay2/hapi-fhir,SingingTree/hapi-fhir,aemay2/hapi-fhir,aemay2/hapi-fhir,jamesagnew/hapi-fhir,SingingTree/hapi-fhir,jamesagnew/hapi-fhir,jamesagnew/hapi-fhir,jamesagnew/hapi-fhir | package ca.uhn.hapi.fhir.docs;
/*-
* #%L
* HAPI FHIR - Docs
* %%
* Copyright (C) 2014 - 2019 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.parser.DataFormatException;
import ca.uhn.fhir.parser.IParser;
import org.hl7.fhir.r4.model.Patient;
import java.io.IOException;
public class Parser {
public static void main(String[] args) throws DataFormatException, IOException {
{
//START SNIPPET: createParser
// Create a FHIR context
FhirContext ctx = FhirContext.forR4();
// Create a Patient resource to serialize
Patient patient = new Patient();
patient.addName().setFamily("Simpson").addGiven("James");
// Instantiate a new parser
IParser parser = ctx.newJsonParser();
// Serialize it
String serialized = parser.encodeResourceToString(patient);
System.out.println(serialized);
//END SNIPPET: createParser
}
{
//START SNIPPET: disableStripVersions
FhirContext ctx = FhirContext.forR4();
IParser parser = ctx.newJsonParser();
// Disable the automatic stripping of versions from references on the parser
parser.setStripVersionsFromReferences(false);
//END SNIPPET: disableStripVersions
//START SNIPPET: disableStripVersionsCtx
ctx.getParserOptions().setStripVersionsFromReferences(false);
//END SNIPPET: disableStripVersionsCtx
}
{
//START SNIPPET: disableStripVersionsField
FhirContext ctx = FhirContext.forR4();
IParser parser = ctx.newJsonParser();
// Preserve versions only on these two fields (for the given parser)
parser.setDontStripVersionsFromReferencesAtPaths("AuditEvent.entity.reference", "Patient.managingOrganization");
// You can also apply this setting to the context so that it will
// flow to all parsers
ctx.getParserOptions().setDontStripVersionsFromReferencesAtPaths("AuditEvent.entity.reference", "Patient.managingOrganization");
//END SNIPPET: disableStripVersionsField
}
}
}
| hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/Parser.java | package ca.uhn.hapi.fhir.docs;
/*-
* #%L
* HAPI FHIR - Docs
* %%
* Copyright (C) 2014 - 2019 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.parser.DataFormatException;
import ca.uhn.fhir.parser.IParser;
import org.hl7.fhir.r4.model.Patient;
import java.io.IOException;
public class Parser {
public static void main(String[] args) throws DataFormatException, IOException {
{
//START SNIPPET: createParser
// Create a FHIR context
FhirContext ctx = FhirContext.forR4();
// Create a Patient resource to serialize
Patient patient = new Patient();
patient.addName().setFamily("Simpson").addGiven("James");
// Instantiate a new parser
IParser parser = ctx.newJsonParser();
// Serialize it
String serialized = parser.encodeResourceToString(patient)
System.out.println(serialized);
//END SNIPPET: createParser
}
{
//START SNIPPET: disableStripVersions
FhirContext ctx = FhirContext.forR4();
IParser parser = ctx.newJsonParser();
// Disable the automatic stripping of versions from references on the parser
parser.setStripVersionsFromReferences(false);
//END SNIPPET: disableStripVersions
//START SNIPPET: disableStripVersionsCtx
ctx.getParserOptions().setStripVersionsFromReferences(false);
//END SNIPPET: disableStripVersionsCtx
}
{
//START SNIPPET: disableStripVersionsField
FhirContext ctx = FhirContext.forR4();
IParser parser = ctx.newJsonParser();
// Preserve versions only on these two fields (for the given parser)
parser.setDontStripVersionsFromReferencesAtPaths("AuditEvent.entity.reference", "Patient.managingOrganization");
// You can also apply this setting to the context so that it will
// flow to all parsers
ctx.getParserOptions().setDontStripVersionsFromReferencesAtPaths("AuditEvent.entity.reference", "Patient.managingOrganization");
//END SNIPPET: disableStripVersionsField
}
}
}
| Fix compile error
| hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/Parser.java | Fix compile error | <ide><path>api-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/Parser.java
<ide> IParser parser = ctx.newJsonParser();
<ide>
<ide> // Serialize it
<del> String serialized = parser.encodeResourceToString(patient)
<add> String serialized = parser.encodeResourceToString(patient);
<ide> System.out.println(serialized);
<ide> //END SNIPPET: createParser
<ide> } |
|
Java | mpl-2.0 | 19efe68b1ece039027b08139e032b4ce483c113b | 0 | JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core | // -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
//
// This file is part of the LibreOffice project.
//
// 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/.
// This is just a testbed for ideas and implementations. (Still, it might turn
// out to be somewhat useful as such while waiting for "real" apps.)
package org.libreoffice.experimental.desktop;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import com.sun.star.awt.Key;
import org.libreoffice.android.AppSupport;
import org.libreoffice.android.Bootstrap;
public class Desktop
extends Activity
{
private static final String TAG = "LODesktop";
/**
* This class contains the state that is initialized once and never changes
* (not specific to a document or a view).
*/
class BootstrapContext
{
}
BootstrapContext bootstrapContext;
private static final Integer ZERO = 0;
private static int normalize(Number value) {
return ZERO.compareTo(-value.intValue());
}
private void initBootstrapContext()
{
bootstrapContext = new BootstrapContext();
Bootstrap.setup(this);
// To enable the putenv below, which turns on all SAL_INFO
// logging, do: "adb shell setprop log.tag.LODesktopLogging
// VERBOSE".
if (Log.isLoggable("LODesktopLogging", Log.VERBOSE))
Bootstrap.putenv("SAL_LOG=+WARN+INFO");
}
// This sucks, we need to experiment and think, can an app process
// have several instances of this Activity active?
static BitmapView theView;
// This is called back from LO in the LO thread
static public void callbackDamaged()
{
synchronized (theView) {
if (!invalidatePosted)
theView.post(new Runnable() {
@Override public void run() {
synchronized (theView) {
theView.invalidate();
invalidatePosted = false;
}
}
});
invalidatePosted = true;
}
}
static boolean invalidatePosted;
@Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
try {
String input;
// input = getIntent().getStringExtra("input");
// if (input == null)
input = "/assets/test1.odt";
// input = "--writer";
// We need to fake up an argv, and the argv[0] even needs to
// point to some file name that we can pretend is the "program".
// setCommandArgs() will prefix argv[0] with the app's data
// directory.
String[] argv = { "lo-document-loader", input };
Bootstrap.setCommandArgs(argv);
// To enable the sleep below, do: "adb shell setprop
// log.tag.LODesktopSleepOnCreate VERBOSE". Yeah, has
// nothing to do with logging as such.
// This should be after at least one call to something in
// the Bootstrap class as it is the static initialiser
// that loads the lo-native-code library, and presumably
// in ndk-gdb you want to set a breapoint in some native
// code...
if (Log.isLoggable("LODesktopSleepOnCreate", Log.VERBOSE)) {
Log.i(TAG, "Sleeping, start ndk-gdb NOW if you intend to debug");
Thread.sleep(20000);
}
if (bootstrapContext == null)
initBootstrapContext();
Log.i(TAG, "onCreate - set content view");
theView = new BitmapView();
setContentView(theView);
AppSupport.registerForDamageCallback(getClass());
// Start a Java thread to run soffice_main(). We don't
// want to start the thread from native code becauce
// native threads apparently have no Java class loaders in
// Android, or someghin. So for instance FindClass fails.
// See https://groups.google.com/group/android-ndk/msg/a0793f009e6e71f7?dmode=source
// .
new Thread(new Runnable() {
@Override public void run() {
AppSupport.runMain();
}
}).start();
}
catch (Exception e) {
e.printStackTrace(System.err);
finish();
}
}
class BitmapView
extends View
{
Bitmap mBitmap;
boolean renderedOnce;
GestureDetector gestureDetector;
ScaleGestureDetector scaleDetector;
boolean scrollInProgress, scalingInProgress;
float translateX = 0, translateY = 0;
float accumulatedScale = 1;
float pivotX = 0, pivotY = 0;
public BitmapView()
{
super(Desktop.this);
setFocusableInTouchMode(true);
gestureDetector =
new GestureDetector(Desktop.this,
new GestureDetector.SimpleOnGestureListener() {
@Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
{
Log.i(TAG, "onFling: (" + velocityX + ", " + velocityY + ")");
return false;
}
@Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
{
Log.i(TAG, "onScroll: (" + distanceX + ", " + distanceY + ")");
translateX += -distanceX;
translateY += -distanceY;
scrollInProgress = true;
invalidate();
return true;
}
});
scaleDetector =
new ScaleGestureDetector(Desktop.this,
new ScaleGestureDetector.SimpleOnScaleGestureListener() {
@Override public boolean onScaleBegin(ScaleGestureDetector detector)
{
scalingInProgress = true;
return true;
}
@Override public boolean onScale(ScaleGestureDetector detector)
{
accumulatedScale *= detector.getScaleFactor();
pivotX = detector.getFocusX();
pivotY = detector.getFocusY();
invalidate();
return true;
}
@Override public void onScaleEnd(ScaleGestureDetector detector)
{
accumulatedScale *= detector.getScaleFactor();
AppSupport.zoom(accumulatedScale, (int) pivotX, (int) pivotY);
accumulatedScale = 1;
pivotX = pivotY = 0;
scalingInProgress = false;
invalidate();
}
});
}
@Override protected void onDraw(Canvas canvas)
{
if (mBitmap == null) {
Log.i(TAG, "calling Bitmap.createBitmap(" + getWidth() + ", " + getHeight() + ", Bitmap.Config.ARGB_8888)");
mBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
AppSupport.setViewSize(getWidth(), getHeight());
}
AppSupport.renderVCL(mBitmap);
if (scrollInProgress) {
canvas.save();
canvas.translate(translateX, translateY);
canvas.drawBitmap(mBitmap, 0, 0, null);
canvas.restore();
} else if (scalingInProgress) {
canvas.save();
canvas.scale(accumulatedScale, accumulatedScale, pivotX, pivotY);
canvas.drawBitmap(mBitmap, 0, 0, null);
canvas.restore();
} else {
canvas.drawBitmap(mBitmap, 0, 0, null);
}
renderedOnce = true;
}
@Override public boolean onKeyDown(int keyCode, KeyEvent event)
{
switch (keyCode) {
case KeyEvent.KEYCODE_0:
case KeyEvent.KEYCODE_1:
case KeyEvent.KEYCODE_2:
case KeyEvent.KEYCODE_3:
case KeyEvent.KEYCODE_4:
case KeyEvent.KEYCODE_5:
case KeyEvent.KEYCODE_6:
case KeyEvent.KEYCODE_7:
case KeyEvent.KEYCODE_8:
case KeyEvent.KEYCODE_9:
AppSupport.key((char) ('0' + keyCode - KeyEvent.KEYCODE_0));
return true;
case KeyEvent.KEYCODE_DEL:
AppSupport.key((char) Key.BACKSPACE);
return true;
case KeyEvent.KEYCODE_ENTER:
AppSupport.key((char) Key.RETURN);
return true;
case KeyEvent.KEYCODE_TAB:
AppSupport.key((char) Key.TAB);
return true;
default:
return false;
}
}
@Override public boolean onTouchEvent(MotionEvent event)
{
boolean scrollJustEnded = false;
if (event.getPointerCount() == 1 &&
gestureDetector.onTouchEvent(event)) {
return true;
}
// There is no callback in SimpleOnGestureListener for end
// of scroll. Is this a good way to detect it? Assume that
// as long as the scrolling gesture is in progress, the
// Gesturedetector.onTouchEvent() will keep returning
// true, so if scrollInProgress is true and we get here,
// the scroll must have ended.
if (scrollInProgress) {
AppSupport.scroll(normalize(translateX), normalize(translateY));
translateX = translateY = 0;
scrollInProgress = false;
scrollJustEnded = true;
invalidate();
} else if (event.getPointerCount() == 2 &&
scaleDetector.onTouchEvent(event) &&
scalingInProgress) {
// If a scaling gesture is in progress no other touch
// processing should be done.
return true;
}
// Just temporary hack. We should not show the keyboard
// unconditionally on a ACTION_UP event here. The LO level
// should callback to us requesting showing the keyboard
// if the user taps in a text area. Unfortunately it seems
// less than obvious where the correct place to insert
// such a request is.
// Also, if the device has a hardware keyboard, we
// probably should not show the soft one unconditionally?
// But what if the user wants to input in another script
// than what the hardware keyboard covers?
if (!scrollJustEnded &&
event.getPointerCount() == 1 &&
event.getActionMasked() == MotionEvent.ACTION_UP) {
// show the keyboard so we can enter text
InputMethodManager imm = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(this, InputMethodManager.SHOW_FORCED);
}
if (event.getPointerCount() == 1) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_MOVE:
AppSupport.touch(event.getActionMasked(), (int) event.getX(), (int) event.getY());
break;
}
}
return true;
}
@Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
BaseInputConnection fic = new LOInputConnection(this, true);
outAttrs.actionLabel = null;
outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
outAttrs.imeOptions = EditorInfo.IME_ACTION_NONE;
return fic;
}
@Override public boolean onCheckIsTextEditor() {
return renderedOnce;
}
}
class LOInputConnection
extends BaseInputConnection
{
public LOInputConnection(View targetView, boolean fullEditor) {
super(targetView, fullEditor);
}
@Override public boolean commitText(CharSequence text, int newCursorPosition) {
for (int i = 0; i < text.length(); i++) {
AppSupport.key(text.charAt(i));
}
return true;
}
}
}
// vim:set shiftwidth=4 softtabstop=4 expandtab:
| android/experimental/desktop/src/org/libreoffice/experimental/desktop/Desktop.java | // -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
//
// This file is part of the LibreOffice project.
//
// 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/.
// This is just a testbed for ideas and implementations. (Still, it might turn
// out to be somewhat useful as such while waiting for "real" apps.)
package org.libreoffice.experimental.desktop;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import com.sun.star.awt.Key;
import org.libreoffice.android.AppSupport;
import org.libreoffice.android.Bootstrap;
public class Desktop
extends Activity
{
private static final String TAG = "LODesktop";
/**
* This class contains the state that is initialized once and never changes
* (not specific to a document or a view).
*/
class BootstrapContext
{
}
BootstrapContext bootstrapContext;
private void initBootstrapContext()
{
bootstrapContext = new BootstrapContext();
Bootstrap.setup(this);
// To enable the putenv below, which turns on all SAL_INFO
// logging, do: "adb shell setprop log.tag.LODesktopLogging
// VERBOSE".
if (Log.isLoggable("LODesktopLogging", Log.VERBOSE))
Bootstrap.putenv("SAL_LOG=+WARN+INFO");
}
// This sucks, we need to experiment and think, can an app process
// have several instances of this Activity active?
static BitmapView theView;
// This is called back from LO in the LO thread
static public void callbackDamaged()
{
synchronized (theView) {
if (!invalidatePosted)
theView.post(new Runnable() {
@Override public void run() {
synchronized (theView) {
theView.invalidate();
invalidatePosted = false;
}
}
});
invalidatePosted = true;
}
}
static boolean invalidatePosted;
@Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
try {
String input;
// input = getIntent().getStringExtra("input");
// if (input == null)
input = "/assets/test1.odt";
// input = "--writer";
// We need to fake up an argv, and the argv[0] even needs to
// point to some file name that we can pretend is the "program".
// setCommandArgs() will prefix argv[0] with the app's data
// directory.
String[] argv = { "lo-document-loader", input };
Bootstrap.setCommandArgs(argv);
// To enable the sleep below, do: "adb shell setprop
// log.tag.LODesktopSleepOnCreate VERBOSE". Yeah, has
// nothing to do with logging as such.
// This should be after at least one call to something in
// the Bootstrap class as it is the static initialiser
// that loads the lo-native-code library, and presumably
// in ndk-gdb you want to set a breapoint in some native
// code...
if (Log.isLoggable("LODesktopSleepOnCreate", Log.VERBOSE)) {
Log.i(TAG, "Sleeping, start ndk-gdb NOW if you intend to debug");
Thread.sleep(20000);
}
if (bootstrapContext == null)
initBootstrapContext();
Log.i(TAG, "onCreate - set content view");
theView = new BitmapView();
setContentView(theView);
AppSupport.registerForDamageCallback(getClass());
// Start a Java thread to run soffice_main(). We don't
// want to start the thread from native code becauce
// native threads apparently have no Java class loaders in
// Android, or someghin. So for instance FindClass fails.
// See https://groups.google.com/group/android-ndk/msg/a0793f009e6e71f7?dmode=source
// .
new Thread(new Runnable() {
@Override public void run() {
AppSupport.runMain();
}
}).start();
}
catch (Exception e) {
e.printStackTrace(System.err);
finish();
}
}
class BitmapView
extends View
{
Bitmap mBitmap;
boolean renderedOnce;
GestureDetector gestureDetector;
ScaleGestureDetector scaleDetector;
boolean scrollInProgress, scalingInProgress;
float translateX = 0, translateY = 0;
float accumulatedScale = 1;
float pivotX = 0, pivotY = 0;
public BitmapView()
{
super(Desktop.this);
setFocusableInTouchMode(true);
gestureDetector =
new GestureDetector(Desktop.this,
new GestureDetector.SimpleOnGestureListener() {
@Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
{
Log.i(TAG, "onFling: (" + velocityX + ", " + velocityY + ")");
return false;
}
@Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
{
Log.i(TAG, "onScroll: (" + distanceX + ", " + distanceY + ")");
translateX += -distanceX;
translateY += -distanceY;
scrollInProgress = true;
invalidate();
return true;
}
});
scaleDetector =
new ScaleGestureDetector(Desktop.this,
new ScaleGestureDetector.SimpleOnScaleGestureListener() {
@Override public boolean onScaleBegin(ScaleGestureDetector detector)
{
scalingInProgress = true;
return true;
}
@Override public boolean onScale(ScaleGestureDetector detector)
{
accumulatedScale *= detector.getScaleFactor();
pivotX = detector.getFocusX();
pivotY = detector.getFocusY();
invalidate();
return true;
}
@Override public void onScaleEnd(ScaleGestureDetector detector)
{
accumulatedScale *= detector.getScaleFactor();
AppSupport.zoom(accumulatedScale, (int) pivotX, (int) pivotY);
accumulatedScale = 1;
pivotX = pivotY = 0;
scalingInProgress = false;
invalidate();
}
});
}
@Override protected void onDraw(Canvas canvas)
{
if (mBitmap == null) {
Log.i(TAG, "calling Bitmap.createBitmap(" + getWidth() + ", " + getHeight() + ", Bitmap.Config.ARGB_8888)");
mBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
AppSupport.setViewSize(getWidth(), getHeight());
}
AppSupport.renderVCL(mBitmap);
if (scrollInProgress) {
canvas.save();
canvas.translate(translateX, translateY);
canvas.drawBitmap(mBitmap, 0, 0, null);
canvas.restore();
} else if (scalingInProgress) {
canvas.save();
canvas.scale(accumulatedScale, accumulatedScale, pivotX, pivotY);
canvas.drawBitmap(mBitmap, 0, 0, null);
canvas.restore();
} else {
canvas.drawBitmap(mBitmap, 0, 0, null);
}
renderedOnce = true;
}
@Override public boolean onKeyDown(int keyCode, KeyEvent event)
{
switch (keyCode) {
case KeyEvent.KEYCODE_0:
case KeyEvent.KEYCODE_1:
case KeyEvent.KEYCODE_2:
case KeyEvent.KEYCODE_3:
case KeyEvent.KEYCODE_4:
case KeyEvent.KEYCODE_5:
case KeyEvent.KEYCODE_6:
case KeyEvent.KEYCODE_7:
case KeyEvent.KEYCODE_8:
case KeyEvent.KEYCODE_9:
AppSupport.key((char) ('0' + keyCode - KeyEvent.KEYCODE_0));
return true;
case KeyEvent.KEYCODE_DEL:
AppSupport.key((char) Key.BACKSPACE);
return true;
case KeyEvent.KEYCODE_ENTER:
AppSupport.key((char) Key.RETURN);
return true;
case KeyEvent.KEYCODE_TAB:
AppSupport.key((char) Key.TAB);
return true;
default:
return false;
}
}
@Override public boolean onTouchEvent(MotionEvent event)
{
boolean scrollJustEnded = false;
if (event.getPointerCount() == 1 &&
gestureDetector.onTouchEvent(event)) {
return true;
}
// There is no callback in SimpleOnGestureListener for end
// of scroll. Is this a good way to detect it? Assume that
// as long as the scrolling gesture is in progress, the
// Gesturedetector.onTouchEvent() will keep returning
// true, so if scrollInProgress is true and we get here,
// the scroll must have ended.
if (scrollInProgress) {
AppSupport.scroll((int) translateX, (int) translateY);
translateX = translateY = 0;
scrollInProgress = false;
scrollJustEnded = true;
invalidate();
} else if (event.getPointerCount() == 2 &&
scaleDetector.onTouchEvent(event) &&
scalingInProgress) {
// If a scaling gesture is in progress no other touch
// processing should be done.
return true;
}
// Just temporary hack. We should not show the keyboard
// unconditionally on a ACTION_UP event here. The LO level
// should callback to us requesting showing the keyboard
// if the user taps in a text area. Unfortunately it seems
// less than obvious where the correct place to insert
// such a request is.
// Also, if the device has a hardware keyboard, we
// probably should not show the soft one unconditionally?
// But what if the user wants to input in another script
// than what the hardware keyboard covers?
if (!scrollJustEnded &&
event.getPointerCount() == 1 &&
event.getActionMasked() == MotionEvent.ACTION_UP) {
// show the keyboard so we can enter text
InputMethodManager imm = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(this, InputMethodManager.SHOW_FORCED);
}
if (event.getPointerCount() == 1) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_MOVE:
AppSupport.touch(event.getActionMasked(), (int) event.getX(), (int) event.getY());
break;
}
}
return true;
}
@Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
BaseInputConnection fic = new LOInputConnection(this, true);
outAttrs.actionLabel = null;
outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
outAttrs.imeOptions = EditorInfo.IME_ACTION_NONE;
return fic;
}
@Override public boolean onCheckIsTextEditor() {
return renderedOnce;
}
}
class LOInputConnection
extends BaseInputConnection
{
public LOInputConnection(View targetView, boolean fullEditor) {
super(targetView, fullEditor);
}
@Override public boolean commitText(CharSequence text, int newCursorPosition) {
for (int i = 0; i < text.length(); i++) {
AppSupport.key(text.charAt(i));
}
return true;
}
}
}
// vim:set shiftwidth=4 softtabstop=4 expandtab:
| Imrove scrolling in the Android "Desktop" app
I got scrolling to respond to the JNI scroll method call. (This is not yet
the gesture I want to implement (scroll by pixels), but at least it’s a
start.)
At first I tried to do some hacking in the C++ part, then found the problem
was in the Java parameters, which set the mouse whell delta too big. When
passed the value 1 or -1 to the Y value of AppSupport.scroll(int x, int y),
the scrolling is reasonable.
Change-Id: Id8fa0ada1a035760b7b05bf21325d0e51ef28fdc
| android/experimental/desktop/src/org/libreoffice/experimental/desktop/Desktop.java | Imrove scrolling in the Android "Desktop" app | <ide><path>ndroid/experimental/desktop/src/org/libreoffice/experimental/desktop/Desktop.java
<ide>
<ide> BootstrapContext bootstrapContext;
<ide>
<add> private static final Integer ZERO = 0;
<add>
<add> private static int normalize(Number value) {
<add> return ZERO.compareTo(-value.intValue());
<add> }
<add>
<ide> private void initBootstrapContext()
<ide> {
<ide> bootstrapContext = new BootstrapContext();
<ide> // the scroll must have ended.
<ide>
<ide> if (scrollInProgress) {
<del> AppSupport.scroll((int) translateX, (int) translateY);
<add> AppSupport.scroll(normalize(translateX), normalize(translateY));
<ide> translateX = translateY = 0;
<ide> scrollInProgress = false;
<ide> scrollJustEnded = true; |
|
JavaScript | mit | 0f1647c3b823bb8af504927e4128a0e7e48043c6 | 0 | gamekeller/next,gamekeller/next | var mongoose = require('mongoose')
var secrets = require('../lib/config').secrets
var connected = false
var redis
var User
module.exports = function(grunt) {
function connect(callback) {
if(!connected) {
mongoose.connect(secrets.db)
redis = require('../lib/redis')
mongoose.connection.on('open', function() {
User = require('../lib/models/User')
connected = true
callback()
})
} else {
callback()
}
}
grunt.registerTask('addUser', 'add a user to the database', function(name, email, pass, admin) {
var done = this.async()
connect(function() {
var user =
new User({
username: name,
email: email,
password: pass,
admin: (admin === 'true')
})
user.save(function(err) {
if(err) {
grunt.log.error('Error: ' + err)
done(false)
} else {
grunt.log.writeln('Saved user: ' + user.username)
done()
}
})
})
})
grunt.registerTask('dropDB', 'drop the database', function() {
var done = this.async()
connect(function() {
mongoose.connection.db.dropDatabase(function(err) {
if(err) {
grunt.fail.fatal('Error: ' + err)
done(false)
} else {
grunt.log.writeln('Successfully dropped Mongo database.')
redis.$.flushdb()
redis.$.quit()
grunt.log.writeln('Successfully dropped Redis database.')
done()
}
})
})
})
grunt.registerTask('seedDB', 'seed the database', function() {
grunt.task.run('addUser:master:[email protected]:master:true')
grunt.task.run('addUser:bob:[email protected]:password:false')
grunt.log.writeln('Adding users "master" and "bob" to the DB.')
})
} | grunt/db.js | var mongoose = require('mongoose')
var secrets = require('../lib/config').secrets
var connected = false
var redis
var User
module.exports = function(grunt) {
function connect(callback) {
if(!connected) {
redis = require('../lib/redis')
User = require('../lib/models/User')
mongoose.connection.on('open', function() {
connected = true
callback()
})
} else {
callback()
}
}
grunt.registerTask('addUser', 'add a user to the database', function(name, email, pass, admin) {
var done = this.async()
connect(function() {
var user =
new User({
username: name,
email: email,
password: pass,
admin: (admin === 'true')
})
user.save(function(err) {
if(err) {
grunt.log.error('Error: ' + err)
done(false)
} else {
grunt.log.writeln('Saved user: ' + user.username)
done()
}
})
})
})
grunt.registerTask('dropDB', 'drop the database', function() {
var done = this.async()
connect(function() {
mongoose.connection.db.dropDatabase(function(err) {
if(err) {
grunt.fail.fatal('Error: ' + err)
done(false)
} else {
grunt.log.writeln('Successfully dropped Mongo database.')
redis.$.flushdb()
redis.$.quit()
grunt.log.writeln('Successfully dropped Redis database.')
done()
}
})
})
})
grunt.registerTask('seedDB', 'seed the database', function() {
grunt.task.run('addUser:master:[email protected]:master:true')
grunt.task.run('addUser:bob:[email protected]:password:false')
grunt.log.writeln('Adding users "master" and "bob" to the DB.')
})
} | Fix database grunt tasks
[ci skip]
| grunt/db.js | Fix database grunt tasks | <ide><path>runt/db.js
<ide> module.exports = function(grunt) {
<ide> function connect(callback) {
<ide> if(!connected) {
<add> mongoose.connect(secrets.db)
<ide> redis = require('../lib/redis')
<del> User = require('../lib/models/User')
<ide> mongoose.connection.on('open', function() {
<add> User = require('../lib/models/User')
<ide> connected = true
<ide> callback()
<ide> }) |
|
JavaScript | mit | 8883e2557cea663dbba176bde568576b31733514 | 0 | maovt/p3_api,PATRIC3/p3_api,maovt/p3_api,maovt/p3_api,aswarren/p3_api,maovt/p3_api,aswarren/p3_api,maovt/p3_api,maovt/p3_api,PATRIC3/p3_api | var express = require('express');
var router = express.Router({strict:true,mergeParams:true});
var defer = require("promised-io/promise").defer;
var when = require("promised-io/promise").when;
var config = require("../config");
var SolrQueryParser = require("../middleware/SolrQueryParser");
var RQLQueryParser = require("../middleware/RQLQueryParser");
var authMiddleware = require("../middleware/auth");
var solrjs = require("solrjs");
var media = require("../middleware/media");
var httpParams = require("../middleware/http-params");
var SOLR_URL=config.get("solr").url;
var bodyParser = require("body-parser");
var rql = require("solrjs/rql");
var debug = require('debug')('p3api-server:dataroute');
var Expander= require("../ExpandingQuery");
var rqlToSolr = function(req, res, next) {
debug("RQLQueryParser", req.queryType);
if (req.queryType=="rql"){
req.call_params[0] = req.call_params[0] || "";
when(Expander.ResolveQuery(req.call_params[0],{req:req,res:res}), function(q){
console.log("Resolved Query: ", q);
if (q=="()") { q = ""; }
req.call_params[0] = rql(q).toSolr({maxRequestLimit: 250})
console.log("Converted Solr Query: ", req.call_params[0]);
req.queryType="solr";
next();
});
}else{
next();
}
}
var querySOLR = function(req, res, next) {
if (req.call_method!="query"){ next(); }
var query = req.call_params[0];
console.log("querySOLR req.params", req.call_params[0]);
var solr = new solrjs(SOLR_URL + "/" + req.call_collection);
when(solr.query(query), function(results) {
console.log("querySOLR results", results);
if (!results || !results.response){
res.results=[];
res.set("Content-Range", "items 0-0/0");
}else{
res.results = results;
res.set("Content-Range", "items " + (results.response.start || 0) + "-" + ((results.response.start||0)+results.response.docs.length) + "/" + results.response.numFound);
}
next();
})
}
var getSOLR = function(req, res, next) {
var solr = new solrjs(SOLR_URL + "/" + req.call_collection);
when(solr.get(req.call_params[0]), function(results) {
res.results = results;
next();
});
}
var decorateQuery = function(req, res, next) {
if (req.call_method !="query"){ return next(); }
debug("decorateQuery", req.solr_query);
req.call_params[0] = req.call_params[0] || "&q=*:*";
if (!req.user) {
req.call_params[0] = req.call_params[0] + "&fq=public:true"
}
else {
req.call_params[0]= req.call_params[0] + ("&fq=(public:true OR owner:" + req.user + " OR user_read:" + req.user + ")");
}
next();
}
var methodHandler = function(req, res, next) {
debug("MethodHandler", req.call_method, req.call_params);
switch(req.call_method) {
case "query":
return querySOLR(req,res,next);
break;
case "get":
return getSOLR(req,res,next)
}
}
router.use(httpParams);
router.use(authMiddleware);
router.use(function(req,res,next){
debug("req.path", req.path);
debug("req content-type", req.get("content-type"));
debug("accept", req.get("accept"));
debug("req.url", req.url);
debug('req.path', req.path);
debug('req.params:', JSON.stringify(req.params));
next();
});
router.get("*", function(req,res,next){
if (req.path=="/"){
req.call_method = "query";
var ctype = req.get('content-type');
debug("ctype: ", ctype);
if (!ctype){ ctype = req.headers['content-type'] = "applicaton/x-www-form-urlencoded"}
if (ctype == "application/solrquery+x-www-form-urlencoded"){
req.queryType = "solr";
}else{
req.queryType = "rql";
}
debug('req.queryType: ', req.queryType)
req.call_params = [req._parsedUrl.query||""];
req.call_collection = req.params.dataType;
}else{
if (req.params[0]){
req.params[0] = req.params[0].substr(1);
var ids = decodeURIComponent(req.params[0]).split(",");
if (ids.length == 1) { ids=ids[0]}
}
req.call_method = "get";
req.call_params = [ids];
req.call_collection = req.params.dataType;
}
next();
})
router.post("*", [
bodyParser.json({type:["application/jsonrpc+json"]}),
bodyParser.json({type:["application/json"]}),
function(req,res,next){
debug("json req._body", req._body);
if (!req._body || !req.body) { next(); return }
var ctype=req.get("content-type");
if (req.body.jsonrpc || (ctype=="application/jsonrpc+json")){
debug("JSON RPC Request", JSON.stringify(req.body,null,4));
if (!req.body.method){
throw Error("Invalid Method");
}
req.call_method=req.body.method;
req.call_params = req.body.params;
req.call_collection = req.params.dataType;
}else{
debug("JSON POST Request", JSON.stringify(req.body,null,4));
req.call_method="post";
req.call_params = [req.body];
req.call_collection = req.params.dataType;
}
next("route");
},
bodyParser.text({type:"application/rqlquery+x-www-form-urlencoded"}),
bodyParser.text({type:"application/solrquery+x-www-form-urlencoded"}),
bodyParser.urlencoded(),
function(req,res,next){
console.log("POST: ", req.body,req);
if (!req._body || !req.body) { next("route"); return }
var ctype=req.get("content-type");
req.call_method="query";
req.call_params = req.body;
req.call_collection = req.params.dataType;
req.queryType = (ctype=="application/solrquery+x-www-form-urlencoded")?"solr":"rql";
next();
}
])
var maxLimit=250;
router.use([
rqlToSolr,
decorateQuery,
function(req,res,next){
if (req.call_method!="query") { return next(); }
var limit = maxLimit;
var q = req.call_params[0];
var re = /(&rows=)(\d*)/;
var matches = q.match(re);
if (matches && matches[2] && (matches[2]>maxLimit)){
limit=maxLimit
}else{
limit=matches[2];
}
if (req.headers.range) {
var range = req.headers.range.match(/^items=(\d+)-(\d+)?$/);
if (range){
start = range[1] || 0;
end = range[2] || maxLimit;
var l = end - start;
if (l>maxLimit){
limit=maxLimit;
}
var queryOffset=start;
}
}
if (matches){
req.call_params[0]= q.replace(matches[0],"&rows="+limit);
}else{
req.call_params[0] = req.call_params[0] + "&rows=" + limit;
}
if (queryOffset) {
re = /(&start=)(\d+)/;
var offsetMatches = q.match(re);
if (!offsetMatches){
req.call_params[0] = req.call_params[0] + "&start=" + queryOffset;
}
}
next();
},
function(req,res,next){
if (!req.call_method || !req.call_collection) { return next("route"); }
debug("req.call_method: ", req.call_method);
debug('req.call_params: ', req.call_params);
debug('req.call_collection: ', req.call_collection);
if (req.call_method=="query"){
debug('req.queryType: ', req.queryType);
}
next();
},
methodHandler,
media
// function(req,res,next){
// res.write(JSON.stringify(res.results,null,4));
// res.end();
// }
])
// router.post("/:dataType/rpc", function(req,res,next){
// debug("Handle RPC Calls");
// next()
// } );
// router.use("/:dataType/query*", function(req,res,next){ req.action="query"; next(); } );
// router.use("/:dataType/query/rql",RQLQueryParser)
// router.use("/:dataType/query/rql",RQLQueryParser)
// router.use("/:dataType/query*",[SolrQueryParser, decorateQuery]);
// router.use("/:dataType/query*",[SolrQueryParser, decorateQuery]);
// router.param(":ids", function(req, res, next, ids) {
// req.params.ids = ids.split(",");
// debug("router.params :ids", req.params.ids);
// next();
// })
// router.get('/:dataType/get/:ids', function(req, res, next) {req.action="get"; debug("req.params: ", req.params); next()});
// router.use(methodHandler);
// router.get("/:dataType/query/rql",function(req,res,next){
// debug("Transform RQL Queried Results Here");
// next()
// })
// router.post("/:dataType/query/rql",function(req,res,next){
// debug("Transform RQL Queried Results Here");
// next()
// })
// router.use("/:dataType/*", [
// function(req,res,next){
// res.type("json");
// res.write(JSON.stringify(res.results,null,4))
// res.end();
// }
// ])
module.exports = router;
| routes/dataType.js | var express = require('express');
var router = express.Router({strict:true,mergeParams:true});
var defer = require("promised-io/promise").defer;
var when = require("promised-io/promise").when;
var config = require("../config");
var SolrQueryParser = require("../middleware/SolrQueryParser");
var RQLQueryParser = require("../middleware/RQLQueryParser");
var authMiddleware = require("../middleware/auth");
var solrjs = require("solrjs");
var media = require("../middleware/media");
var httpParams = require("../middleware/http-params");
var SOLR_URL=config.get("solr").url;
var bodyParser = require("body-parser");
var rql = require("solrjs/rql");
var debug = require('debug')('p3api-server:dataroute');
var Expander= require("../ExpandingQuery");
var rqlToSolr = function(req, res, next) {
debug("RQLQueryParser", req.queryType);
if (req.queryType=="rql"){
req.call_params[0] = req.call_params[0] || "";
when(Expander.ResolveQuery(req.call_params[0],{req:req,res:res}), function(q){
console.log("Resolved Query: ", q);
if (q=="()") { q = ""; }
req.call_params[0] = rql(q).toSolr({maxRequestLimit: 250})
console.log("Converted Solr Query: ", req.call_params[0]);
req.queryType="solr";
next();
});
}else{
next();
}
}
var querySOLR = function(req, res, next) {
if (req.call_method!="query"){ next(); }
var query = req.call_params[0];
console.log("querySOLR req.params", req.call_params[0]);
var solr = new solrjs(SOLR_URL + "/" + req.call_collection);
when(solr.query(query), function(results) {
console.log("querySOLR results", results);
if (!results || !results.response){
res.results=[];
res.set("Content-Range", "items 0-0/0");
}else{
res.results = results;
res.set("Content-Range", "items " + (results.response.start || 0) + "-" + ((results.response.start||0)+results.response.docs.length) + "/" + results.response.numFound);
}
next();
})
}
var getSOLR = function(req, res, next) {
var solr = new solrjs(SOLR_URL + "/" + req.call_collection);
when(solr.get(req.call_params[0]), function(results) {
res.results = results;
next();
});
}
var decorateQuery = function(req, res, next) {
if (req.call_method !="query"){ return next(); }
debug("decorateQuery", req.solr_query);
req.call_params[0] = req.call_params[0] || "&q=*:*";
if (!req.user) {
req.call_params[0] = req.call_params[0] + "&fq=public:true"
}
else {
req.call_params[0]= req.call_params[0] + ("&fq=(public:true OR owner:" + req.user + " OR user_read:" + req.user + ")");
}
next();
}
var methodHandler = function(req, res, next) {
debug("MethodHandler", req.call_method, req.call_params);
switch(req.call_method) {
case "query":
return querySOLR(req,res,next);
break;
case "get":
return getSOLR(req,res,next)
}
}
router.use(httpParams);
router.use(authMiddleware);
router.use(function(req,res,next){
debug("req.path", req.path);
debug("req content-type", req.get("content-type"));
debug("accept", req.get("accept"));
debug("req.url", req.url);
debug('req.path', req.path);
debug('req.params:', JSON.stringify(req.params));
next();
});
router.get("*", function(req,res,next){
if (req.path=="/"){
req.call_method = "query";
var ctype = req.get('content-type');
debug("ctype: ", ctype);
if (!ctype){ ctype = req.headers['content-type'] = "applicaton/x-www-form-urlencoded"}
if (ctype == "application/solrquery+x-www-form-urlencoded"){
req.queryType = "solr";
}else{
req.queryType = "rql";
}
debug('req.queryType: ', req.queryType)
req.call_params = [req._parsedUrl.query||""];
req.call_collection = req.params.dataType;
}else{
if (req.params[0]){
req.params[0] = req.params[0].substr(1);
var ids = decodeURIComponent(req.params[0]).split(",");
if (ids.length == 1) { ids=ids[0]}
}
req.call_method = "get";
req.call_params = [ids];
req.call_collection = req.params.dataType;
}
next();
})
router.post("*", [
bodyParser.json({type:["application/jsonrpc+json"]}),
bodyParser.json({type:["application/json"]}),
function(req,res,next){
debug("json req._body", req._body);
if (!req._body || !req.body) { next(); return }
var ctype=req.get("content-type");
if (req.body.jsonrpc || (ctype=="application/jsonrpc+json")){
debug("JSON RPC Request", JSON.stringify(req.body,null,4));
if (!req.body.method){
throw Error("Invalid Method");
}
req.call_method=req.body.method;
req.call_params = req.body.params;
req.call_collection = req.params.dataType;
}else{
debug("JSON POST Request", JSON.stringify(req.body,null,4));
req.call_method="post";
req.call_params = [req.body];
req.call_collection = req.params.dataType;
}
next("route");
},
bodyParser.text({type:"application/rqlquery+x-www-form-urlencoded"}),
bodyParser.text({type:"application/solrquery+x-www-form-urlencoded"}),
function(req,res,next){
if (!req._body || !req.body) { next("route"); return }
var ctype=req.get("content-type");
req.call_method="query";
req.call_params = req.body;
req.call_collection = req.params.dataType;
req.queryType = (ctype=="application/solrquery+x-www-form-urlencoded")?"solr":"rql";
next();
}
])
var maxLimit=50;
router.use([
rqlToSolr,
decorateQuery,
function(req,res,next){
if (req.call_method!="query") { return next(); }
var limit = maxLimit;
var q = req.call_params[0];
var re = /(&rows=)(\d*)/;
var matches = q.match(re);
if (matches && matches[2] && (matches[2]>maxLimit)){
limit=maxLimit
}else{
limit=matches[2];
}
if (req.headers.range) {
var range = req.headers.range.match(/^items=(\d+)-(\d+)?$/);
if (range){
start = range[1] || 0;
end = range[2] || maxLimit;
var l = end - start;
if (l>maxLimit){
limit=maxLimit;
}
var queryOffset=start;
}
}
if (matches){
req.call_params[0]= q.replace(matches[0],"&rows="+limit);
}else{
req.call_params[0] = req.call_params[0] + "&rows=" + limit;
}
if (queryOffset) {
re = /(&start=)(\d+)/;
var offsetMatches = q.match(re);
if (!offsetMatches){
req.call_params[0] = req.call_params[0] + "&start=" + queryOffset;
}
}
next();
},
function(req,res,next){
if (!req.call_method || !req.call_collection) { return next("route"); }
debug("req.call_method: ", req.call_method);
debug('req.call_params: ', req.call_params);
debug('req.call_collection: ', req.call_collection);
if (req.call_method=="query"){
debug('req.queryType: ', req.queryType);
}
next();
},
methodHandler,
media
// function(req,res,next){
// res.write(JSON.stringify(res.results,null,4));
// res.end();
// }
])
// router.post("/:dataType/rpc", function(req,res,next){
// debug("Handle RPC Calls");
// next()
// } );
// router.use("/:dataType/query*", function(req,res,next){ req.action="query"; next(); } );
// router.use("/:dataType/query/rql",RQLQueryParser)
// router.use("/:dataType/query/rql",RQLQueryParser)
// router.use("/:dataType/query*",[SolrQueryParser, decorateQuery]);
// router.use("/:dataType/query*",[SolrQueryParser, decorateQuery]);
// router.param(":ids", function(req, res, next, ids) {
// req.params.ids = ids.split(",");
// debug("router.params :ids", req.params.ids);
// next();
// })
// router.get('/:dataType/get/:ids', function(req, res, next) {req.action="get"; debug("req.params: ", req.params); next()});
// router.use(methodHandler);
// router.get("/:dataType/query/rql",function(req,res,next){
// debug("Transform RQL Queried Results Here");
// next()
// })
// router.post("/:dataType/query/rql",function(req,res,next){
// debug("Transform RQL Queried Results Here");
// next()
// })
// router.use("/:dataType/*", [
// function(req,res,next){
// res.type("json");
// res.write(JSON.stringify(res.results,null,4))
// res.end();
// }
// ])
module.exports = router;
| fix query post
| routes/dataType.js | fix query post | <ide><path>outes/dataType.js
<ide> },
<ide> bodyParser.text({type:"application/rqlquery+x-www-form-urlencoded"}),
<ide> bodyParser.text({type:"application/solrquery+x-www-form-urlencoded"}),
<del> function(req,res,next){
<add> bodyParser.urlencoded(),
<add> function(req,res,next){
<add> console.log("POST: ", req.body,req);
<ide> if (!req._body || !req.body) { next("route"); return }
<ide> var ctype=req.get("content-type");
<ide> req.call_method="query";
<ide> }
<ide> ])
<ide>
<del>var maxLimit=50;
<add>var maxLimit=250;
<ide>
<ide> router.use([
<ide> rqlToSolr, |
|
Java | apache-2.0 | 93fc92cec3ace944026a0e92f4a0f33b06280a8e | 0 | satishpatil2k13/Alan_Gates-OMID-HBase,ngaut/omid,satishpatil2k13/Alan_Gates-OMID-HBase,yonigottesman/incubator-omid,satishpatil2k13/HBASE_OMID,satishpatil2k13/HBASE_OMID,yahoo/omid,yahoo/omid,ngaut/omid,yonigottesman/incubator-omid | /**
* Copyright (c) 2011 Yahoo! 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. See accompanying LICENSE file.
*/
package com.yahoo.omid.notifications;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.BinaryComparator;
import org.apache.hadoop.hbase.filter.CompareFilter;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.log4j.Logger;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.yahoo.omid.notifications.AppSandbox.App;
import com.yahoo.omid.notifications.conf.DeltaOmidServerConfig;
public class ScannerSandbox {
private static final Log logger = LogFactory.getLog(ScannerSandbox.class);
// Lock used by ScannerContainers to protect concurrent accesses to HBaseAdmin when meta-data is created in HTables
private static final Lock htableLock = new ReentrantLock();
private DeltaOmidServerConfig conf;
private Configuration config = HBaseConfiguration.create();
// Key: Interest where the scanners running on the ScannerContainer will do
// their work
// Value: The ScannerContainer that executes the scanner threads scanning
// each particular interest
private ConcurrentHashMap<String, ScannerContainer> scanners = new ConcurrentHashMap<String, ScannerContainer>();
public ScannerSandbox(DeltaOmidServerConfig conf) {
this.conf = conf;
}
public void registerInterestsFromApplication(App app) throws Exception {
for (String appInterest : app.getInterests()) {
ScannerContainer scannerContainer = scanners.get(appInterest);
if (scannerContainer == null) {
scannerContainer = new ScannerContainer(appInterest);
ScannerContainer previousScannerContainer = scanners.putIfAbsent(appInterest, scannerContainer);
if (previousScannerContainer != null) {
previousScannerContainer.addInterestedApplication(app);
logger.trace("Application added to ScannerContainer for interest " + appInterest);
System.out.println("Application added to ScannerContainer for interest " + appInterest);
return;
} else {
scannerContainer.start();
}
}
scannerContainer.addInterestedApplication(app);
logger.trace("ScannerContainer created for interest " + appInterest);
}
}
public void removeInterestsFromApplication(App app) throws InterruptedException {
for (String appInterest : app.getInterests()) {
ScannerContainer scannerContainer = scanners.get(appInterest);
if (scannerContainer != null) {
synchronized (scannerContainer) {
scannerContainer.removeInterestedApplication(app);
if (scannerContainer.countInterestedApplications() == 0) {
scannerContainer.stop();
scanners.remove(appInterest);
}
}
}
}
}
/**
* Added for testing
*
* @return a map of scanner containers keyed by interest
*/
public Map<String, ScannerContainer> getScanners() {
return scanners;
}
public class ScannerContainer {
private final Logger logger = Logger.getLogger(ScannerContainer.class);
private final long TIMEOUT = 3;
private final TimeUnit UNIT = TimeUnit.SECONDS;
private final ExecutorService exec;
private Interest interest;
private Set<App> interestedApps = Collections.synchronizedSet(new HashSet<App>());
/**
* @param interest
* @param appSandbox
* @throws IOException
*/
public ScannerContainer(String interest) throws IOException {
this.interest = Interest.fromString(interest);
this.exec = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat(
"Scanner container [" + interest + "]").build());
// Generate scaffolding on HBase to maintain the information required to
// perform notifications
htableLock.lock();
HBaseAdmin admin = new HBaseAdmin(config);
try { // TODO: This code should not be here in a production system
// because it disables the table to add a CF
HTableDescriptor tableDesc = admin.getTableDescriptor(this.interest.getTableAsHBaseByteArray());
if (!tableDesc.hasFamily(Bytes.toBytes(Constants.HBASE_META_CF))) {
String tableName = this.interest.getTable();
if (admin.isTableEnabled(tableName)) {
admin.disableTable(tableName);
}
HColumnDescriptor metaCF = new HColumnDescriptor(Constants.HBASE_META_CF);
admin.addColumn(tableName, metaCF); // CF for storing metadata
// related to the notif.
// framework
// TODO I think that coprocessors can not be added dynamically.
// It has been moved to OmidInfrastructure
// Map<String, String> params = new HashMap<String, String>();
// tableDesc.addCoprocessor(TransactionCommittedRegionObserver.class.getName(),
// null, Coprocessor.PRIORITY_USER, params);
admin.enableTable(tableName);
logger.trace("Column family metadata added!!!");
} else {
logger.trace("Column family metadata was already added!!! Skipping...");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
admin.close();
htableLock.unlock();
}
}
public void addInterestedApplication(App app) {
interestedApps.add(app);
}
public void removeInterestedApplication(App app) {
interestedApps.remove(app);
}
public int countInterestedApplications() {
return interestedApps.size();
}
public void start() throws Exception {
// TODO Start the number of required scanners instead of only one
exec.submit(new Scanner());
logger.trace("Scanners on " + interest + " started");
}
public void stop() throws InterruptedException {
exec.shutdownNow();
exec.awaitTermination(TIMEOUT, UNIT);
logger.trace("Scanners on " + interest + " stopped");
}
public class Scanner implements Callable<Boolean> {
private HTable table = null;
private Random regionRoller = new Random();
private Scan scan = new Scan();
@Override
public Boolean call() { // Scan and notify
long scanIntervalMs = conf.getScanIntervalMs();
ResultScanner scanner = null;
configureBasicScanProperties();
try {
table = new HTable(config, interest.getTable());
while (!Thread.currentThread().isInterrupted()) {
try {
// logger.trace(interest + " scanner waiting " + scanIntervalMs + " millis");
Thread.sleep(scanIntervalMs);
chooseRandomRegionToScan();
scanner = table.getScanner(scan);
for (Result result : scanner) { // TODO Maybe paginate the result traversal
UpdatedInterestMsg msg = new UpdatedInterestMsg(interest.toStringRepresentation(),
result.getRow());
synchronized (interestedApps) {
// logger.trace("interested apps size " + interestedApps.size());
for (App app : interestedApps) {
app.getAppInstanceRedirector().tell(msg);
app.getMetrics().notificationSentEvent();
}
}
}
} catch (IOException e) {
logger.warn("Can't get scanner for table " + interest.getTable() + " retrying");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
logger.warn("Scanner on interest " + interest + " finished");
} catch (IOException e) {
logger.warn("Scanner on interest " + interest + " not initiated because can't get table");
} finally {
if (scanner != null) {
scanner.close();
}
if (table != null) {
try {
table.close();
} catch (IOException e) {
// Ignore
}
}
}
return new Boolean(true);
}
private void configureBasicScanProperties() {
byte[] cf = Bytes.toBytes(Constants.HBASE_META_CF);
// Pattern for observer column in framework's metadata column
// family: <cf>/<c>-notify
String column = interest.getColumnFamily() + "/" + interest.getColumn() + Constants.HBASE_NOTIFY_SUFFIX;
byte[] c = Bytes.toBytes(column);
byte[] v = Bytes.toBytes("true");
// Filter by value of the notify column
SingleColumnValueFilter valueFilter = new SingleColumnValueFilter(cf, c, CompareFilter.CompareOp.EQUAL,
new BinaryComparator(v));
valueFilter.setFilterIfMissing(true);
scan.setFilter(valueFilter);
}
private void chooseRandomRegionToScan() {
try {
Pair<byte[][], byte[][]> startEndKeys = table.getStartEndKeys();
byte[][] startKeys = startEndKeys.getFirst();
byte[][] endKeys = startEndKeys.getSecond();
int regionIdx = regionRoller.nextInt(startKeys.length);
scan.setStartRow(startKeys[regionIdx]);
byte[] stopRow = endKeys[regionIdx];
// Take into account that the stop row is exclusive, so we need
// to pad a trailing 0 byte at the end
if (stopRow.length != 0) { // This is to avoid add the trailing
// 0 if there's no stopRow specified
stopRow = addTrailingZeroToBA(endKeys[regionIdx]);
}
scan.setStopRow(stopRow);
// logger.trace("Number of startKeys and endKeys in table: " + startKeys.length + " " +
// endKeys.length);
// logger.trace("Region chosen: " + regionIdx);
// logger.trace("Start & Stop Keys: " + Arrays.toString(startKeys[regionIdx]) + " "
// + Arrays.toString(stopRow));
} catch (IOException e) {
e.printStackTrace();
}
}
// Returns a new bytearray that will occur after the original one passed
// by padding its contents with a trailing 0 byte (remember that a
// byte[] is initialized to 0)
private byte[] addTrailingZeroToBA(byte[] originalBA) {
byte[] resultingBA = new byte[originalBA.length + 1];
System.arraycopy(originalBA, 0, resultingBA, 0, originalBA.length);
return resultingBA;
}
}
}
}
| src/main/java/com/yahoo/omid/notifications/ScannerSandbox.java | /**
* Copyright (c) 2011 Yahoo! 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. See accompanying LICENSE file.
*/
package com.yahoo.omid.notifications;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.BinaryComparator;
import org.apache.hadoop.hbase.filter.CompareFilter;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.log4j.Logger;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.yahoo.omid.notifications.AppSandbox.App;
import com.yahoo.omid.notifications.conf.DeltaOmidServerConfig;
public class ScannerSandbox {
private static final Log logger = LogFactory.getLog(ScannerSandbox.class);
// Lock used by ScannerContainers to protect concurrent accesses to HBaseAdmin when meta-data is created in HTables
private static final Lock htableLock = new ReentrantLock();
private DeltaOmidServerConfig conf;
private Configuration config = HBaseConfiguration.create();
// Key: Interest where the scanners running on the ScannerContainer will do
// their work
// Value: The ScannerContainer that executes the scanner threads scanning
// each particular interest
private ConcurrentHashMap<String, ScannerContainer> scanners = new ConcurrentHashMap<String, ScannerContainer>();
public ScannerSandbox(DeltaOmidServerConfig conf) {
this.conf = conf;
}
public void registerInterestsFromApplication(App app) throws Exception {
for(String appInterest : app.getInterests()) {
ScannerContainer scannerContainer = scanners.get(appInterest);
if (scannerContainer == null) {
scannerContainer = new ScannerContainer(appInterest);
ScannerContainer previousScannerContainer = scanners.putIfAbsent(appInterest, scannerContainer);
if(previousScannerContainer != null) {
previousScannerContainer.addInterestedApplication(app);
logger.trace("Application added to ScannerContainer for interest " + appInterest);
System.out.println("Application added to ScannerContainer for interest " + appInterest);
return;
} else {
scannerContainer.start();
}
}
scannerContainer.addInterestedApplication(app);
logger.trace("ScannerContainer created for interest " + appInterest);
}
}
public void removeInterestsFromApplication(App app) throws InterruptedException {
for(String appInterest : app.getInterests()) {
ScannerContainer scannerContainer = scanners.get(appInterest);
if (scannerContainer != null) {
synchronized(scannerContainer) {
scannerContainer.removeInterestedApplication(app);
if(scannerContainer.countInterestedApplications() == 0) {
scannerContainer.stop();
scanners.remove(appInterest);
}
}
}
}
}
/**
* Added for testing
* @return a map of scanner containers keyed by interest
*/
public Map<String, ScannerContainer> getScanners() {
return scanners;
}
public class ScannerContainer {
private final Logger logger = Logger.getLogger(ScannerContainer.class);
private final long TIMEOUT = 3;
private final TimeUnit UNIT = TimeUnit.SECONDS;
private final ExecutorService exec;
private Interest interest;
private Set<App> interestedApps = Collections.synchronizedSet(new HashSet<App>());
/**
* @param interest
* @param appSandbox
* @throws IOException
*/
public ScannerContainer(String interest) throws IOException {
this.interest = Interest.fromString(interest);
this.exec = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat("Scanner container [" + interest + "]").build());
// Generate scaffolding on HBase to maintain the information required to
// perform notifications
htableLock.lock();
HBaseAdmin admin = new HBaseAdmin(config);
try { // TODO: This code should not be here in a production system
// because it disables the table to add a CF
HTableDescriptor tableDesc = admin.getTableDescriptor(this.interest.getTableAsHBaseByteArray());
if (!tableDesc.hasFamily(Bytes.toBytes(Constants.HBASE_META_CF))) {
String tableName = this.interest.getTable();
if(admin.isTableEnabled(tableName)) {
admin.disableTable(tableName);
}
HColumnDescriptor metaCF = new HColumnDescriptor(Constants.HBASE_META_CF);
admin.addColumn(tableName, metaCF); // CF for storing metadata
// related to the notif.
// framework
// TODO I think that coprocessors can not be added dynamically.
// It has been moved to OmidInfrastructure
// Map<String, String> params = new HashMap<String, String>();
// tableDesc.addCoprocessor(TransactionCommittedRegionObserver.class.getName(),
// null, Coprocessor.PRIORITY_USER, params);
admin.enableTable(tableName);
logger.trace("Column family metadata added!!!");
} else {
logger.trace("Column family metadata was already added!!! Skipping...");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
admin.close();
htableLock.unlock();
}
}
public void addInterestedApplication(App app) {
interestedApps.add(app);
}
public void removeInterestedApplication(App app) {
interestedApps.remove(app);
}
public int countInterestedApplications() {
return interestedApps.size();
}
public void start() throws Exception {
// TODO Start the number of required scanners instead of only one
exec.submit(new Scanner());
logger.trace("Scanners on " + interest + " started");
}
public void stop() throws InterruptedException {
exec.shutdownNow();
exec.awaitTermination(TIMEOUT, UNIT);
logger.trace("Scanners on " + interest + " stopped");
}
public class Scanner implements Callable<Boolean> {
private HTable table = null;
private Random regionRoller = new Random();
private Scan scan = new Scan();
@Override
public Boolean call() { // Scan and notify
long scanIntervalMs = conf.getScanIntervalMs();
ResultScanner scanner = null;
configureBasicScanProperties();
try {
table = new HTable(config, interest.getTable());
while (!Thread.currentThread().isInterrupted()) {
try {
logger.trace(interest + " scanner waiting " + scanIntervalMs + " millis");
Thread.sleep(scanIntervalMs);
chooseRandomRegionToScan();
scanner = table.getScanner(scan);
for (Result result : scanner) { // TODO Maybe paginate the result traversal
UpdatedInterestMsg msg = new UpdatedInterestMsg(interest.toStringRepresentation(), result.getRow());
synchronized (interestedApps) {
logger.trace("interested apps size " + interestedApps.size());
for (App app : interestedApps) {
app.getAppInstanceRedirector().tell(msg);
app.getMetrics().notificationSentEvent();
}
}
}
} catch (IOException e) {
logger.warn("Can't get scanner for table " + interest.getTable() + " retrying");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
logger.warn("Scanner on interest " + interest + " finished");
} catch (IOException e) {
logger.warn("Scanner on interest " + interest + " not initiated because can't get table");
} finally {
if(scanner != null) {
scanner.close();
}
if(table != null) {
try {
table.close();
} catch (IOException e) {
// Ignore
}
}
}
return new Boolean(true);
}
private void configureBasicScanProperties() {
byte[] cf = Bytes.toBytes(Constants.HBASE_META_CF);
// Pattern for observer column in framework's metadata column
// family: <cf>/<c>-notify
String column = interest.getColumnFamily() + "/" + interest.getColumn() + Constants.HBASE_NOTIFY_SUFFIX;
byte[] c = Bytes.toBytes(column);
byte[] v = Bytes.toBytes("true");
// Filter by value of the notify column
SingleColumnValueFilter valueFilter = new SingleColumnValueFilter(cf, c, CompareFilter.CompareOp.EQUAL, new BinaryComparator(v));
valueFilter.setFilterIfMissing(true);
scan.setFilter(valueFilter);
}
private void chooseRandomRegionToScan() {
try {
Pair<byte[][], byte[][]> startEndKeys = table.getStartEndKeys();
byte[][] startKeys = startEndKeys.getFirst();
byte[][] endKeys = startEndKeys.getSecond();
int regionIdx = regionRoller.nextInt(startKeys.length);
scan.setStartRow(startKeys[regionIdx]);
byte[] stopRow = endKeys[regionIdx];
// Take into account that the stop row is exclusive, so we need
// to pad a trailing 0 byte at the end
if (stopRow.length != 0) { // This is to avoid add the trailing
// 0 if there's no stopRow specified
stopRow = addTrailingZeroToBA(endKeys[regionIdx]);
}
scan.setStopRow(stopRow);
// logger.trace("Number of startKeys and endKeys in table: " + startKeys.length + " " + endKeys.length);
// logger.trace("Region chosen: " + regionIdx);
// logger.trace("Start & Stop Keys: " + Arrays.toString(startKeys[regionIdx]) + " "
// + Arrays.toString(stopRow));
} catch (IOException e) {
e.printStackTrace();
}
}
// Returns a new bytearray that will occur after the original one passed
// by padding its contents with a trailing 0 byte (remember that a
// byte[] is initialized to 0)
private byte[] addTrailingZeroToBA(byte[] originalBA) {
byte[] resultingBA = new byte[originalBA.length + 1];
System.arraycopy(originalBA, 0, resultingBA, 0, originalBA.length);
return resultingBA;
}
}
}
}
| Traces commented and style formatted
| src/main/java/com/yahoo/omid/notifications/ScannerSandbox.java | Traces commented and style formatted | <ide><path>rc/main/java/com/yahoo/omid/notifications/ScannerSandbox.java
<ide> public class ScannerSandbox {
<ide>
<ide> private static final Log logger = LogFactory.getLog(ScannerSandbox.class);
<del>
<add>
<ide> // Lock used by ScannerContainers to protect concurrent accesses to HBaseAdmin when meta-data is created in HTables
<ide> private static final Lock htableLock = new ReentrantLock();
<ide>
<ide> }
<ide>
<ide> public void registerInterestsFromApplication(App app) throws Exception {
<del> for(String appInterest : app.getInterests()) {
<add> for (String appInterest : app.getInterests()) {
<ide> ScannerContainer scannerContainer = scanners.get(appInterest);
<ide> if (scannerContainer == null) {
<ide> scannerContainer = new ScannerContainer(appInterest);
<ide> ScannerContainer previousScannerContainer = scanners.putIfAbsent(appInterest, scannerContainer);
<del> if(previousScannerContainer != null) {
<add> if (previousScannerContainer != null) {
<ide> previousScannerContainer.addInterestedApplication(app);
<ide> logger.trace("Application added to ScannerContainer for interest " + appInterest);
<ide> System.out.println("Application added to ScannerContainer for interest " + appInterest);
<ide> }
<ide>
<ide> public void removeInterestsFromApplication(App app) throws InterruptedException {
<del> for(String appInterest : app.getInterests()) {
<add> for (String appInterest : app.getInterests()) {
<ide> ScannerContainer scannerContainer = scanners.get(appInterest);
<ide> if (scannerContainer != null) {
<del> synchronized(scannerContainer) {
<add> synchronized (scannerContainer) {
<ide> scannerContainer.removeInterestedApplication(app);
<del> if(scannerContainer.countInterestedApplications() == 0) {
<add> if (scannerContainer.countInterestedApplications() == 0) {
<ide> scannerContainer.stop();
<del> scanners.remove(appInterest);
<del> }
<del> }
<add> scanners.remove(appInterest);
<add> }
<add> }
<ide> }
<ide> }
<ide> }
<ide>
<ide> /**
<ide> * Added for testing
<add> *
<ide> * @return a map of scanner containers keyed by interest
<ide> */
<ide> public Map<String, ScannerContainer> getScanners() {
<ide> return scanners;
<ide> }
<del>
<add>
<ide> public class ScannerContainer {
<ide>
<ide> private final Logger logger = Logger.getLogger(ScannerContainer.class);
<ide> /**
<ide> * @param interest
<ide> * @param appSandbox
<del> * @throws IOException
<add> * @throws IOException
<ide> */
<ide> public ScannerContainer(String interest) throws IOException {
<ide> this.interest = Interest.fromString(interest);
<del> this.exec = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat("Scanner container [" + interest + "]").build());
<add> this.exec = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat(
<add> "Scanner container [" + interest + "]").build());
<ide> // Generate scaffolding on HBase to maintain the information required to
<ide> // perform notifications
<ide> htableLock.lock();
<ide> if (!tableDesc.hasFamily(Bytes.toBytes(Constants.HBASE_META_CF))) {
<ide> String tableName = this.interest.getTable();
<ide>
<del> if(admin.isTableEnabled(tableName)) {
<add> if (admin.isTableEnabled(tableName)) {
<ide> admin.disableTable(tableName);
<ide> }
<ide>
<ide> logger.trace("Column family metadata added!!!");
<ide> } else {
<ide> logger.trace("Column family metadata was already added!!! Skipping...");
<del> }
<add> }
<ide> } catch (Exception e) {
<ide> e.printStackTrace();
<ide> } finally {
<ide> public void addInterestedApplication(App app) {
<ide> interestedApps.add(app);
<ide> }
<del>
<add>
<ide> public void removeInterestedApplication(App app) {
<ide> interestedApps.remove(app);
<ide> }
<del>
<add>
<ide> public int countInterestedApplications() {
<ide> return interestedApps.size();
<ide> }
<del>
<add>
<ide> public void start() throws Exception {
<ide> // TODO Start the number of required scanners instead of only one
<ide> exec.submit(new Scanner());
<ide> table = new HTable(config, interest.getTable());
<ide> while (!Thread.currentThread().isInterrupted()) {
<ide> try {
<del> logger.trace(interest + " scanner waiting " + scanIntervalMs + " millis");
<add> // logger.trace(interest + " scanner waiting " + scanIntervalMs + " millis");
<ide> Thread.sleep(scanIntervalMs);
<ide> chooseRandomRegionToScan();
<ide> scanner = table.getScanner(scan);
<ide> for (Result result : scanner) { // TODO Maybe paginate the result traversal
<del> UpdatedInterestMsg msg = new UpdatedInterestMsg(interest.toStringRepresentation(), result.getRow());
<add> UpdatedInterestMsg msg = new UpdatedInterestMsg(interest.toStringRepresentation(),
<add> result.getRow());
<ide> synchronized (interestedApps) {
<del> logger.trace("interested apps size " + interestedApps.size());
<add> // logger.trace("interested apps size " + interestedApps.size());
<ide> for (App app : interestedApps) {
<ide> app.getAppInstanceRedirector().tell(msg);
<ide> app.getMetrics().notificationSentEvent();
<ide> }
<ide> } catch (InterruptedException e) {
<ide> e.printStackTrace();
<del> logger.warn("Scanner on interest " + interest + " finished");
<add> logger.warn("Scanner on interest " + interest + " finished");
<ide> } catch (IOException e) {
<ide> logger.warn("Scanner on interest " + interest + " not initiated because can't get table");
<ide> } finally {
<del> if(scanner != null) {
<add> if (scanner != null) {
<ide> scanner.close();
<ide> }
<del> if(table != null) {
<add> if (table != null) {
<ide> try {
<ide> table.close();
<ide> } catch (IOException e) {
<ide> String column = interest.getColumnFamily() + "/" + interest.getColumn() + Constants.HBASE_NOTIFY_SUFFIX;
<ide> byte[] c = Bytes.toBytes(column);
<ide> byte[] v = Bytes.toBytes("true");
<del>
<add>
<ide> // Filter by value of the notify column
<del> SingleColumnValueFilter valueFilter = new SingleColumnValueFilter(cf, c, CompareFilter.CompareOp.EQUAL, new BinaryComparator(v));
<add> SingleColumnValueFilter valueFilter = new SingleColumnValueFilter(cf, c, CompareFilter.CompareOp.EQUAL,
<add> new BinaryComparator(v));
<ide> valueFilter.setFilterIfMissing(true);
<ide> scan.setFilter(valueFilter);
<ide> }
<del>
<add>
<ide> private void chooseRandomRegionToScan() {
<ide> try {
<ide> Pair<byte[][], byte[][]> startEndKeys = table.getStartEndKeys();
<ide> byte[][] startKeys = startEndKeys.getFirst();
<ide> byte[][] endKeys = startEndKeys.getSecond();
<ide> int regionIdx = regionRoller.nextInt(startKeys.length);
<del>
<add>
<ide> scan.setStartRow(startKeys[regionIdx]);
<ide> byte[] stopRow = endKeys[regionIdx];
<ide> // Take into account that the stop row is exclusive, so we need
<ide> stopRow = addTrailingZeroToBA(endKeys[regionIdx]);
<ide> }
<ide> scan.setStopRow(stopRow);
<del>// logger.trace("Number of startKeys and endKeys in table: " + startKeys.length + " " + endKeys.length);
<del>// logger.trace("Region chosen: " + regionIdx);
<del>// logger.trace("Start & Stop Keys: " + Arrays.toString(startKeys[regionIdx]) + " "
<del>// + Arrays.toString(stopRow));
<add> // logger.trace("Number of startKeys and endKeys in table: " + startKeys.length + " " +
<add> // endKeys.length);
<add> // logger.trace("Region chosen: " + regionIdx);
<add> // logger.trace("Start & Stop Keys: " + Arrays.toString(startKeys[regionIdx]) + " "
<add> // + Arrays.toString(stopRow));
<ide> } catch (IOException e) {
<ide> e.printStackTrace();
<ide> }
<ide> }
<del>
<add>
<ide> // Returns a new bytearray that will occur after the original one passed
<ide> // by padding its contents with a trailing 0 byte (remember that a
<ide> // byte[] is initialized to 0) |
|
Java | apache-2.0 | cc9a58f15f209586f5f290f2840132de16a87e7c | 0 | san-tak/alien4cloud,alien4cloud/alien4cloud,alien4cloud/alien4cloud,san-tak/alien4cloud,san-tak/alien4cloud,alien4cloud/alien4cloud,san-tak/alien4cloud,alien4cloud/alien4cloud | package alien4cloud.tosca.parser;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.FileNotFoundException;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.alien4cloud.tosca.model.Csar;
import org.alien4cloud.tosca.model.definitions.AbstractPropertyValue;
import org.alien4cloud.tosca.model.definitions.ComplexPropertyValue;
import org.alien4cloud.tosca.model.definitions.FunctionPropertyValue;
import org.alien4cloud.tosca.model.definitions.IValue;
import org.alien4cloud.tosca.model.definitions.PropertyDefinition;
import org.alien4cloud.tosca.model.definitions.PropertyValue;
import org.alien4cloud.tosca.model.templates.Capability;
import org.alien4cloud.tosca.model.templates.NodeTemplate;
import org.alien4cloud.tosca.model.types.CapabilityType;
import org.alien4cloud.tosca.model.types.DataType;
import org.alien4cloud.tosca.model.types.NodeType;
import org.alien4cloud.tosca.model.types.RelationshipType;
import org.apache.commons.collections4.CollectionUtils;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.collect.Lists;
import alien4cloud.paas.plan.ToscaNodeLifecycleConstants;
import alien4cloud.tosca.model.ArchiveRoot;
/**
* Created by lucboutier on 12/04/2017.
*/
public class ToscaParserAlien140Test extends AbstractToscaParserSimpleProfileTest {
@Override
protected String getRootDirectory() {
return "src/test/resources/tosca/alien_dsl_1_4_0/";
}
@Override
protected String getToscaVersion() {
return "alien_dsl_1_4_0";
}
@Test
public void testServiceRelationshipSubstitution() throws FileNotFoundException, ParsingException {
Mockito.reset(csarRepositorySearchService);
Mockito.when(csarRepositorySearchService.getArchive("tosca-normative-types", "1.0.0-ALIEN14")).thenReturn(Mockito.mock(Csar.class));
NodeType mockRoot = Mockito.mock(NodeType.class);
Mockito.when(mockRoot.isAbstract()).thenReturn(true);
Mockito.when(csarRepositorySearchService.getElementInDependencies(Mockito.eq(NodeType.class), Mockito.eq("tosca.nodes.Root"), Mockito.any(Set.class)))
.thenReturn(mockRoot);
Mockito.when(csarRepositorySearchService.getElementInDependencies(Mockito.eq(CapabilityType.class), Mockito.eq("tosca.capabilities.Root"),
Mockito.any(Set.class))).thenReturn(Mockito.mock(CapabilityType.class));
Mockito.when(csarRepositorySearchService.getElementInDependencies(Mockito.eq(RelationshipType.class), Mockito.eq("tosca.relationships.Root"),
Mockito.any(Set.class))).thenReturn(Mockito.mock(RelationshipType.class));
ParsingResult<ArchiveRoot> parsingResult = parser.parseFile(Paths.get(getRootDirectory(), "substitution_mapping_service_relationship.yml"));
Assert.assertEquals(0, parsingResult.getContext().getParsingErrors().size());
ArchiveRoot archiveRoot = parsingResult.getResult();
Assert.assertNotNull(archiveRoot.getArchive());
Assert.assertEquals(getToscaVersion(), archiveRoot.getArchive().getToscaDefinitionsVersion());
Assert.assertEquals("org.alien4cloud.relationships.test.MyRelationship",
archiveRoot.getTopology().getSubstitutionMapping().getCapabilities().get("subst_capa").getServiceRelationshipType());
}
@Test
public void testCapabilitiesComplexProperty() throws ParsingException {
Mockito.reset(csarRepositorySearchService);
Csar csar = new Csar("tosca-normative-types", "1.0.0-ALIEN14");
Mockito.when(csarRepositorySearchService.getArchive(csar.getName(), csar.getVersion())).thenReturn(csar);
NodeType mockedResult = Mockito.mock(NodeType.class);
Mockito.when(csarRepositorySearchService.getElementInDependencies(Mockito.eq(NodeType.class), Mockito.eq("tosca.nodes.Root"), Mockito.any(Set.class)))
.thenReturn(mockedResult);
CapabilityType mockedCapabilityResult = Mockito.mock(CapabilityType.class);
Mockito.when(csarRepositorySearchService.getElementInDependencies(Mockito.eq(CapabilityType.class), Mockito.eq("tosca.capabilities.Root"),
Mockito.any(Set.class))).thenReturn(mockedCapabilityResult);
DataType mockedDataType = new DataType();
Mockito.when(
csarRepositorySearchService.getElementInDependencies(Mockito.eq(DataType.class), Mockito.eq("tosca.datatypes.Root"), Mockito.any(Set.class)))
.thenReturn(mockedDataType);
ParsingResult<ArchiveRoot> parsingResult = parser.parseFile(Paths.get(getRootDirectory(), "capa_complex_props.yml"));
Assert.assertEquals(0, parsingResult.getContext().getParsingErrors().size());
ArchiveRoot archiveRoot = parsingResult.getResult();
// check the capabilityType
//////////////
CapabilityType capaType = archiveRoot.getCapabilityTypes().values().stream().findFirst().get();
assertNotNull(capaType.getProperties());
Assert.assertEquals(3, capaType.getProperties().size());
// map property
String map = "map";
PropertyDefinition propertyDefinition = capaType.getProperties().get(map);
assertNotNull(propertyDefinition.getDefault());
assertTrue(propertyDefinition.getDefault() instanceof ComplexPropertyValue);
Map<String, Object> propertyMapValue = ((ComplexPropertyValue) propertyDefinition.getDefault()).getValue();
assertNotNull(propertyMapValue);
Assert.assertEquals(2, propertyMapValue.size());
Assert.assertEquals("toto_value", propertyMapValue.get("toto"));
Assert.assertEquals("tata_value", propertyMapValue.get("tata"));
// custom property
String custom = "custom";
propertyDefinition = capaType.getProperties().get(custom);
assertEquals("alien.test.datatypes.Custom", propertyDefinition.getType());
assertNull(propertyDefinition.getDefault());
// custom_with_default property
String custom_with_default = "custom_with_default";
propertyDefinition = capaType.getProperties().get(custom_with_default);
assertNotNull(propertyDefinition.getDefault());
assertTrue(propertyDefinition.getDefault() instanceof ComplexPropertyValue);
propertyMapValue = ((ComplexPropertyValue) propertyDefinition.getDefault()).getValue();
assertNotNull(propertyMapValue);
assertEquals(2, propertyMapValue.size());
assertEquals("defaultName", propertyMapValue.get("name"));
Object list = propertyMapValue.get("groups");
assertTrue(list instanceof List);
assertEquals(2, ((List) list).size());
assertTrue(CollectionUtils.containsAll((List) list, Lists.newArrayList("alien", "fastconnect")));
// check the node template capability
//////////////
NodeTemplate nodeTemplate = archiveRoot.getTopology().getNodeTemplates().values().stream().findFirst().get();
Capability capability = nodeTemplate.getCapabilities().values().stream().findFirst().get();
assertNotNull(capability);
Assert.assertEquals(3, capability.getProperties().size());
// map property
AbstractPropertyValue propertyValue = capability.getProperties().get(map);
assertNotNull(propertyValue);
assertTrue(propertyValue instanceof ComplexPropertyValue);
propertyMapValue = ((ComplexPropertyValue) propertyValue).getValue();
assertNotNull(propertyMapValue);
Assert.assertEquals(2, propertyMapValue.size());
Assert.assertEquals("toto_value", propertyMapValue.get("toto"));
Assert.assertEquals("tata_value", propertyMapValue.get("tata"));
// custom property
propertyValue = capability.getProperties().get(custom);
assertNotNull(propertyValue);
assertTrue(propertyValue instanceof ComplexPropertyValue);
propertyMapValue = ((ComplexPropertyValue) propertyValue).getValue();
assertNotNull(propertyMapValue);
assertEquals(2, propertyMapValue.size());
assertEquals("manual", propertyMapValue.get("name"));
list = propertyMapValue.get("groups");
assertTrue(list instanceof List);
assertEquals(2, ((List) list).size());
assertTrue(CollectionUtils.containsAll((List) list, Lists.newArrayList("manual_alien", "manual_fastconnect")));
// custom_with_default property
propertyValue = capability.getProperties().get(custom_with_default);
assertNotNull(propertyValue);
assertTrue(propertyValue instanceof ComplexPropertyValue);
propertyMapValue = ((ComplexPropertyValue) propertyValue).getValue();
assertNotNull(propertyMapValue);
assertEquals(2, propertyMapValue.size());
assertEquals("defaultName", propertyMapValue.get("name"));
list = propertyMapValue.get("groups");
assertTrue(list instanceof List);
assertEquals(2, ((List) list).size());
assertTrue(CollectionUtils.containsAll((List) list, Lists.newArrayList("alien", "fastconnect")));
}
@Test
public void testInterfaceInputs() throws ParsingException {
Mockito.reset(csarRepositorySearchService);
Mockito.when(csarRepositorySearchService.getArchive("tosca-normative-types", "1.0.0-ALIEN14")).thenReturn(Mockito.mock(Csar.class));
Mockito.when(csarRepositorySearchService.getElementInDependencies(Mockito.eq(NodeType.class), Mockito.eq("tosca.nodes.Root"), Mockito.any(Set.class)))
.thenReturn(Mockito.mock(NodeType.class));
ParsingResult<ArchiveRoot> parsingResult = parser.parseFile(Paths.get(getRootDirectory(), "interface-inputs.yml"));
Assert.assertEquals(0, parsingResult.getContext().getParsingErrors().size());
Map<String, IValue> createInputs = parsingResult.getResult().getNodeTypes().get("org.alien4cloud.test.parsing.InterfaceInputsTestNode").getInterfaces()
.get(ToscaNodeLifecycleConstants.STANDARD).getOperations().get("create").getInputParameters();
assertNotNull(createInputs);
assertEquals(2, createInputs.size());
assertNotNull(createInputs.get("prop_definition"));
assertTrue(createInputs.get("prop_definition") instanceof PropertyDefinition);
assertNotNull(createInputs.get("prop_assignment"));
assertTrue(createInputs.get("prop_assignment") instanceof FunctionPropertyValue);
Map<String, IValue> startInputs = parsingResult.getResult().getNodeTypes().get("org.alien4cloud.test.parsing.InterfaceInputsTestNode").getInterfaces()
.get(ToscaNodeLifecycleConstants.STANDARD).getOperations().get("start").getInputParameters();
assertNotNull(startInputs);
assertEquals(3, startInputs.size());
assertNotNull(startInputs.get("prop_definition"));
assertTrue(startInputs.get("prop_definition") instanceof PropertyDefinition);
assertNotNull(startInputs.get("prop_assignment"));
assertTrue(startInputs.get("prop_assignment") instanceof PropertyValue);
assertNotNull(startInputs.get("new_input"));
assertTrue(startInputs.get("new_input") instanceof PropertyValue);
}
@Test
public void testDuplicateNodeTemplate() throws ParsingException {
Mockito.reset(csarRepositorySearchService);
Mockito.when(csarRepositorySearchService.getArchive("tosca-normative-types", "1.0.0-ALIEN14")).thenReturn(Mockito.mock(Csar.class));
Mockito.when(csarRepositorySearchService.getElementInDependencies(Mockito.eq(NodeType.class), Mockito.eq("tosca.nodes.Root"), Mockito.any(Set.class)))
.thenReturn(Mockito.mock(NodeType.class));
ParsingResult<ArchiveRoot> parsingResult = parser.parseFile(Paths.get(getRootDirectory(), "topo-duplicate-node-template.yml"));
Assert.assertEquals(0, parsingResult.getContext().getParsingErrors().size());
}
} | alien4cloud-tosca/src/test/java/alien4cloud/tosca/parser/ToscaParserAlien140Test.java | package alien4cloud.tosca.parser;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.FileNotFoundException;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Set;
import alien4cloud.paas.plan.ToscaNodeLifecycleConstants;
import org.alien4cloud.tosca.model.Csar;
import org.alien4cloud.tosca.model.definitions.AbstractPropertyValue;
import org.alien4cloud.tosca.model.definitions.ComplexPropertyValue;
import org.alien4cloud.tosca.model.definitions.FunctionPropertyValue;
import org.alien4cloud.tosca.model.definitions.IValue;
import org.alien4cloud.tosca.model.definitions.PropertyDefinition;
import org.alien4cloud.tosca.model.definitions.PropertyValue;
import org.alien4cloud.tosca.model.templates.Capability;
import org.alien4cloud.tosca.model.templates.NodeTemplate;
import org.alien4cloud.tosca.model.types.CapabilityType;
import org.alien4cloud.tosca.model.types.DataType;
import org.alien4cloud.tosca.model.types.NodeType;
import org.alien4cloud.tosca.model.types.RelationshipType;
import org.apache.commons.collections4.CollectionUtils;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.collect.Lists;
import alien4cloud.tosca.model.ArchiveRoot;
/**
* Created by lucboutier on 12/04/2017.
*/
public class ToscaParserAlien140Test extends AbstractToscaParserSimpleProfileTest {
@Override
protected String getRootDirectory() {
return "src/test/resources/tosca/alien_dsl_1_4_0/";
}
@Override
protected String getToscaVersion() {
return "alien_dsl_1_4_0";
}
@Test
public void testServiceRelationshipSubstitution() throws FileNotFoundException, ParsingException {
Mockito.reset(csarRepositorySearchService);
Mockito.when(csarRepositorySearchService.getArchive("tosca-normative-types", "1.0.0-ALIEN14")).thenReturn(Mockito.mock(Csar.class));
Mockito.when(csarRepositorySearchService.getElementInDependencies(Mockito.eq(NodeType.class), Mockito.eq("tosca.nodes.Root"), Mockito.any(Set.class)))
.thenReturn(Mockito.mock(NodeType.class));
Mockito.when(csarRepositorySearchService.getElementInDependencies(Mockito.eq(CapabilityType.class), Mockito.eq("tosca.capabilities.Root"),
Mockito.any(Set.class))).thenReturn(Mockito.mock(CapabilityType.class));
Mockito.when(csarRepositorySearchService.getElementInDependencies(Mockito.eq(RelationshipType.class), Mockito.eq("tosca.relationships.Root"),
Mockito.any(Set.class))).thenReturn(Mockito.mock(RelationshipType.class));
ParsingResult<ArchiveRoot> parsingResult = parser.parseFile(Paths.get(getRootDirectory(), "substitution_mapping_service_relationship.yml"));
Assert.assertEquals(0, parsingResult.getContext().getParsingErrors().size());
ArchiveRoot archiveRoot = parsingResult.getResult();
Assert.assertNotNull(archiveRoot.getArchive());
Assert.assertEquals(getToscaVersion(), archiveRoot.getArchive().getToscaDefinitionsVersion());
Assert.assertEquals("org.alien4cloud.relationships.test.MyRelationship",
archiveRoot.getTopology().getSubstitutionMapping().getCapabilities().get("subst_capa").getServiceRelationshipType());
}
@Test
public void testCapabilitiesComplexProperty() throws ParsingException {
Mockito.reset(csarRepositorySearchService);
Csar csar = new Csar("tosca-normative-types", "1.0.0-ALIEN14");
Mockito.when(csarRepositorySearchService.getArchive(csar.getName(), csar.getVersion())).thenReturn(csar);
NodeType mockedResult = Mockito.mock(NodeType.class);
Mockito.when(csarRepositorySearchService.getElementInDependencies(Mockito.eq(NodeType.class), Mockito.eq("tosca.nodes.Root"), Mockito.any(Set.class)))
.thenReturn(mockedResult);
CapabilityType mockedCapabilityResult = Mockito.mock(CapabilityType.class);
Mockito.when(csarRepositorySearchService.getElementInDependencies(Mockito.eq(CapabilityType.class), Mockito.eq("tosca.capabilities.Root"),
Mockito.any(Set.class))).thenReturn(mockedCapabilityResult);
DataType mockedDataType = new DataType();
Mockito.when(
csarRepositorySearchService.getElementInDependencies(Mockito.eq(DataType.class), Mockito.eq("tosca.datatypes.Root"), Mockito.any(Set.class)))
.thenReturn(mockedDataType);
ParsingResult<ArchiveRoot> parsingResult = parser.parseFile(Paths.get(getRootDirectory(), "capa_complex_props.yml"));
Assert.assertEquals(0, parsingResult.getContext().getParsingErrors().size());
ArchiveRoot archiveRoot = parsingResult.getResult();
// check the capabilityType
//////////////
CapabilityType capaType = archiveRoot.getCapabilityTypes().values().stream().findFirst().get();
assertNotNull(capaType.getProperties());
Assert.assertEquals(3, capaType.getProperties().size());
// map property
String map = "map";
PropertyDefinition propertyDefinition = capaType.getProperties().get(map);
assertNotNull(propertyDefinition.getDefault());
assertTrue(propertyDefinition.getDefault() instanceof ComplexPropertyValue);
Map<String, Object> propertyMapValue = ((ComplexPropertyValue) propertyDefinition.getDefault()).getValue();
assertNotNull(propertyMapValue);
Assert.assertEquals(2, propertyMapValue.size());
Assert.assertEquals("toto_value", propertyMapValue.get("toto"));
Assert.assertEquals("tata_value", propertyMapValue.get("tata"));
// custom property
String custom = "custom";
propertyDefinition = capaType.getProperties().get(custom);
assertEquals("alien.test.datatypes.Custom", propertyDefinition.getType());
assertNull(propertyDefinition.getDefault());
// custom_with_default property
String custom_with_default = "custom_with_default";
propertyDefinition = capaType.getProperties().get(custom_with_default);
assertNotNull(propertyDefinition.getDefault());
assertTrue(propertyDefinition.getDefault() instanceof ComplexPropertyValue);
propertyMapValue = ((ComplexPropertyValue) propertyDefinition.getDefault()).getValue();
assertNotNull(propertyMapValue);
assertEquals(2, propertyMapValue.size());
assertEquals("defaultName", propertyMapValue.get("name"));
Object list = propertyMapValue.get("groups");
assertTrue(list instanceof List);
assertEquals(2, ((List) list).size());
assertTrue(CollectionUtils.containsAll((List) list, Lists.newArrayList("alien", "fastconnect")));
// check the node template capability
//////////////
NodeTemplate nodeTemplate = archiveRoot.getTopology().getNodeTemplates().values().stream().findFirst().get();
Capability capability = nodeTemplate.getCapabilities().values().stream().findFirst().get();
assertNotNull(capability);
Assert.assertEquals(3, capability.getProperties().size());
// map property
AbstractPropertyValue propertyValue = capability.getProperties().get(map);
assertNotNull(propertyValue);
assertTrue(propertyValue instanceof ComplexPropertyValue);
propertyMapValue = ((ComplexPropertyValue) propertyValue).getValue();
assertNotNull(propertyMapValue);
Assert.assertEquals(2, propertyMapValue.size());
Assert.assertEquals("toto_value", propertyMapValue.get("toto"));
Assert.assertEquals("tata_value", propertyMapValue.get("tata"));
// custom property
propertyValue = capability.getProperties().get(custom);
assertNotNull(propertyValue);
assertTrue(propertyValue instanceof ComplexPropertyValue);
propertyMapValue = ((ComplexPropertyValue) propertyValue).getValue();
assertNotNull(propertyMapValue);
assertEquals(2, propertyMapValue.size());
assertEquals("manual", propertyMapValue.get("name"));
list = propertyMapValue.get("groups");
assertTrue(list instanceof List);
assertEquals(2, ((List) list).size());
assertTrue(CollectionUtils.containsAll((List) list, Lists.newArrayList("manual_alien", "manual_fastconnect")));
// custom_with_default property
propertyValue = capability.getProperties().get(custom_with_default);
assertNotNull(propertyValue);
assertTrue(propertyValue instanceof ComplexPropertyValue);
propertyMapValue = ((ComplexPropertyValue) propertyValue).getValue();
assertNotNull(propertyMapValue);
assertEquals(2, propertyMapValue.size());
assertEquals("defaultName", propertyMapValue.get("name"));
list = propertyMapValue.get("groups");
assertTrue(list instanceof List);
assertEquals(2, ((List) list).size());
assertTrue(CollectionUtils.containsAll((List) list, Lists.newArrayList("alien", "fastconnect")));
}
@Test
public void testInterfaceInputs() throws ParsingException {
Mockito.reset(csarRepositorySearchService);
Mockito.when(csarRepositorySearchService.getArchive("tosca-normative-types", "1.0.0-ALIEN14")).thenReturn(Mockito.mock(Csar.class));
Mockito.when(csarRepositorySearchService.getElementInDependencies(Mockito.eq(NodeType.class), Mockito.eq("tosca.nodes.Root"), Mockito.any(Set.class)))
.thenReturn(Mockito.mock(NodeType.class));
ParsingResult<ArchiveRoot> parsingResult = parser.parseFile(Paths.get(getRootDirectory(), "interface-inputs.yml"));
Assert.assertEquals(0, parsingResult.getContext().getParsingErrors().size());
Map<String, IValue> createInputs = parsingResult.getResult().getNodeTypes().get("org.alien4cloud.test.parsing.InterfaceInputsTestNode").getInterfaces()
.get(ToscaNodeLifecycleConstants.STANDARD).getOperations().get("create").getInputParameters();
assertNotNull(createInputs);
assertEquals(2, createInputs.size());
assertNotNull(createInputs.get("prop_definition"));
assertTrue(createInputs.get("prop_definition") instanceof PropertyDefinition);
assertNotNull(createInputs.get("prop_assignment"));
assertTrue(createInputs.get("prop_assignment") instanceof FunctionPropertyValue);
Map<String, IValue> startInputs = parsingResult.getResult().getNodeTypes().get("org.alien4cloud.test.parsing.InterfaceInputsTestNode").getInterfaces()
.get(ToscaNodeLifecycleConstants.STANDARD).getOperations().get("start").getInputParameters();
assertNotNull(startInputs);
assertEquals(3, startInputs.size());
assertNotNull(startInputs.get("prop_definition"));
assertTrue(startInputs.get("prop_definition") instanceof PropertyDefinition);
assertNotNull(startInputs.get("prop_assignment"));
assertTrue(startInputs.get("prop_assignment") instanceof PropertyValue);
assertNotNull(startInputs.get("new_input"));
assertTrue(startInputs.get("new_input") instanceof PropertyValue);
}
@Test
public void testDuplicateNodeTemplate() throws ParsingException {
Mockito.reset(csarRepositorySearchService);
Mockito.when(csarRepositorySearchService.getArchive("tosca-normative-types", "1.0.0-ALIEN14")).thenReturn(Mockito.mock(Csar.class));
Mockito.when(csarRepositorySearchService.getElementInDependencies(Mockito.eq(NodeType.class), Mockito.eq("tosca.nodes.Root"), Mockito.any(Set.class)))
.thenReturn(Mockito.mock(NodeType.class));
ParsingResult<ArchiveRoot> parsingResult = parser.parseFile(Paths.get(getRootDirectory(), "topo-duplicate-node-template.yml"));
Assert.assertEquals(0, parsingResult.getContext().getParsingErrors().size());
}
} | ALIEN-2376 : Services in Alien4Cloud should only be created from abstract types
Fix unit test
| alien4cloud-tosca/src/test/java/alien4cloud/tosca/parser/ToscaParserAlien140Test.java | ALIEN-2376 : Services in Alien4Cloud should only be created from abstract types Fix unit test | <ide><path>lien4cloud-tosca/src/test/java/alien4cloud/tosca/parser/ToscaParserAlien140Test.java
<ide> import java.util.Map;
<ide> import java.util.Set;
<ide>
<del>import alien4cloud.paas.plan.ToscaNodeLifecycleConstants;
<ide> import org.alien4cloud.tosca.model.Csar;
<ide> import org.alien4cloud.tosca.model.definitions.AbstractPropertyValue;
<ide> import org.alien4cloud.tosca.model.definitions.ComplexPropertyValue;
<ide>
<ide> import com.google.common.collect.Lists;
<ide>
<add>import alien4cloud.paas.plan.ToscaNodeLifecycleConstants;
<ide> import alien4cloud.tosca.model.ArchiveRoot;
<ide>
<ide> /**
<ide> public void testServiceRelationshipSubstitution() throws FileNotFoundException, ParsingException {
<ide> Mockito.reset(csarRepositorySearchService);
<ide> Mockito.when(csarRepositorySearchService.getArchive("tosca-normative-types", "1.0.0-ALIEN14")).thenReturn(Mockito.mock(Csar.class));
<del> Mockito.when(csarRepositorySearchService.getElementInDependencies(Mockito.eq(NodeType.class), Mockito.eq("tosca.nodes.Root"), Mockito.any(Set.class)))
<del> .thenReturn(Mockito.mock(NodeType.class));
<add> NodeType mockRoot = Mockito.mock(NodeType.class);
<add> Mockito.when(mockRoot.isAbstract()).thenReturn(true);
<add> Mockito.when(csarRepositorySearchService.getElementInDependencies(Mockito.eq(NodeType.class), Mockito.eq("tosca.nodes.Root"), Mockito.any(Set.class)))
<add> .thenReturn(mockRoot);
<ide> Mockito.when(csarRepositorySearchService.getElementInDependencies(Mockito.eq(CapabilityType.class), Mockito.eq("tosca.capabilities.Root"),
<ide> Mockito.any(Set.class))).thenReturn(Mockito.mock(CapabilityType.class));
<ide> Mockito.when(csarRepositorySearchService.getElementInDependencies(Mockito.eq(RelationshipType.class), Mockito.eq("tosca.relationships.Root"), |
|
Java | mit | d5eafc64294a9658ede629273424a5af9d571d3f | 0 | Benjozork/Onyx,Benjozork/Onyx,Benjozork/Onyx | package me.benjozork.onyx.internal;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Polygon;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.utils.JsonValue;
/**
* Used to convert rectangles to polygons and perform operations of rectangle on the polygon
* @author RishiRaj22
*/
public class PolygonHelper {
private static Polygon p1 = new Polygon();
private static Polygon p2 = new Polygon();
private static Polygon p3 = new Polygon();
/**
* WARNING: EXPENSIVE OPERATION USE ONLY IN INITIALISATION STEPS
* This method is used to create a new rectangular polygon
* @param rectangle The rectangle to be converted to polygon
* @return the created polygon
*/
public static Polygon getPolygon(Rectangle rectangle) {
return getPolygon(rectangle.getX(), rectangle.getY(), rectangle.getWidth(), rectangle.getHeight());
}
/**
* WARNING: EXPENSIVE OPERATION USE ONLY IN INITIALISATION STEPS
* This method is used to create a new rectangular polygon
* @param x the x coordinate of the polygon
* @param y the y coordinate of the polygon
* @param width the width of the polygon
* @param height the height of the polygon
* @return the created polygon
*/
public static Polygon getPolygon(float x, float y, float width, float height) {
float vals[] = {0, 0, width, 0, width, height, 0, height};
Polygon p = new Polygon();
p.setOrigin(width / 2, height / 2);
p.setScale(1, 1);
p.setVertices(vals);
p.setPosition(x, y);
return p;
}
/**
* Used to set the x co-ordinate of polygon
* @param p polygon whose x co-ordinate is to be set
* @param x new value for x co-ordinate of polygon
*/
public static void setX(Polygon p, float x) {
p.setPosition(x, p.getY());
}
/**
* Used to set the y co-ordinate of polygon
* @param p polygon whose y co-ordinate is to be set
* @param y new value for y co-ordinate of polygon
*/
public static void setY(Polygon p, float y) {
p.setPosition(p.getX(), y);
}
/**
* Used to set the width of a rectangular polygon
* @param p polygon whose width is to be set
* @param width new width for the polygon
*/
public static void setWidth(Polygon p, float width) {
float vals[] = p.getVertices();
vals[2] = vals[0] + width;
vals[4] = vals[0] + width;
p.setVertices(vals);
}
/**
* Used to set the height of a rectangular polygon
* @param p polygon whose width is to be set
* @param height new height for the polygonial
*/
public static void setHeight(Polygon p, float height) {
float vals[] = p.getVertices();
vals[5] = vals[1] + height;
vals[7] = vals[1] + height;
p.setVertices(vals);
}
/**
* Used to set the dimensions of the rectangular polygon
* @param p polygon whose dimensions are to be set
* @param width the width to be used
* @param height the height to be used
*/
public static void setDimensions(Polygon p, float width, float height) {
float vals[] = p.getVertices();
vals[5] = vals[1] + height;
vals[7] = vals[1] + height;
vals[2] = vals[0] + width;
vals[4] = vals[0] + width;
p.setVertices(vals);
}
/**
* Check the collsion of two polygons.
* Use this method instead of intersector as this uses the transformed vertices
* of the polygon to check for collision instead of directly using these vertices.
* @param pol1 first polygon used in the check
* @param pol2 second polygon used in the check
* @return whether the two collide
*/
public static boolean polygonCollide(Polygon pol1, Polygon pol2) {
p1.setVertices(pol1.getTransformedVertices());
p2.setVertices(pol2.getTransformedVertices());
return Intersector.intersectPolygons(p1, p2, p3);
}
/**
* WARNING: EXPENSIVE OPERATION USE ONLY IN INITIALISATION STEPS
* Get a polygon from a JSON Value(JSON array of JSON objects having x,y co-ordinates)
* @param value Array denoting the pol
* @param width
* @param height
* @return
*/
public static Polygon loadPolygon(JsonValue value, float width, float height) {
JsonValue.JsonIterator iter = value.iterator();
int len = 0, i = 0;
for (JsonValue val : iter) {
len += 2;
}
float[] vertices = new float[len];
for (JsonValue val : iter) {
vertices[i] = val.getFloat("x") * width;
vertices[i + 1] = val.getFloat("y") * height;
i += 2;
}
return new Polygon(vertices);
}
}
| core/src/me/benjozork/onyx/internal/PolygonHelper.java | package me.benjozork.onyx.internal;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Polygon;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.utils.JsonValue;
/**
* Used to convert rectangles to polygons and perform operations of rectangle on the polygon
* Created by Raj on 28-03-2017.
* @author @fixme add your name here
*/
public class PolygonHelper {
private static Polygon p1 = new Polygon();
private static Polygon p2 = new Polygon();
private static Polygon p3 = new Polygon();
/**
* WARNING: EXPENSIVE OPERATION USE ONLY IN INITIALISATION STEPS
* This method is used to create a new rectangular polygon
* @param rectangle The rectangle to be converted to polygon
* @return
*/
public static Polygon getPolygon(Rectangle rectangle) {
return getPolygon(rectangle.getX(), rectangle.getY(), rectangle.getWidth(), rectangle.getHeight());
}
/**
* WARNING: EXPENSIVE OPERATION USE ONLY IN INITIALISATION STEPS
* This method is used to create a new rectangular polygon
* @param x the x coordinate of the polygon
* @param y the y coordinate of the polygon
* @param width the width of the polygon
* @param height the height of the polygon
* @return
*/
public static Polygon getPolygon(float x, float y, float width, float height) {
float vals[] = {0, 0, width, 0, width, height, 0, height};
Polygon p = new Polygon();
p.setOrigin(width / 2, height / 2);
p.setScale(1, 1);
p.setVertices(vals);
p.setPosition(x, y);
return p;
}
/**
* Used to set the x co-ordinate of polygon
* @param p polygon whose x co-ordinate is to be set
* @param x new value for x co-ordinate of polygon
*/
public static void setX(Polygon p, float x) {
p.setPosition(x, p.getY());
}
/**
* Used to set the y co-ordinate of polygon
* @param p polygon whose y co-ordinate is to be set
* @param y new value for y co-ordinate of polygon
*/
public static void setY(Polygon p, float y) {
p.setPosition(p.getX(), y);
}
/**
* Used to set the width of a rectangular polygon
* @param p polygon whose width is to be set
* @param width new width for the polygon
*/
public static void setWidth(Polygon p, float width) {
float vals[] = p.getVertices();
vals[2] = vals[0] + width;
vals[4] = vals[0] + width;
p.setVertices(vals);
}
/**
* Used to set the height of a rectangular polygon
* @param p polygon whose width is to be set
* @param height new height for the polygonial
*/
public static void setHeight(Polygon p, float height) {
float vals[] = p.getVertices();
vals[5] = vals[1] + height;
vals[7] = vals[1] + height;
p.setVertices(vals);
}
/**
* Used to set the dimensions of the rectangular polygon
* @param p polygon whose dimensions are to be set
* @param width new width for the polygonial
* @param height new height for the polygonial
*/
public static void setDimensions(Polygon p, float width, float height) {
float vals[] = p.getVertices();
vals[5] = vals[1] + height;
vals[7] = vals[1] + height;
vals[2] = vals[0] + width;
vals[4] = vals[0] + width;
p.setVertices(vals);
}
/**
* Check the collsion of two polygons.
* Use this method instead of intersector as this uses the transformed vertices
* of the polygon to check for collision instead of directly using these vertices.
* @param pol1 First polygon to check for collsion
* @param pol2 Second polygon to check for collison
* @return
*/
public static boolean polygonCollide(Polygon pol1, Polygon pol2) {
p1.setVertices(pol1.getTransformedVertices());
p2.setVertices(pol2.getTransformedVertices());
return Intersector.intersectPolygons(p1, p2, p3);
}
/**
* WARNING: EXPENSIVE OPERATION USE ONLY IN INITIALISATION STEPS
* Get a polygon from a JSON Value(JSON array of JSON objects having x,y co-ordinates)
* @param value Array denoting the pol
* @param width
* @param height
* @return
*/
public static Polygon loadPolygon(JsonValue value, float width, float height) {
JsonValue.JsonIterator iter = value.iterator();
int len = 0, i = 0;
for (JsonValue val : iter) {
len += 2;
}
float[] vertices = new float[len];
for (JsonValue val : iter) {
vertices[i] = val.getFloat("x") * width;
vertices[i + 1] = val.getFloat("y") * height;
i += 2;
}
return new Polygon(vertices);
}
}
| fixed PolygonHelper docs
| core/src/me/benjozork/onyx/internal/PolygonHelper.java | fixed PolygonHelper docs | <ide><path>ore/src/me/benjozork/onyx/internal/PolygonHelper.java
<ide>
<ide> /**
<ide> * Used to convert rectangles to polygons and perform operations of rectangle on the polygon
<del> * Created by Raj on 28-03-2017.
<del> * @author @fixme add your name here
<add> * @author RishiRaj22
<ide> */
<del>
<ide> public class PolygonHelper {
<ide>
<ide> private static Polygon p1 = new Polygon();
<ide> * WARNING: EXPENSIVE OPERATION USE ONLY IN INITIALISATION STEPS
<ide> * This method is used to create a new rectangular polygon
<ide> * @param rectangle The rectangle to be converted to polygon
<del> * @return
<add> * @return the created polygon
<ide> */
<ide> public static Polygon getPolygon(Rectangle rectangle) {
<ide> return getPolygon(rectangle.getX(), rectangle.getY(), rectangle.getWidth(), rectangle.getHeight());
<ide> * @param y the y coordinate of the polygon
<ide> * @param width the width of the polygon
<ide> * @param height the height of the polygon
<del> * @return
<add> * @return the created polygon
<ide> */
<ide> public static Polygon getPolygon(float x, float y, float width, float height) {
<ide> float vals[] = {0, 0, width, 0, width, height, 0, height};
<ide> /**
<ide> * Used to set the dimensions of the rectangular polygon
<ide> * @param p polygon whose dimensions are to be set
<del> * @param width new width for the polygonial
<del> * @param height new height for the polygonial
<add> * @param width the width to be used
<add> * @param height the height to be used
<ide> */
<ide> public static void setDimensions(Polygon p, float width, float height) {
<ide> float vals[] = p.getVertices();
<ide> * Check the collsion of two polygons.
<ide> * Use this method instead of intersector as this uses the transformed vertices
<ide> * of the polygon to check for collision instead of directly using these vertices.
<del> * @param pol1 First polygon to check for collsion
<del> * @param pol2 Second polygon to check for collison
<del> * @return
<add> * @param pol1 first polygon used in the check
<add> * @param pol2 second polygon used in the check
<add> * @return whether the two collide
<ide> */
<ide> public static boolean polygonCollide(Polygon pol1, Polygon pol2) {
<ide> p1.setVertices(pol1.getTransformedVertices()); |
|
Java | bsd-3-clause | 5d9f6eb0a6f032bedcef6bdbc701987b795a547e | 0 | NCIP/cananolab,NCIP/cananolab,NCIP/cananolab | package gov.nih.nci.calab.ui.administration;
/**
* This class prepares data to prepopulate the view create aliquot.
*
* @author pansu
*/
/* CVS $Id: PreCreateAliquotAction.java,v 1.6 2006-03-20 21:57:54 pansu Exp $ */
import gov.nih.nci.calab.dto.administration.AliquotBean;
import gov.nih.nci.calab.dto.administration.ContainerInfoBean;
import gov.nih.nci.calab.service.administration.ManageAliquotService;
import gov.nih.nci.calab.service.common.LookupService;
import gov.nih.nci.calab.ui.core.AbstractBaseAction;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorActionForm;
public class PreCreateAliquotAction extends AbstractBaseAction {
private static Logger logger = Logger.getLogger(PreCreateAliquotAction.class);
public ActionForward executeTask(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = null;
HttpSession session = request.getSession();
try {
// TODO fill in details for sample information */
DynaValidatorActionForm theForm = (DynaValidatorActionForm) form;
// retrieve from sesssion first if available assuming these values
// are not likely to change within the same session. If changed, the
// session should be updated.
LookupService lookupService = new LookupService();
ManageAliquotService manageAliquotService = new ManageAliquotService();
if (session.getAttribute("allSampleIds") == null) {
List sampleIds = lookupService.getAllSampleIds();
session.setAttribute("allSampleIds", sampleIds);
}
if (session.getAttribute("allLotIds") == null) {
List lotIds = lookupService.getAllLotIds();
session.setAttribute("allLotIds", lotIds);
}
if (session.getAttribute("allAliquotIds") == null) {
List aliquotIds = lookupService.getAliquots();
session.setAttribute("allAliquotIds", aliquotIds);
}
if (session.getAttribute("aliquotContainerInfo") == null) {
ContainerInfoBean containerInfo = lookupService
.getAliquotContainerInfo();
session.setAttribute("aliquotContainerInfo", containerInfo);
}
if (session.getAttribute("aliquotCreateMethods") == null) {
List methods = manageAliquotService.getAliquotCreateMethods();
session.setAttribute("aliquotCreateMethods", methods);
}
String sampleId = (String) theForm.get("sampleId");
String lotId = (String) theForm.get("lotId");
String parentAliquotId = (String) theForm.get("parentAliquotId");
String numberOfAliquots = (String) theForm.get("numberOfAliquots");
int numAliquots;
if (numberOfAliquots.length() == 0) {
numAliquots = 0;
} else {
numAliquots = Integer.parseInt(numberOfAliquots);
}
AliquotBean template = (AliquotBean) theForm.get("template");
// calculate number of rows in the matrix
if (numAliquots > 0) {
int colNum = manageAliquotService
.getDefaultAliquotMatrixColumnNumber();
int rowNum = (int) Math.ceil((float) numAliquots / colNum);
// calculate the first aliquot Id to use
int firstAliquotNum = manageAliquotService.getFirstAliquotNum(
sampleId, lotId, parentAliquotId);
String aliquotPrefix = manageAliquotService.getAliquotPrefix(
sampleId, lotId, parentAliquotId);
// create a 2-D matrix for aliquot
List<AliquotBean[]> aliquotMatrix = createAliquotMatrix(colNum,
rowNum, numAliquots, aliquotPrefix, firstAliquotNum, template);
session.setAttribute("aliquotMatrix", aliquotMatrix);
}
else {
session.removeAttribute("aliquotMatrix");
}
forward = mapping.findForward("success");
} catch (Exception e) {
ActionMessages errors=new ActionMessages();
ActionMessage error=new ActionMessage("error.preCreateAliquot");
errors.add("error", error);
saveMessages(request, errors);
logger.error("Caught exception loading creating aliquot page", e);
forward = mapping.getInputForward();
}
return forward;
}
public boolean loginRequired() {
// temporarily set to false until login module is working
return false;
// return true;
}
/**
*
* @return a 2-D matrix of aliquots
*/
private List<AliquotBean[]> createAliquotMatrix(int colNum, int rowNum,
int numAliquots, String aliquotPrefix, int firstAliquotId, AliquotBean template) {
List<AliquotBean[]> aliquotMatrix = new ArrayList<AliquotBean[]>();
int aliquotId = firstAliquotId;
for (int i = 0; i < rowNum; i++) {
// calculate number of columsn per row
int cols = colNum;
if (numAliquots % colNum < colNum && numAliquots % colNum > 0
&& i == rowNum - 1) {
cols = numAliquots % colNum;
}
AliquotBean[] aliquotRow = new AliquotBean[colNum];
for (int j = 0; j < cols; j++) {
AliquotBean aliquot = new AliquotBean(aliquotPrefix+aliquotId, template
.getContainer(), template.getHowCreated());
aliquotRow[j] = aliquot;
aliquotId++;
}
aliquotMatrix.add(aliquotRow);
}
return aliquotMatrix;
}
}
| src/gov/nih/nci/calab/ui/administration/PreCreateAliquotAction.java | package gov.nih.nci.calab.ui.administration;
/**
* This class prepares data to prepopulate the view create aliquot.
*
* @author pansu
*/
/* CVS $Id: PreCreateAliquotAction.java,v 1.5 2006-03-20 21:52:26 pansu Exp $ */
import gov.nih.nci.calab.dto.administration.AliquotBean;
import gov.nih.nci.calab.dto.administration.ContainerInfoBean;
import gov.nih.nci.calab.service.administration.ManageAliquotService;
import gov.nih.nci.calab.service.common.LookupService;
import gov.nih.nci.calab.ui.core.AbstractBaseAction;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorActionForm;
public class PreCreateAliquotAction extends AbstractBaseAction {
private static Logger logger = Logger.getLogger(PreCreateAliquotAction.class);
public ActionForward executeTask(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = null;
HttpSession session = request.getSession();
try {
// TODO fill in details for sample information */
DynaValidatorActionForm theForm = (DynaValidatorActionForm) form;
// retrieve from sesssion first if available assuming these values
// are not likely to change within the same session. If changed, the
// session should be updated.
LookupService lookupService = new LookupService();
ManageAliquotService manageAliquotService = new ManageAliquotService();
if (session.getAttribute("allSampleIds") == null) {
List sampleIds = lookupService.getAllSampleIds();
session.setAttribute("allSampleIds", sampleIds);
}
if (session.getAttribute("allLotIds") == null) {
List lotIds = lookupService.getAllLotIds();
session.setAttribute("allLotIds", lotIds);
}
if (session.getAttribute("allAliquotIds") == null) {
List aliquotIds = lookupService.getAliquots();
session.setAttribute("allAliquotIds", aliquotIds);
}
if (session.getAttribute("aliquotContainerInfo") == null) {
ContainerInfoBean containerInfo = lookupService
.getAliquotContainerInfo();
session.setAttribute("aliquotContainerInfo", containerInfo);
}
if (session.getAttribute("aliquotCreateMethods") == null) {
List methods = manageAliquotService.getAliquotCreateMethods();
session.setAttribute("aliquotCreateMethods", methods);
}
String sampleId = (String) theForm.get("sampleId");
String lotId = (String) theForm.get("lotId");
String parentAliquotId = (String) theForm.get("parentAliquotId");
String numberOfAliquots = (String) theForm.get("numberOfAliquots");
int numAliquots;
if (numberOfAliquots.length() == 0) {
numAliquots = 0;
} else {
numAliquots = Integer.parseInt(numberOfAliquots);
}
AliquotBean template = (AliquotBean) theForm.get("template");
// calculate number of rows in the matrix
if (numAliquots > 0) {
int colNum = manageAliquotService
.getDefaultAliquotMatrixColumnNumber();
int rowNum = (int) Math.ceil((float) numAliquots / colNum);
// calculate the first aliquot Id to use
int firstAliquotNum = manageAliquotService.getFirstAliquotNum(
sampleId, lotId, parentAliquotId);
String aliquotPrefix = manageAliquotService.getAliquotPrefix(
sampleId, lotId, parentAliquotId);
// create a 2-D matrix for aliquot
List<AliquotBean[]> aliquotMatrix = createAliquotMatrix(colNum,
rowNum, numAliquots, aliquotPrefix, firstAliquotNum, template);
session.setAttribute("aliquotMatrix", aliquotMatrix);
}
else {
session.removeAttribute("aliquotMatrix");
}
// TODO fill in details to save the data through some service
forward = mapping.findForward("success");
} catch (Exception e) {
ActionMessages errors=new ActionMessages();
ActionMessage error=new ActionMessage("error.preCreateAliquot");
errors.add("error", error);
saveMessages(request, errors);
logger.error("Caught exception loading creating aliquot page", e);
forward = mapping.getInputForward();
}
return forward;
}
public boolean loginRequired() {
// temporarily set to false until login module is working
return false;
// return true;
}
/**
*
* @return a 2-D matrix of aliquots
*/
private List<AliquotBean[]> createAliquotMatrix(int colNum, int rowNum,
int numAliquots, String aliquotPrefix, int firstAliquotId, AliquotBean template) {
List<AliquotBean[]> aliquotMatrix = new ArrayList<AliquotBean[]>();
int aliquotId = firstAliquotId;
for (int i = 0; i < rowNum; i++) {
// calculate number of columsn per row
int cols = colNum;
if (numAliquots % colNum < colNum && numAliquots % colNum > 0
&& i == rowNum - 1) {
cols = numAliquots % colNum;
}
AliquotBean[] aliquotRow = new AliquotBean[colNum];
for (int j = 0; j < cols; j++) {
AliquotBean aliquot = new AliquotBean(aliquotPrefix+aliquotId, template
.getContainer(), template.getHowCreated());
aliquotRow[j] = aliquot;
aliquotId++;
}
aliquotMatrix.add(aliquotRow);
}
return aliquotMatrix;
}
}
| removed an TODO
SVN-Revision: 290
| src/gov/nih/nci/calab/ui/administration/PreCreateAliquotAction.java | removed an TODO | <ide><path>rc/gov/nih/nci/calab/ui/administration/PreCreateAliquotAction.java
<ide> * @author pansu
<ide> */
<ide>
<del>/* CVS $Id: PreCreateAliquotAction.java,v 1.5 2006-03-20 21:52:26 pansu Exp $ */
<add>/* CVS $Id: PreCreateAliquotAction.java,v 1.6 2006-03-20 21:57:54 pansu Exp $ */
<ide>
<ide> import gov.nih.nci.calab.dto.administration.AliquotBean;
<ide> import gov.nih.nci.calab.dto.administration.ContainerInfoBean;
<ide> else {
<ide> session.removeAttribute("aliquotMatrix");
<ide> }
<del> // TODO fill in details to save the data through some service
<ide> forward = mapping.findForward("success");
<ide> } catch (Exception e) {
<ide> ActionMessages errors=new ActionMessages(); |
|
JavaScript | mit | 71b17a42532333698672d933354dad332de7be5f | 0 | Kait-tt/pakumogu,Kait-tt/pakumogu | var mapImg = '/img/map64.png';
var charImg = '/img/chara64.png';
var mySpeed = 8;
var SHEEP_SPEED = 16;
var WOLF_SPEED = 12;
var pixel = 64;
var DIRS = ['up', 'right', 'down', 'left'];
var DX = [0, 1, 0, -1];
var DY = [-1, 0, 1, 0];
function initGame(userObj,mapObj) {
enchant();
var game = new Core(mapObj.width * pixel, mapObj.height * pixel); //game dimension
game.fps = 16;
game.preload(mapImg, charImg);
game.onload = function () {
var map = initDynamicMap(game,mapObj);
game.rootScene.addChild(map);
var character = {};
for(var i=0;i<userObj.length;i++){
var objId = userObj[i].id;
if(myId == objId){
//set speed every move
mySpeed = userObj[i].isEnemy ? WOLF_SPEED : SHEEP_SPEED;
}
character[objId] = initPlayer(game,map,socket,userObj[i]);
if(myId == objId) {
initPlayerMove(game, map, socket, character[objId]);
}
// Add elements to scene.
game.rootScene.addChild(character[objId]);
}
console.log(character);
socket.on('movePlayer', (req) => {
const {x, y} = req.player.coordinate;
var objId = req.player.id;
character[objId].x = x;
character[objId].y = y;
});
};
game.start();
}
function initPlayer(game,map,socket,userObj){
// Player for now will be a 36x36.
var player = new Sprite(pixel, pixel);
player.image = game.assets[charImg];
//starting point
player.x = userObj.coordinate.x * pixel;
player.y = userObj.coordinate.y * pixel;
//if enemy = brown
if(userObj.isEnemy){
player.frame = [1, 1, 2, 2]; //white
}else{
player.frame = [6, 6, 7, 7]; //brown
}
return player;
}
function initPlayerMove(game, map, socket, player) {
// Let player move within bounds.
player.addEventListener(Event.ENTER_FRAME, function () {
// First move the player. If the player's new location has resulted
// in the player being in a "hit" zone, then back the player up to
// its original location. Tweak "hits" by "offset" pixels.
let {x, y} = player;
DIRS.forEach((dir, i) => {
if (!game.input[dir]) { return; }
x += DX[i] * mySpeed;
y += DY[i] * mySpeed;
});
if (!myHitTest(map, x, y)) {
socket.movePlayer({x, y});
}
});
}
function myHitTest (map, x, y) {
return map.hitTest(x, y) ||
map.hitTest(x + pixel - 1, y) ||
map.hitTest(x, y + pixel - 1) ||
map.hitTest(x + pixel - 1, y + pixel - 1);
}
| public/js/proto_02.js | /**
* http://usejsdoc.org/
*/
var mapImg = '/img/map64.png';
var charImg = '/img/chara64.png';
var mySpeed = 8;
var SHEEP_SPEED = 16;
var WOLF_SPEED = 12;
var pixel = 64;
function initGame(userObj,mapObj) {
enchant();
var game = new Core(mapObj.width * pixel, mapObj.height * pixel); //game dimension
game.fps = 16;
game.preload(mapImg, charImg);
game.onload = function () {
var map = initDynamicMap(game,mapObj);
game.rootScene.addChild(map);
var character = {};
for(var i=0;i<userObj.length;i++){
var objId = userObj[i].id;
if(myId == objId){
//set speed every move
if(userObj[i].isEnemy){
mySpeed = WOLF_SPEED;
}else{
mySpeed = SHEEP_SPEED;
}
}
character[objId] = initPlayer(game,map,socket,userObj[i]);
// Add elements to scene.
game.rootScene.addChild(character[objId]);
}
console.log(character);
socket.on('movePlayer', (req) => {
const {x, y} = req.player.coordinate;
var objId = req.player.id;
character[objId].x = x;
character[objId].y = y;
});
};
game.start();
}
function initPlayer(game,map,socket,userObj){
// Player for now will be a 36x36.
var player = new Sprite(pixel, pixel);
player.image = game.assets[charImg];
//starting point
player.x = userObj.coordinate.x * pixel;
player.y = userObj.coordinate.y * pixel;
//if enemy = brown
if(userObj.isEnemy){
player.frame = [1, 1, 2, 2]; //white
}else{
player.frame = [6, 6, 7, 7]; //brown
}
var x = player.x;
var y = player.y;
// Let player move within bounds.
player.addEventListener(Event.ENTER_FRAME, function () {
// First move the player. If the player's new location has resulted
// in the player being in a "hit" zone, then back the player up to
// its original location. Tweak "hits" by "offset" pixels.
if (game.input.up) { // Move up
y -= mySpeed;
if (myHitTest(map, x, y)) {
y += mySpeed;
}
socket.movePlayer({x, y});
}
else if (game.input.down) { // Move down
y += mySpeed;
if (myHitTest(map, x, y)) {
y -= mySpeed;
}
socket.movePlayer({x, y});
}
else if (game.input.left) { // Move left
x -= mySpeed;
if (myHitTest(map, x, y)) {
x += mySpeed;
}
socket.movePlayer({x, y});
}
else if (game.input.right) { // Move right
x += mySpeed;
if (myHitTest(map, x, y)) {
x -= mySpeed;
}
socket.movePlayer({x, y});
}
});
return player;
}
function myHitTest (map, x, y) {
return map.hitTest(x, y) ||
map.hitTest(x + pixel - 1, y) ||
map.hitTest(x, y + pixel - 1) ||
map.hitTest(x + pixel - 1, y + pixel - 1);
}
| refactoring player move code
| public/js/proto_02.js | refactoring player move code | <ide><path>ublic/js/proto_02.js
<del>/**
<del> * http://usejsdoc.org/
<del> */
<del>
<ide> var mapImg = '/img/map64.png';
<ide> var charImg = '/img/chara64.png';
<ide> var mySpeed = 8;
<ide> var SHEEP_SPEED = 16;
<ide> var WOLF_SPEED = 12;
<ide> var pixel = 64;
<add>var DIRS = ['up', 'right', 'down', 'left'];
<add>var DX = [0, 1, 0, -1];
<add>var DY = [-1, 0, 1, 0];
<ide>
<ide> function initGame(userObj,mapObj) {
<ide>
<ide> var objId = userObj[i].id;
<ide> if(myId == objId){
<ide> //set speed every move
<del> if(userObj[i].isEnemy){
<del> mySpeed = WOLF_SPEED;
<del> }else{
<del> mySpeed = SHEEP_SPEED;
<del> }
<add> mySpeed = userObj[i].isEnemy ? WOLF_SPEED : SHEEP_SPEED;
<ide> }
<ide> character[objId] = initPlayer(game,map,socket,userObj[i]);
<add> if(myId == objId) {
<add> initPlayerMove(game, map, socket, character[objId]);
<add> }
<ide> // Add elements to scene.
<ide> game.rootScene.addChild(character[objId]);
<ide> }
<ide> }else{
<ide> player.frame = [6, 6, 7, 7]; //brown
<ide> }
<add>
<add> return player;
<add>}
<ide>
<del> var x = player.x;
<del> var y = player.y;
<del>
<add>function initPlayerMove(game, map, socket, player) {
<ide> // Let player move within bounds.
<ide> player.addEventListener(Event.ENTER_FRAME, function () {
<del> // First move the player. If the player's new location has resulted
<add> // First move the player. If the player's new location has resulted
<ide> // in the player being in a "hit" zone, then back the player up to
<ide> // its original location. Tweak "hits" by "offset" pixels.
<del> if (game.input.up) { // Move up
<del> y -= mySpeed;
<del> if (myHitTest(map, x, y)) {
<del> y += mySpeed;
<del> }
<del> socket.movePlayer({x, y});
<del> }
<del> else if (game.input.down) { // Move down
<del> y += mySpeed;
<del> if (myHitTest(map, x, y)) {
<del> y -= mySpeed;
<del> }
<del> socket.movePlayer({x, y});
<del> }
<del> else if (game.input.left) { // Move left
<del> x -= mySpeed;
<del> if (myHitTest(map, x, y)) {
<del> x += mySpeed;
<del> }
<del> socket.movePlayer({x, y});
<del> }
<del> else if (game.input.right) { // Move right
<del> x += mySpeed;
<del> if (myHitTest(map, x, y)) {
<del> x -= mySpeed;
<del> }
<add>
<add> let {x, y} = player;
<add> DIRS.forEach((dir, i) => {
<add> if (!game.input[dir]) { return; }
<add> x += DX[i] * mySpeed;
<add> y += DY[i] * mySpeed;
<add> });
<add>
<add> if (!myHitTest(map, x, y)) {
<ide> socket.movePlayer({x, y});
<ide> }
<ide> });
<del>
<del> return player;
<ide> }
<ide>
<ide> function myHitTest (map, x, y) { |
|
Java | apache-2.0 | a75a63851b286486b0d9036d3f57076f473e34f8 | 0 | da1z/intellij-community,signed/intellij-community,apixandru/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,allotria/intellij-community,da1z/intellij-community,da1z/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,xfournet/intellij-community,ibinti/intellij-community,asedunov/intellij-community,signed/intellij-community,youdonghai/intellij-community,da1z/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,apixandru/intellij-community,xfournet/intellij-community,da1z/intellij-community,suncycheng/intellij-community,allotria/intellij-community,apixandru/intellij-community,ibinti/intellij-community,signed/intellij-community,FHannes/intellij-community,da1z/intellij-community,signed/intellij-community,allotria/intellij-community,semonte/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,semonte/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,asedunov/intellij-community,xfournet/intellij-community,semonte/intellij-community,xfournet/intellij-community,apixandru/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,signed/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,signed/intellij-community,vvv1559/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,ibinti/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,semonte/intellij-community,signed/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,signed/intellij-community,da1z/intellij-community,da1z/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,semonte/intellij-community,semonte/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,da1z/intellij-community,asedunov/intellij-community,semonte/intellij-community,apixandru/intellij-community,semonte/intellij-community,asedunov/intellij-community,signed/intellij-community,apixandru/intellij-community,allotria/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,allotria/intellij-community,vvv1559/intellij-community,allotria/intellij-community,xfournet/intellij-community,ibinti/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ibinti/intellij-community,FHannes/intellij-community,signed/intellij-community,mglukhikh/intellij-community,signed/intellij-community,signed/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,allotria/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,asedunov/intellij-community,semonte/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,FHannes/intellij-community,ibinti/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,semonte/intellij-community,FHannes/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,signed/intellij-community,allotria/intellij-community,allotria/intellij-community,youdonghai/intellij-community,da1z/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,semonte/intellij-community | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.extensions;
import com.intellij.util.xmlb.annotations.Attribute;
import org.jetbrains.annotations.NotNull;
import org.picocontainer.PicoContainer;
/**
* @author yole
*/
public class CustomLoadingExtensionPointBean extends AbstractExtensionPointBean {
@Attribute("factoryClass")
public String factoryClass;
@Attribute("factoryArgument")
public String factoryArgument;
@NotNull
protected Object instantiateExtension(String implementationClass, @NotNull PicoContainer picoContainer) throws ClassNotFoundException {
if (factoryClass != null) {
ExtensionFactory factory = instantiate(factoryClass, picoContainer);
return factory.createInstance(factoryArgument, implementationClass);
}
else {
if (implementationClass == null) {
throw new RuntimeException("implementation class is not specified for unknown language extension point, " +
"plugin id: " +
(myPluginDescriptor == null ? "<not available>" : myPluginDescriptor.getPluginId()) + ". " +
"Check if 'implementationClass' attribute is specified");
}
//noinspection unchecked
return instantiate(findClass(implementationClass), picoContainer, true);
}
}
}
| platform/extensions/src/com/intellij/openapi/extensions/CustomLoadingExtensionPointBean.java | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.extensions;
import com.intellij.util.xmlb.annotations.Attribute;
import org.jetbrains.annotations.NotNull;
import org.picocontainer.PicoContainer;
/**
* @author yole
*/
public class CustomLoadingExtensionPointBean extends AbstractExtensionPointBean {
@Attribute("factoryClass")
public String factoryClass;
@Attribute("factoryArgument")
public String factoryArgument;
@NotNull
protected Object instantiateExtension(String implementationClass, @NotNull PicoContainer picoContainer) throws ClassNotFoundException {
if (factoryClass != null) {
ExtensionFactory factory = instantiate(factoryClass, picoContainer);
return factory.createInstance(factoryArgument, implementationClass);
}
else {
if (implementationClass == null) {
throw new RuntimeException("implementation class is not specified for unknown language extension point, " +
"plugin id: " +
(myPluginDescriptor == null ? "<not available>" : myPluginDescriptor.getPluginId()) + ". " +
"Check if 'implementationClass' attribute is specified");
}
//noinspection unchecked
return instantiate(implementationClass, picoContainer);
}
}
}
| allow private classes
| platform/extensions/src/com/intellij/openapi/extensions/CustomLoadingExtensionPointBean.java | allow private classes | <ide><path>latform/extensions/src/com/intellij/openapi/extensions/CustomLoadingExtensionPointBean.java
<ide> "Check if 'implementationClass' attribute is specified");
<ide> }
<ide> //noinspection unchecked
<del> return instantiate(implementationClass, picoContainer);
<add> return instantiate(findClass(implementationClass), picoContainer, true);
<ide> }
<ide> }
<ide> } |
|
JavaScript | mit | 6a1559b33e2121a4a893abe2ded0386f3946253b | 0 | LivelyKernel/lively4-core,LivelyKernel/lively4-core | 'use strict';
import './patches.js' // monkey patch the meta sytem....
import * as jquery from '../external/jquery.js';
import * as _ from '../external/underscore.js';
import * as scripts from './script-manager.js';
import * as messaging from './messaging.js';
import * as preferences from './preferences.js';
import * as persistence from './persistence.js';
import html from './html.js';
import files from './files.js';
import paths from './paths.js';
import inspector from './inspector.js';
import contextmenu from './contextmenu.js';
import keys from './keys.js';
import components from './morphic/component-loader.js';
import authGithub from './auth-github.js'
import authDropbox from './auth-dropbox.js'
import authGoogledrive from './auth-googledrive.js'
import expose from './expose.js';
/* expose external modules */
import color from '../external/tinycolor.js';
import focalStorage from '../external/focalStorage.js';
import * as kernel from 'kernel'
let $ = window.$,
babel = window.babel; // known global variables.
import {pt} from 'lively.graphics';
// a) Special shorthands for interactive development
// b) this is the only reasonable way to use modules in template scripts, due to no shared lexical scope #TODO
var exportmodules = [
"scripts",
"messaging",
"preferences",
"persistence",
"files",
"keys",
"paths",
"html",
"components",
"inspector",
"color",
"focalStorage",
"authGithub",
"authDropbox",
"authGoogledrive"
];
// #LiveProgramming #Syntax #ES6Modules #Experiment #Jens
// By structuring our modules differently, we still can act as es6 module to the outside but develop at runtime
// #IDEA: I refactored from "static module and function style" to "dynamic object" style
export default class Lively {
static import(moduleName, path, forceLoad) {
if (lively.modules && path) {
lively.modules.module("" + path).reload({reloadDeps: true, resetEnv: false})
}
if (!path) path = this.defaultPath(moduleName)
if (!path) throw Error("Could not imoport " + moduleName + ", not path specified!")
if (this[moduleName] && !forceLoad)
return new Promise((resolve) => { resolve(this[moduleName])})
if (forceLoad) {
path += "?" + Date.now()
}
return System.import(path).then( (module, err) => {
if (err) {
lively.notify("Could not load module " + moduleName, err);
} else {
console.log("lively: load "+ moduleName)
if (moduleName == "lively") {
this.notify("migrate lively.js")
var oldLively = window.lively;
window.lively =module.default || module
this["previous"] = oldLively
this.components = oldLively.components // components have important state
} else {
this[moduleName] = module.default || module
}
if (lively.components && this[moduleName]) {
lively.components.updatePrototype(this[moduleName].prototype);
}
return module.default || module
}
})
}
static async reloadModule(path) {
path = "" + path;
var module = lively.modules.module(path)
if (!module.isLoaded()) {
console.log("cannot reload module " + path + " because it is not loaded")
return;
}
console.log("reload module: " + path)
return module.reload({reloadDeps: true, resetEnv: false})
.then( () => System.import(path))
.then( mod => {
var moduleName = path.replace(/[^\/]*/,"")
var defaultClass = mod.default
if (lively.components && defaultClass) {
console.log("update template prototype: " + moduleName)
lively.components.updatePrototype(defaultClass.prototype);
};
if (moduleName == "lively") {
this.notify("migrate lively.js")
var oldLively = window.lively;
window.lively =module.default || module
this["previous"] = oldLively
this.components = oldLively.components // components have important state
}
return mod;
})
}
static loadJavaScriptThroughDOM(name, src, force) {
return new Promise((resolve) => {
var scriptNode = document.querySelector("#"+name);
if (scriptNode) {
scriptNode.remove();
}
var script = document.createElement("script");
script.id=name;
script.charset="utf-8"
script.type="text/javascript";
if (force) {
src += + "?" + Date.now();
}
script.src= src;
script.onload = function() {
resolve();
};
document.head.appendChild(script);
})
}
static loadCSSThroughDOM(name, href, force) {
return new Promise((resolve) => {
var linkNode = document.querySelector("#"+name);
if (linkNode) {
linkNode.remove();
}
var link = document.createElement("link");
link.rel="stylesheet"
link.id=name;
link.charset="utf-8"
link.type="text/css";
if (force) {
href += + "?" + Date.now();
}
link.href= href;
link.onload = function() {
resolve();
};
document.head.appendChild(link);
})
}
static fillTemplateStyles(root) {
// there seems to be no <link ..> tag allowed to reference css inside of templates #Jens
var promises = []
_.each(root.querySelectorAll("style"), ea => {
var src = ea.getAttribute("data-src")
if (src) {
promises.push(fetch(lively4url + src).then(r => r.text()).then(css => {
ea.innerHTML = css
}))
}
})
return Promise.all(promises)
}
static defaultPath(moduleName) {
return ({
math: kernel.realpath("/src/external/math.js"),
typo: kernel.realpath("/src/external/typo.js"),
contextmenu: kernel.realpath('/src/client/contextmenu.js'),
customize: kernel.realpath('/src/client/customize.js'),
selecting: kernel.realpath('/src/client/morphic/selecting.js'),
expose: kernel.realpath('/src/client/expose.js')
})[moduleName]
}
static showError(error) {
this.handleError(error)
}
static handleError(error) {
lively.LastError = error
if (!error) return // hmm... this is currious...
lively.notify("Error: ", error.message, 10, () =>
lively.openWorkspace("Error:" + error.message + "\nLine:" + error.lineno + " Col: " + error.colno+"\nSource:" + error.source + "\nError:" + error.stack),
"red")
}
static loaded() {
// #Refactor with #ContextJS
// guard againsst wrapping twice and ending in endless recursion
// if (!console.log.originalFunction) {
// var nativeLog = console.log;
// console.log = function() {
// nativeLog.apply(console, arguments);
// lively.log.apply(undefined, arguments);
// };
// console.log.originalFunction = nativeLog; // #TODO use generic Wrapper mechanism here
// }
// if (!console.error.originalFunction) {
// var nativeError = console.error;
// console.error = function() {
// nativeError.apply(console, arguments);
// lively.log.apply(undefined, arguments);
// };
// console.error.originalFunction = nativeError; // #TODO use generic Wrapper mechanism here
// }
// General Error Handling
if (window.onerror === null) {
window.onerror = function(message, source, lineno, colno, error) {
lively.handleError(error)
}
}
// do it just once
if (!window.unhandledRejectionEventLister) {
window.unhandledRejectionEventLister = function(evt) {lively.handleError(evt.reason)} ;
window.addEventListener('unhandledrejection', unhandledRejectionEventLister);
}
exportmodules.forEach(name => lively[name] = eval(name)); // oh... this seems uglier than expected
// for anonymous lively.modules workspaces
if (lively.modules && !lively.modules.isHookInstalled("fetch", "workspaceFetch")) {
lively.modules.installHook("fetch", function workspaceFetch(proceed, load) {
if (load.address.match("workspace://")) return Promise.resolve("")
return proceed(load)
})
}
// for container content... But this will lead to conflicts with lively4chrome ?? #Jens
lively.loadCSSThroughDOM("livelystyle", lively4url + "/templates/lively4.css")
}
static array(anyList){
return Array.prototype.slice.call(anyList);
}
static openWorkspace(string, pos) {
var name = "juicy-ace-editor";
var comp = document.createElement(name);
return lively.components.openInWindow(comp).then((container) => {
pos = pos || lively.pt(100,100);
comp.changeMode("javascript");
comp.enableAutocompletion();
comp.editor.setValue(string)
lively.setPosition(container,pos);
container.setAttribute("title", "Workspace")
}).then( () => {
comp.editor.focus();
return comp
});
}
static openCoolWorkspace(string, pos) {
var name = "juicy-ace-editor";
var comp = document.createElement(name);
return lively.components.openInWindow(comp).then((container) => {
pos = pos || lively.pt(100,100);
comp.changeMode("javascript");
comp.enableAutocompletion();
comp.editor.setValue(string)
comp.boundEval = function(str) {
return lively.vm.runEval(str, {topLevelVarRecorder: comp }).then(r => r.value)
}
lively.setPosition(container,pos);
container.setAttribute("title", "Cool Workspace")
}).then( () => {
comp.editor.focus();
return comp
});
}
static boundEval(str, ctx) {
// just a hack... to get rid of some async....
// #TODO make this more general
// works: await new Promise((r) => r(3))
// does not work yet: console.log(await new Promise((r) => r(3)))
// if (str.match(/^await /)) {
// str = "(async () => window._ = " + str +")()"
// }
// #Hack #Hammer #Jens Wrap and Unwrap code into function to preserve "this"
var transpiledSource = babel.transform('(function(){/*lively.code.start*/' + str+'})').code
.replace(/^(?:[\s\n]*["']use strict["'];[\s\n]*)([\S\s]*?)(?:\(function\s*\(\)\s*\{\s*\/\*lively.code.start\*\/)/, "$1") // strip prefix
.replace(/\}\);[\s\n]*$/,"") // strip postfix
console.log("code: " + transpiledSource)
console.log("context: " + ctx)
var interactiveEval = function interactiveEval(code) {
return eval(code);
};
return interactiveEval.call(ctx, transpiledSource);
}
static pt(x,y) {
return {x: x, y: y};
}
static setPosition(obj, point) {
obj.style.position = "absolute";
// var bounds = that.getBoundingClientRect().top
//var deltax = point.x - bounds.left
// var deltay = point.y - bounds.top
// obj.style.left = ""+ ((obj.style.left || 0) - deltax) + "px";
// obj.style.top = "" + ((obj.style.top || 0) - deltay) + "px";
obj.style.left = ""+ point.x + "px";
obj.style.top = "" + point.y + "px";
}
// Example: lively.getPosition(that)
static getPosition(obj) {
if (obj.clientX)
return pt(obj.clientX, obj.clientY)
if (obj.style) {
var pos = pt(parseFloat(obj.style.left), parseFloat(obj.style.top))
}
if (isNaN(pos.x) || isNaN(pos.y)) {
pos = $(that).position() // fallback to jQuery...
pos = pt(pos.left, pos.top)
}
return pos
}
// static getPosition(obj) {
// if (obj.clientX)
// return {x: obj.clientX, y: obj.clientY}
// else if (obj.style)
// return {x: parseFloat(obj.style.left), y: parseFloat(obj.style.top)}
// throw Error("" + obj + " has not position");
// }
static openFile(url) {
if (url.hostname == "lively4"){
var container = $('lively-container')[0];
if (container) {
container.followPath(url.pathname);
} else {
console.log("fall back on editor: "+ url);
this.editFile(url);
}
} else {
this.editFile(url);
}
}
static editFile(url) {
var editor = document.createElement("lively-editor");
lively.components.openInWindow(editor).then((container) => {
lively.setPosition(container, lively.pt(100, 100));
editor.setURL(url);
editor.loadFile();
});
}
static hideContextMenu(evt) {
if (evt.path[0] !== document.body) return
console.log("hide context menu:" + evt)
contextmenu.hide()
}
static openContextMenu(container, evt, target) {
if (HaloService.areHalosActive() ||
(HaloService.halosHidden && ((Date.now() - HaloService.halosHidden) < 500))) {
target = that
}
console.log("open context menu: " + target);
contextmenu.openIn(container, evt, target)
}
static log(/* varargs */) {
var args = arguments;
$('lively-console').each(function() {
try{
if (this.log) this.log.apply(this, args);
}catch(e) {
// ignore...
}
});
}
static nativeNotify(title, text, timeout, cb) {
if (!this.notifications) this.notifications = [];
this.notifications.push({title: title, text: text, cb: cb, time: Date.now()})
if (Notification.permission !== "granted") Notification.requestPermission();
var time = Date.now()
// check if the third last notification was already one second ago
if(this.notifications.length > 5 &&
(Date.now() - this.notifications[this.notifications.length - 3].time < 1000)) {
return console.log("SILENT NOTE: " + title + " (" + text + ")");
}
console.log("NOTE: " + title + " (" + text + ")");
var notification = new Notification(title || "", {
icon: 'https://www.lively-kernel.org/media/livelylogo-small.png',
body: text || "",
});
if (cb) notification.onclick = cb
if (timeout === undefined) timeout = 3
setTimeout(() => notification.close(), timeout * 1000);
// notification.onclick = cb
}
static notify(title, text, timeout, cb, color) {
// #TODO make native notifications opitional?
// this.nativeNotify(title, text, timeout, cb)
console.log("Note: " + title + "\n" + text)
if (!this.notificationList || !this.notificationList.parentElement) {
this.notificationList = document.createElement("lively-notification-list")
lively.components.openIn(document.body, this.notificationList).then( () => {
this.notificationList.addNotification(title, text, timeout, cb, color)
})
} else {
if (this.notificationList.addNotification) {
this.notificationList.addNotification(title, text, timeout, cb, color)
} else {
console.log("Notification List not initialized yet")
}
}
}
static initializeDocument(doc, loadedAsExtension) {
console.log("Lively4 initializeDocument");
doc.addEventListener('contextmenu', function(evt) {
if (evt.ctrlKey) {
evt.preventDefault();
lively.openContextMenu($('body')[0], evt);
return false;
}
}, false);
if (loadedAsExtension) {
this.import("customize").then(customize => {
customize.customizePage()
})
lively.notify("Lively4 extension loaded!",
" CTRL+LeftClick ... open halo\n" +
" CTRL+RightClick ... open menu");
} else {
// doc.addEventListener('contextmenu', function(evt) {
// evt.preventDefault();
// lively.openContextMenu($('body')[0], evt);
// return false;
// }, false);
}
doc.addEventListener('click', function(evt){lively.hideContextMenu(evt)}, false);
doc.addEventListener('keydown', function(evt){lively.keys.handle(evt)}, false);
}
static initializeHalos() {
if ($('lively-halo').size() === 0) {
$('<lively-halo>')
.attr('data-lively4-donotpersist', 'all')
.appendTo($('body'));
}
lively.components.loadUnresolved();
}
static initializeSearch() {
if ($('lively-search-widget').size() === 0) {
$('<lively-search-widget>')
.attr('data-lively4-donotpersist', 'all')
.appendTo($('body'));
}
lively.components.loadUnresolved();
}
static unload() {
lively.notify("unloading Lively is not supported yet! Please reload page....");
}
static updateTemplate(html) {
var tagName = components.reloadComponent(html);
if (!tagName) return;
_.each($(tagName), function(oldInstance) {
if (oldInstance.__ingoreUpdates) return;
// if (oldInstance.isMinimized && oldInstance.isMinimized()) return // ignore minimized windows
// if (oldInstance.isMaximized && oldInstance.isMaximized()) return // ignore isMaximized windows
var owner = oldInstance.parentElement;
var newInstance = document.createElement(tagName);
owner.replaceChild(newInstance, oldInstance);
_.each(oldInstance.childNodes, function(ea) {
if (ea) { // there are "undefined" elemented in childNodes... sometimes #TODO
newInstance.appendChild(ea);
console.log("append old child: " + ea);
}
});
_.each(oldInstance.attributes, function(ea) {
console.log("set old attribute " + ea.name + " to: " + ea.value);
newInstance.setAttribute(ea.name, ea.value);
});
// Migrate Position
if (oldInstance.style.position == "absolute") {
newInstance.style.top = oldInstance.style.top
newInstance.style.left = oldInstance.style.left
}
// Migrate "that" pointer
if (window.that == oldInstance) {
window.that = newInstance
}
if (newInstance.livelyMigrate) {
newInstance.livelyMigrate(oldInstance) // give instances a chance to take over old state...
}
});
}
static showPoint(point) {
var comp = document.createElement("div")
comp.style['pointer-events'] = "none";
comp.style.width = "5px";
comp.style.height = "5px";
comp.style.padding = "1px";
comp.style.backgroundColor = 'rgba(255,0,0,0.5)';
comp.isMetaNode = true;
document.body.appendChild(comp);
lively.setPosition(comp, point);
comp.setAttribute("data-is-meta", "true");
setTimeout( () => $(comp).remove(), 3000);
// ea.getBoundingClientRect
}
static showSource(object, evt) {
if (object instanceof HTMLElement) {
var comp = document.createElement("lively-container");
lively.components.openInWindow(comp).then((container) => {
comp.editFile(lively4url +"/templates/" + object.localName + ".html")
})
} else {
lively.notify("Could not show source for: " + object)
}
}
static async showClassSource(object, evt) {
// object = that
if (object instanceof HTMLElement) {
let templateFile = lively4url +"/templates/" + object.localName + ".html",
source = await fetch(templateFile).then( r => r.text());
template = $.parseHTML(source).find( ea => ea.tagName == "TEMPLATE"),
className = template.getAttribute('data-class'),
baseName = this.templateClassNameToTemplateName(className)
moduleURL = lively4url +"/templates/" + baseName + ".js";
lively.openBrowser(moduleURL, true, className);
} else {
lively.notify("Could not show source for: " + object)
}
}
static showElement(elem, timeout) {
if (!elem || !elem.getBoundingClientRect) return
var comp = document.createElement("div")
var bounds = elem.getBoundingClientRect()
var pos = lively.pt(
bounds.left + $(document).scrollLeft(),
bounds.top + $(document).scrollTop())
comp.style.width = bounds.width +"px"
comp.style.height = bounds.height +"px"
comp.style['pointer-events'] = "none"
// comp.style.height = "0px"
comp.style["z-index"] = 1000;
comp.style.border = "1px solid red";
comp.isMetaNode = true;
document.body.appendChild(comp)
lively.setPosition(comp, pos);
comp.setAttribute("data-is-meta", "true")
comp.innerHTML = "<pre data-is-meta='true' style='position: relative; top: -8px; width: 200px; background: rgba(255,255,255,0.8); color: red; font-size: 8pt'>" +
elem.tagName +": " + elem.id + "\n" +
elem.getAttribute("class") +"\n"
+ "</pre>"
setTimeout( () => $(comp).remove(), timeout || 3000)
return comp
}
static allProperties(obj, result) {
result = result || {};
Object.getOwnPropertyNames(obj).forEach( name => {result[name] = obj.constructor.name})
if (obj.__proto__) {
lively.allProperties(obj.__proto__, result);
}
return result
}
static templateClassNameToTemplateName(className) {
return className.replace(/[A-Z]/g, ea => "-" + ea.toLowerCase()).replace(/^-/,"")
}
static async registerTemplate() {
var template = document.currentScript.ownerDocument.querySelector('template');
var clone = document.importNode(template.content, true);
var proto;
var className = template.getAttribute("data-class")
if (className) {
// className = "LivelyFooBar"
baseName = this.templateClassNameToTemplateName(className)
var module= await System.import(lively4url +'/templates/' + baseName +".js");
proto = Object.create(module.prototype || module.default.prototype)
}
lively.components.register(template.id, clone, proto);
}
static get eventListeners() {
if (!window.livelyEventListeners) {
window.livelyEventListeners = []
}
return window.livelyEventListeners
}
static set eventListeners(list) {
window.livelyEventListeners = list
}
// Registration and deregistration of eventlisteners for run-time programming...
static addEventListener(domain, target, type, listener, options) {
this.eventListeners.push(
{target: target, type: type, listener: listener, domain: domain, options: options})
target.addEventListener(type, listener, options)
}
static removeEventListener(domain, target, type, listener) {
this.eventListeners = this.eventListeners.filter(ea => {
if ((!target || (ea.target === target))
&& (!type || (ea.type == type))
&& (!listener || (ea.listener === listener))
&& (!domain || (ea.domain == domain))) {
// actually removing the event listener
// console.log("removeEventListener", ea.target, ea.type, ea.listener)
ea.target.removeEventListener(ea.type, ea.listener, ea.options)
return false
} else {
return true
}
})
}
static openSearchWidget(text) {
var comp = document.getElementsByTagName("lively-search-widget")[0]
if (comp.isVisible && text == comp.query) {
comp.isVisible = false;
} else {
comp.isVisible = true
comp.search(text, true)
}
}
static hideSearchWidget() {
var comp = document.getElementsByTagName("lively-search-widget")[0]
comp.hide();
}
static openHelpWindow(text) {
this.openComponentInWindow("lively-help").then(comp => {
comp.parentElement.style.width = "850px";
comp.parentElement.style.height = "600px";
comp.getHelp(text);
})
}
static openComponentInWindow(name, pos) {
var comp = document.createElement(name);
return lively.components.openInWindow(comp).then((w) => {
if (pos) lively.setPosition(w, pos);
if (comp.windowTitle) w.setAttribute("title", "" + comp.windowTitle);
return comp;
});
}
// lively.openBrowser("https://lively4/etc/mounts", true, "Github")
static async openBrowser(url, edit, pattern, replaceExisting) {
var editorComp;
var containerPromise
if (replaceExisting) {
editorComp = _.detect(document.querySelectorAll("lively-container"),
ea => ea.isSearchBrowser)
}
// that.isSearchBrowser
containerPromise = editorComp ? Promise.resolve(editorComp) :
lively.openComponentInWindow("lively-container");
return containerPromise.then(comp => {
editorComp = comp;
var lastWindow = _.first(document.body.querySelectorAll("lively-window"))
if (!lastWindow) {
comp.parentElement.style.width = "850px"
comp.parentElement.style.height = "600px"
} else {
lively.setPosition(comp.parentElement,
lively.getPosition(lastWindow).addPt(pt(10,10)))
}
if (edit) comp.setAttribute("mode", "edit");
if (pattern) {
comp.isSearchBrowser = true
comp.hideNavbar()
}
return comp.followPath(url)
}).then(() => {
if (edit && pattern) {
editorComp.realAceEditor().then( editor => editor.find(pattern))
}
})
}
}
if (window.lively && window.lively.name != "Lively") {
Object.assign(Lively, window.lively) // copy objects from lively.modules
}
if (!window.lively || window.lively.name != "Lively") {
window.lively = Lively
console.log("loaded lively intializer");
// only load once... not during development
Lively.loaded();
} else {
window.lively = Lively
}
console.log("loaded lively");
| src/client/lively.js | 'use strict';
import './patches.js' // monkey patch the meta sytem....
import * as jquery from '../external/jquery.js';
import * as _ from '../external/underscore.js';
import * as scripts from './script-manager.js';
import * as messaging from './messaging.js';
import * as preferences from './preferences.js';
import * as persistence from './persistence.js';
import html from './html.js';
import files from './files.js';
import paths from './paths.js';
import inspector from './inspector.js';
import contextmenu from './contextmenu.js';
import keys from './keys.js';
import components from './morphic/component-loader.js';
import authGithub from './auth-github.js'
import authDropbox from './auth-dropbox.js'
import authGoogledrive from './auth-googledrive.js'
import expose from './expose.js';
/* expose external modules */
import color from '../external/tinycolor.js';
import focalStorage from '../external/focalStorage.js';
import * as kernel from 'kernel'
let $ = window.$,
babel = window.babel; // known global variables.
import {pt} from 'lively.graphics';
// a) Special shorthands for interactive development
// b) this is the only reasonable way to use modules in template scripts, due to no shared lexical scope #TODO
var exportmodules = [
"scripts",
"messaging",
"preferences",
"persistence",
"files",
"keys",
"paths",
"html",
"components",
"inspector",
"color",
"focalStorage",
"authGithub",
"authDropbox",
"authGoogledrive"
];
// #LiveProgramming #Syntax #ES6Modules #Experiment #Jens
// By structuring our modules differently, we still can act as es6 module to the outside but develop at runtime
// #IDEA: I refactored from "static module and function style" to "dynamic object" style
export default class Lively {
static import(moduleName, path, forceLoad) {
if (lively.modules && path) {
lively.modules.module("" + path).reload({reloadDeps: true, resetEnv: false})
}
if (!path) path = this.defaultPath(moduleName)
if (!path) throw Error("Could not imoport " + moduleName + ", not path specified!")
if (this[moduleName] && !forceLoad)
return new Promise((resolve) => { resolve(this[moduleName])})
if (forceLoad) {
path += "?" + Date.now()
}
return System.import(path).then( (module, err) => {
if (err) {
lively.notify("Could not load module " + moduleName, err);
} else {
console.log("lively: load "+ moduleName)
if (moduleName == "lively") {
this.notify("migrate lively.js")
var oldLively = window.lively;
window.lively =module.default || module
this["previous"] = oldLively
this.components = oldLively.components // components have important state
} else {
this[moduleName] = module.default || module
}
if (lively.components && this[moduleName]) {
lively.components.updatePrototype(this[moduleName].prototype);
}
return module.default || module
}
})
}
static async reloadModule(path) {
path = "" + path;
var module = lively.modules.module(path)
if (!module.isLoaded()) {
console.log("cannot reload module " + path + " because it is not loaded")
return;
}
console.log("reload module: " + path)
return module.reload({reloadDeps: true, resetEnv: false})
.then( () => System.import(path))
.then( mod => {
var moduleName = path.replace(/[^\/]*/,"")
var defaultClass = mod.default
if (lively.components && defaultClass) {
console.log("update template prototype: " + moduleName)
lively.components.updatePrototype(defaultClass.prototype);
};
if (moduleName == "lively") {
this.notify("migrate lively.js")
var oldLively = window.lively;
window.lively =module.default || module
this["previous"] = oldLively
this.components = oldLively.components // components have important state
}
return mod;
})
}
static loadJavaScriptThroughDOM(name, src, force) {
return new Promise((resolve) => {
var scriptNode = document.querySelector("#"+name);
if (scriptNode) {
scriptNode.remove();
}
var script = document.createElement("script");
script.id=name;
script.charset="utf-8"
script.type="text/javascript";
if (force) {
src += + "?" + Date.now();
}
script.src= src;
script.onload = function() {
resolve();
};
document.head.appendChild(script);
})
}
static loadCSSThroughDOM(name, href, force) {
return new Promise((resolve) => {
var linkNode = document.querySelector("#"+name);
if (linkNode) {
linkNode.remove();
}
var link = document.createElement("link");
link.rel="stylesheet"
link.id=name;
link.charset="utf-8"
link.type="text/css";
if (force) {
href += + "?" + Date.now();
}
link.href= href;
link.onload = function() {
resolve();
};
document.head.appendChild(link);
})
}
static fillTemplateStyles(root) {
// there seems to be no <link ..> tag allowed to reference css inside of templates #Jens
var promises = []
_.each(root.querySelectorAll("style"), ea => {
var src = ea.getAttribute("data-src")
if (src) {
promises.push(fetch(lively4url + src).then(r => r.text()).then(css => {
ea.innerHTML = css
}))
}
})
return Promise.all(promises)
}
static defaultPath(moduleName) {
return ({
math: kernel.realpath("/src/external/math.js"),
typo: kernel.realpath("/src/external/typo.js"),
contextmenu: kernel.realpath('/src/client/contextmenu.js'),
customize: kernel.realpath('/src/client/customize.js'),
selecting: kernel.realpath('/src/client/morphic/selecting.js'),
expose: kernel.realpath('/src/client/expose.js')
})[moduleName]
}
static showError(error) {
this.handleError(error)
}
static handleError(error) {
lively.LastError = error
if (!error) return // hmm... this is currious...
lively.notify("Error: ", error.message, 10, () =>
lively.openWorkspace("Error:" + error.message + "\nLine:" + error.lineno + " Col: " + error.colno+"\nSource:" + error.source + "\nError:" + error.stack),
"red")
}
static loaded() {
// #Refactor with #ContextJS
// guard againsst wrapping twice and ending in endless recursion
// if (!console.log.originalFunction) {
// var nativeLog = console.log;
// console.log = function() {
// nativeLog.apply(console, arguments);
// lively.log.apply(undefined, arguments);
// };
// console.log.originalFunction = nativeLog; // #TODO use generic Wrapper mechanism here
// }
// if (!console.error.originalFunction) {
// var nativeError = console.error;
// console.error = function() {
// nativeError.apply(console, arguments);
// lively.log.apply(undefined, arguments);
// };
// console.error.originalFunction = nativeError; // #TODO use generic Wrapper mechanism here
// }
// General Error Handling
if (window.onerror === null) {
window.onerror = function(message, source, lineno, colno, error) {
lively.handleError(error)
}
}
// do it just once
if (!window.unhandledRejectionEventLister) {
window.unhandledRejectionEventLister = function(evt) {lively.handleError(evt.reason)} ;
window.addEventListener('unhandledrejection', unhandledRejectionEventLister);
}
exportmodules.forEach(name => lively[name] = eval(name)); // oh... this seems uglier than expected
// for anonymous lively.modules workspaces
if (lively.modules && !lively.modules.isHookInstalled("fetch", "workspaceFetch")) {
lively.modules.installHook("fetch", function workspaceFetch(proceed, load) {
if (load.address.match("workspace://")) return Promise.resolve("")
return proceed(load)
})
}
// for container content... But this will lead to conflicts with lively4chrome ?? #Jens
lively.loadCSSThroughDOM("livelystyle", lively4url + "/templates/lively4.css")
}
static array(anyList){
return Array.prototype.slice.call(anyList);
}
static openWorkspace(string, pos) {
var name = "juicy-ace-editor";
var comp = document.createElement(name);
return lively.components.openInWindow(comp).then((container) => {
pos = pos || lively.pt(100,100);
comp.changeMode("javascript");
comp.enableAutocompletion();
comp.editor.setValue(string)
lively.setPosition(container,pos);
container.setAttribute("title", "Workspace")
}).then( () => {
comp.editor.focus();
return comp
});
}
static openCoolWorkspace(string, pos) {
var name = "juicy-ace-editor";
var comp = document.createElement(name);
return lively.components.openInWindow(comp).then((container) => {
pos = pos || lively.pt(100,100);
comp.changeMode("javascript");
comp.enableAutocompletion();
comp.editor.setValue(string)
comp.boundEval = function(str) {
return lively.vm.runEval(str, {topLevelVarRecorder: comp }).then(r => r.value)
}
lively.setPosition(container,pos);
container.setAttribute("title", "Cool Workspace")
}).then( () => {
comp.editor.focus();
return comp
});
}
static boundEval(str, ctx) {
// just a hack... to get rid of some async....
// #TODO make this more general
// works: await new Promise((r) => r(3))
// does not work yet: console.log(await new Promise((r) => r(3)))
// if (str.match(/^await /)) {
// str = "(async () => window._ = " + str +")()"
// }
// #Hack #Hammer #Jens Wrap and Unwrap code into function to preserve "this"
var transpiledSource = babel.transform('(function(){/*lively.code.start*/' + str+'})').code
.replace(/^(?:[\s\n]*["']use strict["'];[\s\n]*)([\S\s]*?)(?:\(function\s*\(\)\s*\{\s*\/\*lively.code.start\*\/)/, "$1") // strip prefix
.replace(/\}\);[\s\n]*$/,"") // strip postfix
console.log("code: " + transpiledSource)
console.log("context: " + ctx)
var interactiveEval = function interactiveEval(code) {
return eval(code);
};
return interactiveEval.call(ctx, transpiledSource);
}
static pt(x,y) {
return {x: x, y: y};
}
static setPosition(obj, point) {
obj.style.position = "absolute";
// var bounds = that.getBoundingClientRect().top
//var deltax = point.x - bounds.left
// var deltay = point.y - bounds.top
// obj.style.left = ""+ ((obj.style.left || 0) - deltax) + "px";
// obj.style.top = "" + ((obj.style.top || 0) - deltay) + "px";
obj.style.left = ""+ point.x + "px";
obj.style.top = "" + point.y + "px";
}
// Example: lively.getPosition(that)
static getPosition(obj) {
if (obj.clientX)
return pt(obj.clientX, obj.clientY)
if (obj.style) {
var pos = pt(parseFloat(obj.style.left), parseFloat(obj.style.top))
}
if (isNaN(pos.x) || isNaN(pos.y)) {
pos = $(that).position() // fallback to jQuery...
pos = pt(pos.left, pos.top)
}
return pos
}
// static getPosition(obj) {
// if (obj.clientX)
// return {x: obj.clientX, y: obj.clientY}
// else if (obj.style)
// return {x: parseFloat(obj.style.left), y: parseFloat(obj.style.top)}
// throw Error("" + obj + " has not position");
// }
static openFile(url) {
if (url.hostname == "lively4"){
var container = $('lively-container')[0];
if (container) {
container.followPath(url.pathname);
} else {
console.log("fall back on editor: "+ url);
this.editFile(url);
}
} else {
this.editFile(url);
}
}
static editFile(url) {
var editor = document.createElement("lively-editor");
lively.components.openInWindow(editor).then((container) => {
lively.setPosition(container, lively.pt(100, 100));
editor.setURL(url);
editor.loadFile();
});
}
static hideContextMenu(evt) {
if (evt.path[0] !== document.body) return
console.log("hide context menu:" + evt)
contextmenu.hide()
}
static openContextMenu(container, evt, target) {
if (HaloService.areHalosActive() ||
(HaloService.halosHidden && ((Date.now() - HaloService.halosHidden) < 500))) {
target = that
}
console.log("open context menu: " + target);
contextmenu.openIn(container, evt, target)
}
static log(/* varargs */) {
var args = arguments;
$('lively-console').each(function() {
try{
if (this.log) this.log.apply(this, args);
}catch(e) {
// ignore...
}
});
}
static nativeNotify(title, text, timeout, cb) {
if (!this.notifications) this.notifications = [];
this.notifications.push({title: title, text: text, cb: cb, time: Date.now()})
if (Notification.permission !== "granted") Notification.requestPermission();
var time = Date.now()
// check if the third last notification was already one second ago
if(this.notifications.length > 5 &&
(Date.now() - this.notifications[this.notifications.length - 3].time < 1000)) {
return console.log("SILENT NOTE: " + title + " (" + text + ")");
}
console.log("NOTE: " + title + " (" + text + ")");
var notification = new Notification(title || "", {
icon: 'https://www.lively-kernel.org/media/livelylogo-small.png',
body: text || "",
});
if (cb) notification.onclick = cb
if (timeout === undefined) timeout = 3
setTimeout(() => notification.close(), timeout * 1000);
// notification.onclick = cb
}
static notify(title, text, timeout, cb, color) {
// #TODO make native notifications opitional?
// this.nativeNotify(title, text, timeout, cb)
console.log("Note: " + title + "\n" + text)
if (!this.notificationList || !this.notificationList.parentElement) {
this.notificationList = document.createElement("lively-notification-list")
lively.components.openIn(document.body, this.notificationList).then( () => {
this.notificationList.addNotification(title, text, timeout, cb, color)
})
} else {
if (this.notificationList.addNotification) {
this.notificationList.addNotification(title, text, timeout, cb, color)
} else {
console.log("Notification List not initialized yet")
}
}
}
static initializeDocument(doc, loadedAsExtension) {
console.log("Lively4 initializeDocument");
doc.addEventListener('contextmenu', function(evt) {
if (evt.ctrlKey) {
evt.preventDefault();
lively.openContextMenu($('body')[0], evt);
return false;
}
}, false);
if (loadedAsExtension) {
this.import("customize").then(customize => {
customize.customizePage()
})
lively.notify("Lively4 extension loaded!",
" CTRL+LeftClick ... open halo\n" +
" CTRL+RightClick ... open menu");
} else {
// doc.addEventListener('contextmenu', function(evt) {
// evt.preventDefault();
// lively.openContextMenu($('body')[0], evt);
// return false;
// }, false);
}
doc.addEventListener('click', function(evt){lively.hideContextMenu(evt)}, false);
doc.addEventListener('keydown', function(evt){lively.keys.handle(evt)}, false);
}
static initializeHalos() {
if ($('lively-halo').size() === 0) {
$('<lively-halo>')
.attr('data-lively4-donotpersist', 'all')
.appendTo($('body'));
}
lively.components.loadUnresolved();
}
static initializeSearch() {
if ($('lively-search-widget').size() === 0) {
$('<lively-search-widget>')
.attr('data-lively4-donotpersist', 'all')
.appendTo($('body'));
}
lively.components.loadUnresolved();
}
static unload() {
lively.notify("unloading Lively is not supported yet! Please reload page....");
}
static updateTemplate(html) {
var tagName = components.reloadComponent(html);
if (!tagName) return;
_.each($(tagName), function(oldInstance) {
if (oldInstance.__ingoreUpdates) return;
// if (oldInstance.isMinimized && oldInstance.isMinimized()) return // ignore minimized windows
// if (oldInstance.isMaximized && oldInstance.isMaximized()) return // ignore isMaximized windows
var owner = oldInstance.parentElement;
var newInstance = document.createElement(tagName);
owner.replaceChild(newInstance, oldInstance);
_.each(oldInstance.childNodes, function(ea) {
if (ea) { // there are "undefined" elemented in childNodes... sometimes #TODO
newInstance.appendChild(ea);
console.log("append old child: " + ea);
}
});
_.each(oldInstance.attributes, function(ea) {
console.log("set old attribute " + ea.name + " to: " + ea.value);
newInstance.setAttribute(ea.name, ea.value);
});
// Migrate Position
if (oldInstance.style.position == "absolute") {
newInstance.style.top = oldInstance.style.top
newInstance.style.left = oldInstance.style.left
}
// Migrate "that" pointer
if (window.that == oldInstance) {
window.that = newInstance
}
if (newInstance.livelyMigrate) {
newInstance.livelyMigrate(oldInstance) // give instances a chance to take over old state...
}
});
}
static showPoint(point) {
var comp = document.createElement("div")
comp.style['pointer-events'] = "none";
comp.style.width = "5px";
comp.style.height = "5px";
comp.style.padding = "1px";
comp.style.backgroundColor = 'rgba(255,0,0,0.5)';
comp.isMetaNode = true;
document.body.appendChild(comp);
lively.setPosition(comp, point);
comp.setAttribute("data-is-meta", "true");
setTimeout( () => $(comp).remove(), 3000);
// ea.getBoundingClientRect
}
static showSource(object, evt) {
if (object instanceof HTMLElement) {
var comp = document.createElement("lively-container");
lively.components.openInWindow(comp).then((container) => {
comp.editFile(lively4url +"/templates/" + object.localName + ".html")
})
} else {
lively.notify("Could not show source for: " + object)
}
}
static async showClassSource(object, evt) {
// object = that
if (object instanceof HTMLElement) {
let templateFile = lively4url +"/templates/" + object.localName + ".html",
source = await fetch(templateFile).then( r => r.text());
template = $.parseHTML(source).find( ea => ea.tagName == "TEMPLATE"),
className = template.getAttribute('data-class'),
baseName = this.templateClassNameToTemplateName(className)
moduleURL = lively4url +"/templates/" + baseName + ".js";
lively.openBrowser(moduleURL, true, className);
} else {
lively.notify("Could not show source for: " + object)
}
}
static showElement(elem, timeout) {
if (!elem || !elem.getBoundingClientRect) return
var comp = document.createElement("div")
var bounds = elem.getBoundingClientRect()
var pos = lively.pt(
bounds.left + $(document).scrollLeft(),
bounds.top + $(document).scrollTop())
comp.style.width = bounds.width +"px"
comp.style.height = bounds.height +"px"
comp.style['pointer-events'] = "none"
// comp.style.height = "0px"
comp.style["z-index"] = 1000;
comp.style.border = "1px solid red";
comp.isMetaNode = true;
document.body.appendChild(comp)
lively.setPosition(comp, pos);
comp.setAttribute("data-is-meta", "true")
comp.innerHTML = "<pre data-is-meta='true' style='position: relative; top: -8px; width: 200px; background: rgba(255,255,255,0.8); color: red; font-size: 8pt'>" +
elem.tagName +": " + elem.id + "\n" +
elem.getAttribute("class") +"\n"
+ "</pre>"
setTimeout( () => $(comp).remove(), timeout || 3000)
return comp
}
static allProperties(obj, result) {
result = result || {};
Object.getOwnPropertyNames(obj).forEach( name => {result[name] = obj.constructor.name})
if (obj.__proto__) {
lively.allProperties(obj.__proto__, result);
}
return result
}
static templateClassNameToTemplateName(className) {
return className.replace(/[A-Z]/g, ea => "-" + ea.toLowerCase()).replace(/^-/,"")
}
static async registerTemplate() {
var template = document.currentScript.ownerDocument.querySelector('template');
var clone = document.importNode(template.content, true);
var proto;
var className = template.getAttribute("data-class")
if (className) {
// className = "LivelyFooBar"
baseName = this.templateClassNameToTemplateName(className)
var module= await System.import(lively4url +'/templates/' + baseName +".js");
proto = Object.create(module.prototype || module.default.prototype)
}
lively.components.register(template.id, clone, proto);
}
static get eventListeners() {
if (!window.livelyEventListeners) {
window.livelyEventListeners = []
}
return window.livelyEventListeners
}
static set eventListeners(list) {
window.livelyEventListeners = list
}
// Registration and deregistration of eventlisteners for run-time programming...
static addEventListener(domain, target, type, listener, options) {
this.eventListeners.push(
{target: target, type: type, listener: listener, domain: domain, options: options})
target.addEventListener(type, listener, options)
}
static removeEventListener(domain, target, type, listener) {
this.eventListeners = this.eventListeners.filter(ea => {
if ((!target || (ea.target === target))
&& (!type || (ea.type == type))
&& (!listener || (ea.listener === listener))
&& (!domain || (ea.domain == domain))) {
// actually removing the event listener
// console.log("removeEventListener", ea.target, ea.type, ea.listener)
ea.target.removeEventListener(ea.type, ea.listener, ea.options)
return false
} else {
return true
}
})
}
static openSearchWidget(text) {
var comp = document.getElementsByTagName("lively-search-widget")[0]
if (comp.isVisible && text == comp.query) {
comp.isVisible = false;
} else {
comp.isVisible = true
comp.search(text, true)
}
}
static hideSearchWidget() {
var comp = document.getElementsByTagName("lively-search-widget")[0]
comp.hide();
}
static openHelpWindow(text) {
this.openComponentInWindow("lively-help").then(comp => {
comp.parentElement.style.width = "850px";
comp.parentElement.style.height = "600px";
comp.getHelp(text);
})
}
static openComponentInWindow(name, pos) {
var comp = document.createElement(name);
return lively.components.openInWindow(comp).then((w) => {
if (pos) lively.setPosition(w, pos);
if (comp.windowTitle) w.setAttribute("title", "" + comp.windowTitle);
return comp;
});
}
// lively.openBrowser("https://lively4/etc/mounts", true, "Github")
static async openBrowser(url, edit, pattern) {
var editorComp;
var containerPromise
if (pattern) {
editorComp = _.detect(document.querySelectorAll("lively-container"),
ea => ea.isSearchBrowser)
}
// that.isSearchBrowser
containerPromise = editorComp ? Promise.resolve(editorComp) :
lively.openComponentInWindow("lively-container");
return containerPromise.then(comp => {
editorComp = comp;
comp.parentElement.style.width = "850px"
comp.parentElement.style.height = "600px"
if (edit) comp.setAttribute("mode", "edit");
if (pattern) {
comp.isSearchBrowser = true
comp.hideNavbar()
}
return comp.followPath(url)
}).then(() => {
if (edit && pattern) {
editorComp.realAceEditor().then( editor => editor.find(pattern))
}
})
}
}
if (window.lively && window.lively.name != "Lively") {
Object.assign(Lively, window.lively) // copy objects from lively.modules
}
if (!window.lively || window.lively.name != "Lively") {
window.lively = Lively
console.log("loaded lively intializer");
// only load once... not during development
Lively.loaded();
} else {
window.lively = Lively
}
console.log("loaded lively");
| SYNC M src/client/lively.js;
| src/client/lively.js | SYNC M src/client/lively.js; | <ide><path>rc/client/lively.js
<ide> });
<ide> }
<ide> // lively.openBrowser("https://lively4/etc/mounts", true, "Github")
<del> static async openBrowser(url, edit, pattern) {
<add> static async openBrowser(url, edit, pattern, replaceExisting) {
<ide> var editorComp;
<ide> var containerPromise
<del> if (pattern) {
<add> if (replaceExisting) {
<ide> editorComp = _.detect(document.querySelectorAll("lively-container"),
<ide> ea => ea.isSearchBrowser)
<ide> }
<ide> containerPromise = editorComp ? Promise.resolve(editorComp) :
<ide> lively.openComponentInWindow("lively-container");
<ide>
<add>
<ide> return containerPromise.then(comp => {
<ide> editorComp = comp;
<del> comp.parentElement.style.width = "850px"
<del> comp.parentElement.style.height = "600px"
<add> var lastWindow = _.first(document.body.querySelectorAll("lively-window"))
<add> if (!lastWindow) {
<add> comp.parentElement.style.width = "850px"
<add> comp.parentElement.style.height = "600px"
<add> } else {
<add> lively.setPosition(comp.parentElement,
<add> lively.getPosition(lastWindow).addPt(pt(10,10)))
<add> }
<add>
<ide> if (edit) comp.setAttribute("mode", "edit");
<ide> if (pattern) {
<ide> comp.isSearchBrowser = true |
|
Java | mit | error: pathspec 'src/main/java/org/whirlwin/java8/examples/misc/OptionalExample.java' did not match any file(s) known to git
| ae822ceab6c8f8fed24ea3b7da69e773b7b35873 | 1 | whirlwin/java-8-examples | package org.whirlwin.java8.examples.misc;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class OptionalExample {
private static final Map<Integer, String> nameRegistry = new HashMap<Integer, String>() {{
put(1, "John Doe");
}};
public static void main(String[] args) {
Optional<String> johnDoe = getNameById(1);
printName(johnDoe);
Optional<String> janeDoe = getNameById(2);
printName(janeDoe);
}
public static Optional<String> getNameById(int id) {
String name = nameRegistry.get(id);
return Optional.ofNullable(name);
}
public static void printName(Optional<String> name) {
if (name.isPresent()) {
System.out.println(name.get());
} else {
System.out.println("Warning: Name not set");
}
}
}
| src/main/java/org/whirlwin/java8/examples/misc/OptionalExample.java | Add Optional example.
| src/main/java/org/whirlwin/java8/examples/misc/OptionalExample.java | Add Optional example. | <ide><path>rc/main/java/org/whirlwin/java8/examples/misc/OptionalExample.java
<add>package org.whirlwin.java8.examples.misc;
<add>
<add>import java.util.HashMap;
<add>import java.util.Map;
<add>import java.util.Optional;
<add>
<add>public class OptionalExample {
<add>
<add> private static final Map<Integer, String> nameRegistry = new HashMap<Integer, String>() {{
<add> put(1, "John Doe");
<add> }};
<add>
<add> public static void main(String[] args) {
<add> Optional<String> johnDoe = getNameById(1);
<add> printName(johnDoe);
<add>
<add> Optional<String> janeDoe = getNameById(2);
<add> printName(janeDoe);
<add> }
<add>
<add> public static Optional<String> getNameById(int id) {
<add> String name = nameRegistry.get(id);
<add> return Optional.ofNullable(name);
<add> }
<add>
<add> public static void printName(Optional<String> name) {
<add> if (name.isPresent()) {
<add> System.out.println(name.get());
<add> } else {
<add> System.out.println("Warning: Name not set");
<add> }
<add> }
<add>} |
|
Java | mit | b7028c573497dbab15688b11264cc8356c32d94a | 0 | proxer/ProxerLibJava | package com.proxerme.library.connection.ucp.request;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.proxerme.library.connection.ProxerResult;
import com.proxerme.library.connection.ucp.UcpRequest;
import com.proxerme.library.connection.ucp.result.DeleteReminderResult;
import com.squareup.moshi.Moshi;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
/**
* Deletes the {@link com.proxerme.library.connection.ucp.entitiy.Reminder} (specified through the
* id in the constructor) from the list of the user. The user needs to be logged in for this API.
*
* @author Ruben Gees
*/
public class DeleteReminderRequest extends UcpRequest<Void> {
private static final String ENDPOINT = "deletereminder";
private static final String ID_PARAMETER = "id";
private String id;
/**
* The constructor.
*
* @param id The id of the reminder to delete.
*/
public DeleteReminderRequest(@NonNull String id) {
this.id = id;
}
@Override
protected ProxerResult<Void> parse(@NonNull Moshi moshi, @NonNull ResponseBody body)
throws IOException {
return moshi.adapter(DeleteReminderResult.class).fromJson(body.source());
}
@NonNull
@Override
protected String getApiEndpoint() {
return ENDPOINT;
}
@Override
protected String getMethod() {
return POST;
}
@Nullable
@Override
protected RequestBody getRequestBody() {
return new FormBody.Builder()
.add(ID_PARAMETER, id)
.build();
}
}
| library/src/main/java/com/proxerme/library/connection/ucp/request/DeleteReminderRequest.java | package com.proxerme.library.connection.ucp.request;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.proxerme.library.connection.ProxerResult;
import com.proxerme.library.connection.ucp.UcpRequest;
import com.squareup.moshi.Moshi;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
/**
* Deletes the {@link com.proxerme.library.connection.ucp.entitiy.Reminder} (specified through the
* id in the constructor) from the list of the user. The user needs to be logged in for this API.
*
* @author Ruben Gees
*/
public class DeleteReminderRequest extends UcpRequest<Void> {
private static final String ENDPOINT = "deletereminder";
private static final String ID_PARAMETER = "id";
private String id;
/**
* The constructor.
*
* @param id The id of the reminder to delete.
*/
public DeleteReminderRequest(@NonNull String id) {
this.id = id;
}
@Override
protected ProxerResult<Void> parse(@NonNull Moshi moshi, @NonNull ResponseBody body)
throws IOException {
return null;
}
@NonNull
@Override
protected String getApiEndpoint() {
return ENDPOINT;
}
@Override
protected String getMethod() {
return POST;
}
@Nullable
@Override
protected RequestBody getRequestBody() {
return new FormBody.Builder()
.add(ID_PARAMETER, id)
.build();
}
}
| Add missed implementation for parse
| library/src/main/java/com/proxerme/library/connection/ucp/request/DeleteReminderRequest.java | Add missed implementation for parse | <ide><path>ibrary/src/main/java/com/proxerme/library/connection/ucp/request/DeleteReminderRequest.java
<ide>
<ide> import com.proxerme.library.connection.ProxerResult;
<ide> import com.proxerme.library.connection.ucp.UcpRequest;
<add>import com.proxerme.library.connection.ucp.result.DeleteReminderResult;
<ide> import com.squareup.moshi.Moshi;
<ide>
<ide> import java.io.IOException;
<ide> @Override
<ide> protected ProxerResult<Void> parse(@NonNull Moshi moshi, @NonNull ResponseBody body)
<ide> throws IOException {
<del> return null;
<add> return moshi.adapter(DeleteReminderResult.class).fromJson(body.source());
<ide> }
<ide>
<ide> @NonNull |
|
Java | apache-2.0 | 2530972f6669d0ba06e79a292769be80b0458538 | 0 | ConnectSDK/Connect-SDK-Android-Core | /*
* RokuService
* Connect SDK
*
* Copyright (c) 2014 LG Electronics.
* Created by Hyun Kook Khang on 26 Feb 2014
*
* 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.connectsdk.service;
import android.text.TextUtils;
import android.util.Log;
import com.connectsdk.core.AppInfo;
import com.connectsdk.core.ImageInfo;
import com.connectsdk.core.MediaInfo;
import com.connectsdk.core.Util;
import com.connectsdk.device.ConnectableDevice;
import com.connectsdk.discovery.DiscoveryFilter;
import com.connectsdk.discovery.DiscoveryManager;
import com.connectsdk.etc.helper.DeviceServiceReachability;
import com.connectsdk.etc.helper.HttpConnection;
import com.connectsdk.etc.helper.HttpMessage;
import com.connectsdk.service.capability.CapabilityMethods;
import com.connectsdk.service.capability.KeyControl;
import com.connectsdk.service.capability.Launcher;
import com.connectsdk.service.capability.MediaControl;
import com.connectsdk.service.capability.MediaPlayer;
import com.connectsdk.service.capability.TextInputControl;
import com.connectsdk.service.capability.listeners.ResponseListener;
import com.connectsdk.service.command.NotSupportedServiceSubscription;
import com.connectsdk.service.command.ServiceCommand;
import com.connectsdk.service.command.ServiceCommandError;
import com.connectsdk.service.command.ServiceSubscription;
import com.connectsdk.service.command.URLServiceSubscription;
import com.connectsdk.service.config.ServiceConfig;
import com.connectsdk.service.config.ServiceDescription;
import com.connectsdk.service.roku.RokuApplicationListParser;
import com.connectsdk.service.sessions.LaunchSession;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.SAXException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class RokuService extends DeviceService implements Launcher, MediaPlayer, MediaControl, KeyControl, TextInputControl {
public static final String ID = "Roku";
private static List<String> registeredApps = new ArrayList<String>();
DIALService dialService;
static {
registeredApps.add("YouTube");
registeredApps.add("Netflix");
registeredApps.add("Amazon");
}
public static void registerApp(String appId) {
if (!registeredApps.contains(appId))
registeredApps.add(appId);
}
public RokuService(ServiceDescription serviceDescription,
ServiceConfig serviceConfig) {
super(serviceDescription, serviceConfig);
}
@Override
public void setServiceDescription(ServiceDescription serviceDescription) {
super.setServiceDescription(serviceDescription);
if (this.serviceDescription != null)
this.serviceDescription.setPort(8060);
probeForAppSupport();
}
public static DiscoveryFilter discoveryFilter() {
return new DiscoveryFilter(ID, "roku:ecp");
}
@Override
public CapabilityPriorityLevel getPriorityLevel(Class<? extends CapabilityMethods> clazz) {
if (clazz.equals(MediaPlayer.class)) {
return getMediaPlayerCapabilityLevel();
}
else if (clazz.equals(MediaControl.class)) {
return getMediaControlCapabilityLevel();
}
else if (clazz.equals(Launcher.class)) {
return getLauncherCapabilityLevel();
}
else if (clazz.equals(TextInputControl.class)) {
return getTextInputControlCapabilityLevel();
}
else if (clazz.equals(KeyControl.class)) {
return getKeyControlCapabilityLevel();
}
return CapabilityPriorityLevel.NOT_SUPPORTED;
}
@Override
public Launcher getLauncher() {
return this;
}
@Override
public CapabilityPriorityLevel getLauncherCapabilityLevel() {
return CapabilityPriorityLevel.HIGH;
}
class RokuLaunchSession extends LaunchSession {
public void close(ResponseListener<Object> responseListener) {
home(responseListener);
}
}
@Override
public void launchApp(String appId, AppLaunchListener listener) {
if (appId == null) {
Util.postError(listener, new ServiceCommandError(0,
"Must supply a valid app id", null));
return;
}
AppInfo appInfo = new AppInfo();
appInfo.setId(appId);
launchAppWithInfo(appInfo, listener);
}
@Override
public void launchAppWithInfo(AppInfo appInfo,
Launcher.AppLaunchListener listener) {
launchAppWithInfo(appInfo, null, listener);
}
@Override
public void launchAppWithInfo(final AppInfo appInfo, Object params,
final Launcher.AppLaunchListener listener) {
if (appInfo == null || appInfo.getId() == null) {
Util.postError(listener, new ServiceCommandError(-1,
"Cannot launch app without valid AppInfo object",
appInfo));
return;
}
String baseTargetURL = requestURL("launch", appInfo.getId());
String queryParams = "";
if (params != null && params instanceof JSONObject) {
JSONObject jsonParams = (JSONObject) params;
int count = 0;
Iterator<?> jsonIterator = jsonParams.keys();
while (jsonIterator.hasNext()) {
String key = (String) jsonIterator.next();
String value = null;
try {
value = jsonParams.getString(key);
} catch (JSONException ex) {
}
if (value == null)
continue;
String urlSafeKey = null;
String urlSafeValue = null;
String prefix = (count == 0) ? "?" : "&";
try {
urlSafeKey = URLEncoder.encode(key, "UTF-8");
urlSafeValue = URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException ex) {
}
if (urlSafeKey == null || urlSafeValue == null)
continue;
String appendString = prefix + urlSafeKey + "=" + urlSafeValue;
queryParams = queryParams + appendString;
count++;
}
}
String targetURL = null;
if (queryParams.length() > 0)
targetURL = baseTargetURL + queryParams;
else
targetURL = baseTargetURL;
ResponseListener<Object> responseListener = new ResponseListener<Object>() {
@Override
public void onSuccess(Object response) {
LaunchSession launchSession = new RokuLaunchSession();
launchSession.setService(RokuService.this);
launchSession.setAppId(appInfo.getId());
launchSession.setAppName(appInfo.getName());
launchSession.setSessionType(LaunchSession.LaunchSessionType.App);
Util.postSuccess(listener, launchSession);
}
@Override
public void onError(ServiceCommandError error) {
Util.postError(listener, error);
}
};
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, targetURL, null, responseListener);
request.send();
}
@Override
public void closeApp(LaunchSession launchSession,
ResponseListener<Object> listener) {
home(listener);
}
@Override
public void getAppList(final AppListListener listener) {
ResponseListener<Object> responseListener = new ResponseListener<Object>() {
@Override
public void onSuccess(Object response) {
String msg = (String) response;
SAXParserFactory saxParserFactory = SAXParserFactory
.newInstance();
InputStream stream;
try {
stream = new ByteArrayInputStream(msg.getBytes("UTF-8"));
SAXParser saxParser = saxParserFactory.newSAXParser();
RokuApplicationListParser parser = new RokuApplicationListParser();
saxParser.parse(stream, parser);
List<AppInfo> appList = parser.getApplicationList();
Util.postSuccess(listener, appList);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(ServiceCommandError error) {
Util.postError(listener, error);
}
};
String action = "query";
String param = "apps";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, responseListener);
request.setHttpMethod(ServiceCommand.TYPE_GET);
request.send();
}
@Override
public void getRunningApp(AppInfoListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public ServiceSubscription<AppInfoListener> subscribeRunningApp(
AppInfoListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
return new NotSupportedServiceSubscription<AppInfoListener>();
}
@Override
public void getAppState(LaunchSession launchSession,
AppStateListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public ServiceSubscription<AppStateListener> subscribeAppState(
LaunchSession launchSession, AppStateListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
return null;
}
@Override
public void launchBrowser(String url, Launcher.AppLaunchListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public void launchYouTube(String contentId,
Launcher.AppLaunchListener listener) {
launchYouTube(contentId, (float) 0.0, listener);
}
@Override
public void launchYouTube(String contentId, float startTime,
AppLaunchListener listener) {
if (getDIALService() != null) {
getDIALService().getLauncher().launchYouTube(contentId, startTime,
listener);
} else {
Util.postError(listener, new ServiceCommandError(
0,
"Cannot reach DIAL service for launching with provided start time",
null));
}
}
@Override
public void launchNetflix(final String contentId,
final Launcher.AppLaunchListener listener) {
getAppList(new AppListListener() {
@Override
public void onSuccess(List<AppInfo> appList) {
for (AppInfo appInfo : appList) {
if (appInfo.getName().equalsIgnoreCase("Netflix")) {
JSONObject payload = new JSONObject();
try {
payload.put("mediaType", "movie");
if (contentId != null && contentId.length() > 0)
payload.put("contentId", contentId);
} catch (JSONException e) {
e.printStackTrace();
}
launchAppWithInfo(appInfo, payload, listener);
break;
}
}
}
@Override
public void onError(ServiceCommandError error) {
Util.postError(listener, error);
}
});
}
@Override
public void launchHulu(final String contentId,
final Launcher.AppLaunchListener listener) {
getAppList(new AppListListener() {
@Override
public void onSuccess(List<AppInfo> appList) {
for (AppInfo appInfo : appList) {
if (appInfo.getName().contains("Hulu")) {
JSONObject payload = new JSONObject();
try {
payload.put("contentId", contentId);
} catch (JSONException e) {
e.printStackTrace();
}
launchAppWithInfo(appInfo, payload, listener);
break;
}
}
}
@Override
public void onError(ServiceCommandError error) {
Util.postError(listener, error);
}
});
}
@Override
public void launchAppStore(final String appId, AppLaunchListener listener) {
AppInfo appInfo = new AppInfo("11");
appInfo.setName("Channel Store");
JSONObject params = null;
try {
params = new JSONObject() {
{
put("contentId", appId);
}
};
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
launchAppWithInfo(appInfo, params, listener);
}
@Override
public KeyControl getKeyControl() {
return this;
}
@Override
public CapabilityPriorityLevel getKeyControlCapabilityLevel() {
return CapabilityPriorityLevel.HIGH;
}
@Override
public void up(ResponseListener<Object> listener) {
String action = "keypress";
String param = "Up";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void down(final ResponseListener<Object> listener) {
String action = "keypress";
String param = "Down";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void left(ResponseListener<Object> listener) {
String action = "keypress";
String param = "Left";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void right(ResponseListener<Object> listener) {
String action = "keypress";
String param = "Right";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void ok(final ResponseListener<Object> listener) {
String action = "keypress";
String param = "Select";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void back(ResponseListener<Object> listener) {
String action = "keypress";
String param = "Back";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void home(ResponseListener<Object> listener) {
String action = "keypress";
String param = "Home";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public MediaControl getMediaControl() {
return this;
}
@Override
public CapabilityPriorityLevel getMediaControlCapabilityLevel() {
return CapabilityPriorityLevel.HIGH;
}
@Override
public void play(ResponseListener<Object> listener) {
String action = "keypress";
String param = "Play";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void pause(ResponseListener<Object> listener) {
String action = "keypress";
String param = "Play";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void stop(ResponseListener<Object> listener) {
String action = null;
String param = "input?a=sto";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void rewind(ResponseListener<Object> listener) {
String action = "keypress";
String param = "Rev";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void fastForward(ResponseListener<Object> listener) {
String action = "keypress";
String param = "Fwd";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void previous(ResponseListener<Object> listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public void next(ResponseListener<Object> listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public void getDuration(DurationListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public void getPosition(PositionListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public void seek(long position, ResponseListener<Object> listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public MediaPlayer getMediaPlayer() {
return this;
}
@Override
public CapabilityPriorityLevel getMediaPlayerCapabilityLevel() {
return CapabilityPriorityLevel.HIGH;
}
@Override
public void getMediaInfo(MediaInfoListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public ServiceSubscription<MediaInfoListener> subscribeMediaInfo(
MediaInfoListener listener) {
listener.onError(ServiceCommandError.notSupported());
return null;
}
private void displayMedia(String url, String mimeType, String title,
String description, String iconSrc,
final MediaPlayer.LaunchListener listener) {
ResponseListener<Object> responseListener = new ResponseListener<Object>() {
@Override
public void onSuccess(Object response) {
LaunchSession launchSession = new RokuLaunchSession();
launchSession.setService(RokuService.this);
launchSession.setSessionType(LaunchSession.LaunchSessionType.Media);
Util.postSuccess(listener, new MediaLaunchObject(launchSession, RokuService.this));
}
@Override
public void onError(ServiceCommandError error) {
Util.postError(listener, error);
}
};
String action = "input";
String mediaFormat = mimeType;
if (mimeType.contains("/")) {
int index = mimeType.indexOf("/") + 1;
mediaFormat = mimeType.substring(index);
}
String param;
if (mimeType.contains("image")) {
param = String.format("15985?t=p&u=%s&tr=crossfade", HttpMessage.encode(url));
} else if (mimeType.contains("video")) {
param = String.format(
"15985?t=v&u=%s&k=(null)&videoName=%s&videoFormat=%s",
HttpMessage.encode(url),
TextUtils.isEmpty(title) ? "(null)" : HttpMessage.encode(title),
HttpMessage.encode(mediaFormat));
} else { // if (mimeType.contains("audio")) {
param = String
.format("15985?t=a&u=%s&k=(null)&songname=%s&artistname=%s&songformat=%s&albumarturl=%s",
HttpMessage.encode(url),
TextUtils.isEmpty(title) ? "(null)" : HttpMessage.encode(title),
TextUtils.isEmpty(description) ? "(null)" : HttpMessage.encode(description),
HttpMessage.encode(mediaFormat),
TextUtils.isEmpty(iconSrc) ? "(null)" : HttpMessage.encode(iconSrc));
}
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, responseListener);
request.send();
}
@Override
public void displayImage(String url, String mimeType, String title,
String description, String iconSrc,
MediaPlayer.LaunchListener listener) {
displayMedia(url, mimeType, title, description, iconSrc, listener);
}
@Override
public void displayImage(MediaInfo mediaInfo,
MediaPlayer.LaunchListener listener) {
String mediaUrl = null;
String mimeType = null;
String title = null;
String desc = null;
String iconSrc = null;
if (mediaInfo != null) {
mediaUrl = mediaInfo.getUrl();
mimeType = mediaInfo.getMimeType();
title = mediaInfo.getTitle();
desc = mediaInfo.getDescription();
if (mediaInfo.getImages() != null && mediaInfo.getImages().size() > 0) {
ImageInfo imageInfo = mediaInfo.getImages().get(0);
iconSrc = imageInfo.getUrl();
}
}
displayImage(mediaUrl, mimeType, title, desc, iconSrc, listener);
}
@Override
public void playMedia(String url, String mimeType, String title,
String description, String iconSrc, boolean shouldLoop,
MediaPlayer.LaunchListener listener) {
displayMedia(url, mimeType, title, description, iconSrc, listener);
}
@Override
public void playMedia(MediaInfo mediaInfo, boolean shouldLoop,
MediaPlayer.LaunchListener listener) {
String mediaUrl = null;
String mimeType = null;
String title = null;
String desc = null;
String iconSrc = null;
if (mediaInfo != null) {
mediaUrl = mediaInfo.getUrl();
mimeType = mediaInfo.getMimeType();
title = mediaInfo.getTitle();
desc = mediaInfo.getDescription();
if (mediaInfo.getImages() != null && mediaInfo.getImages().size() > 0) {
ImageInfo imageInfo = mediaInfo.getImages().get(0);
iconSrc = imageInfo.getUrl();
}
}
playMedia(mediaUrl, mimeType, title, desc, iconSrc, shouldLoop, listener);
}
@Override
public void closeMedia(LaunchSession launchSession,
ResponseListener<Object> listener) {
home(listener);
}
@Override
public TextInputControl getTextInputControl() {
return this;
}
@Override
public CapabilityPriorityLevel getTextInputControlCapabilityLevel() {
return CapabilityPriorityLevel.HIGH;
}
@Override
public ServiceSubscription<TextInputStatusListener> subscribeTextInputStatus(
TextInputStatusListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
return new NotSupportedServiceSubscription<TextInputStatusListener>();
}
@Override
public void sendText(String input) {
if (input == null || input.length() == 0) {
return;
}
ResponseListener<Object> listener = new ResponseListener<Object>() {
@Override
public void onSuccess(Object response) {
// TODO Auto-generated method stub
}
@Override
public void onError(ServiceCommandError error) {
// TODO Auto-generated method stub
}
};
String action = "keypress";
String param = null;
try {
param = "Lit_" + URLEncoder.encode(input, "UTF-8");
} catch (UnsupportedEncodingException e) {
// This can be safetly ignored since it isn't a dynamic encoding.
e.printStackTrace();
}
String uri = requestURL(action, param);
Log.d(Util.T, "RokuService::send() | uri = " + uri);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void sendKeyCode(KeyCode keyCode, ResponseListener<Object> listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public void sendEnter() {
ResponseListener<Object> listener = new ResponseListener<Object>() {
@Override
public void onSuccess(Object response) {
// TODO Auto-generated method stub
}
@Override
public void onError(ServiceCommandError error) {
// TODO Auto-generated method stub
}
};
String action = "keypress";
String param = "Enter";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void sendDelete() {
ResponseListener<Object> listener = new ResponseListener<Object>() {
@Override
public void onSuccess(Object response) {
// TODO Auto-generated method stub
}
@Override
public void onError(ServiceCommandError error) {
// TODO Auto-generated method stub
}
};
String action = "keypress";
String param = "Backspace";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void unsubscribe(URLServiceSubscription<?> subscription) {
}
@Override
public void sendCommand(final ServiceCommand<?> mCommand) {
Util.runInBackground(new Runnable() {
@SuppressWarnings("unchecked")
@Override
public void run() {
ServiceCommand<ResponseListener<Object>> command = (ServiceCommand<ResponseListener<Object>>) mCommand;
Object payload = command.getPayload();
try {
Log.d("", "RESP " + command.getTarget());
HttpConnection connection = HttpConnection.newInstance(URI.create(command.getTarget()));
if (command.getHttpMethod().equalsIgnoreCase(ServiceCommand.TYPE_POST)) {
connection.setMethod(HttpConnection.Method.POST);
if (payload != null) {
connection.setPayload(payload.toString());
}
}
connection.execute();
int code = connection.getResponseCode();
Log.d("", "RESP " + code);
if (code == 200 || code == 201) {
Util.postSuccess(command.getResponseListener(), connection.getResponseString());
} else {
Util.postError(command.getResponseListener(), ServiceCommandError.getError(code));
}
} catch (IOException e) {
e.printStackTrace();
Util.postError(command.getResponseListener(), new ServiceCommandError(0, e.getMessage(), null));
}
}
});
}
private String requestURL(String action, String parameter) {
StringBuilder sb = new StringBuilder();
sb.append("http://");
sb.append(serviceDescription.getIpAddress()).append(":");
sb.append(serviceDescription.getPort()).append("/");
if (action != null)
sb.append(action);
if (parameter != null)
sb.append("/").append(parameter);
return sb.toString();
}
private void probeForAppSupport() {
getAppList(new AppListListener() {
@Override
public void onError(ServiceCommandError error) {
}
@Override
public void onSuccess(List<AppInfo> object) {
List<String> appsToAdd = new ArrayList<String>();
for (String probe : registeredApps) {
for (AppInfo app : object) {
if (app.getName().contains(probe)) {
appsToAdd.add("Launcher." + probe);
appsToAdd.add("Launcher." + probe + ".Params");
}
}
}
addCapabilities(appsToAdd);
}
});
}
@Override
protected void updateCapabilities() {
List<String> capabilities = new ArrayList<String>();
capabilities.add(Up);
capabilities.add(Down);
capabilities.add(Left);
capabilities.add(Right);
capabilities.add(OK);
capabilities.add(Back);
capabilities.add(Home);
capabilities.add(Send_Key);
capabilities.add(Application);
capabilities.add(Application_Params);
capabilities.add(Application_List);
capabilities.add(AppStore);
capabilities.add(AppStore_Params);
capabilities.add(Application_Close);
capabilities.add(Display_Image);
capabilities.add(Play_Video);
capabilities.add(Play_Audio);
capabilities.add(Close);
capabilities.add(MetaData_Title);
capabilities.add(FastForward);
capabilities.add(Rewind);
capabilities.add(Play);
capabilities.add(Pause);
capabilities.add(Send);
capabilities.add(Send_Delete);
capabilities.add(Send_Enter);
setCapabilities(capabilities);
}
@Override
public void getPlayState(PlayStateListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public ServiceSubscription<PlayStateListener> subscribePlayState(
PlayStateListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
return null;
}
@Override
public boolean isConnectable() {
return true;
}
@Override
public boolean isConnected() {
return connected;
}
@Override
public void connect() {
// TODO: Fix this for roku. Right now it is using the InetAddress
// reachable function. Need to use an HTTP Method.
// mServiceReachability =
// DeviceServiceReachability.getReachability(serviceDescription.getIpAddress(),
// this);
// mServiceReachability.start();
connected = true;
reportConnected(true);
}
@Override
public void disconnect() {
connected = false;
if (mServiceReachability != null)
mServiceReachability.stop();
Util.runOnUI(new Runnable() {
@Override
public void run() {
if (listener != null)
listener.onDisconnect(RokuService.this, null);
}
});
}
@Override
public void onLoseReachability(DeviceServiceReachability reachability) {
if (connected) {
disconnect();
} else {
if (mServiceReachability != null)
mServiceReachability.stop();
}
}
public DIALService getDIALService() {
if (dialService == null) {
DiscoveryManager discoveryManager = DiscoveryManager.getInstance();
ConnectableDevice device = discoveryManager.getAllDevices().get(
serviceDescription.getIpAddress());
if (device != null) {
DIALService foundService = null;
for (DeviceService service : device.getServices()) {
if (DIALService.class.isAssignableFrom(service.getClass())) {
foundService = (DIALService) service;
break;
}
}
dialService = foundService;
}
}
return dialService;
}
}
| src/com/connectsdk/service/RokuService.java | /*
* RokuService
* Connect SDK
*
* Copyright (c) 2014 LG Electronics.
* Created by Hyun Kook Khang on 26 Feb 2014
*
* 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.connectsdk.service;
import android.text.TextUtils;
import android.util.Log;
import com.connectsdk.core.AppInfo;
import com.connectsdk.core.ImageInfo;
import com.connectsdk.core.MediaInfo;
import com.connectsdk.core.Util;
import com.connectsdk.device.ConnectableDevice;
import com.connectsdk.discovery.DiscoveryFilter;
import com.connectsdk.discovery.DiscoveryManager;
import com.connectsdk.etc.helper.DeviceServiceReachability;
import com.connectsdk.etc.helper.HttpConnection;
import com.connectsdk.etc.helper.HttpMessage;
import com.connectsdk.service.capability.CapabilityMethods;
import com.connectsdk.service.capability.KeyControl;
import com.connectsdk.service.capability.Launcher;
import com.connectsdk.service.capability.MediaControl;
import com.connectsdk.service.capability.MediaPlayer;
import com.connectsdk.service.capability.TextInputControl;
import com.connectsdk.service.capability.listeners.ResponseListener;
import com.connectsdk.service.command.NotSupportedServiceSubscription;
import com.connectsdk.service.command.ServiceCommand;
import com.connectsdk.service.command.ServiceCommandError;
import com.connectsdk.service.command.ServiceSubscription;
import com.connectsdk.service.command.URLServiceSubscription;
import com.connectsdk.service.config.ServiceConfig;
import com.connectsdk.service.config.ServiceDescription;
import com.connectsdk.service.roku.RokuApplicationListParser;
import com.connectsdk.service.sessions.LaunchSession;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.SAXException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class RokuService extends DeviceService implements Launcher, MediaPlayer, MediaControl, KeyControl, TextInputControl {
public static final String ID = "Roku";
private static List<String> registeredApps = new ArrayList<String>();
DIALService dialService;
static {
registeredApps.add("YouTube");
registeredApps.add("Netflix");
registeredApps.add("Amazon");
}
public static void registerApp(String appId) {
if (!registeredApps.contains(appId))
registeredApps.add(appId);
}
public RokuService(ServiceDescription serviceDescription,
ServiceConfig serviceConfig) {
super(serviceDescription, serviceConfig);
}
@Override
public void setServiceDescription(ServiceDescription serviceDescription) {
super.setServiceDescription(serviceDescription);
if (this.serviceDescription != null)
this.serviceDescription.setPort(8060);
probeForAppSupport();
}
public static DiscoveryFilter discoveryFilter() {
return new DiscoveryFilter(ID, "roku:ecp");
}
@Override
public CapabilityPriorityLevel getPriorityLevel(Class<? extends CapabilityMethods> clazz) {
if (clazz.equals(MediaPlayer.class)) {
return getMediaPlayerCapabilityLevel();
}
else if (clazz.equals(MediaControl.class)) {
return getMediaControlCapabilityLevel();
}
else if (clazz.equals(Launcher.class)) {
return getLauncherCapabilityLevel();
}
else if (clazz.equals(TextInputControl.class)) {
return getTextInputControlCapabilityLevel();
}
else if (clazz.equals(KeyControl.class)) {
return getKeyControlCapabilityLevel();
}
return CapabilityPriorityLevel.NOT_SUPPORTED;
}
@Override
public Launcher getLauncher() {
return this;
}
@Override
public CapabilityPriorityLevel getLauncherCapabilityLevel() {
return CapabilityPriorityLevel.HIGH;
}
class RokuLaunchSession extends LaunchSession {
String appName;
RokuService service;
RokuLaunchSession(RokuService service) {
this.service = service;
}
RokuLaunchSession(RokuService service, String appId, String appName) {
this.service = service;
this.appId = appId;
this.appName = appName;
}
RokuLaunchSession(RokuService service, JSONObject obj)
throws JSONException {
this.service = service;
fromJSONObject(obj);
}
public void close(ResponseListener<Object> responseListener) {
home(responseListener);
}
@Override
public JSONObject toJSONObject() throws JSONException {
JSONObject obj = super.toJSONObject();
obj.put("type", "roku");
obj.put("appName", appName);
return obj;
}
@Override
public void fromJSONObject(JSONObject obj) throws JSONException {
super.fromJSONObject(obj);
appName = obj.optString("appName");
}
}
@Override
public void launchApp(String appId, AppLaunchListener listener) {
if (appId == null) {
Util.postError(listener, new ServiceCommandError(0,
"Must supply a valid app id", null));
return;
}
AppInfo appInfo = new AppInfo();
appInfo.setId(appId);
launchAppWithInfo(appInfo, listener);
}
@Override
public void launchAppWithInfo(AppInfo appInfo,
Launcher.AppLaunchListener listener) {
launchAppWithInfo(appInfo, null, listener);
}
@Override
public void launchAppWithInfo(final AppInfo appInfo, Object params,
final Launcher.AppLaunchListener listener) {
if (appInfo == null || appInfo.getId() == null) {
Util.postError(listener, new ServiceCommandError(-1,
"Cannot launch app without valid AppInfo object",
appInfo));
return;
}
String baseTargetURL = requestURL("launch", appInfo.getId());
String queryParams = "";
if (params != null && params instanceof JSONObject) {
JSONObject jsonParams = (JSONObject) params;
int count = 0;
Iterator<?> jsonIterator = jsonParams.keys();
while (jsonIterator.hasNext()) {
String key = (String) jsonIterator.next();
String value = null;
try {
value = jsonParams.getString(key);
} catch (JSONException ex) {
}
if (value == null)
continue;
String urlSafeKey = null;
String urlSafeValue = null;
String prefix = (count == 0) ? "?" : "&";
try {
urlSafeKey = URLEncoder.encode(key, "UTF-8");
urlSafeValue = URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException ex) {
}
if (urlSafeKey == null || urlSafeValue == null)
continue;
String appendString = prefix + urlSafeKey + "=" + urlSafeValue;
queryParams = queryParams + appendString;
count++;
}
}
String targetURL = null;
if (queryParams.length() > 0)
targetURL = baseTargetURL + queryParams;
else
targetURL = baseTargetURL;
ResponseListener<Object> responseListener = new ResponseListener<Object>() {
@Override
public void onSuccess(Object response) {
Util.postSuccess(listener, new RokuLaunchSession(
RokuService.this, appInfo.getId(), appInfo.getName()));
}
@Override
public void onError(ServiceCommandError error) {
Util.postError(listener, error);
}
};
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, targetURL, null, responseListener);
request.send();
}
@Override
public void closeApp(LaunchSession launchSession,
ResponseListener<Object> listener) {
home(listener);
}
@Override
public void getAppList(final AppListListener listener) {
ResponseListener<Object> responseListener = new ResponseListener<Object>() {
@Override
public void onSuccess(Object response) {
String msg = (String) response;
SAXParserFactory saxParserFactory = SAXParserFactory
.newInstance();
InputStream stream;
try {
stream = new ByteArrayInputStream(msg.getBytes("UTF-8"));
SAXParser saxParser = saxParserFactory.newSAXParser();
RokuApplicationListParser parser = new RokuApplicationListParser();
saxParser.parse(stream, parser);
List<AppInfo> appList = parser.getApplicationList();
Util.postSuccess(listener, appList);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(ServiceCommandError error) {
Util.postError(listener, error);
}
};
String action = "query";
String param = "apps";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, responseListener);
request.setHttpMethod(ServiceCommand.TYPE_GET);
request.send();
}
@Override
public void getRunningApp(AppInfoListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public ServiceSubscription<AppInfoListener> subscribeRunningApp(
AppInfoListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
return new NotSupportedServiceSubscription<AppInfoListener>();
}
@Override
public void getAppState(LaunchSession launchSession,
AppStateListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public ServiceSubscription<AppStateListener> subscribeAppState(
LaunchSession launchSession, AppStateListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
return null;
}
@Override
public void launchBrowser(String url, Launcher.AppLaunchListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public void launchYouTube(String contentId,
Launcher.AppLaunchListener listener) {
launchYouTube(contentId, (float) 0.0, listener);
}
@Override
public void launchYouTube(String contentId, float startTime,
AppLaunchListener listener) {
if (getDIALService() != null) {
getDIALService().getLauncher().launchYouTube(contentId, startTime,
listener);
} else {
Util.postError(listener, new ServiceCommandError(
0,
"Cannot reach DIAL service for launching with provided start time",
null));
}
}
@Override
public void launchNetflix(final String contentId,
final Launcher.AppLaunchListener listener) {
getAppList(new AppListListener() {
@Override
public void onSuccess(List<AppInfo> appList) {
for (AppInfo appInfo : appList) {
if (appInfo.getName().equalsIgnoreCase("Netflix")) {
JSONObject payload = new JSONObject();
try {
payload.put("mediaType", "movie");
if (contentId != null && contentId.length() > 0)
payload.put("contentId", contentId);
} catch (JSONException e) {
e.printStackTrace();
}
launchAppWithInfo(appInfo, payload, listener);
break;
}
}
}
@Override
public void onError(ServiceCommandError error) {
Util.postError(listener, error);
}
});
}
@Override
public void launchHulu(final String contentId,
final Launcher.AppLaunchListener listener) {
getAppList(new AppListListener() {
@Override
public void onSuccess(List<AppInfo> appList) {
for (AppInfo appInfo : appList) {
if (appInfo.getName().contains("Hulu")) {
JSONObject payload = new JSONObject();
try {
payload.put("contentId", contentId);
} catch (JSONException e) {
e.printStackTrace();
}
launchAppWithInfo(appInfo, payload, listener);
break;
}
}
}
@Override
public void onError(ServiceCommandError error) {
Util.postError(listener, error);
}
});
}
@Override
public void launchAppStore(final String appId, AppLaunchListener listener) {
AppInfo appInfo = new AppInfo("11");
appInfo.setName("Channel Store");
JSONObject params = null;
try {
params = new JSONObject() {
{
put("contentId", appId);
}
};
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
launchAppWithInfo(appInfo, params, listener);
}
@Override
public KeyControl getKeyControl() {
return this;
}
@Override
public CapabilityPriorityLevel getKeyControlCapabilityLevel() {
return CapabilityPriorityLevel.HIGH;
}
@Override
public void up(ResponseListener<Object> listener) {
String action = "keypress";
String param = "Up";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void down(final ResponseListener<Object> listener) {
String action = "keypress";
String param = "Down";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void left(ResponseListener<Object> listener) {
String action = "keypress";
String param = "Left";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void right(ResponseListener<Object> listener) {
String action = "keypress";
String param = "Right";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void ok(final ResponseListener<Object> listener) {
String action = "keypress";
String param = "Select";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void back(ResponseListener<Object> listener) {
String action = "keypress";
String param = "Back";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void home(ResponseListener<Object> listener) {
String action = "keypress";
String param = "Home";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public MediaControl getMediaControl() {
return this;
}
@Override
public CapabilityPriorityLevel getMediaControlCapabilityLevel() {
return CapabilityPriorityLevel.HIGH;
}
@Override
public void play(ResponseListener<Object> listener) {
String action = "keypress";
String param = "Play";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void pause(ResponseListener<Object> listener) {
String action = "keypress";
String param = "Play";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void stop(ResponseListener<Object> listener) {
String action = null;
String param = "input?a=sto";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void rewind(ResponseListener<Object> listener) {
String action = "keypress";
String param = "Rev";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void fastForward(ResponseListener<Object> listener) {
String action = "keypress";
String param = "Fwd";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void previous(ResponseListener<Object> listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public void next(ResponseListener<Object> listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public void getDuration(DurationListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public void getPosition(PositionListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public void seek(long position, ResponseListener<Object> listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public MediaPlayer getMediaPlayer() {
return this;
}
@Override
public CapabilityPriorityLevel getMediaPlayerCapabilityLevel() {
return CapabilityPriorityLevel.HIGH;
}
@Override
public void getMediaInfo(MediaInfoListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public ServiceSubscription<MediaInfoListener> subscribeMediaInfo(
MediaInfoListener listener) {
listener.onError(ServiceCommandError.notSupported());
return null;
}
private void displayMedia(String url, String mimeType, String title,
String description, String iconSrc,
final MediaPlayer.LaunchListener listener) {
ResponseListener<Object> responseListener = new ResponseListener<Object>() {
@Override
public void onSuccess(Object response) {
Util.postSuccess(listener, new MediaLaunchObject(
new RokuLaunchSession(RokuService.this),
RokuService.this));
}
@Override
public void onError(ServiceCommandError error) {
Util.postError(listener, error);
}
};
String action = "input";
String mediaFormat = mimeType;
if (mimeType.contains("/")) {
int index = mimeType.indexOf("/") + 1;
mediaFormat = mimeType.substring(index);
}
String param;
if (mimeType.contains("image")) {
param = String.format("15985?t=p&u=%s&tr=crossfade", HttpMessage.encode(url));
} else if (mimeType.contains("video")) {
param = String.format(
"15985?t=v&u=%s&k=(null)&videoName=%s&videoFormat=%s",
HttpMessage.encode(url),
TextUtils.isEmpty(title) ? "(null)" : HttpMessage.encode(title),
HttpMessage.encode(mediaFormat));
} else { // if (mimeType.contains("audio")) {
param = String
.format("15985?t=a&u=%s&k=(null)&songname=%s&artistname=%s&songformat=%s&albumarturl=%s",
HttpMessage.encode(url),
TextUtils.isEmpty(title) ? "(null)" : HttpMessage.encode(title),
TextUtils.isEmpty(description) ? "(null)" : HttpMessage.encode(description),
HttpMessage.encode(mediaFormat),
TextUtils.isEmpty(iconSrc) ? "(null)" : HttpMessage.encode(iconSrc));
}
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, responseListener);
request.send();
}
@Override
public void displayImage(String url, String mimeType, String title,
String description, String iconSrc,
MediaPlayer.LaunchListener listener) {
displayMedia(url, mimeType, title, description, iconSrc, listener);
}
@Override
public void displayImage(MediaInfo mediaInfo,
MediaPlayer.LaunchListener listener) {
String mediaUrl = null;
String mimeType = null;
String title = null;
String desc = null;
String iconSrc = null;
if (mediaInfo != null) {
mediaUrl = mediaInfo.getUrl();
mimeType = mediaInfo.getMimeType();
title = mediaInfo.getTitle();
desc = mediaInfo.getDescription();
if (mediaInfo.getImages() != null && mediaInfo.getImages().size() > 0) {
ImageInfo imageInfo = mediaInfo.getImages().get(0);
iconSrc = imageInfo.getUrl();
}
}
displayImage(mediaUrl, mimeType, title, desc, iconSrc, listener);
}
@Override
public void playMedia(String url, String mimeType, String title,
String description, String iconSrc, boolean shouldLoop,
MediaPlayer.LaunchListener listener) {
displayMedia(url, mimeType, title, description, iconSrc, listener);
}
@Override
public void playMedia(MediaInfo mediaInfo, boolean shouldLoop,
MediaPlayer.LaunchListener listener) {
String mediaUrl = null;
String mimeType = null;
String title = null;
String desc = null;
String iconSrc = null;
if (mediaInfo != null) {
mediaUrl = mediaInfo.getUrl();
mimeType = mediaInfo.getMimeType();
title = mediaInfo.getTitle();
desc = mediaInfo.getDescription();
if (mediaInfo.getImages() != null && mediaInfo.getImages().size() > 0) {
ImageInfo imageInfo = mediaInfo.getImages().get(0);
iconSrc = imageInfo.getUrl();
}
}
playMedia(mediaUrl, mimeType, title, desc, iconSrc, shouldLoop, listener);
}
@Override
public void closeMedia(LaunchSession launchSession,
ResponseListener<Object> listener) {
home(listener);
}
@Override
public TextInputControl getTextInputControl() {
return this;
}
@Override
public CapabilityPriorityLevel getTextInputControlCapabilityLevel() {
return CapabilityPriorityLevel.HIGH;
}
@Override
public ServiceSubscription<TextInputStatusListener> subscribeTextInputStatus(
TextInputStatusListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
return new NotSupportedServiceSubscription<TextInputStatusListener>();
}
@Override
public void sendText(String input) {
if (input == null || input.length() == 0) {
return;
}
ResponseListener<Object> listener = new ResponseListener<Object>() {
@Override
public void onSuccess(Object response) {
// TODO Auto-generated method stub
}
@Override
public void onError(ServiceCommandError error) {
// TODO Auto-generated method stub
}
};
String action = "keypress";
String param = null;
try {
param = "Lit_" + URLEncoder.encode(input, "UTF-8");
} catch (UnsupportedEncodingException e) {
// This can be safetly ignored since it isn't a dynamic encoding.
e.printStackTrace();
}
String uri = requestURL(action, param);
Log.d(Util.T, "RokuService::send() | uri = " + uri);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void sendKeyCode(KeyCode keyCode, ResponseListener<Object> listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public void sendEnter() {
ResponseListener<Object> listener = new ResponseListener<Object>() {
@Override
public void onSuccess(Object response) {
// TODO Auto-generated method stub
}
@Override
public void onError(ServiceCommandError error) {
// TODO Auto-generated method stub
}
};
String action = "keypress";
String param = "Enter";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void sendDelete() {
ResponseListener<Object> listener = new ResponseListener<Object>() {
@Override
public void onSuccess(Object response) {
// TODO Auto-generated method stub
}
@Override
public void onError(ServiceCommandError error) {
// TODO Auto-generated method stub
}
};
String action = "keypress";
String param = "Backspace";
String uri = requestURL(action, param);
ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
this, uri, null, listener);
request.send();
}
@Override
public void unsubscribe(URLServiceSubscription<?> subscription) {
}
@Override
public void sendCommand(final ServiceCommand<?> mCommand) {
Util.runInBackground(new Runnable() {
@SuppressWarnings("unchecked")
@Override
public void run() {
ServiceCommand<ResponseListener<Object>> command = (ServiceCommand<ResponseListener<Object>>) mCommand;
Object payload = command.getPayload();
try {
Log.d("", "RESP " + command.getTarget());
HttpConnection connection = HttpConnection.newInstance(URI.create(command.getTarget()));
if (command.getHttpMethod().equalsIgnoreCase(ServiceCommand.TYPE_POST)) {
connection.setMethod(HttpConnection.Method.POST);
if (payload != null) {
connection.setPayload(payload.toString());
}
}
connection.execute();
int code = connection.getResponseCode();
Log.d("", "RESP " + code);
if (code == 200 || code == 201) {
Util.postSuccess(command.getResponseListener(), connection.getResponseString());
} else {
Util.postError(command.getResponseListener(), ServiceCommandError.getError(code));
}
} catch (IOException e) {
e.printStackTrace();
Util.postError(command.getResponseListener(), new ServiceCommandError(0, e.getMessage(), null));
}
}
});
}
private String requestURL(String action, String parameter) {
StringBuilder sb = new StringBuilder();
sb.append("http://");
sb.append(serviceDescription.getIpAddress()).append(":");
sb.append(serviceDescription.getPort()).append("/");
if (action != null)
sb.append(action);
if (parameter != null)
sb.append("/").append(parameter);
return sb.toString();
}
private void probeForAppSupport() {
getAppList(new AppListListener() {
@Override
public void onError(ServiceCommandError error) {
}
@Override
public void onSuccess(List<AppInfo> object) {
List<String> appsToAdd = new ArrayList<String>();
for (String probe : registeredApps) {
for (AppInfo app : object) {
if (app.getName().contains(probe)) {
appsToAdd.add("Launcher." + probe);
appsToAdd.add("Launcher." + probe + ".Params");
}
}
}
addCapabilities(appsToAdd);
}
});
}
@Override
protected void updateCapabilities() {
List<String> capabilities = new ArrayList<String>();
capabilities.add(Up);
capabilities.add(Down);
capabilities.add(Left);
capabilities.add(Right);
capabilities.add(OK);
capabilities.add(Back);
capabilities.add(Home);
capabilities.add(Send_Key);
capabilities.add(Application);
capabilities.add(Application_Params);
capabilities.add(Application_List);
capabilities.add(AppStore);
capabilities.add(AppStore_Params);
capabilities.add(Application_Close);
capabilities.add(Display_Image);
capabilities.add(Play_Video);
capabilities.add(Play_Audio);
capabilities.add(Close);
capabilities.add(MetaData_Title);
capabilities.add(FastForward);
capabilities.add(Rewind);
capabilities.add(Play);
capabilities.add(Pause);
capabilities.add(Send);
capabilities.add(Send_Delete);
capabilities.add(Send_Enter);
setCapabilities(capabilities);
}
@Override
public void getPlayState(PlayStateListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
}
@Override
public ServiceSubscription<PlayStateListener> subscribePlayState(
PlayStateListener listener) {
Util.postError(listener, ServiceCommandError.notSupported());
return null;
}
@Override
public boolean isConnectable() {
return true;
}
@Override
public boolean isConnected() {
return connected;
}
@Override
public void connect() {
// TODO: Fix this for roku. Right now it is using the InetAddress
// reachable function. Need to use an HTTP Method.
// mServiceReachability =
// DeviceServiceReachability.getReachability(serviceDescription.getIpAddress(),
// this);
// mServiceReachability.start();
connected = true;
reportConnected(true);
}
@Override
public void disconnect() {
connected = false;
if (mServiceReachability != null)
mServiceReachability.stop();
Util.runOnUI(new Runnable() {
@Override
public void run() {
if (listener != null)
listener.onDisconnect(RokuService.this, null);
}
});
}
@Override
public void onLoseReachability(DeviceServiceReachability reachability) {
if (connected) {
disconnect();
} else {
if (mServiceReachability != null)
mServiceReachability.stop();
}
}
public DIALService getDIALService() {
if (dialService == null) {
DiscoveryManager discoveryManager = DiscoveryManager.getInstance();
ConnectableDevice device = discoveryManager.getAllDevices().get(
serviceDescription.getIpAddress());
if (device != null) {
DIALService foundService = null;
for (DeviceService service : device.getServices()) {
if (DIALService.class.isAssignableFrom(service.getClass())) {
foundService = (DIALService) service;
break;
}
}
dialService = foundService;
}
}
return dialService;
}
}
| Fix RokuLaunchSession implementation
| src/com/connectsdk/service/RokuService.java | Fix RokuLaunchSession implementation | <ide><path>rc/com/connectsdk/service/RokuService.java
<ide> /*
<ide> * RokuService
<ide> * Connect SDK
<del> *
<add> *
<ide> * Copyright (c) 2014 LG Electronics.
<ide> * Created by Hyun Kook Khang on 26 Feb 2014
<del> *
<add> *
<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> * You may obtain a copy of the License at
<ide> }
<ide> return CapabilityPriorityLevel.NOT_SUPPORTED;
<ide> }
<del>
<add>
<ide> @Override
<ide> public Launcher getLauncher() {
<ide> return this;
<ide> }
<ide>
<ide> class RokuLaunchSession extends LaunchSession {
<del> String appName;
<del> RokuService service;
<del>
<del> RokuLaunchSession(RokuService service) {
<del> this.service = service;
<del> }
<del>
<del> RokuLaunchSession(RokuService service, String appId, String appName) {
<del> this.service = service;
<del> this.appId = appId;
<del> this.appName = appName;
<del> }
<del>
<del> RokuLaunchSession(RokuService service, JSONObject obj)
<del> throws JSONException {
<del> this.service = service;
<del> fromJSONObject(obj);
<del> }
<ide>
<ide> public void close(ResponseListener<Object> responseListener) {
<ide> home(responseListener);
<del> }
<del>
<del> @Override
<del> public JSONObject toJSONObject() throws JSONException {
<del> JSONObject obj = super.toJSONObject();
<del> obj.put("type", "roku");
<del> obj.put("appName", appName);
<del> return obj;
<del> }
<del>
<del> @Override
<del> public void fromJSONObject(JSONObject obj) throws JSONException {
<del> super.fromJSONObject(obj);
<del> appName = obj.optString("appName");
<ide> }
<ide> }
<ide>
<ide>
<ide> @Override
<ide> public void onSuccess(Object response) {
<del> Util.postSuccess(listener, new RokuLaunchSession(
<del> RokuService.this, appInfo.getId(), appInfo.getName()));
<add> LaunchSession launchSession = new RokuLaunchSession();
<add> launchSession.setService(RokuService.this);
<add> launchSession.setAppId(appInfo.getId());
<add> launchSession.setAppName(appInfo.getName());
<add> launchSession.setSessionType(LaunchSession.LaunchSessionType.App);
<add> Util.postSuccess(listener, launchSession);
<ide> }
<ide>
<ide> @Override
<ide>
<ide> @Override
<ide> public void onSuccess(Object response) {
<del> Util.postSuccess(listener, new MediaLaunchObject(
<del> new RokuLaunchSession(RokuService.this),
<del> RokuService.this));
<add> LaunchSession launchSession = new RokuLaunchSession();
<add> launchSession.setService(RokuService.this);
<add> launchSession.setSessionType(LaunchSession.LaunchSessionType.Media);
<add> Util.postSuccess(listener, new MediaLaunchObject(launchSession, RokuService.this));
<ide> }
<ide>
<ide> @Override
<ide> param = String.format(
<ide> "15985?t=v&u=%s&k=(null)&videoName=%s&videoFormat=%s",
<ide> HttpMessage.encode(url),
<del> TextUtils.isEmpty(title) ? "(null)" : HttpMessage.encode(title),
<add> TextUtils.isEmpty(title) ? "(null)" : HttpMessage.encode(title),
<ide> HttpMessage.encode(mediaFormat));
<ide> } else { // if (mimeType.contains("audio")) {
<ide> param = String
<ide> .format("15985?t=a&u=%s&k=(null)&songname=%s&artistname=%s&songformat=%s&albumarturl=%s",
<ide> HttpMessage.encode(url),
<ide> TextUtils.isEmpty(title) ? "(null)" : HttpMessage.encode(title),
<del> TextUtils.isEmpty(description) ? "(null)" : HttpMessage.encode(description),
<del> HttpMessage.encode(mediaFormat),
<del> TextUtils.isEmpty(iconSrc) ? "(null)" : HttpMessage.encode(iconSrc));
<add> TextUtils.isEmpty(description) ? "(null)" : HttpMessage.encode(description),
<add> HttpMessage.encode(mediaFormat),
<add> TextUtils.isEmpty(iconSrc) ? "(null)" : HttpMessage.encode(iconSrc));
<ide> }
<ide>
<ide> String uri = requestURL(action, param); |
|
Java | apache-2.0 | 030ccb9502c5cc13013cee5bd6fa35a8f47ddce0 | 0 | leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere | /*
* 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.shardingsphere.core.optimize.result;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import lombok.Getter;
import org.apache.shardingsphere.core.parse.lexer.token.DefaultKeyword;
import org.apache.shardingsphere.core.parse.parser.expression.SQLExpression;
import org.apache.shardingsphere.core.parse.parser.expression.SQLNumberExpression;
import org.apache.shardingsphere.core.parse.parser.expression.SQLPlaceholderExpression;
import org.apache.shardingsphere.core.parse.parser.expression.SQLTextExpression;
import org.apache.shardingsphere.core.rule.DataNode;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* Insert column values.
*
* @author panjuan
*/
@Getter
public final class InsertColumnValues {
private final DefaultKeyword type;
private final Set<String> columnNames = new LinkedHashSet<>();
private final List<InsertColumnValue> columnValues = new LinkedList<>();
public InsertColumnValues(final DefaultKeyword type, final List<String> columnNames) {
this.type = type;
this.columnNames.addAll(columnNames);
}
/**
* Add insert column value.
*
* @param columnValues column values
* @param columnParameters column parameters
*/
public void addInsertColumnValue(final List<SQLExpression> columnValues, final List<Object> columnParameters) {
this.columnValues.add(new InsertColumnValue(columnValues, columnParameters));
}
@Getter
public final class InsertColumnValue {
private final List<SQLExpression> values = new LinkedList<>();
private final List<Object> parameters = new LinkedList<>();
private final List<DataNode> dataNodes = new LinkedList<>();
public InsertColumnValue(final List<SQLExpression> values, final List<Object> parameters) {
this.values.addAll(values);
this.parameters.addAll(parameters);
}
/**
* Set column value.
*
* @param columnName column name
* @param columnValue column value
*/
public void setColumnValue(final String columnName, final Object columnValue) {
SQLExpression sqlExpression = values.get(getColumnIndex(columnName));
if (sqlExpression instanceof SQLPlaceholderExpression) {
parameters.set(getParameterIndex(sqlExpression), columnValue);
} else {
SQLExpression columnExpression = String.class == columnValue.getClass() ? new SQLTextExpression(String.valueOf(columnValue)) : new SQLNumberExpression((Number) columnValue);
values.set(getColumnIndex(columnName), columnExpression);
}
}
private int getColumnIndex(final String columnName) {
return new ArrayList<>(columnNames).indexOf(columnName);
}
private int getParameterIndex(final SQLExpression sqlExpression) {
List<SQLExpression> sqlPlaceholderExpressions = new ArrayList<>(Collections2.filter(values, new Predicate<SQLExpression>() {
@Override
public boolean apply(final SQLExpression input) {
return input instanceof SQLPlaceholderExpression;
}
}));
return sqlPlaceholderExpressions.indexOf(sqlExpression);
}
/**
* Get column value.
*
* @param columnName column Name
* @return column value
*/
public Object getColumnValue(final String columnName) {
SQLExpression sqlExpression = values.get(getColumnIndex(columnName));
if (sqlExpression instanceof SQLPlaceholderExpression) {
return parameters.get(getParameterIndex(sqlExpression));
} else if (sqlExpression instanceof SQLTextExpression) {
return ((SQLTextExpression) sqlExpression).getText();
} else {
return ((SQLNumberExpression) sqlExpression).getNumber();
}
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
if (DefaultKeyword.SET == type) {
fillResultBySet(result);
} else {
fillResultByValues(result);
}
return result.toString();
}
private void fillResultBySet(final StringBuilder result) {
for (int i = 0; i < columnNames.size(); i++) {
result.append(String.format("%s = %s", new ArrayList<>(columnNames).get(i), getColumnSQLExpressionValue(i))).append(", ");
}
result.delete(result.length() - 2, result.length());
}
private void fillResultByValues(final StringBuilder result) {
result.append("(");
for (int i = 0; i < columnNames.size(); i++) {
result.append(getColumnSQLExpressionValue(i)).append(", ");
}
result.delete(result.length() - 2, result.length()).append(")");
}
private String getColumnSQLExpressionValue(final int columnValueIndex) {
SQLExpression sqlExpression = values.get(columnValueIndex);
if (sqlExpression instanceof SQLPlaceholderExpression) {
return "?";
} else if (sqlExpression instanceof SQLTextExpression) {
return String.format("'%s'", ((SQLTextExpression) sqlExpression).getText());
} else {
return String.valueOf(((SQLNumberExpression) sqlExpression).getNumber());
}
}
}
}
| sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/InsertColumnValues.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.shardingsphere.core.optimize.result;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import lombok.Getter;
import org.apache.shardingsphere.core.parse.lexer.token.DefaultKeyword;
import org.apache.shardingsphere.core.parse.parser.expression.SQLExpression;
import org.apache.shardingsphere.core.parse.parser.expression.SQLNumberExpression;
import org.apache.shardingsphere.core.parse.parser.expression.SQLPlaceholderExpression;
import org.apache.shardingsphere.core.parse.parser.expression.SQLTextExpression;
import org.apache.shardingsphere.core.rule.DataNode;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* Insert column values.
*
* @author panjuan
*/
@Getter
public final class InsertColumnValues {
private final DefaultKeyword type;
private final Set<String> columnNames = new LinkedHashSet<>();
private final List<InsertColumnValue> columnValues = new LinkedList<>();
public InsertColumnValues(final DefaultKeyword type, final List<String> columnNames) {
this.type = type;
this.columnNames.addAll(columnNames);
}
/**
* Add insert column value.
*
* @param columnValues column values
* @param columnParameters column parameters
*/
public void addInsertColumnValue(final List<SQLExpression> columnValues, final List<Object> columnParameters) {
this.columnValues.add(new InsertColumnValue(columnValues, columnParameters));
}
/**
* Get column name.
*
* @param columnIndex column index
* @return column name
*/
public String getColumnName(final int columnIndex) {
return new ArrayList<>(columnNames).get(columnIndex);
}
@Getter
public final class InsertColumnValue {
private final List<SQLExpression> values = new LinkedList<>();
private final List<Object> parameters = new LinkedList<>();
private final List<DataNode> dataNodes = new LinkedList<>();
public InsertColumnValue(final List<SQLExpression> values, final List<Object> parameters) {
this.values.addAll(values);
this.parameters.addAll(parameters);
}
/**
* Set column value.
*
* @param columnName column name
* @param columnValue column value
*/
public void setColumnValue(final String columnName, final Object columnValue) {
SQLExpression sqlExpression = values.get(getColumnIndex(columnName));
if (sqlExpression instanceof SQLPlaceholderExpression) {
parameters.set(getParameterIndex(sqlExpression), columnValue);
} else {
SQLExpression columnExpression = String.class == columnValue.getClass() ? new SQLTextExpression(String.valueOf(columnValue)) : new SQLNumberExpression((Number) columnValue);
values.set(getColumnIndex(columnName), columnExpression);
}
}
private int getColumnIndex(final String columnName) {
return new ArrayList<>(columnNames).indexOf(columnName);
}
private int getParameterIndex(final SQLExpression sqlExpression) {
List<SQLExpression> sqlPlaceholderExpressions = new ArrayList<>(Collections2.filter(values, new Predicate<SQLExpression>() {
@Override
public boolean apply(final SQLExpression input) {
return input instanceof SQLPlaceholderExpression;
}
}));
return sqlPlaceholderExpressions.indexOf(sqlExpression);
}
/**
* Get column value.
*
* @param columnName column Name
* @return column value
*/
public Object getColumnValue(final String columnName) {
SQLExpression sqlExpression = values.get(getColumnIndex(columnName));
if (sqlExpression instanceof SQLPlaceholderExpression) {
return parameters.get(getParameterIndex(sqlExpression));
} else if (sqlExpression instanceof SQLTextExpression) {
return ((SQLTextExpression) sqlExpression).getText();
} else {
return ((SQLNumberExpression) sqlExpression).getNumber();
}
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
if (DefaultKeyword.SET == type) {
fillResultBySet(result);
} else {
fillResultByValues(result);
}
return result.toString();
}
private void fillResultBySet(final StringBuilder result) {
for (int i = 0; i < columnNames.size(); i++) {
result.append(String.format("%s = %s", getColumnName(i), getColumnSQLExpressionValue(i))).append(", ");
}
result.delete(result.length() - 2, result.length());
}
private void fillResultByValues(final StringBuilder result) {
result.append("(");
for (int i = 0; i < columnNames.size(); i++) {
result.append(getColumnSQLExpressionValue(i)).append(", ");
}
result.delete(result.length() - 2, result.length()).append(")");
}
private String getColumnSQLExpressionValue(final int columnValueIndex) {
SQLExpression sqlExpression = values.get(columnValueIndex);
if (sqlExpression instanceof SQLPlaceholderExpression) {
return "?";
} else if (sqlExpression instanceof SQLTextExpression) {
return String.format("'%s'", ((SQLTextExpression) sqlExpression).getText());
} else {
return String.valueOf(((SQLNumberExpression) sqlExpression).getNumber());
}
}
}
}
| delete getColumnName()
| sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/InsertColumnValues.java | delete getColumnName() | <ide><path>harding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/InsertColumnValues.java
<ide> */
<ide> public void addInsertColumnValue(final List<SQLExpression> columnValues, final List<Object> columnParameters) {
<ide> this.columnValues.add(new InsertColumnValue(columnValues, columnParameters));
<del> }
<del>
<del> /**
<del> * Get column name.
<del> *
<del> * @param columnIndex column index
<del> * @return column name
<del> */
<del> public String getColumnName(final int columnIndex) {
<del> return new ArrayList<>(columnNames).get(columnIndex);
<ide> }
<ide>
<ide> @Getter
<ide>
<ide> private void fillResultBySet(final StringBuilder result) {
<ide> for (int i = 0; i < columnNames.size(); i++) {
<del> result.append(String.format("%s = %s", getColumnName(i), getColumnSQLExpressionValue(i))).append(", ");
<add> result.append(String.format("%s = %s", new ArrayList<>(columnNames).get(i), getColumnSQLExpressionValue(i))).append(", ");
<ide> }
<ide> result.delete(result.length() - 2, result.length());
<ide> } |
|
Java | apache-2.0 | e31cf463ea62454f6b0102290f187712692a4736 | 0 | yakatak/okhttp,rschilling/okhttp,VioletLife/okhttp,germanattanasio/okhttp,jrodbx/okhttp,teffy/okhttp,wfxiang08/okhttp,artem-zinnatullin/okhttp,qingsong-xu/okhttp,SunnyDayDev/okhttp,ze-pequeno/okhttp,ansman/okhttp,NightlyNexus/okhttp,joansmith/okhttp,tiarebalbi/okhttp,mjbenedict/okhttp,jrodbx/okhttp,NightlyNexus/okhttp,jrodbx/okhttp,chaitanyajun12/okhttp,cmzy/okhttp,germanattanasio/okhttp,xph906/NetProphet,hgl888/okhttp,xph906/NewOKHttp,yakatak/okhttp,ansman/okhttp,tiarebalbi/okhttp,Voxer/okhttp,artem-zinnatullin/okhttp,SunnyDayDev/okhttp,mjbenedict/okhttp,hgl888/okhttp,Synix/okhttp,cnoldtree/okhttp,hgl888/okhttp,teffy/okhttp,zmarkan/okhttp,cnoldtree/okhttp,VioletLife/okhttp,zmarkan/okhttp,yakatak/okhttp,ansman/okhttp,square/okhttp,yschimke/okhttp,VioletLife/okhttp,tiarebalbi/okhttp,wfxiang08/okhttp,teffy/okhttp,rschilling/okhttp,mjbenedict/okhttp,qingsong-xu/okhttp,xph906/NewOKHttp,artem-zinnatullin/okhttp,xph906/NewOKHttp,NightlyNexus/okhttp,joansmith/okhttp,qingsong-xu/okhttp,cmzy/okhttp,zmarkan/okhttp,nachocove/okhttp,square/okhttp,square/okhttp,nfuller/okhttp,xph906/NetProphet,joansmith/okhttp,yschimke/okhttp,Voxer/okhttp,nachocove/okhttp,Synix/okhttp,nfuller/okhttp,chaitanyajun12/okhttp,cketti/okhttp,chaitanyajun12/okhttp,xph906/NetProphet,rschilling/okhttp,ze-pequeno/okhttp,wfxiang08/okhttp,SunnyDayDev/okhttp,Voxer/okhttp,nfuller/okhttp,yschimke/okhttp,germanattanasio/okhttp,ze-pequeno/okhttp,cnoldtree/okhttp,nachocove/okhttp,cketti/okhttp,Synix/okhttp,cketti/okhttp | /*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.okhttp;
import com.squareup.okhttp.internal.Util;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.net.ssl.SSLPeerUnverifiedException;
import okio.ByteString;
import static java.util.Collections.unmodifiableSet;
/**
* Constrains which certificates are trusted. Pinning certificates defends
* against attacks on certificate authorities. It also prevents connections
* through man-in-the-middle certificate authorities either known or unknown to
* the application's user.
*
* <p>This class currently pins a certificate's Subject Public Key Info as
* described on <a href="http://goo.gl/AIx3e5">Adam Langley's Weblog</a>. Pins
* are base-64 SHA-1 hashes, consistent with the format Chromium uses for <a
* href="http://goo.gl/XDh6je">static certificates</a>. See Chromium's <a
* href="http://goo.gl/4CCnGs">pinsets</a> for hostnames that are pinned in that
* browser.
*
* <h3>Setting up Certificate Pinning</h3>
* The easiest way to pin a host is turn on pinning with a broken configuration
* and read the expected configuration when the connection fails. Be sure to
* do this on a trusted network, and without man-in-the-middle tools like <a
* href="http://charlesproxy.com">Charles</a> or <a
* href="http://fiddlertool.com">Fiddler</a>.
*
* <p>For example, to pin {@code https://publicobject.com}, start with a broken
* configuration: <pre> {@code
*
* String hostname = "publicobject.com";
* CertificatePinner certificatePinner = new CertificatePinner.Builder()
* .add(hostname, "sha1/AAAAAAAAAAAAAAAAAAAAAAAAAAA=")
* .build();
* OkHttpClient client = new OkHttpClient();
* client.setCertificatePinner(certificatePinner);
*
* Request request = new Request.Builder()
* .url("https://" + hostname)
* .build();
* client.newCall(request).execute();
* }</pre>
*
* As expected, this fails with a certificate pinning exception: <pre> {@code
*
* javax.net.ssl.SSLPeerUnverifiedException: Certificate pinning failure!
* Peer certificate chain:
* sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw=: CN=publicobject.com, OU=PositiveSSL
* sha1/SXxoaOSEzPC6BgGmxAt/EAcsajw=: CN=COMODO RSA Domain Validation Secure Server CA
* sha1/blhOM3W9V/bVQhsWAcLYwPU6n24=: CN=COMODO RSA Certification Authority
* sha1/T5x9IXmcrQ7YuQxXnxoCmeeQ84c=: CN=AddTrust External CA Root
* Pinned certificates for publicobject.com:
* sha1/AAAAAAAAAAAAAAAAAAAAAAAAAAA=
* at com.squareup.okhttp.CertificatePinner.check(CertificatePinner.java)
* at com.squareup.okhttp.Connection.upgradeToTls(Connection.java)
* at com.squareup.okhttp.Connection.connect(Connection.java)
* at com.squareup.okhttp.Connection.connectAndSetOwner(Connection.java)
* }</pre>
*
* Follow up by pasting the public key hashes from the exception into the
* certificate pinner's configuration: <pre> {@code
*
* CertificatePinner certificatePinner = new CertificatePinner.Builder()
* .add("publicobject.com", "sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw=")
* .add("publicobject.com", "sha1/SXxoaOSEzPC6BgGmxAt/EAcsajw=")
* .add("publicobject.com", "sha1/blhOM3W9V/bVQhsWAcLYwPU6n24=")
* .add("publicobject.com", "sha1/T5x9IXmcrQ7YuQxXnxoCmeeQ84c=")
* .build();
* }</pre>
*
* Pinning is per-hostname and/or per-wildcard pattern. To pin both
* {@code publicobject.com} and {@code www.publicobject.com}, you must
* configure both hostnames.
*
* <p>Wildcard pattern rules:
* <ol>
* <li>Asterisk {@code *} is only permitted in the left-most
* domain name label and must be the only character in that label
* (i.e., must match the whole left-most label). For example,
* {@code *.example.com} is permitted, while {@code *a.example.com},
* {@code a*.example.com}, {@code a*b.example.com}, {@code a.*.example.com}
* are not permitted.
* <li>Asterisk {@code *} cannot match across domain name labels.
* For example, {@code *.example.com} matches {@code test.example.com}
* but does not match {@code sub.test.example.com}.
* <li>Wildcard patterns for single-label domain names are not permitted.
* </ol>
*
* If hostname pinned directly and via wildcard pattern, both
* direct and wildcard pins will be used. For example: {@code *.example.com} pinned
* with {@code pin1} and {@code a.example.com} pinned with {@code pin2},
* to check {@code a.example.com} both {@code pin1} and {@code pin2} will be used.
*
* <h3>Warning: Certificate Pinning is Dangerous!</h3>
* Pinning certificates limits your server team's abilities to update their TLS
* certificates. By pinning certificates, you take on additional operational
* complexity and limit your ability to migrate between certificate authorities.
* Do not use certificate pinning without the blessing of your server's TLS
* administrator!
*
* <h4>Note about self-signed certificates</h4>
* {@link CertificatePinner} can not be used to pin self-signed certificate
* if such certificate is not accepted by {@link javax.net.ssl.TrustManager}.
*
* @see <a href="https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning">
* OWASP: Certificate and Public Key Pinning</a>
*/
public final class CertificatePinner {
public static final CertificatePinner DEFAULT = new Builder().build();
private final Map<String, Set<ByteString>> hostnameToPins;
private CertificatePinner(Builder builder) {
hostnameToPins = Util.immutableMap(builder.hostnameToPins);
}
/**
* Confirms that at least one of the certificates pinned for {@code hostname}
* is in {@code peerCertificates}. Does nothing if there are no certificates
* pinned for {@code hostname}. OkHttp calls this after a successful TLS
* handshake, but before the connection is used.
*
* @throws SSLPeerUnverifiedException if {@code peerCertificates} don't match
* the certificates pinned for {@code hostname}.
*/
public void check(String hostname, List<Certificate> peerCertificates)
throws SSLPeerUnverifiedException {
Set<ByteString> pins = findMatchingPins(hostname);
if (pins == null) return;
for (int i = 0, size = peerCertificates.size(); i < size; i++) {
X509Certificate x509Certificate = (X509Certificate) peerCertificates.get(i);
if (pins.contains(sha1(x509Certificate))) return; // Success!
}
// If we couldn't find a matching pin, format a nice exception.
StringBuilder message = new StringBuilder()
.append("Certificate pinning failure!")
.append("\n Peer certificate chain:");
for (int i = 0, size = peerCertificates.size(); i < size; i++) {
X509Certificate x509Certificate = (X509Certificate) peerCertificates.get(i);
message.append("\n ").append(pin(x509Certificate))
.append(": ").append(x509Certificate.getSubjectDN().getName());
}
message.append("\n Pinned certificates for ").append(hostname).append(":");
for (ByteString pin : pins) {
message.append("\n sha1/").append(pin.base64());
}
throw new SSLPeerUnverifiedException(message.toString());
}
/** @deprecated replaced with {@link #check(String, List)}. */
public void check(String hostname, Certificate... peerCertificates)
throws SSLPeerUnverifiedException {
check(hostname, Arrays.asList(peerCertificates));
}
/**
* Returns list of matching certificates' pins for the hostname
* or {@code null} if hostname does not have pinned certificates.
*/
Set<ByteString> findMatchingPins(String hostname) {
Set<ByteString> directPins = hostnameToPins.get(hostname);
Set<ByteString> wildcardPins = null;
int indexOfFirstDot = hostname.indexOf('.');
int indexOfLastDot = hostname.lastIndexOf('.');
// Skip hostnames with one dot symbol for wildcard pattern search
// example.com will be skipped
// a.example.com won't be skipped
if (indexOfFirstDot != indexOfLastDot) {
// a.example.com -> search for wildcard pattern *.example.com
wildcardPins = hostnameToPins.get("*." + hostname.substring(indexOfFirstDot + 1));
}
if (directPins == null && wildcardPins == null) return null;
if (directPins != null && wildcardPins != null) {
Set<ByteString> pins = new LinkedHashSet<>();
pins.addAll(directPins);
pins.addAll(wildcardPins);
return pins;
}
if (directPins != null) return directPins;
return wildcardPins;
}
/**
* Returns the SHA-1 of {@code certificate}'s public key. This uses the
* mechanism Moxie Marlinspike describes in <a
* href="https://github.com/moxie0/AndroidPinning">Android Pinning</a>.
*/
public static String pin(Certificate certificate) {
if (!(certificate instanceof X509Certificate)) {
throw new IllegalArgumentException("Certificate pinning requires X509 certificates");
}
return "sha1/" + sha1((X509Certificate) certificate).base64();
}
private static ByteString sha1(X509Certificate x509Certificate) {
return Util.sha1(ByteString.of(x509Certificate.getPublicKey().getEncoded()));
}
/** Builds a configured certificate pinner. */
public static final class Builder {
private final Map<String, Set<ByteString>> hostnameToPins = new LinkedHashMap<>();
/**
* Pins certificates for {@code hostname}.
*
* @param hostname lower-case host name or wildcard pattern such as {@code *.example.com}.
* @param pins SHA-1 hashes. Each pin is a SHA-1 hash of a
* certificate's Subject Public Key Info, base64-encoded and prefixed with
* {@code sha1/}.
*/
public Builder add(String hostname, String... pins) {
if (hostname == null) throw new IllegalArgumentException("hostname == null");
Set<ByteString> hostPins = new LinkedHashSet<>();
Set<ByteString> previousPins = hostnameToPins.put(hostname, unmodifiableSet(hostPins));
if (previousPins != null) {
hostPins.addAll(previousPins);
}
for (String pin : pins) {
if (!pin.startsWith("sha1/")) {
throw new IllegalArgumentException("pins must start with 'sha1/': " + pin);
}
ByteString decodedPin = ByteString.decodeBase64(pin.substring("sha1/".length()));
if (decodedPin == null) {
throw new IllegalArgumentException("pins must be base64: " + pin);
}
hostPins.add(decodedPin);
}
return this;
}
public CertificatePinner build() {
return new CertificatePinner(this);
}
}
}
| okhttp/src/main/java/com/squareup/okhttp/CertificatePinner.java | /*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.okhttp;
import com.squareup.okhttp.internal.Util;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.net.ssl.SSLPeerUnverifiedException;
import okio.ByteString;
import static java.util.Collections.unmodifiableSet;
/**
* Constrains which certificates are trusted. Pinning certificates defends
* against attacks on certificate authorities. It also prevents connections
* through man-in-the-middle certificate authorities either known or unknown to
* the application's user.
*
* <p>This class currently pins a certificate's Subject Public Key Info as
* described on <a href="http://goo.gl/AIx3e5">Adam Langley's Weblog</a>. Pins
* are base-64 SHA-1 hashes, consistent with the format Chromium uses for <a
* href="http://goo.gl/XDh6je">static certificates</a>. See Chromium's <a
* href="http://goo.gl/4CCnGs">pinsets</a> for hostnames that are pinned in that
* browser.
*
* <h3>Setting up Certificate Pinning</h3>
* The easiest way to pin a host is turn on pinning with a broken configuration
* and read the expected configuration when the connection fails. Be sure to
* do this on a trusted network, and without man-in-the-middle tools like <a
* href="http://charlesproxy.com">Charles</a> or <a
* href="http://fiddlertool.com">Fiddler</a>.
*
* <p>For example, to pin {@code https://publicobject.com}, start with a broken
* configuration: <pre> {@code
*
* String hostname = "publicobject.com";
* CertificatePinner certificatePinner = new CertificatePinner.Builder()
* .add(hostname, "sha1/BOGUSPIN")
* .build();
* OkHttpClient client = new OkHttpClient();
* client.setCertificatePinner(certificatePinner);
*
* Request request = new Request.Builder()
* .url("https://" + hostname)
* .build();
* client.newCall(request).execute();
* }</pre>
*
* As expected, this fails with a certificate pinning exception: <pre> {@code
*
* javax.net.ssl.SSLPeerUnverifiedException: Certificate pinning failure!
* Peer certificate chain:
* sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw=: CN=publicobject.com, OU=PositiveSSL
* sha1/SXxoaOSEzPC6BgGmxAt/EAcsajw=: CN=COMODO RSA Domain Validation Secure Server CA
* sha1/blhOM3W9V/bVQhsWAcLYwPU6n24=: CN=COMODO RSA Certification Authority
* sha1/T5x9IXmcrQ7YuQxXnxoCmeeQ84c=: CN=AddTrust External CA Root
* Pinned certificates for publicobject.com:
* sha1/BOGUSPIN
* at com.squareup.okhttp.CertificatePinner.check(CertificatePinner.java)
* at com.squareup.okhttp.Connection.upgradeToTls(Connection.java)
* at com.squareup.okhttp.Connection.connect(Connection.java)
* at com.squareup.okhttp.Connection.connectAndSetOwner(Connection.java)
* }</pre>
*
* Follow up by pasting the public key hashes from the exception into the
* certificate pinner's configuration: <pre> {@code
*
* CertificatePinner certificatePinner = new CertificatePinner.Builder()
* .add("publicobject.com", "sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw=")
* .add("publicobject.com", "sha1/SXxoaOSEzPC6BgGmxAt/EAcsajw=")
* .add("publicobject.com", "sha1/blhOM3W9V/bVQhsWAcLYwPU6n24=")
* .add("publicobject.com", "sha1/T5x9IXmcrQ7YuQxXnxoCmeeQ84c=")
* .build();
* }</pre>
*
* Pinning is per-hostname and/or per-wildcard pattern. To pin both
* {@code publicobject.com} and {@code www.publicobject.com}, you must
* configure both hostnames.
*
* <p>Wildcard pattern rules:
* <ol>
* <li>Asterisk {@code *} is only permitted in the left-most
* domain name label and must be the only character in that label
* (i.e., must match the whole left-most label). For example,
* {@code *.example.com} is permitted, while {@code *a.example.com},
* {@code a*.example.com}, {@code a*b.example.com}, {@code a.*.example.com}
* are not permitted.
* <li>Asterisk {@code *} cannot match across domain name labels.
* For example, {@code *.example.com} matches {@code test.example.com}
* but does not match {@code sub.test.example.com}.
* <li>Wildcard patterns for single-label domain names are not permitted.
* </ol>
*
* If hostname pinned directly and via wildcard pattern, both
* direct and wildcard pins will be used. For example: {@code *.example.com} pinned
* with {@code pin1} and {@code a.example.com} pinned with {@code pin2},
* to check {@code a.example.com} both {@code pin1} and {@code pin2} will be used.
*
* <h3>Warning: Certificate Pinning is Dangerous!</h3>
* Pinning certificates limits your server team's abilities to update their TLS
* certificates. By pinning certificates, you take on additional operational
* complexity and limit your ability to migrate between certificate authorities.
* Do not use certificate pinning without the blessing of your server's TLS
* administrator!
*
* <h4>Note about self-signed certificates</h4>
* {@link CertificatePinner} can not be used to pin self-signed certificate
* if such certificate is not accepted by {@link javax.net.ssl.TrustManager}.
*
* @see <a href="https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning">
* OWASP: Certificate and Public Key Pinning</a>
*/
public final class CertificatePinner {
public static final CertificatePinner DEFAULT = new Builder().build();
private final Map<String, Set<ByteString>> hostnameToPins;
private CertificatePinner(Builder builder) {
hostnameToPins = Util.immutableMap(builder.hostnameToPins);
}
/**
* Confirms that at least one of the certificates pinned for {@code hostname}
* is in {@code peerCertificates}. Does nothing if there are no certificates
* pinned for {@code hostname}. OkHttp calls this after a successful TLS
* handshake, but before the connection is used.
*
* @throws SSLPeerUnverifiedException if {@code peerCertificates} don't match
* the certificates pinned for {@code hostname}.
*/
public void check(String hostname, List<Certificate> peerCertificates)
throws SSLPeerUnverifiedException {
Set<ByteString> pins = findMatchingPins(hostname);
if (pins == null) return;
for (int i = 0, size = peerCertificates.size(); i < size; i++) {
X509Certificate x509Certificate = (X509Certificate) peerCertificates.get(i);
if (pins.contains(sha1(x509Certificate))) return; // Success!
}
// If we couldn't find a matching pin, format a nice exception.
StringBuilder message = new StringBuilder()
.append("Certificate pinning failure!")
.append("\n Peer certificate chain:");
for (int i = 0, size = peerCertificates.size(); i < size; i++) {
X509Certificate x509Certificate = (X509Certificate) peerCertificates.get(i);
message.append("\n ").append(pin(x509Certificate))
.append(": ").append(x509Certificate.getSubjectDN().getName());
}
message.append("\n Pinned certificates for ").append(hostname).append(":");
for (ByteString pin : pins) {
message.append("\n sha1/").append(pin.base64());
}
throw new SSLPeerUnverifiedException(message.toString());
}
/** @deprecated replaced with {@link #check(String, List)}. */
public void check(String hostname, Certificate... peerCertificates)
throws SSLPeerUnverifiedException {
check(hostname, Arrays.asList(peerCertificates));
}
/**
* Returns list of matching certificates' pins for the hostname
* or {@code null} if hostname does not have pinned certificates.
*/
Set<ByteString> findMatchingPins(String hostname) {
Set<ByteString> directPins = hostnameToPins.get(hostname);
Set<ByteString> wildcardPins = null;
int indexOfFirstDot = hostname.indexOf('.');
int indexOfLastDot = hostname.lastIndexOf('.');
// Skip hostnames with one dot symbol for wildcard pattern search
// example.com will be skipped
// a.example.com won't be skipped
if (indexOfFirstDot != indexOfLastDot) {
// a.example.com -> search for wildcard pattern *.example.com
wildcardPins = hostnameToPins.get("*." + hostname.substring(indexOfFirstDot + 1));
}
if (directPins == null && wildcardPins == null) return null;
if (directPins != null && wildcardPins != null) {
Set<ByteString> pins = new LinkedHashSet<>();
pins.addAll(directPins);
pins.addAll(wildcardPins);
return pins;
}
if (directPins != null) return directPins;
return wildcardPins;
}
/**
* Returns the SHA-1 of {@code certificate}'s public key. This uses the
* mechanism Moxie Marlinspike describes in <a
* href="https://github.com/moxie0/AndroidPinning">Android Pinning</a>.
*/
public static String pin(Certificate certificate) {
if (!(certificate instanceof X509Certificate)) {
throw new IllegalArgumentException("Certificate pinning requires X509 certificates");
}
return "sha1/" + sha1((X509Certificate) certificate).base64();
}
private static ByteString sha1(X509Certificate x509Certificate) {
return Util.sha1(ByteString.of(x509Certificate.getPublicKey().getEncoded()));
}
/** Builds a configured certificate pinner. */
public static final class Builder {
private final Map<String, Set<ByteString>> hostnameToPins = new LinkedHashMap<>();
/**
* Pins certificates for {@code hostname}.
*
* @param hostname lower-case host name or wildcard pattern such as {@code *.example.com}.
* @param pins SHA-1 hashes. Each pin is a SHA-1 hash of a
* certificate's Subject Public Key Info, base64-encoded and prefixed with
* {@code sha1/}.
*/
public Builder add(String hostname, String... pins) {
if (hostname == null) throw new IllegalArgumentException("hostname == null");
Set<ByteString> hostPins = new LinkedHashSet<>();
Set<ByteString> previousPins = hostnameToPins.put(hostname, unmodifiableSet(hostPins));
if (previousPins != null) {
hostPins.addAll(previousPins);
}
for (String pin : pins) {
if (!pin.startsWith("sha1/")) {
throw new IllegalArgumentException("pins must start with 'sha1/': " + pin);
}
ByteString decodedPin = ByteString.decodeBase64(pin.substring("sha1/".length()));
if (decodedPin == null) {
throw new IllegalArgumentException("pins must be base64: " + pin);
}
hostPins.add(decodedPin);
}
return this;
}
public CertificatePinner build() {
return new CertificatePinner(this);
}
}
}
| Use bogus pin that doesn’t throw an exception
"sha1/BOGUSPIN" throws an `IllegalArgumentException` because `BOGUSPIN` is not valid base64.
| okhttp/src/main/java/com/squareup/okhttp/CertificatePinner.java | Use bogus pin that doesn’t throw an exception | <ide><path>khttp/src/main/java/com/squareup/okhttp/CertificatePinner.java
<ide> *
<ide> * String hostname = "publicobject.com";
<ide> * CertificatePinner certificatePinner = new CertificatePinner.Builder()
<del> * .add(hostname, "sha1/BOGUSPIN")
<add> * .add(hostname, "sha1/AAAAAAAAAAAAAAAAAAAAAAAAAAA=")
<ide> * .build();
<ide> * OkHttpClient client = new OkHttpClient();
<ide> * client.setCertificatePinner(certificatePinner);
<ide> * sha1/blhOM3W9V/bVQhsWAcLYwPU6n24=: CN=COMODO RSA Certification Authority
<ide> * sha1/T5x9IXmcrQ7YuQxXnxoCmeeQ84c=: CN=AddTrust External CA Root
<ide> * Pinned certificates for publicobject.com:
<del> * sha1/BOGUSPIN
<add> * sha1/AAAAAAAAAAAAAAAAAAAAAAAAAAA=
<ide> * at com.squareup.okhttp.CertificatePinner.check(CertificatePinner.java)
<ide> * at com.squareup.okhttp.Connection.upgradeToTls(Connection.java)
<ide> * at com.squareup.okhttp.Connection.connect(Connection.java) |
|
JavaScript | mit | 6ca51739786bdfd7176bbb07d89a58b24274aaab | 0 | hideack/evac | var parser = require('../../../lib/plugin/in/webpageparse.js'),
here = require('here').here,
nock = require('nock');
describe('input plugin: webpageparse', function(){
var mockSite1 = "http://test1.hideack";
var mockSite2 = "http://test2.hideack";
beforeEach(function() {
var testBody1 = here(/*
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<p id="evac">foobar</p>
</body>
</html>
*/
).unindent();
var testBody2 = here(/*
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<p id="evac">hogemoge</p>
</body>
</html>
*/
).unindent();
nock(mockSite1).get('/').reply(200, testBody1);
nock(mockSite2).get('/').reply(200, testBody2);
});
it('should be get to HTTP contents.', function(done){
parser.load({url:"http://test1.hideack/", target:"#evac"}, function(error, outputs){
error.should.be.false;
done();
});
});
it('should be get to any HTTP contents.', function(done){
parser.load({url:["http://test1.hideack/", "http://test2.hideack/"], target:"#evac"}, function(error, outputs){
error.should.be.false;
outputs.should.deep.equal(["foobar", "hogemoge"]);
done();
});
});
it('should be get to any HTTP contents with behind params.', function(done){
parser.load({url:["http://test1.hideack/", "http://test2.hideack/"], target:"#evac", behind: 1000}, function(error, outputs){
error.should.be.false;
done();
});
});
});
| test/plugin/in/webpageparser.js | var parser = require('../../../lib/plugin/in/webpageparse.js'),
here = require('here').here,
nock = require('nock');
describe('input plugin: webpageparse', function(){
var mockSite1 = "http://test1.hideack";
var mockSite2 = "http://test2.hideack";
beforeEach(function() {
var testBody1 = here(/*
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<p id="evac">foobar</p>
</body>
</html>
*/
).unindent();
var testBody2 = here(/*
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<p id="evac">hogemoge</p>
</body>
</html>
*/
).unindent();
nock(mockSite1).get('/').reply(200, testBody1);
nock(mockSite2).get('/').reply(200, testBody2);
});
it('should be get to HTTP contents.', function(done){
parser.load({url:"http://test1.hideack/", target:"#evac"}, function(error, outputs){
error.should.be.false;
done();
});
});
it('should be get to any HTTP contents.', function(done){
parser.load({url:["http://test1.hideack/", "http://test2.hideack/"], target:"#evac"}, function(error, outputs){
error.should.be.false;
outputs.should.deep.equal(["foobar", "hogemoge"]);
done();
});
});
});
| behindパラメータを含んだ呼び出しテスト追加
| test/plugin/in/webpageparser.js | behindパラメータを含んだ呼び出しテスト追加 | <ide><path>est/plugin/in/webpageparser.js
<ide> });
<ide> });
<ide>
<add> it('should be get to any HTTP contents with behind params.', function(done){
<add> parser.load({url:["http://test1.hideack/", "http://test2.hideack/"], target:"#evac", behind: 1000}, function(error, outputs){
<add> error.should.be.false;
<add> done();
<add> });
<add> });
<ide> });
<ide> |
|
Java | apache-2.0 | 462571235e133fd46ff7533de7ea530f5ad76115 | 0 | apache/solr,apache/solr,apache/solr,apache/solr,apache/solr | /**
* 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.solr.handler;
import org.apache.lucene.index.IndexCommit;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.FastOutputStream;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.core.CloseHook;
import org.apache.solr.core.IndexDeletionPolicyWrapper;
import org.apache.solr.core.SolrCore;
import org.apache.solr.core.SolrEventListener;
import org.apache.solr.request.BinaryQueryResponseWriter;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrQueryResponse;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.update.DirectUpdateHandler2;
import org.apache.solr.util.RefCounted;
import org.apache.solr.util.plugin.SolrCoreAware;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.zip.Adler32;
import java.util.zip.Checksum;
import java.util.zip.DeflaterOutputStream;
/**
* <p> A Handler which provides a REST API for replication and serves replication requests from Slaves. <p/> </p>
* <p>When running on the master, it provides the following commands <ol> <li>Get the current replicatable index version
* (command=indexversion)</li> <li>Get the list of files for a given index version
* (command=filelist&indexversion=<VERSION>)</li> <li>Get full or a part (chunk) of a given index or a config
* file (command=filecontent&file=<FILE_NAME>) You can optionally specify an offset and length to get that
* chunk of the file. You can request a configuration file by using "cf" parameter instead of the "file" parameter.</li>
* <li>Get status/statistics (command=details)</li> </ol> </p> <p>When running on the slave, it provides the following
* commands <ol> <li>Perform a snap pull now (command=snappull)</li> <li>Get status/statistics (command=details)</li>
* <li>Abort a snap pull (command=abort)</li> <li>Enable/Disable polling the master for new versions (command=enablepoll
* or command=disablepoll)</li> </ol> </p>
*
* @version $Id$
* @since solr 1.4
*/
public class ReplicationHandler extends RequestHandlerBase implements SolrCoreAware {
private static final Logger LOG = LoggerFactory.getLogger(ReplicationHandler.class.getName());
private SolrCore core;
private SnapPuller snapPuller;
private ReentrantLock snapPullLock = new ReentrantLock();
private String includeConfFiles;
private NamedList<String> confFileNameAlias = new NamedList<String>();
private boolean isMaster = false;
private boolean isSlave = false;
private boolean replicateOnOptimize = false;
private boolean replicateOnCommit = false;
private boolean replicateOnStart = false;
private int numTimesReplicated = 0;
private final Map<String, FileInfo> confFileInfoCache = new HashMap<String, FileInfo>();
private Integer reserveCommitDuration = SnapPuller.readInterval("00:00:10");
private volatile IndexCommit indexCommitPoint;
volatile NamedList snapShootDetails;
private AtomicBoolean replicationEnabled = new AtomicBoolean(true);
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
rsp.setHttpCaching(false);
final SolrParams solrParams = req.getParams();
String command = solrParams.get(COMMAND);
if (command == null) {
rsp.add(STATUS, OK_STATUS);
rsp.add("message", "No command");
return;
}
// This command does not give the current index version of the master
// It gives the current 'replicateable' index version
if(CMD_ENABLE_REPL.equalsIgnoreCase(command)){
replicationEnabled.set(true);
rsp.add(STATUS, OK_STATUS);
} else if(CMD_DISABLE_REPL.equalsIgnoreCase(command)){
replicationEnabled.set(false);
rsp.add(STATUS, OK_STATUS);
} else if (command.equals(CMD_INDEX_VERSION)) {
IndexCommit commitPoint = indexCommitPoint; // make a copy so it won't change
if (commitPoint != null && replicationEnabled.get()) {
rsp.add(CMD_INDEX_VERSION, commitPoint.getVersion());
rsp.add(GENERATION, commitPoint.getGeneration());
} else {
// This happens when replication is not configured to happen after startup and no commit/optimize
// has happened yet.
rsp.add(CMD_INDEX_VERSION, 0L);
rsp.add(GENERATION, 0L);
}
} else if (command.equals(CMD_GET_FILE)) {
getFileStream(solrParams, rsp);
} else if (command.equals(CMD_GET_FILE_LIST)) {
getFileList(solrParams, rsp);
} else if (command.equalsIgnoreCase(CMD_BACKUP)) {
doSnapShoot(new ModifiableSolrParams(solrParams), rsp,req);
rsp.add(STATUS, OK_STATUS);
} else if (command.equalsIgnoreCase(CMD_FETCH_INDEX)) {
String masterUrl = solrParams.get(MASTER_URL);
if (!isSlave && masterUrl == null) {
rsp.add(STATUS,ERR_STATUS);
rsp.add("message","No slave configured or no 'masterUrl' Specified");
return;
}
final SolrParams paramsCopy = new ModifiableSolrParams(solrParams);
new Thread() {
public void run() {
doFetch(paramsCopy);
}
}.start();
rsp.add(STATUS, OK_STATUS);
} else if (command.equalsIgnoreCase(CMD_DISABLE_POLL)) {
if (snapPuller != null){
snapPuller.disablePoll();
rsp.add(STATUS, OK_STATUS);
} else {
rsp.add(STATUS, ERR_STATUS);
rsp.add("message","No slave configured");
}
} else if (command.equalsIgnoreCase(CMD_ENABLE_POLL)) {
if (snapPuller != null){
snapPuller.enablePoll();
rsp.add(STATUS, OK_STATUS);
}else {
rsp.add(STATUS,ERR_STATUS);
rsp.add("message","No slave configured");
}
} else if (command.equalsIgnoreCase(CMD_ABORT_FETCH)) {
if (snapPuller != null){
snapPuller.abortPull();
rsp.add(STATUS, OK_STATUS);
} else {
rsp.add(STATUS,ERR_STATUS);
rsp.add("message","No slave configured");
}
} else if (command.equals(CMD_FILE_CHECKSUM)) {
// this command is not used by anyone
getFileChecksum(solrParams, rsp);
} else if (command.equals(CMD_SHOW_COMMITS)) {
rsp.add(CMD_SHOW_COMMITS, getCommits());
} else if (command.equals(CMD_DETAILS)) {
rsp.add(CMD_DETAILS, getReplicationDetails());
RequestHandlerUtils.addExperimentalFormatWarning(rsp);
}
}
private List<NamedList> getCommits() {
Map<Long, IndexCommit> commits = core.getDeletionPolicy().getCommits();
List<NamedList> l = new ArrayList<NamedList>();
for (IndexCommit c : commits.values()) {
try {
NamedList nl = new NamedList();
nl.add("indexVersion", c.getVersion());
nl.add(GENERATION, c.getGeneration());
nl.add(CMD_GET_FILE_LIST, c.getFileNames().toString());
l.add(nl);
} catch (IOException e) {
LOG.warn("Exception while reading files for commit " + c, e);
}
}
return l;
}
/**
* Gets the checksum of a file
*/
private void getFileChecksum(SolrParams solrParams, SolrQueryResponse rsp) {
Checksum checksum = new Adler32();
File dir = new File(core.getIndexDir());
rsp.add(CHECKSUM, getCheckSums(solrParams.getParams(FILE), dir, checksum));
dir = new File(core.getResourceLoader().getConfigDir());
rsp.add(CONF_CHECKSUM, getCheckSums(solrParams.getParams(CONF_FILE_SHORT), dir, checksum));
}
private Map<String, Long> getCheckSums(String[] files, File dir, Checksum checksum) {
Map<String, Long> checksumMap = new HashMap<String, Long>();
if (files == null || files.length == 0)
return checksumMap;
for (String file : files) {
File f = new File(dir, file);
Long checkSumVal = getCheckSum(checksum, f);
if (checkSumVal != null)
checksumMap.put(file, checkSumVal);
}
return checksumMap;
}
static Long getCheckSum(Checksum checksum, File f) {
FileInputStream fis = null;
checksum.reset();
byte[] buffer = new byte[1024 * 1024];
int bytesRead;
try {
fis = new FileInputStream(f);
while ((bytesRead = fis.read(buffer)) >= 0)
checksum.update(buffer, 0, bytesRead);
return checksum.getValue();
} catch (Exception e) {
LOG.warn("Exception in finding checksum of " + f, e);
} finally {
IOUtils.closeQuietly(fis);
}
return null;
}
private volatile SnapPuller tempSnapPuller;
void doFetch(SolrParams solrParams) {
String masterUrl = solrParams == null ? null : solrParams.get(MASTER_URL);
if (!snapPullLock.tryLock())
return;
try {
tempSnapPuller = snapPuller;
if (masterUrl != null) {
NamedList<Object> nl = solrParams.toNamedList();
nl.remove(SnapPuller.POLL_INTERVAL);
tempSnapPuller = new SnapPuller(nl, this, core);
}
tempSnapPuller.fetchLatestIndex(core);
} catch (Exception e) {
LOG.error("SnapPull failed ", e);
} finally {
tempSnapPuller = snapPuller;
snapPullLock.unlock();
}
}
boolean isReplicating() {
return snapPullLock.isLocked();
}
private void doSnapShoot(SolrParams params, SolrQueryResponse rsp, SolrQueryRequest req) {
try {
IndexCommit indexCommit = core.getDeletionPolicy().getLatestCommit();
if(indexCommit == null) {
indexCommit = req.getSearcher().getReader().getIndexCommit();
}
if (indexCommit != null) {
new SnapShooter(core, params.get("location")).createSnapAsync(indexCommit.getFileNames(), this);
}
} catch (Exception e) {
LOG.warn("Exception during creating a snapshot", e);
rsp.add("exception", e);
}
}
/**
* This method adds an Object of FileStream to the resposnse . The FileStream implements a custom protocol which is
* understood by SnapPuller.FileFetcher
*
* @see org.apache.solr.handler.SnapPuller.FileFetcher
*/
private void getFileStream(SolrParams solrParams, SolrQueryResponse rsp) {
ModifiableSolrParams rawParams = new ModifiableSolrParams(solrParams);
rawParams.set(CommonParams.WT, FILE_STREAM);
rsp.add(FILE_STREAM, new FileStream(solrParams));
}
@SuppressWarnings("unchecked")
private void getFileList(SolrParams solrParams, SolrQueryResponse rsp) {
String v = solrParams.get(CMD_INDEX_VERSION);
if (v == null) {
rsp.add("status", "no indexversion specified");
return;
}
long version = Long.parseLong(v);
IndexCommit commit = core.getDeletionPolicy().getCommitPoint(version);
if (commit == null) {
rsp.add("status", "invalid indexversion");
return;
}
// reserve the indexcommit for sometime
core.getDeletionPolicy().setReserveDuration(version, reserveCommitDuration);
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
try {
//get all the files in the commit
//use a set to workaround possible Lucene bug which returns same file name multiple times
Collection<String> files = new HashSet<String>(commit.getFileNames());
for (String fileName : files) {
File file = new File(core.getIndexDir(), fileName);
Map<String, Object> fileMeta = getFileInfo(file);
result.add(fileMeta);
}
} catch (IOException e) {
rsp.add("status", "unable to get file names for given indexversion");
rsp.add("exception", e);
LOG.warn("Unable to get file names for indexCommit version: "
+ version, e);
}
rsp.add(CMD_GET_FILE_LIST, result);
if (confFileNameAlias.size() < 1)
return;
LOG.debug("Adding config files to list: " + includeConfFiles);
//if configuration files need to be included get their details
rsp.add(CONF_FILES, getConfFileInfoFromCache(confFileNameAlias, confFileInfoCache));
}
/**
* For configuration files, checksum of the file is included because, unlike index files, they may have same content
* but different timestamps.
* <p/>
* The local conf files information is cached so that everytime it does not have to compute the checksum. The cache is
* refreshed only if the lastModified of the file changes
*/
List<Map<String, Object>> getConfFileInfoFromCache(NamedList<String> nameAndAlias,
final Map<String, FileInfo> confFileInfoCache) {
List<Map<String, Object>> confFiles = new ArrayList<Map<String, Object>>();
synchronized (confFileInfoCache) {
File confDir = new File(core.getResourceLoader().getConfigDir());
Checksum checksum = null;
for (int i = 0; i < nameAndAlias.size(); i++) {
String cf = nameAndAlias.getName(i);
File f = new File(confDir, cf);
if (!f.exists() || f.isDirectory()) continue; //must not happen
FileInfo info = confFileInfoCache.get(cf);
if (info == null || info.lastmodified != f.lastModified() || info.size != f.length()) {
if (checksum == null) checksum = new Adler32();
info = new FileInfo(f.lastModified(), cf, f.length(), getCheckSum(checksum, f));
confFileInfoCache.put(cf, info);
}
Map<String, Object> m = info.getAsMap();
if (nameAndAlias.getVal(i) != null) m.put(ALIAS, nameAndAlias.getVal(i));
confFiles.add(m);
}
}
return confFiles;
}
static class FileInfo {
long lastmodified;
String name;
long size;
long checksum;
public FileInfo(long lasmodified, String name, long size, long checksum) {
this.lastmodified = lasmodified;
this.name = name;
this.size = size;
this.checksum = checksum;
}
Map<String, Object> getAsMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put(NAME, name);
map.put(SIZE, size);
map.put(LAST_MODIFIED, lastmodified);
map.put(CHECKSUM, checksum);
return map;
}
}
void disablePoll() {
if (isSlave)
snapPuller.disablePoll();
}
void enablePoll() {
if (isSlave)
snapPuller.enablePoll();
}
boolean isPollingDisabled() {
return snapPuller.isPollingDisabled();
}
int getTimesReplicatedSinceStartup() {
return numTimesReplicated;
}
void setTimesReplicatedSinceStartup() {
numTimesReplicated++;
}
long getIndexSize() {
return computeIndexSize(new File(core.getIndexDir()));
}
private long computeIndexSize(File f) {
if (f.isFile())
return f.length();
File[] files = f.listFiles();
long size = 0;
if (files != null && files.length > 0) {
for (File file : files) size += file.length();
}
return size;
}
/**
* Collects the details such as name, size ,lastModified of a file
*/
private Map<String, Object> getFileInfo(File file) {
Map<String, Object> fileMeta = new HashMap<String, Object>();
fileMeta.put(NAME, file.getName());
fileMeta.put(SIZE, file.length());
fileMeta.put(LAST_MODIFIED, file.lastModified());
return fileMeta;
}
public String getDescription() {
return "ReplicationHandler provides replication of index and configuration files from Master to Slaves";
}
public String getSourceId() {
return "$Id$";
}
public String getSource() {
return "$URL$";
}
public String getVersion() {
return "$Revision$";
}
String readableSize(long size) {
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMaximumFractionDigits(2);
if (size / (1024 * 1024 * 1024) > 0) {
return formatter.format(size * 1.0d / (1024 * 1024 * 1024)) + " GB";
} else if (size / (1024 * 1024) > 0) {
return formatter.format(size * 1.0d / (1024 * 1024)) + " MB";
} else if (size / 1024 > 0) {
return formatter.format(size * 1.0d / 1024) + " KB";
} else {
return String.valueOf(size) + " bytes";
}
}
private long[] getIndexVersion() {
long version[] = new long[2];
RefCounted<SolrIndexSearcher> searcher = core.getSearcher();
try {
version[0] = searcher.get().getReader().getIndexCommit().getVersion();
version[1] = searcher.get().getReader().getIndexCommit().getGeneration();
} catch (IOException e) {
LOG.warn("Unable to get index version : ", e);
} finally {
searcher.decref();
}
return version;
}
@Override
@SuppressWarnings("unchecked")
public NamedList getStatistics() {
NamedList list = super.getStatistics();
if (core != null) {
list.add("indexSize", readableSize(getIndexSize()));
long[] versionGen = getIndexVersion();
list.add("indexVersion", versionGen[0]);
list.add(GENERATION, versionGen[1]);
list.add("indexPath", core.getIndexDir());
list.add("isMaster", String.valueOf(isMaster));
list.add("isSlave", String.valueOf(isSlave));
SnapPuller snapPuller = tempSnapPuller;
if (snapPuller != null) {
list.add(MASTER_URL, snapPuller.getMasterUrl());
if (snapPuller.getPollInterval() != null) {
list.add(SnapPuller.POLL_INTERVAL, snapPuller.getPollInterval());
}
list.add("isPollingDisabled", String.valueOf(isPollingDisabled()));
list.add("isReplicating", String.valueOf(isReplicating()));
}
if (isMaster) {
if (includeConfFiles != null)
list.add("confFilesToReplicate", includeConfFiles);
String replicateAfterString="";
if (replicateOnCommit)
replicateAfterString += "commit, ";
if (replicateOnOptimize)
replicateAfterString += "optimize, ";
if(replicateOnStart)
replicateAfterString += "startup, ";
if(replicateAfterString.lastIndexOf(',') > -1)
replicateAfterString = replicateAfterString.substring(0, replicateAfterString.lastIndexOf(','));
list.add(REPLICATE_AFTER, replicateAfterString);
}
}
return list;
}
/**
* Used for showing statistics and progress information.
*/
NamedList<Object> getReplicationDetails() {
String timeLastReplicated = "", confFilesReplicated = "", confFilesReplicatedTime = "", timesIndexReplicated = "", timesConfigReplicated = "";
NamedList<Object> details = new SimpleOrderedMap<Object>();
NamedList<Object> master = new SimpleOrderedMap<Object>();
NamedList<Object> slave = new SimpleOrderedMap<Object>();
FileInputStream inFile = null;
details.add("indexSize", readableSize(getIndexSize()));
details.add("indexPath", core.getIndexDir());
details.add(CMD_SHOW_COMMITS, getCommits());
details.add("isMaster", String.valueOf(isMaster));
details.add("isSlave", String.valueOf(isSlave));
long[] versionAndGeneration = getIndexVersion();
details.add("indexVersion", versionAndGeneration[0]);
details.add(GENERATION, versionAndGeneration[1]);
IndexCommit commit = indexCommitPoint; // make a copy so it won't change
if (isMaster) {
if (includeConfFiles != null)
master.add(CONF_FILES, includeConfFiles);
String replicateAfterString="";
if (replicateOnCommit)
replicateAfterString += "commit, ";
if (replicateOnOptimize)
replicateAfterString += "optimize, ";
if(replicateOnStart)
replicateAfterString += "startup, ";
if(replicateAfterString.lastIndexOf(',') > -1)
replicateAfterString = replicateAfterString.substring(0, replicateAfterString.lastIndexOf(','));
master.add(REPLICATE_AFTER, replicateAfterString);
}
if (isMaster && commit != null) {
master.add("replicatableIndexVersion", commit.getVersion());
master.add("replicatableGeneration", commit.getGeneration());
}
SnapPuller snapPuller = tempSnapPuller;
if (snapPuller != null) {
try {
Properties props = new Properties();
File f = new File(core.getDataDir(), SnapPuller.REPLICATION_PROPERTIES);
if (f.exists()) {
inFile = new FileInputStream(f);
props.load(inFile);
timeLastReplicated = props.getProperty("indexReplicatedAt");
if (props.containsKey("timesIndexReplicated"))
timesIndexReplicated = props.getProperty("timesIndexReplicated");
if (props.containsKey("confFilesReplicated"))
confFilesReplicated = props.getProperty("confFilesReplicated");
if (props.containsKey("confFilesReplicatedAt"))
confFilesReplicatedTime = props.getProperty("confFilesReplicatedAt");
if (props.containsKey("timesConfigReplicated"))
timesConfigReplicated = props.getProperty("timesConfigReplicated");
}
} catch (Exception e) {
LOG.warn("Exception while reading " + SnapPuller.REPLICATION_PROPERTIES);
} finally {
IOUtils.closeQuietly(inFile);
}
try {
NamedList nl = snapPuller.getCommandResponse(CMD_DETAILS);
slave.add("masterDetails", nl.get(CMD_DETAILS));
} catch (IOException e) {
LOG.warn("Exception while invoking a 'details' method on master ", e);
}
slave.add(MASTER_URL, snapPuller.getMasterUrl());
if (snapPuller.getPollInterval() != null) {
slave.add(SnapPuller.POLL_INTERVAL, snapPuller.getPollInterval());
}
if (snapPuller.getNextScheduledExecTime() != null && !isPollingDisabled()) {
Date d = new Date(snapPuller.getNextScheduledExecTime());
slave.add("nextExecutionAt", d.toString());
} else if (isPollingDisabled()) {
slave.add("nextExecutionAt", "Polling disabled");
} else
slave.add("nextExecutionAt", "");
if (timeLastReplicated != null && timeLastReplicated.length() > 0) {
Date d = new Date(Long.valueOf(timeLastReplicated));
slave.add("indexReplicatedAt", d.toString());
} else {
slave.add("indexReplicatedAt", "");
}
slave.add("timesIndexReplicated", timesIndexReplicated);
slave.add("confFilesReplicated", confFilesReplicated);
slave.add("timesConfigReplicated", timesConfigReplicated);
if (confFilesReplicatedTime != null && confFilesReplicatedTime.length() > 0) {
Date d = new Date(Long.valueOf(confFilesReplicatedTime));
slave.add("confFilesReplicatedAt", d.toString());
} else {
slave.add("confFilesReplicatedAt", confFilesReplicatedTime);
}
try {
long bytesToDownload = 0;
List<String> filesToDownload = new ArrayList<String>();
if (snapPuller.getFilesToDownload() != null) {
for (Map<String, Object> file : snapPuller.getFilesToDownload()) {
filesToDownload.add((String) file.get(NAME));
bytesToDownload += (Long) file.get(SIZE);
}
}
//get list of conf files to download
for (Map<String, Object> file : snapPuller.getConfFilesToDownload()) {
filesToDownload.add((String) file.get(NAME));
bytesToDownload += (Long) file.get(SIZE);
}
slave.add("filesToDownload", filesToDownload.toString());
slave.add("numFilesToDownload", String.valueOf(filesToDownload.size()));
slave.add("bytesToDownload", readableSize(bytesToDownload));
long bytesDownloaded = 0;
List<String> filesDownloaded = new ArrayList<String>();
for (Map<String, Object> file : snapPuller.getFilesDownloaded()) {
filesDownloaded.add((String) file.get(NAME));
bytesDownloaded += (Long) file.get(SIZE);
}
//get list of conf files downloaded
for (Map<String, Object> file : snapPuller.getConfFilesDownloaded()) {
filesDownloaded.add((String) file.get(NAME));
bytesDownloaded += (Long) file.get(SIZE);
}
slave.add("filesDownloaded", filesDownloaded.toString());
slave.add("numFilesDownloaded", String.valueOf(filesDownloaded.size()));
Map<String, Object> currentFile = snapPuller.getCurrentFile();
String currFile = null;
long currFileSize = 0, currFileSizeDownloaded = 0;
float percentDownloaded = 0;
if (currentFile != null) {
currFile = (String) currentFile.get(NAME);
currFileSize = (Long) currentFile.get(SIZE);
if (currentFile.containsKey("bytesDownloaded")) {
currFileSizeDownloaded = (Long) currentFile.get("bytesDownloaded");
bytesDownloaded += currFileSizeDownloaded;
if (currFileSize > 0)
percentDownloaded = (currFileSizeDownloaded * 100) / currFileSize;
}
}
long timeElapsed = 0, estimatedTimeRemaining = 0;
Date replicationStartTime = null;
if (snapPuller.getReplicationStartTime() > 0) {
replicationStartTime = new Date(snapPuller.getReplicationStartTime());
timeElapsed = (System.currentTimeMillis() - snapPuller.getReplicationStartTime()) / 1000;
}
if (replicationStartTime != null) {
slave.add("replicationStartTime", replicationStartTime.toString());
}
slave.add("timeElapsed", String.valueOf(timeElapsed) + "s");
if (bytesDownloaded > 0)
estimatedTimeRemaining = ((bytesToDownload - bytesDownloaded) * timeElapsed) / bytesDownloaded;
float totalPercent = 0;
long downloadSpeed = 0;
if (bytesToDownload > 0)
totalPercent = (bytesDownloaded * 100) / bytesToDownload;
if (timeElapsed > 0)
downloadSpeed = (bytesDownloaded / timeElapsed);
if (currFile != null)
slave.add("currentFile", currFile);
slave.add("currentFileSize", readableSize(currFileSize));
slave.add("currentFileSizeDownloaded", readableSize(currFileSizeDownloaded));
slave.add("currentFileSizePercent", String.valueOf(percentDownloaded));
slave.add("bytesDownloaded", readableSize(bytesDownloaded));
slave.add("totalPercent", String.valueOf(totalPercent));
slave.add("timeRemaining", String.valueOf(estimatedTimeRemaining) + "s");
slave.add("downloadSpeed", readableSize(downloadSpeed));
slave.add("isPollingDisabled", String.valueOf(isPollingDisabled()));
slave.add("isReplicating", String.valueOf(isReplicating()));
} catch (Exception e) {
LOG.error("Exception while writing details: ", e);
}
}
if(isMaster)
details.add("master", master);
if(isSlave)
details.add("slave", slave);
NamedList snapshotStats = snapShootDetails;
if (snapshotStats != null)
details.add(CMD_BACKUP, snapshotStats);
return details;
}
void refreshCommitpoint(){
IndexCommit commitPoint = core.getDeletionPolicy().getLatestCommit();
if(replicateOnCommit && !commitPoint.isOptimized()){
indexCommitPoint = commitPoint;
}
if(replicateOnOptimize && commitPoint.isOptimized()){
indexCommitPoint = commitPoint;
}
}
@SuppressWarnings("unchecked")
public void inform(SolrCore core) {
this.core = core;
registerFileStreamResponseWriter();
registerCloseHook();
NamedList slave = (NamedList) initArgs.get("slave");
if (slave != null) {
tempSnapPuller = snapPuller = new SnapPuller(slave, this, core);
isSlave = true;
}
NamedList master = (NamedList) initArgs.get("master");
if (master != null) {
includeConfFiles = (String) master.get(CONF_FILES);
if (includeConfFiles != null && includeConfFiles.trim().length() > 0) {
List<String> files = Arrays.asList(includeConfFiles.split(","));
for (String file : files) {
if (file.trim().length() == 0) continue;
String[] strs = file.split(":");
// if there is an alias add it or it is null
confFileNameAlias.add(strs[0], strs.length > 1 ? strs[1] : null);
}
LOG.info("Replication enabled for following config files: " + includeConfFiles);
}
List backup = master.getAll("backupAfter");
boolean backupOnCommit = backup.contains("commit");
boolean backupOnOptimize = backup.contains("optimize");
List replicateAfter = master.getAll(REPLICATE_AFTER);
replicateOnCommit = replicateAfter.contains("commit");
replicateOnOptimize = replicateAfter.contains("optimize");
if (replicateOnOptimize || backupOnOptimize) {
core.getUpdateHandler().registerOptimizeCallback(getEventListener(backupOnOptimize, replicateOnOptimize));
}
if (replicateOnCommit || backupOnCommit) {
replicateOnCommit = true;
core.getUpdateHandler().registerCommitCallback(getEventListener(backupOnCommit, replicateOnCommit));
}
if (replicateAfter.contains("startup")) {
replicateOnStart = true;
RefCounted<SolrIndexSearcher> s = core.getNewestSearcher(false);
try {
if (core.getUpdateHandler() instanceof DirectUpdateHandler2) {
((DirectUpdateHandler2) core.getUpdateHandler()).forceOpenWriter();
} else {
LOG.warn("The update handler being used is not an instance or sub-class of DirectUpdateHandler2. " +
"Replicate on Startup cannot work.");
}
if(s.get().getReader().getIndexCommit() != null)
if(s.get().getReader().getIndexCommit().getGeneration() != 1L)
indexCommitPoint = s.get().getReader().getIndexCommit();
} catch (IOException e) {
LOG.warn("Unable to get IndexCommit on startup", e);
} finally {
s.decref();
}
}
String reserve = (String) master.get(RESERVE);
if (reserve != null && !reserve.trim().equals("")) {
reserveCommitDuration = SnapPuller.readInterval(reserve);
}
LOG.info("Commits will be reserved for " + reserveCommitDuration);
isMaster = true;
}
}
/**
* register a closehook
*/
private void registerCloseHook() {
core.addCloseHook(new CloseHook() {
public void close(SolrCore core) {
if (snapPuller != null) {
snapPuller.destroy();
}
}
});
}
/**
* A ResponseWriter is registered automatically for wt=filestream This response writer is used to transfer index files
* in a block-by-block manner within the same HTTP response.
*/
private void registerFileStreamResponseWriter() {
core.registerResponseWriter(FILE_STREAM, new BinaryQueryResponseWriter() {
public void write(OutputStream out, SolrQueryRequest request, SolrQueryResponse resp) throws IOException {
FileStream stream = (FileStream) resp.getValues().get(FILE_STREAM);
stream.write(out);
}
public void write(Writer writer, SolrQueryRequest request, SolrQueryResponse response) throws IOException {
throw new RuntimeException("This is a binary writer , Cannot write to a characterstream");
}
public String getContentType(SolrQueryRequest request, SolrQueryResponse response) {
return "application/octet-stream";
}
public void init(NamedList args) { /*no op*/ }
});
}
/**
* Register a listener for postcommit/optimize
*
* @param snapshoot do a snapshoot
* @param getCommit get a commitpoint also
*
* @return an instance of the eventlistener
*/
private SolrEventListener getEventListener(final boolean snapshoot, final boolean getCommit) {
return new SolrEventListener() {
public void init(NamedList args) {/*no op*/ }
/**
* This refreshes the latest replicateable index commit and optionally can create Snapshots as well
*/
public void postCommit() {
if (getCommit) {
indexCommitPoint = core.getDeletionPolicy().getLatestCommit();
}
if (snapshoot) {
try {
SnapShooter snapShooter = new SnapShooter(core, null);
snapShooter.createSnapAsync(core.getDeletionPolicy().getLatestCommit().getFileNames(), ReplicationHandler.this);
} catch (Exception e) {
LOG.error("Exception while snapshooting", e);
}
}
}
public void newSearcher(SolrIndexSearcher newSearcher, SolrIndexSearcher currentSearcher) { /*no op*/}
};
}
private class FileStream {
private SolrParams params;
private FastOutputStream fos;
private Long indexVersion;
private IndexDeletionPolicyWrapper delPolicy;
public FileStream(SolrParams solrParams) {
params = solrParams;
delPolicy = core.getDeletionPolicy();
}
public void write(OutputStream out) throws IOException {
String fileName = params.get(FILE);
String cfileName = params.get(CONF_FILE_SHORT);
String sOffset = params.get(OFFSET);
String sLen = params.get(LEN);
String compress = params.get(COMPRESSION);
String sChecksum = params.get(CHECKSUM);
String sindexVersion = params.get(CMD_INDEX_VERSION);
if (sindexVersion != null) indexVersion = Long.parseLong(sindexVersion);
if (Boolean.parseBoolean(compress)) {
fos = new FastOutputStream(new DeflaterOutputStream(out));
} else {
fos = new FastOutputStream(out);
}
FileInputStream inputStream = null;
int packetsWritten = 0;
try {
long offset = -1;
int len = -1;
//check if checksum is requested
boolean useChecksum = Boolean.parseBoolean(sChecksum);
if (sOffset != null)
offset = Long.parseLong(sOffset);
if (sLen != null)
len = Integer.parseInt(sLen);
if (fileName == null && cfileName == null) {
//no filename do nothing
writeNothing();
}
File file = null;
if (cfileName != null) {
//if if is a conf file read from config diectory
file = new File(core.getResourceLoader().getConfigDir(), cfileName);
} else {
//else read from the indexdirectory
file = new File(core.getIndexDir(), fileName);
}
if (file.exists() && file.canRead()) {
inputStream = new FileInputStream(file);
FileChannel channel = inputStream.getChannel();
//if offset is mentioned move the pointer to that point
if (offset != -1)
channel.position(offset);
byte[] buf = new byte[(len == -1 || len > PACKET_SZ) ? PACKET_SZ : len];
Checksum checksum = null;
if (useChecksum)
checksum = new Adler32();
ByteBuffer bb = ByteBuffer.wrap(buf);
while (true) {
bb.clear();
long bytesRead = channel.read(bb);
if (bytesRead <= 0) {
writeNothing();
fos.close();
break;
}
fos.writeInt((int) bytesRead);
if (useChecksum) {
checksum.reset();
checksum.update(buf, 0, (int) bytesRead);
fos.writeLong(checksum.getValue());
}
fos.write(buf, 0, (int) bytesRead);
fos.flush();
if (indexVersion != null && (packetsWritten % 5 == 0)) {
//after every 5 packets reserve the commitpoint for some time
delPolicy.setReserveDuration(indexVersion, reserveCommitDuration);
}
packetsWritten++;
}
} else {
writeNothing();
}
} catch (IOException e) {
LOG.warn("Exception while writing response for params: " + params, e);
} finally {
IOUtils.closeQuietly(inputStream);
}
}
/**
* Used to write a marker for EOF
*/
private void writeNothing() throws IOException {
fos.writeInt(0);
fos.flush();
}
}
public static final String MASTER_URL = "masterUrl";
public static final String STATUS = "status";
public static final String COMMAND = "command";
public static final String CMD_DETAILS = "details";
public static final String CMD_BACKUP = "backup";
public static final String CMD_FETCH_INDEX = "fetchindex";
public static final String CMD_ABORT_FETCH = "abortfetch";
public static final String CMD_GET_FILE_LIST = "filelist";
public static final String CMD_GET_FILE = "filecontent";
public static final String CMD_FILE_CHECKSUM = "filechecksum";
public static final String CMD_DISABLE_POLL = "disablepoll";
public static final String CMD_DISABLE_REPL = "disablereplication";
public static final String CMD_ENABLE_REPL = "enablereplication";
public static final String CMD_ENABLE_POLL = "enablepoll";
public static final String CMD_INDEX_VERSION = "indexversion";
public static final String CMD_SHOW_COMMITS = "commits";
public static final String GENERATION = "generation";
public static final String OFFSET = "offset";
public static final String LEN = "len";
public static final String FILE = "file";
public static final String NAME = "name";
public static final String SIZE = "size";
public static final String LAST_MODIFIED = "lastmodified";
public static final String CONF_FILE_SHORT = "cf";
public static final String CHECKSUM = "checksum";
public static final String ALIAS = "alias";
public static final String CONF_CHECKSUM = "confchecksum";
public static final String CONF_FILES = "confFiles";
public static final String REPLICATE_AFTER = "replicateAfter";
public static final String FILE_STREAM = "filestream";
public static final int PACKET_SZ = 1024 * 1024; // 1MB
public static final String RESERVE = "commitReserveDuration";
public static final String COMPRESSION = "compression";
public static final String EXTERNAL = "external";
public static final String INTERNAL = "internal";
public static final String ERR_STATUS = "ERROR";
public static final String OK_STATUS = "OK";
}
| src/java/org/apache/solr/handler/ReplicationHandler.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.solr.handler;
import org.apache.lucene.index.IndexCommit;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.FastOutputStream;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.core.CloseHook;
import org.apache.solr.core.IndexDeletionPolicyWrapper;
import org.apache.solr.core.SolrCore;
import org.apache.solr.core.SolrEventListener;
import org.apache.solr.request.BinaryQueryResponseWriter;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrQueryResponse;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.update.DirectUpdateHandler2;
import org.apache.solr.util.RefCounted;
import org.apache.solr.util.plugin.SolrCoreAware;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.zip.Adler32;
import java.util.zip.Checksum;
import java.util.zip.DeflaterOutputStream;
/**
* <p> A Handler which provides a REST API for replication and serves replication requests from Slaves. <p/> </p>
* <p>When running on the master, it provides the following commands <ol> <li>Get the current replicatable index version
* (command=indexversion)</li> <li>Get the list of files for a given index version
* (command=filelist&indexversion=<VERSION>)</li> <li>Get full or a part (chunk) of a given index or a config
* file (command=filecontent&file=<FILE_NAME>) You can optionally specify an offset and length to get that
* chunk of the file. You can request a configuration file by using "cf" parameter instead of the "file" parameter.</li>
* <li>Get status/statistics (command=details)</li> </ol> </p> <p>When running on the slave, it provides the following
* commands <ol> <li>Perform a snap pull now (command=snappull)</li> <li>Get status/statistics (command=details)</li>
* <li>Abort a snap pull (command=abort)</li> <li>Enable/Disable polling the master for new versions (command=enablepoll
* or command=disablepoll)</li> </ol> </p>
*
* @version $Id$
* @since solr 1.4
*/
public class ReplicationHandler extends RequestHandlerBase implements SolrCoreAware {
private static final Logger LOG = LoggerFactory.getLogger(ReplicationHandler.class.getName());
private SolrCore core;
private SnapPuller snapPuller;
private ReentrantLock snapPullLock = new ReentrantLock();
private String includeConfFiles;
private NamedList<String> confFileNameAlias = new NamedList<String>();
private boolean isMaster = false;
private boolean isSlave = false;
private boolean replicateOnOptimize = false;
private boolean replicateOnCommit = false;
private boolean replicateOnStart = false;
private int numTimesReplicated = 0;
private final Map<String, FileInfo> confFileInfoCache = new HashMap<String, FileInfo>();
private Integer reserveCommitDuration = SnapPuller.readInterval("00:00:10");
private volatile IndexCommit indexCommitPoint;
volatile NamedList snapShootDetails;
private AtomicBoolean replicationEnabled = new AtomicBoolean(true);
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
rsp.setHttpCaching(false);
final SolrParams solrParams = req.getParams();
String command = solrParams.get(COMMAND);
if (command == null) {
rsp.add(STATUS, OK_STATUS);
rsp.add("message", "No command");
return;
}
// This command does not give the current index version of the master
// It gives the current 'replicateable' index version
if(CMD_ENABLE_REPL.equalsIgnoreCase(command)){
replicationEnabled.set(true);
rsp.add(STATUS, OK_STATUS);
} else if(CMD_DISABLE_REPL.equalsIgnoreCase(command)){
replicationEnabled.set(false);
rsp.add(STATUS, OK_STATUS);
} else if (command.equals(CMD_INDEX_VERSION)) {
IndexCommit commitPoint = indexCommitPoint; // make a copy so it won't change
if (commitPoint != null && replicationEnabled.get()) {
rsp.add(CMD_INDEX_VERSION, commitPoint.getVersion());
rsp.add(GENERATION, commitPoint.getGeneration());
} else {
// This happens when replication is not configured to happen after startup and no commit/optimize
// has happened yet.
rsp.add(CMD_INDEX_VERSION, 0L);
rsp.add(GENERATION, 0L);
}
} else if (command.equals(CMD_GET_FILE)) {
getFileStream(solrParams, rsp);
} else if (command.equals(CMD_GET_FILE_LIST)) {
getFileList(solrParams, rsp);
} else if (command.equalsIgnoreCase(CMD_BACKUP)) {
doSnapShoot(new ModifiableSolrParams(solrParams), rsp);
rsp.add(STATUS, OK_STATUS);
} else if (command.equalsIgnoreCase(CMD_FETCH_INDEX)) {
String masterUrl = solrParams.get(MASTER_URL);
if (!isSlave && masterUrl == null) {
rsp.add(STATUS,ERR_STATUS);
rsp.add("message","No slave configured or no 'masterUrl' Specified");
return;
}
final SolrParams paramsCopy = new ModifiableSolrParams(solrParams);
new Thread() {
public void run() {
doFetch(paramsCopy);
}
}.start();
rsp.add(STATUS, OK_STATUS);
} else if (command.equalsIgnoreCase(CMD_DISABLE_POLL)) {
if (snapPuller != null){
snapPuller.disablePoll();
rsp.add(STATUS, OK_STATUS);
} else {
rsp.add(STATUS, ERR_STATUS);
rsp.add("message","No slave configured");
}
} else if (command.equalsIgnoreCase(CMD_ENABLE_POLL)) {
if (snapPuller != null){
snapPuller.enablePoll();
rsp.add(STATUS, OK_STATUS);
}else {
rsp.add(STATUS,ERR_STATUS);
rsp.add("message","No slave configured");
}
} else if (command.equalsIgnoreCase(CMD_ABORT_FETCH)) {
if (snapPuller != null){
snapPuller.abortPull();
rsp.add(STATUS, OK_STATUS);
} else {
rsp.add(STATUS,ERR_STATUS);
rsp.add("message","No slave configured");
}
} else if (command.equals(CMD_FILE_CHECKSUM)) {
// this command is not used by anyone
getFileChecksum(solrParams, rsp);
} else if (command.equals(CMD_SHOW_COMMITS)) {
rsp.add(CMD_SHOW_COMMITS, getCommits());
} else if (command.equals(CMD_DETAILS)) {
rsp.add(CMD_DETAILS, getReplicationDetails());
RequestHandlerUtils.addExperimentalFormatWarning(rsp);
}
}
private List<NamedList> getCommits() {
Map<Long, IndexCommit> commits = core.getDeletionPolicy().getCommits();
List<NamedList> l = new ArrayList<NamedList>();
for (IndexCommit c : commits.values()) {
try {
NamedList nl = new NamedList();
nl.add("indexVersion", c.getVersion());
nl.add(GENERATION, c.getGeneration());
nl.add(CMD_GET_FILE_LIST, c.getFileNames().toString());
l.add(nl);
} catch (IOException e) {
LOG.warn("Exception while reading files for commit " + c, e);
}
}
return l;
}
/**
* Gets the checksum of a file
*/
private void getFileChecksum(SolrParams solrParams, SolrQueryResponse rsp) {
Checksum checksum = new Adler32();
File dir = new File(core.getIndexDir());
rsp.add(CHECKSUM, getCheckSums(solrParams.getParams(FILE), dir, checksum));
dir = new File(core.getResourceLoader().getConfigDir());
rsp.add(CONF_CHECKSUM, getCheckSums(solrParams.getParams(CONF_FILE_SHORT), dir, checksum));
}
private Map<String, Long> getCheckSums(String[] files, File dir, Checksum checksum) {
Map<String, Long> checksumMap = new HashMap<String, Long>();
if (files == null || files.length == 0)
return checksumMap;
for (String file : files) {
File f = new File(dir, file);
Long checkSumVal = getCheckSum(checksum, f);
if (checkSumVal != null)
checksumMap.put(file, checkSumVal);
}
return checksumMap;
}
static Long getCheckSum(Checksum checksum, File f) {
FileInputStream fis = null;
checksum.reset();
byte[] buffer = new byte[1024 * 1024];
int bytesRead;
try {
fis = new FileInputStream(f);
while ((bytesRead = fis.read(buffer)) >= 0)
checksum.update(buffer, 0, bytesRead);
return checksum.getValue();
} catch (Exception e) {
LOG.warn("Exception in finding checksum of " + f, e);
} finally {
IOUtils.closeQuietly(fis);
}
return null;
}
private volatile SnapPuller tempSnapPuller;
void doFetch(SolrParams solrParams) {
String masterUrl = solrParams == null ? null : solrParams.get(MASTER_URL);
if (!snapPullLock.tryLock())
return;
try {
tempSnapPuller = snapPuller;
if (masterUrl != null) {
NamedList<Object> nl = solrParams.toNamedList();
nl.remove(SnapPuller.POLL_INTERVAL);
tempSnapPuller = new SnapPuller(nl, this, core);
}
tempSnapPuller.fetchLatestIndex(core);
} catch (Exception e) {
LOG.error("SnapPull failed ", e);
} finally {
tempSnapPuller = snapPuller;
snapPullLock.unlock();
}
}
boolean isReplicating() {
return snapPullLock.isLocked();
}
private void doSnapShoot(SolrParams params, SolrQueryResponse rsp) {
try {
IndexCommit indexCommit = core.getDeletionPolicy().getLatestCommit();
if (indexCommit != null) {
new SnapShooter(core, params.get("location")).createSnapAsync(indexCommit.getFileNames(), this);
}
} catch (Exception e) {
LOG.warn("Exception during creating a snapshot", e);
rsp.add("exception", e);
}
}
/**
* This method adds an Object of FileStream to the resposnse . The FileStream implements a custom protocol which is
* understood by SnapPuller.FileFetcher
*
* @see org.apache.solr.handler.SnapPuller.FileFetcher
*/
private void getFileStream(SolrParams solrParams, SolrQueryResponse rsp) {
ModifiableSolrParams rawParams = new ModifiableSolrParams(solrParams);
rawParams.set(CommonParams.WT, FILE_STREAM);
rsp.add(FILE_STREAM, new FileStream(solrParams));
}
@SuppressWarnings("unchecked")
private void getFileList(SolrParams solrParams, SolrQueryResponse rsp) {
String v = solrParams.get(CMD_INDEX_VERSION);
if (v == null) {
rsp.add("status", "no indexversion specified");
return;
}
long version = Long.parseLong(v);
IndexCommit commit = core.getDeletionPolicy().getCommitPoint(version);
if (commit == null) {
rsp.add("status", "invalid indexversion");
return;
}
// reserve the indexcommit for sometime
core.getDeletionPolicy().setReserveDuration(version, reserveCommitDuration);
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
try {
//get all the files in the commit
//use a set to workaround possible Lucene bug which returns same file name multiple times
Collection<String> files = new HashSet<String>(commit.getFileNames());
for (String fileName : files) {
File file = new File(core.getIndexDir(), fileName);
Map<String, Object> fileMeta = getFileInfo(file);
result.add(fileMeta);
}
} catch (IOException e) {
rsp.add("status", "unable to get file names for given indexversion");
rsp.add("exception", e);
LOG.warn("Unable to get file names for indexCommit version: "
+ version, e);
}
rsp.add(CMD_GET_FILE_LIST, result);
if (confFileNameAlias.size() < 1)
return;
LOG.debug("Adding config files to list: " + includeConfFiles);
//if configuration files need to be included get their details
rsp.add(CONF_FILES, getConfFileInfoFromCache(confFileNameAlias, confFileInfoCache));
}
/**
* For configuration files, checksum of the file is included because, unlike index files, they may have same content
* but different timestamps.
* <p/>
* The local conf files information is cached so that everytime it does not have to compute the checksum. The cache is
* refreshed only if the lastModified of the file changes
*/
List<Map<String, Object>> getConfFileInfoFromCache(NamedList<String> nameAndAlias,
final Map<String, FileInfo> confFileInfoCache) {
List<Map<String, Object>> confFiles = new ArrayList<Map<String, Object>>();
synchronized (confFileInfoCache) {
File confDir = new File(core.getResourceLoader().getConfigDir());
Checksum checksum = null;
for (int i = 0; i < nameAndAlias.size(); i++) {
String cf = nameAndAlias.getName(i);
File f = new File(confDir, cf);
if (!f.exists() || f.isDirectory()) continue; //must not happen
FileInfo info = confFileInfoCache.get(cf);
if (info == null || info.lastmodified != f.lastModified() || info.size != f.length()) {
if (checksum == null) checksum = new Adler32();
info = new FileInfo(f.lastModified(), cf, f.length(), getCheckSum(checksum, f));
confFileInfoCache.put(cf, info);
}
Map<String, Object> m = info.getAsMap();
if (nameAndAlias.getVal(i) != null) m.put(ALIAS, nameAndAlias.getVal(i));
confFiles.add(m);
}
}
return confFiles;
}
static class FileInfo {
long lastmodified;
String name;
long size;
long checksum;
public FileInfo(long lasmodified, String name, long size, long checksum) {
this.lastmodified = lasmodified;
this.name = name;
this.size = size;
this.checksum = checksum;
}
Map<String, Object> getAsMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put(NAME, name);
map.put(SIZE, size);
map.put(LAST_MODIFIED, lastmodified);
map.put(CHECKSUM, checksum);
return map;
}
}
void disablePoll() {
if (isSlave)
snapPuller.disablePoll();
}
void enablePoll() {
if (isSlave)
snapPuller.enablePoll();
}
boolean isPollingDisabled() {
return snapPuller.isPollingDisabled();
}
int getTimesReplicatedSinceStartup() {
return numTimesReplicated;
}
void setTimesReplicatedSinceStartup() {
numTimesReplicated++;
}
long getIndexSize() {
return computeIndexSize(new File(core.getIndexDir()));
}
private long computeIndexSize(File f) {
if (f.isFile())
return f.length();
File[] files = f.listFiles();
long size = 0;
if (files != null && files.length > 0) {
for (File file : files) size += file.length();
}
return size;
}
/**
* Collects the details such as name, size ,lastModified of a file
*/
private Map<String, Object> getFileInfo(File file) {
Map<String, Object> fileMeta = new HashMap<String, Object>();
fileMeta.put(NAME, file.getName());
fileMeta.put(SIZE, file.length());
fileMeta.put(LAST_MODIFIED, file.lastModified());
return fileMeta;
}
public String getDescription() {
return "ReplicationHandler provides replication of index and configuration files from Master to Slaves";
}
public String getSourceId() {
return "$Id$";
}
public String getSource() {
return "$URL$";
}
public String getVersion() {
return "$Revision$";
}
String readableSize(long size) {
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMaximumFractionDigits(2);
if (size / (1024 * 1024 * 1024) > 0) {
return formatter.format(size * 1.0d / (1024 * 1024 * 1024)) + " GB";
} else if (size / (1024 * 1024) > 0) {
return formatter.format(size * 1.0d / (1024 * 1024)) + " MB";
} else if (size / 1024 > 0) {
return formatter.format(size * 1.0d / 1024) + " KB";
} else {
return String.valueOf(size) + " bytes";
}
}
private long[] getIndexVersion() {
long version[] = new long[2];
RefCounted<SolrIndexSearcher> searcher = core.getSearcher();
try {
version[0] = searcher.get().getReader().getIndexCommit().getVersion();
version[1] = searcher.get().getReader().getIndexCommit().getGeneration();
} catch (IOException e) {
LOG.warn("Unable to get index version : ", e);
} finally {
searcher.decref();
}
return version;
}
@Override
@SuppressWarnings("unchecked")
public NamedList getStatistics() {
NamedList list = super.getStatistics();
if (core != null) {
list.add("indexSize", readableSize(getIndexSize()));
long[] versionGen = getIndexVersion();
list.add("indexVersion", versionGen[0]);
list.add(GENERATION, versionGen[1]);
list.add("indexPath", core.getIndexDir());
list.add("isMaster", String.valueOf(isMaster));
list.add("isSlave", String.valueOf(isSlave));
SnapPuller snapPuller = tempSnapPuller;
if (snapPuller != null) {
list.add(MASTER_URL, snapPuller.getMasterUrl());
if (snapPuller.getPollInterval() != null) {
list.add(SnapPuller.POLL_INTERVAL, snapPuller.getPollInterval());
}
list.add("isPollingDisabled", String.valueOf(isPollingDisabled()));
list.add("isReplicating", String.valueOf(isReplicating()));
}
if (isMaster) {
if (includeConfFiles != null)
list.add("confFilesToReplicate", includeConfFiles);
String replicateAfterString="";
if (replicateOnCommit)
replicateAfterString += "commit, ";
if (replicateOnOptimize)
replicateAfterString += "optimize, ";
if(replicateOnStart)
replicateAfterString += "startup, ";
if(replicateAfterString.lastIndexOf(',') > -1)
replicateAfterString = replicateAfterString.substring(0, replicateAfterString.lastIndexOf(','));
list.add(REPLICATE_AFTER, replicateAfterString);
}
}
return list;
}
/**
* Used for showing statistics and progress information.
*/
NamedList<Object> getReplicationDetails() {
String timeLastReplicated = "", confFilesReplicated = "", confFilesReplicatedTime = "", timesIndexReplicated = "", timesConfigReplicated = "";
NamedList<Object> details = new SimpleOrderedMap<Object>();
NamedList<Object> master = new SimpleOrderedMap<Object>();
NamedList<Object> slave = new SimpleOrderedMap<Object>();
FileInputStream inFile = null;
details.add("indexSize", readableSize(getIndexSize()));
details.add("indexPath", core.getIndexDir());
details.add(CMD_SHOW_COMMITS, getCommits());
details.add("isMaster", String.valueOf(isMaster));
details.add("isSlave", String.valueOf(isSlave));
long[] versionAndGeneration = getIndexVersion();
details.add("indexVersion", versionAndGeneration[0]);
details.add(GENERATION, versionAndGeneration[1]);
IndexCommit commit = indexCommitPoint; // make a copy so it won't change
if (isMaster) {
if (includeConfFiles != null)
master.add(CONF_FILES, includeConfFiles);
String replicateAfterString="";
if (replicateOnCommit)
replicateAfterString += "commit, ";
if (replicateOnOptimize)
replicateAfterString += "optimize, ";
if(replicateOnStart)
replicateAfterString += "startup, ";
if(replicateAfterString.lastIndexOf(',') > -1)
replicateAfterString = replicateAfterString.substring(0, replicateAfterString.lastIndexOf(','));
master.add(REPLICATE_AFTER, replicateAfterString);
}
if (isMaster && commit != null) {
master.add("replicatableIndexVersion", commit.getVersion());
master.add("replicatableGeneration", commit.getGeneration());
}
SnapPuller snapPuller = tempSnapPuller;
if (snapPuller != null) {
try {
Properties props = new Properties();
File f = new File(core.getDataDir(), SnapPuller.REPLICATION_PROPERTIES);
if (f.exists()) {
inFile = new FileInputStream(f);
props.load(inFile);
timeLastReplicated = props.getProperty("indexReplicatedAt");
if (props.containsKey("timesIndexReplicated"))
timesIndexReplicated = props.getProperty("timesIndexReplicated");
if (props.containsKey("confFilesReplicated"))
confFilesReplicated = props.getProperty("confFilesReplicated");
if (props.containsKey("confFilesReplicatedAt"))
confFilesReplicatedTime = props.getProperty("confFilesReplicatedAt");
if (props.containsKey("timesConfigReplicated"))
timesConfigReplicated = props.getProperty("timesConfigReplicated");
}
} catch (Exception e) {
LOG.warn("Exception while reading " + SnapPuller.REPLICATION_PROPERTIES);
} finally {
IOUtils.closeQuietly(inFile);
}
try {
NamedList nl = snapPuller.getCommandResponse(CMD_DETAILS);
slave.add("masterDetails", nl.get(CMD_DETAILS));
} catch (IOException e) {
LOG.warn("Exception while invoking a 'details' method on master ", e);
}
slave.add(MASTER_URL, snapPuller.getMasterUrl());
if (snapPuller.getPollInterval() != null) {
slave.add(SnapPuller.POLL_INTERVAL, snapPuller.getPollInterval());
}
if (snapPuller.getNextScheduledExecTime() != null && !isPollingDisabled()) {
Date d = new Date(snapPuller.getNextScheduledExecTime());
slave.add("nextExecutionAt", d.toString());
} else if (isPollingDisabled()) {
slave.add("nextExecutionAt", "Polling disabled");
} else
slave.add("nextExecutionAt", "");
if (timeLastReplicated != null && timeLastReplicated.length() > 0) {
Date d = new Date(Long.valueOf(timeLastReplicated));
slave.add("indexReplicatedAt", d.toString());
} else {
slave.add("indexReplicatedAt", "");
}
slave.add("timesIndexReplicated", timesIndexReplicated);
slave.add("confFilesReplicated", confFilesReplicated);
slave.add("timesConfigReplicated", timesConfigReplicated);
if (confFilesReplicatedTime != null && confFilesReplicatedTime.length() > 0) {
Date d = new Date(Long.valueOf(confFilesReplicatedTime));
slave.add("confFilesReplicatedAt", d.toString());
} else {
slave.add("confFilesReplicatedAt", confFilesReplicatedTime);
}
try {
long bytesToDownload = 0;
List<String> filesToDownload = new ArrayList<String>();
if (snapPuller.getFilesToDownload() != null) {
for (Map<String, Object> file : snapPuller.getFilesToDownload()) {
filesToDownload.add((String) file.get(NAME));
bytesToDownload += (Long) file.get(SIZE);
}
}
//get list of conf files to download
for (Map<String, Object> file : snapPuller.getConfFilesToDownload()) {
filesToDownload.add((String) file.get(NAME));
bytesToDownload += (Long) file.get(SIZE);
}
slave.add("filesToDownload", filesToDownload.toString());
slave.add("numFilesToDownload", String.valueOf(filesToDownload.size()));
slave.add("bytesToDownload", readableSize(bytesToDownload));
long bytesDownloaded = 0;
List<String> filesDownloaded = new ArrayList<String>();
for (Map<String, Object> file : snapPuller.getFilesDownloaded()) {
filesDownloaded.add((String) file.get(NAME));
bytesDownloaded += (Long) file.get(SIZE);
}
//get list of conf files downloaded
for (Map<String, Object> file : snapPuller.getConfFilesDownloaded()) {
filesDownloaded.add((String) file.get(NAME));
bytesDownloaded += (Long) file.get(SIZE);
}
slave.add("filesDownloaded", filesDownloaded.toString());
slave.add("numFilesDownloaded", String.valueOf(filesDownloaded.size()));
Map<String, Object> currentFile = snapPuller.getCurrentFile();
String currFile = null;
long currFileSize = 0, currFileSizeDownloaded = 0;
float percentDownloaded = 0;
if (currentFile != null) {
currFile = (String) currentFile.get(NAME);
currFileSize = (Long) currentFile.get(SIZE);
if (currentFile.containsKey("bytesDownloaded")) {
currFileSizeDownloaded = (Long) currentFile.get("bytesDownloaded");
bytesDownloaded += currFileSizeDownloaded;
if (currFileSize > 0)
percentDownloaded = (currFileSizeDownloaded * 100) / currFileSize;
}
}
long timeElapsed = 0, estimatedTimeRemaining = 0;
Date replicationStartTime = null;
if (snapPuller.getReplicationStartTime() > 0) {
replicationStartTime = new Date(snapPuller.getReplicationStartTime());
timeElapsed = (System.currentTimeMillis() - snapPuller.getReplicationStartTime()) / 1000;
}
if (replicationStartTime != null) {
slave.add("replicationStartTime", replicationStartTime.toString());
}
slave.add("timeElapsed", String.valueOf(timeElapsed) + "s");
if (bytesDownloaded > 0)
estimatedTimeRemaining = ((bytesToDownload - bytesDownloaded) * timeElapsed) / bytesDownloaded;
float totalPercent = 0;
long downloadSpeed = 0;
if (bytesToDownload > 0)
totalPercent = (bytesDownloaded * 100) / bytesToDownload;
if (timeElapsed > 0)
downloadSpeed = (bytesDownloaded / timeElapsed);
if (currFile != null)
slave.add("currentFile", currFile);
slave.add("currentFileSize", readableSize(currFileSize));
slave.add("currentFileSizeDownloaded", readableSize(currFileSizeDownloaded));
slave.add("currentFileSizePercent", String.valueOf(percentDownloaded));
slave.add("bytesDownloaded", readableSize(bytesDownloaded));
slave.add("totalPercent", String.valueOf(totalPercent));
slave.add("timeRemaining", String.valueOf(estimatedTimeRemaining) + "s");
slave.add("downloadSpeed", readableSize(downloadSpeed));
slave.add("isPollingDisabled", String.valueOf(isPollingDisabled()));
slave.add("isReplicating", String.valueOf(isReplicating()));
} catch (Exception e) {
LOG.error("Exception while writing details: ", e);
}
}
if(isMaster)
details.add("master", master);
if(isSlave)
details.add("slave", slave);
NamedList snapshotStats = snapShootDetails;
if (snapshotStats != null)
details.add(CMD_BACKUP, snapshotStats);
return details;
}
void refreshCommitpoint(){
IndexCommit commitPoint = core.getDeletionPolicy().getLatestCommit();
if(replicateOnCommit && !commitPoint.isOptimized()){
indexCommitPoint = commitPoint;
}
if(replicateOnOptimize && commitPoint.isOptimized()){
indexCommitPoint = commitPoint;
}
}
@SuppressWarnings("unchecked")
public void inform(SolrCore core) {
this.core = core;
registerFileStreamResponseWriter();
registerCloseHook();
NamedList slave = (NamedList) initArgs.get("slave");
if (slave != null) {
tempSnapPuller = snapPuller = new SnapPuller(slave, this, core);
isSlave = true;
}
NamedList master = (NamedList) initArgs.get("master");
if (master != null) {
includeConfFiles = (String) master.get(CONF_FILES);
if (includeConfFiles != null && includeConfFiles.trim().length() > 0) {
List<String> files = Arrays.asList(includeConfFiles.split(","));
for (String file : files) {
if (file.trim().length() == 0) continue;
String[] strs = file.split(":");
// if there is an alias add it or it is null
confFileNameAlias.add(strs[0], strs.length > 1 ? strs[1] : null);
}
LOG.info("Replication enabled for following config files: " + includeConfFiles);
}
List backup = master.getAll("backupAfter");
boolean backupOnCommit = backup.contains("commit");
boolean backupOnOptimize = backup.contains("optimize");
List replicateAfter = master.getAll(REPLICATE_AFTER);
replicateOnCommit = replicateAfter.contains("commit");
replicateOnOptimize = replicateAfter.contains("optimize");
if (replicateOnOptimize || backupOnOptimize) {
core.getUpdateHandler().registerOptimizeCallback(getEventListener(backupOnOptimize, replicateOnOptimize));
}
if (replicateOnCommit || backupOnCommit) {
replicateOnCommit = true;
core.getUpdateHandler().registerCommitCallback(getEventListener(backupOnCommit, replicateOnCommit));
}
if (replicateAfter.contains("startup")) {
replicateOnStart = true;
RefCounted<SolrIndexSearcher> s = core.getNewestSearcher(false);
try {
if (core.getUpdateHandler() instanceof DirectUpdateHandler2) {
((DirectUpdateHandler2) core.getUpdateHandler()).forceOpenWriter();
} else {
LOG.warn("The update handler being used is not an instance or sub-class of DirectUpdateHandler2. " +
"Replicate on Startup cannot work.");
}
if(s.get().getReader().getIndexCommit() != null)
if(s.get().getReader().getIndexCommit().getGeneration() != 1L)
indexCommitPoint = s.get().getReader().getIndexCommit();
} catch (IOException e) {
LOG.warn("Unable to get IndexCommit on startup", e);
} finally {
s.decref();
}
}
String reserve = (String) master.get(RESERVE);
if (reserve != null && !reserve.trim().equals("")) {
reserveCommitDuration = SnapPuller.readInterval(reserve);
}
LOG.info("Commits will be reserved for " + reserveCommitDuration);
isMaster = true;
}
}
/**
* register a closehook
*/
private void registerCloseHook() {
core.addCloseHook(new CloseHook() {
public void close(SolrCore core) {
if (snapPuller != null) {
snapPuller.destroy();
}
}
});
}
/**
* A ResponseWriter is registered automatically for wt=filestream This response writer is used to transfer index files
* in a block-by-block manner within the same HTTP response.
*/
private void registerFileStreamResponseWriter() {
core.registerResponseWriter(FILE_STREAM, new BinaryQueryResponseWriter() {
public void write(OutputStream out, SolrQueryRequest request, SolrQueryResponse resp) throws IOException {
FileStream stream = (FileStream) resp.getValues().get(FILE_STREAM);
stream.write(out);
}
public void write(Writer writer, SolrQueryRequest request, SolrQueryResponse response) throws IOException {
throw new RuntimeException("This is a binary writer , Cannot write to a characterstream");
}
public String getContentType(SolrQueryRequest request, SolrQueryResponse response) {
return "application/octet-stream";
}
public void init(NamedList args) { /*no op*/ }
});
}
/**
* Register a listener for postcommit/optimize
*
* @param snapshoot do a snapshoot
* @param getCommit get a commitpoint also
*
* @return an instance of the eventlistener
*/
private SolrEventListener getEventListener(final boolean snapshoot, final boolean getCommit) {
return new SolrEventListener() {
public void init(NamedList args) {/*no op*/ }
/**
* This refreshes the latest replicateable index commit and optionally can create Snapshots as well
*/
public void postCommit() {
if (getCommit) {
indexCommitPoint = core.getDeletionPolicy().getLatestCommit();
}
if (snapshoot) {
try {
SnapShooter snapShooter = new SnapShooter(core, null);
snapShooter.createSnapAsync(core.getDeletionPolicy().getLatestCommit().getFileNames(), ReplicationHandler.this);
} catch (Exception e) {
LOG.error("Exception while snapshooting", e);
}
}
}
public void newSearcher(SolrIndexSearcher newSearcher, SolrIndexSearcher currentSearcher) { /*no op*/}
};
}
private class FileStream {
private SolrParams params;
private FastOutputStream fos;
private Long indexVersion;
private IndexDeletionPolicyWrapper delPolicy;
public FileStream(SolrParams solrParams) {
params = solrParams;
delPolicy = core.getDeletionPolicy();
}
public void write(OutputStream out) throws IOException {
String fileName = params.get(FILE);
String cfileName = params.get(CONF_FILE_SHORT);
String sOffset = params.get(OFFSET);
String sLen = params.get(LEN);
String compress = params.get(COMPRESSION);
String sChecksum = params.get(CHECKSUM);
String sindexVersion = params.get(CMD_INDEX_VERSION);
if (sindexVersion != null) indexVersion = Long.parseLong(sindexVersion);
if (Boolean.parseBoolean(compress)) {
fos = new FastOutputStream(new DeflaterOutputStream(out));
} else {
fos = new FastOutputStream(out);
}
FileInputStream inputStream = null;
int packetsWritten = 0;
try {
long offset = -1;
int len = -1;
//check if checksum is requested
boolean useChecksum = Boolean.parseBoolean(sChecksum);
if (sOffset != null)
offset = Long.parseLong(sOffset);
if (sLen != null)
len = Integer.parseInt(sLen);
if (fileName == null && cfileName == null) {
//no filename do nothing
writeNothing();
}
File file = null;
if (cfileName != null) {
//if if is a conf file read from config diectory
file = new File(core.getResourceLoader().getConfigDir(), cfileName);
} else {
//else read from the indexdirectory
file = new File(core.getIndexDir(), fileName);
}
if (file.exists() && file.canRead()) {
inputStream = new FileInputStream(file);
FileChannel channel = inputStream.getChannel();
//if offset is mentioned move the pointer to that point
if (offset != -1)
channel.position(offset);
byte[] buf = new byte[(len == -1 || len > PACKET_SZ) ? PACKET_SZ : len];
Checksum checksum = null;
if (useChecksum)
checksum = new Adler32();
ByteBuffer bb = ByteBuffer.wrap(buf);
while (true) {
bb.clear();
long bytesRead = channel.read(bb);
if (bytesRead <= 0) {
writeNothing();
fos.close();
break;
}
fos.writeInt((int) bytesRead);
if (useChecksum) {
checksum.reset();
checksum.update(buf, 0, (int) bytesRead);
fos.writeLong(checksum.getValue());
}
fos.write(buf, 0, (int) bytesRead);
fos.flush();
if (indexVersion != null && (packetsWritten % 5 == 0)) {
//after every 5 packets reserve the commitpoint for some time
delPolicy.setReserveDuration(indexVersion, reserveCommitDuration);
}
packetsWritten++;
}
} else {
writeNothing();
}
} catch (IOException e) {
LOG.warn("Exception while writing response for params: " + params, e);
} finally {
IOUtils.closeQuietly(inputStream);
}
}
/**
* Used to write a marker for EOF
*/
private void writeNothing() throws IOException {
fos.writeInt(0);
fos.flush();
}
}
public static final String MASTER_URL = "masterUrl";
public static final String STATUS = "status";
public static final String COMMAND = "command";
public static final String CMD_DETAILS = "details";
public static final String CMD_BACKUP = "backup";
public static final String CMD_FETCH_INDEX = "fetchindex";
public static final String CMD_ABORT_FETCH = "abortfetch";
public static final String CMD_GET_FILE_LIST = "filelist";
public static final String CMD_GET_FILE = "filecontent";
public static final String CMD_FILE_CHECKSUM = "filechecksum";
public static final String CMD_DISABLE_POLL = "disablepoll";
public static final String CMD_DISABLE_REPL = "disablereplication";
public static final String CMD_ENABLE_REPL = "enablereplication";
public static final String CMD_ENABLE_POLL = "enablepoll";
public static final String CMD_INDEX_VERSION = "indexversion";
public static final String CMD_SHOW_COMMITS = "commits";
public static final String GENERATION = "generation";
public static final String OFFSET = "offset";
public static final String LEN = "len";
public static final String FILE = "file";
public static final String NAME = "name";
public static final String SIZE = "size";
public static final String LAST_MODIFIED = "lastmodified";
public static final String CONF_FILE_SHORT = "cf";
public static final String CHECKSUM = "checksum";
public static final String ALIAS = "alias";
public static final String CONF_CHECKSUM = "confchecksum";
public static final String CONF_FILES = "confFiles";
public static final String REPLICATE_AFTER = "replicateAfter";
public static final String FILE_STREAM = "filestream";
public static final int PACKET_SZ = 1024 * 1024; // 1MB
public static final String RESERVE = "commitReserveDuration";
public static final String COMPRESSION = "compression";
public static final String EXTERNAL = "external";
public static final String INTERNAL = "internal";
public static final String ERR_STATUS = "ERROR";
public static final String OK_STATUS = "OK";
}
| SOLR-1315 backup command should work when there was no commit/optimize since startup
git-svn-id: 3b1ff1236863b4d63a22e4dae568675c2e247730@805675 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/solr/handler/ReplicationHandler.java | SOLR-1315 backup command should work when there was no commit/optimize since startup | <ide><path>rc/java/org/apache/solr/handler/ReplicationHandler.java
<ide> } else if (command.equals(CMD_GET_FILE_LIST)) {
<ide> getFileList(solrParams, rsp);
<ide> } else if (command.equalsIgnoreCase(CMD_BACKUP)) {
<del> doSnapShoot(new ModifiableSolrParams(solrParams), rsp);
<add> doSnapShoot(new ModifiableSolrParams(solrParams), rsp,req);
<ide> rsp.add(STATUS, OK_STATUS);
<ide> } else if (command.equalsIgnoreCase(CMD_FETCH_INDEX)) {
<ide> String masterUrl = solrParams.get(MASTER_URL);
<ide> return snapPullLock.isLocked();
<ide> }
<ide>
<del> private void doSnapShoot(SolrParams params, SolrQueryResponse rsp) {
<add> private void doSnapShoot(SolrParams params, SolrQueryResponse rsp, SolrQueryRequest req) {
<ide> try {
<ide> IndexCommit indexCommit = core.getDeletionPolicy().getLatestCommit();
<add> if(indexCommit == null) {
<add> indexCommit = req.getSearcher().getReader().getIndexCommit();
<add> }
<ide> if (indexCommit != null) {
<ide> new SnapShooter(core, params.get("location")).createSnapAsync(indexCommit.getFileNames(), this);
<ide> } |
|
Java | apache-2.0 | 174104794d867b9ede68c098a656a61a87a001be | 0 | Gigaspaces/xap-openspaces,Gigaspaces/xap-openspaces,Gigaspaces/xap-openspaces | /*
* Copyright 2006-2007 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.openspaces.core.executor;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation marking a field of type {@link org.openspaces.core.GigaSpace} allowing for
* {@link org.openspaces.core.executor.Task} to be injected with the space it is executed on.
*
* @author kimchy
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TaskGigaSpace {
}
| src/main/src/org/openspaces/core/executor/TaskGigaSpace.java | /*
* Copyright 2006-2007 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.openspaces.core.executor;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annoation marking a field of type {@link org.openspaces.core.GigaSpace} allowing for
* {@link org.openspaces.core.executor.Task} to be injected with the space it is executed on.
*
* @author kimchy
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TaskGigaSpace {
}
| Fix typo
svn path=/trunk/openspaces/; revision=91807
Former-commit-id: d560a4b286cc38e76f19dcc7da7db32545b60d2a | src/main/src/org/openspaces/core/executor/TaskGigaSpace.java | Fix typo | <ide><path>rc/main/src/org/openspaces/core/executor/TaskGigaSpace.java
<ide> import java.lang.annotation.Target;
<ide>
<ide> /**
<del> * Annoation marking a field of type {@link org.openspaces.core.GigaSpace} allowing for
<add> * Annotation marking a field of type {@link org.openspaces.core.GigaSpace} allowing for
<ide> * {@link org.openspaces.core.executor.Task} to be injected with the space it is executed on.
<ide> *
<ide> * @author kimchy |
|
Java | apache-2.0 | 11c2517c65003d15039a912eb7b73bb1e42162b2 | 0 | vbelakov/h2o,eg-zhang/h2o-2,elkingtonmcb/h2o-2,100star/h2o,h2oai/h2o,calvingit21/h2o-2,elkingtonmcb/h2o-2,111t8e/h2o-2,eg-zhang/h2o-2,h2oai/h2o-2,rowhit/h2o-2,100star/h2o,vbelakov/h2o,eg-zhang/h2o-2,calvingit21/h2o-2,calvingit21/h2o-2,h2oai/h2o-2,100star/h2o,h2oai/h2o,100star/h2o,elkingtonmcb/h2o-2,h2oai/h2o,elkingtonmcb/h2o-2,vbelakov/h2o,111t8e/h2o-2,eg-zhang/h2o-2,rowhit/h2o-2,elkingtonmcb/h2o-2,100star/h2o,eg-zhang/h2o-2,111t8e/h2o-2,vbelakov/h2o,calvingit21/h2o-2,calvingit21/h2o-2,eg-zhang/h2o-2,rowhit/h2o-2,111t8e/h2o-2,h2oai/h2o,111t8e/h2o-2,h2oai/h2o,calvingit21/h2o-2,vbelakov/h2o,eg-zhang/h2o-2,rowhit/h2o-2,rowhit/h2o-2,h2oai/h2o,100star/h2o,h2oai/h2o-2,elkingtonmcb/h2o-2,111t8e/h2o-2,vbelakov/h2o,eg-zhang/h2o-2,111t8e/h2o-2,elkingtonmcb/h2o-2,eg-zhang/h2o-2,111t8e/h2o-2,eg-zhang/h2o-2,h2oai/h2o-2,h2oai/h2o-2,rowhit/h2o-2,h2oai/h2o-2,h2oai/h2o-2,elkingtonmcb/h2o-2,h2oai/h2o,rowhit/h2o-2,vbelakov/h2o,100star/h2o,h2oai/h2o,h2oai/h2o-2,h2oai/h2o-2,100star/h2o,elkingtonmcb/h2o-2,rowhit/h2o-2,calvingit21/h2o-2,111t8e/h2o-2,vbelakov/h2o,vbelakov/h2o,rowhit/h2o-2,h2oai/h2o,vbelakov/h2o,h2oai/h2o,calvingit21/h2o-2,rowhit/h2o-2,elkingtonmcb/h2o-2,calvingit21/h2o-2,calvingit21/h2o-2,h2oai/h2o-2,111t8e/h2o-2,100star/h2o | package water;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import water.util.Log;
/**
* The Thread that looks for TCP Cloud requests.
*
* This thread just spins on reading TCP requests from other Nodes.
* @author <a href="mailto:[email protected]"></a>
* @version 1.0
*/
public class TCPReceiverThread extends Thread {
public static ServerSocketChannel SOCK;
public TCPReceiverThread() { super("TCP-Accept"); }
// The Run Method.
// Started by main() on a single thread, this code manages reading TCP requests
@SuppressWarnings("resource")
public void run() {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
ServerSocketChannel errsock = null;
boolean saw_error = false;
while( true ) {
try {
// Cleanup from any prior socket failures. Rare unless we're really sick.
if( errsock != null ) { // One time attempt a socket close
final ServerSocketChannel tmp2 = errsock; errsock = null;
tmp2.close(); // Could throw, but errsock cleared for next pass
}
if( saw_error ) Thread.sleep(100); // prevent deny-of-service endless socket-creates
saw_error = false;
// ---
// More common-case setup of a ServerSocket
if( SOCK == null ) {
SOCK = ServerSocketChannel.open();
SOCK.socket().setReceiveBufferSize(AutoBuffer.BBSIZE);
SOCK.socket().bind(H2O.SELF._key);
}
// Block for TCP connection and setup to read from it.
SocketChannel sock = SOCK.accept();
// Pass off the TCP connection to a separate reader thread
new TCPReaderThread(sock,new AutoBuffer(sock)).start();
} catch( java.nio.channels.AsynchronousCloseException ex ) {
break; // Socket closed for shutdown
} catch( Exception e ) {
// On any error from anybody, close all sockets & re-open
Log.err("IO error on TCP port "+H2O.UDP_PORT+": ",e);
saw_error = true;
errsock = SOCK ; SOCK = null; // Signal error recovery on the next loop
}
}
}
// A private thread for reading from this open socket.
public static class TCPReaderThread extends Thread {
public SocketChannel _sock;
public AutoBuffer _ab;
public TCPReaderThread(SocketChannel sock, AutoBuffer ab) {
super("TCP-"+ab._h2o+"-"+(ab._h2o._tcp_readers++));
_sock = sock;
_ab = ab;
setPriority(MAX_PRIORITY-1);
}
public void run() {
while( true ) { // Loop, reading fresh TCP requests until the sender closes
try {
// Record the last time we heard from any given Node
_ab._h2o._last_heard_from = System.currentTimeMillis();
TimeLine.record_recv(_ab, true,0);
// Hand off the TCP connection to the proper handler
int ctrl = _ab.getCtrl();
int x = ctrl;
if( ctrl < 0 || ctrl >= UDP.udp.UDPS.length ) x = 0;
switch( UDP.udp.UDPS[x] ) {
case exec: RPC.remote_exec (_ab); break;
case ack: RPC.tcp_ack (_ab); break;
case timeline: TimeLine.tcp_call(_ab); break;
default: throw new RuntimeException("Unknown TCP Type: " + ctrl+" "+_ab._h2o);
}
} catch( java.nio.channels.AsynchronousCloseException ex ) {
break; // Socket closed for shutdown
} catch( Exception e ) {
// On any error from anybody, close everything
Log.err("IO error on TCP port "+H2O.UDP_PORT+": ",e);
break;
}
// Reuse open sockets for the next task
try {
if( !_sock.isOpen() ) break;
_ab = new AutoBuffer(_sock);
} catch( Exception e ) {
// Exceptions here are *normal*, this is an idle TCP connection and
// either the OS can time it out, or the cloud might shutdown. We
// don't care what happens to this socket.
break; // Ignore all errors; silently die if socket is closed
}
}
}
}
}
| src/main/java/water/TCPReceiverThread.java | package water;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import water.util.Log;
/**
* The Thread that looks for TCP Cloud requests.
*
* This thread just spins on reading TCP requests from other Nodes.
* @author <a href="mailto:[email protected]"></a>
* @version 1.0
*/
public class TCPReceiverThread extends Thread {
public static ServerSocketChannel SOCK;
public TCPReceiverThread() { super("TCP-Accept"); }
// The Run Method.
// Started by main() on a single thread, this code manages reading TCP requests
@SuppressWarnings("resource")
public void run() {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
ServerSocketChannel errsock = null;
boolean saw_error = false;
while( true ) {
try {
// Cleanup from any prior socket failures. Rare unless we're really sick.
if( errsock != null ) { // One time attempt a socket close
final ServerSocketChannel tmp2 = errsock; errsock = null;
tmp2.close(); // Could throw, but errsock cleared for next pass
}
if( saw_error ) Thread.sleep(100); // prevent deny-of-service endless socket-creates
saw_error = false;
// ---
// More common-case setup of a ServerSocket
if( SOCK == null ) {
SOCK = ServerSocketChannel.open();
SOCK.socket().setReceiveBufferSize(AutoBuffer.BBSIZE);
SOCK.socket().bind(H2O.SELF._key);
}
// Block for TCP connection and setup to read from it.
SocketChannel sock = SOCK.accept();
// Pass off the TCP connection to a separate reader thread
new TCPReaderThread(sock,new AutoBuffer(sock)).start();
} catch( java.nio.channels.AsynchronousCloseException ex ) {
break; // Socket closed for shutdown
} catch( Exception e ) {
// On any error from anybody, close all sockets & re-open
Log.err("IO error on TCP port "+H2O.UDP_PORT+": ",e);
saw_error = true;
errsock = SOCK ; SOCK = null; // Signal error recovery on the next loop
}
}
}
// A private thread for reading from this open socket.
public static class TCPReaderThread extends Thread {
public SocketChannel _sock;
public AutoBuffer _ab;
public TCPReaderThread(SocketChannel sock, AutoBuffer ab) {
super("TCP-"+ab._h2o+"-"+(ab._h2o._tcp_readers++));
_sock = sock;
_ab = ab;
setPriority(MAX_PRIORITY-1);
}
public void run() {
while( true ) { // Loop, reading fresh TCP requests until the sender closes
try {
// Record the last time we heard from any given Node
_ab._h2o._last_heard_from = System.currentTimeMillis();
TimeLine.record_recv(_ab, true,0);
// Hand off the TCP connection to the proper handler
int ctrl = _ab.getCtrl();
switch( UDP.udp.UDPS[ctrl] ) {
case exec: RPC.remote_exec (_ab); break;
case ack: RPC.tcp_ack (_ab); break;
case timeline: TimeLine.tcp_call(_ab); break;
default: throw new RuntimeException("Unknown TCP Type: " + ctrl+" "+_ab._h2o);
}
} catch( java.nio.channels.AsynchronousCloseException ex ) {
break; // Socket closed for shutdown
} catch( Exception e ) {
// On any error from anybody, close everything
Log.err("IO error on TCP port "+H2O.UDP_PORT+": ",e);
break;
}
// Reuse open sockets for the next task
try {
if( !_sock.isOpen() ) break;
_ab = new AutoBuffer(_sock);
} catch( Exception e ) {
// Exceptions here are *normal*, this is an idle TCP connection and
// either the OS can time it out, or the cloud might shutdown. We
// don't care what happens to this socket.
break; // Ignore all errors; silently die if socket is closed
}
}
}
}
}
| better handling of broken TCP connections
| src/main/java/water/TCPReceiverThread.java | better handling of broken TCP connections | <ide><path>rc/main/java/water/TCPReceiverThread.java
<ide> TimeLine.record_recv(_ab, true,0);
<ide> // Hand off the TCP connection to the proper handler
<ide> int ctrl = _ab.getCtrl();
<del> switch( UDP.udp.UDPS[ctrl] ) {
<add> int x = ctrl;
<add> if( ctrl < 0 || ctrl >= UDP.udp.UDPS.length ) x = 0;
<add> switch( UDP.udp.UDPS[x] ) {
<ide> case exec: RPC.remote_exec (_ab); break;
<ide> case ack: RPC.tcp_ack (_ab); break;
<ide> case timeline: TimeLine.tcp_call(_ab); break; |
|
JavaScript | mit | ad8d0a941408cbce616a4bc9fc2343107742dde7 | 0 | silverbux/rsjs | 0bc7b3b8-2e9c-11e5-b3a9-a45e60cdfd11 | helloWorld.js | 0bbb8ee3-2e9c-11e5-8c33-a45e60cdfd11 | 0bc7b3b8-2e9c-11e5-b3a9-a45e60cdfd11 | helloWorld.js | 0bc7b3b8-2e9c-11e5-b3a9-a45e60cdfd11 | <ide><path>elloWorld.js
<del>0bbb8ee3-2e9c-11e5-8c33-a45e60cdfd11
<add>0bc7b3b8-2e9c-11e5-b3a9-a45e60cdfd11 |
|
Java | apache-2.0 | ae19ee36cfc15da40892c38e8c974a182a525aa6 | 0 | TiBeN/ia-mame | package org.tibennetwork.iamame.mame;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.DataBindingException;
import javax.xml.bind.JAXB;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Factory for MameSystems
*/
public class MachineRepository {
/**
* Mame XML root element container.
*/
@XmlRootElement(name = "mame")
@XmlAccessorType(XmlAccessType.FIELD)
public static class MameXmlContainer {
@XmlElement(name="machine")
private List<Machine> machines = new ArrayList<Machine>();
public List<Machine> getMachines() {
return machines;
}
public void setMachines(List<Machine> machines) {
this.machines = machines;
}
}
private MameRuntime mame;
public MachineRepository (MameRuntime mame) {
this.mame = mame;
}
/**
* Return a MameSystem object corresponding
* to the given system name
*/
public Machine findByName (String machineName)
throws IOException,
InterruptedException,
MachineDoesntExistException {
// Call MameRuntime to get Xml data of the given system,
// then unmarshall it
String[] mameCommandLine = {"-listxml", machineName};
InputStream is;
MameXmlContainer ms = null;
try {
is = this.mame.executeAndReturnStdoutAsInputStream(
mameCommandLine);
ms = JAXB.unmarshal(is, MameXmlContainer.class);
} catch (MameExecutionException | DataBindingException e) {
throw new MachineDoesntExistException(
String.format("The machine '%s' doesn't exist or is not "
+ "supported by the provided Mame version",
machineName));
}
for (Machine m: ms.getMachines()) {
if (m.getName().equals(machineName)) {
String parentMachineName = m.getRomof();
if(parentMachineName != null) {
m.setParentMachine(
this.findByName(parentMachineName));
}
return m;
}
}
throw new RuntimeException(String.format(
"Unhandled case: Mame returned no errors while searching "
+ "for machine %s but the machine has not been found "
+ "on the XML content",
machineName));
}
}
| src/main/java/org/tibennetwork/iamame/mame/MachineRepository.java | package org.tibennetwork.iamame.mame;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXB;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Factory for MameSystems
*/
public class MachineRepository {
/**
* Mame XML root element container.
*/
@XmlRootElement(name = "mame")
@XmlAccessorType(XmlAccessType.FIELD)
public static class MameXmlContainer {
@XmlElement(name="machine")
private List<Machine> machines = new ArrayList<Machine>();
public List<Machine> getMachines() {
return machines;
}
public void setMachines(List<Machine> machines) {
this.machines = machines;
}
}
private MameRuntime mame;
public MachineRepository (MameRuntime mame) {
this.mame = mame;
}
/**
* Return a MameSystem object corresponding
* to the given system name
*/
public Machine findByName (String machineName)
throws IOException,
InterruptedException,
MachineDoesntExistException {
// Call MameRuntime to get Xml data of the given system,
// then unmarshall it
String[] mameCommandLine = {"-listxml", machineName};
InputStream is;
try {
is = this.mame.executeAndReturnStdoutAsInputStream(
mameCommandLine);
} catch (MameExecutionException e) {
throw new MachineDoesntExistException(
String.format("The machine '%s' doesn't exist or is not "
+ "supported by the provided Mame version",
machineName));
}
// Bouger cette classe ici en interne
MameXmlContainer ms = JAXB.unmarshal(is, MameXmlContainer.class);
for (Machine m: ms.getMachines()) {
if (m.getName().equals(machineName)) {
String parentMachineName = m.getRomof();
if(parentMachineName != null) {
m.setParentMachine(
this.findByName(parentMachineName));
}
return m;
}
}
throw new RuntimeException(String.format(
"Unhandled case: Mame returned no errors while searching "
+ "for machine %s but the machine has not been found "
+ "on the XML content",
machineName));
}
}
| Now catch unmarshall errors as unknown mame system
| src/main/java/org/tibennetwork/iamame/mame/MachineRepository.java | Now catch unmarshall errors as unknown mame system | <ide><path>rc/main/java/org/tibennetwork/iamame/mame/MachineRepository.java
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide>
<add>import javax.xml.bind.DataBindingException;
<ide> import javax.xml.bind.JAXB;
<ide> import javax.xml.bind.annotation.XmlAccessType;
<ide> import javax.xml.bind.annotation.XmlAccessorType;
<ide> String[] mameCommandLine = {"-listxml", machineName};
<ide> InputStream is;
<ide>
<add> MameXmlContainer ms = null;
<add>
<ide> try {
<ide> is = this.mame.executeAndReturnStdoutAsInputStream(
<ide> mameCommandLine);
<del> } catch (MameExecutionException e) {
<add> ms = JAXB.unmarshal(is, MameXmlContainer.class);
<add> } catch (MameExecutionException | DataBindingException e) {
<ide> throw new MachineDoesntExistException(
<ide> String.format("The machine '%s' doesn't exist or is not "
<ide> + "supported by the provided Mame version",
<ide> machineName));
<ide> }
<del>
<del> // Bouger cette classe ici en interne
<del> MameXmlContainer ms = JAXB.unmarshal(is, MameXmlContainer.class);
<ide>
<ide> for (Machine m: ms.getMachines()) {
<ide> if (m.getName().equals(machineName)) { |
|
JavaScript | mit | 07c5bedaaa74e4eca702255e040c2dfbaf2675a4 | 0 | rhc2104/sqlteaching,rhc2104/sqlteaching | var sql = window.SQL;
// The db variable gets set every time a level is loaded.
var db;
// Return an HTML table as a string, given SQL.js results
var table_from_results = function(res) {
var table_string = '<table>';
if (res) {
table_string += '<tr>';
for (var index in res[0].columns) {
table_string += '<th>' + res[0].columns[index] + '</th>';
}
table_string += '</tr>';
for (var row_index in res[0].values) {
table_string += '<tr>';
for (var col_index in res[0].values[row_index]) {
table_string += '<td>' + res[0].values[row_index][col_index] + '</td>';
}
table_string += '</tr>';
}
}
table_string += '</table>';
return table_string;
};
var grade_results = function(results, correct_answer) {
if (!results) {
return false;
}
// Check to make sure the results are equal, but normalize case and remove whitespace from column names.
var normalize = function(x){return x.toUpperCase().replace(/\s/g, "")};
return JSON.stringify(results[0].columns.map(normalize)) == JSON.stringify(correct_answer.columns.map(normalize)) &&
JSON.stringify(results[0].values) == JSON.stringify(correct_answer.values);
};
var show_is_correct = function(is_correct, custom_error_message) {
if (is_correct) {
is_correct_html = 'Congrats! That is correct!<br/>';
if (current_level < levels.length) {
is_correct_html += '<a href="#!' + levels[current_level]['short_name'] + '" tabindex="3">Next Lesson</a>';
} else {
is_correct_html += 'That is currently the end of the tutorial. Please check back later for more!';
}
$('#answer-correct').html(is_correct_html);
$('#answer-correct').show();
$('#answer-wrong').hide();
} else if (custom_error_message) {
$('#answer-wrong').text(custom_error_message);
$('#answer-wrong').show();
$('#answer-correct').hide();
} else {
$('#answer-wrong').text('That was incorrect. Please try again.');
$('#answer-wrong').show();
$('#answer-correct').hide();
}
};
var strings_present = function(strings) {
var ans = $('#sql-input').val().toLowerCase();
for (var index in strings) {
if (ans.indexOf(strings[index].toLowerCase()) < 0) {
return false;
}
}
return true;
};
var execute_query = function() {
var cur_level = levels[current_level-1];
var correct_answer = cur_level['answer'];
try {
var results = db.exec($('#sql-input').val());
if (results.length == 0) {
$('#results').html('');
show_is_correct(false, 'The query you have entered did not return any results. Please try again.');
} else {
$('#results').html(table_from_results(results));
var is_correct = grade_results(results, correct_answer);
if (is_correct) {
// The required strings are optional, but if they exist and it fails, we show a custom error message.
if (!cur_level['required'] || strings_present(cur_level['required'])) {
show_is_correct(true, null);
localStorage.setItem('completed-' + cur_level['short_name'], 'correct');
// By calling render_menu, the completed level gets a checkmark added
render_menu();
} else {
show_is_correct(false, cur_level['custom_error_message']);
}
} else {
show_is_correct(false, 'The query you have entered did not return the proper results. Please try again.');
}
}
} catch (err) {
$('#results').html('');
show_is_correct(false, 'The query you have entered is not valid. Please try again.');
}
$('.expected-results-container').show();
$('#expected-results').html(table_from_results([correct_answer]));
return false;
};
// Onclick handler for when you click "Run SQL"
$('#sql-link').click(execute_query);
// Keypress handler for ctrl + enter to "Run SQL"
$('#sql-input').keypress(function(event) {
var keyCode = (event.which ? event.which : event.keyCode);
if (keyCode === 10 || keyCode == 13 && event.ctrlKey) {
execute_query();
return false;
}
});
/**
* This variable has the prompts and answers for each level.
*
* It is an array of dictionaries. In each dictionary, there are the following keys:
* - name: name shown on web page
* - short_name: identifier added to the URL
* - database_type: is passed into the load_database function, in order to determine the tables loaded
* - answer: the query that the user writes must return data that matches this value
* - prompt: what is shown to the user in that web page
*
* And the following keys are optional:
* - required: Extra validation in the form of case-insensitive required strings
* - custom_error_message: If the validation fails, show this error message to the user
*/
var levels = [{'name': 'SELECT *',
'short_name': 'select',
'database_type': 'family',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'num_books_read'],
'values': [[1, 'Dave', 'male', 'human', 200],
[2, 'Mary', 'female', 'human', 180],
[3, 'Pickles', 'male', 'dog', 0]]},
'prompt': 'In SQL, data is usually organized in various tables. For example, a sports team database might have the tables <em>teams</em>, <em>players</em>, and <em>games</em>. A wedding database might have tables <em>guests</em>, <em>vendors</em>, and <em>music_playlist</em>.<br/><br/>Imagine we have a table that stores family members with each member\'s name, age, species, and gender.<br/><br/>Let\'s start by grabbing all of the data in one table. We have a table called <strong>family_members</strong> that is shown below. In order to grab all of that data, please run the following command: <code>SELECT * FROM family_members;</code><br/><br/>The <code>*</code> above means that all of the columns will be returned, which in this case are <em>id</em>, <em>name</em>, <em>gender</em>, <em>species</em>, and <em>num_books_read</em>. <br/><br/>Note: This tutorial uses the <a href="http://en.wikipedia.org/wiki/SQLite" target="_blank">SQLite</a> database engine. The different variants of SQL use slightly different syntax.'},
{'name': 'SELECT specific columns',
'short_name': 'select_columns',
'database_type': 'family',
'answer': {'columns': ['name', 'species'],
'values': [['Dave', 'human'],
['Mary', 'human'],
['Pickles', 'dog']]},
'prompt': '<code>SELECT *</code> grabs all fields (called columns) in a table. If we only wanted to see the name and num_books_read columns, we would type<br/> <code>SELECT name, num_books_read FROM family_members;</code>.<br/><br/>Can you return just the name and species columns?'},
{'name': 'WHERE ... Equals',
'short_name': 'where_equals',
'database_type': 'family',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'num_books_read'],
'values': [[3, 'Pickles', 'male', 'dog', 0]]},
'prompt': 'In order to select particular rows from this table, we use the <code>WHERE</code> keyword. So for example, if we wanted to grab all of the rows that correspond to humans, we would type <br/><code>SELECT * FROM family_members WHERE species = \'human\';</code><br/> Note that the quotes have to be around the word human, as it is an explicit value, unlike a keyword such as <code>WHERE</code>.<br/><br/>Can you run a query that returns all of the rows that refer to dogs?'},
{'name': 'WHERE ... Greater than',
'short_name': 'where_greater_than',
'database_type': 'family',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'num_books_read'],
'values': [[1, 'Dave', 'male', 'human', 200]]},
'prompt': 'If we want to only select family members based on a numerical field, we can also use the <code>WHERE</code> keyword. For example, if we wanted to select family members with a num_books_read, we would type <br/><code>SELECT * FROM family_members WHERE num_books_read > 0;</code><br/><br/> Can you run return all rows of family members whose num_books_read is greater than 190?'},
{'name': 'WHERE ... Greater than or equal',
'short_name': 'where_greater_than_or_equal',
'database_type': 'family',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'num_books_read'],
'values': [[1, 'Dave', 'male', 'human', 200],
[2, 'Mary', 'female', 'human', 180]]},
'prompt': 'SQL accepts various inequality symbols, including: <br/><code>=</code> "equal to"<br/><code>></code> "greater than"<br/><code><</code> "less than"<br/><code>>=</code> "greater than or equal to"<br/><code><=</code> "less than or equal to"<br/><br/> Can you return all rows in <strong>family_members</strong> where num_books_read is a value greater or equal to 180?'},
{'name': 'AND',
'short_name': 'and',
'database_type': 'friends_of_pickles',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'height_cm'],
'values': [[5, 'Odie', 'male', 'dog', 40],
[6, 'Jumpy', 'male', 'dog', 35]]},
'prompt': 'In the <code>WHERE</code> part of a query, you can search for multiple attributes by using the <code>AND</code> keyword. For example, if you wanted to find the friends of Pickles that are over 25cm in height and are cats, you would run: <br/><code>SELECT * FROM friends_of_pickles WHERE height_cm > 25 AND species = \'cat\';</code><br/><br/>Can you find all of Pickles\' friends that are dogs and under the height of 45cm?'},
{'name': 'OR',
'short_name': 'or',
'database_type': 'friends_of_pickles',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'height_cm'],
'values': [[3, 'Fry', 'male', 'cat', 30],
[4, 'Leela', 'female', 'cat', 25],
[5, 'Odie', 'male', 'dog', 40],
[6, 'Jumpy', 'male', 'dog', 35],
[7, 'Sneakers', 'male', 'dog', 55]]},
'prompt': 'In the <code>WHERE</code> part of a query, you can search for rows that match any of multiple attributes by using the <code>OR</code> keyword. For example, if you wanted to find the friends of Pickles that are over 25cm in height or are cats, you would run: <br/><code>SELECT * FROM friends_of_pickles WHERE height_cm > 25 OR species = \'cat\';</code><br/><br/>Can you find all of Pickles\' friends that are dogs or under the height of 45cm?'},
{'name': 'IN',
'short_name': 'in',
'database_type': 'friends_of_pickles',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'height_cm'],
'values': [[1, 'Dave', 'male', 'human', 180],
[2, 'Mary', 'female', 'human', 160]]},
'prompt': 'Using the <code>WHERE</code> clause, we can find rows where a value is in a list of several possible values. <br/><br/><code>SELECT * FROM friends_of_pickles WHERE species IN (\'cat\', \'human\');</code> would return the <strong>friends_of_pickles</strong> that are either a cat or a human. <br/><br/>To find rows that are not in a list, you use <code>NOT IN</code> instead of <code>IN</code>. <br/><br/>Can you run a query that would return the rows that are <strong>not</strong> cats or dogs?'},
{'name': 'DISTINCT',
'short_name': 'distinct',
'database_type': 'friends_of_pickles',
'answer': {'columns': ['species'],
'values': [['human'], ['dog']]},
'prompt': 'By putting <code>DISTINCT</code> after <code>SELECT</code>, you do not return duplicates. <br/><br/>For example, if you run <br/> <code>SELECT DISTINCT gender, species FROM friends_of_pickles WHERE height_cm < 100;</code>, you will get the gender/species combinations of the animals less than 100cm in height. <br/><br/>Note that even though there are multiple male dogs under that height, we only see one row that returns "male" and "dog".<br/><br/> Can you return a list of the distinct species of animals greater than 50cm in height?'},
{'name': 'ORDER BY',
'short_name': 'order_by',
'database_type': 'friends_of_pickles',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'height_cm'],
'values': [[1, 'Dave', 'male', 'human', 180],
[2, 'Mary', 'female', 'human', 160],
[7, 'Sneakers', 'male', 'dog', 55],
[5, 'Odie', 'male', 'dog', 40],
[6, 'Jumpy', 'male', 'dog', 35],
[3, 'Fry', 'male', 'cat', 30],
[4, 'Leela', 'female', 'cat', 25]]},
'prompt': 'If you want to sort the rows by some kind of attribute, you can use the <code>ORDER BY</code> keyword. For example, if you want to sort the <strong>friends_of_pickles</strong> by name, you would run: <code>SELECT * FROM friends_of_pickles ORDER BY name;</code>. That returns the names in ascending alphabetical order.<br/><br/> In order to put the names in descending order, you would add a <code>DESC</code> at the end of the query.<br/><br/> Can you run a query that sorts the <strong>friends_of_pickles</strong> by <em>height_cm</em> in descending order?'},
{'name': 'LIMIT # of returned rows',
'short_name': 'limit',
'database_type': 'friends_of_pickles',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'height_cm'],
'values': [[1, 'Dave', 'male', 'human', 180]]},
'prompt': 'Often, tables contain millions of rows, and it can take a while to grab everything. If we just want to see a few examples of the data in a table, we can select the first few rows with the <code>LIMIT</code> keyword. If you use <code>ORDER BY</code>, you would get the first rows for that order. <br/><br/>If you wanted to see the two shortest <strong>friends_of_pickles</strong>, you would run: <code>SELECT * FROM friends_of_pickles ORDER BY height_cm LIMIT 2;</code><br/><br/> Can you return the single row (and all columns) of the tallest <strong>friends_of_pickles</strong>?<br/><br/>Note: <br/>- Some variants of SQL do not use the <code>LIMIT</code> keyword.<br/>- The <code>LIMIT</code> keyword comes after the <code>DESC</code> keyword.'},
{'name': 'COUNT(*)',
'short_name': 'count',
'database_type': 'friends_of_pickles',
'answer': {'columns': ['COUNT(*)'],
'values': [[7]]},
'prompt': 'Another way to explore a table is to check the number of rows in it. For example, if we are querying a table <em>states_of_us</em>, we\'d expect 50 rows, or 500 rows in a table called <em>fortune_500_companies</em>.<br/><br/><code>SELECT COUNT(*) FROM friends_of_pickles;</code> returns the total number of rows in the table <strong>friends_of_pickles</strong>. Try this for yourself.'},
{'name': 'COUNT(*) ... WHERE',
'short_name': 'count_where',
'database_type': 'friends_of_pickles',
'answer': {'columns': ['COUNT(*)'],
'values': [[3]]},
'prompt': 'We can combine <code>COUNT(*)</code> with <code>WHERE</code> to return the number of rows that matches the <code>WHERE</code> clause.<br/><br/> For example, <code>SELECT COUNT(*) FROM friends_of_pickles WHERE species = \'human\';</code> returns 2.<br/><br/>Can you return the number of rows in <strong>friends_of_pickles</strong> where the species is a dog?'},
{'name': 'SUM',
'short_name': 'sum',
'database_type': 'family_and_legs',
'answer': {'columns': ['SUM(num_books_read)'],
'values': [[380]]},
'prompt': 'We can use the <code>SUM</code> keyword in order to find the sum of a given value. <br/><br/>For example, running <code>SELECT SUM(num_legs) FROM family_members;</code> returns the total number of legs in the family. <br/><br/>Can you find the total num_books_read made by this family?'},
{'name': 'AVG',
'short_name': 'avg',
'database_type': 'family_and_legs',
'answer': {'columns': ['AVG(num_books_read)'],
'values': [[126.66666666666667]]},
'prompt': 'We can use the <code>AVG</code> keyword in order to find the average of a given value. <br/><br/>For example, running <code>SELECT AVG(num_legs) FROM family_members;</code> returns the average number of legs of each family member. <br/><br/>Can you find the average num_books_read made by each family member? <br/><br/>Note: <br/>- Because of the way computers handle numbers, averages will not always be completely exact.'},
{'name': 'MAX and MIN',
'short_name': 'max_min',
'database_type': 'family_and_legs',
'answer': {'columns': ['MAX(num_books_read)'],
'values': [[200]]},
'prompt': 'We can use the <code>MAX</code> and <code>MIN</code> to find the maximum or minimum value of a table. <br/><br/>To find the least number of legs in a family member (<em>2</em>), you can run <br/><code>SELECT MIN(num_legs) FROM family_members;</code> <br/><br/>Can you find the highest num_books_read that a family member makes?'},
{'name': 'GROUP BY',
'short_name': 'group_by',
'database_type': 'friends_of_pickles',
'answer': {'columns': ['MAX(height_cm)', 'species'],
'values': [[30, 'cat'],
[55, 'dog'],
[180, 'human']]},
'prompt': 'You can use aggregate functions such as <code>COUNT</code>, <code>SUM</code>, <code>AVG</code>, <code>MAX</code>, and <code>MIN</code> with the <code>GROUP BY</code> clause. <br/><br/> When you <code>GROUP BY</code> something, you split the table into different piles based on the value of each row. <br/><br/>For example, <br/><code>SELECT COUNT(*), species FROM friends_of_pickles GROUP BY species;</code> would return the number of rows for each species. <br/><br/> Can you return the tallest height for each species? Remember to return the species name next to the height too, like in the example query.'},
{'name': 'Nested queries',
'short_name': 'nested',
'database_type': 'family_and_legs',
'required': ['(', ')'],
'custom_error_message': 'You must use a nested query in your answer.',
'answer': {'columns': ['id', 'name', 'species', 'num_books_read', 'num_legs'],
'values': [[1, 'Dave', 'human', 200, 2]]},
'prompt': 'In SQL, you can put a SQL query inside another SQL query. <br/><br/>For example, to find the family members with the least number of legs, <br/> you can run: <br/><code>SELECT * FROM family_members WHERE num_legs = (SELECT MIN(num_legs) FROM family_members);</code> <br/><br/> The <code>SELECT</code> query inside the parentheses is executed first, and returns the minimum number of legs. Then, that value (2) is used in the outside query, to find all family members that have 2 legs. <br/><br/> Can you return the family members that have the highest num_books_read?'},
{'name': 'NULL',
'short_name': 'null',
'database_type': 'family_null',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'favorite_book'],
'values': [[1, 'Dave', 'male', 'human', 'To Kill a Mockingbird'],
[2, 'Mary', 'female', 'human', 'Gone with the Wind']]},
'prompt': 'Sometimes, in a given row, there is no value at all for a given column. For example, a dog does not have a favorite book, so in that case there is no point in putting a value in the <em>favorite_book</em> column, and the value is <code>NULL</code>. In order to find the rows where the value for a column is or is not <code>NULL</code>, you would use <code>IS NULL</code> or <code>IS NOT NULL</code>.<br/><br/>Can you return all of the rows of <strong>family_members</strong> where <em>favorite_book</em> is not null?'},
{'name': 'Date',
'short_name': 'date',
'database_type': 'celebs_born',
'answer': {'columns': ['id', 'name', 'birthdate'],
'values': [[2, 'Justin Timberlake', '1981-01-31'],
[3, 'Taylor Swift', '1989-12-13']]},
'prompt': 'Sometimes, a column can contain a date value. The first 4 digits represents the year, the next 2 digits represents the month, and the next 2 digits represents the day of the month. For example, <code>1985-07-20</code> would mean July 20, 1985.<br/><br/>You can compare dates by using <code><</code> and <code>></code>. For example, <code>SELECT * FROM celebs_born WHERE birthdate < \'1985-08-17\';</code> returns a list of celebrities that were born before August 17th, 1985.<br/><br/>Can you return a list of celebrities that were born after September 1st, 1980?'},
{'name': 'Inner joins',
'short_name': 'joins',
'database_type': 'tv',
'answer': {'columns': ['name', 'actor_name'],
'values': [['Doogie Howser', 'Neil Patrick Harris'],
['Barney Stinson', 'Neil Patrick Harris'],
['Lily Aldrin', 'Alyson Hannigan'],
['Willow Rosenberg', 'Alyson Hannigan']]},
'prompt': 'Different parts of information can be stored in different tables, and in order to put them together, we use <code>INNER JOIN ... ON</code>. Joining tables gets to the core of SQL functionality, but it can get very complicated. We will start with a simple example, and will start with an <code>INNER JOIN</code>.<br/><br/>As you can see below, there are 3 tables:<br/><strong>character</strong>: Each character is a row and is represented by a unique identifier (<em>id</em>), e.g. 1 is Doogie Howser<br/><strong>character_tv_show:</strong> For each character, which show is he/she in?<br/><strong>character_actor</strong>: For each character, who is the actor?<br/><br/>See that in <strong>character_tv_show</strong>, instead of storing both the character and TV show names (e.g. Willow Rosenberg and Buffy the Vampire Slayer), it stores the <em>character_id</em> as a substitute for the character name. This <em>character_id</em> refers to the matching <em>id</em> row from the <strong>character</strong> table. <br/><br/>This is done so data is not duplicated. For example, if the name of a character were to change, you would only have to change the name of the character in one row. <br/><br/>This allows us to "join" the tables together "on" that reference/common column. <br/><br/>To get each character name with his/her TV show name, we can write <br/><code>SELECT character.name, character_tv_show.tv_show_name<br/> FROM character <br/>INNER JOIN character_tv_show<br/> ON character.id = character_tv_show.character_id;</code><br/>This puts together every row in <strong>character</strong> with the corresponding row in <strong>character_tv_show</strong>, or vice versa.<br/><br/>Note:<br/>- We use the syntax <strong>table_name</strong>.<em>column_name</em>. If we only used <em>column_name</em>, SQL might incorrectly assume which table it is coming from.<br/> - The example query above is written over multiple lines for readability, but that does not affect the query. <br/><br/>Can you use an inner join to pair each character name with the actor who plays them? Select the columns: <strong>character</strong>.<em>name</em>, <strong>character_actor</strong>.<em>actor_name</em>'},
{'name': 'Multiple joins',
'short_name': 'multiple_joins',
'database_type': 'tv_normalized',
'answer': {'columns': ['name', 'name'],
'values': [['Doogie Howser', 'Neil Patrick Harris'],
['Barney Stinson', 'Neil Patrick Harris'],
['Lily Aldrin', 'Alyson Hannigan'],
['Willow Rosenberg', 'Alyson Hannigan']]},
'prompt': 'In the previous exercise, we explained that TV show character names were not duplicated, so if the name of a character were to change, you would only have to change the name of the character in one row. <br/><br/>However, the previous example was a bit artificial because the TV show names and actor names were duplicated. <br/><br/>In order to not duplicate any names, we need to have more tables, and use multiple joins. <br/><br/>We have tables for characters, TV shows, and actors. Those tables represent things (also known as entities). <br/><br/>In addition those tables, we have the relationship tables <strong>character_tv_show</strong> and <strong>character_actor</strong>, which capture the relationship between two entities. <br/><br/>This is a flexible way of capturing the relationship between different entities, as some TV show characters might be in multiple shows, and some actors are known for playing multiple characters. <br/><br/>To get each character name with his/her TV show name, we can write <br/><code>SELECT character.name, tv_show.name<br/> FROM character <br/>INNER JOIN character_tv_show<br/> ON character.id = character_tv_show.character_id<br/>INNER JOIN tv_show<br/> ON character_tv_show.tv_show_id = tv_show.id;</code><br/><br/>Can you use two joins to pair each character name with the actor who plays them? Select the columns: <strong>character</strong>.<em>name</em>, <strong>actor</strong>.<em>name</em>'},
{'name': 'Joins with WHERE',
'short_name': 'joins_with_where',
'required': ['Willow Rosenberg', 'How I Met Your Mother'],
'custom_error_message': 'You must check that the characters are not named "Willow Rosenberg" or in the show "How I Met Your Mother".',
'database_type': 'tv_normalized',
'answer': {'columns': ['name', 'name'],
'values': [['Doogie Howser', 'Doogie Howser, M.D.']]},
'prompt': 'You can also use joins with the <code>WHERE</code> clause. <br/><br/> To get a list of characters and TV shows that are not in "Buffy the Vampire Slayer" and are not Barney Stinson, you would run: <br/> <code>SELECT character.name, tv_show.name<br/> FROM character <br/>INNER JOIN character_tv_show<br/> ON character.id = character_tv_show.character_id<br/>INNER JOIN tv_show<br/> ON character_tv_show.tv_show_id = tv_show.id WHERE character.name != \'Barney Stinson\' AND tv_show.name != \'Buffy the Vampire Slayer\';</code> <br/><br/>Can you return a list of characters and TV shows that are not named "Willow Rosenberg" or in the show "How I Met Your Mother"?'},
{'name': 'Left joins',
'short_name': 'left_joins',
'database_type': 'tv_extra',
'answer': {'columns': ['name', 'name'],
'values': [['Doogie Howser', 'Neil Patrick Harris'],
['Barney Stinson', 'Neil Patrick Harris'],
['Lily Aldrin', 'Alyson Hannigan'],
['Willow Rosenberg', 'Alyson Hannigan'],
['Steve Urkel', null],
['Homer Simpson', null]]},
'prompt': 'In the previous exercise, we used joins to match up TV character names with their actors. When you use <code>INNER JOIN</code>, that is called an "inner join" because it only returns rows where there is data for both the character name and the actor. <br/><br/> However, perhaps you want to get all of the character names, even if there isn\'t corresponding data for the name of the actor. A <code>LEFT JOIN</code> returns all of the data from the first (or "left") table, and if there isn\'t corresponding data for the second table, it returns <code>NULL</code> for those columns. <br/><br/> Using left joins between character names and TV shows would look like this: <br/><code>SELECT character.name, tv_show.name<br/> FROM character <br/>LEFT JOIN character_tv_show<br/> ON character.id = character_tv_show.character_id<br/> LEFT JOIN tv_show<br/> ON character_tv_show.tv_show_id = tv_show.id;</code> <br/><br/> Can you use left joins to match character names with the actors that play them? Select the columns: <strong>character</strong>.<em>name</em>, <strong>actor</strong>.<em>name</em> <br/><br/>Note: Other variants of SQL have <code>RIGHT JOIN</code> and <code>OUTER JOIN</code>, but those features are not present in SQLite.'},
{'name': 'Table alias',
'short_name': 'table_alias',
'required': ['AS', 'c.name', 'a.name'],
'custom_error_message': 'You must use table aliases as described above.',
'database_type': 'tv_extra',
'answer': {'columns': ['name', 'name'],
'values': [['Doogie Howser', 'Neil Patrick Harris'],
['Barney Stinson', 'Neil Patrick Harris'],
['Lily Aldrin', 'Alyson Hannigan'],
['Willow Rosenberg', 'Alyson Hannigan'],
['Steve Urkel', null],
['Homer Simpson', null]]},
'prompt': 'These queries are starting to get pretty long! <br/><br/>In the previous exercise, we ran a query containing the tables <strong>character</strong>, <strong>tv_show</strong>, and <strong>character_tv_show</strong>. We can write a shorter query if we used aliases for those tables. Basically, we create a "nickname" for that table. <br/><br/> If you want to use an alias for a table, you add <code>AS *alias_name*</code> after the table name. <br/><br/> For example, to use left joins between characters and tv shows with aliases, you would run: <br/> <code>SELECT c.name, t.name<br/>FROM character AS c<br/>LEFT JOIN character_tv_show AS ct<br/>ON c.id = ct.character_id<br/>LEFT JOIN tv_show AS t<br/>ON ct.tv_show_id = t.id;</code> <br/><br/> As you can see, it is shorter than the query in the previous exercise.<br/><br/> Can you use left joins to match character names with the actors that play them, and use aliases to make the query shorter? The aliases for <strong>character</strong>, <strong>character_actor</strong>, and <strong>actor</strong> should be <strong>c</strong>, <strong>ca</strong>, and <strong>a</strong>. <br/><br/>Select the columns: <strong>c</strong>.<em>name</em>, <strong>a</strong>.<em>name</em>'},
{'name': 'Column alias',
'short_name': 'column_alias',
'database_type': 'tv_extra',
'answer': {'columns': ['character', 'actor'],
'values': [['Doogie Howser', 'Neil Patrick Harris'],
['Barney Stinson', 'Neil Patrick Harris'],
['Lily Aldrin', 'Alyson Hannigan'],
['Willow Rosenberg', 'Alyson Hannigan'],
['Steve Urkel', null],
['Homer Simpson', null]]},
'prompt': 'In addition to making aliases for tables, you can also make them for columns. <br/><br/> This clears up confusion on which column is which. In the previous exercise, both columns in the result are simply called "name", and that can be confusing. <br/><br/> If you want to use an alias for a column, you add <code>AS *alias_name*</code> after the column name. <br/><br/> If we wanted to use left joins between character names and TV shows and clearly denote which column has character names, and which has TV show names, it would look like this: <br/><code>SELECT character.name AS character, tv_show.name AS name<br/> FROM character <br/>LEFT JOIN character_tv_show<br/> ON character.id = character_tv_show.character_id<br/> LEFT JOIN tv_show<br/> ON character_tv_show.tv_show_id = tv_show.id;</code> <br/><br/>Can you use left joins to match character names with the actors that play them, and use aliases to call the two columns returned <em>character</em> and <em>actor</em>?'},
{'name': 'Self joins',
'short_name': 'self_join',
'database_type': 'self_join',
'answer': {'columns': ['employee_name', 'boss_name'],
'values': [['Patrick Smith', 'Abigail Reed'],
['Abigail Reed', 'Bob Carey'],
['Bob Carey', 'Maxine Tang']]},
'prompt': 'Sometimes, it may make sense for you to do a self join. In that case, you need to use table aliases to determine which data is from the "first"/"left" table. <br/><br/>For example, to get a list of Rock Paper Scissors objects and the objects they beat, you can run the following: <br/><code>SELECT r1.name AS object, r2.name AS beats <br/>FROM rps AS r1 <br/>INNER JOIN rps AS r2 <br/>ON r1.defeats_id = r2.id;</code><br/><br/> Can you run a query that returns the name of an employee and the name of their boss? Use column aliases to make the columns <em>employee_name</em> and <em>boss_name</em>.'},
{'name': 'LIKE',
'short_name': 'like',
'database_type': 'robot',
'answer': {'columns': ['id', 'name'],
'values': [[1, 'Robot 2000'],
[2, 'Champion Robot 2001'],
[4, 'Turbo Robot 2002'],
[5, 'Super Robot 2003'],
[6, 'Super Turbo Robot 2004']]},
'prompt': 'In SQL, you can use the <code>LIKE</code> command in order to search through text-based values. With <code>LIKE</code>, there are two special characters: <code>%</code> and <code>_</code>. <br/><br/> The percent sign (<code>%</code>) represents zero, one, or multiple characters. <br/><br/> The underscore (<code>_</code>) represents one character. <br/><br/> For example, <code>LIKE "SUPER _"</code> would match values such as "SUPER 1", "SUPER A", and "SUPER Z". <br/><br/> <code>LIKE "SUPER%"</code> would match any value where <code>SUPER</code> is at the beginning, such as "SUPER CAT", "SUPER 123", or even "SUPER" by itself. <br/><br/> <code>SELECT * FROM robots WHERE name LIKE "%Robot%";</code> would yield all values that contain "Robot" in the name. Can you run a query that returns "Robot" followed by a year between 2000 and 2099? (So 2015 is a valid value at the end, but 2123 is not.) <br/><br/> Note: <code>LIKE</code> queries are <strong>not</strong> case sensitive.'},
{'name': 'CASE',
'short_name': 'case',
'database_type': 'friends_of_pickles',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'height_cm', 'sound'],
'values': [[1, 'Dave', 'male', 'human', 180, 'talk'],
[2, 'Mary', 'female', 'human', 160, 'talk'],
[3, 'Fry', 'male', 'cat', 30, 'meow'],
[4, 'Leela', 'female', 'cat', 25, 'meow'],
[5, 'Odie', 'male', 'dog', 40, 'bark'],
[6, 'Jumpy', 'male', 'dog', 35, 'bark'],
[7, 'Sneakers', 'male', 'dog', 55, 'bark']]},
'prompt': 'You can use a <code>CASE</code> statement to return certain values when certain scenarios are true. <br/><br/> A <code>CASE</code> statement takes the following form: <br/><br/> <code>CASE WHEN *first thing is true* THEN *value1*<br/>WHEN *second thing is true* THEN *value2*<br/>...<br/>ELSE *value for all other situations* <br/> END </code> <br/><br/> For example, in order to return the number of legs for each row in <strong>friends_of_pickles</strong>, you could run: <br/> <code>SELECT *, <br/> CASE WHEN species = \'human\' THEN 2 ELSE 4 END AS num_legs <br/> FROM friends_of_pickles;</code><br/><br/> Can you return the results with a column named <em>sound</em> that returns "talk" for humans, "bark" for dogs, and "meow" for cats?'},
{'name': 'SUBSTR',
'short_name': 'substr',
'database_type': 'robot_code',
'answer': {'columns': ['id', 'name', 'location'],
'values': [[1, 'R2000 - Robot 2000', 'New City, NY'],
[3, 'D0001 - Dragon', 'New York City, NY'],
[4, 'R2002 - Turbo Robot 2002', 'Spring Valley, NY'],
[5, 'R2003 - Super Robot 2003', 'Nyack, NY'],
[8, 'U2111 - Unreleased Turbo Robot 2111', 'Buffalo, NY']]},
'prompt': 'In SQL, you can search for the substring of a given value. Perhaps a location is stored in the format "city, state" and you just want to grab the state. <br/><br/> SUBSTR is used in this format: <code>SUBSTR(<em>column_name</em>, <em>index</em>, <em>number_of_characters</em>)</code> <br/><br/> <em>index</em> is a number that denotes where you would start the substring. 1 would indicate the first character, 2 would indicated the second character, etc. The index could also be negative, which means you would count from the end of the string. -1 would denote the last character, -2 would denote the 2nd to last character, etc. <br/><br/> <em>number_of_characters</em> is optional; if it is not included, the substring contains the "rest of the string". <br/><br/>Here are some examples:<br/> <code>SUBSTR(name, 1, 5)</code> is the first 5 characters of the name. <br/> <code>SUBSTR(name, -4)</code> is the last 4 characters of the name. <br/><br/><code>SELECT * FROM robots WHERE SUBSTR(name, -4) LIKE \'20__\';</code> is another way of returning all of the robots that have been released between 2000 and 2099.<br/><br/>Note: In other versions of SQL, you could use <code>RIGHT</code> to do this.<br/><br/> Can you return all of the robots that are located in NY?'},
{'name': 'COALESCE',
'short_name': 'coalesce',
'database_type': 'fighting',
'answer': {'columns': ['name', 'weapon'],
'values': [['US Marine', 'M1A1 Abrams Tank'],
['John Wilkes Booth', '.44 caliber Derringer'],
['Zorro', 'Sword of Zorro'],
['Innocent Bystander', null]]},
'prompt': '<code>COALESCE</code> takes a list of columns, and returns the value of the first column that is not null. <br/><br/>Suppose we wanted to find the most powerful weapon that a combatant has on hand. If value of <em>gun</em> is not null, that is the value returned. Otherwise, the value of <em>sword</em> is returned. Then you would run: <br/> <code>SELECT name, COALESCE(gun, sword) as weapon FROM fighters;</code> <br/><br/> Suppose that a fighter\'s tank could count as a weapon, and it would take precedence over the gun and the sword. Could you find each fighter\'s weapon in that scenario?'}
];
// Create the SQL database
var load_database = function(db_type) {
var database, sqlstr, table_names;
database = new sql.Database();
switch (db_type) {
case 'family':
sqlstr = "CREATE TABLE family_members (id int, name char, gender char, species char, num_books_read int);";
sqlstr += "INSERT INTO family_members VALUES (1, 'Dave', 'male', 'human', 200);";
sqlstr += "INSERT INTO family_members VALUES (2, 'Mary', 'female', 'human', 180);";
sqlstr += "INSERT INTO family_members VALUES (3, 'Pickles', 'male', 'dog', 0);";
table_names = ['family_members'];
break;
case 'friends_of_pickles':
sqlstr = "CREATE TABLE friends_of_pickles (id int, name char, gender char, species char, height_cm int);";
sqlstr += "INSERT INTO friends_of_pickles VALUES (1, 'Dave', 'male', 'human', 180);";
sqlstr += "INSERT INTO friends_of_pickles VALUES (2, 'Mary', 'female', 'human', 160);";
sqlstr += "INSERT INTO friends_of_pickles VALUES (3, 'Fry', 'male', 'cat', 30);";
sqlstr += "INSERT INTO friends_of_pickles VALUES (4, 'Leela', 'female', 'cat', 25);";
sqlstr += "INSERT INTO friends_of_pickles VALUES (5, 'Odie', 'male', 'dog', 40);";
sqlstr += "INSERT INTO friends_of_pickles VALUES (6, 'Jumpy', 'male', 'dog', 35);";
sqlstr += "INSERT INTO friends_of_pickles VALUES (7, 'Sneakers', 'male', 'dog', 55);";
table_names = ['friends_of_pickles'];
break;
case 'family_and_legs':
sqlstr = "CREATE TABLE family_members (id int, name char, species char, num_books_read int, num_legs int);";
sqlstr += "INSERT INTO family_members VALUES (1, 'Dave', 'human', 200, 2);";
sqlstr += "INSERT INTO family_members VALUES (2, 'Mary', 'human', 180, 2);";
sqlstr += "INSERT INTO family_members VALUES (3, 'Pickles', 'dog', 0, 4);";
table_names = ['family_members'];
break;
case 'family_null':
sqlstr = "CREATE TABLE family_members (id int, name char, gender char, species char, favorite_book char);";
sqlstr += "INSERT INTO family_members VALUES (1, 'Dave', 'male', 'human', 'To Kill a Mockingbird');";
sqlstr += "INSERT INTO family_members VALUES (2, 'Mary', 'female', 'human', 'Gone with the Wind');";
sqlstr += "INSERT INTO family_members VALUES (3, 'Pickles', 'male', 'dog', NULL);";
table_names = ['family_members'];
break;
case 'celebs_born':
sqlstr = "CREATE TABLE celebs_born (id int, name char, birthdate date);";
sqlstr += "INSERT INTO celebs_born VALUES (1, 'Michael Jordan', '1963-02-17');";
sqlstr += "INSERT INTO celebs_born VALUES (2, 'Justin Timberlake', '1981-01-31');";
sqlstr += "INSERT INTO celebs_born VALUES (3, 'Taylor Swift', '1989-12-13');";
table_names = ['celebs_born'];
break;
case 'tv':
sqlstr = "CREATE TABLE character (id int, name char);";
sqlstr += "INSERT INTO character VALUES (1, 'Doogie Howser');";
sqlstr += "INSERT INTO character VALUES (2, 'Barney Stinson');";
sqlstr += "INSERT INTO character VALUES (3, 'Lily Aldrin');";
sqlstr += "INSERT INTO character VALUES (4, 'Willow Rosenberg');";
sqlstr += "CREATE TABLE character_tv_show (id int, character_id int, tv_show_name char);";
sqlstr += "INSERT INTO character_tv_show VALUES (1, 4, 'Buffy the Vampire Slayer');";
sqlstr += "INSERT INTO character_tv_show VALUES (2, 3, 'How I Met Your Mother');";
sqlstr += "INSERT INTO character_tv_show VALUES (3, 2, 'How I Met Your Mother');";
sqlstr += "INSERT INTO character_tv_show VALUES (4, 1, 'Doogie Howser, M.D.');";
sqlstr += "CREATE TABLE character_actor (id int, character_id int, actor_name char);";
sqlstr += "INSERT INTO character_actor VALUES (1, 4, 'Alyson Hannigan');";
sqlstr += "INSERT INTO character_actor VALUES (2, 3, 'Alyson Hannigan');";
sqlstr += "INSERT INTO character_actor VALUES (3, 2, 'Neil Patrick Harris');";
sqlstr += "INSERT INTO character_actor VALUES (4, 1, 'Neil Patrick Harris');";
table_names = ['character', 'character_tv_show', 'character_actor'];
break;
case 'tv_normalized':
sqlstr = "CREATE TABLE character (id int, name char);";
sqlstr += "INSERT INTO character VALUES (1, 'Doogie Howser');";
sqlstr += "INSERT INTO character VALUES (2, 'Barney Stinson');";
sqlstr += "INSERT INTO character VALUES (3, 'Lily Aldrin');";
sqlstr += "INSERT INTO character VALUES (4, 'Willow Rosenberg');";
sqlstr += "CREATE TABLE tv_show (id int, name char);";
sqlstr += "INSERT INTO tv_show VALUES (1, 'Buffy the Vampire Slayer');";
sqlstr += "INSERT INTO tv_show VALUES (2, 'How I Met Your Mother');";
sqlstr += "INSERT INTO tv_show VALUES (3, 'Doogie Howser, M.D.');";
sqlstr += "CREATE TABLE character_tv_show (id int, character_id int, tv_show_id int);";
sqlstr += "INSERT INTO character_tv_show VALUES (1, 1, 3);";
sqlstr += "INSERT INTO character_tv_show VALUES (2, 2, 2);";
sqlstr += "INSERT INTO character_tv_show VALUES (3, 3, 2);";
sqlstr += "INSERT INTO character_tv_show VALUES (4, 4, 1);";
sqlstr += "CREATE TABLE actor (id int, name char);";
sqlstr += "INSERT INTO actor VALUES (1, 'Alyson Hannigan');";
sqlstr += "INSERT INTO actor VALUES (2, 'Neil Patrick Harris');";
sqlstr += "CREATE TABLE character_actor (id int, character_id int, actor_id int);";
sqlstr += "INSERT INTO character_actor VALUES (1, 1, 2);";
sqlstr += "INSERT INTO character_actor VALUES (2, 2, 2);";
sqlstr += "INSERT INTO character_actor VALUES (3, 3, 1);";
sqlstr += "INSERT INTO character_actor VALUES (4, 4, 1);";
table_names = ['character', 'tv_show', 'character_tv_show', 'actor', 'character_actor'];
break;
case 'tv_extra':
sqlstr = "CREATE TABLE character (id int, name char);";
sqlstr += "INSERT INTO character VALUES (1, 'Doogie Howser');";
sqlstr += "INSERT INTO character VALUES (2, 'Barney Stinson');";
sqlstr += "INSERT INTO character VALUES (3, 'Lily Aldrin');";
sqlstr += "INSERT INTO character VALUES (4, 'Willow Rosenberg');";
sqlstr += "INSERT INTO character VALUES (5, 'Steve Urkel');";
sqlstr += "INSERT INTO character VALUES (6, 'Homer Simpson');";
sqlstr += "CREATE TABLE tv_show (id int, name char);";
sqlstr += "INSERT INTO tv_show VALUES (1, 'Buffy the Vampire Slayer');";
sqlstr += "INSERT INTO tv_show VALUES (2, 'How I Met Your Mother');";
sqlstr += "INSERT INTO tv_show VALUES (3, 'Doogie Howser, M.D.');";
sqlstr += "INSERT INTO tv_show VALUES (4, 'Friends');";
sqlstr += "CREATE TABLE character_tv_show (id int, character_id int, tv_show_id int);";
sqlstr += "INSERT INTO character_tv_show VALUES (1, 1, 3);";
sqlstr += "INSERT INTO character_tv_show VALUES (2, 2, 2);";
sqlstr += "INSERT INTO character_tv_show VALUES (3, 3, 2);";
sqlstr += "INSERT INTO character_tv_show VALUES (4, 4, 1);";
sqlstr += "CREATE TABLE actor (id int, name char);";
sqlstr += "INSERT INTO actor VALUES (1, 'Alyson Hannigan');";
sqlstr += "INSERT INTO actor VALUES (2, 'Neil Patrick Harris');";
sqlstr += "INSERT INTO actor VALUES (3, 'Adam Sandler');";
sqlstr += "INSERT INTO actor VALUES (4, 'Steve Carell');";
sqlstr += "CREATE TABLE character_actor (id int, character_id int, actor_id int);";
sqlstr += "INSERT INTO character_actor VALUES (1, 1, 2);";
sqlstr += "INSERT INTO character_actor VALUES (2, 2, 2);";
sqlstr += "INSERT INTO character_actor VALUES (3, 3, 1);";
sqlstr += "INSERT INTO character_actor VALUES (4, 4, 1);";
table_names = ['character', 'tv_show', 'character_tv_show', 'actor', 'character_actor'];
break;
case 'self_join':
sqlstr = "CREATE TABLE rps (id int, name char, defeats_id int);";
sqlstr += "INSERT INTO rps VALUES (1, 'Rock', 3);";
sqlstr += "INSERT INTO rps VALUES (2, 'Paper', 1);";
sqlstr += "INSERT INTO rps VALUES (3, 'Scissors', 2);";
sqlstr += "CREATE TABLE employees (id int, name char, title char, boss_id int);";
sqlstr += "INSERT INTO employees VALUES (1, 'Patrick Smith', 'Software Engineer', 2);";
sqlstr += "INSERT INTO employees VALUES (2, 'Abigail Reed', 'Engineering Manager', 3);";
sqlstr += "INSERT INTO employees VALUES (3, 'Bob Carey', 'Director of Engineering', 4);";
sqlstr += "INSERT INTO employees VALUES (4, 'Maxine Tang', 'CEO', null);";
table_names = ['rps', 'employees'];
break;
case 'robot':
sqlstr = "CREATE TABLE robots (id int, name char);";
sqlstr += "INSERT INTO robots VALUES (1, 'Robot 2000');";
sqlstr += "INSERT INTO robots VALUES (2, 'Champion Robot 2001');";
sqlstr += "INSERT INTO robots VALUES (3, 'Dragon');";
sqlstr += "INSERT INTO robots VALUES (4, 'Turbo Robot 2002');";
sqlstr += "INSERT INTO robots VALUES (5, 'Super Robot 2003');";
sqlstr += "INSERT INTO robots VALUES (6, 'Super Turbo Robot 2004');";
sqlstr += "INSERT INTO robots VALUES (7, 'Not A Robot');";
sqlstr += "INSERT INTO robots VALUES (8, 'Unreleased Turbo Robot 2111');";
table_names = ['robots'];
break;
case 'robot_code':
sqlstr = "CREATE TABLE robots (id int, name char, location char);";
sqlstr += "INSERT INTO robots VALUES (1, 'R2000 - Robot 2000', 'New City, NY');";
sqlstr += "INSERT INTO robots VALUES (2, 'R2001 - Champion Robot 2001', 'Palo Alto, CA');";
sqlstr += "INSERT INTO robots VALUES (3, 'D0001 - Dragon', 'New York City, NY');";
sqlstr += "INSERT INTO robots VALUES (4, 'R2002 - Turbo Robot 2002', 'Spring Valley, NY');";
sqlstr += "INSERT INTO robots VALUES (5, 'R2003 - Super Robot 2003', 'Nyack, NY');";
sqlstr += "INSERT INTO robots VALUES (6, 'R2004 - Super Turbo Robot 2004', 'Tampa, FL');";
sqlstr += "INSERT INTO robots VALUES (7, 'N0001 - Not A Robot', 'Seattle, WA');";
sqlstr += "INSERT INTO robots VALUES (8, 'U2111 - Unreleased Turbo Robot 2111', 'Buffalo, NY');";
table_names = ['robots'];
break;
case 'fighting':
sqlstr = "CREATE TABLE fighters (id int, name char, gun char, sword char, tank char);";
sqlstr += "INSERT INTO fighters VALUES (1, 'US Marine', 'Colt 9mm SMG', 'Swiss Army Knife', 'M1A1 Abrams Tank');";
sqlstr += "INSERT INTO fighters VALUES (2, 'John Wilkes Booth', '.44 caliber Derringer', null, null);";
sqlstr += "INSERT INTO fighters VALUES (3, 'Zorro', null, 'Sword of Zorro', null);";
sqlstr += "INSERT INTO fighters VALUES (4, 'Innocent Bystander', null, null, null);";
table_names = ['fighters'];
break;
}
database.run(sqlstr);
var current_table_string = '';
for (var index in table_names) {
results = database.exec("SELECT * FROM " + table_names[index] + ";");
current_table_string += '<div class="table-name">' + table_names[index] + '</div>' + table_from_results(results);
}
$('#current-tables').html(current_table_string);
return database;
};
var current_level;
var current_level_name;
var render_menu = function() {
// Add links to menu
var menu_html = '';
for (var index in levels) {
if (index == (current_level - 1)) {
menu_html += '<strong>';
}
menu_html += '<div class="menu-item">';
if (localStorage.getItem('completed-' + levels[index]['short_name'])) {
menu_html += '<span class="glyphicon glyphicon-ok"></span>';
}
menu_html += '<a href="#!' + levels[index]['short_name'] + '">' + levels[index]['name'] + '</a>';
menu_html += '</div>';
if (index == (current_level - 1)) {
menu_html += '</strong>';
}
}
$('.menu').html(menu_html);
}
var load_level = function() {
var hash_code = window.location.hash.substr(2);
if (hash_code == 'menu') {
render_menu();
$('.menu').removeClass('menu-hidden-for-mobile');
$('.not-menu-container').hide();
return;
}
$('.menu').addClass('menu-hidden-for-mobile');
$('.not-menu-container').show();
// The current level is 1 by default, unless the hash code matches the short name for a level.
current_level = 1;
for (var index in levels) {
if (hash_code == levels[index]['short_name']) {
current_level = parseInt(index, 10) + 1;
break;
}
}
var database = load_database(levels[current_level-1]['database_type']);
// Set text for current level
lesson_name = levels[current_level-1]['name'];
$('#lesson-name').text("Lesson " + current_level + ": " + lesson_name);
$('#prompt').html(levels[current_level-1]['prompt']);
// Add "next" and "previous" links if it makes sense.
if (current_level > 1) {
$('#previous-link').attr('href', '#!' + levels[current_level-2]['short_name']);
$('#previous-link').show();
} else {
$('#previous-link').hide();
}
if (current_level < levels.length) {
$('#next-link').attr('href', '#!' + levels[current_level]['short_name']);
$('#next-link').show();
} else {
$('#next-link').hide();
}
// Add links to menu
render_menu();
// Clear out old data
$('#answer-correct').hide();
$('#answer-wrong').hide();
$('#sql-input').val('');
$('#results').html('');
$('.expected-results-container').hide();
return database;
};
db = load_level();
// When the URL after the # changes, we load a new level,
// and let Google Analytics know that the page has changed.
$(window).bind('hashchange', function() {
db = load_level();
ga('send', 'pageview', {'page': location.pathname + location.search + location.hash});
});
| sqlteaching.js | var sql = window.SQL;
// The db variable gets set every time a level is loaded.
var db;
// Return an HTML table as a string, given SQL.js results
var table_from_results = function(res) {
var table_string = '<table>';
if (res) {
table_string += '<tr>';
for (var index in res[0].columns) {
table_string += '<th>' + res[0].columns[index] + '</th>';
}
table_string += '</tr>';
for (var row_index in res[0].values) {
table_string += '<tr>';
for (var col_index in res[0].values[row_index]) {
table_string += '<td>' + res[0].values[row_index][col_index] + '</td>';
}
table_string += '</tr>';
}
}
table_string += '</table>';
return table_string;
};
var grade_results = function(results, correct_answer) {
if (!results) {
return false;
}
// Check to make sure the results are equal, but normalize case and remove whitespace from column names.
var normalize = function(x){return x.toUpperCase().replace(/\s/g, "")};
return JSON.stringify(results[0].columns.map(normalize)) == JSON.stringify(correct_answer.columns.map(normalize)) &&
JSON.stringify(results[0].values) == JSON.stringify(correct_answer.values);
};
var show_is_correct = function(is_correct, custom_error_message) {
if (is_correct) {
is_correct_html = 'Congrats! That is correct!<br/>';
if (current_level < levels.length) {
is_correct_html += '<a href="#!' + levels[current_level]['short_name'] + '" tabindex="3">Next Lesson</a>';
} else {
is_correct_html += 'That is currently the end of the tutorial. Please check back later for more!';
}
$('#answer-correct').html(is_correct_html);
$('#answer-correct').show();
$('#answer-wrong').hide();
} else if (custom_error_message) {
$('#answer-wrong').text(custom_error_message);
$('#answer-wrong').show();
$('#answer-correct').hide();
} else {
$('#answer-wrong').text('That was incorrect. Please try again.');
$('#answer-wrong').show();
$('#answer-correct').hide();
}
};
var strings_present = function(strings) {
var ans = $('#sql-input').val().toLowerCase();
for (var index in strings) {
if (ans.indexOf(strings[index].toLowerCase()) < 0) {
return false;
}
}
return true;
};
var execute_query = function() {
var cur_level = levels[current_level-1];
var correct_answer = cur_level['answer'];
try {
var results = db.exec($('#sql-input').val());
if (results.length == 0) {
$('#results').html('');
show_is_correct(false, 'The query you have entered did not return any results. Please try again.');
} else {
$('#results').html(table_from_results(results));
var is_correct = grade_results(results, correct_answer);
if (is_correct) {
// The required strings are optional, but if they exist and it fails, we show a custom error message.
if (!cur_level['required'] || strings_present(cur_level['required'])) {
show_is_correct(true, null);
localStorage.setItem('completed-' + cur_level['short_name'], 'correct');
// By calling render_menu, the completed level gets a checkmark added
render_menu();
} else {
show_is_correct(false, cur_level['custom_error_message']);
}
} else {
show_is_correct(false, 'The query you have entered did not return the proper results. Please try again.');
}
}
} catch (err) {
$('#results').html('');
show_is_correct(false, 'The query you have entered is not valid. Please try again.');
}
$('.expected-results-container').show();
$('#expected-results').html(table_from_results([correct_answer]));
return false;
};
// Onclick handler for when you click "Run SQL"
$('#sql-link').click(execute_query);
// Keypress handler for ctrl + enter to "Run SQL"
$('#sql-input').keypress(function(event) {
var keyCode = (event.which ? event.which : event.keyCode);
if (keyCode === 10 || keyCode == 13 && event.ctrlKey) {
execute_query();
return false;
}
});
/**
* This variable has the prompts and answers for each level.
*
* It is an array of dictionaries. In each dictionary, there are the following keys:
* - name: name shown on web page
* - short_name: identifier added to the URL
* - database_type: is passed into the load_database function, in order to determine the tables loaded
* - answer: the query that the user writes must return data that matches this value
* - prompt: what is shown to the user in that web page
*
* And the following keys are optional:
* - required: Extra validation in the form of case-insensitive required strings
* - custom_error_message: If the validation fails, show this error message to the user
*/
var levels = [{'name': 'SELECT *',
'short_name': 'select',
'database_type': 'family',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'num_books_read'],
'values': [[1, 'Dave', 'male', 'human', 200],
[2, 'Mary', 'female', 'human', 180],
[3, 'Pickles', 'male', 'dog', 0]]},
'prompt': 'In SQL, data is usually organized in various tables. For example, a sports team database might have the tables <em>teams</em>, <em>players</em>, and <em>games</em>. A wedding database might have tables <em>guests</em>, <em>vendors</em>, and <em>music_playlist</em>.<br/><br/>Imagine we have a table that stores family members with each member\'s name, age, species, and gender.<br/><br/>Let\'s start by grabbing all of the data in one table. We have a table called <strong>family_members</strong> that is shown below. In order to grab all of that data, please run the following command: <code>SELECT * FROM family_members;</code><br/><br/>The <code>*</code> above means that all of the columns will be returned, which in this case are <em>id</em>, <em>name</em>, <em>gender</em>, <em>species</em>, and <em>num_books_read</em>. <br/><br/>Note: This tutorial uses the <a href="http://en.wikipedia.org/wiki/SQLite" target="_blank">SQLite</a> database engine. The different variants of SQL use slightly different syntax.'},
{'name': 'SELECT specific columns',
'short_name': 'select_columns',
'database_type': 'family',
'answer': {'columns': ['name', 'species'],
'values': [['Dave', 'human'],
['Mary', 'human'],
['Pickles', 'dog']]},
'prompt': '<code>SELECT *</code> grabs all fields (called columns) in a table. If we only wanted to see the name and num_books_read columns, we would type<br/> <code>SELECT name, num_books_read FROM family_members;</code>.<br/><br/>Can you return just the name and species columns?'},
{'name': 'WHERE ... Equals',
'short_name': 'where_equals',
'database_type': 'family',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'num_books_read'],
'values': [[3, 'Pickles', 'male', 'dog', 0]]},
'prompt': 'In order to select particular rows from this table, we use the <code>WHERE</code> keyword. So for example, if we wanted to grab all of the rows that correspond to humans, we would type <br/><code>SELECT * FROM family_members WHERE species = \'human\';</code><br/> Note that the quotes have to be around the word human, as it is an explicit value, unlike a keyword such as <code>WHERE</code>.<br/><br/>Can you run a query that returns all of the rows that refer to dogs?'},
{'name': 'WHERE ... Greater than',
'short_name': 'where_greater_than',
'database_type': 'family',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'num_books_read'],
'values': [[1, 'Dave', 'male', 'human', 200]]},
'prompt': 'If we want to only select family members based on a numerical field, we can also use the <code>WHERE</code> keyword. For example, if we wanted to select family members with a num_books_read, we would type <br/><code>SELECT * FROM family_members WHERE num_books_read > 0;</code><br/><br/> Can you run return all rows of family members whose num_books_read is greater than 190?'},
{'name': 'WHERE ... Greater than or equal',
'short_name': 'where_greater_than_or_equal',
'database_type': 'family',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'num_books_read'],
'values': [[1, 'Dave', 'male', 'human', 200],
[2, 'Mary', 'female', 'human', 180]]},
'prompt': 'SQL accepts various inequality symbols, including: <br/><code>=</code> "equal to"<br/><code>></code> "greater than"<br/><code><</code> "less than"<br/><code>>=</code> "greater than or equal to"<br/><code><=</code> "less than or equal to"<br/><br/> Can you return all rows in <strong>family_members</strong> where num_books_read is a value greater or equal to 180?'},
{'name': 'AND',
'short_name': 'and',
'database_type': 'friends_of_pickles',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'height_cm'],
'values': [[5, 'Odie', 'male', 'dog', 40],
[6, 'Jumpy', 'male', 'dog', 35]]},
'prompt': 'In the <code>WHERE</code> part of a query, you can search for multiple attributes by using the <code>AND</code> keyword. For example, if you wanted to find the friends of Pickles that are over 25cm in height and are cats, you would run: <br/><code>SELECT * FROM friends_of_pickles WHERE height_cm > 25 AND species = \'cat\';</code><br/><br/>Can you find all of Pickles\' friends that are dogs and under the height of 45cm?'},
{'name': 'OR',
'short_name': 'or',
'database_type': 'friends_of_pickles',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'height_cm'],
'values': [[3, 'Fry', 'male', 'cat', 30],
[4, 'Leela', 'female', 'cat', 25],
[5, 'Odie', 'male', 'dog', 40],
[6, 'Jumpy', 'male', 'dog', 35],
[7, 'Sneakers', 'male', 'dog', 55]]},
'prompt': 'In the <code>WHERE</code> part of a query, you can search for rows that match any of multiple attributes by using the <code>OR</code> keyword. For example, if you wanted to find the friends of Pickles that are over 25cm in height or are cats, you would run: <br/><code>SELECT * FROM friends_of_pickles WHERE height_cm > 25 OR species = \'cat\';</code><br/><br/>Can you find all of Pickles\' friends that are dogs or under the height of 45cm?'},
{'name': 'IN',
'short_name': 'in',
'database_type': 'friends_of_pickles',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'height_cm'],
'values': [[1, 'Dave', 'male', 'human', 180],
[2, 'Mary', 'female', 'human', 160]]},
'prompt': 'Using the <code>WHERE</code> clause, we can find rows where a value is in a list of several possible values. <br/><br/><code>SELECT * FROM friends_of_pickles WHERE species IN (\'cat\', \'human\');</code> would return the <strong>friends_of_pickles</strong> that are either a cat or a human. <br/><br/>To find rows that are not in a list, you use <code>NOT IN</code> instead of <code>IN</code>. <br/><br/>Can you run a query that would return the rows that are <strong>not</strong> cats or dogs?'},
{'name': 'DISTINCT',
'short_name': 'distinct',
'database_type': 'friends_of_pickles',
'answer': {'columns': ['species'],
'values': [['human'], ['dog']]},
'prompt': 'By putting <code>DISTINCT</code> after <code>SELECT</code>, you do not return duplicates. <br/><br/>For example, if you run <br/> <code>SELECT DISTINCT gender, species FROM friends_of_pickles WHERE height_cm < 100;</code>, you will get the gender/species combinations of the animals less than 100cm in height. <br/><br/>Note that even though there are multiple male dogs under that height, we only see one row that returns "male" and "dog".<br/><br/> Can you return a list of the distinct species of animals greater than 50cm in height?'},
{'name': 'ORDER BY',
'short_name': 'order_by',
'database_type': 'friends_of_pickles',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'height_cm'],
'values': [[1, 'Dave', 'male', 'human', 180],
[2, 'Mary', 'female', 'human', 160],
[7, 'Sneakers', 'male', 'dog', 55],
[5, 'Odie', 'male', 'dog', 40],
[6, 'Jumpy', 'male', 'dog', 35],
[3, 'Fry', 'male', 'cat', 30],
[4, 'Leela', 'female', 'cat', 25]]},
'prompt': 'If you want to sort the rows by some kind of attribute, you can use the <code>ORDER BY</code> keyword. For example, if you want to sort the <strong>friends_of_pickles</strong> by name, you would run: <code>SELECT * FROM friends_of_pickles ORDER BY name;</code>. That returns the names in ascending alphabetical order.<br/><br/> In order to put the names in descending order, you would add a <code>DESC</code> at the end of the query.<br/><br/> Can you run a query that sorts the <strong>friends_of_pickles</strong> by <em>height_cm</em> in descending order?'},
{'name': 'LIMIT # of returned rows',
'short_name': 'limit',
'database_type': 'friends_of_pickles',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'height_cm'],
'values': [[1, 'Dave', 'male', 'human', 180]]},
'prompt': 'Often, tables contain millions of rows, and it can take a while to grab everything. If we just want to see a few examples of the data in a table, we can select the first few rows with the <code>LIMIT</code> keyword. If you use <code>ORDER BY</code>, you would get the first rows for that order. <br/><br/>If you wanted to see the two shortest <strong>friends_of_pickles</strong>, you would run: <code>SELECT * FROM friends_of_pickles ORDER BY height_cm LIMIT 2;</code><br/><br/> Can you return the single row (and all columns) of the tallest <strong>friends_of_pickles</strong>?<br/><br/>Note: <br/>- Some variants of SQL do not use the <code>LIMIT</code> keyword.<br/>- The <code>LIMIT</code> keyword comes after the <code>DESC</code> keyword.'},
{'name': 'COUNT(*)',
'short_name': 'count',
'database_type': 'friends_of_pickles',
'answer': {'columns': ['COUNT(*)'],
'values': [[7]]},
'prompt': 'Another way to explore a table is to check the number of rows in it. For example, if we are querying a table <em>states_of_us</em>, we\'d expect 50 rows, or 500 rows in a table called <em>fortune_500_companies</em>.<br/><br/><code>SELECT COUNT(*) FROM friends_of_pickles;</code> returns the total number of rows in the table <strong>friends_of_pickles</strong>. Try this for yourself.'},
{'name': 'COUNT(*) ... WHERE',
'short_name': 'count_where',
'database_type': 'friends_of_pickles',
'answer': {'columns': ['COUNT(*)'],
'values': [[3]]},
'prompt': 'We can combine <code>COUNT(*)</code> with <code>WHERE</code> to return the number of rows that matches the <code>WHERE</code> clause.<br/><br/> For example, <code>SELECT COUNT(*) FROM friends_of_pickles WHERE species = \'human\';</code> returns 2.<br/><br/>Can you return the number of rows in <strong>friends_of_pickles</strong> where the species is a dog?'},
{'name': 'SUM',
'short_name': 'sum',
'database_type': 'family_and_legs',
'answer': {'columns': ['SUM(num_books_read)'],
'values': [[380]]},
'prompt': 'We can use the <code>SUM</code> keyword in order to find the sum of a given value. <br/><br/>For example, running <code>SELECT SUM(num_legs) FROM family_members;</code> returns the total number of legs in the family. <br/><br/>Can you find the total num_books_read made by this family?'},
{'name': 'AVG',
'short_name': 'avg',
'database_type': 'family_and_legs',
'answer': {'columns': ['AVG(num_books_read)'],
'values': [[126.66666666666667]]},
'prompt': 'We can use the <code>AVG</code> keyword in order to find the average of a given value. <br/><br/>For example, running <code>SELECT AVG(num_legs) FROM family_members;</code> returns the average number of legs of each family member. <br/><br/>Can you find the average num_books_read made by each family member? <br/><br/>Note: <br/>- Because of the way computers handle numbers, averages will not always be completely exact.'},
{'name': 'MAX and MIN',
'short_name': 'max_min',
'database_type': 'family_and_legs',
'answer': {'columns': ['MAX(num_books_read)'],
'values': [[200]]},
'prompt': 'We can use the <code>MAX</code> and <code>MIN</code> to find the maximum or minimum value of a table. <br/><br/>To find the least number of legs in a family member (<em>2</em>), you can run <br/><code>SELECT MIN(num_legs) FROM family_members;</code> <br/><br/>Can you find the highest num_books_read that a family member makes?'},
{'name': 'GROUP BY',
'short_name': 'group_by',
'database_type': 'friends_of_pickles',
'answer': {'columns': ['MAX(height_cm)', 'species'],
'values': [[30, 'cat'],
[55, 'dog'],
[180, 'human']]},
'prompt': 'You can use aggregate functions such as <code>COUNT</code>, <code>SUM</code>, <code>AVG</code>, <code>MAX</code>, and <code>MIN</code> with the <code>GROUP BY</code> clause. <br/><br/> When you <code>GROUP BY</code> something, you split the table into different piles based on the value of each row. <br/><br/>For example, <br/><code>SELECT COUNT(*), species FROM friends_of_pickles GROUP BY species;</code> would return the number of rows for each species. <br/><br/> Can you return the tallest height for each species? Remember to return the species name next to the height too, like in the example query.'},
{'name': 'Nested queries',
'short_name': 'nested',
'database_type': 'family_and_legs',
'required': ['(', ')'],
'custom_error_message': 'You must use a nested query in your answer.',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'num_books_read', 'num_legs'],
'values': [[1, 'Dave', 'male', 'human', 200, 2]]},
'prompt': 'In SQL, you can put a SQL query inside another SQL query. <br/><br/>For example, to find the family members with the least number of legs, <br/> you can run: <br/><code>SELECT * FROM family_members WHERE num_legs = (SELECT MIN(num_legs) FROM family_members);</code> <br/><br/> The <code>SELECT</code> query inside the parentheses is executed first, and returns the minimum number of legs. Then, that value (2) is used in the outside query, to find all family members that have 2 legs. <br/><br/> Can you return the family members that have the highest num_books_read?'},
{'name': 'NULL',
'short_name': 'null',
'database_type': 'family_null',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'num_books_read', 'favorite_book'],
'values': [[1, 'Dave', 'male', 'human', 200, 'To Kill a Mockingbird'],
[2, 'Mary', 'female', 'human', 180, 'Gone with the Wind']]},
'prompt': 'Sometimes, in a given row, there is no value at all for a given column. For example, a dog does not have a favorite book, so in that case there is no point in putting a value in the <em>favorite_book</em> column, and the value is <code>NULL</code>. In order to find the rows where the value for a column is or is not <code>NULL</code>, you would use <code>IS NULL</code> or <code>IS NOT NULL</code>.<br/><br/>Can you return all of the rows of <strong>family_members</strong> where <em>favorite_book</em> is not null?'},
{'name': 'Date',
'short_name': 'date',
'database_type': 'celebs_born',
'answer': {'columns': ['id', 'name', 'birthdate'],
'values': [[2, 'Justin Timberlake', '1981-01-31'],
[3, 'Taylor Swift', '1989-12-13']]},
'prompt': 'Sometimes, a column can contain a date value. The first 4 digits represents the year, the next 2 digits represents the month, and the next 2 digits represents the day of the month. For example, <code>1985-07-20</code> would mean July 20, 1985.<br/><br/>You can compare dates by using <code><</code> and <code>></code>. For example, <code>SELECT * FROM celebs_born WHERE birthdate < \'1985-08-17\';</code> returns a list of celebrities that were born before August 17th, 1985.<br/><br/>Can you return a list of celebrities that were born after September 1st, 1980?'},
{'name': 'Inner joins',
'short_name': 'joins',
'database_type': 'tv',
'answer': {'columns': ['name', 'actor_name'],
'values': [['Doogie Howser', 'Neil Patrick Harris'],
['Barney Stinson', 'Neil Patrick Harris'],
['Lily Aldrin', 'Alyson Hannigan'],
['Willow Rosenberg', 'Alyson Hannigan']]},
'prompt': 'Different parts of information can be stored in different tables, and in order to put them together, we use <code>INNER JOIN ... ON</code>. Joining tables gets to the core of SQL functionality, but it can get very complicated. We will start with a simple example, and will start with an <code>INNER JOIN</code>.<br/><br/>As you can see below, there are 3 tables:<br/><strong>character</strong>: Each character is a row and is represented by a unique identifier (<em>id</em>), e.g. 1 is Doogie Howser<br/><strong>character_tv_show:</strong> For each character, which show is he/she in?<br/><strong>character_actor</strong>: For each character, who is the actor?<br/><br/>See that in <strong>character_tv_show</strong>, instead of storing both the character and TV show names (e.g. Willow Rosenberg and Buffy the Vampire Slayer), it stores the <em>character_id</em> as a substitute for the character name. This <em>character_id</em> refers to the matching <em>id</em> row from the <strong>character</strong> table. <br/><br/>This is done so data is not duplicated. For example, if the name of a character were to change, you would only have to change the name of the character in one row. <br/><br/>This allows us to "join" the tables together "on" that reference/common column. <br/><br/>To get each character name with his/her TV show name, we can write <br/><code>SELECT character.name, character_tv_show.tv_show_name<br/> FROM character <br/>INNER JOIN character_tv_show<br/> ON character.id = character_tv_show.character_id;</code><br/>This puts together every row in <strong>character</strong> with the corresponding row in <strong>character_tv_show</strong>, or vice versa.<br/><br/>Note:<br/>- We use the syntax <strong>table_name</strong>.<em>column_name</em>. If we only used <em>column_name</em>, SQL might incorrectly assume which table it is coming from.<br/> - The example query above is written over multiple lines for readability, but that does not affect the query. <br/><br/>Can you use an inner join to pair each character name with the actor who plays them? Select the columns: <strong>character</strong>.<em>name</em>, <strong>character_actor</strong>.<em>actor_name</em>'},
{'name': 'Multiple joins',
'short_name': 'multiple_joins',
'database_type': 'tv_normalized',
'answer': {'columns': ['name', 'name'],
'values': [['Doogie Howser', 'Neil Patrick Harris'],
['Barney Stinson', 'Neil Patrick Harris'],
['Lily Aldrin', 'Alyson Hannigan'],
['Willow Rosenberg', 'Alyson Hannigan']]},
'prompt': 'In the previous exercise, we explained that TV show character names were not duplicated, so if the name of a character were to change, you would only have to change the name of the character in one row. <br/><br/>However, the previous example was a bit artificial because the TV show names and actor names were duplicated. <br/><br/>In order to not duplicate any names, we need to have more tables, and use multiple joins. <br/><br/>We have tables for characters, TV shows, and actors. Those tables represent things (also known as entities). <br/><br/>In addition those tables, we have the relationship tables <strong>character_tv_show</strong> and <strong>character_actor</strong>, which capture the relationship between two entities. <br/><br/>This is a flexible way of capturing the relationship between different entities, as some TV show characters might be in multiple shows, and some actors are known for playing multiple characters. <br/><br/>To get each character name with his/her TV show name, we can write <br/><code>SELECT character.name, tv_show.name<br/> FROM character <br/>INNER JOIN character_tv_show<br/> ON character.id = character_tv_show.character_id<br/>INNER JOIN tv_show<br/> ON character_tv_show.tv_show_id = tv_show.id;</code><br/><br/>Can you use two joins to pair each character name with the actor who plays them? Select the columns: <strong>character</strong>.<em>name</em>, <strong>actor</strong>.<em>name</em>'},
{'name': 'Joins with WHERE',
'short_name': 'joins_with_where',
'required': ['Willow Rosenberg', 'How I Met Your Mother'],
'custom_error_message': 'You must check that the characters are not named "Willow Rosenberg" or in the show "How I Met Your Mother".',
'database_type': 'tv_normalized',
'answer': {'columns': ['name', 'name'],
'values': [['Doogie Howser', 'Doogie Howser, M.D.']]},
'prompt': 'You can also use joins with the <code>WHERE</code> clause. <br/><br/> To get a list of characters and TV shows that are not in "Buffy the Vampire Slayer" and are not Barney Stinson, you would run: <br/> <code>SELECT character.name, tv_show.name<br/> FROM character <br/>INNER JOIN character_tv_show<br/> ON character.id = character_tv_show.character_id<br/>INNER JOIN tv_show<br/> ON character_tv_show.tv_show_id = tv_show.id WHERE character.name != \'Barney Stinson\' AND tv_show.name != \'Buffy the Vampire Slayer\';</code> <br/><br/>Can you return a list of characters and TV shows that are not named "Willow Rosenberg" or in the show "How I Met Your Mother"?'},
{'name': 'Left joins',
'short_name': 'left_joins',
'database_type': 'tv_extra',
'answer': {'columns': ['name', 'name'],
'values': [['Doogie Howser', 'Neil Patrick Harris'],
['Barney Stinson', 'Neil Patrick Harris'],
['Lily Aldrin', 'Alyson Hannigan'],
['Willow Rosenberg', 'Alyson Hannigan'],
['Steve Urkel', null],
['Homer Simpson', null]]},
'prompt': 'In the previous exercise, we used joins to match up TV character names with their actors. When you use <code>INNER JOIN</code>, that is called an "inner join" because it only returns rows where there is data for both the character name and the actor. <br/><br/> However, perhaps you want to get all of the character names, even if there isn\'t corresponding data for the name of the actor. A <code>LEFT JOIN</code> returns all of the data from the first (or "left") table, and if there isn\'t corresponding data for the second table, it returns <code>NULL</code> for those columns. <br/><br/> Using left joins between character names and TV shows would look like this: <br/><code>SELECT character.name, tv_show.name<br/> FROM character <br/>LEFT JOIN character_tv_show<br/> ON character.id = character_tv_show.character_id<br/> LEFT JOIN tv_show<br/> ON character_tv_show.tv_show_id = tv_show.id;</code> <br/><br/> Can you use left joins to match character names with the actors that play them? Select the columns: <strong>character</strong>.<em>name</em>, <strong>actor</strong>.<em>name</em> <br/><br/>Note: Other variants of SQL have <code>RIGHT JOIN</code> and <code>OUTER JOIN</code>, but those features are not present in SQLite.'},
{'name': 'Table alias',
'short_name': 'table_alias',
'required': ['AS', 'c.name', 'a.name'],
'custom_error_message': 'You must use table aliases as described above.',
'database_type': 'tv_extra',
'answer': {'columns': ['name', 'name'],
'values': [['Doogie Howser', 'Neil Patrick Harris'],
['Barney Stinson', 'Neil Patrick Harris'],
['Lily Aldrin', 'Alyson Hannigan'],
['Willow Rosenberg', 'Alyson Hannigan'],
['Steve Urkel', null],
['Homer Simpson', null]]},
'prompt': 'These queries are starting to get pretty long! <br/><br/>In the previous exercise, we ran a query containing the tables <strong>character</strong>, <strong>tv_show</strong>, and <strong>character_tv_show</strong>. We can write a shorter query if we used aliases for those tables. Basically, we create a "nickname" for that table. <br/><br/> If you want to use an alias for a table, you add <code>AS *alias_name*</code> after the table name. <br/><br/> For example, to use left joins between characters and tv shows with aliases, you would run: <br/> <code>SELECT c.name, t.name<br/>FROM character AS c<br/>LEFT JOIN character_tv_show AS ct<br/>ON c.id = ct.character_id<br/>LEFT JOIN tv_show AS t<br/>ON ct.tv_show_id = t.id;</code> <br/><br/> As you can see, it is shorter than the query in the previous exercise.<br/><br/> Can you use left joins to match character names with the actors that play them, and use aliases to make the query shorter? The aliases for <strong>character</strong>, <strong>character_actor</strong>, and <strong>actor</strong> should be <strong>c</strong>, <strong>ca</strong>, and <strong>a</strong>. <br/><br/>Select the columns: <strong>c</strong>.<em>name</em>, <strong>a</strong>.<em>name</em>'},
{'name': 'Column alias',
'short_name': 'column_alias',
'database_type': 'tv_extra',
'answer': {'columns': ['character', 'actor'],
'values': [['Doogie Howser', 'Neil Patrick Harris'],
['Barney Stinson', 'Neil Patrick Harris'],
['Lily Aldrin', 'Alyson Hannigan'],
['Willow Rosenberg', 'Alyson Hannigan'],
['Steve Urkel', null],
['Homer Simpson', null]]},
'prompt': 'In addition to making aliases for tables, you can also make them for columns. <br/><br/> This clears up confusion on which column is which. In the previous exercise, both columns in the result are simply called "name", and that can be confusing. <br/><br/> If you want to use an alias for a column, you add <code>AS *alias_name*</code> after the column name. <br/><br/> If we wanted to use left joins between character names and TV shows and clearly denote which column has character names, and which has TV show names, it would look like this: <br/><code>SELECT character.name AS character, tv_show.name AS name<br/> FROM character <br/>LEFT JOIN character_tv_show<br/> ON character.id = character_tv_show.character_id<br/> LEFT JOIN tv_show<br/> ON character_tv_show.tv_show_id = tv_show.id;</code> <br/><br/>Can you use left joins to match character names with the actors that play them, and use aliases to call the two columns returned <em>character</em> and <em>actor</em>?'},
{'name': 'Self joins',
'short_name': 'self_join',
'database_type': 'self_join',
'answer': {'columns': ['employee_name', 'boss_name'],
'values': [['Patrick Smith', 'Abigail Reed'],
['Abigail Reed', 'Bob Carey'],
['Bob Carey', 'Maxine Tang']]},
'prompt': 'Sometimes, it may make sense for you to do a self join. In that case, you need to use table aliases to determine which data is from the "first"/"left" table. <br/><br/>For example, to get a list of Rock Paper Scissors objects and the objects they beat, you can run the following: <br/><code>SELECT r1.name AS object, r2.name AS beats <br/>FROM rps AS r1 <br/>INNER JOIN rps AS r2 <br/>ON r1.defeats_id = r2.id;</code><br/><br/> Can you run a query that returns the name of an employee and the name of their boss? Use column aliases to make the columns <em>employee_name</em> and <em>boss_name</em>.'},
{'name': 'LIKE',
'short_name': 'like',
'database_type': 'robot',
'answer': {'columns': ['id', 'name'],
'values': [[1, 'Robot 2000'],
[2, 'Champion Robot 2001'],
[4, 'Turbo Robot 2002'],
[5, 'Super Robot 2003'],
[6, 'Super Turbo Robot 2004']]},
'prompt': 'In SQL, you can use the <code>LIKE</code> command in order to search through text-based values. With <code>LIKE</code>, there are two special characters: <code>%</code> and <code>_</code>. <br/><br/> The percent sign (<code>%</code>) represents zero, one, or multiple characters. <br/><br/> The underscore (<code>_</code>) represents one character. <br/><br/> For example, <code>LIKE "SUPER _"</code> would match values such as "SUPER 1", "SUPER A", and "SUPER Z". <br/><br/> <code>LIKE "SUPER%"</code> would match any value where <code>SUPER</code> is at the beginning, such as "SUPER CAT", "SUPER 123", or even "SUPER" by itself. <br/><br/> <code>SELECT * FROM robots WHERE name LIKE "%Robot%";</code> would yield all values that contain "Robot" in the name. Can you run a query that returns "Robot" followed by a year between 2000 and 2099? (So 2015 is a valid value at the end, but 2123 is not.) <br/><br/> Note: <code>LIKE</code> queries are <strong>not</strong> case sensitive.'},
{'name': 'CASE',
'short_name': 'case',
'database_type': 'friends_of_pickles',
'answer': {'columns': ['id', 'name', 'gender', 'species', 'height_cm', 'sound'],
'values': [[1, 'Dave', 'male', 'human', 180, 'talk'],
[2, 'Mary', 'female', 'human', 160, 'talk'],
[3, 'Fry', 'male', 'cat', 30, 'meow'],
[4, 'Leela', 'female', 'cat', 25, 'meow'],
[5, 'Odie', 'male', 'dog', 40, 'bark'],
[6, 'Jumpy', 'male', 'dog', 35, 'bark'],
[7, 'Sneakers', 'male', 'dog', 55, 'bark']]},
'prompt': 'You can use a <code>CASE</code> statement to return certain values when certain scenarios are true. <br/><br/> A <code>CASE</code> statement takes the following form: <br/><br/> <code>CASE WHEN *first thing is true* THEN *value1*<br/>WHEN *second thing is true* THEN *value2*<br/>...<br/>ELSE *value for all other situations* <br/> END </code> <br/><br/> For example, in order to return the number of legs for each row in <strong>friends_of_pickles</strong>, you could run: <br/> <code>SELECT *, <br/> CASE WHEN species = \'human\' THEN 2 ELSE 4 END AS num_legs <br/> FROM friends_of_pickles;</code><br/><br/> Can you return the results with a column named <em>sound</em> that returns "talk" for humans, "bark" for dogs, and "meow" for cats?'},
{'name': 'SUBSTR',
'short_name': 'substr',
'database_type': 'robot_code',
'answer': {'columns': ['id', 'name', 'location'],
'values': [[1, 'R2000 - Robot 2000', 'New City, NY'],
[3, 'D0001 - Dragon', 'New York City, NY'],
[4, 'R2002 - Turbo Robot 2002', 'Spring Valley, NY'],
[5, 'R2003 - Super Robot 2003', 'Nyack, NY'],
[8, 'U2111 - Unreleased Turbo Robot 2111', 'Buffalo, NY']]},
'prompt': 'In SQL, you can search for the substring of a given value. Perhaps a location is stored in the format "city, state" and you just want to grab the state. <br/><br/> SUBSTR is used in this format: <code>SUBSTR(<em>column_name</em>, <em>index</em>, <em>number_of_characters</em>)</code> <br/><br/> <em>index</em> is a number that denotes where you would start the substring. 1 would indicate the first character, 2 would indicated the second character, etc. The index could also be negative, which means you would count from the end of the string. -1 would denote the last character, -2 would denote the 2nd to last character, etc. <br/><br/> <em>number_of_characters</em> is optional; if it is not included, the substring contains the "rest of the string". <br/><br/>Here are some examples:<br/> <code>SUBSTR(name, 1, 5)</code> is the first 5 characters of the name. <br/> <code>SUBSTR(name, -4)</code> is the last 4 characters of the name. <br/><br/><code>SELECT * FROM robots WHERE SUBSTR(name, -4) LIKE \'20__\';</code> is another way of returning all of the robots that have been released between 2000 and 2099.<br/><br/>Note: In other versions of SQL, you could use <code>RIGHT</code> to do this.<br/><br/> Can you return all of the robots that are located in NY?'},
{'name': 'COALESCE',
'short_name': 'coalesce',
'database_type': 'fighting',
'answer': {'columns': ['name', 'weapon'],
'values': [['US Marine', 'M1A1 Abrams Tank'],
['John Wilkes Booth', '.44 caliber Derringer'],
['Zorro', 'Sword of Zorro'],
['Innocent Bystander', null]]},
'prompt': '<code>COALESCE</code> takes a list of columns, and returns the value of the first column that is not null. <br/><br/>Suppose we wanted to find the most powerful weapon that a combatant has on hand. If value of <em>gun</em> is not null, that is the value returned. Otherwise, the value of <em>sword</em> is returned. Then you would run: <br/> <code>SELECT name, COALESCE(gun, sword) as weapon FROM fighters;</code> <br/><br/> Suppose that a fighter\'s tank could count as a weapon, and it would take precedence over the gun and the sword. Could you find each fighter\'s weapon in that scenario?'}
];
// Create the SQL database
var load_database = function(db_type) {
var database, sqlstr, table_names;
database = new sql.Database();
switch (db_type) {
case 'family':
sqlstr = "CREATE TABLE family_members (id int, name char, gender char, species char, num_books_read int);";
sqlstr += "INSERT INTO family_members VALUES (1, 'Dave', 'male', 'human', 200);";
sqlstr += "INSERT INTO family_members VALUES (2, 'Mary', 'female', 'human', 180);";
sqlstr += "INSERT INTO family_members VALUES (3, 'Pickles', 'male', 'dog', 0);";
table_names = ['family_members'];
break;
case 'friends_of_pickles':
sqlstr = "CREATE TABLE friends_of_pickles (id int, name char, gender char, species char, height_cm int);";
sqlstr += "INSERT INTO friends_of_pickles VALUES (1, 'Dave', 'male', 'human', 180);";
sqlstr += "INSERT INTO friends_of_pickles VALUES (2, 'Mary', 'female', 'human', 160);";
sqlstr += "INSERT INTO friends_of_pickles VALUES (3, 'Fry', 'male', 'cat', 30);";
sqlstr += "INSERT INTO friends_of_pickles VALUES (4, 'Leela', 'female', 'cat', 25);";
sqlstr += "INSERT INTO friends_of_pickles VALUES (5, 'Odie', 'male', 'dog', 40);";
sqlstr += "INSERT INTO friends_of_pickles VALUES (6, 'Jumpy', 'male', 'dog', 35);";
sqlstr += "INSERT INTO friends_of_pickles VALUES (7, 'Sneakers', 'male', 'dog', 55);";
table_names = ['friends_of_pickles'];
break;
case 'family_and_legs':
sqlstr = "CREATE TABLE family_members (id int, name char, species char, num_books_read int, num_legs int);";
sqlstr += "INSERT INTO family_members VALUES (1, 'Dave', 'human', 200, 2);";
sqlstr += "INSERT INTO family_members VALUES (2, 'Mary', 'human', 180, 2);";
sqlstr += "INSERT INTO family_members VALUES (3, 'Pickles', 'dog', 0, 4);";
table_names = ['family_members'];
break;
case 'family_null':
sqlstr = "CREATE TABLE family_members (id int, name char, gender char, species char, num_books_read int, favorite_book char);";
sqlstr += "INSERT INTO family_members VALUES (1, 'Dave', 'male', 'human', 200, 'To Kill a Mockingbird');";
sqlstr += "INSERT INTO family_members VALUES (2, 'Mary', 'female', 'human', 180, 'Gone with the Wind');";
sqlstr += "INSERT INTO family_members VALUES (3, 'Pickles', 'male', 'dog', 0, NULL);";
table_names = ['family_members'];
break;
case 'celebs_born':
sqlstr = "CREATE TABLE celebs_born (id int, name char, birthdate date);";
sqlstr += "INSERT INTO celebs_born VALUES (1, 'Michael Jordan', '1963-02-17');";
sqlstr += "INSERT INTO celebs_born VALUES (2, 'Justin Timberlake', '1981-01-31');";
sqlstr += "INSERT INTO celebs_born VALUES (3, 'Taylor Swift', '1989-12-13');";
table_names = ['celebs_born'];
break;
case 'tv':
sqlstr = "CREATE TABLE character (id int, name char);";
sqlstr += "INSERT INTO character VALUES (1, 'Doogie Howser');";
sqlstr += "INSERT INTO character VALUES (2, 'Barney Stinson');";
sqlstr += "INSERT INTO character VALUES (3, 'Lily Aldrin');";
sqlstr += "INSERT INTO character VALUES (4, 'Willow Rosenberg');";
sqlstr += "CREATE TABLE character_tv_show (id int, character_id int, tv_show_name char);";
sqlstr += "INSERT INTO character_tv_show VALUES (1, 4, 'Buffy the Vampire Slayer');";
sqlstr += "INSERT INTO character_tv_show VALUES (2, 3, 'How I Met Your Mother');";
sqlstr += "INSERT INTO character_tv_show VALUES (3, 2, 'How I Met Your Mother');";
sqlstr += "INSERT INTO character_tv_show VALUES (4, 1, 'Doogie Howser, M.D.');";
sqlstr += "CREATE TABLE character_actor (id int, character_id int, actor_name char);";
sqlstr += "INSERT INTO character_actor VALUES (1, 4, 'Alyson Hannigan');";
sqlstr += "INSERT INTO character_actor VALUES (2, 3, 'Alyson Hannigan');";
sqlstr += "INSERT INTO character_actor VALUES (3, 2, 'Neil Patrick Harris');";
sqlstr += "INSERT INTO character_actor VALUES (4, 1, 'Neil Patrick Harris');";
table_names = ['character', 'character_tv_show', 'character_actor'];
break;
case 'tv_normalized':
sqlstr = "CREATE TABLE character (id int, name char);";
sqlstr += "INSERT INTO character VALUES (1, 'Doogie Howser');";
sqlstr += "INSERT INTO character VALUES (2, 'Barney Stinson');";
sqlstr += "INSERT INTO character VALUES (3, 'Lily Aldrin');";
sqlstr += "INSERT INTO character VALUES (4, 'Willow Rosenberg');";
sqlstr += "CREATE TABLE tv_show (id int, name char);";
sqlstr += "INSERT INTO tv_show VALUES (1, 'Buffy the Vampire Slayer');";
sqlstr += "INSERT INTO tv_show VALUES (2, 'How I Met Your Mother');";
sqlstr += "INSERT INTO tv_show VALUES (3, 'Doogie Howser, M.D.');";
sqlstr += "CREATE TABLE character_tv_show (id int, character_id int, tv_show_id int);";
sqlstr += "INSERT INTO character_tv_show VALUES (1, 1, 3);";
sqlstr += "INSERT INTO character_tv_show VALUES (2, 2, 2);";
sqlstr += "INSERT INTO character_tv_show VALUES (3, 3, 2);";
sqlstr += "INSERT INTO character_tv_show VALUES (4, 4, 1);";
sqlstr += "CREATE TABLE actor (id int, name char);";
sqlstr += "INSERT INTO actor VALUES (1, 'Alyson Hannigan');";
sqlstr += "INSERT INTO actor VALUES (2, 'Neil Patrick Harris');";
sqlstr += "CREATE TABLE character_actor (id int, character_id int, actor_id int);";
sqlstr += "INSERT INTO character_actor VALUES (1, 1, 2);";
sqlstr += "INSERT INTO character_actor VALUES (2, 2, 2);";
sqlstr += "INSERT INTO character_actor VALUES (3, 3, 1);";
sqlstr += "INSERT INTO character_actor VALUES (4, 4, 1);";
table_names = ['character', 'tv_show', 'character_tv_show', 'actor', 'character_actor'];
break;
case 'tv_extra':
sqlstr = "CREATE TABLE character (id int, name char);";
sqlstr += "INSERT INTO character VALUES (1, 'Doogie Howser');";
sqlstr += "INSERT INTO character VALUES (2, 'Barney Stinson');";
sqlstr += "INSERT INTO character VALUES (3, 'Lily Aldrin');";
sqlstr += "INSERT INTO character VALUES (4, 'Willow Rosenberg');";
sqlstr += "INSERT INTO character VALUES (5, 'Steve Urkel');";
sqlstr += "INSERT INTO character VALUES (6, 'Homer Simpson');";
sqlstr += "CREATE TABLE tv_show (id int, name char);";
sqlstr += "INSERT INTO tv_show VALUES (1, 'Buffy the Vampire Slayer');";
sqlstr += "INSERT INTO tv_show VALUES (2, 'How I Met Your Mother');";
sqlstr += "INSERT INTO tv_show VALUES (3, 'Doogie Howser, M.D.');";
sqlstr += "INSERT INTO tv_show VALUES (4, 'Friends');";
sqlstr += "CREATE TABLE character_tv_show (id int, character_id int, tv_show_id int);";
sqlstr += "INSERT INTO character_tv_show VALUES (1, 1, 3);";
sqlstr += "INSERT INTO character_tv_show VALUES (2, 2, 2);";
sqlstr += "INSERT INTO character_tv_show VALUES (3, 3, 2);";
sqlstr += "INSERT INTO character_tv_show VALUES (4, 4, 1);";
sqlstr += "CREATE TABLE actor (id int, name char);";
sqlstr += "INSERT INTO actor VALUES (1, 'Alyson Hannigan');";
sqlstr += "INSERT INTO actor VALUES (2, 'Neil Patrick Harris');";
sqlstr += "INSERT INTO actor VALUES (3, 'Adam Sandler');";
sqlstr += "INSERT INTO actor VALUES (4, 'Steve Carell');";
sqlstr += "CREATE TABLE character_actor (id int, character_id int, actor_id int);";
sqlstr += "INSERT INTO character_actor VALUES (1, 1, 2);";
sqlstr += "INSERT INTO character_actor VALUES (2, 2, 2);";
sqlstr += "INSERT INTO character_actor VALUES (3, 3, 1);";
sqlstr += "INSERT INTO character_actor VALUES (4, 4, 1);";
table_names = ['character', 'tv_show', 'character_tv_show', 'actor', 'character_actor'];
break;
case 'self_join':
sqlstr = "CREATE TABLE rps (id int, name char, defeats_id int);";
sqlstr += "INSERT INTO rps VALUES (1, 'Rock', 3);";
sqlstr += "INSERT INTO rps VALUES (2, 'Paper', 1);";
sqlstr += "INSERT INTO rps VALUES (3, 'Scissors', 2);";
sqlstr += "CREATE TABLE employees (id int, name char, title char, boss_id int);";
sqlstr += "INSERT INTO employees VALUES (1, 'Patrick Smith', 'Software Engineer', 2);";
sqlstr += "INSERT INTO employees VALUES (2, 'Abigail Reed', 'Engineering Manager', 3);";
sqlstr += "INSERT INTO employees VALUES (3, 'Bob Carey', 'Director of Engineering', 4);";
sqlstr += "INSERT INTO employees VALUES (4, 'Maxine Tang', 'CEO', null);";
table_names = ['rps', 'employees'];
break;
case 'robot':
sqlstr = "CREATE TABLE robots (id int, name char);";
sqlstr += "INSERT INTO robots VALUES (1, 'Robot 2000');";
sqlstr += "INSERT INTO robots VALUES (2, 'Champion Robot 2001');";
sqlstr += "INSERT INTO robots VALUES (3, 'Dragon');";
sqlstr += "INSERT INTO robots VALUES (4, 'Turbo Robot 2002');";
sqlstr += "INSERT INTO robots VALUES (5, 'Super Robot 2003');";
sqlstr += "INSERT INTO robots VALUES (6, 'Super Turbo Robot 2004');";
sqlstr += "INSERT INTO robots VALUES (7, 'Not A Robot');";
sqlstr += "INSERT INTO robots VALUES (8, 'Unreleased Turbo Robot 2111');";
table_names = ['robots'];
break;
case 'robot_code':
sqlstr = "CREATE TABLE robots (id int, name char, location char);";
sqlstr += "INSERT INTO robots VALUES (1, 'R2000 - Robot 2000', 'New City, NY');";
sqlstr += "INSERT INTO robots VALUES (2, 'R2001 - Champion Robot 2001', 'Palo Alto, CA');";
sqlstr += "INSERT INTO robots VALUES (3, 'D0001 - Dragon', 'New York City, NY');";
sqlstr += "INSERT INTO robots VALUES (4, 'R2002 - Turbo Robot 2002', 'Spring Valley, NY');";
sqlstr += "INSERT INTO robots VALUES (5, 'R2003 - Super Robot 2003', 'Nyack, NY');";
sqlstr += "INSERT INTO robots VALUES (6, 'R2004 - Super Turbo Robot 2004', 'Tampa, FL');";
sqlstr += "INSERT INTO robots VALUES (7, 'N0001 - Not A Robot', 'Seattle, WA');";
sqlstr += "INSERT INTO robots VALUES (8, 'U2111 - Unreleased Turbo Robot 2111', 'Buffalo, NY');";
table_names = ['robots'];
break;
case 'fighting':
sqlstr = "CREATE TABLE fighters (id int, name char, gun char, sword char, tank char);";
sqlstr += "INSERT INTO fighters VALUES (1, 'US Marine', 'Colt 9mm SMG', 'Swiss Army Knife', 'M1A1 Abrams Tank');";
sqlstr += "INSERT INTO fighters VALUES (2, 'John Wilkes Booth', '.44 caliber Derringer', null, null);";
sqlstr += "INSERT INTO fighters VALUES (3, 'Zorro', null, 'Sword of Zorro', null);";
sqlstr += "INSERT INTO fighters VALUES (4, 'Innocent Bystander', null, null, null);";
table_names = ['fighters'];
break;
}
database.run(sqlstr);
var current_table_string = '';
for (var index in table_names) {
results = database.exec("SELECT * FROM " + table_names[index] + ";");
current_table_string += '<div class="table-name">' + table_names[index] + '</div>' + table_from_results(results);
}
$('#current-tables').html(current_table_string);
return database;
};
var current_level;
var current_level_name;
var render_menu = function() {
// Add links to menu
var menu_html = '';
for (var index in levels) {
if (index == (current_level - 1)) {
menu_html += '<strong>';
}
menu_html += '<div class="menu-item">';
if (localStorage.getItem('completed-' + levels[index]['short_name'])) {
menu_html += '<span class="glyphicon glyphicon-ok"></span>';
}
menu_html += '<a href="#!' + levels[index]['short_name'] + '">' + levels[index]['name'] + '</a>';
menu_html += '</div>';
if (index == (current_level - 1)) {
menu_html += '</strong>';
}
}
$('.menu').html(menu_html);
}
var load_level = function() {
var hash_code = window.location.hash.substr(2);
if (hash_code == 'menu') {
render_menu();
$('.menu').removeClass('menu-hidden-for-mobile');
$('.not-menu-container').hide();
return;
}
$('.menu').addClass('menu-hidden-for-mobile');
$('.not-menu-container').show();
// The current level is 1 by default, unless the hash code matches the short name for a level.
current_level = 1;
for (var index in levels) {
if (hash_code == levels[index]['short_name']) {
current_level = parseInt(index, 10) + 1;
break;
}
}
var database = load_database(levels[current_level-1]['database_type']);
// Set text for current level
lesson_name = levels[current_level-1]['name'];
$('#lesson-name').text("Lesson " + current_level + ": " + lesson_name);
$('#prompt').html(levels[current_level-1]['prompt']);
// Add "next" and "previous" links if it makes sense.
if (current_level > 1) {
$('#previous-link').attr('href', '#!' + levels[current_level-2]['short_name']);
$('#previous-link').show();
} else {
$('#previous-link').hide();
}
if (current_level < levels.length) {
$('#next-link').attr('href', '#!' + levels[current_level]['short_name']);
$('#next-link').show();
} else {
$('#next-link').hide();
}
// Add links to menu
render_menu();
// Clear out old data
$('#answer-correct').hide();
$('#answer-wrong').hide();
$('#sql-input').val('');
$('#results').html('');
$('.expected-results-container').hide();
return database;
};
db = load_level();
// When the URL after the # changes, we load a new level,
// and let Google Analytics know that the page has changed.
$(window).bind('hashchange', function() {
db = load_level();
ga('send', 'pageview', {'page': location.pathname + location.search + location.hash});
});
| fix bug
| sqlteaching.js | fix bug | <ide><path>qlteaching.js
<ide> 'database_type': 'family_and_legs',
<ide> 'required': ['(', ')'],
<ide> 'custom_error_message': 'You must use a nested query in your answer.',
<del> 'answer': {'columns': ['id', 'name', 'gender', 'species', 'num_books_read', 'num_legs'],
<del> 'values': [[1, 'Dave', 'male', 'human', 200, 2]]},
<add> 'answer': {'columns': ['id', 'name', 'species', 'num_books_read', 'num_legs'],
<add> 'values': [[1, 'Dave', 'human', 200, 2]]},
<ide> 'prompt': 'In SQL, you can put a SQL query inside another SQL query. <br/><br/>For example, to find the family members with the least number of legs, <br/> you can run: <br/><code>SELECT * FROM family_members WHERE num_legs = (SELECT MIN(num_legs) FROM family_members);</code> <br/><br/> The <code>SELECT</code> query inside the parentheses is executed first, and returns the minimum number of legs. Then, that value (2) is used in the outside query, to find all family members that have 2 legs. <br/><br/> Can you return the family members that have the highest num_books_read?'},
<ide>
<ide> {'name': 'NULL',
<ide> 'short_name': 'null',
<ide> 'database_type': 'family_null',
<del> 'answer': {'columns': ['id', 'name', 'gender', 'species', 'num_books_read', 'favorite_book'],
<del> 'values': [[1, 'Dave', 'male', 'human', 200, 'To Kill a Mockingbird'],
<del> [2, 'Mary', 'female', 'human', 180, 'Gone with the Wind']]},
<add> 'answer': {'columns': ['id', 'name', 'gender', 'species', 'favorite_book'],
<add> 'values': [[1, 'Dave', 'male', 'human', 'To Kill a Mockingbird'],
<add> [2, 'Mary', 'female', 'human', 'Gone with the Wind']]},
<ide> 'prompt': 'Sometimes, in a given row, there is no value at all for a given column. For example, a dog does not have a favorite book, so in that case there is no point in putting a value in the <em>favorite_book</em> column, and the value is <code>NULL</code>. In order to find the rows where the value for a column is or is not <code>NULL</code>, you would use <code>IS NULL</code> or <code>IS NOT NULL</code>.<br/><br/>Can you return all of the rows of <strong>family_members</strong> where <em>favorite_book</em> is not null?'},
<ide>
<ide> {'name': 'Date',
<ide> table_names = ['family_members'];
<ide> break;
<ide> case 'family_null':
<del> sqlstr = "CREATE TABLE family_members (id int, name char, gender char, species char, num_books_read int, favorite_book char);";
<del> sqlstr += "INSERT INTO family_members VALUES (1, 'Dave', 'male', 'human', 200, 'To Kill a Mockingbird');";
<del> sqlstr += "INSERT INTO family_members VALUES (2, 'Mary', 'female', 'human', 180, 'Gone with the Wind');";
<del> sqlstr += "INSERT INTO family_members VALUES (3, 'Pickles', 'male', 'dog', 0, NULL);";
<add> sqlstr = "CREATE TABLE family_members (id int, name char, gender char, species char, favorite_book char);";
<add> sqlstr += "INSERT INTO family_members VALUES (1, 'Dave', 'male', 'human', 'To Kill a Mockingbird');";
<add> sqlstr += "INSERT INTO family_members VALUES (2, 'Mary', 'female', 'human', 'Gone with the Wind');";
<add> sqlstr += "INSERT INTO family_members VALUES (3, 'Pickles', 'male', 'dog', NULL);";
<ide> table_names = ['family_members'];
<ide> break;
<ide> case 'celebs_born': |
|
Java | apache-2.0 | 6fc6e1fbe2bf821160aab518af1db0cd83480032 | 0 | cisco-system-traffic-generator/trex-stateless-gui,cisco-system-traffic-generator/trex-stateless-gui | /**
* *****************************************************************************
* Copyright (c) 2016
*
* 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.exalttech.trex.ui.controllers;
import com.exalttech.trex.ui.models.datastore.Connection;
import com.exalttech.trex.ui.util.TrexAlertBuilder;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import com.google.common.base.Strings;
import com.google.common.eventbus.EventBus;
import com.google.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xored.javafx.packeteditor.controllers.FieldEditorController;
import com.xored.javafx.packeteditor.events.ScapyClientNeedConnectEvent;
import com.exalttech.trex.core.ConnectionManager;
import com.exalttech.trex.remote.models.profiles.Packet;
import com.exalttech.trex.remote.models.profiles.Profile;
import com.exalttech.trex.remote.models.profiles.Stream;
import com.exalttech.trex.ui.StreamBuilderType;
import com.exalttech.trex.ui.dialog.DialogView;
import com.exalttech.trex.ui.models.PacketInfo;
import com.exalttech.trex.ui.views.streams.binders.BuilderDataBinding;
import com.exalttech.trex.ui.views.streams.builder.PacketBuilderHelper;
import com.exalttech.trex.ui.views.streams.viewer.PacketHex;
import com.exalttech.trex.ui.views.streams.viewer.PacketParser;
import com.exalttech.trex.util.TrafficProfile;
import com.exalttech.trex.util.Util;
public class PacketBuilderHomeController extends DialogView implements Initializable {
private static final Logger LOG = Logger.getLogger(PacketBuilderHomeController.class.getName());
private enum SelectedEditMode {
Cancel,
Advanced,
Simple
}
@FXML
private AnchorPane hexPane;
@FXML
private Button nextStreamBtn;
@FXML
private Button streamEditorModeBtn;
@FXML
private Button prevStreamBtn;
@FXML
private Button saveButton;
@FXML
private StreamPropertiesViewController streamPropertiesController;
@FXML
private PacketViewerController packetViewerController;
@FXML
private ProtocolSelectionController protocolSelectionController;
@FXML
private ProtocolDataController protocolDataController;
@FXML
private Tab packetViewerTab;
@FXML
private Tab packetEditorTab;
@FXML
private Tab fieldEngineTab;
@FXML
private Tab packetViewerWithTreeTab;
@FXML
private Tab protocolSelectionTab;
@FXML
private Tab protocolDataTab;
@FXML
private Tab advanceSettingsTab;
@FXML
private AdvancedSettingsController advancedSettingsController;
@FXML
private Tab streamPropertiesTab;
@FXML
private TabPane streamTabPane;
@Inject
private FieldEditorController packetBuilderController;
@Inject
private EventBus eventBus;
private PacketInfo packetInfo = null;
private PacketParser parser;
private PacketHex packetHex;
private Profile selectedProfile;
private boolean isBuildPacket = false;
private List<Profile> profileList;
private String yamlFileName;
private int currentSelectedProfileIndex;
private BuilderDataBinding builderDataBinder;
private TrafficProfile trafficProfile;
private BooleanProperty isImportedStreamProperty = new SimpleBooleanProperty(false);
@Override
public void initialize(URL url, ResourceBundle rb) {
trafficProfile = new TrafficProfile();
packetHex = new PacketHex(hexPane);
nextStreamBtn.setGraphic(new ImageView(new Image("/icons/next_stream.png")));
prevStreamBtn.setGraphic(new ImageView(new Image("/icons/prev_stream.png")));
packetInfo = new PacketInfo();
parser = new PacketParser();
}
public boolean initStreamBuilder(String pcapFileBinary, List<Profile> profileList, int selectedProfileIndex, String yamlFileName, StreamBuilderType type) throws Exception {
selectedProfile = profileList.get(selectedProfileIndex);
this.profileList = profileList;
this.yamlFileName = yamlFileName;
currentSelectedProfileIndex = selectedProfileIndex;
if (selectedProfile.getStream().getAdvancedMode() && !ConnectionManager.getInstance().isScapyConnected()) {
SelectedEditMode action = prepareToAdvancedMode();
if (action == SelectedEditMode.Cancel) {
return false;
} else {
selectedProfile.getStream().setAdvancedMode(action == SelectedEditMode.Advanced);
}
}
packetBuilderController.reset();
streamPropertiesController.init(profileList, selectedProfileIndex);
updateNextPrevButtonState();
switch (type) {
case BUILD_STREAM:
initStreamBuilder(new BuilderDataBinding());
break;
case EDIT_STREAM:
initEditStream(pcapFileBinary);
break;
default:
break;
}
if (selectedProfile.getStream().getAdvancedMode()) {
showAdvancedModeTabs();
} else {
showSimpleModeTabs();
}
return true;
}
private SelectedEditMode prepareToAdvancedMode() {
String warningText = "There is no connection to Scapy server\n" +
"Please, refer to documentation about\n" +
"Scapy server and advanced mode.";
ButtonType tryConnect = new ButtonType("Connect", ButtonBar.ButtonData.YES);
ButtonType continueSimple = new ButtonType("Simple Mode");
while (true) {
Optional<ButtonType> userSelection = TrexAlertBuilder.build()
.setType(Alert.AlertType.WARNING)
.setHeader("Scapy server connection required")
.setContent(warningText)
.setButtons(tryConnect, continueSimple, ButtonType.CANCEL)
.getAlert()
.showAndWait();
if (!userSelection.isPresent() || userSelection.get().equals(ButtonType.CANCEL)) {
return SelectedEditMode.Cancel;
} else if (userSelection.get().equals(continueSimple)) {
return SelectedEditMode.Simple;
}
eventBus.post(new ScapyClientNeedConnectEvent());
if (ConnectionManager.getInstance().isScapyConnected()) {
return SelectedEditMode.Advanced;
}
TrexAlertBuilder.build()
.setType(Alert.AlertType.ERROR)
.setContent("Connection to Scapy server failed.")
.getAlert()
.showAndWait();
}
}
private void initEditStream(String pcapFileBinary) throws IOException {
streamTabPane.setDisable(false);
saveButton.setDisable(false);
streamEditorModeBtn.setDisable(false);
Stream currentStream = selectedProfile.getStream();
streamEditorModeBtn.setText(currentStream.getAdvancedMode() ? "Simple mode" : "Advanced mode");
if (!Util.isNullOrEmpty(currentStream.getPacket().getMeta())) {
BuilderDataBinding dataBinding = getDataBinding();
if (dataBinding != null) {
initStreamBuilder(dataBinding);
return;
} else {
streamTabPane.setDisable(true);
saveButton.setDisable(true);
streamEditorModeBtn.setDisable(true);
}
} else {
isImportedStreamProperty.set(true);
}
if (isImportedStreamProperty.get()) {
streamTabPane.getTabs().remove(protocolDataTab);
streamTabPane.getTabs().remove(protocolSelectionTab);
streamTabPane.getTabs().remove(advanceSettingsTab);
streamTabPane.getTabs().remove(packetViewerWithTreeTab);
streamTabPane.getTabs().remove(packetEditorTab);
streamTabPane.getTabs().remove(fieldEngineTab);
}
if (pcapFileBinary != null) {
try {
isBuildPacket = false;
File pcapFile = trafficProfile.decodePcapBinary(pcapFileBinary);
parser.parseFile(pcapFile.getAbsolutePath(), packetInfo);
packetHex.setData(packetInfo);
} catch (IOException ex) {
LOG.error("Failed to load PCAP value", ex);
}
}
String base64UserModel = currentStream.getPacket().getModel();
if (!Strings.isNullOrEmpty(base64UserModel)) {
packetBuilderController.loadUserModel(base64UserModel);
} else {
byte[] base64Packet = currentStream.getPacket().getBinary().getBytes();
byte[] packet = Base64.getDecoder().decode(base64Packet);
packetBuilderController.loadPcapBinary(packet);
}
}
private BuilderDataBinding getDataBinding() {
String meta = selectedProfile.getStream().getPacket().getMeta();
boolean emptyMeta = meta == null;
isImportedStreamProperty.setValue(emptyMeta);
if (emptyMeta) {
return null;
}
final String metaJSON = new String(Base64.getDecoder().decode(meta));
if (metaJSON.charAt(0) != '{') {
TrexAlertBuilder.build()
.setType(Alert.AlertType.ERROR)
.setTitle("Warning")
.setHeader("Stream initialization failed")
.setContent("This stream couldn't be edited due to outdated data format.")
.getAlert()
.showAndWait();
return null;
}
try {
return new ObjectMapper().readValue(metaJSON, BuilderDataBinding.class);
} catch (Exception exc) {
LOG.error("Can't read packet meta", exc);
TrexAlertBuilder.build()
.setType(Alert.AlertType.ERROR)
.setTitle("Warning")
.setHeader("Stream initialization failed")
.setContent(exc.getMessage())
.getAlert()
.showAndWait();
return null;
}
}
private void initStreamBuilder(BuilderDataBinding builderDataBinder) {
isImportedStreamProperty.setValue(false);
isBuildPacket = true;
String packetEditorModel = selectedProfile.getStream().getPacket().getModel();
if (!Strings.isNullOrEmpty(packetEditorModel)) {
packetBuilderController.loadUserModel(packetEditorModel);
}
this.builderDataBinder = builderDataBinder;
// initialize builder tabs
protocolSelectionController.bindSelections(builderDataBinder.getProtocolSelection());
protocolDataController.bindSelection(builderDataBinder);
advancedSettingsController.bindSelections(builderDataBinder.getAdvancedPropertiesDB());
packetViewerWithTreeTab.selectedProperty().addListener((ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {
if (newValue) {
try {
// handle it and send the result to packet viewer controller
packetViewerController.setPacketView(protocolDataController.getProtocolData());
} catch (Exception ex) {
LOG.error("Error creating packet", ex);
}
}
});
}
private void showSimpleModeTabs() {
streamTabPane.getTabs().clear();
if (isImportedStreamProperty.get()) {
streamTabPane.getTabs().addAll(
streamPropertiesTab,
packetViewerTab
);
} else {
streamTabPane.getTabs().addAll(
streamPropertiesTab,
protocolSelectionTab,
protocolDataTab,
advanceSettingsTab,
packetViewerWithTreeTab
);
}
}
private void showAdvancedModeTabs() {
streamTabPane.getTabs().clear();
streamTabPane.getTabs().addAll(streamPropertiesTab, packetEditorTab, fieldEngineTab);
}
@FXML
public void handleCloseDialog(final MouseEvent event) {
Node node = (Node) event.getSource();
Stage stage = (Stage) node.getScene().getWindow();
stage.hide();
}
@FXML
public void saveProfileBtnClicked(ActionEvent event) {
if (saveStream()) {
// close the dialog
Node node = (Node) event.getSource();
Stage stage = (Stage) node.getScene().getWindow();
stage.hide();
}
}
private boolean saveStream() {
try {
String fieldEngineError = packetBuilderController.getFieldEngineError();
if (!Strings.isNullOrEmpty(fieldEngineError)) {
streamTabPane.getSelectionModel().select(fieldEngineTab);
LOG.error("Unable to save stream due to errors in Field Engine:" + fieldEngineError);
return false;
}
updateCurrentProfile();
if (streamPropertiesController.isValidStreamPropertiesFields()) {
String yamlData = trafficProfile.convertTrafficProfileToYaml(profileList.toArray(new Profile[profileList.size()]));
FileUtils.writeStringToFile(new File(yamlFileName), yamlData);
Util.optimizeMemory();
return true;
}
} catch (Exception ex) {
LOG.error("Error Saving yaml file", ex);
}
return false;
}
@FXML
public void nextStreamBtnClicked(ActionEvent event) {
nextStreamBtn.setDisable(true);
loadProfile(true);
}
@FXML
public void switchEditorMode(ActionEvent event) throws Exception {
Stream currentStream = streamPropertiesController.getUpdatedSelectedProfile().getStream();
boolean advancedMode = currentStream.getAdvancedMode();
try {
if (advancedMode) {
streamEditorModeBtn.setText("Advanced mode");
currentStream.setAdvancedMode(false);
showSimpleModeTabs();
} else {
if (!ConnectionManager.getInstance().isScapyConnected()) {
SelectedEditMode userSelection = prepareToAdvancedMode();
if (userSelection == SelectedEditMode.Cancel || userSelection == SelectedEditMode.Simple) {
return;
}
}
if (isImportedStreamProperty.getValue()) {
byte[] base64Packet = currentStream.getPacket().getBinary().getBytes();
byte[] packet = Base64.getDecoder().decode(base64Packet);
packetBuilderController.loadPcapBinary(packet);
} else {
packetBuilderController.loadSimpleUserModel(builderDataBinder.serializeAsPacketModel());
}
streamEditorModeBtn.setText("Simple mode");
currentStream.setAdvancedMode(true);
showAdvancedModeTabs();
}
} catch (Exception e) {
LOG.error("Unable to open advanced mode due to: " + e.getMessage());
alertWarning("Can't open Advanced mode", "Some errors occurred. See logs for more details.");
}
}
@FXML
public void prevStreamBtnClick(ActionEvent event) {
prevStreamBtn.setDisable(true);
loadProfile(false);
}
private void loadProfile(boolean isNext) {
try {
Util.optimizeMemory();
updateCurrentProfile();
if (streamPropertiesController.isValidStreamPropertiesFields()) {
if (isNext) {
this.currentSelectedProfileIndex += 1;
} else {
this.currentSelectedProfileIndex -= 1;
}
loadStream();
}
} catch (Exception ex) {
LOG.error("Invalid data", ex);
}
updateNextPrevButtonState();
}
private void resetTabs() {
streamTabPane.getTabs().clear();
streamTabPane.getTabs().add(streamPropertiesTab);
streamTabPane.getTabs().add(packetViewerTab);
streamTabPane.getTabs().add(protocolSelectionTab);
streamTabPane.getTabs().add(protocolDataTab);
streamTabPane.getTabs().add(advanceSettingsTab);
streamTabPane.getTabs().add(packetViewerWithTreeTab);
streamTabPane.getTabs().add(packetEditorTab);
streamTabPane.getTabs().add(fieldEngineTab);
}
private void updateNextPrevButtonState() {
nextStreamBtn.setDisable((currentSelectedProfileIndex >= profileList.size() - 1));
prevStreamBtn.setDisable((currentSelectedProfileIndex == 0));
}
private void loadStream() throws IOException {
resetTabs();
streamTabPane.getSelectionModel().select(streamPropertiesTab);
selectedProfile = profileList.get(currentSelectedProfileIndex);
Stream currentStream = selectedProfile.getStream();
String windowTitle = "Edit Stream (" + selectedProfile.getName() + ")";
// update window title
Stage stage = (Stage) streamTabPane.getScene().getWindow();
stage.setTitle(windowTitle);
streamPropertiesController.init(profileList, currentSelectedProfileIndex);
initEditStream(currentStream.getPacket().getBinary());
if (currentStream.getAdvancedMode()) {
showAdvancedModeTabs();
} else {
showSimpleModeTabs();
}
}
private void updateCurrentProfile() throws Exception {
selectedProfile = streamPropertiesController.getUpdatedSelectedProfile();
String hexPacket = null;
if (packetHex != null && !isBuildPacket) {
hexPacket = packetHex.getPacketHexFromList();
} else if (isBuildPacket) {
hexPacket = PacketBuilderHelper.getPacketHex(protocolDataController.getProtocolData().getPacket().getRawData());
selectedProfile.getStream().setAdditionalProperties(protocolDataController.getVm(advancedSettingsController.getCacheSize()));
selectedProfile.getStream().setFlags(protocolDataController.getFlagsValue());
// save stream selected in stream property
final String metaJSON = new ObjectMapper().writeValueAsString(builderDataBinder);
final String encodedMeta = Base64.getEncoder().encodeToString(metaJSON.getBytes());
selectedProfile.getStream().getPacket().setMeta(encodedMeta);
}
String encodedBinaryPacket = trafficProfile.encodeBinaryFromHexString(hexPacket);
Packet packet = selectedProfile.getStream().getPacket();
if (selectedProfile.getStream().getAdvancedMode()) {
packet.setBinary(packetBuilderController.getModel().getPkt().binary);
packet.setModel(packetBuilderController.getModel().serialize());
selectedProfile.getStream().setAdditionalProperties(packetBuilderController.getPktVmInstructions());
} else {
packet.setBinary(encodedBinaryPacket);
packet.setModel("");
}
}
@Override
public void onEnterKeyPressed(Stage stage) {
// ignore event
}
@Override
public void onEscapKeyPressed() {
// ignoring global escape
}
private boolean alertWarning(String header, String content) {
ButtonType buttonTypeTry = new ButtonType("Try", ButtonBar.ButtonData.YES);
ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
Alert alert = TrexAlertBuilder.build()
.setType(Alert.AlertType.WARNING)
.setTitle("Warning")
.setHeader(header)
.setContent(content + "\nWould you like to change ip or port and try connection again ?")
.setButtons(buttonTypeTry, buttonTypeCancel)
.getAlert();
alert.showAndWait();
ButtonType res = alert.getResult();
return res.getButtonData() != ButtonBar.ButtonData.CANCEL_CLOSE;
}
}
| src/main/java/com/exalttech/trex/ui/controllers/PacketBuilderHomeController.java | /**
* *****************************************************************************
* Copyright (c) 2016
*
* 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.exalttech.trex.ui.controllers;
import com.exalttech.trex.ui.models.datastore.Connection;
import com.exalttech.trex.ui.util.TrexAlertBuilder;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import com.google.common.base.Strings;
import com.google.common.eventbus.EventBus;
import com.google.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Base64;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xored.javafx.packeteditor.controllers.FieldEditorController;
import com.xored.javafx.packeteditor.events.ScapyClientNeedConnectEvent;
import com.exalttech.trex.core.ConnectionManager;
import com.exalttech.trex.remote.models.profiles.Packet;
import com.exalttech.trex.remote.models.profiles.Profile;
import com.exalttech.trex.remote.models.profiles.Stream;
import com.exalttech.trex.ui.StreamBuilderType;
import com.exalttech.trex.ui.dialog.DialogView;
import com.exalttech.trex.ui.models.PacketInfo;
import com.exalttech.trex.ui.views.streams.binders.BuilderDataBinding;
import com.exalttech.trex.ui.views.streams.builder.PacketBuilderHelper;
import com.exalttech.trex.ui.views.streams.viewer.PacketHex;
import com.exalttech.trex.ui.views.streams.viewer.PacketParser;
import com.exalttech.trex.util.TrafficProfile;
import com.exalttech.trex.util.Util;
public class PacketBuilderHomeController extends DialogView implements Initializable {
private static final Logger LOG = Logger.getLogger(PacketBuilderHomeController.class.getName());
private enum SelectedEditMode {
Cancel,
Advanced,
Simple
}
@FXML
private AnchorPane hexPane;
@FXML
private Button nextStreamBtn;
@FXML
private Button streamEditorModeBtn;
@FXML
private Button prevStreamBtn;
@FXML
private Button saveButton;
@FXML
private StreamPropertiesViewController streamPropertiesController;
@FXML
private PacketViewerController packetViewerController;
@FXML
private ProtocolSelectionController protocolSelectionController;
@FXML
private ProtocolDataController protocolDataController;
@FXML
private Tab packetViewerTab;
@FXML
private Tab packetEditorTab;
@FXML
private Tab fieldEngineTab;
@FXML
private Tab packetViewerWithTreeTab;
@FXML
private Tab protocolSelectionTab;
@FXML
private Tab protocolDataTab;
@FXML
private Tab advanceSettingsTab;
@FXML
private AdvancedSettingsController advancedSettingsController;
@FXML
private Tab streamPropertiesTab;
@FXML
private TabPane streamTabPane;
@Inject
private FieldEditorController packetBuilderController;
@Inject
private EventBus eventBus;
private PacketInfo packetInfo = null;
private PacketParser parser;
private PacketHex packetHex;
private Profile selectedProfile;
private boolean isBuildPacket = false;
private List<Profile> profileList;
private String yamlFileName;
private int currentSelectedProfileIndex;
private BuilderDataBinding builderDataBinder;
private TrafficProfile trafficProfile;
private BooleanProperty isImportedStreamProperty = new SimpleBooleanProperty(false);
@Override
public void initialize(URL url, ResourceBundle rb) {
trafficProfile = new TrafficProfile();
packetHex = new PacketHex(hexPane);
nextStreamBtn.setGraphic(new ImageView(new Image("/icons/next_stream.png")));
prevStreamBtn.setGraphic(new ImageView(new Image("/icons/prev_stream.png")));
packetInfo = new PacketInfo();
parser = new PacketParser();
}
public boolean initStreamBuilder(String pcapFileBinary, List<Profile> profileList, int selectedProfileIndex, String yamlFileName, StreamBuilderType type) throws Exception {
selectedProfile = profileList.get(selectedProfileIndex);
this.profileList = profileList;
this.yamlFileName = yamlFileName;
currentSelectedProfileIndex = selectedProfileIndex;
if (selectedProfile.getStream().getAdvancedMode() && !ConnectionManager.getInstance().isScapyConnected()) {
SelectedEditMode action = prepareToAdvancedMode();
if (action == SelectedEditMode.Cancel) {
return false;
} else {
selectedProfile.getStream().setAdvancedMode(action == SelectedEditMode.Advanced);
}
}
packetBuilderController.reset();
streamPropertiesController.init(profileList, selectedProfileIndex);
updateNextPrevButtonState();
switch (type) {
case BUILD_STREAM:
initStreamBuilder(new BuilderDataBinding());
break;
case EDIT_STREAM:
initEditStream(pcapFileBinary);
break;
default:
break;
}
if (selectedProfile.getStream().getAdvancedMode()) {
if (isImportedStreamProperty.getValue()) {
Stream currentStream = streamPropertiesController.getUpdatedSelectedProfile().getStream();
byte[] base64Packet = currentStream.getPacket().getBinary().getBytes();
byte[] packet = Base64.getDecoder().decode(base64Packet);
packetBuilderController.loadPcapBinary(packet);
packetBuilderController.loadVmInstructions(currentStream.getAdditionalProperties().get("vm"));
} else {
packetBuilderController.loadSimpleUserModel(builderDataBinder.serializeAsPacketModel());
}
showAdvancedModeTabs();
} else {
showSimpleModeTabs();
}
return true;
}
private SelectedEditMode prepareToAdvancedMode() {
String warningText = "There is no connection to Scapy server\n" +
"Please, refer to documentation about\n" +
"Scapy server and advanced mode.";
ButtonType tryConnect = new ButtonType("Connect", ButtonBar.ButtonData.YES);
ButtonType continueSimple = new ButtonType("Simple Mode");
while (true) {
Optional<ButtonType> userSelection = TrexAlertBuilder.build()
.setType(Alert.AlertType.WARNING)
.setHeader("Scapy server connection required")
.setContent(warningText)
.setButtons(tryConnect, continueSimple, ButtonType.CANCEL)
.getAlert()
.showAndWait();
if (!userSelection.isPresent() || userSelection.get().equals(ButtonType.CANCEL)) {
return SelectedEditMode.Cancel;
} else if (userSelection.get().equals(continueSimple)) {
return SelectedEditMode.Simple;
}
eventBus.post(new ScapyClientNeedConnectEvent());
if (ConnectionManager.getInstance().isScapyConnected()) {
return SelectedEditMode.Advanced;
}
TrexAlertBuilder.build()
.setType(Alert.AlertType.ERROR)
.setContent("Connection to Scapy server failed.")
.getAlert()
.showAndWait();
}
}
private void initEditStream(String pcapFileBinary) {
streamTabPane.setDisable(false);
saveButton.setDisable(false);
streamEditorModeBtn.setDisable(false);
Stream currentStream = selectedProfile.getStream();
streamEditorModeBtn.setText(currentStream.getAdvancedMode() ? "Simple mode" : "Advanced mode");
if (!Util.isNullOrEmpty(currentStream.getPacket().getMeta())) {
BuilderDataBinding dataBinding = getDataBinding();
if (dataBinding != null) {
initStreamBuilder(dataBinding);
return;
} else {
streamTabPane.setDisable(true);
saveButton.setDisable(true);
streamEditorModeBtn.setDisable(true);
}
} else {
isImportedStreamProperty.set(true);
}
if (isImportedStreamProperty.get()) {
streamTabPane.getTabs().remove(protocolDataTab);
streamTabPane.getTabs().remove(protocolSelectionTab);
streamTabPane.getTabs().remove(advanceSettingsTab);
streamTabPane.getTabs().remove(packetViewerWithTreeTab);
streamTabPane.getTabs().remove(packetEditorTab);
streamTabPane.getTabs().remove(fieldEngineTab);
}
if (pcapFileBinary != null) {
try {
isBuildPacket = false;
File pcapFile = trafficProfile.decodePcapBinary(pcapFileBinary);
parser.parseFile(pcapFile.getAbsolutePath(), packetInfo);
packetHex.setData(packetInfo);
} catch (IOException ex) {
LOG.error("Failed to load PCAP value", ex);
}
}
String base64UserModel = currentStream.getPacket().getModel();
if (!Strings.isNullOrEmpty(base64UserModel)) {
packetBuilderController.loadUserModel(base64UserModel);
}
}
private BuilderDataBinding getDataBinding() {
String meta = selectedProfile.getStream().getPacket().getMeta();
boolean emptyMeta = meta == null;
isImportedStreamProperty.setValue(emptyMeta);
if (emptyMeta) {
return null;
}
final String metaJSON = new String(Base64.getDecoder().decode(meta));
if (metaJSON.charAt(0) != '{') {
TrexAlertBuilder.build()
.setType(Alert.AlertType.ERROR)
.setTitle("Warning")
.setHeader("Stream initialization failed")
.setContent("This stream couldn't be edited due to outdated data format.")
.getAlert()
.showAndWait();
return null;
}
try {
return new ObjectMapper().readValue(metaJSON, BuilderDataBinding.class);
} catch (Exception exc) {
LOG.error("Can't read packet meta", exc);
TrexAlertBuilder.build()
.setType(Alert.AlertType.ERROR)
.setTitle("Warning")
.setHeader("Stream initialization failed")
.setContent(exc.getMessage())
.getAlert()
.showAndWait();
return null;
}
}
private void initStreamBuilder(BuilderDataBinding builderDataBinder) {
isImportedStreamProperty.setValue(false);
isBuildPacket = true;
String packetEditorModel = selectedProfile.getStream().getPacket().getModel();
if (!Strings.isNullOrEmpty(packetEditorModel)) {
packetBuilderController.loadUserModel(packetEditorModel);
}
this.builderDataBinder = builderDataBinder;
// initialize builder tabs
protocolSelectionController.bindSelections(builderDataBinder.getProtocolSelection());
protocolDataController.bindSelection(builderDataBinder);
advancedSettingsController.bindSelections(builderDataBinder.getAdvancedPropertiesDB());
packetViewerWithTreeTab.selectedProperty().addListener((ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {
if (newValue) {
try {
// handle it and send the result to packet viewer controller
packetViewerController.setPacketView(protocolDataController.getProtocolData());
} catch (Exception ex) {
LOG.error("Error creating packet", ex);
}
}
});
}
private void showSimpleModeTabs() {
streamTabPane.getTabs().clear();
if (isImportedStreamProperty.get()) {
streamTabPane.getTabs().addAll(
streamPropertiesTab,
packetViewerTab
);
} else {
streamTabPane.getTabs().addAll(
streamPropertiesTab,
protocolSelectionTab,
protocolDataTab,
advanceSettingsTab,
packetViewerWithTreeTab
);
}
}
private void showAdvancedModeTabs() {
streamTabPane.getTabs().clear();
streamTabPane.getTabs().addAll(streamPropertiesTab, packetEditorTab, fieldEngineTab);
}
@FXML
public void handleCloseDialog(final MouseEvent event) {
Node node = (Node) event.getSource();
Stage stage = (Stage) node.getScene().getWindow();
stage.hide();
}
@FXML
public void saveProfileBtnClicked(ActionEvent event) {
if (saveStream()) {
// close the dialog
Node node = (Node) event.getSource();
Stage stage = (Stage) node.getScene().getWindow();
stage.hide();
}
}
private boolean saveStream() {
try {
String fieldEngineError = packetBuilderController.getFieldEngineError();
if (!Strings.isNullOrEmpty(fieldEngineError)) {
streamTabPane.getSelectionModel().select(fieldEngineTab);
LOG.error("Unable to save stream due to errors in Field Engine:" + fieldEngineError);
return false;
}
updateCurrentProfile();
if (streamPropertiesController.isValidStreamPropertiesFields()) {
String yamlData = trafficProfile.convertTrafficProfileToYaml(profileList.toArray(new Profile[profileList.size()]));
FileUtils.writeStringToFile(new File(yamlFileName), yamlData);
Util.optimizeMemory();
return true;
}
} catch (Exception ex) {
LOG.error("Error Saving yaml file", ex);
}
return false;
}
@FXML
public void nextStreamBtnClicked(ActionEvent event) {
nextStreamBtn.setDisable(true);
loadProfile(true);
}
@FXML
public void switchEditorMode(ActionEvent event) throws Exception {
Stream currentStream = streamPropertiesController.getUpdatedSelectedProfile().getStream();
boolean advancedMode = currentStream.getAdvancedMode();
try {
if (advancedMode) {
streamEditorModeBtn.setText("Advanced mode");
currentStream.setAdvancedMode(false);
showSimpleModeTabs();
} else {
if (!ConnectionManager.getInstance().isScapyConnected()) {
SelectedEditMode userSelection = prepareToAdvancedMode();
if (userSelection == SelectedEditMode.Cancel || userSelection == SelectedEditMode.Simple) {
return;
}
}
if (isImportedStreamProperty.getValue()) {
byte[] base64Packet = currentStream.getPacket().getBinary().getBytes();
byte[] packet = Base64.getDecoder().decode(base64Packet);
packetBuilderController.loadPcapBinary(packet);
} else {
packetBuilderController.loadSimpleUserModel(builderDataBinder.serializeAsPacketModel());
}
streamEditorModeBtn.setText("Simple mode");
currentStream.setAdvancedMode(true);
showAdvancedModeTabs();
}
} catch (Exception e) {
LOG.error("Unable to open advanced mode due to: " + e.getMessage());
alertWarning("Can't open Advanced mode", "Some errors occurred. See logs for more details.");
}
}
@FXML
public void prevStreamBtnClick(ActionEvent event) {
prevStreamBtn.setDisable(true);
loadProfile(false);
}
private void loadProfile(boolean isNext) {
try {
Util.optimizeMemory();
updateCurrentProfile();
if (streamPropertiesController.isValidStreamPropertiesFields()) {
if (isNext) {
this.currentSelectedProfileIndex += 1;
} else {
this.currentSelectedProfileIndex -= 1;
}
loadStream();
}
} catch (Exception ex) {
LOG.error("Invalid data", ex);
}
updateNextPrevButtonState();
}
private void resetTabs() {
streamTabPane.getTabs().clear();
streamTabPane.getTabs().add(streamPropertiesTab);
streamTabPane.getTabs().add(packetViewerTab);
streamTabPane.getTabs().add(protocolSelectionTab);
streamTabPane.getTabs().add(protocolDataTab);
streamTabPane.getTabs().add(advanceSettingsTab);
streamTabPane.getTabs().add(packetViewerWithTreeTab);
streamTabPane.getTabs().add(packetEditorTab);
streamTabPane.getTabs().add(fieldEngineTab);
}
private void updateNextPrevButtonState() {
nextStreamBtn.setDisable((currentSelectedProfileIndex >= profileList.size() - 1));
prevStreamBtn.setDisable((currentSelectedProfileIndex == 0));
}
private void loadStream() {
resetTabs();
streamTabPane.getSelectionModel().select(streamPropertiesTab);
selectedProfile = profileList.get(currentSelectedProfileIndex);
Stream currentStream = selectedProfile.getStream();
String windowTitle = "Edit Stream (" + selectedProfile.getName() + ")";
// update window title
Stage stage = (Stage) streamTabPane.getScene().getWindow();
stage.setTitle(windowTitle);
streamPropertiesController.init(profileList, currentSelectedProfileIndex);
initEditStream(currentStream.getPacket().getBinary());
if (currentStream.getAdvancedMode()) {
showAdvancedModeTabs();
} else {
showSimpleModeTabs();
}
}
private void updateCurrentProfile() throws Exception {
selectedProfile = streamPropertiesController.getUpdatedSelectedProfile();
String hexPacket = null;
if (packetHex != null && !isBuildPacket) {
hexPacket = packetHex.getPacketHexFromList();
} else if (isBuildPacket) {
hexPacket = PacketBuilderHelper.getPacketHex(protocolDataController.getProtocolData().getPacket().getRawData());
selectedProfile.getStream().setAdditionalProperties(protocolDataController.getVm(advancedSettingsController.getCacheSize()));
selectedProfile.getStream().setFlags(protocolDataController.getFlagsValue());
// save stream selected in stream property
final String metaJSON = new ObjectMapper().writeValueAsString(builderDataBinder);
final String encodedMeta = Base64.getEncoder().encodeToString(metaJSON.getBytes());
selectedProfile.getStream().getPacket().setMeta(encodedMeta);
}
String encodedBinaryPacket = trafficProfile.encodeBinaryFromHexString(hexPacket);
Packet packet = selectedProfile.getStream().getPacket();
if (selectedProfile.getStream().getAdvancedMode()) {
packet.setBinary(packetBuilderController.getModel().getPkt().binary);
packet.setModel(packetBuilderController.getModel().serialize());
selectedProfile.getStream().setAdditionalProperties(packetBuilderController.getPktVmInstructions());
} else {
packet.setBinary(encodedBinaryPacket);
packet.setModel("");
}
}
@Override
public void onEnterKeyPressed(Stage stage) {
// ignore event
}
@Override
public void onEscapKeyPressed() {
// ignoring global escape
}
private boolean alertWarning(String header, String content) {
ButtonType buttonTypeTry = new ButtonType("Try", ButtonBar.ButtonData.YES);
ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
Alert alert = TrexAlertBuilder.build()
.setType(Alert.AlertType.WARNING)
.setTitle("Warning")
.setHeader(header)
.setContent(content + "\nWould you like to change ip or port and try connection again ?")
.setButtons(buttonTypeTry, buttonTypeCancel)
.getAlert();
alert.showAndWait();
ButtonType res = alert.getResult();
return res.getButtonData() != ButtonBar.ButtonData.CANCEL_CLOSE;
}
}
| Fixed initialization of Packet Editor
- It overwrote FE instructions with emtpy, now it's not
| src/main/java/com/exalttech/trex/ui/controllers/PacketBuilderHomeController.java | Fixed initialization of Packet Editor | <ide><path>rc/main/java/com/exalttech/trex/ui/controllers/PacketBuilderHomeController.java
<ide> import java.io.File;
<ide> import java.io.IOException;
<ide> import java.net.URL;
<del>import java.util.Base64;
<del>import java.util.List;
<del>import java.util.Optional;
<del>import java.util.ResourceBundle;
<add>import java.util.*;
<ide>
<ide> import com.fasterxml.jackson.databind.ObjectMapper;
<ide>
<ide> }
<ide>
<ide> if (selectedProfile.getStream().getAdvancedMode()) {
<del> if (isImportedStreamProperty.getValue()) {
<del> Stream currentStream = streamPropertiesController.getUpdatedSelectedProfile().getStream();
<del> byte[] base64Packet = currentStream.getPacket().getBinary().getBytes();
<del> byte[] packet = Base64.getDecoder().decode(base64Packet);
<del> packetBuilderController.loadPcapBinary(packet);
<del> packetBuilderController.loadVmInstructions(currentStream.getAdditionalProperties().get("vm"));
<del> } else {
<del> packetBuilderController.loadSimpleUserModel(builderDataBinder.serializeAsPacketModel());
<del> }
<ide> showAdvancedModeTabs();
<ide> } else {
<ide> showSimpleModeTabs();
<ide> }
<ide> }
<ide>
<del> private void initEditStream(String pcapFileBinary) {
<add> private void initEditStream(String pcapFileBinary) throws IOException {
<ide> streamTabPane.setDisable(false);
<ide> saveButton.setDisable(false);
<ide> streamEditorModeBtn.setDisable(false);
<ide> String base64UserModel = currentStream.getPacket().getModel();
<ide> if (!Strings.isNullOrEmpty(base64UserModel)) {
<ide> packetBuilderController.loadUserModel(base64UserModel);
<add> } else {
<add> byte[] base64Packet = currentStream.getPacket().getBinary().getBytes();
<add> byte[] packet = Base64.getDecoder().decode(base64Packet);
<add> packetBuilderController.loadPcapBinary(packet);
<ide> }
<ide> }
<ide>
<ide> prevStreamBtn.setDisable((currentSelectedProfileIndex == 0));
<ide> }
<ide>
<del> private void loadStream() {
<add> private void loadStream() throws IOException {
<ide> resetTabs();
<ide> streamTabPane.getSelectionModel().select(streamPropertiesTab);
<ide> selectedProfile = profileList.get(currentSelectedProfileIndex); |
|
JavaScript | mit | 41c1568453516230abefcda02fa5be8da0dc5d9f | 0 | justinforce/muster,justinforce/muster | /*!
* Muster v1.0
* http://apps.education.ucsb.edu/redmine/projects/muster
*
* Copyright 2011, Justin Force
* Licensed under the BSD 3-Clause License
*/
/*jslint browser: true, indent: 2 */
/*global jQuery */
(function (context, $) {
'use strict'; // strict ECMAScript interpretation
var MergeSort, // object to privide merge sort for Array and jQuery
// Constants
POSSIBLE_PARAMETERS = [ 'database', 'select', 'from', 'where', 'order' ],
DEFAULT_URL = 'https://apps.education.ucsb.edu/muster/';
/* Add stable merge sort to Array and jQuery prototypes
*
* N.B. It may seem unnecessary to define this with a constructor and a
* prototype, but for compliance and clarity with 'use strict', we
* should. With 'use strict', `this` will NOT default to pointing to the
* base object (window), so we explicitly say that it's a pointer to its
* function's parent object by defining a constructor and prototype.
*/
MergeSort = function () {};
MergeSort.prototype = {
msort: function (compare) {
var length = this.length,
middle = Math.floor(length / 2);
if (compare === undefined) {
compare = function (left, right) {
if (left < right) {
return -1;
}
if (left === right) {
return 0;
} else {
return 1;
}
};
}
if (length < 2) {
return this;
}
function merge(left, right, compare) {
var result = [];
while (left.length > 0 || right.length > 0) {
if (left.length > 0 && right.length > 0) {
if (compare(left[0], right[0]) <= 0) {
result.push(left[0]);
left = left.slice(1);
} else {
result.push(right[0]);
right = right.slice(1);
}
} else if (left.length > 0) {
result.push(left[0]);
left = left.slice(1);
} else if (right.length > 0) {
result.push(right[0]);
right = right.slice(1);
}
}
return result;
}
return merge(
this.slice(0, middle).msort(compare),
this.slice(middle, length).msort(compare),
compare
);
}
};
Array.prototype.msort = jQuery.fn.msort = MergeSort.prototype.msort;
///////////////////////////////////////////////////////////////////////////////
// Constructors and utility functions. Utility functions are specifically meant
// NOT to be methods of the Muster object.
///////////////////////////////////////////////////////////////////////////////
// Constructor
function Muster(args) {
if (typeof args === 'string') {
this.database = args;
} else if (args !== undefined) {
this.url = args.url;
this.database = args.database;
}
if (this.url === undefined) {
this.url = DEFAULT_URL;
}
}
// Constructor wrapper.
// Whether called as a function or a constructor, it always returns an instance
// of Muster, i.e. `Muster` and `new Muster()` are equivalent.
function constructorWrapper(args) {
return new Muster(args);
}
// Assemble the request URI
function getRequestUri(url, database, params) {
// each value is [ 'key', 'value' ] and will become 'key=value'
var parameterPairs = [];
// Add database to parameters
params.database = database;
// assemble the parameters
$.each(POSSIBLE_PARAMETERS, function () {
if (params[this] !== undefined && params[this].length > 0) {
parameterPairs.push([this, window.escape(params[this])].join('='));
}
});
parameterPairs.push('callback=?'); // jQuery JSONP support
return [url, '?', parameterPairs.join('&')].join('');
}
/* Return a copy of the table which supports stable sorting when the table's
* column headings are clicked.
*
* Triggers the $(window).bind('muster_sorted') event after sorting.
*
* N.B. If table contents are modified after the table is sorted, sorting and
* reverse sorting by clicking the same heading multiple times WILL NOT
* correctly sort based on the new content. Sorting again by the same
* column just reverses the rows. This has the dual benefits of being
* efficient and maintaining a stable sort. If, in the future, Muster
* needs to handle sorting a table after data has been modified
* dynamically, all of the headings should be stripped of their 'sort'
* and 'rsort' classes (i.e.
* th.removeClass('sorted').removeClass('rsorted')) BEFORE sorting is
* performed to ensure a new sort is performed and that the order isn't
* simply reversed.
*/
function getSortableTable(table) {
table.find('th').css({cursor: 'pointer'}).click(function (event) {
var sortedRows,
th = $(event.target), // the heading that was clicked
table = th.closest('table'),
tbody = table.find('tbody'),
index = th.index() + 1, // the numerical position of the clicked heading
rows = table.find('tbody tr'),
sorted = th.hasClass('sorted'), // is the column already sorted?
rsorted = th.hasClass('rsorted'); // is the column already reverse sorted?
// Remove sort statuses from all other headings
th.siblings().removeClass('sorted').removeClass('rsorted');
// If it's already sorted, the quickest solution is to just reverse it.
// Otherwise, do a stable merge sort of the unsorted column and mark it
// as sorted.
if (sorted || rsorted) {
th.toggleClass('sorted').toggleClass('rsorted');
sortedRows = Array.prototype.reverse.apply(rows);
} else {
sortedRows = rows.msort(function (left, right) {
// compare the text of each cell, case insensitive
left = $(left).find('td:nth-child(' + index + ')').text().toLowerCase();
right = $(right).find('td:nth-child(' + index + ')').text().toLowerCase();
if (left < right) {
return -1;
} else if (left === right) {
return 0;
} else {
return 1;
}
});
th.toggleClass('sorted');
}
tbody.append(sortedRows);
$(window).trigger('muster_sorted');
});
return table;
}
// Expose Muster constructor as method of 'context' (i.e. window.Muster). It's
// not capitalized because it's a method of 'context' that returns an instance
// of Muster. The Muster constructor should never be called directly.
context.muster = constructorWrapper;
///////////////////////////////////////////////////////////////////////////////
// Muster's prototype
// All public methods are defined here.
///////////////////////////////////////////////////////////////////////////////
Muster.prototype = {
query: function (query, callback) {
var muster = this;
$.getJSON(getRequestUri(this.url, this.database, query), function (data) {
muster.columns = data.columns;
muster.results = data.results;
callback.apply(muster);
});
},
isEmpty: function () {
return this.results.length < 1;
},
clone: function () {
var property,
oldMuster = this,
newMuster = constructorWrapper();
for (property in oldMuster) {
if (oldMuster.hasOwnProperty(property)) {
newMuster[property] = oldMuster[property];
}
}
return newMuster;
},
filter: function (column, value) {
var clone = this.clone();
clone.results = $.grep(this.results, function (row) {
return row[column] === value;
});
return clone;
},
get: function (column) {
var ret = [];
$.each(this.results, function () {
ret.push(this[column]);
});
return ret;
},
getUnique: function (column) {
return $.unique(this.get(column));
},
getFirst: function (column) {
return this.results[0][column];
},
groupBy: function (column) {
// ret is an array of arrays. Each array in ret shares the same value for
// row[column]. uniq keeps track of whether we've encountered a value
// before so we only traverse the results once.
var ret = [],
uniq = [],
muster = this;
$.each(this.results, function () {
var i = uniq.indexOf(this[column]);
if (i < 0) {
uniq.push(this[column]);
i = uniq.length - 1;
ret[i] = muster.clone();
ret[i].results = [];
}
ret[i].results.push(this);
});
return ret;
},
/* Return a modified Muster which joins together similar rows based on
* `uniqueColumn` (usually something like "id"). Columns with multiple
* values become nested.
*
* { "id": 2, "friend": "Bob" }
* { "id": 2, "friend": "Doug" }
* { "id": 3, "friend": "Sue" }
* { "id": 3, "friend": "Daisy" }
*
* becomes
*
* { "id": 2, "friend": [ "Bob", "Doug" ] }
* { "id": 3, "friend": [ "Sue", "Daisy" ] }
*/
serializeJoinedResults: function (uniqueColumn) {
var grouped = this.groupBy(uniqueColumn),
columns = grouped[0].columns,
clone = this.clone();
clone.results = [];
/* For each row in each group, examine the values one at a time.
*
* - If the value isn't yet defined in the output, just copy the
* incoming value to the output
*
* - If the value in the output is already defined and is a string, it
* is a single value. We convert it to an array consisting of the
* original value plus the incoming value.
*
* - Otherwise, the output is already an array. Just push the new value
* onto it.
*
* Once we figure out the row contents, we push it into the clone and
* return the clone at the end.
*/
$.each(grouped, function () {
var mergedRow = {};
$.each(this.results, function () {
var row = this;
$.each(columns, function () {
if (mergedRow[this] === undefined) {
mergedRow[this] = row[this];
} else if (typeof mergedRow[this] === 'string') {
if (mergedRow[this] !== row[this]) {
mergedRow[this] = [mergedRow[this], row[this]];
}
} else {
mergedRow[this].push(row[this]);
}
});
});
clone.results.push(mergedRow);
});
return clone;
},
toTable: function (columnSpec, parent, callback) {
var columns, columnLabels,
table = $('<table><thead><tr></tr></thead><tbody></tbody></table>'),
thead = table.find('thead tr'),
tbody = table.find('tbody');
if (!columnSpec) {
columns = columnLabels = this.columns;
} else {
columns = [];
columnLabels = [];
$.each(columnSpec, function () {
if (this instanceof Array) {
columns.push(this[0]);
columnLabels.push(this[1]);
} else if (typeof this === 'string') {
columns.push(this);
columnLabels.push(this);
}
});
}
$.each(columnLabels, function () {
thead.append('<th>' + this);
});
$.each(this.results, function () {
var row = this,
tr = $('<tr>');
tbody.append(tr);
$.each(columns, function () {
var value,
td = $('<td>');
if (typeof this === 'function') {
// formatting function
value = this.apply(row);
} else if (row[this] instanceof Array) {
// multiple values
value = row[this].join('</li><li>');
value = '<ul><li>' + value + '</li></ul>';
} else {
// just a string
value = row[this];
}
tr.append(td.append(value));
});
});
table = getSortableTable(table);
if (parent) {
$($(parent).html(table));
}
if (callback) {
callback.apply(table);
}
return table;
}
};
// Add Array.indexOf to browsers that don't have it (i.e. IE)
(function () {
if (Array.indexOf === undefined) {
Array.prototype.indexOf = function (obj) {
var i, len;
for (i = 0, len = this.length; i < len; i += 1) {
if (this[i] === obj) {
return i;
}
}
return -1;
};
}
}());
}(window, jQuery));
| WebContent/muster.js | /*!
* Muster v1.0
* http://apps.education.ucsb.edu/redmine/projects/muster
*
* Copyright 2011, Justin Force
* Licensed under the BSD 3-Clause License
*/
/*jslint browser: true, indent: 2 */
/*global jQuery */
(function (context, $) {
'use strict'; // strict ECMAScript interpretation
var MergeSort, // object to privide merge sort for Array and jQuery
// Constants
POSSIBLE_PARAMETERS = [ 'database', 'select', 'from', 'where', 'order' ],
DEFAULT_URL = 'https://apps.education.ucsb.edu/muster/';
/* Add stable merge sort to Array and jQuery prototypes
*
* N.B. It may seem unnecessary to define this with a constructor and a
* prototype, but for compliance and clarity with 'use strict', we
* should. With 'use strict', `this` will NOT default to pointing to the
* base object (window), so we explicitly say that it's a pointer to its
* function's parent object by defining a constructor and prototype.
*/
MergeSort = function () {};
MergeSort.prototype = {
msort: function (compare) {
var length = this.length,
middle = Math.floor(length / 2);
if (compare === undefined) {
compare = function (left, right) {
if (left < right) {
return -1;
}
if (left === right) {
return 0;
} else {
return 1;
}
};
}
if (length < 2) {
return this;
}
function merge(left, right, compare) {
var result = [];
while (left.length > 0 || right.length > 0) {
if (left.length > 0 && right.length > 0) {
if (compare(left[0], right[0]) <= 0) {
result.push(left[0]);
left = left.slice(1);
} else {
result.push(right[0]);
right = right.slice(1);
}
} else if (left.length > 0) {
result.push(left[0]);
left = left.slice(1);
} else if (right.length > 0) {
result.push(right[0]);
right = right.slice(1);
}
}
return result;
}
return merge(
this.slice(0, middle).msort(compare),
this.slice(middle, length).msort(compare),
compare
);
}
};
Array.prototype.msort = jQuery.fn.msort = MergeSort.prototype.msort;
///////////////////////////////////////////////////////////////////////////////
// Constructors and utility functions. Utility functions are specifically meant
// NOT to be methods of the Muster object.
///////////////////////////////////////////////////////////////////////////////
// Constructor
function Muster(args) {
if (typeof args === 'string') {
this.database = args;
} else if (args !== undefined) {
this.url = args.url;
this.database = args.database;
}
if (this.url === undefined) {
this.url = DEFAULT_URL;
}
}
// Constructor wrapper.
// Whether called as a function or a constructor, it always returns an instance
// of Muster, i.e. `Muster` and `new Muster()` are equivalent.
function constructorWrapper(args) {
return new Muster(args);
}
// Assemble the request URI
function getRequestUri(url, database, params) {
// each value is [ 'key', 'value' ] and will become 'key=value'
var parameterPairs = [];
// Add database to parameters
params.database = database;
// assemble the parameters
$.each(POSSIBLE_PARAMETERS, function () {
if (params[this] !== undefined && params[this].length > 0) {
parameterPairs.push([this, window.escape(params[this])].join('='));
}
});
parameterPairs.push('callback=?'); // jQuery JSONP support
return [url, '?', parameterPairs.join('&')].join('');
}
/* Return a copy of the table which supports stable sorting when the table's
* column headings are clicked.
*
* Triggers the $(window).bind('muster_sorted') event after sorting.
*
* N.B. If table contents are modified after the table is sorted, sorting and
* reverse sorting by clicking the same heading multiple times WILL NOT
* correctly sort based on the new content. Sorting again by the same
* column just reverses the rows. This has the dual benefits of being
* efficient and maintaining a stable sort. If, in the future, Muster
* needs to handle sorting a table after data has been modified
* dynamically, all of the headings should be stripped of their 'sort'
* and 'rsort' classes (i.e.
* th.removeClass('sorted').removeClass('rsorted')) BEFORE sorting is
* performed to ensure a new sort is performed and that the order isn't
* simply reversed.
*/
function getSortableTable(table) {
table.find('th').css({cursor: 'pointer'}).click(function (event) {
var sortedRows,
th = $(event.target), // the heading that was clicked
table = th.closest('table'),
tbody = table.find('tbody'),
index = th.index() + 1, // the numerical position of the clicked heading
rows = table.find('tbody tr'),
sorted = th.hasClass('sorted'), // is the column already sorted?
rsorted = th.hasClass('rsorted'); // is the column already reverse sorted?
// Remove sort statuses from all other headings
th.siblings().removeClass('sorted').removeClass('rsorted');
// If it's already sorted, the quickest solution is to just reverse it.
// Otherwise, do a stable merge sort of the unsorted column and mark it
// as sorted.
if (sorted || rsorted) {
th.toggleClass('sorted').toggleClass('rsorted');
sortedRows = Array.prototype.reverse.apply(rows);
} else {
sortedRows = rows.msort(function (left, right) {
// compare the text of each cell, case insensitive
left = $(left).find('td:nth-child(' + index + ')').text().toLowerCase();
right = $(right).find('td:nth-child(' + index + ')').text().toLowerCase();
if (left < right) {
return -1;
} else if (left === right) {
return 0;
} else {
return 1;
}
});
th.toggleClass('sorted');
}
tbody.append(sortedRows);
$(window).trigger('muster_sorted');
});
return table;
}
// Expose Muster constructor as method of 'context' (i.e. window.Muster). It's
// not capitalized because it's a method of 'context' that returns an instance
// of Muster. The Muster constructor should never be called directly.
context.muster = constructorWrapper;
///////////////////////////////////////////////////////////////////////////////
// Muster's prototype
// All public methods are defined here.
///////////////////////////////////////////////////////////////////////////////
Muster.prototype = {
query: function (query, callback) {
var muster = this;
$.getJSON(getRequestUri(this.url, this.database, query), function (data) {
muster.columns = data.columns;
muster.results = data.results;
callback.apply(muster);
});
},
isEmpty: function () {
return this.results.length < 1;
},
clone: function () {
var property,
oldMuster = this,
newMuster = constructorWrapper();
for (property in oldMuster) {
if (oldMuster.hasOwnProperty(property)) {
newMuster[property] = oldMuster[property];
}
}
return newMuster;
},
filter: function (column, value) {
var clone = this.clone();
clone.results = $.grep(this.results, function (row) {
return row[column] === value;
});
return clone;
},
get: function (column) {
var ret = [];
$.each(this.results, function () {
ret.push(this[column]);
});
return ret;
},
getUnique: function (column) {
return $.unique(this.get(column));
},
getFirst: function (column) {
return this.results[0][column];
},
groupBy: function (column) {
// ret is an array of arrays. Each array in ret shares the same value for
// row[column]. uniq keeps track of whether we've encountered a value
// before so we only traverse the results once.
var ret = [],
uniq = [],
muster = this;
$.each(this.results, function () {
var i = uniq.indexOf(this[column]);
if (i < 0) {
uniq.push(this[column]);
i = uniq.length - 1;
ret[i] = muster.clone();
ret[i].results = [];
}
ret[i].results.push(this);
});
return ret;
},
/* Return a modified Muster which joins together similar rows based on
* `uniqueColumn` (usually something like "id"). Columns with multiple
* values become nested.
*
* { "id": 2, "friend": "Bob" }
* { "id": 2, "friend": "Doug" }
* { "id": 3, "friend": "Sue" }
* { "id": 3, "friend": "Daisy" }
*
* becomes
*
* { "id": 2, "friend": [ "Bob", "Doug" ] }
* { "id": 3, "friend": [ "Sue", "Daisy" ] }
*/
serializeJoinedResults: function (uniqueColumn) {
var grouped = this.groupBy(uniqueColumn),
columns = grouped[0].columns,
clone = this.clone();
clone.results = [];
/* For each row in each group, examine the values one at a time.
*
* - If the value isn't yet defined in the output, just copy the
* incoming value to the output
*
* - If the value in the output is already defined and is a string, it
* is a single value. We convert it to an array consisting of the
* original value plus the incoming value.
*
* - Otherwise, the output is already an array. Just push the new value
* onto it.
*
* Once we figure out the row contents, we push it into the clone and
* return the clone at the end.
*/
$.each(grouped, function () {
var mergedRow = {};
$.each(this.results, function () {
var row = this;
$.each(columns, function () {
if (mergedRow[this] === undefined) {
mergedRow[this] = row[this];
} else if (typeof mergedRow[this] === 'string') {
if (mergedRow[this] !== row[this]) {
mergedRow[this] = [mergedRow[this], row[this]];
}
} else {
mergedRow[this].push(row[this]);
}
});
});
clone.results.push(mergedRow);
});
return clone;
},
toTable: function (columnSpec, parent, callback) {
var columns, columnLabels,
table = $('<table><thead><tr></tr></thead><tbody></tbody></table>'),
thead = table.find('thead tr'),
tbody = table.find('tbody');
if (columnSpec === undefined) {
columns = columnLabels = this.columns;
} else {
columns = [];
columnLabels = [];
$.each(columnSpec, function () {
if (this instanceof Array) {
columns.push(this[0]);
columnLabels.push(this[1]);
} else if (typeof this === 'string') {
columns.push(this);
columnLabels.push(this);
}
});
}
$.each(columnLabels, function () {
thead.append('<th>' + this);
});
$.each(this.results, function () {
var row = this,
tr = $('<tr>');
tbody.append(tr);
$.each(columns, function () {
var value,
td = $('<td>');
if (typeof this === 'function') {
// formatting function
value = this.apply(row);
} else if (row[this] instanceof Array) {
// multiple values
value = row[this].join('</li><li>');
value = '<ul><li>' + value + '</li></ul>';
} else {
// just a string
value = row[this];
}
tr.append(td.append(value));
});
});
table = getSortableTable(table);
if (parent) {
$($(parent).html(table));
}
if (callback) {
callback.apply(table);
}
return table;
}
};
// Add Array.indexOf to browsers that don't have it (i.e. IE)
(function () {
if (Array.indexOf === undefined) {
Array.prototype.indexOf = function (obj) {
var i, len;
for (i = 0, len = this.length; i < len; i += 1) {
if (this[i] === obj) {
return i;
}
}
return -1;
};
}
}());
}(window, jQuery));
| Allow columnSpec to be null
| WebContent/muster.js | Allow columnSpec to be null | <ide><path>ebContent/muster.js
<ide> thead = table.find('thead tr'),
<ide> tbody = table.find('tbody');
<ide>
<del> if (columnSpec === undefined) {
<add> if (!columnSpec) {
<ide> columns = columnLabels = this.columns;
<ide> } else {
<ide> columns = []; |
|
Java | apache-2.0 | error: pathspec 'subprojects/groovy-jmx/src/main/java/groovy/jmx/GroovyMBean.java' did not match any file(s) known to git
| 3ec376560eecef3f9f51a627925e9889840b8728 | 1 | shils/incubator-groovy,apache/incubator-groovy,paulk-asert/groovy,apache/incubator-groovy,shils/groovy,shils/groovy,armsargis/groovy,apache/incubator-groovy,paulk-asert/groovy,paulk-asert/incubator-groovy,shils/incubator-groovy,apache/groovy,shils/groovy,paulk-asert/incubator-groovy,shils/groovy,shils/incubator-groovy,shils/incubator-groovy,paulk-asert/incubator-groovy,paulk-asert/groovy,armsargis/groovy,armsargis/groovy,apache/groovy,paulk-asert/incubator-groovy,apache/groovy,armsargis/groovy,apache/incubator-groovy,paulk-asert/groovy,apache/groovy,paulk-asert/incubator-groovy | /*
* 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 groovy.util;
import groovy.lang.GroovyObjectSupport;
import groovy.lang.GroovyRuntimeException;
import javax.management.Attribute;
import javax.management.JMException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanParameterInfo;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A GroovyObject facade for an underlying MBean which acts like a normal
* groovy object but which is actually implemented via
* an underlying JMX MBean.
* Properties and normal method invocations
* delegate to the MBeanServer to the actual MBean.
*/
public class GroovyMBean extends GroovyObjectSupport {
private final MBeanServerConnection server;
private final ObjectName name;
private MBeanInfo beanInfo;
private final boolean ignoreErrors;
private final Map<String, String[]> operations = new HashMap<String, String[]>();
public GroovyMBean(MBeanServerConnection server, String objectName) throws JMException, IOException {
this(server, objectName, false);
}
public GroovyMBean(MBeanServerConnection server, String objectName, boolean ignoreErrors) throws JMException, IOException {
this(server, new ObjectName(objectName), ignoreErrors);
}
public GroovyMBean(MBeanServerConnection server, ObjectName name) throws JMException, IOException {
this(server, name, false);
}
public GroovyMBean(MBeanServerConnection server, ObjectName name, boolean ignoreErrors) throws JMException, IOException {
this.server = server;
this.name = name;
this.ignoreErrors = ignoreErrors;
this.beanInfo = server.getMBeanInfo(name);
MBeanOperationInfo[] operationInfos = beanInfo.getOperations();
for (MBeanOperationInfo info : operationInfos) {
String signature[] = createSignature(info);
// Construct a simplistic key to support overloaded operations on the MBean.
String operationKey = createOperationKey(info.getName(), signature.length);
operations.put(operationKey, signature);
}
}
public MBeanServerConnection server() {
return server;
}
public ObjectName name() {
return name;
}
public MBeanInfo info() {
return beanInfo;
}
public Object getProperty(String property) {
try {
return server.getAttribute(name, property);
}
catch (MBeanException e) {
throwExceptionWithTarget("Could not access property: " + property + ". Reason: ", e);
}
catch (Exception e) {
if (!ignoreErrors)
throwException("Could not access property: " + property + ". Reason: ", e);
}
return null;
}
public void setProperty(String property, Object value) {
try {
server.setAttribute(name, new Attribute(property, value));
}
catch (MBeanException e) {
throwExceptionWithTarget("Could not set property: " + property + ". Reason: ", e);
}
catch (Exception e) {
throwException("Could not set property: " + property + ". Reason: ", e);
}
}
public Object invokeMethod(String method, Object arguments) {
Object[] argArray;
if (arguments instanceof Object[]) {
argArray = (Object[]) arguments;
} else {
argArray = new Object[]{arguments};
}
// Locate the specific method based on the name and number of parameters
String operationKey = createOperationKey(method, argArray.length);
String[] signature = operations.get(operationKey);
if (signature != null) {
try {
return server.invoke(name, method, argArray, signature);
}
catch (MBeanException e) {
throwExceptionWithTarget("Could not invoke method: " + method + ". Reason: ", e);
}
catch (Exception e) {
throwException("Could not invoke method: " + method + ". Reason: ", e);
}
return null;
} else {
return super.invokeMethod(method, arguments);
}
}
protected String[] createSignature(MBeanOperationInfo info) {
MBeanParameterInfo[] params = info.getSignature();
String[] answer = new String[params.length];
for (int i = 0; i < params.length; i++) {
answer[i] = params[i].getType();
}
return answer;
}
/**
* Construct a simple key based on the method name and the number of parameters
*
* @param operation - the mbean operation name
* @param params - the number of parameters the operation supports
* @return simple unique identifier for a method
*/
protected String createOperationKey(String operation, int params) {
// This could be changed to support some hash of the parameter types, etc.
// but should distinguish between reordered params while allowing normal
// type coercions to be honored
return operation + "_" + params;
}
/**
* List of the names of each of the attributes on the MBean
*
* @return list of attribute names
*/
public Collection<String> listAttributeNames() {
List<String> list = new ArrayList<String>();
try {
MBeanAttributeInfo[] attrs = beanInfo.getAttributes();
for (MBeanAttributeInfo attr : attrs) {
list.add(attr.getName());
}
} catch (Exception e) {
throwException("Could not list attribute names. Reason: ", e);
}
return list;
}
/**
* The values of each of the attributes on the MBean
*
* @return list of values of each attribute
*/
public List<String> listAttributeValues() {
List<String> list = new ArrayList<String>();
Collection<String> names = listAttributeNames();
for (String name : names) {
try {
Object val = this.getProperty(name);
if (val != null) {
list.add(name + " : " + val.toString());
}
} catch (Exception e) {
throwException("Could not list attribute values. Reason: ", e);
}
}
return list;
}
/**
* List of string representations of all of the attributes on the MBean.
*
* @return list of descriptions of each attribute on the mbean
*/
public Collection<String> listAttributeDescriptions() {
List<String> list = new ArrayList<String>();
try {
MBeanAttributeInfo[] attrs = beanInfo.getAttributes();
for (MBeanAttributeInfo attr : attrs) {
list.add(describeAttribute(attr));
}
} catch (Exception e) {
throwException("Could not list attribute descriptions. Reason: ", e);
}
return list;
}
/**
* Description of the specified attribute name.
*
* @param attr - the attribute
* @return String the description
*/
protected String describeAttribute(MBeanAttributeInfo attr) {
StringBuilder buf = new StringBuilder();
buf.append("(");
if (attr.isReadable()) {
buf.append("r");
}
if (attr.isWritable()) {
buf.append("w");
}
buf.append(") ")
.append(attr.getType())
.append(" ")
.append(attr.getName());
return buf.toString();
}
/**
* Description of the specified attribute name.
*
* @param attributeName - stringified name of the attribute
* @return the description
*/
public String describeAttribute(String attributeName) {
String ret = "Attribute not found";
try {
MBeanAttributeInfo[] attributes = beanInfo.getAttributes();
for (MBeanAttributeInfo attribute : attributes) {
if (attribute.getName().equals(attributeName)) {
return describeAttribute(attribute);
}
}
} catch (Exception e) {
throwException("Could not describe attribute '" + attributeName + "'. Reason: ", e);
}
return ret;
}
/**
* Names of all the operations available on the MBean.
*
* @return all the operations on the MBean
*/
public Collection<String> listOperationNames() {
List<String> list = new ArrayList<String>();
try {
MBeanOperationInfo[] operations = beanInfo.getOperations();
for (MBeanOperationInfo operation : operations) {
list.add(operation.getName());
}
} catch (Exception e) {
throwException("Could not list operation names. Reason: ", e);
}
return list;
}
/**
* Description of all of the operations available on the MBean.
*
* @return full description of each operation on the MBean
*/
public Collection<String> listOperationDescriptions() {
List<String> list = new ArrayList<String>();
try {
MBeanOperationInfo[] operations = beanInfo.getOperations();
for (MBeanOperationInfo operation : operations) {
list.add(describeOperation(operation));
}
} catch (Exception e) {
throwException("Could not list operation descriptions. Reason: ", e);
}
return list;
}
/**
* Get the description of the specified operation. This returns a Collection since
* operations can be overloaded and one operationName can have multiple forms.
*
* @param operationName the name of the operation to describe
* @return Collection of operation description
*/
public List<String> describeOperation(String operationName) {
List<String> list = new ArrayList<String>();
try {
MBeanOperationInfo[] operations = beanInfo.getOperations();
for (MBeanOperationInfo operation : operations) {
if (operation.getName().equals(operationName)) {
list.add(describeOperation(operation));
}
}
} catch (Exception e) {
throwException("Could not describe operations matching name '" + operationName + "'. Reason: ", e);
}
return list;
}
/**
* Description of the operation.
*
* @param operation the operation to describe
* @return pretty-printed description
*/
protected String describeOperation(MBeanOperationInfo operation) {
StringBuilder buf = new StringBuilder();
buf.append(operation.getReturnType())
.append(" ")
.append(operation.getName())
.append("(");
MBeanParameterInfo[] params = operation.getSignature();
for (int j = 0; j < params.length; j++) {
MBeanParameterInfo param = params[j];
if (j != 0) {
buf.append(", ");
}
buf.append(param.getType())
.append(" ")
.append(param.getName());
}
buf.append(")");
return buf.toString();
}
/**
* Return an end user readable representation of the underlying MBean
*
* @return the user readable description
*/
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append("MBean Name:")
.append("\n ")
.append(name.getCanonicalName())
.append("\n ");
if (!listAttributeDescriptions().isEmpty()) {
buf.append("\nAttributes:");
for (String attrDesc : listAttributeDescriptions()) {
buf.append("\n ").append(attrDesc);
}
}
if (!listOperationDescriptions().isEmpty()) {
buf.append("\nOperations:");
for (String attrDesc : listOperationDescriptions()) {
buf.append("\n ").append(attrDesc);
}
}
return buf.toString();
}
private void throwException(String m, Exception e) {
if (!ignoreErrors) {
throw new GroovyRuntimeException(m + e, e);
}
}
private void throwExceptionWithTarget(String m, MBeanException e) {
if (!ignoreErrors) {
throw new GroovyRuntimeException(m + e, e.getTargetException());
}
}
}
| subprojects/groovy-jmx/src/main/java/groovy/jmx/GroovyMBean.java | Split history main/java/groovy/util/GroovyMBean.java to main/java/groovy/jmx - resolve conflict and keep both files
| subprojects/groovy-jmx/src/main/java/groovy/jmx/GroovyMBean.java | Split history main/java/groovy/util/GroovyMBean.java to main/java/groovy/jmx - resolve conflict and keep both files | <ide><path>ubprojects/groovy-jmx/src/main/java/groovy/jmx/GroovyMBean.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
<add> * under the License.
<add> */
<add>package groovy.util;
<add>
<add>import groovy.lang.GroovyObjectSupport;
<add>import groovy.lang.GroovyRuntimeException;
<add>
<add>import javax.management.Attribute;
<add>import javax.management.JMException;
<add>import javax.management.MBeanAttributeInfo;
<add>import javax.management.MBeanException;
<add>import javax.management.MBeanInfo;
<add>import javax.management.MBeanOperationInfo;
<add>import javax.management.MBeanParameterInfo;
<add>import javax.management.MBeanServerConnection;
<add>import javax.management.ObjectName;
<add>import java.io.IOException;
<add>import java.util.ArrayList;
<add>import java.util.Collection;
<add>import java.util.HashMap;
<add>import java.util.List;
<add>import java.util.Map;
<add>
<add>/**
<add> * A GroovyObject facade for an underlying MBean which acts like a normal
<add> * groovy object but which is actually implemented via
<add> * an underlying JMX MBean.
<add> * Properties and normal method invocations
<add> * delegate to the MBeanServer to the actual MBean.
<add> */
<add>public class GroovyMBean extends GroovyObjectSupport {
<add> private final MBeanServerConnection server;
<add> private final ObjectName name;
<add> private MBeanInfo beanInfo;
<add> private final boolean ignoreErrors;
<add> private final Map<String, String[]> operations = new HashMap<String, String[]>();
<add>
<add> public GroovyMBean(MBeanServerConnection server, String objectName) throws JMException, IOException {
<add> this(server, objectName, false);
<add> }
<add>
<add> public GroovyMBean(MBeanServerConnection server, String objectName, boolean ignoreErrors) throws JMException, IOException {
<add> this(server, new ObjectName(objectName), ignoreErrors);
<add> }
<add>
<add> public GroovyMBean(MBeanServerConnection server, ObjectName name) throws JMException, IOException {
<add> this(server, name, false);
<add> }
<add>
<add> public GroovyMBean(MBeanServerConnection server, ObjectName name, boolean ignoreErrors) throws JMException, IOException {
<add> this.server = server;
<add> this.name = name;
<add> this.ignoreErrors = ignoreErrors;
<add> this.beanInfo = server.getMBeanInfo(name);
<add>
<add> MBeanOperationInfo[] operationInfos = beanInfo.getOperations();
<add> for (MBeanOperationInfo info : operationInfos) {
<add> String signature[] = createSignature(info);
<add> // Construct a simplistic key to support overloaded operations on the MBean.
<add> String operationKey = createOperationKey(info.getName(), signature.length);
<add> operations.put(operationKey, signature);
<add> }
<add> }
<add>
<add> public MBeanServerConnection server() {
<add> return server;
<add> }
<add>
<add> public ObjectName name() {
<add> return name;
<add> }
<add>
<add> public MBeanInfo info() {
<add> return beanInfo;
<add> }
<add>
<add> public Object getProperty(String property) {
<add> try {
<add> return server.getAttribute(name, property);
<add> }
<add> catch (MBeanException e) {
<add> throwExceptionWithTarget("Could not access property: " + property + ". Reason: ", e);
<add> }
<add> catch (Exception e) {
<add> if (!ignoreErrors)
<add> throwException("Could not access property: " + property + ". Reason: ", e);
<add> }
<add> return null;
<add> }
<add>
<add> public void setProperty(String property, Object value) {
<add> try {
<add> server.setAttribute(name, new Attribute(property, value));
<add> }
<add> catch (MBeanException e) {
<add> throwExceptionWithTarget("Could not set property: " + property + ". Reason: ", e);
<add> }
<add> catch (Exception e) {
<add> throwException("Could not set property: " + property + ". Reason: ", e);
<add> }
<add> }
<add>
<add> public Object invokeMethod(String method, Object arguments) {
<add> Object[] argArray;
<add> if (arguments instanceof Object[]) {
<add> argArray = (Object[]) arguments;
<add> } else {
<add> argArray = new Object[]{arguments};
<add> }
<add> // Locate the specific method based on the name and number of parameters
<add> String operationKey = createOperationKey(method, argArray.length);
<add> String[] signature = operations.get(operationKey);
<add>
<add> if (signature != null) {
<add> try {
<add> return server.invoke(name, method, argArray, signature);
<add> }
<add> catch (MBeanException e) {
<add> throwExceptionWithTarget("Could not invoke method: " + method + ". Reason: ", e);
<add> }
<add> catch (Exception e) {
<add> throwException("Could not invoke method: " + method + ". Reason: ", e);
<add> }
<add> return null;
<add> } else {
<add> return super.invokeMethod(method, arguments);
<add> }
<add> }
<add>
<add> protected String[] createSignature(MBeanOperationInfo info) {
<add> MBeanParameterInfo[] params = info.getSignature();
<add> String[] answer = new String[params.length];
<add> for (int i = 0; i < params.length; i++) {
<add> answer[i] = params[i].getType();
<add> }
<add> return answer;
<add> }
<add>
<add> /**
<add> * Construct a simple key based on the method name and the number of parameters
<add> *
<add> * @param operation - the mbean operation name
<add> * @param params - the number of parameters the operation supports
<add> * @return simple unique identifier for a method
<add> */
<add> protected String createOperationKey(String operation, int params) {
<add> // This could be changed to support some hash of the parameter types, etc.
<add> // but should distinguish between reordered params while allowing normal
<add> // type coercions to be honored
<add> return operation + "_" + params;
<add> }
<add>
<add> /**
<add> * List of the names of each of the attributes on the MBean
<add> *
<add> * @return list of attribute names
<add> */
<add> public Collection<String> listAttributeNames() {
<add> List<String> list = new ArrayList<String>();
<add> try {
<add> MBeanAttributeInfo[] attrs = beanInfo.getAttributes();
<add> for (MBeanAttributeInfo attr : attrs) {
<add> list.add(attr.getName());
<add> }
<add> } catch (Exception e) {
<add> throwException("Could not list attribute names. Reason: ", e);
<add> }
<add> return list;
<add> }
<add>
<add> /**
<add> * The values of each of the attributes on the MBean
<add> *
<add> * @return list of values of each attribute
<add> */
<add> public List<String> listAttributeValues() {
<add> List<String> list = new ArrayList<String>();
<add> Collection<String> names = listAttributeNames();
<add> for (String name : names) {
<add> try {
<add> Object val = this.getProperty(name);
<add> if (val != null) {
<add> list.add(name + " : " + val.toString());
<add> }
<add> } catch (Exception e) {
<add> throwException("Could not list attribute values. Reason: ", e);
<add> }
<add> }
<add> return list;
<add> }
<add>
<add> /**
<add> * List of string representations of all of the attributes on the MBean.
<add> *
<add> * @return list of descriptions of each attribute on the mbean
<add> */
<add> public Collection<String> listAttributeDescriptions() {
<add> List<String> list = new ArrayList<String>();
<add> try {
<add> MBeanAttributeInfo[] attrs = beanInfo.getAttributes();
<add> for (MBeanAttributeInfo attr : attrs) {
<add> list.add(describeAttribute(attr));
<add> }
<add> } catch (Exception e) {
<add> throwException("Could not list attribute descriptions. Reason: ", e);
<add> }
<add> return list;
<add> }
<add>
<add> /**
<add> * Description of the specified attribute name.
<add> *
<add> * @param attr - the attribute
<add> * @return String the description
<add> */
<add> protected String describeAttribute(MBeanAttributeInfo attr) {
<add> StringBuilder buf = new StringBuilder();
<add> buf.append("(");
<add> if (attr.isReadable()) {
<add> buf.append("r");
<add> }
<add> if (attr.isWritable()) {
<add> buf.append("w");
<add> }
<add> buf.append(") ")
<add> .append(attr.getType())
<add> .append(" ")
<add> .append(attr.getName());
<add> return buf.toString();
<add> }
<add>
<add> /**
<add> * Description of the specified attribute name.
<add> *
<add> * @param attributeName - stringified name of the attribute
<add> * @return the description
<add> */
<add> public String describeAttribute(String attributeName) {
<add> String ret = "Attribute not found";
<add> try {
<add> MBeanAttributeInfo[] attributes = beanInfo.getAttributes();
<add> for (MBeanAttributeInfo attribute : attributes) {
<add> if (attribute.getName().equals(attributeName)) {
<add> return describeAttribute(attribute);
<add> }
<add> }
<add> } catch (Exception e) {
<add> throwException("Could not describe attribute '" + attributeName + "'. Reason: ", e);
<add> }
<add> return ret;
<add> }
<add>
<add> /**
<add> * Names of all the operations available on the MBean.
<add> *
<add> * @return all the operations on the MBean
<add> */
<add> public Collection<String> listOperationNames() {
<add> List<String> list = new ArrayList<String>();
<add> try {
<add> MBeanOperationInfo[] operations = beanInfo.getOperations();
<add> for (MBeanOperationInfo operation : operations) {
<add> list.add(operation.getName());
<add> }
<add> } catch (Exception e) {
<add> throwException("Could not list operation names. Reason: ", e);
<add> }
<add> return list;
<add> }
<add>
<add> /**
<add> * Description of all of the operations available on the MBean.
<add> *
<add> * @return full description of each operation on the MBean
<add> */
<add> public Collection<String> listOperationDescriptions() {
<add> List<String> list = new ArrayList<String>();
<add> try {
<add> MBeanOperationInfo[] operations = beanInfo.getOperations();
<add> for (MBeanOperationInfo operation : operations) {
<add> list.add(describeOperation(operation));
<add> }
<add> } catch (Exception e) {
<add> throwException("Could not list operation descriptions. Reason: ", e);
<add> }
<add> return list;
<add> }
<add>
<add> /**
<add> * Get the description of the specified operation. This returns a Collection since
<add> * operations can be overloaded and one operationName can have multiple forms.
<add> *
<add> * @param operationName the name of the operation to describe
<add> * @return Collection of operation description
<add> */
<add> public List<String> describeOperation(String operationName) {
<add> List<String> list = new ArrayList<String>();
<add> try {
<add> MBeanOperationInfo[] operations = beanInfo.getOperations();
<add> for (MBeanOperationInfo operation : operations) {
<add> if (operation.getName().equals(operationName)) {
<add> list.add(describeOperation(operation));
<add> }
<add> }
<add> } catch (Exception e) {
<add> throwException("Could not describe operations matching name '" + operationName + "'. Reason: ", e);
<add> }
<add> return list;
<add> }
<add>
<add> /**
<add> * Description of the operation.
<add> *
<add> * @param operation the operation to describe
<add> * @return pretty-printed description
<add> */
<add> protected String describeOperation(MBeanOperationInfo operation) {
<add> StringBuilder buf = new StringBuilder();
<add> buf.append(operation.getReturnType())
<add> .append(" ")
<add> .append(operation.getName())
<add> .append("(");
<add>
<add> MBeanParameterInfo[] params = operation.getSignature();
<add> for (int j = 0; j < params.length; j++) {
<add> MBeanParameterInfo param = params[j];
<add> if (j != 0) {
<add> buf.append(", ");
<add> }
<add> buf.append(param.getType())
<add> .append(" ")
<add> .append(param.getName());
<add> }
<add> buf.append(")");
<add> return buf.toString();
<add> }
<add>
<add> /**
<add> * Return an end user readable representation of the underlying MBean
<add> *
<add> * @return the user readable description
<add> */
<add> public String toString() {
<add> StringBuilder buf = new StringBuilder();
<add> buf.append("MBean Name:")
<add> .append("\n ")
<add> .append(name.getCanonicalName())
<add> .append("\n ");
<add> if (!listAttributeDescriptions().isEmpty()) {
<add> buf.append("\nAttributes:");
<add> for (String attrDesc : listAttributeDescriptions()) {
<add> buf.append("\n ").append(attrDesc);
<add> }
<add> }
<add> if (!listOperationDescriptions().isEmpty()) {
<add> buf.append("\nOperations:");
<add> for (String attrDesc : listOperationDescriptions()) {
<add> buf.append("\n ").append(attrDesc);
<add> }
<add> }
<add> return buf.toString();
<add> }
<add>
<add> private void throwException(String m, Exception e) {
<add> if (!ignoreErrors) {
<add> throw new GroovyRuntimeException(m + e, e);
<add> }
<add> }
<add>
<add> private void throwExceptionWithTarget(String m, MBeanException e) {
<add> if (!ignoreErrors) {
<add> throw new GroovyRuntimeException(m + e, e.getTargetException());
<add> }
<add> }
<add>} |
|
Java | apache-2.0 | 5b7fba2e96943b525b03b6752518e223dc202fe2 | 0 | HDXconnor/Risque,HDXconnor/Risque | /*
* 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 game.tests;
import game.logic.Dice;
import game.objects.AttackOutcome;
import game.objects.exceptions.DiceException;
import java.util.ArrayList;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
*
* @author Simeon
*/
public class DiceTest {
ArrayList<Integer> attackerDice;
ArrayList<Integer> defenderDice;
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
attackerDice = null;
defenderDice = null;
}
@Test(expected = DiceException.class)
public void testNumberOfDice_0_0() throws DiceException {
Dice.Roll(0, 0);
}
@Test(expected = DiceException.class)
public void testNumberOfDice_9_1() throws DiceException {
Dice.Roll(9, 1);
}
@Test(expected = DiceException.class)
public void testNumberOfDice_1_9() throws DiceException {
Dice.Roll(1, 9);
}
@Test
public void testDiceRolled() throws DiceException {
int nAttackerDice = 3;
int nDefenderDice = 2;
AttackOutcome ao = Dice.Roll(nAttackerDice, nDefenderDice);
assertTrue(ao.getAttackerDice().size() == nAttackerDice);
assertTrue(ao.getDefenderDice().size() == nDefenderDice);
}
@Test
public void testTroopLosses() throws DiceException {
AttackOutcome ao = Dice.Roll(3, 2);
attackerDice = ao.getAttackerDice();
defenderDice = ao.getDefenderDice();
int attackerLosses = 0;
int defenderLosses = 0;
for (int i = 0; i < 2; i++) {
if (attackerDice.get(i) > defenderDice.get(i)) {
defenderLosses++;
} else {
attackerLosses++;
}
}
assertTrue(ao.getTroopsLostByAttacker() == attackerLosses);
assertTrue(ao.getTroopsLostByDefender() == defenderLosses);
}
}
| test/game/tests/DiceTest.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 game.tests;
import game.logic.Dice;
import game.objects.AttackOutcome;
import game.objects.exceptions.DiceException;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
*
* @author Simeon
*/
public class DiceTest {
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test(expected = DiceException.class)
public void testDiceException() throws DiceException {
Dice.Roll(0, 0);
}
}
| did more dice tests
| test/game/tests/DiceTest.java | did more dice tests | <ide><path>est/game/tests/DiceTest.java
<ide> import game.logic.Dice;
<ide> import game.objects.AttackOutcome;
<ide> import game.objects.exceptions.DiceException;
<add>import java.util.ArrayList;
<ide> import org.junit.After;
<ide> import org.junit.AfterClass;
<ide> import static org.junit.Assert.assertTrue;
<ide> * @author Simeon
<ide> */
<ide> public class DiceTest {
<add>
<add> ArrayList<Integer> attackerDice;
<add> ArrayList<Integer> defenderDice;
<ide>
<ide> @BeforeClass
<ide> public static void setUpClass() throws Exception {
<ide>
<ide> @After
<ide> public void tearDown() throws Exception {
<add> attackerDice = null;
<add> defenderDice = null;
<ide> }
<ide>
<ide> @Test(expected = DiceException.class)
<del> public void testDiceException() throws DiceException {
<add> public void testNumberOfDice_0_0() throws DiceException {
<ide> Dice.Roll(0, 0);
<ide> }
<ide>
<add> @Test(expected = DiceException.class)
<add> public void testNumberOfDice_9_1() throws DiceException {
<add> Dice.Roll(9, 1);
<add> }
<add>
<add> @Test(expected = DiceException.class)
<add> public void testNumberOfDice_1_9() throws DiceException {
<add> Dice.Roll(1, 9);
<add> }
<add>
<add> @Test
<add> public void testDiceRolled() throws DiceException {
<add> int nAttackerDice = 3;
<add> int nDefenderDice = 2;
<add> AttackOutcome ao = Dice.Roll(nAttackerDice, nDefenderDice);
<add> assertTrue(ao.getAttackerDice().size() == nAttackerDice);
<add> assertTrue(ao.getDefenderDice().size() == nDefenderDice);
<add> }
<add>
<add> @Test
<add> public void testTroopLosses() throws DiceException {
<add> AttackOutcome ao = Dice.Roll(3, 2);
<add> attackerDice = ao.getAttackerDice();
<add> defenderDice = ao.getDefenderDice();
<add> int attackerLosses = 0;
<add> int defenderLosses = 0;
<add> for (int i = 0; i < 2; i++) {
<add> if (attackerDice.get(i) > defenderDice.get(i)) {
<add> defenderLosses++;
<add> } else {
<add> attackerLosses++;
<add> }
<add> }
<add> assertTrue(ao.getTroopsLostByAttacker() == attackerLosses);
<add> assertTrue(ao.getTroopsLostByDefender() == defenderLosses);
<add> }
<add>
<ide> } |
|
Java | mit | 5509e008400fb85c4f8789b8df883d958ba5b8d1 | 0 | TobleMiner/MF-Canary | package TobleMiner.MineFight.GameEngine.Match.Spawning;
import java.util.Random;
import org.bukkit.Location;
import org.bukkit.entity.Projectile;
import org.bukkit.util.Vector;
import TobleMiner.MineFight.Main;
import TobleMiner.MineFight.Debug.Debugger;
import TobleMiner.MineFight.GameEngine.Match.Match;
import TobleMiner.MineFight.GameEngine.Player.PVPPlayer;
import TobleMiner.MineFight.Protection.Area3D;
import TobleMiner.MineFight.Util.Geometry.Line3D;
public class Spawnengine
{
private Match match;
private Random rand = new Random();
public Spawnengine(Match m)
{
this.match = m;
}
public Location findSafeSpawn(Location base, PVPPlayer player)
{
if(!Main.gameEngine.configuration.isSpawnengineEnabled(this.match.getWorld()))
return base;
Debugger.writeDebugOut("Spawnengine active");
double minDist = Main.gameEngine.configuration.minEnemySpawnDistance(this.match.getWorld());
Debugger.writeDebugOut(String.format("Min spawn dist: %.2f", minDist));
double smallestLOSangle = Main.gameEngine.configuration.smallestLineOfSightAngle(this.match.getWorld());
double maxLOScomputationDistance = Main.gameEngine.configuration.maxLOScomputationDistance(this.match.getWorld());
double minProjDist = Main.gameEngine.configuration.minProjectileDist(this.match.getWorld());
boolean safe = false;
double radius = 0d;
Location current = base.clone();
while(!safe)
{
safe = true;
for(PVPPlayer p : this.match.getPlayers())
{
current = base.clone();
double rndAngle = rand.nextDouble() * 2 * Math.PI;
current.add(new Vector(radius * Math.sin(rndAngle), 0d, radius * Math.cos(rndAngle)));
if(p.getTeam() != player.getTeam() && p.isSpawned())
{
Vector vect = new Vector(minDist, minDist, minDist);
if(Main.gameEngine.configuration.isMinEnemySpawnDistance2D(this.match.getWorld()))
vect.setY(0d);
Area3D dzone = new Area3D(p.thePlayer.getLocation().clone().add(vect), p.thePlayer.getLocation().clone().add(vect.clone().multiply(-1d)));
Debugger.writeDebugOut(String.format("Area: (%s) Location: [%d, %d, %d]", dzone.toString(), current.getBlockX(), current.getBlockY(), current.getBlockZ()));
if(dzone.isCoordInsideRegion(current))
{
safe = false;
Debugger.writeDebugOut(String.format("Spawn not safe for '%s' due to near enemy player '%s' Radius: %.2f", player.thePlayer.getName(), p.thePlayer.getName(), radius));
break;
}
if(safe && radius <= maxLOScomputationDistance)
{
Vector look = p.thePlayer.getLocation().getDirection();
Vector lookat = p.thePlayer.getLocation().clone().subtract(current).toVector();
double lookAngle = look.angle(lookat) * 180d * Math.PI;
if(lookAngle < smallestLOSangle)
{
safe = false;
Debugger.writeDebugOut(String.format("Spawn not safe for '%s' due to look from enemy player '%s' Radius: %.2f Look-angle: %.2f°", player.thePlayer.getName(), p.thePlayer.getName(), radius, lookAngle));
break;
}
}
if(safe)
{
for(Area3D dangerZone : match.dangerZones)
{
if(dangerZone.isCoordInsideRegion(current))
{
safe = false;
break;
}
}
}
if(safe)
{
for(Projectile proj : match.allProjectiles)
{
Location projLoc = proj.getLocation();
Vector projDir = proj.getVelocity();
Line3D path = new Line3D(projLoc, projDir);
if(path.getSmallestDist(current) < minProjDist)
{
safe = false;
break;
}
}
}
}
}
radius += 1d;
}
return current;
}
}
| src/TobleMiner/MineFight/GameEngine/Match/Spawning/Spawnengine.java | package TobleMiner.MineFight.GameEngine.Match.Spawning;
import java.util.Random;
import org.bukkit.Location;
import org.bukkit.entity.Projectile;
import org.bukkit.util.Vector;
import TobleMiner.MineFight.Main;
import TobleMiner.MineFight.Debug.Debugger;
import TobleMiner.MineFight.GameEngine.Match.Match;
import TobleMiner.MineFight.GameEngine.Player.PVPPlayer;
import TobleMiner.MineFight.Protection.Area3D;
import TobleMiner.MineFight.Util.Geometry.Line3D;
public class Spawnengine
{
private Match match;
private Random rand = new Random();
public Spawnengine(Match m)
{
this.match = m;
}
public Location findSafeSpawn(Location base, PVPPlayer player)
{
if(!Main.gameEngine.configuration.isSpawnengineEnabled(this.match.getWorld()))
return base;
Debugger.writeDebugOut("Spawnengine active");
double minDist = Main.gameEngine.configuration.minEnemySpawnDistance(this.match.getWorld());
Debugger.writeDebugOut(String.format("Min spawn dist: %.2f", minDist));
double smallestLOSangle = Main.gameEngine.configuration.smallestLineOfSightAngle(this.match.getWorld());
double maxLOScomputationDistance = Main.gameEngine.configuration.maxLOScomputationDistance(this.match.getWorld());
double minProjDist = Main.gameEngine.configuration.minProjectileDist(this.match.getWorld());
boolean safe = false;
double radius = 0d;
Location current = base.clone();
while(!safe)
{
safe = true;
for(PVPPlayer p : this.match.getPlayers())
{
current = base.clone();
double rndAngle = rand.nextDouble() * 2 * Math.PI;
current.add(new Vector(radius * Math.sin(rndAngle), 0d, radius * Math.cos(rndAngle)));
if(p.getTeam() != player.getTeam() && p.isSpawned())
{
Vector vect = new Vector(minDist, minDist, minDist);
if(Main.gameEngine.configuration.isMinEnemySpawnDistance2D(this.match.getWorld()))
vect.setY(0d);
Area3D dzone = new Area3D(p.thePlayer.getLocation().clone().add(vect), p.thePlayer.getLocation().clone().add(vect.clone().multiply(-1d)));
Debugger.writeDebugOut(String.format("Area: (%s) Location: [%d, %d, %d]", dzone.toString(), current.getBlockX(), current.getBlockY(), current.getBlockZ()));
if(dzone.isCoordInsideRegion(current))
{
safe = false;
Debugger.writeDebugOut(String.format("Spawn not safe for '%s' due to near enemy player '%s' Radius: %.2f", player.thePlayer.getName(), p.thePlayer.getName(), radius));
}
if(safe && radius <= maxLOScomputationDistance)
{
Vector look = p.thePlayer.getLocation().getDirection();
Vector lookat = p.thePlayer.getLocation().clone().subtract(current).toVector();
double lookAngle = look.angle(lookat) * 180d * Math.PI;
if(lookAngle < smallestLOSangle)
{
safe = false;
Debugger.writeDebugOut(String.format("Spawn not safe for '%s' due to look from enemy player '%s' Radius: %.2f Look-angle: %.2f°", player.thePlayer.getName(), p.thePlayer.getName(), radius, lookAngle));
}
}
if(safe)
{
for(Area3D dangerZone : match.dangerZones)
{
if(dangerZone.isCoordInsideRegion(current))
safe = false;
}
}
if(safe)
{
for(Projectile proj : match.allProjectiles)
{
Location projLoc = proj.getLocation();
Vector projDir = proj.getVelocity();
Line3D path = new Line3D(projLoc, projDir);
if(path.getSmallestDist(current) < minProjDist)
safe = false;
}
}
}
}
radius += 1d;
}
return current;
}
}
| Increased spawnengine-performance
| src/TobleMiner/MineFight/GameEngine/Match/Spawning/Spawnengine.java | Increased spawnengine-performance | <ide><path>rc/TobleMiner/MineFight/GameEngine/Match/Spawning/Spawnengine.java
<ide> {
<ide> safe = false;
<ide> Debugger.writeDebugOut(String.format("Spawn not safe for '%s' due to near enemy player '%s' Radius: %.2f", player.thePlayer.getName(), p.thePlayer.getName(), radius));
<add> break;
<ide> }
<ide> if(safe && radius <= maxLOScomputationDistance)
<ide> {
<ide> {
<ide> safe = false;
<ide> Debugger.writeDebugOut(String.format("Spawn not safe for '%s' due to look from enemy player '%s' Radius: %.2f Look-angle: %.2f°", player.thePlayer.getName(), p.thePlayer.getName(), radius, lookAngle));
<add> break;
<ide> }
<ide> }
<ide> if(safe)
<ide> for(Area3D dangerZone : match.dangerZones)
<ide> {
<ide> if(dangerZone.isCoordInsideRegion(current))
<add> {
<ide> safe = false;
<add> break;
<add> }
<ide> }
<ide> }
<ide> if(safe)
<ide> Vector projDir = proj.getVelocity();
<ide> Line3D path = new Line3D(projLoc, projDir);
<ide> if(path.getSmallestDist(current) < minProjDist)
<add> {
<ide> safe = false;
<add> break;
<add> }
<ide> }
<ide> }
<ide> } |
|
JavaScript | mit | 94a77f5b4da1d91bb1ed277bd30b98ae90db2410 | 0 | nazaninreihani/binary-next-gen,binary-com/binary-next-gen,nazaninreihani/binary-next-gen,binary-com/binary-next-gen,binary-com/binary-next-gen,nazaninreihani/binary-next-gen | /* eslint-disable */
'use strict';
(function init() {
// clean stale data in local storage
localStorage.removeItem('assets');
localStorage.removeItem('settings');
var defaultConfig = {
language: 'EN',
theme: 'light',
apiUrl: 'wss://ws.binaryws.com/websockets/v3',
accounts: []
};
function parseOAuthResponse(responseUrl) {
var urlParts = responseUrl.split('?');
if (urlParts.length !== 2) {
throw new Error('Not a valid url');
}
var objURL = {};
responseUrl.replace(
new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
function( $0, $1, $2, $3 ){
objURL[ $1 ] = $3;
}
);
var accounts = [];
for(var i = 1;; i++) {
var account = objURL['acct' + i],
token = objURL['token' + i],
currency = objURL['cur' + i];
if (!account || !token) break;
accounts.push({ account: account, token: token, currency : currency || '', });
}
var sortedAccounts = accounts.sort((a,b) => b.currency.length - a.currency.length);
return sortedAccounts;
}
function readConfig() {
try {
window.BinaryBoot = JSON.parse(localStorage.getItem('boot')) || defaultConfig;
} catch (e) {
window.BinaryBoot = defaultConfig;
window.console.log('Error while initializing', e);
}
}
function parseUrlAndStoreAccountInfo(url) {
if (~url.indexOf('acct1')) {
var accounts = parseOAuthResponse(url);
window.BinaryBoot.accounts = accounts;
try {
localStorage.setItem('boot', JSON.stringify(window.BinaryBoot));
localStorage.setItem('account', JSON.stringify({ token: accounts[0].token }));
} catch (e) {
window.console.log('Error while saving boot config', e);
}
}
}
readConfig();
parseUrlAndStoreAccountInfo(window.location.href);
window.BinaryBoot.parseUrl = parseOAuthResponse;
if(window.cordova) {
window.BinaryBoot.appId = 1006;
} else if(window.electron) {
window.BinaryBoot.appId = 1306;
} else if (/localhost:/g.test(window.location.href)) {
window.BinaryBoot.appId = 3588;
} else if (/arnabk.github.io:/g.test(window.location.href)) {
window.BinaryBoot.appId = 3604;
} else if (/beta/g.test(window.location.href)) {
window.BinaryBoot.appId = 4343; //This is for BETA release
} else {
window.BinaryBoot.appId = 1001; //This is for PROD release
}
var lang = window.BinaryBoot.language;
var redirectIndex = window.location.href.indexOf('?');
if (~redirectIndex) {
if (window.location.href.indexOf('/beta') === -1) {
window.location.href = '/';
} else {
window.location.href = '/beta';
}
}
if (!window.BinaryBoot.apiUrl) {
window.BinaryBoot.apiUrl = defaultConfig.apiUrl;
}
const testConfig = localStorage.getItem('test-config');
if(testConfig) {
try {
const config = JSON.parse(testConfig) || { };
window.BinaryBoot.appId = config.appId || window.BinaryBoot.appId;;
window.BinaryBoot.apiUrl = config.apiUrl || window.BinaryBoot.apiUrl;;
} catch (e) { }
}
window.BinaryBoot.connection = new WebSocket(window.BinaryBoot.apiUrl + '?app_id=' + window.BinaryBoot.appId + '&l=' + lang);
})();
| www/boot.js | /* eslint-disable */
'use strict';
(function init() {
// clean stale data in local storage
localStorage.removeItem('assets');
localStorage.removeItem('settings');
var defaultConfig = {
language: 'EN',
theme: 'light',
accounts: []
};
function parseOAuthResponse(responseUrl) {
var urlParts = responseUrl.split('?');
if (urlParts.length !== 2) {
throw new Error('Not a valid url');
}
var objURL = {};
responseUrl.replace(
new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
function( $0, $1, $2, $3 ){
objURL[ $1 ] = $3;
}
);
var accounts = [];
for(var i = 1;; i++) {
var account = objURL['acct' + i],
token = objURL['token' + i],
currency = objURL['cur' + i];
if (!account || !token) break;
accounts.push({ account: account, token: token, currency : currency || '', });
}
var sortedAccounts = accounts.sort((a,b) => b.currency.length - a.currency.length);
return sortedAccounts;
}
function readConfig() {
try {
window.BinaryBoot = JSON.parse(localStorage.getItem('boot')) || defaultConfig;
} catch (e) {
window.BinaryBoot = defaultConfig;
window.console.log('Error while initializing', e);
}
}
function parseUrlAndStoreAccountInfo(url) {
if (~url.indexOf('acct1')) {
var accounts = parseOAuthResponse(url);
window.BinaryBoot.accounts = accounts;
try {
localStorage.setItem('boot', JSON.stringify(window.BinaryBoot));
localStorage.setItem('account', JSON.stringify({ token: accounts[0].token }));
} catch (e) {
window.console.log('Error while saving boot config', e);
}
}
}
var apiUrl = 'wss://ws.binaryws.com/websockets/v3';
readConfig();
parseUrlAndStoreAccountInfo(window.location.href);
window.BinaryBoot.parseUrl = parseOAuthResponse;
if(window.cordova) {
window.BinaryBoot.appId = 1006;
} else if(window.electron) {
window.BinaryBoot.appId = 1306;
} else if (/localhost:/g.test(window.location.href)) {
window.BinaryBoot.appId = 3588;
} else if (/arnabk.github.io:/g.test(window.location.href)) {
window.BinaryBoot.appId = 3604;
} else if (/beta/g.test(window.location.href)) {
window.BinaryBoot.appId = 4343; //This is for BETA release
} else {
window.BinaryBoot.appId = 1001; //This is for PROD release
}
var lang = window.BinaryBoot.language;
var redirectIndex = window.location.href.indexOf('?');
if (~redirectIndex) {
if (window.location.href.indexOf('/beta') === -1) {
window.location.href = '/';
} else {
window.location.href = '/beta';
}
}
window.BinaryBoot.connection = new WebSocket(apiUrl + '?app_id=' + window.BinaryBoot.appId + '&l=' + lang);
})();
| Provide a way for QA to change apiUrl & appId
| www/boot.js | Provide a way for QA to change apiUrl & appId | <ide><path>ww/boot.js
<ide> var defaultConfig = {
<ide> language: 'EN',
<ide> theme: 'light',
<add> apiUrl: 'wss://ws.binaryws.com/websockets/v3',
<ide> accounts: []
<ide> };
<ide>
<ide> }
<ide>
<ide>
<del> var apiUrl = 'wss://ws.binaryws.com/websockets/v3';
<ide>
<ide> readConfig();
<ide> parseUrlAndStoreAccountInfo(window.location.href);
<ide> }
<ide> }
<ide>
<del> window.BinaryBoot.connection = new WebSocket(apiUrl + '?app_id=' + window.BinaryBoot.appId + '&l=' + lang);
<add> if (!window.BinaryBoot.apiUrl) {
<add> window.BinaryBoot.apiUrl = defaultConfig.apiUrl;
<add> }
<add> const testConfig = localStorage.getItem('test-config');
<add> if(testConfig) {
<add> try {
<add> const config = JSON.parse(testConfig) || { };
<add> window.BinaryBoot.appId = config.appId || window.BinaryBoot.appId;;
<add> window.BinaryBoot.apiUrl = config.apiUrl || window.BinaryBoot.apiUrl;;
<add> } catch (e) { }
<add> }
<add>
<add> window.BinaryBoot.connection = new WebSocket(window.BinaryBoot.apiUrl + '?app_id=' + window.BinaryBoot.appId + '&l=' + lang);
<ide> })(); |
|
Java | mit | 043b85b3b8dd2b1f1475b7dc45d1141ee8b3ac2f | 0 | visualing/VisualingVideoPlayer,visualing/VisualingVideoPlayer,lipangit/JiaoZiVideoPlayer,lipangit/jiecaovideoplayer,lipangit/JiaoZiVideoPlayer | package fm.jiecao.jcvideoplayer_lib;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.provider.Settings;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by Nathen on 16/7/30.
*/
public abstract class JCVideoPlayer extends FrameLayout implements View.OnClickListener, SeekBar.OnSeekBarChangeListener, View.OnTouchListener {
public static final String TAG = "JieCaoVideoPlayer";
public static boolean ACTION_BAR_EXIST = true;
public static boolean TOOL_BAR_EXIST = true;
public static int FULLSCREEN_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_SENSOR;
public static int NORMAL_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
public static boolean SAVE_PROGRESS = true;
public static boolean WIFI_TIP_DIALOG_SHOWED = false;
public static final int FULLSCREEN_ID = 33797;
public static final int TINY_ID = 33798;
public static final int THRESHOLD = 80;
public static final int FULL_SCREEN_NORMAL_DELAY = 300;
public static long CLICK_QUIT_FULLSCREEN_TIME = 0;
public static final int SCREEN_LAYOUT_NORMAL = 0;
public static final int SCREEN_LAYOUT_LIST = 1;
public static final int SCREEN_WINDOW_FULLSCREEN = 2;
public static final int SCREEN_WINDOW_TINY = 3;
public static final int CURRENT_STATE_NORMAL = 0;
public static final int CURRENT_STATE_PREPARING = 1;
public static final int CURRENT_STATE_PLAYING = 2;
public static final int CURRENT_STATE_PLAYING_BUFFERING_START = 3;
public static final int CURRENT_STATE_PAUSE = 5;
public static final int CURRENT_STATE_AUTO_COMPLETE = 6;
public static final int CURRENT_STATE_ERROR = 7;
public static int BACKUP_PLAYING_BUFFERING_STATE = -1;
public int currentState = -1;
public int currentScreen = -1;
public boolean loop = false;
public Map<String, String> headData;
public String url = "";
public Object[] objects = null;
public int seekToInAdvance = 0;
public ImageView startButton;
public SeekBar progressBar;
public ImageView fullscreenButton;
public TextView currentTimeTextView, totalTimeTextView;
public ViewGroup textureViewContainer;
public ViewGroup topContainer, bottomContainer;
protected static JCUserAction JC_USER_EVENT;
protected static Timer UPDATE_PROGRESS_TIMER;
protected int mScreenWidth;
protected int mScreenHeight;
protected AudioManager mAudioManager;
protected Handler mHandler;
protected ProgressTimerTask mProgressTimerTask;
protected boolean mTouchingProgressBar;
protected float mDownX;
protected float mDownY;
protected boolean mChangeVolume;
protected boolean mChangePosition;
protected boolean mChangeBrightness;
protected int mGestureDownPosition;
protected int mGestureDownVolume;
protected float mGestureDownBrightness;
protected int mSeekTimePosition;
public JCVideoPlayer(Context context) {
super(context);
init(context);
}
public JCVideoPlayer(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public void init(Context context) {
View.inflate(context, getLayoutId(), this);
startButton = (ImageView) findViewById(R.id.start);
fullscreenButton = (ImageView) findViewById(R.id.fullscreen);
progressBar = (SeekBar) findViewById(R.id.bottom_seek_progress);
currentTimeTextView = (TextView) findViewById(R.id.current);
totalTimeTextView = (TextView) findViewById(R.id.total);
bottomContainer = (ViewGroup) findViewById(R.id.layout_bottom);
textureViewContainer = (ViewGroup) findViewById(R.id.surface_container);
topContainer = (ViewGroup) findViewById(R.id.layout_top);
startButton.setOnClickListener(this);
fullscreenButton.setOnClickListener(this);
progressBar.setOnSeekBarChangeListener(this);
bottomContainer.setOnClickListener(this);
textureViewContainer.setOnClickListener(this);
textureViewContainer.setOnTouchListener(this);
mScreenWidth = getContext().getResources().getDisplayMetrics().widthPixels;
mScreenHeight = getContext().getResources().getDisplayMetrics().heightPixels;
mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
mHandler = new Handler();
}
public void setUp(String url, int screen, Object... objects) {
if (!TextUtils.isEmpty(this.url) && TextUtils.equals(this.url, url)) {
return;
}
this.url = url;
this.objects = objects;
this.currentScreen = screen;
this.headData = null;
setUiWitStateAndScreen(CURRENT_STATE_NORMAL);
}
@Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.start) {
Log.i(TAG, "onClick start [" + this.hashCode() + "] ");
if (TextUtils.isEmpty(url)) {
Toast.makeText(getContext(), getResources().getString(R.string.no_url), Toast.LENGTH_SHORT).show();
return;
}
if (currentState == CURRENT_STATE_NORMAL || currentState == CURRENT_STATE_ERROR) {
if (!url.startsWith("file") && !JCUtils.isWifiConnected(getContext()) && !WIFI_TIP_DIALOG_SHOWED) {
showWifiDialog();
return;
}
prepareMediaPlayer();
onEvent(currentState != CURRENT_STATE_ERROR ? JCUserAction.ON_CLICK_START_ICON : JCUserAction.ON_CLICK_START_ERROR);
} else if (currentState == CURRENT_STATE_PLAYING) {
onEvent(JCUserAction.ON_CLICK_PAUSE);
Log.d(TAG, "pauseVideo [" + this.hashCode() + "] ");
JCMediaManager.instance().mediaPlayer.pause();
setUiWitStateAndScreen(CURRENT_STATE_PAUSE);
} else if (currentState == CURRENT_STATE_PAUSE) {
onEvent(JCUserAction.ON_CLICK_RESUME);
JCMediaManager.instance().mediaPlayer.start();
setUiWitStateAndScreen(CURRENT_STATE_PLAYING);
} else if (currentState == CURRENT_STATE_AUTO_COMPLETE) {
onEvent(JCUserAction.ON_CLICK_START_AUTO_COMPLETE);
prepareMediaPlayer();
}
} else if (i == R.id.fullscreen) {
Log.i(TAG, "onClick fullscreen [" + this.hashCode() + "] ");
if (currentState == CURRENT_STATE_AUTO_COMPLETE) return;
if (currentScreen == SCREEN_WINDOW_FULLSCREEN) {
//quit fullscreen
backPress();
} else {
Log.d(TAG, "toFullscreenActivity [" + this.hashCode() + "] ");
onEvent(JCUserAction.ON_ENTER_FULLSCREEN);
startWindowFullscreen();
}
} else if (i == R.id.surface_container && currentState == CURRENT_STATE_ERROR) {
Log.i(TAG, "onClick surfaceContainer State=Error [" + this.hashCode() + "] ");
prepareMediaPlayer();
}
}
public void prepareMediaPlayer() {
JCVideoPlayerManager.completeAll();
Log.d(TAG, "prepareMediaPlayer [" + this.hashCode() + "] ");
initTextureView();
addTextureView();
AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
mAudioManager.requestAudioFocus(onAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
JCUtils.scanForActivity(getContext()).getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
JCMediaManager.CURRENT_PLAYING_URL = url;
JCMediaManager.CURRENT_PLING_LOOP = loop;
JCMediaManager.MAP_HEADER_DATA = headData;
setUiWitStateAndScreen(CURRENT_STATE_PREPARING);
JCVideoPlayerManager.setFirstFloor(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
float x = event.getX();
float y = event.getY();
int id = v.getId();
if (id == R.id.surface_container) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i(TAG, "onTouch surfaceContainer actionDown [" + this.hashCode() + "] ");
mTouchingProgressBar = true;
mDownX = x;
mDownY = y;
mChangeVolume = false;
mChangePosition = false;
mChangeBrightness = false;
break;
case MotionEvent.ACTION_MOVE:
Log.i(TAG, "onTouch surfaceContainer actionMove [" + this.hashCode() + "] ");
float deltaX = x - mDownX;
float deltaY = y - mDownY;
float absDeltaX = Math.abs(deltaX);
float absDeltaY = Math.abs(deltaY);
if (currentScreen == SCREEN_WINDOW_FULLSCREEN) {
if (!mChangePosition && !mChangeVolume && !mChangeBrightness) {
if (absDeltaX > THRESHOLD || absDeltaY > THRESHOLD) {
cancelProgressTimer();
if (absDeltaX >= THRESHOLD) {
// 全屏模式下的CURRENT_STATE_ERROR状态下,不响应进度拖动事件.
// 否则会因为mediaplayer的状态非法导致App Crash
if (currentState != CURRENT_STATE_ERROR) {
mChangePosition = true;
mGestureDownPosition = getCurrentPositionWhenPlaying();
}
} else {
//如果y轴滑动距离超过设置的处理范围,那么进行滑动事件处理
if (mDownX < mScreenWidth * 0.5f) {//左侧改变亮度
mChangeBrightness = true;
try {
mGestureDownBrightness = Settings.System.getInt(getContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
System.out.println("当前亮度 " + mGestureDownBrightness);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
} else {//右侧改变声音
mChangeVolume = true;
mGestureDownVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
}
}
}
}
}
if (mChangePosition) {
int totalTimeDuration = getDuration();
mSeekTimePosition = (int) (mGestureDownPosition + deltaX * totalTimeDuration / mScreenWidth);
if (mSeekTimePosition > totalTimeDuration)
mSeekTimePosition = totalTimeDuration;
String seekTime = JCUtils.stringForTime(mSeekTimePosition);
String totalTime = JCUtils.stringForTime(totalTimeDuration);
showProgressDialog(deltaX, seekTime, mSeekTimePosition, totalTime, totalTimeDuration);
}
if (mChangeVolume) {
deltaY = -deltaY;
int max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int deltaV = (int) (max * deltaY * 3 / mScreenHeight);
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mGestureDownVolume + deltaV, 0);
//dialog中显示百分比
int volumePercent = (int) (mGestureDownVolume * 100 / max + deltaY * 3 * 100 / mScreenHeight);
showVolumeDialog(-deltaY, volumePercent);
System.out.println("percentfdsfdsf : " + volumePercent + " " + deltaY);
}
if (mChangeBrightness) {
deltaY = -deltaY;
int deltaV = (int) (255 * deltaY * 3 / mScreenHeight);
WindowManager.LayoutParams params = JCUtils.getAppCompActivity(getContext()).getWindow().getAttributes();
if (((mGestureDownBrightness + deltaV) / 255) >= 1) {//这和声音有区别,必须自己过滤一下负值
params.screenBrightness = 1;
} else if (((mGestureDownBrightness + deltaV) / 255) <= 0) {
params.screenBrightness = 0.01f;
} else {
params.screenBrightness = (mGestureDownBrightness + deltaV) / 255;
}
JCUtils.getAppCompActivity(getContext()).getWindow().setAttributes(params);
//dialog中显示百分比
int brightnessPercent = (int) (mGestureDownBrightness * 100 / 255 + deltaY * 3 * 100 / mScreenHeight);
System.out.println("percentfdsfdsf : " + brightnessPercent + " " + deltaY + " " + mGestureDownBrightness);
showBrightnessDialog(brightnessPercent);
// mDownY = y;
}
break;
case MotionEvent.ACTION_UP:
Log.i(TAG, "onTouch surfaceContainer actionUp [" + this.hashCode() + "] ");
mTouchingProgressBar = false;
dismissProgressDialog();
dismissVolumeDialog();
dismissBrightnessDialog();
if (mChangePosition) {
onEvent(JCUserAction.ON_TOUCH_SCREEN_SEEK_POSITION);
JCMediaManager.instance().mediaPlayer.seekTo(mSeekTimePosition);
int duration = getDuration();
int progress = mSeekTimePosition * 100 / (duration == 0 ? 1 : duration);
progressBar.setProgress(progress);
}
if (mChangeVolume) {
onEvent(JCUserAction.ON_TOUCH_SCREEN_SEEK_VOLUME);
}
startProgressTimer();
break;
}
}
return false;
}
public int widthRatio = 16;
public int heightRatio = 9;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (currentScreen == SCREEN_WINDOW_FULLSCREEN || currentScreen == SCREEN_WINDOW_TINY) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
if (widthRatio != 0 && heightRatio != 0) {
int specWidth = MeasureSpec.getSize(widthMeasureSpec);
int specHeight = (int) ((specWidth * (float) heightRatio) / widthRatio);
setMeasuredDimension(specWidth, specHeight);
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(specWidth, MeasureSpec.EXACTLY);
int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(specHeight, MeasureSpec.EXACTLY);
getChildAt(0).measure(childWidthMeasureSpec, childHeightMeasureSpec);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void initTextureView() {
removeTextureView();
JCMediaManager.textureView = new JCResizeTextureView(getContext());
JCMediaManager.textureView.setSurfaceTextureListener(JCMediaManager.instance());
}
public void addTextureView() {
Log.d(TAG, "addTextureView [" + this.hashCode() + "] ");
FrameLayout.LayoutParams layoutParams =
new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
textureViewContainer.addView(JCMediaManager.textureView, layoutParams);
}
public void removeTextureView() {
JCMediaManager.savedSurfaceTexture = null;
if (JCMediaManager.textureView != null && JCMediaManager.textureView.getParent() != null) {
((ViewGroup) JCMediaManager.textureView.getParent()).removeView(JCMediaManager.textureView);
}
}
public void setUiWitStateAndScreen(int state) {
currentState = state;
switch (currentState) {
case CURRENT_STATE_NORMAL:
cancelProgressTimer();
if (isCurrentJcvd()) {//这个if是无法取代的,否则进入全屏的时候会releaseMediaPlayer
JCMediaManager.instance().releaseMediaPlayer();
}
break;
case CURRENT_STATE_PREPARING:
resetProgressAndTime();
break;
case CURRENT_STATE_PLAYING:
case CURRENT_STATE_PAUSE:
case CURRENT_STATE_PLAYING_BUFFERING_START:
startProgressTimer();
break;
case CURRENT_STATE_ERROR:
cancelProgressTimer();
break;
case CURRENT_STATE_AUTO_COMPLETE:
cancelProgressTimer();
progressBar.setProgress(100);
currentTimeTextView.setText(totalTimeTextView.getText());
break;
}
}
public void startProgressTimer() {
cancelProgressTimer();
UPDATE_PROGRESS_TIMER = new Timer();
mProgressTimerTask = new ProgressTimerTask();
UPDATE_PROGRESS_TIMER.schedule(mProgressTimerTask, 0, 300);
}
public void cancelProgressTimer() {
if (UPDATE_PROGRESS_TIMER != null) {
UPDATE_PROGRESS_TIMER.cancel();
}
if (mProgressTimerTask != null) {
mProgressTimerTask.cancel();
}
}
public void onPrepared() {
Log.i(TAG, "onPrepared " + " [" + this.hashCode() + "] ");
if (currentState != CURRENT_STATE_PREPARING) return;
if (seekToInAdvance != 0) {
JCMediaManager.instance().mediaPlayer.seekTo(seekToInAdvance);
seekToInAdvance = 0;
} else {
int position = JCUtils.getSavedProgress(getContext(), url);
if (position != 0) {
JCMediaManager.instance().mediaPlayer.seekTo(position);
}
}
startProgressTimer();
setUiWitStateAndScreen(CURRENT_STATE_PLAYING);
}
public void clearFullscreenLayout() {
ViewGroup vp = (ViewGroup) (JCUtils.scanForActivity(getContext()))//.getWindow().getDecorView();
.findViewById(Window.ID_ANDROID_CONTENT);
View oldF = vp.findViewById(FULLSCREEN_ID);
View oldT = vp.findViewById(TINY_ID);
if (oldF != null) {
vp.removeView(oldF);
}
if (oldT != null) {
vp.removeView(oldT);
}
showSupportActionBar(getContext());
}
public void onAutoCompletion() {
//加上这句,避免循环播放video的时候,内存不断飙升。
Runtime.getRuntime().gc();
Log.i(TAG, "onAutoCompletion " + " [" + this.hashCode() + "] ");
onEvent(JCUserAction.ON_AUTO_COMPLETE);
dismissVolumeDialog();
dismissProgressDialog();
dismissBrightnessDialog();
cancelProgressTimer();
setUiWitStateAndScreen(CURRENT_STATE_AUTO_COMPLETE);
if (currentScreen == SCREEN_WINDOW_FULLSCREEN) {
backPress();
}
JCUtils.saveProgress(getContext(), url, 0);
}
public void onCompletion() {
Log.i(TAG, "onCompletion " + " [" + this.hashCode() + "] ");
//save position
if (currentState == CURRENT_STATE_PLAYING || currentState == CURRENT_STATE_PAUSE) {
int position = getCurrentPositionWhenPlaying();
// int duration = getDuration();
JCUtils.saveProgress(getContext(), url, position);
}
cancelProgressTimer();
setUiWitStateAndScreen(CURRENT_STATE_NORMAL);
// 清理缓存变量
textureViewContainer.removeView(JCMediaManager.textureView);
JCMediaManager.instance().currentVideoWidth = 0;
JCMediaManager.instance().currentVideoHeight = 0;
AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
mAudioManager.abandonAudioFocus(onAudioFocusChangeListener);
JCUtils.scanForActivity(getContext()).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
clearFullscreenLayout();
JCUtils.getAppCompActivity(getContext()).setRequestedOrientation(NORMAL_ORIENTATION);
// JCMediaManager.textureView = null;
JCMediaManager.savedSurfaceTexture = null;
}
//退出全屏和小窗的方法
public void playOnThisJcvd() {
Log.i(TAG, "playOnThisJcvd " + " [" + this.hashCode() + "] ");
//1.清空全屏和小窗的jcvd
currentState = JCVideoPlayerManager.getSecondFloor().currentState;
clearFloatScreen();
//2.在本jcvd上播放
setUiWitStateAndScreen(currentState);
addTextureView();
}
public void clearFloatScreen() {
JCUtils.getAppCompActivity(getContext()).setRequestedOrientation(NORMAL_ORIENTATION);
showSupportActionBar(getContext());
JCVideoPlayer currJcvd = JCVideoPlayerManager.getCurrentJcvd();
currJcvd.textureViewContainer.removeView(JCMediaManager.textureView);
ViewGroup vp = (ViewGroup) (JCUtils.scanForActivity(getContext()))//.getWindow().getDecorView();
.findViewById(Window.ID_ANDROID_CONTENT);
vp.removeView(currJcvd);
JCVideoPlayerManager.setSecondFloor(null);
}
public static long lastAutoFullscreenTime = 0;
//重力感应的时候调用的函数,
public void autoFullscreen(float x) {
if (isCurrentJcvd()
&& currentState == CURRENT_STATE_PLAYING
&& currentScreen != SCREEN_WINDOW_FULLSCREEN
&& currentScreen != SCREEN_WINDOW_TINY) {
if (x > 0) {
JCUtils.getAppCompActivity(getContext()).setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
JCUtils.getAppCompActivity(getContext()).setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
}
startWindowFullscreen();
}
}
public void autoQuitFullscreen() {
if ((System.currentTimeMillis() - lastAutoFullscreenTime) > 2000
&& isCurrentJcvd()
&& currentState == CURRENT_STATE_PLAYING
&& currentScreen == SCREEN_WINDOW_FULLSCREEN) {
lastAutoFullscreenTime = System.currentTimeMillis();
backPress();
}
}
public void onSeekComplete() {
}
public void onError(int what, int extra) {
Log.e(TAG, "onError " + what + " - " + extra + " [" + this.hashCode() + "] ");
if (what != 38 && what != -38) {
setUiWitStateAndScreen(CURRENT_STATE_ERROR);
if (isCurrentJcvd()) {
JCMediaManager.instance().releaseMediaPlayer();
}
}
}
public void onInfo(int what, int extra) {
Log.d(TAG, "onInfo what - " + what + " extra - " + extra);
if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
if (currentState == CURRENT_STATE_PLAYING_BUFFERING_START) return;
BACKUP_PLAYING_BUFFERING_STATE = currentState;
setUiWitStateAndScreen(CURRENT_STATE_PLAYING_BUFFERING_START);//没这个case
Log.d(TAG, "MEDIA_INFO_BUFFERING_START");
} else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
if (BACKUP_PLAYING_BUFFERING_STATE != -1) {
setUiWitStateAndScreen(BACKUP_PLAYING_BUFFERING_STATE);
BACKUP_PLAYING_BUFFERING_STATE = -1;
}
Log.d(TAG, "MEDIA_INFO_BUFFERING_END");
}
}
public void onVideoSizeChanged() {
Log.i(TAG, "onVideoSizeChanged " + " [" + this.hashCode() + "] ");
JCMediaManager.textureView.setVideoSize(JCMediaManager.instance().getVideoSize());
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
Log.i(TAG, "bottomProgress onStartTrackingTouch [" + this.hashCode() + "] ");
cancelProgressTimer();
ViewParent vpdown = getParent();
while (vpdown != null) {
vpdown.requestDisallowInterceptTouchEvent(true);
vpdown = vpdown.getParent();
}
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Log.i(TAG, "bottomProgress onStopTrackingTouch [" + this.hashCode() + "] ");
onEvent(JCUserAction.ON_SEEK_POSITION);
startProgressTimer();
ViewParent vpup = getParent();
while (vpup != null) {
vpup.requestDisallowInterceptTouchEvent(false);
vpup = vpup.getParent();
}
if (currentState != CURRENT_STATE_PLAYING &&
currentState != CURRENT_STATE_PAUSE) return;
int time = seekBar.getProgress() * getDuration() / 100;
JCMediaManager.instance().mediaPlayer.seekTo(time);
Log.i(TAG, "seekTo " + time + " [" + this.hashCode() + "] ");
}
public static boolean backPress() {
Log.i(TAG, "backPress");
if ((System.currentTimeMillis() - CLICK_QUIT_FULLSCREEN_TIME) < FULL_SCREEN_NORMAL_DELAY)
return false;
if (JCVideoPlayerManager.getSecondFloor() != null) {
CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
JCVideoPlayer jcVideoPlayer = JCVideoPlayerManager.getSecondFloor();
jcVideoPlayer.onEvent(jcVideoPlayer.currentScreen == JCVideoPlayerStandard.SCREEN_WINDOW_FULLSCREEN ?
JCUserAction.ON_QUIT_FULLSCREEN :
JCUserAction.ON_QUIT_TINYSCREEN);
JCVideoPlayerManager.getFirstFloor().playOnThisJcvd();
return true;
} else if (JCVideoPlayerManager.getFirstFloor() != null &&
(JCVideoPlayerManager.getFirstFloor().currentScreen == SCREEN_WINDOW_FULLSCREEN ||
JCVideoPlayerManager.getFirstFloor().currentScreen == SCREEN_WINDOW_TINY)) {//以前我总想把这两个判断写到一起,这分明是两个独立是逻辑
CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
//直接退出全屏和小窗
JCVideoPlayerManager.getCurrentJcvd().currentState = CURRENT_STATE_NORMAL;
JCVideoPlayerManager.getFirstFloor().clearFloatScreen();
JCMediaManager.instance().releaseMediaPlayer();
JCVideoPlayerManager.setFirstFloor(null);
return true;
}
return false;
}
public void startWindowFullscreen() {
Log.i(TAG, "startWindowFullscreen " + " [" + this.hashCode() + "] ");
hideSupportActionBar(getContext());
JCUtils.getAppCompActivity(getContext()).setRequestedOrientation(FULLSCREEN_ORIENTATION);
ViewGroup vp = (ViewGroup) (JCUtils.scanForActivity(getContext()))//.getWindow().getDecorView();
.findViewById(Window.ID_ANDROID_CONTENT);
View old = vp.findViewById(FULLSCREEN_ID);
if (old != null) {
vp.removeView(old);
}
// ((ViewGroup)JCMediaManager.textureView.getParent()).removeView(JCMediaManager.textureView);
textureViewContainer.removeView(JCMediaManager.textureView);
try {
Constructor<JCVideoPlayer> constructor = (Constructor<JCVideoPlayer>) JCVideoPlayer.this.getClass().getConstructor(Context.class);
JCVideoPlayer jcVideoPlayer = constructor.newInstance(getContext());
jcVideoPlayer.setId(FULLSCREEN_ID);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
vp.addView(jcVideoPlayer, lp);
jcVideoPlayer.setUp(url, JCVideoPlayerStandard.SCREEN_WINDOW_FULLSCREEN, objects);
jcVideoPlayer.setUiWitStateAndScreen(currentState);
jcVideoPlayer.addTextureView();
JCVideoPlayerManager.setSecondFloor(jcVideoPlayer);
// final Animation ra = AnimationUtils.loadAnimation(getContext(), R.anim.start_fullscreen);
// jcVideoPlayer.setAnimation(ra);
CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
} catch (Exception e) {
e.printStackTrace();
}
}
public void startWindowTiny() {
Log.i(TAG, "startWindowTiny " + " [" + this.hashCode() + "] ");
onEvent(JCUserAction.ON_ENTER_TINYSCREEN);
if (currentState == CURRENT_STATE_NORMAL || currentState == CURRENT_STATE_ERROR) return;
ViewGroup vp = (ViewGroup) (JCUtils.scanForActivity(getContext()))//.getWindow().getDecorView();
.findViewById(Window.ID_ANDROID_CONTENT);
View old = vp.findViewById(TINY_ID);
if (old != null) {
vp.removeView(old);
}
textureViewContainer.removeView(JCMediaManager.textureView);
try {
Constructor<JCVideoPlayer> constructor = (Constructor<JCVideoPlayer>) JCVideoPlayer.this.getClass().getConstructor(Context.class);
JCVideoPlayer jcVideoPlayer = constructor.newInstance(getContext());
jcVideoPlayer.setId(TINY_ID);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(400, 400);
lp.gravity = Gravity.RIGHT | Gravity.BOTTOM;
vp.addView(jcVideoPlayer, lp);
jcVideoPlayer.setUp(url, JCVideoPlayerStandard.SCREEN_WINDOW_TINY, objects);
jcVideoPlayer.setUiWitStateAndScreen(currentState);
jcVideoPlayer.addTextureView();
JCVideoPlayerManager.setSecondFloor(jcVideoPlayer);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public class ProgressTimerTask extends TimerTask {
@Override
public void run() {
if (currentState == CURRENT_STATE_PLAYING || currentState == CURRENT_STATE_PAUSE || currentState == CURRENT_STATE_PLAYING_BUFFERING_START) {
// Log.v(TAG, "onProgressUpdate " + position + "/" + duration + " [" + this.hashCode() + "] ");
mHandler.post(new Runnable() {
@Override
public void run() {
setProgressAndText();
}
});
}
}
}
public int getCurrentPositionWhenPlaying() {
int position = 0;
if (JCMediaManager.instance().mediaPlayer == null) return position;//这行代码不应该在这,如果代码和逻辑万无一失的话,心头之恨呐
if (currentState == CURRENT_STATE_PLAYING ||
currentState == CURRENT_STATE_PAUSE ||
currentState == CURRENT_STATE_PLAYING_BUFFERING_START) {
try {
position = JCMediaManager.instance().mediaPlayer.getCurrentPosition();
} catch (IllegalStateException e) {
e.printStackTrace();
return position;
}
}
return position;
}
public int getDuration() {
int duration = 0;
if (JCMediaManager.instance().mediaPlayer == null) return duration;
try {
duration = JCMediaManager.instance().mediaPlayer.getDuration();
} catch (IllegalStateException e) {
e.printStackTrace();
return duration;
}
return duration;
}
public void setProgressAndText() {
int position = getCurrentPositionWhenPlaying();
int duration = getDuration();
int progress = position * 100 / (duration == 0 ? 1 : duration);
if (!mTouchingProgressBar) {
if (progress != 0) progressBar.setProgress(progress);
}
if (position != 0) currentTimeTextView.setText(JCUtils.stringForTime(position));
totalTimeTextView.setText(JCUtils.stringForTime(duration));
}
public void setBufferProgress(int bufferProgress) {
if (bufferProgress != 0) progressBar.setSecondaryProgress(bufferProgress);
}
public void resetProgressAndTime() {
progressBar.setProgress(0);
progressBar.setSecondaryProgress(0);
currentTimeTextView.setText(JCUtils.stringForTime(0));
totalTimeTextView.setText(JCUtils.stringForTime(0));
}
public static AudioManager.OnAudioFocusChangeListener onAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
break;
case AudioManager.AUDIOFOCUS_LOSS:
releaseAllVideos();
Log.d(TAG, "AUDIOFOCUS_LOSS [" + this.hashCode() + "]");
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
try {
if (JCMediaManager.instance().mediaPlayer != null &&
JCMediaManager.instance().mediaPlayer.isPlaying()) {
JCMediaManager.instance().mediaPlayer.pause();
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
Log.d(TAG, "AUDIOFOCUS_LOSS_TRANSIENT [" + this.hashCode() + "]");
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
break;
}
}
};
public void release() {
if (url.equals(JCMediaManager.CURRENT_PLAYING_URL) &&
(System.currentTimeMillis() - CLICK_QUIT_FULLSCREEN_TIME) > FULL_SCREEN_NORMAL_DELAY) {
//在非全屏的情况下只能backPress()
if (JCVideoPlayerManager.getSecondFloor() != null &&
JCVideoPlayerManager.getSecondFloor().currentScreen == SCREEN_WINDOW_FULLSCREEN) {//点击全屏
} else if (JCVideoPlayerManager.getSecondFloor() == null && JCVideoPlayerManager.getFirstFloor() != null &&
JCVideoPlayerManager.getFirstFloor().currentScreen == SCREEN_WINDOW_FULLSCREEN) {//直接全屏
} else {
Log.d(TAG, "release [" + this.hashCode() + "]");
releaseAllVideos();
}
}
}
//isCurrentJcvd and isCurrenPlayUrl should be two logic methods,isCurrentJcvd is for different jcvd with same
//url when fullscreen or tiny screen. isCurrenPlayUrl is to find where is myself when back from tiny screen.
//Sometimes they are overlap.
public boolean isCurrentJcvd() {//虽然看这个函数很不爽,但是干不掉
return JCVideoPlayerManager.getCurrentJcvd() != null
&& JCVideoPlayerManager.getCurrentJcvd() == this;
}
// public boolean isCurrenPlayingUrl() {
// return url.equals(JCMediaManager.CURRENT_PLAYING_URL);
// }
public static void releaseAllVideos() {
if ((System.currentTimeMillis() - CLICK_QUIT_FULLSCREEN_TIME) > FULL_SCREEN_NORMAL_DELAY) {
Log.d(TAG, "releaseAllVideos");
JCVideoPlayerManager.completeAll();
JCMediaManager.instance().releaseMediaPlayer();
}
}
public static void setJcUserAction(JCUserAction jcUserEvent) {
JC_USER_EVENT = jcUserEvent;
}
public void onEvent(int type) {
if (JC_USER_EVENT != null && isCurrentJcvd()) {
JC_USER_EVENT.onEvent(type, url, currentScreen, objects);
}
}
public static void startFullscreen(Context context, Class _class, String url, Object... objects) {
hideSupportActionBar(context);
JCUtils.getAppCompActivity(context).setRequestedOrientation(FULLSCREEN_ORIENTATION);
ViewGroup vp = (ViewGroup) (JCUtils.scanForActivity(context))//.getWindow().getDecorView();
.findViewById(Window.ID_ANDROID_CONTENT);
View old = vp.findViewById(JCVideoPlayer.FULLSCREEN_ID);
if (old != null) {
vp.removeView(old);
}
try {
Constructor<JCVideoPlayer> constructor = _class.getConstructor(Context.class);
final JCVideoPlayer jcVideoPlayer = constructor.newInstance(context);
jcVideoPlayer.setId(JCVideoPlayer.FULLSCREEN_ID);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
vp.addView(jcVideoPlayer, lp);
// final Animation ra = AnimationUtils.loadAnimation(context, R.anim.start_fullscreen);
// jcVideoPlayer.setAnimation(ra);
jcVideoPlayer.setUp(url, JCVideoPlayerStandard.SCREEN_WINDOW_FULLSCREEN, objects);
CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
jcVideoPlayer.startButton.performClick();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void hideSupportActionBar(Context context) {
if (ACTION_BAR_EXIST) {
ActionBar ab = JCUtils.getAppCompActivity(context).getSupportActionBar();
if (ab != null) {
ab.setShowHideAnimationEnabled(false);
ab.hide();
}
}
if (TOOL_BAR_EXIST) {
JCUtils.getAppCompActivity(context).getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
public static void showSupportActionBar(Context context) {
if (ACTION_BAR_EXIST) {
ActionBar ab = JCUtils.getAppCompActivity(context).getSupportActionBar();
if (ab != null) {
ab.setShowHideAnimationEnabled(false);
ab.show();
}
}
if (TOOL_BAR_EXIST) {
JCUtils.getAppCompActivity(context).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
public static class JCAutoFullscreenListener implements SensorEventListener {
@Override
public void onSensorChanged(SensorEvent event) {//可以得到传感器实时测量出来的变化值
final float x = event.values[SensorManager.DATA_X];
float y = event.values[SensorManager.DATA_Y];
float z = event.values[SensorManager.DATA_Z];
//过滤掉用力过猛会有一个反向的大数值
if (((x > -15 && x < -10) || (x < 15 && x > 10)) && Math.abs(y) < 1.5) {
if ((System.currentTimeMillis() - lastAutoFullscreenTime) > 2000) {
if (JCVideoPlayerManager.getCurrentJcvd() != null) {
JCVideoPlayerManager.getCurrentJcvd().autoFullscreen(x);
}
lastAutoFullscreenTime = System.currentTimeMillis();
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
public static void clearSavedProgress(Context context, String url) {
JCUtils.clearSavedProgress(context, url);
}
public void showWifiDialog() {
}
public void showProgressDialog(float deltaX,
String seekTime, int seekTimePosition,
String totalTime, int totalTimeDuration) {
}
public void dismissProgressDialog() {
}
public void showVolumeDialog(float deltaY, int volumePercent) {
}
public void dismissVolumeDialog() {
}
public void showBrightnessDialog(int brightnessPercent) {
}
public void dismissBrightnessDialog() {
}
public abstract int getLayoutId();
}
| jcvideoplayer-lib/src/main/java/fm/jiecao/jcvideoplayer_lib/JCVideoPlayer.java | package fm.jiecao.jcvideoplayer_lib;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.provider.Settings;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by Nathen on 16/7/30.
*/
public abstract class JCVideoPlayer extends FrameLayout implements View.OnClickListener, SeekBar.OnSeekBarChangeListener, View.OnTouchListener {
public static final String TAG = "JieCaoVideoPlayer";
public static boolean ACTION_BAR_EXIST = true;
public static boolean TOOL_BAR_EXIST = true;
public static int FULLSCREEN_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_SENSOR;
public static int NORMAL_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
public static boolean SAVE_PROGRESS = true;
public static boolean WIFI_TIP_DIALOG_SHOWED = false;
public static final int FULLSCREEN_ID = 33797;
public static final int TINY_ID = 33798;
public static final int THRESHOLD = 80;
public static final int FULL_SCREEN_NORMAL_DELAY = 300;
public static long CLICK_QUIT_FULLSCREEN_TIME = 0;
public static final int SCREEN_LAYOUT_NORMAL = 0;
public static final int SCREEN_LAYOUT_LIST = 1;
public static final int SCREEN_WINDOW_FULLSCREEN = 2;
public static final int SCREEN_WINDOW_TINY = 3;
public static final int CURRENT_STATE_NORMAL = 0;
public static final int CURRENT_STATE_PREPARING = 1;
public static final int CURRENT_STATE_PLAYING = 2;
public static final int CURRENT_STATE_PLAYING_BUFFERING_START = 3;
public static final int CURRENT_STATE_PAUSE = 5;
public static final int CURRENT_STATE_AUTO_COMPLETE = 6;
public static final int CURRENT_STATE_ERROR = 7;
public static int BACKUP_PLAYING_BUFFERING_STATE = -1;
public int currentState = -1;
public int currentScreen = -1;
public boolean loop = false;
public Map<String, String> headData;
public String url = "";
public Object[] objects = null;
public int seekToInAdvance = 0;
public ImageView startButton;
public SeekBar progressBar;
public ImageView fullscreenButton;
public TextView currentTimeTextView, totalTimeTextView;
public ViewGroup textureViewContainer;
public ViewGroup topContainer, bottomContainer;
protected static JCUserAction JC_USER_EVENT;
protected static Timer UPDATE_PROGRESS_TIMER;
protected int mScreenWidth;
protected int mScreenHeight;
protected AudioManager mAudioManager;
protected Handler mHandler;
protected ProgressTimerTask mProgressTimerTask;
protected boolean mTouchingProgressBar;
protected float mDownX;
protected float mDownY;
protected boolean mChangeVolume;
protected boolean mChangePosition;
protected boolean mChangeBrightness;
protected int mGestureDownPosition;
protected int mGestureDownVolume;
protected float mGestureDownBrightness;
protected int mSeekTimePosition;
public JCVideoPlayer(Context context) {
super(context);
init(context);
}
public JCVideoPlayer(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public void init(Context context) {
View.inflate(context, getLayoutId(), this);
startButton = (ImageView) findViewById(R.id.start);
fullscreenButton = (ImageView) findViewById(R.id.fullscreen);
progressBar = (SeekBar) findViewById(R.id.bottom_seek_progress);
currentTimeTextView = (TextView) findViewById(R.id.current);
totalTimeTextView = (TextView) findViewById(R.id.total);
bottomContainer = (ViewGroup) findViewById(R.id.layout_bottom);
textureViewContainer = (ViewGroup) findViewById(R.id.surface_container);
topContainer = (ViewGroup) findViewById(R.id.layout_top);
startButton.setOnClickListener(this);
fullscreenButton.setOnClickListener(this);
progressBar.setOnSeekBarChangeListener(this);
bottomContainer.setOnClickListener(this);
textureViewContainer.setOnClickListener(this);
textureViewContainer.setOnTouchListener(this);
mScreenWidth = getContext().getResources().getDisplayMetrics().widthPixels;
mScreenHeight = getContext().getResources().getDisplayMetrics().heightPixels;
mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
mHandler = new Handler();
}
public void setUp(String url, int screen, Object... objects) {
if (!TextUtils.isEmpty(this.url) && TextUtils.equals(this.url, url)) {
return;
}
this.url = url;
this.objects = objects;
this.currentScreen = screen;
this.headData = null;
setUiWitStateAndScreen(CURRENT_STATE_NORMAL);
}
@Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.start) {
Log.i(TAG, "onClick start [" + this.hashCode() + "] ");
if (TextUtils.isEmpty(url)) {
Toast.makeText(getContext(), getResources().getString(R.string.no_url), Toast.LENGTH_SHORT).show();
return;
}
if (currentState == CURRENT_STATE_NORMAL || currentState == CURRENT_STATE_ERROR) {
if (!url.startsWith("file") && !JCUtils.isWifiConnected(getContext()) && !WIFI_TIP_DIALOG_SHOWED) {
showWifiDialog();
return;
}
prepareMediaPlayer();
onEvent(currentState != CURRENT_STATE_ERROR ? JCUserAction.ON_CLICK_START_ICON : JCUserAction.ON_CLICK_START_ERROR);
} else if (currentState == CURRENT_STATE_PLAYING) {
onEvent(JCUserAction.ON_CLICK_PAUSE);
Log.d(TAG, "pauseVideo [" + this.hashCode() + "] ");
JCMediaManager.instance().mediaPlayer.pause();
setUiWitStateAndScreen(CURRENT_STATE_PAUSE);
} else if (currentState == CURRENT_STATE_PAUSE) {
onEvent(JCUserAction.ON_CLICK_RESUME);
JCMediaManager.instance().mediaPlayer.start();
setUiWitStateAndScreen(CURRENT_STATE_PLAYING);
} else if (currentState == CURRENT_STATE_AUTO_COMPLETE) {
onEvent(JCUserAction.ON_CLICK_START_AUTO_COMPLETE);
prepareMediaPlayer();
}
} else if (i == R.id.fullscreen) {
Log.i(TAG, "onClick fullscreen [" + this.hashCode() + "] ");
if (currentState == CURRENT_STATE_AUTO_COMPLETE) return;
if (currentScreen == SCREEN_WINDOW_FULLSCREEN) {
//quit fullscreen
backPress();
} else {
Log.d(TAG, "toFullscreenActivity [" + this.hashCode() + "] ");
onEvent(JCUserAction.ON_ENTER_FULLSCREEN);
startWindowFullscreen();
}
} else if (i == R.id.surface_container && currentState == CURRENT_STATE_ERROR) {
Log.i(TAG, "onClick surfaceContainer State=Error [" + this.hashCode() + "] ");
prepareMediaPlayer();
}
}
public void prepareMediaPlayer() {
JCVideoPlayerManager.completeAll();
Log.d(TAG, "prepareMediaPlayer [" + this.hashCode() + "] ");
initTextureView();
addTextureView();
AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
mAudioManager.requestAudioFocus(onAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
JCUtils.scanForActivity(getContext()).getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
JCMediaManager.CURRENT_PLAYING_URL = url;
JCMediaManager.CURRENT_PLING_LOOP = loop;
JCMediaManager.MAP_HEADER_DATA = headData;
setUiWitStateAndScreen(CURRENT_STATE_PREPARING);
JCVideoPlayerManager.setFirstFloor(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
float x = event.getX();
float y = event.getY();
int id = v.getId();
if (id == R.id.surface_container) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i(TAG, "onTouch surfaceContainer actionDown [" + this.hashCode() + "] ");
mTouchingProgressBar = true;
mDownX = x;
mDownY = y;
mChangeVolume = false;
mChangePosition = false;
mChangeBrightness = false;
break;
case MotionEvent.ACTION_MOVE:
Log.i(TAG, "onTouch surfaceContainer actionMove [" + this.hashCode() + "] ");
float deltaX = x - mDownX;
float deltaY = y - mDownY;
float absDeltaX = Math.abs(deltaX);
float absDeltaY = Math.abs(deltaY);
if (currentScreen == SCREEN_WINDOW_FULLSCREEN) {
if (!mChangePosition && !mChangeVolume && !mChangeBrightness) {
if (absDeltaX > THRESHOLD || absDeltaY > THRESHOLD) {
cancelProgressTimer();
if (absDeltaX >= THRESHOLD) {
// 全屏模式下的CURRENT_STATE_ERROR状态下,不响应进度拖动事件.
// 否则会因为mediaplayer的状态非法导致App Crash
if (currentState != CURRENT_STATE_ERROR) {
mChangePosition = true;
mGestureDownPosition = getCurrentPositionWhenPlaying();
}
} else {
//如果y轴滑动距离超过设置的处理范围,那么进行滑动事件处理
if (mDownX < mScreenWidth * 0.5f) {//左侧改变亮度
mChangeBrightness = true;
try {
mGestureDownBrightness = Settings.System.getInt(getContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
System.out.println("当前亮度 " + mGestureDownBrightness);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
} else {//右侧改变声音
mChangeVolume = true;
mGestureDownVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
}
}
}
}
}
if (mChangePosition) {
int totalTimeDuration = getDuration();
mSeekTimePosition = (int) (mGestureDownPosition + deltaX * totalTimeDuration / mScreenWidth);
if (mSeekTimePosition > totalTimeDuration)
mSeekTimePosition = totalTimeDuration;
String seekTime = JCUtils.stringForTime(mSeekTimePosition);
String totalTime = JCUtils.stringForTime(totalTimeDuration);
showProgressDialog(deltaX, seekTime, mSeekTimePosition, totalTime, totalTimeDuration);
}
if (mChangeVolume) {
deltaY = -deltaY;
int max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int deltaV = (int) (max * deltaY * 3 / mScreenHeight);
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mGestureDownVolume + deltaV, 0);
//dialog中显示百分比
int volumePercent = (int) (mGestureDownVolume * 100 / max + deltaY * 3 * 100 / mScreenHeight);
showVolumeDialog(-deltaY, volumePercent);
System.out.println("percentfdsfdsf : " + volumePercent + " " + deltaY);
}
if (mChangeBrightness) {
deltaY = -deltaY;
int deltaV = (int) (255 * deltaY * 3 / mScreenHeight);
WindowManager.LayoutParams params = JCUtils.getAppCompActivity(getContext()).getWindow().getAttributes();
if (((mGestureDownBrightness + deltaV) / 255) >= 1) {//这和声音有区别,必须自己过滤一下负值
params.screenBrightness = 1;
} else if (((mGestureDownBrightness + deltaV) / 255) <= 0) {
params.screenBrightness = 0.01f;
} else {
params.screenBrightness = (mGestureDownBrightness + deltaV) / 255;
}
JCUtils.getAppCompActivity(getContext()).getWindow().setAttributes(params);
//dialog中显示百分比
int brightnessPercent = (int) (mGestureDownBrightness * 100 / 255 + deltaY * 3 * 100 / mScreenHeight);
System.out.println("percentfdsfdsf : " + brightnessPercent + " " + deltaY + " " + mGestureDownBrightness);
showBrightnessDialog(brightnessPercent);
// mDownY = y;
}
break;
case MotionEvent.ACTION_UP:
Log.i(TAG, "onTouch surfaceContainer actionUp [" + this.hashCode() + "] ");
mTouchingProgressBar = false;
dismissProgressDialog();
dismissVolumeDialog();
dismissBrightnessDialog();
if (mChangePosition) {
onEvent(JCUserAction.ON_TOUCH_SCREEN_SEEK_POSITION);
JCMediaManager.instance().mediaPlayer.seekTo(mSeekTimePosition);
int duration = getDuration();
int progress = mSeekTimePosition * 100 / (duration == 0 ? 1 : duration);
progressBar.setProgress(progress);
}
if (mChangeVolume) {
onEvent(JCUserAction.ON_TOUCH_SCREEN_SEEK_VOLUME);
}
startProgressTimer();
break;
}
}
return false;
}
public int widthRatio = 16;
public int heightRatio = 9;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (currentScreen == SCREEN_WINDOW_FULLSCREEN || currentScreen == SCREEN_WINDOW_TINY) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
if (widthRatio != 0 && heightRatio != 0) {
int specWidth = MeasureSpec.getSize(widthMeasureSpec);
int specHeight = (int) ((specWidth * (float) heightRatio) / widthRatio);
setMeasuredDimension(specWidth, specHeight);
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(specWidth, MeasureSpec.EXACTLY);
int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(specHeight, MeasureSpec.EXACTLY);
getChildAt(0).measure(childWidthMeasureSpec, childHeightMeasureSpec);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void initTextureView() {
removeTextureView();
JCMediaManager.textureView = new JCResizeTextureView(getContext());
JCMediaManager.textureView.setSurfaceTextureListener(JCMediaManager.instance());
}
public void addTextureView() {
Log.d(TAG, "addTextureView [" + this.hashCode() + "] ");
FrameLayout.LayoutParams layoutParams =
new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
textureViewContainer.addView(JCMediaManager.textureView, layoutParams);
}
public void removeTextureView() {
JCMediaManager.savedSurfaceTexture = null;
if (JCMediaManager.textureView != null && JCMediaManager.textureView.getParent() != null) {
((ViewGroup) JCMediaManager.textureView.getParent()).removeView(JCMediaManager.textureView);
}
}
public void setUiWitStateAndScreen(int state) {
currentState = state;
switch (currentState) {
case CURRENT_STATE_NORMAL:
cancelProgressTimer();
if (isCurrentJcvd()) {//这个if是无法取代的,否则进入全屏的时候会releaseMediaPlayer
JCMediaManager.instance().releaseMediaPlayer();
}
break;
case CURRENT_STATE_PREPARING:
resetProgressAndTime();
break;
case CURRENT_STATE_PLAYING:
case CURRENT_STATE_PAUSE:
case CURRENT_STATE_PLAYING_BUFFERING_START:
startProgressTimer();
break;
case CURRENT_STATE_ERROR:
cancelProgressTimer();
break;
case CURRENT_STATE_AUTO_COMPLETE:
cancelProgressTimer();
progressBar.setProgress(100);
currentTimeTextView.setText(totalTimeTextView.getText());
break;
}
}
public void startProgressTimer() {
cancelProgressTimer();
UPDATE_PROGRESS_TIMER = new Timer();
mProgressTimerTask = new ProgressTimerTask();
UPDATE_PROGRESS_TIMER.schedule(mProgressTimerTask, 0, 300);
}
public void cancelProgressTimer() {
if (UPDATE_PROGRESS_TIMER != null) {
UPDATE_PROGRESS_TIMER.cancel();
}
if (mProgressTimerTask != null) {
mProgressTimerTask.cancel();
}
}
public void onPrepared() {
Log.i(TAG, "onPrepared " + " [" + this.hashCode() + "] ");
if (currentState != CURRENT_STATE_PREPARING) return;
if (seekToInAdvance != 0) {
JCMediaManager.instance().mediaPlayer.seekTo(seekToInAdvance);
seekToInAdvance = 0;
} else {
int position = JCUtils.getSavedProgress(getContext(), url);
if (position != 0) {
JCMediaManager.instance().mediaPlayer.seekTo(position);
}
}
startProgressTimer();
setUiWitStateAndScreen(CURRENT_STATE_PLAYING);
}
public void clearFullscreenLayout() {
ViewGroup vp = (ViewGroup) (JCUtils.scanForActivity(getContext()))//.getWindow().getDecorView();
.findViewById(Window.ID_ANDROID_CONTENT);
View oldF = vp.findViewById(FULLSCREEN_ID);
View oldT = vp.findViewById(TINY_ID);
if (oldF != null) {
vp.removeView(oldF);
}
if (oldT != null) {
vp.removeView(oldT);
}
showSupportActionBar(getContext());
}
public void onAutoCompletion() {
//加上这句,避免循环播放video的时候,内存不断飙升。
Runtime.getRuntime().gc();
Log.i(TAG, "onAutoCompletion " + " [" + this.hashCode() + "] ");
onEvent(JCUserAction.ON_AUTO_COMPLETE);
dismissVolumeDialog();
dismissProgressDialog();
dismissBrightnessDialog();
cancelProgressTimer();
setUiWitStateAndScreen(CURRENT_STATE_AUTO_COMPLETE);
if (currentScreen == SCREEN_WINDOW_FULLSCREEN) {
backPress();
}
JCUtils.saveProgress(getContext(), url, 0);
// JCMediaManager.textureView = null;
JCMediaManager.savedSurfaceTexture = null;
}
public void onCompletion() {
Log.i(TAG, "onCompletion " + " [" + this.hashCode() + "] ");
//save position
if (currentState == CURRENT_STATE_PLAYING || currentState == CURRENT_STATE_PAUSE) {
int position = getCurrentPositionWhenPlaying();
// int duration = getDuration();
JCUtils.saveProgress(getContext(), url, position);
}
cancelProgressTimer();
setUiWitStateAndScreen(CURRENT_STATE_NORMAL);
// 清理缓存变量
textureViewContainer.removeView(JCMediaManager.textureView);
JCMediaManager.instance().currentVideoWidth = 0;
JCMediaManager.instance().currentVideoHeight = 0;
AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
mAudioManager.abandonAudioFocus(onAudioFocusChangeListener);
JCUtils.scanForActivity(getContext()).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
clearFullscreenLayout();
JCUtils.getAppCompActivity(getContext()).setRequestedOrientation(NORMAL_ORIENTATION);
// JCMediaManager.textureView = null;
JCMediaManager.savedSurfaceTexture = null;
}
//退出全屏和小窗的方法
public void playOnThisJcvd() {
Log.i(TAG, "playOnThisJcvd " + " [" + this.hashCode() + "] ");
//1.清空全屏和小窗的jcvd
currentState = JCVideoPlayerManager.getSecondFloor().currentState;
clearFloatScreen();
//2.在本jcvd上播放
setUiWitStateAndScreen(currentState);
addTextureView();
}
public void clearFloatScreen() {
JCUtils.getAppCompActivity(getContext()).setRequestedOrientation(NORMAL_ORIENTATION);
showSupportActionBar(getContext());
JCVideoPlayer currJcvd = JCVideoPlayerManager.getCurrentJcvd();
currJcvd.textureViewContainer.removeView(JCMediaManager.textureView);
ViewGroup vp = (ViewGroup) (JCUtils.scanForActivity(getContext()))//.getWindow().getDecorView();
.findViewById(Window.ID_ANDROID_CONTENT);
vp.removeView(currJcvd);
JCVideoPlayerManager.setSecondFloor(null);
}
public static long lastAutoFullscreenTime = 0;
//重力感应的时候调用的函数,
public void autoFullscreen(float x) {
if (isCurrentJcvd()
&& currentState == CURRENT_STATE_PLAYING
&& currentScreen != SCREEN_WINDOW_FULLSCREEN
&& currentScreen != SCREEN_WINDOW_TINY) {
if (x > 0) {
JCUtils.getAppCompActivity(getContext()).setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
JCUtils.getAppCompActivity(getContext()).setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
}
startWindowFullscreen();
}
}
public void autoQuitFullscreen() {
if ((System.currentTimeMillis() - lastAutoFullscreenTime) > 2000
&& isCurrentJcvd()
&& currentState == CURRENT_STATE_PLAYING
&& currentScreen == SCREEN_WINDOW_FULLSCREEN) {
lastAutoFullscreenTime = System.currentTimeMillis();
backPress();
}
}
public void onSeekComplete() {
}
public void onError(int what, int extra) {
Log.e(TAG, "onError " + what + " - " + extra + " [" + this.hashCode() + "] ");
if (what != 38 && what != -38) {
setUiWitStateAndScreen(CURRENT_STATE_ERROR);
if (isCurrentJcvd()) {
JCMediaManager.instance().releaseMediaPlayer();
}
}
}
public void onInfo(int what, int extra) {
Log.d(TAG, "onInfo what - " + what + " extra - " + extra);
if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
if (currentState == CURRENT_STATE_PLAYING_BUFFERING_START) return;
BACKUP_PLAYING_BUFFERING_STATE = currentState;
setUiWitStateAndScreen(CURRENT_STATE_PLAYING_BUFFERING_START);//没这个case
Log.d(TAG, "MEDIA_INFO_BUFFERING_START");
} else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
if (BACKUP_PLAYING_BUFFERING_STATE != -1) {
setUiWitStateAndScreen(BACKUP_PLAYING_BUFFERING_STATE);
BACKUP_PLAYING_BUFFERING_STATE = -1;
}
Log.d(TAG, "MEDIA_INFO_BUFFERING_END");
}
}
public void onVideoSizeChanged() {
Log.i(TAG, "onVideoSizeChanged " + " [" + this.hashCode() + "] ");
JCMediaManager.textureView.setVideoSize(JCMediaManager.instance().getVideoSize());
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
Log.i(TAG, "bottomProgress onStartTrackingTouch [" + this.hashCode() + "] ");
cancelProgressTimer();
ViewParent vpdown = getParent();
while (vpdown != null) {
vpdown.requestDisallowInterceptTouchEvent(true);
vpdown = vpdown.getParent();
}
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Log.i(TAG, "bottomProgress onStopTrackingTouch [" + this.hashCode() + "] ");
onEvent(JCUserAction.ON_SEEK_POSITION);
startProgressTimer();
ViewParent vpup = getParent();
while (vpup != null) {
vpup.requestDisallowInterceptTouchEvent(false);
vpup = vpup.getParent();
}
if (currentState != CURRENT_STATE_PLAYING &&
currentState != CURRENT_STATE_PAUSE) return;
int time = seekBar.getProgress() * getDuration() / 100;
JCMediaManager.instance().mediaPlayer.seekTo(time);
Log.i(TAG, "seekTo " + time + " [" + this.hashCode() + "] ");
}
public static boolean backPress() {
Log.i(TAG, "backPress");
if ((System.currentTimeMillis() - CLICK_QUIT_FULLSCREEN_TIME) < FULL_SCREEN_NORMAL_DELAY)
return false;
if (JCVideoPlayerManager.getSecondFloor() != null) {
CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
JCVideoPlayer jcVideoPlayer = JCVideoPlayerManager.getSecondFloor();
jcVideoPlayer.onEvent(jcVideoPlayer.currentScreen == JCVideoPlayerStandard.SCREEN_WINDOW_FULLSCREEN ?
JCUserAction.ON_QUIT_FULLSCREEN :
JCUserAction.ON_QUIT_TINYSCREEN);
JCVideoPlayerManager.getFirstFloor().playOnThisJcvd();
return true;
} else if (JCVideoPlayerManager.getFirstFloor() != null &&
(JCVideoPlayerManager.getFirstFloor().currentScreen == SCREEN_WINDOW_FULLSCREEN ||
JCVideoPlayerManager.getFirstFloor().currentScreen == SCREEN_WINDOW_TINY)) {//以前我总想把这两个判断写到一起,这分明是两个独立是逻辑
CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
//直接退出全屏和小窗
JCVideoPlayerManager.getCurrentJcvd().currentState = CURRENT_STATE_NORMAL;
JCVideoPlayerManager.getFirstFloor().clearFloatScreen();
JCMediaManager.instance().releaseMediaPlayer();
JCVideoPlayerManager.setFirstFloor(null);
return true;
}
return false;
}
public void startWindowFullscreen() {
Log.i(TAG, "startWindowFullscreen " + " [" + this.hashCode() + "] ");
hideSupportActionBar(getContext());
JCUtils.getAppCompActivity(getContext()).setRequestedOrientation(FULLSCREEN_ORIENTATION);
ViewGroup vp = (ViewGroup) (JCUtils.scanForActivity(getContext()))//.getWindow().getDecorView();
.findViewById(Window.ID_ANDROID_CONTENT);
View old = vp.findViewById(FULLSCREEN_ID);
if (old != null) {
vp.removeView(old);
}
// ((ViewGroup)JCMediaManager.textureView.getParent()).removeView(JCMediaManager.textureView);
textureViewContainer.removeView(JCMediaManager.textureView);
try {
Constructor<JCVideoPlayer> constructor = (Constructor<JCVideoPlayer>) JCVideoPlayer.this.getClass().getConstructor(Context.class);
JCVideoPlayer jcVideoPlayer = constructor.newInstance(getContext());
jcVideoPlayer.setId(FULLSCREEN_ID);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
vp.addView(jcVideoPlayer, lp);
jcVideoPlayer.setUp(url, JCVideoPlayerStandard.SCREEN_WINDOW_FULLSCREEN, objects);
jcVideoPlayer.setUiWitStateAndScreen(currentState);
jcVideoPlayer.addTextureView();
JCVideoPlayerManager.setSecondFloor(jcVideoPlayer);
// final Animation ra = AnimationUtils.loadAnimation(getContext(), R.anim.start_fullscreen);
// jcVideoPlayer.setAnimation(ra);
CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
} catch (Exception e) {
e.printStackTrace();
}
}
public void startWindowTiny() {
Log.i(TAG, "startWindowTiny " + " [" + this.hashCode() + "] ");
onEvent(JCUserAction.ON_ENTER_TINYSCREEN);
if (currentState == CURRENT_STATE_NORMAL || currentState == CURRENT_STATE_ERROR) return;
ViewGroup vp = (ViewGroup) (JCUtils.scanForActivity(getContext()))//.getWindow().getDecorView();
.findViewById(Window.ID_ANDROID_CONTENT);
View old = vp.findViewById(TINY_ID);
if (old != null) {
vp.removeView(old);
}
textureViewContainer.removeView(JCMediaManager.textureView);
try {
Constructor<JCVideoPlayer> constructor = (Constructor<JCVideoPlayer>) JCVideoPlayer.this.getClass().getConstructor(Context.class);
JCVideoPlayer jcVideoPlayer = constructor.newInstance(getContext());
jcVideoPlayer.setId(TINY_ID);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(400, 400);
lp.gravity = Gravity.RIGHT | Gravity.BOTTOM;
vp.addView(jcVideoPlayer, lp);
jcVideoPlayer.setUp(url, JCVideoPlayerStandard.SCREEN_WINDOW_TINY, objects);
jcVideoPlayer.setUiWitStateAndScreen(currentState);
jcVideoPlayer.addTextureView();
JCVideoPlayerManager.setSecondFloor(jcVideoPlayer);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public class ProgressTimerTask extends TimerTask {
@Override
public void run() {
if (currentState == CURRENT_STATE_PLAYING || currentState == CURRENT_STATE_PAUSE || currentState == CURRENT_STATE_PLAYING_BUFFERING_START) {
// Log.v(TAG, "onProgressUpdate " + position + "/" + duration + " [" + this.hashCode() + "] ");
mHandler.post(new Runnable() {
@Override
public void run() {
setProgressAndText();
}
});
}
}
}
public int getCurrentPositionWhenPlaying() {
int position = 0;
if (JCMediaManager.instance().mediaPlayer == null) return position;//这行代码不应该在这,如果代码和逻辑万无一失的话,心头之恨呐
if (currentState == CURRENT_STATE_PLAYING ||
currentState == CURRENT_STATE_PAUSE ||
currentState == CURRENT_STATE_PLAYING_BUFFERING_START) {
try {
position = JCMediaManager.instance().mediaPlayer.getCurrentPosition();
} catch (IllegalStateException e) {
e.printStackTrace();
return position;
}
}
return position;
}
public int getDuration() {
int duration = 0;
if (JCMediaManager.instance().mediaPlayer == null) return duration;
try {
duration = JCMediaManager.instance().mediaPlayer.getDuration();
} catch (IllegalStateException e) {
e.printStackTrace();
return duration;
}
return duration;
}
public void setProgressAndText() {
int position = getCurrentPositionWhenPlaying();
int duration = getDuration();
int progress = position * 100 / (duration == 0 ? 1 : duration);
if (!mTouchingProgressBar) {
if (progress != 0) progressBar.setProgress(progress);
}
if (position != 0) currentTimeTextView.setText(JCUtils.stringForTime(position));
totalTimeTextView.setText(JCUtils.stringForTime(duration));
}
public void setBufferProgress(int bufferProgress) {
if (bufferProgress != 0) progressBar.setSecondaryProgress(bufferProgress);
}
public void resetProgressAndTime() {
progressBar.setProgress(0);
progressBar.setSecondaryProgress(0);
currentTimeTextView.setText(JCUtils.stringForTime(0));
totalTimeTextView.setText(JCUtils.stringForTime(0));
}
public static AudioManager.OnAudioFocusChangeListener onAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
break;
case AudioManager.AUDIOFOCUS_LOSS:
releaseAllVideos();
Log.d(TAG, "AUDIOFOCUS_LOSS [" + this.hashCode() + "]");
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
try {
if (JCMediaManager.instance().mediaPlayer != null &&
JCMediaManager.instance().mediaPlayer.isPlaying()) {
JCMediaManager.instance().mediaPlayer.pause();
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
Log.d(TAG, "AUDIOFOCUS_LOSS_TRANSIENT [" + this.hashCode() + "]");
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
break;
}
}
};
public void release() {
if (url.equals(JCMediaManager.CURRENT_PLAYING_URL) &&
(System.currentTimeMillis() - CLICK_QUIT_FULLSCREEN_TIME) > FULL_SCREEN_NORMAL_DELAY) {
//在非全屏的情况下只能backPress()
if (JCVideoPlayerManager.getSecondFloor() != null &&
JCVideoPlayerManager.getSecondFloor().currentScreen == SCREEN_WINDOW_FULLSCREEN) {//点击全屏
} else if (JCVideoPlayerManager.getSecondFloor() == null && JCVideoPlayerManager.getFirstFloor() != null &&
JCVideoPlayerManager.getFirstFloor().currentScreen == SCREEN_WINDOW_FULLSCREEN) {//直接全屏
} else {
Log.d(TAG, "release [" + this.hashCode() + "]");
releaseAllVideos();
}
}
}
//isCurrentJcvd and isCurrenPlayUrl should be two logic methods,isCurrentJcvd is for different jcvd with same
//url when fullscreen or tiny screen. isCurrenPlayUrl is to find where is myself when back from tiny screen.
//Sometimes they are overlap.
public boolean isCurrentJcvd() {//虽然看这个函数很不爽,但是干不掉
return JCVideoPlayerManager.getCurrentJcvd() != null
&& JCVideoPlayerManager.getCurrentJcvd() == this;
}
// public boolean isCurrenPlayingUrl() {
// return url.equals(JCMediaManager.CURRENT_PLAYING_URL);
// }
public static void releaseAllVideos() {
if ((System.currentTimeMillis() - CLICK_QUIT_FULLSCREEN_TIME) > FULL_SCREEN_NORMAL_DELAY) {
Log.d(TAG, "releaseAllVideos");
JCVideoPlayerManager.completeAll();
JCMediaManager.instance().releaseMediaPlayer();
}
}
public static void setJcUserAction(JCUserAction jcUserEvent) {
JC_USER_EVENT = jcUserEvent;
}
public void onEvent(int type) {
if (JC_USER_EVENT != null && isCurrentJcvd()) {
JC_USER_EVENT.onEvent(type, url, currentScreen, objects);
}
}
public static void startFullscreen(Context context, Class _class, String url, Object... objects) {
hideSupportActionBar(context);
JCUtils.getAppCompActivity(context).setRequestedOrientation(FULLSCREEN_ORIENTATION);
ViewGroup vp = (ViewGroup) (JCUtils.scanForActivity(context))//.getWindow().getDecorView();
.findViewById(Window.ID_ANDROID_CONTENT);
View old = vp.findViewById(JCVideoPlayer.FULLSCREEN_ID);
if (old != null) {
vp.removeView(old);
}
try {
Constructor<JCVideoPlayer> constructor = _class.getConstructor(Context.class);
final JCVideoPlayer jcVideoPlayer = constructor.newInstance(context);
jcVideoPlayer.setId(JCVideoPlayer.FULLSCREEN_ID);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
vp.addView(jcVideoPlayer, lp);
// final Animation ra = AnimationUtils.loadAnimation(context, R.anim.start_fullscreen);
// jcVideoPlayer.setAnimation(ra);
jcVideoPlayer.setUp(url, JCVideoPlayerStandard.SCREEN_WINDOW_FULLSCREEN, objects);
CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
jcVideoPlayer.startButton.performClick();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void hideSupportActionBar(Context context) {
if (ACTION_BAR_EXIST) {
ActionBar ab = JCUtils.getAppCompActivity(context).getSupportActionBar();
if (ab != null) {
ab.setShowHideAnimationEnabled(false);
ab.hide();
}
}
if (TOOL_BAR_EXIST) {
JCUtils.getAppCompActivity(context).getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
public static void showSupportActionBar(Context context) {
if (ACTION_BAR_EXIST) {
ActionBar ab = JCUtils.getAppCompActivity(context).getSupportActionBar();
if (ab != null) {
ab.setShowHideAnimationEnabled(false);
ab.show();
}
}
if (TOOL_BAR_EXIST) {
JCUtils.getAppCompActivity(context).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
public static class JCAutoFullscreenListener implements SensorEventListener {
@Override
public void onSensorChanged(SensorEvent event) {//可以得到传感器实时测量出来的变化值
final float x = event.values[SensorManager.DATA_X];
float y = event.values[SensorManager.DATA_Y];
float z = event.values[SensorManager.DATA_Z];
//过滤掉用力过猛会有一个反向的大数值
if (((x > -15 && x < -10) || (x < 15 && x > 10)) && Math.abs(y) < 1.5) {
if ((System.currentTimeMillis() - lastAutoFullscreenTime) > 2000) {
if (JCVideoPlayerManager.getCurrentJcvd() != null) {
JCVideoPlayerManager.getCurrentJcvd().autoFullscreen(x);
}
lastAutoFullscreenTime = System.currentTimeMillis();
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
public static void clearSavedProgress(Context context, String url) {
JCUtils.clearSavedProgress(context, url);
}
public void showWifiDialog() {
}
public void showProgressDialog(float deltaX,
String seekTime, int seekTimePosition,
String totalTime, int totalTimeDuration) {
}
public void dismissProgressDialog() {
}
public void showVolumeDialog(float deltaY, int volumePercent) {
}
public void dismissVolumeDialog() {
}
public void showBrightnessDialog(int brightnessPercent) {
}
public void dismissBrightnessDialog() {
}
public abstract int getLayoutId();
}
| fix importent bug
| jcvideoplayer-lib/src/main/java/fm/jiecao/jcvideoplayer_lib/JCVideoPlayer.java | fix importent bug | <ide><path>cvideoplayer-lib/src/main/java/fm/jiecao/jcvideoplayer_lib/JCVideoPlayer.java
<ide> backPress();
<ide> }
<ide> JCUtils.saveProgress(getContext(), url, 0);
<del>
<del>// JCMediaManager.textureView = null;
<del> JCMediaManager.savedSurfaceTexture = null;
<ide> }
<ide>
<ide> public void onCompletion() { |
|
Java | apache-2.0 | a90da9fe37dcd3b81819606d3fc1862300fdd110 | 0 | alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,adedayo/intellij-community,caot/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,ryano144/intellij-community,kool79/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,signed/intellij-community,ahb0327/intellij-community,kool79/intellij-community,ibinti/intellij-community,slisson/intellij-community,holmes/intellij-community,youdonghai/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,amith01994/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,diorcety/intellij-community,jagguli/intellij-community,supersven/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,xfournet/intellij-community,allotria/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,izonder/intellij-community,robovm/robovm-studio,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,asedunov/intellij-community,ernestp/consulo,asedunov/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,ernestp/consulo,ahb0327/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,ryano144/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,izonder/intellij-community,samthor/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,holmes/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,ibinti/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,amith01994/intellij-community,suncycheng/intellij-community,da1z/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,caot/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,clumsy/intellij-community,apixandru/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,samthor/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,samthor/intellij-community,semonte/intellij-community,ibinti/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,caot/intellij-community,consulo/consulo,blademainer/intellij-community,da1z/intellij-community,allotria/intellij-community,samthor/intellij-community,slisson/intellij-community,supersven/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,caot/intellij-community,retomerz/intellij-community,ernestp/consulo,blademainer/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,allotria/intellij-community,holmes/intellij-community,amith01994/intellij-community,kool79/intellij-community,allotria/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,ryano144/intellij-community,jagguli/intellij-community,fnouama/intellij-community,clumsy/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,supersven/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,robovm/robovm-studio,clumsy/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,da1z/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,fitermay/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,semonte/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,allotria/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,diorcety/intellij-community,caot/intellij-community,youdonghai/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,ibinti/intellij-community,samthor/intellij-community,holmes/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,consulo/consulo,TangHao1987/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,slisson/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,wreckJ/intellij-community,xfournet/intellij-community,signed/intellij-community,izonder/intellij-community,fnouama/intellij-community,retomerz/intellij-community,apixandru/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,semonte/intellij-community,tmpgit/intellij-community,supersven/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,signed/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,amith01994/intellij-community,supersven/intellij-community,supersven/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,kool79/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,ernestp/consulo,caot/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,semonte/intellij-community,holmes/intellij-community,orekyuu/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,izonder/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,caot/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,consulo/consulo,da1z/intellij-community,signed/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,consulo/consulo,nicolargo/intellij-community,adedayo/intellij-community,da1z/intellij-community,hurricup/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,ernestp/consulo,vladmm/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,FHannes/intellij-community,dslomov/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,petteyg/intellij-community,ryano144/intellij-community,samthor/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,petteyg/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,allotria/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,semonte/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,allotria/intellij-community,izonder/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,signed/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,holmes/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,allotria/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,izonder/intellij-community,da1z/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,semonte/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,allotria/intellij-community,adedayo/intellij-community,amith01994/intellij-community,fitermay/intellij-community,fitermay/intellij-community,clumsy/intellij-community,hurricup/intellij-community,FHannes/intellij-community,signed/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,da1z/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,retomerz/intellij-community,da1z/intellij-community,allotria/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,caot/intellij-community,wreckJ/intellij-community,da1z/intellij-community,FHannes/intellij-community,kdwink/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,kool79/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,samthor/intellij-community,ibinti/intellij-community,robovm/robovm-studio,fnouama/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,slisson/intellij-community,signed/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,kdwink/intellij-community,retomerz/intellij-community,supersven/intellij-community,jagguli/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,izonder/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,kdwink/intellij-community,ibinti/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,retomerz/intellij-community,vladmm/intellij-community,holmes/intellij-community,consulo/consulo,jagguli/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,fitermay/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,caot/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,consulo/consulo,MER-GROUP/intellij-community,xfournet/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,clumsy/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,diorcety/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,caot/intellij-community,signed/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,caot/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,ryano144/intellij-community,hurricup/intellij-community,da1z/intellij-community,FHannes/intellij-community,dslomov/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,akosyakov/intellij-community,semonte/intellij-community,kool79/intellij-community,slisson/intellij-community,holmes/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,izonder/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,retomerz/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community | class Test1 {
void foo(){}
{
Comparable<String> a = new Comparable<String>() {
@Override
public int compareTo(final String o) {
<selection>new Runnable() {
@Override
public void run() {
System.out.println(o);
}
}.run();
return 0;</selection>
}
};
}
} | plugins/IntentionPowerPak/test/com/siyeh/ipp/types/lambda2anonymous/InsertFinal_after.java | class Test1 {
void foo(){}
{
Comparable<String> a = new Comparable<String>() {
@Override
public int compareTo(final String o) {
<selection>new Runnable() {
@Override
public void run() {
System.out.println(o);
}
}.run();
return 0;</selection>
}
};
}
} | fix testdata
| plugins/IntentionPowerPak/test/com/siyeh/ipp/types/lambda2anonymous/InsertFinal_after.java | fix testdata | <ide><path>lugins/IntentionPowerPak/test/com/siyeh/ipp/types/lambda2anonymous/InsertFinal_after.java
<ide> }
<ide> };
<ide> }
<del>}
<add>} |
|
Java | bsd-3-clause | 52ed32cb451af8b8538d23d341efeaa1823c2d91 | 0 | markles/GeoGit,annacarol/GeoGig,markles/GeoGit,boundlessgeo/GeoGig,markles/GeoGit,boundlessgeo/GeoGig,markles/GeoGit,annacarol/GeoGig,markles/GeoGit,annacarol/GeoGig,boundlessgeo/GeoGig | /* Copyright (c) 2013 OpenPlans. All rights reserved.
* This code is licensed under the BSD New License, available at the root
* application directory.
*/
package org.geogit.api.plumbing;
import static com.google.common.base.Preconditions.checkState;
import java.util.List;
import javax.annotation.Nullable;
import org.geogit.api.AbstractGeoGitOp;
import org.geogit.api.ObjectId;
import org.geogit.api.RevTree;
import org.geogit.api.plumbing.diff.DiffCountConsumer;
import org.geogit.api.plumbing.diff.DiffObjectCount;
import org.geogit.api.plumbing.diff.DiffTreeVisitor;
import org.geogit.api.plumbing.diff.DiffTreeWalk;
import org.geogit.api.plumbing.diff.PathFilteringDiffConsumer;
import org.geogit.storage.StagingDatabase;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
/**
* A faster alternative to count the number of diffs between two trees than walking a
* {@link DiffTreeWalk} iterator.
*
* @see DiffCountConsumer
*/
public class DiffCount extends AbstractGeoGitOp<DiffObjectCount> {
private final List<String> pathFilters = Lists.newLinkedList();
private String oldRefSpec;
private String newRefSpec;
public DiffCount setOldVersion(@Nullable String refSpec) {
this.oldRefSpec = refSpec;
return this;
}
public DiffCount setNewVersion(@Nullable String refSpec) {
this.newRefSpec = refSpec;
return this;
}
/**
* @param path the path filter to use during the diff operation
* @return {@code this}
*/
public DiffCount addFilter(@Nullable String path) {
if (path != null) {
pathFilters.add(path);
}
return this;
}
/**
* @param paths list of paths to filter by, if {@code null} or empty, then no filtering is done,
* otherwise the list must not contain null elements.
*/
public DiffCount setFilter(@Nullable List<String> paths) {
pathFilters.clear();
if (paths != null) {
pathFilters.addAll(paths);
}
return this;
}
@Override
protected DiffObjectCount _call() {
checkState(oldRefSpec != null, "old ref spec not provided");
checkState(newRefSpec != null, "new ref spec not provided");
final RevTree oldTree = getTree(oldRefSpec);
final RevTree newTree = getTree(newRefSpec);
DiffObjectCount diffCount;
StagingDatabase index = stagingDatabase();
DiffTreeVisitor visitor = new DiffTreeVisitor(oldTree, newTree, index, index);
DiffCountConsumer counter = new DiffCountConsumer(index);
DiffTreeVisitor.Consumer filter = counter;
if (!pathFilters.isEmpty()) {
filter = new PathFilteringDiffConsumer(pathFilters, counter);
}
visitor.walk(filter);
diffCount = counter.get();
return diffCount;
}
/**
* @return the tree referenced by the old ref, or the head of the index.
*/
private RevTree getTree(String refSpec) {
final RevTree headTree;
Optional<ObjectId> resolved = command(ResolveTreeish.class).setTreeish(refSpec).call();
if (resolved.isPresent()) {
ObjectId headTreeId = resolved.get();
headTree = command(RevObjectParse.class).setObjectId(headTreeId).call(RevTree.class)
.get();
} else {
headTree = RevTree.EMPTY;
}
return headTree;
}
}
| src/core/src/main/java/org/geogit/api/plumbing/DiffCount.java | /* Copyright (c) 2013 OpenPlans. All rights reserved.
* This code is licensed under the BSD New License, available at the root
* application directory.
*/
package org.geogit.api.plumbing;
import static com.google.common.base.Preconditions.checkState;
import java.util.List;
import javax.annotation.Nullable;
import org.geogit.api.AbstractGeoGitOp;
import org.geogit.api.ObjectId;
import org.geogit.api.RevTree;
import org.geogit.api.plumbing.diff.DiffCountConsumer;
import org.geogit.api.plumbing.diff.DiffObjectCount;
import org.geogit.api.plumbing.diff.DiffTreeVisitor;
import org.geogit.api.plumbing.diff.DiffTreeWalk;
import org.geogit.api.plumbing.diff.PathFilteringDiffConsumer;
import org.geogit.storage.StagingDatabase;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
/**
* A faster alternative to count the number of diffs between two trees than walking a
* {@link DiffTreeWalk} iterator.
*
* @see DiffCountConsumer
*/
public class DiffCount extends AbstractGeoGitOp<DiffObjectCount> {
private final List<String> pathFilters = Lists.newLinkedList();
private String oldRefSpec;
private String newRefSpec;
public DiffCount setOldVersion(@Nullable String refSpec) {
this.oldRefSpec = refSpec;
return this;
}
public DiffCount setNewVersion(@Nullable String refSpec) {
this.newRefSpec = refSpec;
return this;
}
/**
* @param path the path filter to use during the diff operation
* @return {@code this}
*/
public DiffCount addFilter(@Nullable String path) {
if (path != null) {
pathFilters.add(path);
}
return this;
}
/**
* @param paths list of paths to filter by, if {@code null} or empty, then no filtering is done,
* otherwise the list must not contain null elements.
*/
public DiffCount setFilter(@Nullable List<String> paths) {
pathFilters.clear();
if (paths != null) {
pathFilters.addAll(paths);
}
return this;
}
@Override
protected DiffObjectCount _call() {
checkState(oldRefSpec != null, "old ref spec not provided");
checkState(newRefSpec != null, "new ref spec not provided");
final RevTree oldTree = getTree(oldRefSpec);
final RevTree newTree = getTree(newRefSpec);
DiffObjectCount diffCount;
StagingDatabase index = stagingDatabase();
DiffTreeVisitor visitor = new DiffTreeVisitor(oldTree, newTree, index, index);
DiffCountConsumer counter = new DiffCountConsumer(index);
DiffTreeVisitor.Consumer filter = counter;
if (!pathFilters.isEmpty()) {
filter = new PathFilteringDiffConsumer(pathFilters, counter);
}
visitor.walk(filter);
diffCount = counter.get();
return diffCount;
}
/**
* @return the tree referenced by the old ref, or the head of the index.
*/
private RevTree getTree(String refSpec) {
final RevTree headTree;
Optional<ObjectId> resolved = command(ResolveTreeish.class).setTreeish(refSpec).call();
if (resolved.isPresent() && !resolved.get().isNull()) {
ObjectId headTreeId = resolved.get();
headTree = command(RevObjectParse.class).setObjectId(headTreeId).call(RevTree.class)
.get();
} else {
headTree = RevTree.EMPTY;
}
return headTree;
}
}
| Remove unnecesary check for null id after 16cb52117 is merged
| src/core/src/main/java/org/geogit/api/plumbing/DiffCount.java | Remove unnecesary check for null id after 16cb52117 is merged | <ide><path>rc/core/src/main/java/org/geogit/api/plumbing/DiffCount.java
<ide>
<ide> final RevTree headTree;
<ide> Optional<ObjectId> resolved = command(ResolveTreeish.class).setTreeish(refSpec).call();
<del> if (resolved.isPresent() && !resolved.get().isNull()) {
<add> if (resolved.isPresent()) {
<ide> ObjectId headTreeId = resolved.get();
<ide> headTree = command(RevObjectParse.class).setObjectId(headTreeId).call(RevTree.class)
<ide> .get(); |
|
Java | apache-2.0 | fabec3b8e1d18974b4a38db3f16d9a7622c2718d | 0 | mohanaraosv/commons-dbcp,mohanaraosv/commons-dbcp,mohanaraosv/commons-dbcp | /*
* 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.dbcp.datasources;
import java.io.Serializable;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.NoSuchElementException;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import javax.naming.Referenceable;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.DataSource;
import javax.sql.PooledConnection;
import org.apache.commons.dbcp.SQLNestedException;
import org.apache.commons.pool.impl.GenericObjectPool;
/**
* <p>The base class for <code>SharedPoolDataSource</code> and
* <code>PerUserPoolDataSource</code>. Many of the configuration properties
* are shared and defined here. This class is declared public in order
* to allow particular usage with commons-beanutils; do not make direct
* use of it outside of commons-dbcp.
* </p>
*
* <p>
* A J2EE container will normally provide some method of initializing the
* <code>DataSource</code> whose attributes are presented
* as bean getters/setters and then deploying it via JNDI. It is then
* available to an application as a source of pooled logical connections to
* the database. The pool needs a source of physical connections. This
* source is in the form of a <code>ConnectionPoolDataSource</code> that
* can be specified via the {@link #setDataSourceName(String)} used to
* lookup the source via JNDI.
* </p>
*
* <p>
* Although normally used within a JNDI environment, A DataSource
* can be instantiated and initialized as any bean. In this case the
* <code>ConnectionPoolDataSource</code> will likely be instantiated in
* a similar manner. This class allows the physical source of connections
* to be attached directly to this pool using the
* {@link #setConnectionPoolDataSource(ConnectionPoolDataSource)} method.
* </p>
*
* <p>
* The dbcp package contains an adapter,
* {@link org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS},
* that can be used to allow the use of <code>DataSource</code>'s based on this
* class with jdbc driver implementations that do not supply a
* <code>ConnectionPoolDataSource</code>, but still
* provide a {@link java.sql.Driver} implementation.
* </p>
*
* <p>
* The <a href="package-summary.html">package documentation</a> contains an
* example using Apache Tomcat and JNDI and it also contains a non-JNDI example.
* </p>
*
* @author John D. McNally
* @version $Revision$ $Date$
*/
public abstract class InstanceKeyDataSource
implements DataSource, Referenceable, Serializable {
private static final long serialVersionUID = -4243533936955098795L;
private static final String GET_CONNECTION_CALLED
= "A Connection was already requested from this source, "
+ "further initialization is not allowed.";
private static final String BAD_TRANSACTION_ISOLATION
= "The requested TransactionIsolation level is invalid.";
/**
* Internal constant to indicate the level is not set.
*/
protected static final int UNKNOWN_TRANSACTIONISOLATION = -1;
/** Guards property setters - once true, setters throw IllegalStateException */
private volatile boolean getConnectionCalled = false;
/** Underlying source of PooledConnections */
private ConnectionPoolDataSource dataSource = null;
/** DataSource Name used to find the ConnectionPoolDataSource */
private String dataSourceName = null;
// Default connection properties
private boolean defaultAutoCommit = false;
private int defaultTransactionIsolation = UNKNOWN_TRANSACTIONISOLATION;
private boolean defaultReadOnly = false;
/** Description */
private String description = null;
/** Environment that may be used to set up a jndi initial context. */
Properties jndiEnvironment = null;
/** Login TimeOut in seconds */
private int loginTimeout = 0;
/** Log stream */
private PrintWriter logWriter = null;
// Pool properties
private boolean _testOnBorrow = GenericObjectPool.DEFAULT_TEST_ON_BORROW;
private boolean _testOnReturn = GenericObjectPool.DEFAULT_TEST_ON_RETURN;
private int _timeBetweenEvictionRunsMillis = (int)
Math.min(Integer.MAX_VALUE,
GenericObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS);
private int _numTestsPerEvictionRun =
GenericObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
private int _minEvictableIdleTimeMillis = (int)
Math.min(Integer.MAX_VALUE,
GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
private boolean _testWhileIdle = GenericObjectPool.DEFAULT_TEST_WHILE_IDLE;
private String validationQuery = null;
private boolean rollbackAfterValidation = false;
/** true iff one of the setters for testOnBorrow, testOnReturn, testWhileIdle has been called. */
private boolean testPositionSet = false;
/** Instance key */
protected String instanceKey = null;
/**
* Default no-arg constructor for Serialization
*/
public InstanceKeyDataSource() {
defaultAutoCommit = true;
}
/**
* Throws an IllegalStateException, if a PooledConnection has already
* been requested.
*/
protected void assertInitializationAllowed()
throws IllegalStateException {
if (getConnectionCalled) {
throw new IllegalStateException(GET_CONNECTION_CALLED);
}
}
/**
* Close the connection pool being maintained by this datasource.
*/
public abstract void close() throws Exception;
protected abstract PooledConnectionManager getConnectionManager(UserPassKey upkey);
/* JDBC_4_ANT_KEY_BEGIN */
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
public <T> T unwrap(Class<T> iface) throws SQLException {
throw new SQLException("InstanceKeyDataSource is not a wrapper.");
}
/* JDBC_4_ANT_KEY_END */
// -------------------------------------------------------------------
// Properties
/**
* Get the value of connectionPoolDataSource. This method will return
* null, if the backing datasource is being accessed via jndi.
*
* @return value of connectionPoolDataSource.
*/
public ConnectionPoolDataSource getConnectionPoolDataSource() {
return dataSource;
}
/**
* Set the backend ConnectionPoolDataSource. This property should not be
* set if using jndi to access the datasource.
*
* @param v Value to assign to connectionPoolDataSource.
*/
public void setConnectionPoolDataSource(ConnectionPoolDataSource v) {
assertInitializationAllowed();
if (dataSourceName != null) {
throw new IllegalStateException(
"Cannot set the DataSource, if JNDI is used.");
}
if (dataSource != null)
{
throw new IllegalStateException(
"The CPDS has already been set. It cannot be altered.");
}
dataSource = v;
instanceKey = InstanceKeyObjectFactory.registerNewInstance(this);
}
/**
* Get the name of the ConnectionPoolDataSource which backs this pool.
* This name is used to look up the datasource from a jndi service
* provider.
*
* @return value of dataSourceName.
*/
public String getDataSourceName() {
return dataSourceName;
}
/**
* Set the name of the ConnectionPoolDataSource which backs this pool.
* This name is used to look up the datasource from a jndi service
* provider.
*
* @param v Value to assign to dataSourceName.
*/
public void setDataSourceName(String v) {
assertInitializationAllowed();
if (dataSource != null) {
throw new IllegalStateException(
"Cannot set the JNDI name for the DataSource, if already " +
"set using setConnectionPoolDataSource.");
}
if (dataSourceName != null)
{
throw new IllegalStateException(
"The DataSourceName has already been set. " +
"It cannot be altered.");
}
this.dataSourceName = v;
instanceKey = InstanceKeyObjectFactory.registerNewInstance(this);
}
/**
* Get the value of defaultAutoCommit, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setAutoCommit(boolean).
* The default is true.
*
* @return value of defaultAutoCommit.
*/
public boolean isDefaultAutoCommit() {
return defaultAutoCommit;
}
/**
* Set the value of defaultAutoCommit, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setAutoCommit(boolean).
* The default is true.
*
* @param v Value to assign to defaultAutoCommit.
*/
public void setDefaultAutoCommit(boolean v) {
assertInitializationAllowed();
this.defaultAutoCommit = v;
}
/**
* Get the value of defaultReadOnly, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setReadOnly(boolean).
* The default is false.
*
* @return value of defaultReadOnly.
*/
public boolean isDefaultReadOnly() {
return defaultReadOnly;
}
/**
* Set the value of defaultReadOnly, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setReadOnly(boolean).
* The default is false.
*
* @param v Value to assign to defaultReadOnly.
*/
public void setDefaultReadOnly(boolean v) {
assertInitializationAllowed();
this.defaultReadOnly = v;
}
/**
* Get the value of defaultTransactionIsolation, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setTransactionIsolation(int).
* If this method returns -1, the default is JDBC driver dependent.
*
* @return value of defaultTransactionIsolation.
*/
public int getDefaultTransactionIsolation() {
return defaultTransactionIsolation;
}
/**
* Set the value of defaultTransactionIsolation, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setTransactionIsolation(int).
* The default is JDBC driver dependent.
*
* @param v Value to assign to defaultTransactionIsolation
*/
public void setDefaultTransactionIsolation(int v) {
assertInitializationAllowed();
switch (v) {
case Connection.TRANSACTION_NONE:
case Connection.TRANSACTION_READ_COMMITTED:
case Connection.TRANSACTION_READ_UNCOMMITTED:
case Connection.TRANSACTION_REPEATABLE_READ:
case Connection.TRANSACTION_SERIALIZABLE:
break;
default:
throw new IllegalArgumentException(BAD_TRANSACTION_ISOLATION);
}
this.defaultTransactionIsolation = v;
}
/**
* Get the description. This property is defined by jdbc as for use with
* GUI (or other) tools that might deploy the datasource. It serves no
* internal purpose.
*
* @return value of description.
*/
public String getDescription() {
return description;
}
/**
* Set the description. This property is defined by jdbc as for use with
* GUI (or other) tools that might deploy the datasource. It serves no
* internal purpose.
*
* @param v Value to assign to description.
*/
public void setDescription(String v) {
this.description = v;
}
/**
* Get the value of jndiEnvironment which is used when instantiating
* a jndi InitialContext. This InitialContext is used to locate the
* backend ConnectionPoolDataSource.
*
* @return value of jndiEnvironment.
*/
public String getJndiEnvironment(String key) {
String value = null;
if (jndiEnvironment != null) {
value = jndiEnvironment.getProperty(key);
}
return value;
}
/**
* Sets the value of the given JNDI environment property to be used when
* instantiating a JNDI InitialContext. This InitialContext is used to
* locate the backend ConnectionPoolDataSource.
*
* @param key the JNDI environment property to set.
* @param value the value assigned to specified JNDI environment property.
*/
public void setJndiEnvironment(String key, String value) {
if (jndiEnvironment == null) {
jndiEnvironment = new Properties();
}
jndiEnvironment.setProperty(key, value);
}
/**
* Get the value of loginTimeout.
* @return value of loginTimeout.
*/
public int getLoginTimeout() {
return loginTimeout;
}
/**
* Set the value of loginTimeout.
* @param v Value to assign to loginTimeout.
*/
public void setLoginTimeout(int v) {
this.loginTimeout = v;
}
/**
* Get the value of logWriter.
* @return value of logWriter.
*/
public PrintWriter getLogWriter() {
if (logWriter == null) {
logWriter = new PrintWriter(System.out);
}
return logWriter;
}
/**
* Set the value of logWriter.
* @param v Value to assign to logWriter.
*/
public void setLogWriter(PrintWriter v) {
this.logWriter = v;
}
/**
* @see #getTestOnBorrow
*/
public final boolean isTestOnBorrow() {
return getTestOnBorrow();
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* before being returned by the {*link #borrowObject}
* method. If the object fails to validate,
* it will be dropped from the pool, and we will attempt
* to borrow another.
*
* @see #setTestOnBorrow
*/
public boolean getTestOnBorrow() {
return _testOnBorrow;
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* before being returned by the {*link #borrowObject}
* method. If the object fails to validate,
* it will be dropped from the pool, and we will attempt
* to borrow another. For a <code>true</code> value to have any effect,
* the <code>validationQuery</code> property must be set to a non-null
* string.
*
* @see #getTestOnBorrow
*/
public void setTestOnBorrow(boolean testOnBorrow) {
assertInitializationAllowed();
_testOnBorrow = testOnBorrow;
testPositionSet = true;
}
/**
* @see #getTestOnReturn
*/
public final boolean isTestOnReturn() {
return getTestOnReturn();
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* before being returned to the pool within the
* {*link #returnObject}.
*
* @see #setTestOnReturn
*/
public boolean getTestOnReturn() {
return _testOnReturn;
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* before being returned to the pool within the
* {*link #returnObject}. For a <code>true</code> value to have any effect,
* the <code>validationQuery</code> property must be set to a non-null
* string.
*
* @see #getTestOnReturn
*/
public void setTestOnReturn(boolean testOnReturn) {
assertInitializationAllowed();
_testOnReturn = testOnReturn;
testPositionSet = true;
}
/**
* Returns the number of milliseconds to sleep between runs of the
* idle object evictor thread.
* When non-positive, no idle object evictor thread will be
* run.
*
* @see #setTimeBetweenEvictionRunsMillis
*/
public int getTimeBetweenEvictionRunsMillis() {
return _timeBetweenEvictionRunsMillis;
}
/**
* Sets the number of milliseconds to sleep between runs of the
* idle object evictor thread.
* When non-positive, no idle object evictor thread will be
* run.
*
* @see #getTimeBetweenEvictionRunsMillis
*/
public void
setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) {
assertInitializationAllowed();
_timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
/**
* Returns the number of objects to examine during each run of the
* idle object evictor thread (if any).
*
* @see #setNumTestsPerEvictionRun
* @see #setTimeBetweenEvictionRunsMillis
*/
public int getNumTestsPerEvictionRun() {
return _numTestsPerEvictionRun;
}
/**
* Sets the number of objects to examine during each run of the
* idle object evictor thread (if any).
* <p>
* When a negative value is supplied, <tt>ceil({*link #numIdle})/abs({*link #getNumTestsPerEvictionRun})</tt>
* tests will be run. I.e., when the value is <i>-n</i>, roughly one <i>n</i>th of the
* idle objects will be tested per run.
*
* @see #getNumTestsPerEvictionRun
* @see #setTimeBetweenEvictionRunsMillis
*/
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
assertInitializationAllowed();
_numTestsPerEvictionRun = numTestsPerEvictionRun;
}
/**
* Returns the minimum amount of time an object may sit idle in the pool
* before it is eligable for eviction by the idle object evictor
* (if any).
*
* @see #setMinEvictableIdleTimeMillis
* @see #setTimeBetweenEvictionRunsMillis
*/
public int getMinEvictableIdleTimeMillis() {
return _minEvictableIdleTimeMillis;
}
/**
* Sets the minimum amount of time an object may sit idle in the pool
* before it is eligable for eviction by the idle object evictor
* (if any).
* When non-positive, no objects will be evicted from the pool
* due to idle time alone.
*
* @see #getMinEvictableIdleTimeMillis
* @see #setTimeBetweenEvictionRunsMillis
*/
public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) {
assertInitializationAllowed();
_minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
/**
* @see #getTestWhileIdle
*/
public final boolean isTestWhileIdle() {
return getTestWhileIdle();
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* by the idle object evictor (if any). If an object
* fails to validate, it will be dropped from the pool.
*
* @see #setTestWhileIdle
* @see #setTimeBetweenEvictionRunsMillis
*/
public boolean getTestWhileIdle() {
return _testWhileIdle;
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* by the idle object evictor (if any). If an object
* fails to validate, it will be dropped from the pool. For a
* <code>true</code> value to have any effect,
* the <code>validationQuery</code> property must be set to a non-null
* string.
*
* @see #getTestWhileIdle
* @see #setTimeBetweenEvictionRunsMillis
*/
public void setTestWhileIdle(boolean testWhileIdle) {
assertInitializationAllowed();
_testWhileIdle = testWhileIdle;
testPositionSet = true;
}
/**
* The SQL query that will be used to validate connections from this pool
* before returning them to the caller. If specified, this query
* <strong>MUST</strong> be an SQL SELECT statement that returns at least
* one row.
*/
public String getValidationQuery() {
return (this.validationQuery);
}
/**
* The SQL query that will be used to validate connections from this pool
* before returning them to the caller. If specified, this query
* <strong>MUST</strong> be an SQL SELECT statement that returns at least
* one row. If none of the properties, testOnBorow, testOnReturn, testWhileIdle
* have been previously set, calling this method sets testOnBorrow to true.
*/
public void setValidationQuery(String validationQuery) {
assertInitializationAllowed();
this.validationQuery = validationQuery;
if (!testPositionSet) {
setTestOnBorrow(true);
}
}
/**
* Whether a rollback will be issued after executing the SQL query
* that will be used to validate connections from this pool
* before returning them to the caller.
*
* @return true if a rollback will be issued after executing the
* validation query
* @since 1.2.2
*/
public boolean isRollbackAfterValidation() {
return (this.rollbackAfterValidation);
}
/**
* Whether a rollback will be issued after executing the SQL query
* that will be used to validate connections from this pool
* before returning them to the caller. Default behavior is NOT
* to issue a rollback. The setting will only have an effect
* if a validation query is set
*
* @param rollbackAfterValidation new property value
* @since 1.2.2
*/
public void setRollbackAfterValidation(boolean rollbackAfterValidation) {
assertInitializationAllowed();
this.rollbackAfterValidation = rollbackAfterValidation;
}
// ----------------------------------------------------------------------
// Instrumentation Methods
// ----------------------------------------------------------------------
// DataSource implementation
/**
* Attempt to establish a database connection.
*/
public Connection getConnection() throws SQLException {
return getConnection(null, null);
}
/**
* Attempt to retrieve a database connection using {@link #getPooledConnectionAndInfo(String, String)}
* with the provided username and password. The password on the {@link PooledConnectionAndInfo}
* instance returned by <code>getPooledConnectionAndInfo</code> is compared to the <code>password</code>
* parameter. If the comparison fails, a database connection using the supplied username and password
* is attempted. If the connection attempt fails, an SQLException is thrown, indicating that the given password
* did not match the password used to create the pooled connection. If the connection attempt succeeds, this
* means that the database password has been changed. In this case, the <code>PooledConnectionAndInfo</code>
* instance retrieved with the old password is destroyed and the <code>getPooledConnectionAndInfo</code> is
* repeatedly invoked until a <code>PooledConnectionAndInfo</code> instance with the new password is returned.
*
*/
public Connection getConnection(String username, String password)
throws SQLException {
if (instanceKey == null) {
throw new SQLException("Must set the ConnectionPoolDataSource "
+ "through setDataSourceName or setConnectionPoolDataSource"
+ " before calling getConnection.");
}
getConnectionCalled = true;
PooledConnectionAndInfo info = null;
try {
info = getPooledConnectionAndInfo(username, password);
} catch (NoSuchElementException e) {
closeDueToException(info);
throw new SQLNestedException("Cannot borrow connection from pool", e);
} catch (RuntimeException e) {
closeDueToException(info);
throw e;
} catch (SQLException e) {
closeDueToException(info);
throw e;
} catch (Exception e) {
closeDueToException(info);
throw new SQLNestedException("Cannot borrow connection from pool", e);
}
if (!(null == password ? null == info.getPassword()
: password.equals(info.getPassword()))) { // Password on PooledConnectionAndInfo does not match
try { // See if password has changed by attempting connection
testCPDS(username, password);
} catch (SQLException ex) {
// Password has not changed, so refuse client, but return connection to the pool
closeDueToException(info);
throw new SQLException("Given password did not match password used"
+ " to create the PooledConnection.");
} catch (javax.naming.NamingException ne) {
throw (SQLException) new SQLException(
"NamingException encountered connecting to database").initCause(ne);
}
/*
* Password must have changed -> destroy connection and keep retrying until we get a new, good one,
* destroying any idle connections with the old passowrd as we pull them from the pool.
*/
final UserPassKey upkey = info.getUserPassKey();
final PooledConnectionManager manager = getConnectionManager(upkey);
manager.invalidate(info.getPooledConnection()); // Destroy and remove from pool
manager.setPassword(upkey.getPassword()); // Reset the password on the factory if using CPDSConnectionFactory
info = null;
for (int i = 0; i < 10; i++) { // Bound the number of retries - only needed if bad instances return
try {
info = getPooledConnectionAndInfo(username, password);
} catch (NoSuchElementException e) {
closeDueToException(info);
throw new SQLNestedException("Cannot borrow connection from pool", e);
} catch (RuntimeException e) {
closeDueToException(info);
throw e;
} catch (SQLException e) {
closeDueToException(info);
throw e;
} catch (Exception e) {
closeDueToException(info);
throw new SQLNestedException("Cannot borrow connection from pool", e);
}
if (info != null && password.equals(info.getPassword())) {
break;
} else {
if (info != null) {
manager.invalidate(info.getPooledConnection());
}
info = null;
}
}
if (info == null) {
throw new SQLException("Cannot borrow connection from pool - password change failure.");
}
}
Connection con = info.getPooledConnection().getConnection();
try {
setupDefaults(con, username);
con.clearWarnings();
return con;
} catch (SQLException ex) {
try {
con.close();
} catch (Exception exc) {
getLogWriter().println(
"ignoring exception during close: " + exc);
}
throw ex;
}
}
protected abstract PooledConnectionAndInfo
getPooledConnectionAndInfo(String username, String password)
throws SQLException;
protected abstract void setupDefaults(Connection con, String username)
throws SQLException;
private void closeDueToException(PooledConnectionAndInfo info) {
if (info != null) {
try {
info.getPooledConnection().getConnection().close();
} catch (Exception e) {
// do not throw this exception because we are in the middle
// of handling another exception. But record it because
// it potentially leaks connections from the pool.
getLogWriter().println("[ERROR] Could not return connection to "
+ "pool during exception handling. " + e.getMessage());
}
}
}
protected ConnectionPoolDataSource
testCPDS(String username, String password)
throws javax.naming.NamingException, SQLException {
// The source of physical db connections
ConnectionPoolDataSource cpds = this.dataSource;
if (cpds == null) {
Context ctx = null;
if (jndiEnvironment == null) {
ctx = new InitialContext();
} else {
ctx = new InitialContext(jndiEnvironment);
}
Object ds = ctx.lookup(dataSourceName);
if (ds instanceof ConnectionPoolDataSource) {
cpds = (ConnectionPoolDataSource) ds;
} else {
throw new SQLException("Illegal configuration: "
+ "DataSource " + dataSourceName
+ " (" + ds.getClass().getName() + ")"
+ " doesn't implement javax.sql.ConnectionPoolDataSource");
}
}
// try to get a connection with the supplied username/password
PooledConnection conn = null;
try {
if (username != null) {
conn = cpds.getPooledConnection(username, password);
}
else {
conn = cpds.getPooledConnection();
}
if (conn == null) {
throw new SQLException(
"Cannot connect using the supplied username/password");
}
}
finally {
if (conn != null) {
try {
conn.close();
}
catch (SQLException e) {
// at least we could connect
}
}
}
return cpds;
}
protected byte whenExhaustedAction(int maxActive, int maxWait) {
byte whenExhausted = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
if (maxActive <= 0) {
whenExhausted = GenericObjectPool.WHEN_EXHAUSTED_GROW;
} else if (maxWait == 0) {
whenExhausted = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
}
return whenExhausted;
}
// ----------------------------------------------------------------------
// Referenceable implementation
/**
* Retrieves the Reference of this object.
* <strong>Note:</strong> <code>InstanceKeyDataSource</code> subclasses
* should override this method. The implementaion included below
* is not robust and will be removed at the next major version DBCP
* release.
*
* @return The non-null Reference of this object.
* @exception NamingException If a naming exception was encountered
* while retrieving the reference.
*/
// TODO: Remove the implementation of this method at next major
// version release.
public Reference getReference() throws NamingException {
final String className = getClass().getName();
final String factoryName = className + "Factory"; // XXX: not robust
Reference ref = new Reference(className, factoryName, null);
ref.add(new StringRefAddr("instanceKey", instanceKey));
return ref;
}
}
| src/java/org/apache/commons/dbcp/datasources/InstanceKeyDataSource.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.dbcp.datasources;
import java.io.Serializable;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.NoSuchElementException;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import javax.naming.Referenceable;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.DataSource;
import javax.sql.PooledConnection;
import org.apache.commons.dbcp.SQLNestedException;
import org.apache.commons.pool.impl.GenericObjectPool;
/**
* <p>The base class for <code>SharedPoolDataSource</code> and
* <code>PerUserPoolDataSource</code>. Many of the configuration properties
* are shared and defined here. This class is declared public in order
* to allow particular usage with commons-beanutils; do not make direct
* use of it outside of commons-dbcp.
* </p>
*
* <p>
* A J2EE container will normally provide some method of initializing the
* <code>DataSource</code> whose attributes are presented
* as bean getters/setters and then deploying it via JNDI. It is then
* available to an application as a source of pooled logical connections to
* the database. The pool needs a source of physical connections. This
* source is in the form of a <code>ConnectionPoolDataSource</code> that
* can be specified via the {@link #setDataSourceName(String)} used to
* lookup the source via JNDI.
* </p>
*
* <p>
* Although normally used within a JNDI environment, A DataSource
* can be instantiated and initialized as any bean. In this case the
* <code>ConnectionPoolDataSource</code> will likely be instantiated in
* a similar manner. This class allows the physical source of connections
* to be attached directly to this pool using the
* {@link #setConnectionPoolDataSource(ConnectionPoolDataSource)} method.
* </p>
*
* <p>
* The dbcp package contains an adapter,
* {@link org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS},
* that can be used to allow the use of <code>DataSource</code>'s based on this
* class with jdbc driver implementations that do not supply a
* <code>ConnectionPoolDataSource</code>, but still
* provide a {@link java.sql.Driver} implementation.
* </p>
*
* <p>
* The <a href="package-summary.html">package documentation</a> contains an
* example using Apache Tomcat and JNDI and it also contains a non-JNDI example.
* </p>
*
* @author John D. McNally
* @version $Revision$ $Date$
*/
public abstract class InstanceKeyDataSource
implements DataSource, Referenceable, Serializable {
private static final long serialVersionUID = -4243533936955098795L;
private static final String GET_CONNECTION_CALLED
= "A Connection was already requested from this source, "
+ "further initialization is not allowed.";
private static final String BAD_TRANSACTION_ISOLATION
= "The requested TransactionIsolation level is invalid.";
/**
* Internal constant to indicate the level is not set.
*/
protected static final int UNKNOWN_TRANSACTIONISOLATION = -1;
/** Guards property setters - once true, setters throw IllegalStateException */
private volatile boolean getConnectionCalled = false;
private ConnectionPoolDataSource dataSource = null;
/** DataSource Name used to find the ConnectionPoolDataSource */
private String dataSourceName = null;
private boolean defaultAutoCommit = false;
private int defaultTransactionIsolation = UNKNOWN_TRANSACTIONISOLATION;
// private int maxActive = GenericObjectPool.DEFAULT_MAX_ACTIVE;
// private int maxIdle = GenericObjectPool.DEFAULT_MAX_IDLE;
// private int maxWait = (int)Math.min(Integer.MAX_VALUE,
// GenericObjectPool.DEFAULT_MAX_WAIT);
private boolean defaultReadOnly = false;
/** Description */
private String description = null;
/** Environment that may be used to set up a jndi initial context. */
Properties jndiEnvironment = null;
/** Login TimeOut in seconds */
private int loginTimeout = 0;
/** Log stream */
private PrintWriter logWriter = null;
private boolean _testOnBorrow = GenericObjectPool.DEFAULT_TEST_ON_BORROW;
private boolean _testOnReturn = GenericObjectPool.DEFAULT_TEST_ON_RETURN;
private int _timeBetweenEvictionRunsMillis = (int)
Math.min(Integer.MAX_VALUE,
GenericObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS);
private int _numTestsPerEvictionRun =
GenericObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
private int _minEvictableIdleTimeMillis = (int)
Math.min(Integer.MAX_VALUE,
GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
private boolean _testWhileIdle = GenericObjectPool.DEFAULT_TEST_WHILE_IDLE;
private String validationQuery = null;
private boolean rollbackAfterValidation = false;
private boolean testPositionSet = false;
protected String instanceKey = null;
/**
* Default no-arg constructor for Serialization
*/
public InstanceKeyDataSource() {
defaultAutoCommit = true;
}
/**
* Throws an IllegalStateException, if a PooledConnection has already
* been requested.
*/
protected void assertInitializationAllowed()
throws IllegalStateException {
if (getConnectionCalled) {
throw new IllegalStateException(GET_CONNECTION_CALLED);
}
}
/**
* Close the connection pool being maintained by this datasource.
*/
public abstract void close() throws Exception;
protected abstract PooledConnectionManager getConnectionManager(UserPassKey upkey);
/* JDBC_4_ANT_KEY_BEGIN */
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
public <T> T unwrap(Class<T> iface) throws SQLException {
throw new SQLException("InstanceKeyDataSource is not a wrapper.");
}
/* JDBC_4_ANT_KEY_END */
// -------------------------------------------------------------------
// Properties
/**
* Get the value of connectionPoolDataSource. This method will return
* null, if the backing datasource is being accessed via jndi.
*
* @return value of connectionPoolDataSource.
*/
public ConnectionPoolDataSource getConnectionPoolDataSource() {
return dataSource;
}
/**
* Set the backend ConnectionPoolDataSource. This property should not be
* set if using jndi to access the datasource.
*
* @param v Value to assign to connectionPoolDataSource.
*/
public void setConnectionPoolDataSource(ConnectionPoolDataSource v) {
assertInitializationAllowed();
if (dataSourceName != null) {
throw new IllegalStateException(
"Cannot set the DataSource, if JNDI is used.");
}
if (dataSource != null)
{
throw new IllegalStateException(
"The CPDS has already been set. It cannot be altered.");
}
dataSource = v;
instanceKey = InstanceKeyObjectFactory.registerNewInstance(this);
}
/**
* Get the name of the ConnectionPoolDataSource which backs this pool.
* This name is used to look up the datasource from a jndi service
* provider.
*
* @return value of dataSourceName.
*/
public String getDataSourceName() {
return dataSourceName;
}
/**
* Set the name of the ConnectionPoolDataSource which backs this pool.
* This name is used to look up the datasource from a jndi service
* provider.
*
* @param v Value to assign to dataSourceName.
*/
public void setDataSourceName(String v) {
assertInitializationAllowed();
if (dataSource != null) {
throw new IllegalStateException(
"Cannot set the JNDI name for the DataSource, if already " +
"set using setConnectionPoolDataSource.");
}
if (dataSourceName != null)
{
throw new IllegalStateException(
"The DataSourceName has already been set. " +
"It cannot be altered.");
}
this.dataSourceName = v;
instanceKey = InstanceKeyObjectFactory.registerNewInstance(this);
}
/**
* Get the value of defaultAutoCommit, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setAutoCommit(boolean).
* The default is true.
*
* @return value of defaultAutoCommit.
*/
public boolean isDefaultAutoCommit() {
return defaultAutoCommit;
}
/**
* Set the value of defaultAutoCommit, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setAutoCommit(boolean).
* The default is true.
*
* @param v Value to assign to defaultAutoCommit.
*/
public void setDefaultAutoCommit(boolean v) {
assertInitializationAllowed();
this.defaultAutoCommit = v;
}
/**
* Get the value of defaultReadOnly, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setReadOnly(boolean).
* The default is false.
*
* @return value of defaultReadOnly.
*/
public boolean isDefaultReadOnly() {
return defaultReadOnly;
}
/**
* Set the value of defaultReadOnly, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setReadOnly(boolean).
* The default is false.
*
* @param v Value to assign to defaultReadOnly.
*/
public void setDefaultReadOnly(boolean v) {
assertInitializationAllowed();
this.defaultReadOnly = v;
}
/**
* Get the value of defaultTransactionIsolation, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setTransactionIsolation(int).
* If this method returns -1, the default is JDBC driver dependent.
*
* @return value of defaultTransactionIsolation.
*/
public int getDefaultTransactionIsolation() {
return defaultTransactionIsolation;
}
/**
* Set the value of defaultTransactionIsolation, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setTransactionIsolation(int).
* The default is JDBC driver dependent.
*
* @param v Value to assign to defaultTransactionIsolation
*/
public void setDefaultTransactionIsolation(int v) {
assertInitializationAllowed();
switch (v) {
case Connection.TRANSACTION_NONE:
case Connection.TRANSACTION_READ_COMMITTED:
case Connection.TRANSACTION_READ_UNCOMMITTED:
case Connection.TRANSACTION_REPEATABLE_READ:
case Connection.TRANSACTION_SERIALIZABLE:
break;
default:
throw new IllegalArgumentException(BAD_TRANSACTION_ISOLATION);
}
this.defaultTransactionIsolation = v;
}
/**
* Get the description. This property is defined by jdbc as for use with
* GUI (or other) tools that might deploy the datasource. It serves no
* internal purpose.
*
* @return value of description.
*/
public String getDescription() {
return description;
}
/**
* Set the description. This property is defined by jdbc as for use with
* GUI (or other) tools that might deploy the datasource. It serves no
* internal purpose.
*
* @param v Value to assign to description.
*/
public void setDescription(String v) {
this.description = v;
}
/**
* Get the value of jndiEnvironment which is used when instantiating
* a jndi InitialContext. This InitialContext is used to locate the
* backend ConnectionPoolDataSource.
*
* @return value of jndiEnvironment.
*/
public String getJndiEnvironment(String key) {
String value = null;
if (jndiEnvironment != null) {
value = jndiEnvironment.getProperty(key);
}
return value;
}
/**
* Sets the value of the given JNDI environment property to be used when
* instantiating a JNDI InitialContext. This InitialContext is used to
* locate the backend ConnectionPoolDataSource.
*
* @param key the JNDI environment property to set.
* @param value the value assigned to specified JNDI environment property.
*/
public void setJndiEnvironment(String key, String value) {
if (jndiEnvironment == null) {
jndiEnvironment = new Properties();
}
jndiEnvironment.setProperty(key, value);
}
/**
* Get the value of loginTimeout.
* @return value of loginTimeout.
*/
public int getLoginTimeout() {
return loginTimeout;
}
/**
* Set the value of loginTimeout.
* @param v Value to assign to loginTimeout.
*/
public void setLoginTimeout(int v) {
this.loginTimeout = v;
}
/**
* Get the value of logWriter.
* @return value of logWriter.
*/
public PrintWriter getLogWriter() {
if (logWriter == null) {
logWriter = new PrintWriter(System.out);
}
return logWriter;
}
/**
* Set the value of logWriter.
* @param v Value to assign to logWriter.
*/
public void setLogWriter(PrintWriter v) {
this.logWriter = v;
}
/**
* @see #getTestOnBorrow
*/
public final boolean isTestOnBorrow() {
return getTestOnBorrow();
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* before being returned by the {*link #borrowObject}
* method. If the object fails to validate,
* it will be dropped from the pool, and we will attempt
* to borrow another.
*
* @see #setTestOnBorrow
*/
public boolean getTestOnBorrow() {
return _testOnBorrow;
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* before being returned by the {*link #borrowObject}
* method. If the object fails to validate,
* it will be dropped from the pool, and we will attempt
* to borrow another. For a <code>true</code> value to have any effect,
* the <code>validationQuery</code> property must be set to a non-null
* string.
*
* @see #getTestOnBorrow
*/
public void setTestOnBorrow(boolean testOnBorrow) {
assertInitializationAllowed();
_testOnBorrow = testOnBorrow;
testPositionSet = true;
}
/**
* @see #getTestOnReturn
*/
public final boolean isTestOnReturn() {
return getTestOnReturn();
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* before being returned to the pool within the
* {*link #returnObject}.
*
* @see #setTestOnReturn
*/
public boolean getTestOnReturn() {
return _testOnReturn;
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* before being returned to the pool within the
* {*link #returnObject}. For a <code>true</code> value to have any effect,
* the <code>validationQuery</code> property must be set to a non-null
* string.
*
* @see #getTestOnReturn
*/
public void setTestOnReturn(boolean testOnReturn) {
assertInitializationAllowed();
_testOnReturn = testOnReturn;
testPositionSet = true;
}
/**
* Returns the number of milliseconds to sleep between runs of the
* idle object evictor thread.
* When non-positive, no idle object evictor thread will be
* run.
*
* @see #setTimeBetweenEvictionRunsMillis
*/
public int getTimeBetweenEvictionRunsMillis() {
return _timeBetweenEvictionRunsMillis;
}
/**
* Sets the number of milliseconds to sleep between runs of the
* idle object evictor thread.
* When non-positive, no idle object evictor thread will be
* run.
*
* @see #getTimeBetweenEvictionRunsMillis
*/
public void
setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) {
assertInitializationAllowed();
_timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
/**
* Returns the number of objects to examine during each run of the
* idle object evictor thread (if any).
*
* @see #setNumTestsPerEvictionRun
* @see #setTimeBetweenEvictionRunsMillis
*/
public int getNumTestsPerEvictionRun() {
return _numTestsPerEvictionRun;
}
/**
* Sets the number of objects to examine during each run of the
* idle object evictor thread (if any).
* <p>
* When a negative value is supplied, <tt>ceil({*link #numIdle})/abs({*link #getNumTestsPerEvictionRun})</tt>
* tests will be run. I.e., when the value is <i>-n</i>, roughly one <i>n</i>th of the
* idle objects will be tested per run.
*
* @see #getNumTestsPerEvictionRun
* @see #setTimeBetweenEvictionRunsMillis
*/
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
assertInitializationAllowed();
_numTestsPerEvictionRun = numTestsPerEvictionRun;
}
/**
* Returns the minimum amount of time an object may sit idle in the pool
* before it is eligable for eviction by the idle object evictor
* (if any).
*
* @see #setMinEvictableIdleTimeMillis
* @see #setTimeBetweenEvictionRunsMillis
*/
public int getMinEvictableIdleTimeMillis() {
return _minEvictableIdleTimeMillis;
}
/**
* Sets the minimum amount of time an object may sit idle in the pool
* before it is eligable for eviction by the idle object evictor
* (if any).
* When non-positive, no objects will be evicted from the pool
* due to idle time alone.
*
* @see #getMinEvictableIdleTimeMillis
* @see #setTimeBetweenEvictionRunsMillis
*/
public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) {
assertInitializationAllowed();
_minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
/**
* @see #getTestWhileIdle
*/
public final boolean isTestWhileIdle() {
return getTestWhileIdle();
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* by the idle object evictor (if any). If an object
* fails to validate, it will be dropped from the pool.
*
* @see #setTestWhileIdle
* @see #setTimeBetweenEvictionRunsMillis
*/
public boolean getTestWhileIdle() {
return _testWhileIdle;
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* by the idle object evictor (if any). If an object
* fails to validate, it will be dropped from the pool. For a
* <code>true</code> value to have any effect,
* the <code>validationQuery</code> property must be set to a non-null
* string.
*
* @see #getTestWhileIdle
* @see #setTimeBetweenEvictionRunsMillis
*/
public void setTestWhileIdle(boolean testWhileIdle) {
assertInitializationAllowed();
_testWhileIdle = testWhileIdle;
testPositionSet = true;
}
/**
* The SQL query that will be used to validate connections from this pool
* before returning them to the caller. If specified, this query
* <strong>MUST</strong> be an SQL SELECT statement that returns at least
* one row.
*/
public String getValidationQuery() {
return (this.validationQuery);
}
/**
* The SQL query that will be used to validate connections from this pool
* before returning them to the caller. If specified, this query
* <strong>MUST</strong> be an SQL SELECT statement that returns at least
* one row. Default behavior is to test the connection when it is
* borrowed.
*/
public void setValidationQuery(String validationQuery) {
assertInitializationAllowed();
this.validationQuery = validationQuery;
if (!testPositionSet) {
setTestOnBorrow(true);
}
}
/**
* Whether a rollback will be issued after executing the SQL query
* that will be used to validate connections from this pool
* before returning them to the caller.
*
* @return true if a rollback will be issued after executing the
* validation query
* @since 1.2.2
*/
public boolean isRollbackAfterValidation() {
return (this.rollbackAfterValidation);
}
/**
* Whether a rollback will be issued after executing the SQL query
* that will be used to validate connections from this pool
* before returning them to the caller. Default behavior is NOT
* to issue a rollback. The setting will only have an effect
* if a validation query is set
*
* @param rollbackAfterValidation new property value
* @since 1.2.2
*/
public void setRollbackAfterValidation(boolean rollbackAfterValidation) {
assertInitializationAllowed();
this.rollbackAfterValidation = rollbackAfterValidation;
}
// ----------------------------------------------------------------------
// Instrumentation Methods
// ----------------------------------------------------------------------
// DataSource implementation
/**
* Attempt to establish a database connection.
*/
public Connection getConnection() throws SQLException {
return getConnection(null, null);
}
/**
* Attempt to retrieve a database connection using {@link #getPooledConnectionAndInfo(String, String)}
* with the provided username and password. The password on the {@link PooledConnectionAndInfo}
* instance returned by <code>getPooledConnectionAndInfo</code> is compared to the <code>password</code>
* parameter. If the comparison fails, a database connection using the supplied username and password
* is attempted. If the connection attempt fails, an SQLException is thrown, indicating that the given password
* did not match the password used to create the pooled connection. If the connection attempt succeeds, this
* means that the database password has been changed. In this case, the <code>PooledConnectionAndInfo</code>
* instance retrieved with the old password is destroyed and the <code>getPooledConnectionAndInfo</code> is
* repeatedly invoked until a <code>PooledConnectionAndInfo</code> instance with the new password is returned.
*
*/
public Connection getConnection(String username, String password)
throws SQLException {
if (instanceKey == null) {
throw new SQLException("Must set the ConnectionPoolDataSource "
+ "through setDataSourceName or setConnectionPoolDataSource"
+ " before calling getConnection.");
}
getConnectionCalled = true;
PooledConnectionAndInfo info = null;
try {
info = getPooledConnectionAndInfo(username, password);
} catch (NoSuchElementException e) {
closeDueToException(info);
throw new SQLNestedException("Cannot borrow connection from pool", e);
} catch (RuntimeException e) {
closeDueToException(info);
throw e;
} catch (SQLException e) {
closeDueToException(info);
throw e;
} catch (Exception e) {
closeDueToException(info);
throw new SQLNestedException("Cannot borrow connection from pool", e);
}
if (!(null == password ? null == info.getPassword()
: password.equals(info.getPassword()))) { // Password on PooledConnectionAndInfo does not match
try { // See if password has changed by attempting connection
testCPDS(username, password);
} catch (SQLException ex) {
// Password has not changed, so refuse client, but return connection to the pool
closeDueToException(info);
throw new SQLException("Given password did not match password used"
+ " to create the PooledConnection.");
} catch (javax.naming.NamingException ne) {
throw (SQLException) new SQLException(
"NamingException encountered connecting to database").initCause(ne);
}
/*
* Password must have changed -> destroy connection and keep retrying until we get a new, good one,
* destroying any idle connections with the old passowrd as we pull them from the pool.
*/
final UserPassKey upkey = info.getUserPassKey();
final PooledConnectionManager manager = getConnectionManager(upkey);
manager.invalidate(info.getPooledConnection()); // Destroy and remove from pool
manager.setPassword(upkey.getPassword()); // Reset the password on the factory if using CPDSConnectionFactory
info = null;
for (int i = 0; i < 10; i++) { // Bound the number of retries - only needed if bad instances return
try {
info = getPooledConnectionAndInfo(username, password);
} catch (NoSuchElementException e) {
closeDueToException(info);
throw new SQLNestedException("Cannot borrow connection from pool", e);
} catch (RuntimeException e) {
closeDueToException(info);
throw e;
} catch (SQLException e) {
closeDueToException(info);
throw e;
} catch (Exception e) {
closeDueToException(info);
throw new SQLNestedException("Cannot borrow connection from pool", e);
}
if (info != null && password.equals(info.getPassword())) {
break;
} else {
if (info != null) {
manager.invalidate(info.getPooledConnection());
}
info = null;
}
}
if (info == null) {
throw new SQLException("Cannot borrow connection from pool - password change failure.");
}
}
Connection con = info.getPooledConnection().getConnection();
try {
setupDefaults(con, username);
con.clearWarnings();
return con;
} catch (SQLException ex) {
try {
con.close();
} catch (Exception exc) {
getLogWriter().println(
"ignoring exception during close: " + exc);
}
throw ex;
}
}
protected abstract PooledConnectionAndInfo
getPooledConnectionAndInfo(String username, String password)
throws SQLException;
protected abstract void setupDefaults(Connection con, String username)
throws SQLException;
private void closeDueToException(PooledConnectionAndInfo info) {
if (info != null) {
try {
info.getPooledConnection().getConnection().close();
} catch (Exception e) {
// do not throw this exception because we are in the middle
// of handling another exception. But record it because
// it potentially leaks connections from the pool.
getLogWriter().println("[ERROR] Could not return connection to "
+ "pool during exception handling. " + e.getMessage());
}
}
}
protected ConnectionPoolDataSource
testCPDS(String username, String password)
throws javax.naming.NamingException, SQLException {
// The source of physical db connections
ConnectionPoolDataSource cpds = this.dataSource;
if (cpds == null) {
Context ctx = null;
if (jndiEnvironment == null) {
ctx = new InitialContext();
} else {
ctx = new InitialContext(jndiEnvironment);
}
Object ds = ctx.lookup(dataSourceName);
if (ds instanceof ConnectionPoolDataSource) {
cpds = (ConnectionPoolDataSource) ds;
} else {
throw new SQLException("Illegal configuration: "
+ "DataSource " + dataSourceName
+ " (" + ds.getClass().getName() + ")"
+ " doesn't implement javax.sql.ConnectionPoolDataSource");
}
}
// try to get a connection with the supplied username/password
PooledConnection conn = null;
try {
if (username != null) {
conn = cpds.getPooledConnection(username, password);
}
else {
conn = cpds.getPooledConnection();
}
if (conn == null) {
throw new SQLException(
"Cannot connect using the supplied username/password");
}
}
finally {
if (conn != null) {
try {
conn.close();
}
catch (SQLException e) {
// at least we could connect
}
}
}
return cpds;
}
protected byte whenExhaustedAction(int maxActive, int maxWait) {
byte whenExhausted = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
if (maxActive <= 0) {
whenExhausted = GenericObjectPool.WHEN_EXHAUSTED_GROW;
} else if (maxWait == 0) {
whenExhausted = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
}
return whenExhausted;
}
// ----------------------------------------------------------------------
// Referenceable implementation
/**
* Retrieves the Reference of this object.
* <strong>Note:</strong> <code>InstanceKeyDataSource</code> subclasses
* should override this method. The implementaion included below
* is not robust and will be removed at the next major version DBCP
* release.
*
* @return The non-null Reference of this object.
* @exception NamingException If a naming exception was encountered
* while retrieving the reference.
*/
// TODO: Remove the implementation of this method at next major
// version release.
public Reference getReference() throws NamingException {
final String className = getClass().getName();
final String factoryName = className + "Factory"; // XXX: not robust
Reference ref = new Reference(className, factoryName, null);
ref.add(new StringRefAddr("instanceKey", instanceKey));
return ref;
}
}
| Javadoc fixes.
git-svn-id: ad951d5a084f562764370c7a59da74380db26404@907428 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/commons/dbcp/datasources/InstanceKeyDataSource.java | Javadoc fixes. | <ide><path>rc/java/org/apache/commons/dbcp/datasources/InstanceKeyDataSource.java
<ide> * Internal constant to indicate the level is not set.
<ide> */
<ide> protected static final int UNKNOWN_TRANSACTIONISOLATION = -1;
<del>
<add>
<ide> /** Guards property setters - once true, setters throw IllegalStateException */
<ide> private volatile boolean getConnectionCalled = false;
<ide>
<add> /** Underlying source of PooledConnections */
<ide> private ConnectionPoolDataSource dataSource = null;
<add>
<ide> /** DataSource Name used to find the ConnectionPoolDataSource */
<ide> private String dataSourceName = null;
<add>
<add> // Default connection properties
<ide> private boolean defaultAutoCommit = false;
<ide> private int defaultTransactionIsolation = UNKNOWN_TRANSACTIONISOLATION;
<del>// private int maxActive = GenericObjectPool.DEFAULT_MAX_ACTIVE;
<del>// private int maxIdle = GenericObjectPool.DEFAULT_MAX_IDLE;
<del>// private int maxWait = (int)Math.min(Integer.MAX_VALUE,
<del>// GenericObjectPool.DEFAULT_MAX_WAIT);
<ide> private boolean defaultReadOnly = false;
<add>
<ide> /** Description */
<ide> private String description = null;
<add>
<ide> /** Environment that may be used to set up a jndi initial context. */
<ide> Properties jndiEnvironment = null;
<add>
<ide> /** Login TimeOut in seconds */
<ide> private int loginTimeout = 0;
<add>
<ide> /** Log stream */
<ide> private PrintWriter logWriter = null;
<add>
<add> // Pool properties
<ide> private boolean _testOnBorrow = GenericObjectPool.DEFAULT_TEST_ON_BORROW;
<ide> private boolean _testOnReturn = GenericObjectPool.DEFAULT_TEST_ON_RETURN;
<ide> private int _timeBetweenEvictionRunsMillis = (int)
<ide> private boolean _testWhileIdle = GenericObjectPool.DEFAULT_TEST_WHILE_IDLE;
<ide> private String validationQuery = null;
<ide> private boolean rollbackAfterValidation = false;
<add>
<add> /** true iff one of the setters for testOnBorrow, testOnReturn, testWhileIdle has been called. */
<ide> private boolean testPositionSet = false;
<ide>
<add> /** Instance key */
<ide> protected String instanceKey = null;
<ide>
<ide> /**
<ide> * The SQL query that will be used to validate connections from this pool
<ide> * before returning them to the caller. If specified, this query
<ide> * <strong>MUST</strong> be an SQL SELECT statement that returns at least
<del> * one row. Default behavior is to test the connection when it is
<del> * borrowed.
<add> * one row. If none of the properties, testOnBorow, testOnReturn, testWhileIdle
<add> * have been previously set, calling this method sets testOnBorrow to true.
<ide> */
<ide> public void setValidationQuery(String validationQuery) {
<ide> assertInitializationAllowed(); |
|
Java | mit | 5f535b78bb05bedb87ac862f31a93e58d6bdb081 | 0 | Um-Mitternacht/Witchworks,backuporg/Witchworks,Um-Mitternacht/Wiccan_Arts | package com.wiccanarts.client.core;
import com.wiccanarts.client.handler.ModelHandler;
import com.wiccanarts.common.block.ModBlocks;
import com.wiccanarts.common.core.proxy.ISidedProxy;
import com.wiccanarts.common.item.ModItems;
import net.minecraft.client.Minecraft;
import net.minecraft.util.text.ITextComponent;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* This class was created by <Arekkuusu> on 26/02/2017.
* It's distributed as part of Wiccan Arts under
* the MIT license.
*/
@Mod.EventBusSubscriber(Side.CLIENT)
public class ClientProxy implements ISidedProxy {
/**
* Here you can register your Item models that do not have a class.
* <p>
* According to the registry name of the item, the model loader will look
* into the models file and bind the item to its corresponding model.
* </p>
*/
@SideOnly(Side.CLIENT)
@SubscribeEvent
public static void registerItemModels(ModelRegistryEvent event) {
ModelHandler.registerModels(); //These do have a class, but need to be registered in the event
ModelHandler.registerItem(ModItems.GARNET);
ModelHandler.registerItem(ModItems.MOLDAVITE);
ModelHandler.registerItem(ModItems.NUUMMITE);
ModelHandler.registerItem(ModItems.PETOSKEY_STONE);
ModelHandler.registerItem(ModItems.SERPENTINE);
ModelHandler.registerItem(ModItems.TIGERS_EYE);
ModelHandler.registerItem(ModItems.TOURMALINE);
ModelHandler.registerItem(ModItems.BLOODSTONE);
ModelHandler.registerItem(ModItems.JASPER);
ModelHandler.registerItem(ModItems.MALACHITE);
ModelHandler.registerItem(ModItems.AMETHYST);
ModelHandler.registerItem(ModItems.ALEXANDRITE);
ModelHandler.registerItem(ModItems.QUARTZ);
ModelHandler.registerItem(ModItems.SILVER_POWDER);
ModelHandler.registerItem(ModItems.SILVER_NUGGET);
ModelHandler.registerItem(ModItems.SILVER_INGOT);
ModelHandler.registerBlock(ModBlocks.SILVER_BLOCK);
ModelHandler.registerBlock(ModBlocks.COQUINA);
ModelHandler.registerBlock(ModBlocks.MOLDAVITE_BLOCK);
ModelHandler.registerBlock(ModBlocks.BLOODSTONE_BLOCK);
ModelHandler.registerBlock(ModBlocks.SILVER_ORE);
}
@SideOnly(Side.CLIENT)
@Override
public void preInit(FMLPreInitializationEvent event) {
registerRenders();
}
@SideOnly(Side.CLIENT)
@Override
public void init(FMLInitializationEvent event) {
}
@SideOnly(Side.CLIENT)
@Override
public void postInit(FMLPostInitializationEvent event) {
}
/**
* Register here all Renders. For example:
* {@code RenderingRegistry.registerEntityRenderingHandler(Entity.class, RenderEntity::new);}
* or
* {@code ClientRegistry.bindTileEntitySpecialRenderer(Tile.class, new RenderTile());}
*
* @see RenderingRegistry
*/
@SideOnly(Side.CLIENT)
private void registerRenders() {
}
/**
* Display a Record text with a format and localization.
*
* @param text An {@link ITextComponent}
*/
@SideOnly(Side.CLIENT)
@Override
public void displayRecordText(ITextComponent text) {
Minecraft.getMinecraft().ingameGUI.setRecordPlayingMessage(text.getFormattedText());
}
@SideOnly(Side.CLIENT)
private boolean doParticle() {
if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER)
return false;
float chance = 1F;
if (Minecraft.getMinecraft().gameSettings.particleSetting == 1)
chance = 0.6F;
else if (Minecraft.getMinecraft().gameSettings.particleSetting == 2)
chance = 0.2F;
return chance == 1F || Math.random() < chance;
}
}
| src/main/java/com/wiccanarts/client/core/ClientProxy.java | package com.wiccanarts.client.core;
import com.wiccanarts.client.handler.ModelHandler;
import com.wiccanarts.common.block.ModBlocks;
import com.wiccanarts.common.core.proxy.ISidedProxy;
import com.wiccanarts.common.item.ModItems;
import net.minecraft.client.Minecraft;
import net.minecraft.util.text.ITextComponent;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* This class was created by <Arekkuusu> on 26/02/2017.
* It's distributed as part of Wiccan Arts under
* the MIT license.
*/
@Mod.EventBusSubscriber(Side.CLIENT)
public class ClientProxy implements ISidedProxy {
/**
* Here you can register your Item models that do not have a class.
* <p>
* According to the registry name of the item, the model loader will look
* into the models file and bind the item to its corresponding model.
* </p>
*/
@SideOnly(Side.CLIENT)
@SubscribeEvent
public static void registerItemModels(ModelRegistryEvent event) {
ModelHandler.registerModels(); //These do have a class, but need to be registered in the event
ModelHandler.registerItem(ModItems.GARNET);
ModelHandler.registerItem(ModItems.MOLDAVITE);
ModelHandler.registerItem(ModItems.NUUMMITE);
ModelHandler.registerItem(ModItems.PETOSKEY_STONE);
ModelHandler.registerItem(ModItems.SERPENTINE);
ModelHandler.registerItem(ModItems.TIGERS_EYE);
ModelHandler.registerItem(ModItems.TOURMALINE);
ModelHandler.registerItem(ModItems.BLOODSTONE);
ModelHandler.registerItem(ModItems.JASPER);
ModelHandler.registerItem(ModItems.MALACHITE);
ModelHandler.registerItem(ModItems.AMETHYST);
ModelHandler.registerItem(ModItems.ALEXANDRITE);
ModelHandler.registerItem(ModItems.QUARTZ);
ModelHandler.registerItem(ModItems.SILVER_POWDER);
ModelHandler.registerItem(ModItems.SILVER_NUGGET);
ModelHandler.registerItem(ModItems.SILVER_INGOT);
ModelHandler.registerBlock(ModBlocks.SILVER_BLOCK);
ModelHandler.registerBlock(ModBlocks.COQUINA);
//ModelHandler.registerBlock(ModBlocks.MOLDAVITE_BLOCK);
//ModelHandler.registerBlock(ModBlocks.BLOODSTONE_BLOCK);
ModelHandler.registerBlock(ModBlocks.SILVER_ORE);
}
@SideOnly(Side.CLIENT)
@Override
public void preInit(FMLPreInitializationEvent event) {
registerRenders();
}
@SideOnly(Side.CLIENT)
@Override
public void init(FMLInitializationEvent event) {
}
@SideOnly(Side.CLIENT)
@Override
public void postInit(FMLPostInitializationEvent event) {
}
/**
* Register here all Renders. For example:
* {@code RenderingRegistry.registerEntityRenderingHandler(Entity.class, RenderEntity::new);}
* or
* {@code ClientRegistry.bindTileEntitySpecialRenderer(Tile.class, new RenderTile());}
*
* @see RenderingRegistry
*/
@SideOnly(Side.CLIENT)
private void registerRenders() {
}
/**
* Display a Record text with a format and localization.
*
* @param text An {@link ITextComponent}
*/
@SideOnly(Side.CLIENT)
@Override
public void displayRecordText(ITextComponent text) {
Minecraft.getMinecraft().ingameGUI.setRecordPlayingMessage(text.getFormattedText());
}
@SideOnly(Side.CLIENT)
private boolean doParticle() {
if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER)
return false;
float chance = 1F;
if (Minecraft.getMinecraft().gameSettings.particleSetting == 1)
chance = 0.6F;
else if (Minecraft.getMinecraft().gameSettings.particleSetting == 2)
chance = 0.2F;
return chance == 1F || Math.random() < chance;
}
}
| Changed back comments
Commented them because game wouldn't start with them
| src/main/java/com/wiccanarts/client/core/ClientProxy.java | Changed back comments | <ide><path>rc/main/java/com/wiccanarts/client/core/ClientProxy.java
<ide>
<ide> ModelHandler.registerBlock(ModBlocks.SILVER_BLOCK);
<ide> ModelHandler.registerBlock(ModBlocks.COQUINA);
<del> //ModelHandler.registerBlock(ModBlocks.MOLDAVITE_BLOCK);
<del> //ModelHandler.registerBlock(ModBlocks.BLOODSTONE_BLOCK);
<add> ModelHandler.registerBlock(ModBlocks.MOLDAVITE_BLOCK);
<add> ModelHandler.registerBlock(ModBlocks.BLOODSTONE_BLOCK);
<ide> ModelHandler.registerBlock(ModBlocks.SILVER_ORE);
<ide> }
<ide> |
|
Java | apache-2.0 | fed6c6996cfe7290d38674e5d0ed1b61b52b7874 | 0 | blindpirate/gradle,robinverduijn/gradle,gstevey/gradle,blindpirate/gradle,blindpirate/gradle,lsmaira/gradle,robinverduijn/gradle,gstevey/gradle,blindpirate/gradle,blindpirate/gradle,robinverduijn/gradle,robinverduijn/gradle,gstevey/gradle,blindpirate/gradle,gradle/gradle,robinverduijn/gradle,gradle/gradle,gradle/gradle,robinverduijn/gradle,robinverduijn/gradle,gstevey/gradle,lsmaira/gradle,gradle/gradle,gradle/gradle,gradle/gradle,lsmaira/gradle,blindpirate/gradle,gradle/gradle,gstevey/gradle,lsmaira/gradle,gstevey/gradle,gradle/gradle,lsmaira/gradle,gstevey/gradle,lsmaira/gradle,gstevey/gradle,gstevey/gradle,robinverduijn/gradle,lsmaira/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,lsmaira/gradle,blindpirate/gradle,blindpirate/gradle,lsmaira/gradle,gradle/gradle,robinverduijn/gradle,lsmaira/gradle,robinverduijn/gradle | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.artifacts.ivyservice.resolutionstrategy;
import com.google.common.collect.Lists;
import groovy.lang.Closure;
import org.gradle.api.Action;
import org.gradle.api.InvalidActionClosureException;
import org.gradle.api.InvalidUserCodeException;
import org.gradle.api.RuleAction;
import org.gradle.api.artifacts.ComponentMetadata;
import org.gradle.api.artifacts.VersionSelection;
import org.gradle.api.artifacts.VersionSelectionRules;
import org.gradle.api.artifacts.ivy.IvyModuleDescriptor;
import org.gradle.api.internal.ClosureBackedRuleAction;
import org.gradle.api.internal.NoInputsRuleAction;
import org.gradle.api.internal.artifacts.VersionSelectionInternal;
import org.gradle.api.internal.artifacts.VersionSelectionRulesInternal;
import org.gradle.api.internal.artifacts.ivyservice.DefaultIvyModuleDescriptor;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.BuildableModuleVersionMetaDataResolveResult;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.DefaultBuildableModuleVersionMetaDataResolveResult;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ModuleComponentRepositoryAccess;
import org.gradle.api.internal.artifacts.metadata.IvyModuleVersionMetaData;
import org.gradle.api.internal.artifacts.metadata.ModuleVersionMetaData;
import org.gradle.api.internal.artifacts.metadata.MutableModuleVersionMetaData;
import org.gradle.api.internal.artifacts.repositories.resolver.ComponentMetadataDetailsAdapter;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class DefaultVersionSelectionRules implements VersionSelectionRulesInternal {
final Set<RuleAction<? super VersionSelection>> versionSelectionRules = new LinkedHashSet<RuleAction<? super VersionSelection>>();
private final static List<Class<?>> VALID_INPUT_TYPES = Lists.newArrayList(ComponentMetadata.class, IvyModuleDescriptor.class);
private final static String USER_CODE_ERROR = "Could not apply version selection rule with all().";
private static final String UNSUPPORTED_PARAMETER_TYPE_ERROR = "Unsupported parameter type for version selection rule: %s";
public void apply(VersionSelection selection, ModuleComponentRepositoryAccess moduleAccess) {
MetadataProvider metadataProvider = new MetadataProvider(selection, moduleAccess);
for (RuleAction<? super VersionSelection> rule : versionSelectionRules) {
List<Object> inputs = Lists.newArrayList();
for (Class<?> inputType : rule.getInputTypes()) {
if (inputType == ComponentMetadata.class) {
inputs.add(metadataProvider.getComponentMetadata());
continue;
}
if (inputType == IvyModuleDescriptor.class) {
IvyModuleDescriptor ivyModuleDescriptor = metadataProvider.getIvyModuleDescriptor();
if (ivyModuleDescriptor != null) {
inputs.add(ivyModuleDescriptor);
continue;
} else {
// Don't process rule for non-ivy modules
return;
}
}
// We've already validated the inputs: should never get here.
throw new IllegalStateException();
}
try {
rule.execute(selection, inputs);
} catch (Exception e) {
throw new InvalidUserCodeException(USER_CODE_ERROR, e);
}
}
}
public boolean hasRules() {
return versionSelectionRules.size() > 0;
}
public VersionSelectionRules all(Action<? super VersionSelection> selectionAction) {
versionSelectionRules.add(new NoInputsRuleAction<VersionSelection>(selectionAction));
return this;
}
public VersionSelectionRules all(RuleAction<? super VersionSelection> ruleAction) {
versionSelectionRules.add(validateInputTypes(ruleAction));
return this;
}
public VersionSelectionRules all(Closure<?> closure) {
versionSelectionRules.add(createRuleActionFromClosure(closure));
return this;
}
private RuleAction<? super VersionSelection> createRuleActionFromClosure(Closure<?> closure) {
try {
return validateInputTypes(new ClosureBackedRuleAction<VersionSelection>(VersionSelection.class, closure));
} catch (RuntimeException e) {
throw new InvalidActionClosureException(String.format("The closure provided is not valid as a rule action for '%s'.", VersionSelectionRules.class.getSimpleName()), closure, e);
}
}
private RuleAction<? super VersionSelection> validateInputTypes(RuleAction<? super VersionSelection> ruleAction) {
for (Class<?> inputType : ruleAction.getInputTypes()) {
if (!VALID_INPUT_TYPES.contains(inputType)) {
throw new InvalidUserCodeException(String.format(UNSUPPORTED_PARAMETER_TYPE_ERROR, inputType.getName()));
}
}
return ruleAction;
}
private static class MetadataProvider {
private final VersionSelection versionSelection;
private final ModuleComponentRepositoryAccess moduleAccess;
private MutableModuleVersionMetaData cachedMetaData;
private MetadataProvider(VersionSelection versionSelection, ModuleComponentRepositoryAccess moduleAccess) {
this.versionSelection = versionSelection;
this.moduleAccess = moduleAccess;
}
public ComponentMetadata getComponentMetadata() {
return new ComponentMetadataDetailsAdapter(getMetaData());
}
public IvyModuleDescriptor getIvyModuleDescriptor() {
ModuleVersionMetaData metaData = getMetaData();
if (metaData instanceof IvyModuleVersionMetaData) {
IvyModuleVersionMetaData ivyMetadata = (IvyModuleVersionMetaData) metaData;
return new DefaultIvyModuleDescriptor(ivyMetadata.getExtraInfo(), ivyMetadata.getBranch(), ivyMetadata.getStatus());
}
return null;
}
private MutableModuleVersionMetaData getMetaData() {
if (cachedMetaData == null) {
cachedMetaData = initMetaData(versionSelection, moduleAccess);
}
return cachedMetaData;
}
private MutableModuleVersionMetaData initMetaData(VersionSelection selection, ModuleComponentRepositoryAccess moduleAccess) {
BuildableModuleVersionMetaDataResolveResult descriptorResult = new DefaultBuildableModuleVersionMetaDataResolveResult();
moduleAccess.resolveComponentMetaData(((VersionSelectionInternal) selection).getDependencyMetaData(), selection.getCandidate(), descriptorResult);
return descriptorResult.getMetaData();
}
}
}
| subprojects/core-impl/src/main/groovy/org/gradle/api/internal/artifacts/ivyservice/resolutionstrategy/DefaultVersionSelectionRules.java | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.artifacts.ivyservice.resolutionstrategy;
import com.google.common.collect.Lists;
import groovy.lang.Closure;
import org.gradle.api.Action;
import org.gradle.api.InvalidActionClosureException;
import org.gradle.api.InvalidUserCodeException;
import org.gradle.api.RuleAction;
import org.gradle.api.artifacts.ComponentMetadata;
import org.gradle.api.artifacts.ComponentMetadataDetails;
import org.gradle.api.artifacts.VersionSelection;
import org.gradle.api.artifacts.VersionSelectionRules;
import org.gradle.api.artifacts.ivy.IvyModuleDescriptor;
import org.gradle.api.internal.NoInputsRuleAction;
import org.gradle.api.internal.ClosureBackedRuleAction;
import org.gradle.api.internal.artifacts.VersionSelectionInternal;
import org.gradle.api.internal.artifacts.VersionSelectionRulesInternal;
import org.gradle.api.internal.artifacts.ivyservice.DefaultIvyModuleDescriptor;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.BuildableModuleVersionMetaDataResolveResult;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.DefaultBuildableModuleVersionMetaDataResolveResult;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ModuleComponentRepositoryAccess;
import org.gradle.api.internal.artifacts.metadata.IvyModuleVersionMetaData;
import org.gradle.api.internal.artifacts.metadata.MutableModuleVersionMetaData;
import org.gradle.api.internal.artifacts.repositories.resolver.ComponentMetadataDetailsAdapter;
import java.util.*;
public class DefaultVersionSelectionRules implements VersionSelectionRulesInternal {
final Set<RuleAction<? super VersionSelection>> versionSelectionRules = new LinkedHashSet<RuleAction<? super VersionSelection>>();
private final static List<Class<?>> VALID_INPUT_TYPES = Lists.newArrayList(ComponentMetadata.class, IvyModuleDescriptor.class);
private final static String USER_CODE_ERROR = "Could not apply version selection rule with all().";
private static final String UNSUPPORTED_PARAMETER_TYPE_ERROR = "Unsupported parameter type for version selection rule: %s";
public void apply(VersionSelection selection, ModuleComponentRepositoryAccess moduleAccess) {
for (RuleAction<? super VersionSelection> rule : versionSelectionRules) {
List<Object> inputs = Lists.newArrayList();
for (Class<?> inputType : rule.getInputTypes()) {
if (inputType == ComponentMetadata.class) {
MutableModuleVersionMetaData metaData = getMetaData(selection, moduleAccess);
ComponentMetadataDetails componentMetadata = new ComponentMetadataDetailsAdapter(metaData);
inputs.add(componentMetadata);
continue;
}
if (inputType == IvyModuleDescriptor.class) {
MutableModuleVersionMetaData metaData = getMetaData(selection, moduleAccess);
if (metaData instanceof IvyModuleVersionMetaData) {
IvyModuleVersionMetaData ivyMetadata = (IvyModuleVersionMetaData) metaData;
inputs.add(new DefaultIvyModuleDescriptor(ivyMetadata.getExtraInfo(), ivyMetadata.getBranch(), ivyMetadata.getStatus()));
continue;
} else {
return;
}
}
throw new InvalidUserCodeException(String.format(UNSUPPORTED_PARAMETER_TYPE_ERROR, inputType.getName()));
}
try {
rule.execute(selection, inputs);
} catch (Exception e) {
throw new InvalidUserCodeException(USER_CODE_ERROR, e);
}
}
}
private MutableModuleVersionMetaData getMetaData(VersionSelection selection, ModuleComponentRepositoryAccess moduleAccess) {
BuildableModuleVersionMetaDataResolveResult descriptorResult = new DefaultBuildableModuleVersionMetaDataResolveResult();
moduleAccess.resolveComponentMetaData(((VersionSelectionInternal) selection).getDependencyMetaData(), selection.getCandidate(), descriptorResult);
return descriptorResult.getMetaData();
}
public boolean hasRules() {
return versionSelectionRules.size() > 0;
}
public VersionSelectionRules all(Action<? super VersionSelection> selectionAction) {
versionSelectionRules.add(new NoInputsRuleAction<VersionSelection>(selectionAction));
return this;
}
public VersionSelectionRules all(RuleAction<? super VersionSelection> ruleAction) {
versionSelectionRules.add(validateInputTypes(ruleAction));
return this;
}
public VersionSelectionRules all(Closure<?> closure) {
versionSelectionRules.add(createRuleActionFromClosure(closure));
return this;
}
private RuleAction<? super VersionSelection> createRuleActionFromClosure(Closure<?> closure) {
try {
return validateInputTypes(new ClosureBackedRuleAction<VersionSelection>(VersionSelection.class, closure));
} catch (RuntimeException e) {
throw new InvalidActionClosureException(String.format("The closure provided is not valid as a rule action for '%s'.", VersionSelectionRules.class.getSimpleName()), closure, e);
}
}
private RuleAction<? super VersionSelection> validateInputTypes(RuleAction<? super VersionSelection> ruleAction) {
for (Class<?> inputType : ruleAction.getInputTypes()) {
if (!VALID_INPUT_TYPES.contains(inputType)) {
throw new InvalidUserCodeException(String.format(UNSUPPORTED_PARAMETER_TYPE_ERROR, inputType.getName()));
}
}
return ruleAction;
}
}
| Cache the metadata directly when executing version selection rules
+review REVIEW-5137
| subprojects/core-impl/src/main/groovy/org/gradle/api/internal/artifacts/ivyservice/resolutionstrategy/DefaultVersionSelectionRules.java | Cache the metadata directly when executing version selection rules | <ide><path>ubprojects/core-impl/src/main/groovy/org/gradle/api/internal/artifacts/ivyservice/resolutionstrategy/DefaultVersionSelectionRules.java
<ide> import org.gradle.api.InvalidUserCodeException;
<ide> import org.gradle.api.RuleAction;
<ide> import org.gradle.api.artifacts.ComponentMetadata;
<del>import org.gradle.api.artifacts.ComponentMetadataDetails;
<ide> import org.gradle.api.artifacts.VersionSelection;
<ide> import org.gradle.api.artifacts.VersionSelectionRules;
<ide> import org.gradle.api.artifacts.ivy.IvyModuleDescriptor;
<add>import org.gradle.api.internal.ClosureBackedRuleAction;
<ide> import org.gradle.api.internal.NoInputsRuleAction;
<del>import org.gradle.api.internal.ClosureBackedRuleAction;
<ide> import org.gradle.api.internal.artifacts.VersionSelectionInternal;
<ide> import org.gradle.api.internal.artifacts.VersionSelectionRulesInternal;
<ide> import org.gradle.api.internal.artifacts.ivyservice.DefaultIvyModuleDescriptor;
<ide> import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.DefaultBuildableModuleVersionMetaDataResolveResult;
<ide> import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ModuleComponentRepositoryAccess;
<ide> import org.gradle.api.internal.artifacts.metadata.IvyModuleVersionMetaData;
<add>import org.gradle.api.internal.artifacts.metadata.ModuleVersionMetaData;
<ide> import org.gradle.api.internal.artifacts.metadata.MutableModuleVersionMetaData;
<ide> import org.gradle.api.internal.artifacts.repositories.resolver.ComponentMetadataDetailsAdapter;
<ide>
<del>import java.util.*;
<add>import java.util.LinkedHashSet;
<add>import java.util.List;
<add>import java.util.Set;
<ide>
<ide> public class DefaultVersionSelectionRules implements VersionSelectionRulesInternal {
<ide> final Set<RuleAction<? super VersionSelection>> versionSelectionRules = new LinkedHashSet<RuleAction<? super VersionSelection>>();
<ide> private static final String UNSUPPORTED_PARAMETER_TYPE_ERROR = "Unsupported parameter type for version selection rule: %s";
<ide>
<ide> public void apply(VersionSelection selection, ModuleComponentRepositoryAccess moduleAccess) {
<add> MetadataProvider metadataProvider = new MetadataProvider(selection, moduleAccess);
<add>
<ide> for (RuleAction<? super VersionSelection> rule : versionSelectionRules) {
<ide> List<Object> inputs = Lists.newArrayList();
<ide> for (Class<?> inputType : rule.getInputTypes()) {
<ide> if (inputType == ComponentMetadata.class) {
<del> MutableModuleVersionMetaData metaData = getMetaData(selection, moduleAccess);
<del> ComponentMetadataDetails componentMetadata = new ComponentMetadataDetailsAdapter(metaData);
<del> inputs.add(componentMetadata);
<add> inputs.add(metadataProvider.getComponentMetadata());
<ide> continue;
<ide> }
<ide> if (inputType == IvyModuleDescriptor.class) {
<del> MutableModuleVersionMetaData metaData = getMetaData(selection, moduleAccess);
<del> if (metaData instanceof IvyModuleVersionMetaData) {
<del> IvyModuleVersionMetaData ivyMetadata = (IvyModuleVersionMetaData) metaData;
<del> inputs.add(new DefaultIvyModuleDescriptor(ivyMetadata.getExtraInfo(), ivyMetadata.getBranch(), ivyMetadata.getStatus()));
<add> IvyModuleDescriptor ivyModuleDescriptor = metadataProvider.getIvyModuleDescriptor();
<add> if (ivyModuleDescriptor != null) {
<add> inputs.add(ivyModuleDescriptor);
<ide> continue;
<ide> } else {
<add> // Don't process rule for non-ivy modules
<ide> return;
<ide> }
<ide> }
<del> throw new InvalidUserCodeException(String.format(UNSUPPORTED_PARAMETER_TYPE_ERROR, inputType.getName()));
<add> // We've already validated the inputs: should never get here.
<add> throw new IllegalStateException();
<ide> }
<ide>
<ide> try {
<ide> throw new InvalidUserCodeException(USER_CODE_ERROR, e);
<ide> }
<ide> }
<del> }
<del>
<del> private MutableModuleVersionMetaData getMetaData(VersionSelection selection, ModuleComponentRepositoryAccess moduleAccess) {
<del> BuildableModuleVersionMetaDataResolveResult descriptorResult = new DefaultBuildableModuleVersionMetaDataResolveResult();
<del> moduleAccess.resolveComponentMetaData(((VersionSelectionInternal) selection).getDependencyMetaData(), selection.getCandidate(), descriptorResult);
<del> return descriptorResult.getMetaData();
<ide> }
<ide>
<ide> public boolean hasRules() {
<ide> }
<ide> return ruleAction;
<ide> }
<add>
<add> private static class MetadataProvider {
<add> private final VersionSelection versionSelection;
<add> private final ModuleComponentRepositoryAccess moduleAccess;
<add> private MutableModuleVersionMetaData cachedMetaData;
<add>
<add> private MetadataProvider(VersionSelection versionSelection, ModuleComponentRepositoryAccess moduleAccess) {
<add> this.versionSelection = versionSelection;
<add> this.moduleAccess = moduleAccess;
<add> }
<add>
<add> public ComponentMetadata getComponentMetadata() {
<add> return new ComponentMetadataDetailsAdapter(getMetaData());
<add> }
<add>
<add> public IvyModuleDescriptor getIvyModuleDescriptor() {
<add> ModuleVersionMetaData metaData = getMetaData();
<add> if (metaData instanceof IvyModuleVersionMetaData) {
<add> IvyModuleVersionMetaData ivyMetadata = (IvyModuleVersionMetaData) metaData;
<add> return new DefaultIvyModuleDescriptor(ivyMetadata.getExtraInfo(), ivyMetadata.getBranch(), ivyMetadata.getStatus());
<add> }
<add> return null;
<add> }
<add>
<add> private MutableModuleVersionMetaData getMetaData() {
<add> if (cachedMetaData == null) {
<add> cachedMetaData = initMetaData(versionSelection, moduleAccess);
<add> }
<add> return cachedMetaData;
<add> }
<add>
<add> private MutableModuleVersionMetaData initMetaData(VersionSelection selection, ModuleComponentRepositoryAccess moduleAccess) {
<add> BuildableModuleVersionMetaDataResolveResult descriptorResult = new DefaultBuildableModuleVersionMetaDataResolveResult();
<add> moduleAccess.resolveComponentMetaData(((VersionSelectionInternal) selection).getDependencyMetaData(), selection.getCandidate(), descriptorResult);
<add> return descriptorResult.getMetaData();
<add> }
<add>
<add> }
<ide> } |
|
JavaScript | mit | 901617b7cc57310cd0cb8ac38fbc0775517c6636 | 0 | silverbux/rsjs | 12713502-2e9c-11e5-8e17-a45e60cdfd11 | helloWorld.js | 125de1f3-2e9c-11e5-a92f-a45e60cdfd11 | 12713502-2e9c-11e5-8e17-a45e60cdfd11 | helloWorld.js | 12713502-2e9c-11e5-8e17-a45e60cdfd11 | <ide><path>elloWorld.js
<del>125de1f3-2e9c-11e5-a92f-a45e60cdfd11
<add>12713502-2e9c-11e5-8e17-a45e60cdfd11 |
|
Java | apache-2.0 | 6997ff4ba78fb523f925f11abc7f020dea88fe63 | 0 | tdiesler/camel,satishgummadelli/camel,onders86/camel,scranton/camel,allancth/camel,lowwool/camel,dvankleef/camel,stalet/camel,royopa/camel,stravag/camel,zregvart/camel,drsquidop/camel,askannon/camel,hqstevenson/camel,satishgummadelli/camel,Thopap/camel,coderczp/camel,allancth/camel,akhettar/camel,jameszkw/camel,tadayosi/camel,NickCis/camel,noelo/camel,logzio/camel,jlpedrosa/camel,CandleCandle/camel,MrCoder/camel,snurmine/camel,tarilabs/camel,ge0ffrey/camel,dpocock/camel,MohammedHammam/camel,edigrid/camel,gyc567/camel,trohovsky/camel,rparree/camel,ssharma/camel,grgrzybek/camel,ge0ffrey/camel,oscerd/camel,mnki/camel,isavin/camel,davidkarlsen/camel,jonmcewen/camel,isavin/camel,veithen/camel,grange74/camel,tdiesler/camel,punkhorn/camel-upstream,rmarting/camel,anoordover/camel,jamesnetherton/camel,woj-i/camel,bfitzpat/camel,JYBESSON/camel,partis/camel,DariusX/camel,stalet/camel,nikvaessen/camel,nicolaferraro/camel,qst-jdc-labs/camel,tarilabs/camel,yury-vashchyla/camel,josefkarasek/camel,ekprayas/camel,ssharma/camel,jkorab/camel,johnpoth/camel,yuruki/camel,sverkera/camel,ssharma/camel,oscerd/camel,edigrid/camel,jkorab/camel,oalles/camel,jarst/camel,pplatek/camel,mike-kukla/camel,sebi-hgdata/camel,curso007/camel,pkletsko/camel,sabre1041/camel,lburgazzoli/camel,gnodet/camel,koscejev/camel,acartapanis/camel,satishgummadelli/camel,jollygeorge/camel,chirino/camel,adessaigne/camel,YoshikiHigo/camel,askannon/camel,tarilabs/camel,mcollovati/camel,akhettar/camel,yogamaha/camel,dvankleef/camel,w4tson/camel,kevinearls/camel,lasombra/camel,dkhanolkar/camel,maschmid/camel,dkhanolkar/camel,skinzer/camel,YoshikiHigo/camel,johnpoth/camel,anton-k11/camel,iweiss/camel,dmvolod/camel,brreitme/camel,josefkarasek/camel,arnaud-deprez/camel,oalles/camel,cunningt/camel,snurmine/camel,grgrzybek/camel,RohanHart/camel,objectiser/camel,tkopczynski/camel,w4tson/camel,lowwool/camel,JYBESSON/camel,MrCoder/camel,chirino/camel,iweiss/camel,snadakuduru/camel,acartapanis/camel,yuruki/camel,borcsokj/camel,driseley/camel,erwelch/camel,yuruki/camel,skinzer/camel,anoordover/camel,onders86/camel,gautric/camel,jkorab/camel,rparree/camel,bhaveshdt/camel,borcsokj/camel,prashant2402/camel,lasombra/camel,manuelh9r/camel,rmarting/camel,jamesnetherton/camel,yury-vashchyla/camel,mzapletal/camel,tkopczynski/camel,sverkera/camel,nikvaessen/camel,grgrzybek/camel,jkorab/camel,dsimansk/camel,sebi-hgdata/camel,veithen/camel,neoramon/camel,tkopczynski/camel,tdiesler/camel,anoordover/camel,duro1/camel,joakibj/camel,driseley/camel,oalles/camel,maschmid/camel,dmvolod/camel,atoulme/camel,anton-k11/camel,apache/camel,dsimansk/camel,maschmid/camel,snurmine/camel,engagepoint/camel,cunningt/camel,JYBESSON/camel,anoordover/camel,gilfernandes/camel,jollygeorge/camel,borcsokj/camel,iweiss/camel,mnki/camel,lburgazzoli/apache-camel,trohovsky/camel,jollygeorge/camel,yogamaha/camel,noelo/camel,oscerd/camel,koscejev/camel,pkletsko/camel,dmvolod/camel,nicolaferraro/camel,oalles/camel,nikhilvibhav/camel,Fabryprog/camel,bfitzpat/camel,onders86/camel,rmarting/camel,gyc567/camel,stravag/camel,pmoerenhout/camel,acartapanis/camel,cunningt/camel,rparree/camel,salikjan/camel,acartapanis/camel,w4tson/camel,maschmid/camel,YMartsynkevych/camel,stravag/camel,oscerd/camel,gautric/camel,trohovsky/camel,bfitzpat/camel,jonmcewen/camel,FingolfinTEK/camel,alvinkwekel/camel,davidwilliams1978/camel,bdecoste/camel,allancth/camel,chanakaudaya/camel,partis/camel,dvankleef/camel,partis/camel,CandleCandle/camel,lowwool/camel,gyc567/camel,jonmcewen/camel,nikvaessen/camel,arnaud-deprez/camel,manuelh9r/camel,acartapanis/camel,bgaudaen/camel,tkopczynski/camel,yury-vashchyla/camel,lburgazzoli/apache-camel,RohanHart/camel,igarashitm/camel,snadakuduru/camel,lburgazzoli/apache-camel,cunningt/camel,sirlatrom/camel,brreitme/camel,jlpedrosa/camel,christophd/camel,qst-jdc-labs/camel,pax95/camel,onders86/camel,pmoerenhout/camel,johnpoth/camel,DariusX/camel,anton-k11/camel,onders86/camel,yury-vashchyla/camel,pplatek/camel,grange74/camel,satishgummadelli/camel,aaronwalker/camel,mcollovati/camel,jollygeorge/camel,pplatek/camel,nikhilvibhav/camel,logzio/camel,pmoerenhout/camel,manuelh9r/camel,isavin/camel,aaronwalker/camel,edigrid/camel,christophd/camel,coderczp/camel,tlehoux/camel,bdecoste/camel,adessaigne/camel,mgyongyosi/camel,bhaveshdt/camel,MohammedHammam/camel,neoramon/camel,christophd/camel,tarilabs/camel,mgyongyosi/camel,mohanaraosv/camel,driseley/camel,YMartsynkevych/camel,mike-kukla/camel,iweiss/camel,ge0ffrey/camel,NetNow/camel,yogamaha/camel,dkhanolkar/camel,lburgazzoli/apache-camel,tlehoux/camel,curso007/camel,Thopap/camel,pax95/camel,ramonmaruko/camel,apache/camel,bhaveshdt/camel,YoshikiHigo/camel,jmandawg/camel,mnki/camel,FingolfinTEK/camel,chanakaudaya/camel,alvinkwekel/camel,trohovsky/camel,royopa/camel,JYBESSON/camel,CodeSmell/camel,joakibj/camel,grange74/camel,sabre1041/camel,tlehoux/camel,jameszkw/camel,allancth/camel,atoulme/camel,atoulme/camel,yogamaha/camel,adessaigne/camel,jpav/camel,haku/camel,jlpedrosa/camel,lburgazzoli/camel,neoramon/camel,dpocock/camel,apache/camel,CandleCandle/camel,grange74/camel,gilfernandes/camel,atoulme/camel,woj-i/camel,gnodet/camel,drsquidop/camel,igarashitm/camel,atoulme/camel,dkhanolkar/camel,noelo/camel,alvinkwekel/camel,YMartsynkevych/camel,akhettar/camel,sabre1041/camel,logzio/camel,apache/camel,sabre1041/camel,lasombra/camel,partis/camel,mohanaraosv/camel,johnpoth/camel,ge0ffrey/camel,akhettar/camel,Fabryprog/camel,jpav/camel,christophd/camel,dpocock/camel,igarashitm/camel,snurmine/camel,bhaveshdt/camel,ssharma/camel,jmandawg/camel,FingolfinTEK/camel,ramonmaruko/camel,DariusX/camel,RohanHart/camel,nboukhed/camel,tadayosi/camel,brreitme/camel,haku/camel,askannon/camel,tlehoux/camel,chanakaudaya/camel,Thopap/camel,noelo/camel,pmoerenhout/camel,logzio/camel,prashant2402/camel,aaronwalker/camel,objectiser/camel,jmandawg/camel,anoordover/camel,askannon/camel,erwelch/camel,lburgazzoli/apache-camel,punkhorn/camel-upstream,CandleCandle/camel,chanakaudaya/camel,woj-i/camel,RohanHart/camel,nikhilvibhav/camel,oscerd/camel,ekprayas/camel,askannon/camel,jlpedrosa/camel,gyc567/camel,MohammedHammam/camel,brreitme/camel,MrCoder/camel,sirlatrom/camel,jonmcewen/camel,yuruki/camel,gautric/camel,mike-kukla/camel,dsimansk/camel,mgyongyosi/camel,jollygeorge/camel,FingolfinTEK/camel,RohanHart/camel,gilfernandes/camel,aaronwalker/camel,askannon/camel,edigrid/camel,bgaudaen/camel,chirino/camel,sirlatrom/camel,arnaud-deprez/camel,tadayosi/camel,davidwilliams1978/camel,grange74/camel,noelo/camel,lburgazzoli/camel,punkhorn/camel-upstream,lasombra/camel,borcsokj/camel,yuruki/camel,gyc567/camel,trohovsky/camel,qst-jdc-labs/camel,haku/camel,apache/camel,prashant2402/camel,mike-kukla/camel,dmvolod/camel,dsimansk/camel,zregvart/camel,woj-i/camel,curso007/camel,bdecoste/camel,bgaudaen/camel,jkorab/camel,woj-i/camel,nicolaferraro/camel,bfitzpat/camel,pax95/camel,veithen/camel,duro1/camel,mnki/camel,allancth/camel,isururanawaka/camel,jarst/camel,mcollovati/camel,coderczp/camel,NickCis/camel,bgaudaen/camel,duro1/camel,dkhanolkar/camel,curso007/camel,gautric/camel,zregvart/camel,joakibj/camel,oalles/camel,isavin/camel,davidkarlsen/camel,rparree/camel,manuelh9r/camel,ssharma/camel,veithen/camel,w4tson/camel,josefkarasek/camel,logzio/camel,sirlatrom/camel,erwelch/camel,ekprayas/camel,koscejev/camel,YoshikiHigo/camel,isururanawaka/camel,punkhorn/camel-upstream,chirino/camel,ullgren/camel,ramonmaruko/camel,erwelch/camel,akhettar/camel,stalet/camel,cunningt/camel,arnaud-deprez/camel,JYBESSON/camel,MohammedHammam/camel,jarst/camel,sverkera/camel,eformat/camel,anton-k11/camel,pkletsko/camel,yogamaha/camel,stalet/camel,koscejev/camel,alvinkwekel/camel,gilfernandes/camel,johnpoth/camel,skinzer/camel,snurmine/camel,skinzer/camel,igarashitm/camel,snadakuduru/camel,sirlatrom/camel,kevinearls/camel,mohanaraosv/camel,aaronwalker/camel,joakibj/camel,pax95/camel,MohammedHammam/camel,yury-vashchyla/camel,noelo/camel,zregvart/camel,coderczp/camel,snurmine/camel,MrCoder/camel,lburgazzoli/apache-camel,drsquidop/camel,davidwilliams1978/camel,pkletsko/camel,mike-kukla/camel,snadakuduru/camel,pplatek/camel,engagepoint/camel,lowwool/camel,curso007/camel,prashant2402/camel,dvankleef/camel,pmoerenhout/camel,gnodet/camel,ge0ffrey/camel,objectiser/camel,davidwilliams1978/camel,pkletsko/camel,erwelch/camel,sebi-hgdata/camel,bdecoste/camel,nboukhed/camel,brreitme/camel,kevinearls/camel,mnki/camel,tlehoux/camel,oscerd/camel,dsimansk/camel,duro1/camel,drsquidop/camel,dkhanolkar/camel,arnaud-deprez/camel,nboukhed/camel,mohanaraosv/camel,royopa/camel,chanakaudaya/camel,neoramon/camel,drsquidop/camel,NetNow/camel,NickCis/camel,tadayosi/camel,koscejev/camel,dvankleef/camel,davidwilliams1978/camel,anton-k11/camel,gyc567/camel,dpocock/camel,edigrid/camel,CandleCandle/camel,ekprayas/camel,pplatek/camel,coderczp/camel,MrCoder/camel,gnodet/camel,jarst/camel,nikhilvibhav/camel,CodeSmell/camel,jameszkw/camel,eformat/camel,edigrid/camel,mgyongyosi/camel,mzapletal/camel,acartapanis/camel,scranton/camel,logzio/camel,eformat/camel,royopa/camel,davidkarlsen/camel,Thopap/camel,davidkarlsen/camel,NetNow/camel,jkorab/camel,jamesnetherton/camel,erwelch/camel,lburgazzoli/camel,apache/camel,chirino/camel,tdiesler/camel,curso007/camel,royopa/camel,nikvaessen/camel,stravag/camel,onders86/camel,mzapletal/camel,mohanaraosv/camel,jpav/camel,grgrzybek/camel,mike-kukla/camel,qst-jdc-labs/camel,stalet/camel,CandleCandle/camel,gilfernandes/camel,stravag/camel,pplatek/camel,YMartsynkevych/camel,jamesnetherton/camel,pax95/camel,hqstevenson/camel,neoramon/camel,ullgren/camel,jmandawg/camel,scranton/camel,maschmid/camel,sebi-hgdata/camel,lowwool/camel,cunningt/camel,prashant2402/camel,anoordover/camel,rparree/camel,FingolfinTEK/camel,isavin/camel,gautric/camel,davidwilliams1978/camel,YoshikiHigo/camel,sabre1041/camel,eformat/camel,allancth/camel,dpocock/camel,chirino/camel,sverkera/camel,hqstevenson/camel,MrCoder/camel,atoulme/camel,nicolaferraro/camel,engagepoint/camel,ramonmaruko/camel,YoshikiHigo/camel,Fabryprog/camel,jamesnetherton/camel,tdiesler/camel,CodeSmell/camel,logzio/camel,jameszkw/camel,bhaveshdt/camel,FingolfinTEK/camel,pplatek/camel,grgrzybek/camel,sverkera/camel,NetNow/camel,jpav/camel,anton-k11/camel,dmvolod/camel,snadakuduru/camel,jollygeorge/camel,borcsokj/camel,adessaigne/camel,isavin/camel,iweiss/camel,mzapletal/camel,kevinearls/camel,mcollovati/camel,stravag/camel,MohammedHammam/camel,sebi-hgdata/camel,CodeSmell/camel,chanakaudaya/camel,igarashitm/camel,skinzer/camel,ekprayas/camel,joakibj/camel,tadayosi/camel,dpocock/camel,arnaud-deprez/camel,Thopap/camel,bdecoste/camel,josefkarasek/camel,mzapletal/camel,duro1/camel,scranton/camel,sabre1041/camel,scranton/camel,joakibj/camel,bhaveshdt/camel,sirlatrom/camel,mnki/camel,mgyongyosi/camel,adessaigne/camel,ullgren/camel,grgrzybek/camel,gautric/camel,jmandawg/camel,lowwool/camel,engagepoint/camel,isururanawaka/camel,NickCis/camel,jarst/camel,tdiesler/camel,lburgazzoli/camel,christophd/camel,gnodet/camel,salikjan/camel,tkopczynski/camel,yury-vashchyla/camel,w4tson/camel,jpav/camel,nikvaessen/camel,kevinearls/camel,igarashitm/camel,royopa/camel,jameszkw/camel,pmoerenhout/camel,jonmcewen/camel,josefkarasek/camel,isururanawaka/camel,RohanHart/camel,grange74/camel,sebi-hgdata/camel,haku/camel,Fabryprog/camel,manuelh9r/camel,bgaudaen/camel,jpav/camel,eformat/camel,rmarting/camel,Thopap/camel,rmarting/camel,drsquidop/camel,trohovsky/camel,driseley/camel,johnpoth/camel,yuruki/camel,maschmid/camel,veithen/camel,veithen/camel,hqstevenson/camel,bdecoste/camel,jarst/camel,akhettar/camel,koscejev/camel,driseley/camel,aaronwalker/camel,ramonmaruko/camel,NickCis/camel,coderczp/camel,kevinearls/camel,isururanawaka/camel,pax95/camel,jonmcewen/camel,jlpedrosa/camel,mgyongyosi/camel,jlpedrosa/camel,nikvaessen/camel,brreitme/camel,YMartsynkevych/camel,haku/camel,rparree/camel,snadakuduru/camel,pkletsko/camel,nboukhed/camel,ge0ffrey/camel,borcsokj/camel,satishgummadelli/camel,woj-i/camel,ullgren/camel,mohanaraosv/camel,dmvolod/camel,jamesnetherton/camel,tadayosi/camel,hqstevenson/camel,josefkarasek/camel,lburgazzoli/camel,sverkera/camel,mzapletal/camel,haku/camel,nboukhed/camel,isururanawaka/camel,tarilabs/camel,driseley/camel,qst-jdc-labs/camel,ekprayas/camel,adessaigne/camel,NetNow/camel,tarilabs/camel,bfitzpat/camel,JYBESSON/camel,engagepoint/camel,rmarting/camel,eformat/camel,dsimansk/camel,jmandawg/camel,hqstevenson/camel,skinzer/camel,iweiss/camel,satishgummadelli/camel,dvankleef/camel,NickCis/camel,oalles/camel,partis/camel,YMartsynkevych/camel,tkopczynski/camel,bfitzpat/camel,ramonmaruko/camel,partis/camel,lasombra/camel,nboukhed/camel,ssharma/camel,christophd/camel,yogamaha/camel,objectiser/camel,jameszkw/camel,w4tson/camel,qst-jdc-labs/camel,scranton/camel,gilfernandes/camel,duro1/camel,NetNow/camel,bgaudaen/camel,neoramon/camel,stalet/camel,tlehoux/camel,lasombra/camel,DariusX/camel,prashant2402/camel,manuelh9r/camel | /**
* 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.camel.processor;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.impl.ProducerCache;
import org.apache.camel.impl.ServiceSupport;
import org.apache.camel.model.RoutingSlipType;
import org.apache.camel.util.CollectionStringBuffer;
import org.apache.camel.util.ExchangeHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import static org.apache.camel.util.ObjectHelper.notNull;
/**
* Implements a <a href="http://activemq.apache.org/camel/routing-slip.html">Routing Slip</a>
* pattern where the list of actual endpoints to send a message exchange to are
* dependent on the value of a message header.
*/
public class RoutingSlip extends ServiceSupport implements Processor {
private static final transient Log LOG = LogFactory.getLog(RoutingSlip.class);
private final String header;
private final String uriDelimiter;
private ProducerCache producerCache = new ProducerCache();
public RoutingSlip(String header) {
this(header, RoutingSlipType.DEFAULT_DELIMITER);
}
public RoutingSlip(String header, String uriDelimiter) {
notNull(header, "header");
notNull(uriDelimiter, "uriDelimiter");
this.header = header;
this.uriDelimiter = uriDelimiter;
}
@Override
public String toString() {
return "RoutingSlip[header=" + header + " uriDelimiter=" + uriDelimiter + "]";
}
public void process(Exchange exchange) throws Exception {
Message message = exchange.getIn();
String[] recipients = recipients(message);
Exchange current = exchange;
for (String nextRecipient : recipients) {
Endpoint endpoint = resolveEndpoint(exchange, nextRecipient);
Producer producer = producerCache.getProducer(endpoint);
Exchange ex = current.newInstance();
updateRoutingSlip(current);
copyOutToIn(ex, current);
producer.process(ex);
current = ex;
}
ExchangeHelper.copyResults(exchange, current);
}
protected Endpoint resolveEndpoint(Exchange exchange, Object recipient) {
return ExchangeHelper.resolveEndpoint(exchange, recipient);
}
protected void doStop() throws Exception {
producerCache.stop();
}
protected void doStart() throws Exception {
}
private void updateRoutingSlip(Exchange current) {
Message message = getResultMessage(current);
String oldSlip = message.getHeader(header, String.class);
if (oldSlip != null) {
int delimiterIndex = oldSlip.indexOf(uriDelimiter);
String newSlip = delimiterIndex > 0 ? oldSlip.substring(delimiterIndex + 1) : "";
message.setHeader(header, newSlip);
}
}
/**
* Returns the outbound message if available. Otherwise return the inbound
* message.
*/
private Message getResultMessage(Exchange exchange) {
Message message = exchange.getOut(false);
// if this endpoint had no out (like a mock endpoint)
// just take the in
if (message == null) {
message = exchange.getIn();
}
return message;
}
/**
* Return the list of recipients defined in the routing slip in the
* specified message.
*/
private String[] recipients(Message message) {
Object headerValue = message.getHeader(header);
if (headerValue != null && !headerValue.equals("")) {
return headerValue.toString().split(uriDelimiter);
}
return new String[] {};
}
/**
* Copy the outbound data in 'source' to the inbound data in 'result'.
*/
private void copyOutToIn(Exchange result, Exchange source) {
result.setException(source.getException());
Message fault = source.getFault(false);
if (fault != null) {
result.getFault(true).copyFrom(fault);
}
result.setIn(getResultMessage(source));
result.getProperties().clear();
result.getProperties().putAll(source.getProperties());
}
}
| camel-core/src/main/java/org/apache/camel/processor/RoutingSlip.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.camel.processor;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.impl.ProducerCache;
import org.apache.camel.impl.ServiceSupport;
import org.apache.camel.model.RoutingSlipType;
import org.apache.camel.util.CollectionStringBuffer;
import org.apache.camel.util.ExchangeHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import static org.apache.camel.util.ObjectHelper.notNull;
/**
* Implements a <a href="http://activemq.apache.org/camel/routing-slip.html">Routing Slip</a>
* pattern where the list of actual endpoints to send a message exchange to are
* dependent on the value of a message header.
*/
public class RoutingSlip extends ServiceSupport implements Processor {
private static final transient Log LOG = LogFactory.getLog(RoutingSlip.class);
private final String header;
private final String uriDelimiter;
private ProducerCache producerCache = new ProducerCache();
public RoutingSlip(String header) {
this(header, RoutingSlipType.DEFAULT_DELIMITER);
}
public RoutingSlip(String header, String uriDelimiter) {
notNull(header, "header");
notNull(uriDelimiter, "uriDelimiter");
this.header = header;
this.uriDelimiter = uriDelimiter;
}
@Override
public String toString() {
return "RoutingSlip[header=" + header + " uriDelimiter=" + uriDelimiter + "]";
}
public void process(Exchange exchange) throws Exception {
Message message = exchange.getIn();
String[] recipients = recipients(message);
Exchange current = exchange;
for (String nextRecipient : recipients) {
Endpoint endpoint = resolveEndpoint(exchange, nextRecipient);
Producer producer = producerCache.getProducer(endpoint);
Exchange ex = current.newInstance();
updateRoutingSlip(current);
copyOutToIn(ex, current);
producer.process(ex);
current = ex;
}
ExchangeHelper.copyResults(exchange, current);
}
protected Endpoint resolveEndpoint(Exchange exchange, Object recipient) {
return ExchangeHelper.resolveEndpoint(exchange, recipient);
}
protected void doStop() throws Exception {
producerCache.stop();
}
protected void doStart() throws Exception {
}
private void updateRoutingSlip(Exchange current) {
Message message = getResultMessage(current);
// TODO: Why not use indexOf and substr to find first delimiter, to skip first elemeent
message.setHeader(header, removeFirstElement(recipients(message)));
}
/**
* Returns the outbound message if available. Otherwise return the inbound
* message.
*/
private Message getResultMessage(Exchange exchange) {
Message message = exchange.getOut(false);
// if this endpoint had no out (like a mock endpoint)
// just take the in
if (message == null) {
message = exchange.getIn();
}
return message;
}
/**
* Return the list of recipients defined in the routing slip in the
* specified message.
*/
private String[] recipients(Message message) {
Object headerValue = message.getHeader(header);
if (headerValue != null && !headerValue.equals("")) {
return headerValue.toString().split(uriDelimiter);
}
return new String[] {};
}
/**
* Return a string representation of the element list with the first element
* removed.
*/
private String removeFirstElement(String[] elements) {
CollectionStringBuffer updatedElements = new CollectionStringBuffer(uriDelimiter);
for (int i = 1; i < elements.length; i++) {
updatedElements.append(elements[i]);
}
return updatedElements.toString();
}
/**
* Copy the outbound data in 'source' to the inbound data in 'result'.
*/
private void copyOutToIn(Exchange result, Exchange source) {
result.setException(source.getException());
Message fault = source.getFault(false);
if (fault != null) {
result.getFault(true).copyFrom(fault);
}
result.setIn(getResultMessage(source));
result.getProperties().clear();
result.getProperties().putAll(source.getProperties());
}
}
| Clean up code
git-svn-id: e3ccc80b644512be24afa6caf639b2d1f1969354@720503 13f79535-47bb-0310-9956-ffa450edef68
| camel-core/src/main/java/org/apache/camel/processor/RoutingSlip.java | Clean up code | <ide><path>amel-core/src/main/java/org/apache/camel/processor/RoutingSlip.java
<ide>
<ide> private void updateRoutingSlip(Exchange current) {
<ide> Message message = getResultMessage(current);
<del> // TODO: Why not use indexOf and substr to find first delimiter, to skip first elemeent
<del> message.setHeader(header, removeFirstElement(recipients(message)));
<add> String oldSlip = message.getHeader(header, String.class);
<add> if (oldSlip != null) {
<add> int delimiterIndex = oldSlip.indexOf(uriDelimiter);
<add> String newSlip = delimiterIndex > 0 ? oldSlip.substring(delimiterIndex + 1) : "";
<add> message.setHeader(header, newSlip);
<add> }
<ide> }
<ide>
<ide> /**
<ide> }
<ide>
<ide> /**
<del> * Return a string representation of the element list with the first element
<del> * removed.
<del> */
<del> private String removeFirstElement(String[] elements) {
<del> CollectionStringBuffer updatedElements = new CollectionStringBuffer(uriDelimiter);
<del> for (int i = 1; i < elements.length; i++) {
<del> updatedElements.append(elements[i]);
<del> }
<del> return updatedElements.toString();
<del> }
<del>
<del> /**
<ide> * Copy the outbound data in 'source' to the inbound data in 'result'.
<ide> */
<ide> private void copyOutToIn(Exchange result, Exchange source) { |
|
Java | apache-2.0 | de9516e368312a5a4e929921d43e716adbbcf8df | 0 | stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,colezlaw/DependencyCheck,hansjoachim/DependencyCheck,jeremylong/DependencyCheck,colezlaw/DependencyCheck,jeremylong/DependencyCheck,hansjoachim/DependencyCheck,stevespringett/DependencyCheck,awhitford/DependencyCheck,stevespringett/DependencyCheck,colezlaw/DependencyCheck,stefanneuhaus/DependencyCheck,stevespringett/DependencyCheck,awhitford/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,awhitford/DependencyCheck,stevespringett/DependencyCheck,stevespringett/DependencyCheck,stefanneuhaus/DependencyCheck,stevespringett/DependencyCheck,colezlaw/DependencyCheck,awhitford/DependencyCheck,colezlaw/DependencyCheck,hansjoachim/DependencyCheck,stefanneuhaus/DependencyCheck,awhitford/DependencyCheck,awhitford/DependencyCheck,stefanneuhaus/DependencyCheck,stevespringett/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,awhitford/DependencyCheck,hansjoachim/DependencyCheck,colezlaw/DependencyCheck,hansjoachim/DependencyCheck,colezlaw/DependencyCheck,awhitford/DependencyCheck,jeremylong/DependencyCheck,hansjoachim/DependencyCheck,hansjoachim/DependencyCheck | /*
* This file is part of dependency-check-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 (c) 2015 The OWASP Foundatio. All Rights Reserved.
*/
package org.owasp.dependencycheck.analyzer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.dependency.Confidence;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.Evidence;
import java.io.File;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import org.owasp.dependencycheck.BaseDBTestCase;
/**
* Unit tests for NodePackageAnalyzer.
*
* @author Dale Visser
*/
public class ComposerLockAnalyzerTest extends BaseDBTestCase {
/**
* The analyzer to test.
*/
ComposerLockAnalyzer analyzer;
/**
* Correctly setup the analyzer for testing.
*
* @throws Exception thrown if there is a problem
*/
@Before
public void setUp() throws Exception {
analyzer = new ComposerLockAnalyzer();
analyzer.setFilesMatched(true);
analyzer.initialize();
}
/**
* Cleanup the analyzer's temp files, etc.
*
* @throws Exception thrown if there is a problem
*/
@After
public void tearDown() throws Exception {
analyzer.close();
analyzer = null;
}
/**
* Test of getName method, of class ComposerLockAnalyzer.
*/
@Test
public void testGetName() {
assertEquals("Composer.lock analyzer", analyzer.getName());
}
/**
* Test of supportsExtension method, of class ComposerLockAnalyzer.
*/
@Test
public void testSupportsFiles() {
assertTrue(analyzer.accept(new File("composer.lock")));
}
/**
* Test of inspect method, of class PythonDistributionAnalyzer.
*
* @throws AnalysisException is thrown when an exception occurs.
*/
@Test
public void testAnalyzePackageJson() throws Exception {
final Engine engine = new Engine();
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this,
"composer.lock"));
analyzer.analyze(result, engine);
}
}
| dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/ComposerLockAnalyzerTest.java | /*
* This file is part of dependency-check-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 (c) 2015 The OWASP Foundatio. All Rights Reserved.
*/
package org.owasp.dependencycheck.analyzer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.dependency.Confidence;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.Evidence;
import java.io.File;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import org.owasp.dependencycheck.BaseDBTestCase;
/**
* Unit tests for NodePackageAnalyzer.
*
* @author Dale Visser <[email protected]>
*/
public class ComposerLockAnalyzerTest extends BaseDBTestCase {
/**
* The analyzer to test.
*/
ComposerLockAnalyzer analyzer;
/**
* Correctly setup the analyzer for testing.
*
* @throws Exception thrown if there is a problem
*/
@Before
public void setUp() throws Exception {
analyzer = new ComposerLockAnalyzer();
analyzer.setFilesMatched(true);
analyzer.initialize();
}
/**
* Cleanup the analyzer's temp files, etc.
*
* @throws Exception thrown if there is a problem
*/
@After
public void tearDown() throws Exception {
analyzer.close();
analyzer = null;
}
/**
* Test of getName method, of class ComposerLockAnalyzer.
*/
@Test
public void testGetName() {
assertEquals("Composer.lock analyzer", analyzer.getName());
}
/**
* Test of supportsExtension method, of class ComposerLockAnalyzer.
*/
@Test
public void testSupportsFiles() {
assertTrue(analyzer.accept(new File("composer.lock")));
}
/**
* Test of inspect method, of class PythonDistributionAnalyzer.
*
* @throws AnalysisException is thrown when an exception occurs.
*/
@Test
public void testAnalyzePackageJson() throws Exception {
final Engine engine = new Engine();
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this,
"composer.lock"));
analyzer.analyze(result, engine);
}
}
| doclint fixes
| dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/ComposerLockAnalyzerTest.java | doclint fixes | <ide><path>ependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/ComposerLockAnalyzerTest.java
<ide> /**
<ide> * Unit tests for NodePackageAnalyzer.
<ide> *
<del> * @author Dale Visser <[email protected]>
<add> * @author Dale Visser
<ide> */
<ide> public class ComposerLockAnalyzerTest extends BaseDBTestCase {
<ide> |
|
JavaScript | mit | d7b13013bc9aaf6b6c786dd8d800c913f7809c96 | 0 | ranmocy/rCaltrain,paulirish/caltrainschedule.io,ranmocy/rCaltrain,ranmocy/rCaltrain,ranmocy/rCaltrain,paulirish/caltrainschedule.io,ranmocy/rCaltrain,ranmocy/rCaltrain,paulirish/caltrainschedule.io | function data_checker (names, callback) {
var mark = {}, callback = callback;
names.forEach(function(name) {
mark[name] = false;
});
return function(name) {
mark[name] = true;
var all_true = true;
for (var n in mark)
if (!mark[n])
all_true = false;
if (all_true)
callback();
};
}
function schedule (event) {
var times = event.data.times;
var now_date = new Date();
// Fix the stop ids
var from_id = parseInt($("#from").prop("value")), to_id = parseInt($("#to").prop("value"));
if (to_id > from_id) {
// South Bound
from_id += 1;
to_id += 1;
};
// Save selections to cookies
$.cookie("from", $("#from").prop("value"));
$.cookie("to", $("#to").prop("value"));
$.cookie("when", $("#when").prop("value"));
$.cookie("now", $("#now").prop("checked"));
// trip_id regexp
var trip_reg;
if ($("#now").is(":checked")) {
switch (now_date.getDay()) {
case 1: case 2: case 3: case 4: case 5:
trip_reg = /Weekday/;
break;
case 6:
trip_reg = /Saturday/;
break;
case 0:
trip_reg = /Sunday/;
break;
default:
alert("now_date.getDay() got wrong: " + now_date.getDay());
}
} else {
if ($("#when").prop("value") == "weekend") {
trip_reg = /Saturday|Sunday/;
} else {
trip_reg = /Weekday/;
};
};
// Select trips
var trips = {};
times.forEach(function(t) {
if (!trip_reg.exec(t.trip_id)) {
return;
};
if (t.stop_id == from_id) {
trips[t.trip_id] = {
from: from_id,
from_time: t.arrival_time
};
} else if (t.stop_id == to_id) {
$.extend(trips[t.trip_id], {
to: to_id,
to_time: t.departure_time
});
};
});
// generate html strings and sort
var now_str = now_date.getHours() + ':' + now_date.getMinutes() + ':00';
var next_train = '99:99:99';
var trip_strs = [];
for (var trip_id in trips) {
var trip = trips[trip_id];
// check if available, 2014 OCT only,
if (!/14OCT/.exec(trip_id) ||
typeof(trip.from_time) == "undefined" ||
typeof(trip.to_time) == "undefined" ||
($("#now").is(":checked") && trip.from_time < now_str)) {
continue;
};
if (next_train > trip.from_time) {
next_train = trip.from_time;
};
var from_parts = trip.from_time.split(':').map(function(t) { return parseInt(t) });
var to_parts = trip.to_time.split(':').map(function(t) { return parseInt(t) });
var trip_time = (to_parts[0] - from_parts[0]) * 60 + (to_parts[1] - from_parts[1]);
var item = '<div class="trip">' +
trip.from_time + ' => ' + trip.to_time + ' = ' + trip_time + 'min' +
'</div>';
trip_strs.push(item);
};
trip_strs.sort();
// append next train info
var info = $("#info").empty();
if ($("#now").is(":checked") && next_train !== '99:99:99') {
var next_parts = next_train.split(':').map(function(t) { return parseInt(t) });
console.debug(next_train, next_parts);
var next_relative = (next_parts[0] - now_date.getHours()) * 60 + (next_parts[1] - now_date.getMinutes());
info.append('<div class="info">Next train: ' + next_relative + 'min</div>');
};
// append the result
var result = $("#result").empty();
trip_strs.forEach(function(str) {
result.append(str);
});
}
$(document).ready(function() {
var stops, times;
var checker = data_checker(["stops", "times"], function() {
// All data is finished
var city_ids = {}, city_names = {};
var from = $("#from"), to = $("#to");
stops.forEach(function(s) {
if (/Station/.exec(s.stop_name)) { return; }; // remove duplications
city_ids[s.stop_id] = s.stop_name;
if (typeof(city_ids[s.stop_name]) == "undefined") {
city_ids[s.stop_name] = s.stop_id;
from.append(new Option(s.stop_name, s.stop_id));
to.append(new Option(s.stop_name, s.stop_id));
};
});
from.on("change", { times: times }, schedule);
to.on("change", { times: times }, schedule);
$("#when").on("change", { times: times }, schedule);
$("#now").change({ times: times }, function(event) {
$("#when").prop("disabled", $(this).is(":checked"));
schedule(event);
});
$("#search").on("click", { times: times }, schedule).prop("disabled", false);
$("#reverse").on("click", { times: times }, function(event) {
var t = from.prop("value");
from.prop("value", to.prop("value"));
to.prop("value", t);
schedule(event);
}).prop("disabled", false);
// load selections from cookies
$.cookie.defaults.expires = 365;
$.cookie.defaults.path = '/';
$("#from").prop("value", $.cookie("from"));
$("#to").prop("value", $.cookie("to"));
$("#when").prop("value", $.cookie("when"));
$("#now").prop("checked", $.cookie("now"));
schedule({data: {times: times}});
});
Papa.parse("gtfs/stops.txt", {
download: true,
dynamicTyping: true,
header: true,
complete: function(results) {
stops = results.data;
checker("stops");
}
});
Papa.parse("gtfs/stop_times.txt", {
download: true,
dynamicTyping: true,
header: true,
complete: function(results) {
times = results.data;
checker("times");
}
});
});
| default.js | function data_checker (names, callback) {
var mark = {}, callback = callback;
names.forEach(function(name) {
mark[name] = false;
});
return function(name) {
mark[name] = true;
var all_true = true;
for (var n in mark)
if (!mark[n])
all_true = false;
if (all_true)
callback();
};
}
function schedule (event) {
var times = event.data.times;
var now_date = new Date();
// Fix the stop ids
var from_id = parseInt($("#from").prop("value")), to_id = parseInt($("#to").prop("value"));
if (to_id > from_id) {
// South Bound
from_id += 1;
to_id += 1;
};
// Save selections to cookies
$.cookie("from", $("#from").prop("value"));
$.cookie("to", $("#to").prop("value"));
$.cookie("when", $("#when").prop("value"));
$.cookie("now", $("#now").prop("checked"));
// trip_id regexp
var trip_reg;
if ($("#now").is(":checked")) {
switch (now_date.getDay()) {
case 1: case 2: case 3: case 4: case 5:
trip_reg = /Weekday/;
break;
case 6:
trip_reg = /Saturday/;
break;
case 0:
trip_reg = /Sunday/;
break;
default:
alert("now_date.getDay() got wrong: " + now_date.getDay());
}
} else {
if ($("#when").prop("value") == "weekend") {
trip_reg = /Saturday|Sunday/;
} else {
trip_reg = /Weekday/;
};
};
// Select trips
var trips = {};
times.forEach(function(t) {
if (!trip_reg.exec(t.trip_id)) {
return;
};
if (t.stop_id == from_id) {
trips[t.trip_id] = {
from: from_id,
from_time: t.arrival_time
};
} else if (t.stop_id == to_id) {
$.extend(trips[t.trip_id], {
to: to_id,
to_time: t.departure_time
});
};
});
// generate html strings and sort
var now_str = now_date.getHours() + ':' + now_date.getMinutes() + ':00';
var next_train = '99:99:99';
var trip_strs = [];
for (var trip_id in trips) {
var trip = trips[trip_id];
// check if available, 2014 OCT only,
if (!/14OCT/.exec(trip_id) ||
typeof(trip.from_time) == "undefined" ||
typeof(trip.to_time) == "undefined" ||
($("#now").is(":checked") && trip.from_time < now_str)) {
continue;
};
if (next_train > trip.from_time) {
next_train = trip.from_time;
};
var from_parts = trip.from_time.split(':').map(function(t) { return parseInt(t) });
var to_parts = trip.to_time.split(':').map(function(t) { return parseInt(t) });
var trip_time = (to_parts[0] - from_parts[0]) * 60 + (to_parts[1] - from_parts[1]);
var item = '<div class="trip">' +
trip.from_time + ' => ' + trip.to_time + ' = ' + trip_time + 'min' +
'</div>';
trip_strs.push(item);
};
trip_strs.sort();
// append next train info
var info = $("#info").empty();
if ($("#now").is(":checked")) {
var next_parts = next_train.split(':').map(function(t) { return parseInt(t) });
console.debug(next_train, next_parts);
var next_relative = (next_parts[0] - now_date.getHours()) * 60 + (next_parts[1] - now_date.getMinutes());
info.append('<div class="info">Next train: ' + next_relative + 'min</div>');
};
// append the result
var result = $("#result").empty();
trip_strs.forEach(function(str) {
result.append(str);
});
}
$(document).ready(function() {
var stops, times;
var checker = data_checker(["stops", "times"], function() {
// All data is finished
var city_ids = {}, city_names = {};
var from = $("#from"), to = $("#to");
stops.forEach(function(s) {
if (/Station/.exec(s.stop_name)) { return; }; // remove duplications
city_ids[s.stop_id] = s.stop_name;
if (typeof(city_ids[s.stop_name]) == "undefined") {
city_ids[s.stop_name] = s.stop_id;
from.append(new Option(s.stop_name, s.stop_id));
to.append(new Option(s.stop_name, s.stop_id));
};
});
from.on("change", { times: times }, schedule);
to.on("change", { times: times }, schedule);
$("#when").on("change", { times: times }, schedule);
$("#now").change({ times: times }, function(event) {
$("#when").prop("disabled", $(this).is(":checked"));
schedule(event);
});
$("#search").on("click", { times: times }, schedule).prop("disabled", false);
$("#reverse").on("click", { times: times }, function(event) {
var t = from.prop("value");
from.prop("value", to.prop("value"));
to.prop("value", t);
schedule(event);
}).prop("disabled", false);
// load selections from cookies
$.cookie.defaults.expires = 365;
$.cookie.defaults.path = '/';
$("#from").prop("value", $.cookie("from"));
$("#to").prop("value", $.cookie("to"));
$("#when").prop("value", $.cookie("when"));
$("#now").prop("checked", $.cookie("now"));
schedule({data: {times: times}});
});
Papa.parse("gtfs/stops.txt", {
download: true,
dynamicTyping: true,
header: true,
complete: function(results) {
stops = results.data;
checker("stops");
}
});
Papa.parse("gtfs/stop_times.txt", {
download: true,
dynamicTyping: true,
header: true,
complete: function(results) {
times = results.data;
checker("times");
}
});
});
| not display next train if no result
| default.js | not display next train if no result | <ide><path>efault.js
<ide>
<ide> // append next train info
<ide> var info = $("#info").empty();
<del> if ($("#now").is(":checked")) {
<add> if ($("#now").is(":checked") && next_train !== '99:99:99') {
<ide> var next_parts = next_train.split(':').map(function(t) { return parseInt(t) });
<ide> console.debug(next_train, next_parts);
<ide> var next_relative = (next_parts[0] - now_date.getHours()) * 60 + (next_parts[1] - now_date.getMinutes()); |
|
JavaScript | mit | f469bf549148ef7c8cab75e00c073a46992c0134 | 0 | jamonkko/console-log-server | (function(exports){
exports.neatJSON = neatJSON;
function neatJSON(value,opts){
opts = opts || {}
if (!('wrap' in opts)) opts.wrap = 80;
if (opts.wrap==true) opts.wrap = -1;
if (!('indent' in opts)) opts.indent = ' ';
if (!('arrayPadding' in opts)) opts.arrayPadding = ('padding' in opts) ? opts.padding : 0;
if (!('objectPadding' in opts)) opts.objectPadding = ('padding' in opts) ? opts.padding : 0;
if (!('beforeComma' in opts)) opts.beforeComma = ('aroundComma' in opts) ? opts.aroundComma : 0;
if (!('afterComma' in opts)) opts.afterComma = ('aroundComma' in opts) ? opts.aroundComma : 0;
if (!('beforeColon' in opts)) opts.beforeColon = ('aroundColon' in opts) ? opts.aroundColon : 0;
if (!('afterColon' in opts)) opts.afterColon = ('aroundColon' in opts) ? opts.aroundColon : 0;
if (!('beforeColon1' in opts)) opts.beforeColon1 = ('aroundColon1' in opts) ? opts.aroundColon1 : ('beforeColon' in opts) ? opts.beforeColon : 0;
if (!('afterColon1' in opts)) opts.afterColon1 = ('aroundColon1' in opts) ? opts.aroundColon1 : ('afterColon' in opts) ? opts.afterColon : 0;
if (!('beforeColonN' in opts)) opts.beforeColonN = ('aroundColonN' in opts) ? opts.aroundColonN : ('beforeColon' in opts) ? opts.beforeColon : 0;
if (!('afterColonN' in opts)) opts.afterColonN = ('aroundColonN' in opts) ? opts.aroundColonN : ('afterColon' in opts) ? opts.afterColon : 0;
var apad = repeat(' ',opts.arrayPadding),
opad = repeat(' ',opts.objectPadding),
comma = repeat(' ',opts.beforeComma)+','+repeat(' ',opts.afterComma),
colon1 = repeat(' ',opts.beforeColon1)+':'+repeat(' ',opts.afterColon1),
colonN = repeat(' ',opts.beforeColonN)+':'+repeat(' ',opts.afterColonN);
var build = memoize();
return build(value,'');
function memoize(){
var memo = new Map;
return function(o,indent){
var byIndent=memo.get(o);
if (!byIndent) memo.set(o,byIndent={});
if (!byIndent[indent]) byIndent[indent] = rawBuild(o,indent);
return byIndent[indent];
}
}
function rawBuild(o,indent){
if (o===null || o===undefined) return indent+'null';
else{
if (typeof o==='number'){
var isFloat = (o === +o && o !== (o|0));
return indent + ((isFloat && ('decimals' in opts)) ? o.toFixed(opts.decimals) : (o+''));
}else if (o instanceof Array){
if (!o.length) return indent+"[]";
var pieces = o.map(function(v){ return build(v,'') });
var oneLine = indent+'['+apad+pieces.join(comma)+apad+']';
if (opts.wrap===false || oneLine.length<=opts.wrap) return oneLine;
if (opts.short){
var indent2 = indent+' '+apad;
pieces = o.map(function(v){ return build(v,indent2) });
pieces[0] = pieces[0].replace(indent2,indent+'['+apad);
pieces[pieces.length-1] = pieces[pieces.length-1]+apad+']';
return pieces.join(',\n');
}else{
var indent2 = indent+opts.indent;
return indent+'[\n'+o.map(function(v){ return build(v,indent2) }).join(',\n')+'\n'+(opts.indentLast?indent2:indent)+']';
}
}else if (o instanceof Object){
var sortedKV=[],i=0;
var sort = opts.sort || opts.sorted;
for (var k in o){
var kv = sortedKV[i++] = [k,o[k]];
if (sort===true) kv[2] = k;
else if (typeof sort==='function') kv[2]=sort(k,o[k],o);
}
if (!sortedKV.length) return indent+'{}';
if (sort) sortedKV = sortedKV.sort(function(a,b){ a=a[2]; b=b[2]; return a<b?-1:a>b?1:0 });
var keyvals=sortedKV.map(function(kv){ return [JSON.stringify(kv[0]), build(kv[1],'')] });
if (opts.sorted) keyvals = keyvals.sort(function(kv1,kv2){ kv1=kv1[0]; kv2=kv2[0]; return kv1<kv2?-1:kv1>kv2?1:0 });
keyvals = keyvals.map(function(kv){ return kv.join(colon1) }).join(comma);
var oneLine = indent+"{"+opad+keyvals+opad+"}";
if (opts.wrap===false || oneLine.length<opts.wrap) return oneLine;
if (opts.short){
keyvals = sortedKV.map(function(kv){ return [indent+' '+opad+JSON.stringify(kv[0]), kv[1]] });
keyvals[0][0] = keyvals[0][0].replace(indent+' ',indent+'{');
if (opts.aligned){
var longest = 0;
for (var i=keyvals.length;i--;) if (keyvals[i][0].length>longest) longest = keyvals[i][0].length;
var padding = repeat(' ',longest);
for (var i=keyvals.length;i--;) keyvals[i][0] = padRight(padding,keyvals[i][0]);
}
for (var i=keyvals.length;i--;){
var k=keyvals[i][0], v=keyvals[i][1];
var indent2 = repeat(' ',(k+colonN).length);
var oneLine = k+colonN+build(v,'');
keyvals[i] = (opts.wrap===false || oneLine.length<=opts.wrap || !v || typeof v!="object") ? oneLine : (k+colonN+build(v,indent2).replace(/^\s+/,''));
}
return keyvals.join(',\n') + opad + '}';
}else{
var keyvals=[],i=0;
for (var k in o) keyvals[i++] = [indent+opts.indent+JSON.stringify(k),o[k]];
if (opts.sorted) keyvals = keyvals.sort(function(kv1,kv2){ kv1=kv1[0]; kv2=kv2[0]; return kv1<kv2?-1:kv1>kv2?1:0 });
if (opts.aligned){
var longest = 0;
for (var i=keyvals.length;i--;) if (keyvals[i][0].length>longest) longest = keyvals[i][0].length;
var padding = repeat(' ',longest);
for (var i=keyvals.length;i--;) keyvals[i][0] = padRight(padding,keyvals[i][0]);
}
var indent2 = indent+opts.indent;
for (var i=keyvals.length;i--;){
var k=keyvals[i][0], v=keyvals[i][1];
var oneLine = k+colonN+build(v,'');
keyvals[i] = (opts.wrap===false || oneLine.length<=opts.wrap || !v || typeof v!="object") ? oneLine : (k+colonN+build(v,indent2).replace(/^\s+/,''));
}
return indent+'{\n'+keyvals.join(',\n')+'\n'+(opts.indentLast?indent2:indent)+'}'
}
}else if (typeof o === 'string'){
return indent+'\"'+o+'\"';
}else{
return indent+JSON.stringify(o);
}
}
}
function repeat(str,times){ // http://stackoverflow.com/a/17800645/405017
var result = '';
while(true){
if (times & 1) result += str;
times >>= 1;
if (times) str += str;
else break;
}
return result;
}
function padRight(pad, str){
return (str + pad).substring(0, pad.length);
}
}
neatJSON.version = "0.8.1";
})(typeof exports === 'undefined' ? this : exports);
| vendor/neat-json/index.js | (function(exports){
exports.neatJSON = neatJSON;
function neatJSON(value,opts){
opts = opts || {}
if (!('wrap' in opts)) opts.wrap = 80;
if (opts.wrap==true) opts.wrap = -1;
if (!('indent' in opts)) opts.indent = ' ';
if (!('arrayPadding' in opts)) opts.arrayPadding = ('padding' in opts) ? opts.padding : 0;
if (!('objectPadding' in opts)) opts.objectPadding = ('padding' in opts) ? opts.padding : 0;
if (!('beforeComma' in opts)) opts.beforeComma = ('aroundComma' in opts) ? opts.aroundComma : 0;
if (!('afterComma' in opts)) opts.afterComma = ('aroundComma' in opts) ? opts.aroundComma : 0;
if (!('beforeColon' in opts)) opts.beforeColon = ('aroundColon' in opts) ? opts.aroundColon : 0;
if (!('afterColon' in opts)) opts.afterColon = ('aroundColon' in opts) ? opts.aroundColon : 0;
if (!('beforeColon1' in opts)) opts.beforeColon1 = ('aroundColon1' in opts) ? opts.aroundColon1 : ('beforeColon' in opts) ? opts.beforeColon : 0;
if (!('afterColon1' in opts)) opts.afterColon1 = ('aroundColon1' in opts) ? opts.aroundColon1 : ('afterColon' in opts) ? opts.afterColon : 0;
if (!('beforeColonN' in opts)) opts.beforeColonN = ('aroundColonN' in opts) ? opts.aroundColonN : ('beforeColon' in opts) ? opts.beforeColon : 0;
if (!('afterColonN' in opts)) opts.afterColonN = ('aroundColonN' in opts) ? opts.aroundColonN : ('afterColon' in opts) ? opts.afterColon : 0;
var apad = repeat(' ',opts.arrayPadding),
opad = repeat(' ',opts.objectPadding),
comma = repeat(' ',opts.beforeComma)+','+repeat(' ',opts.afterComma),
colon1 = repeat(' ',opts.beforeColon1)+':'+repeat(' ',opts.afterColon1),
colonN = repeat(' ',opts.beforeColonN)+':'+repeat(' ',opts.afterColonN);
var build = memoize();
return build(value,'');
function memoize(){
var memo = new Map;
return function(o,indent){
var byIndent=memo.get(o);
if (!byIndent) memo.set(o,byIndent={});
if (!byIndent[indent]) byIndent[indent] = rawBuild(o,indent);
return byIndent[indent];
}
}
function rawBuild(o,indent){
if (o===null || o===undefined) return indent+'null';
else{
if (typeof o==='number'){
var isFloat = (o === +o && o !== (o|0));
return indent + ((isFloat && ('decimals' in opts)) ? o.toFixed(opts.decimals) : (o+''));
}else if (o instanceof Array){
if (!o.length) return indent+"[]";
var pieces = o.map(function(v){ return build(v,'') });
var oneLine = indent+'['+apad+pieces.join(comma)+apad+']';
if (opts.wrap===false || oneLine.length<=opts.wrap) return oneLine;
if (opts.short){
var indent2 = indent+' '+apad;
pieces = o.map(function(v){ return build(v,indent2) });
pieces[0] = pieces[0].replace(indent2,indent+'['+apad);
pieces[pieces.length-1] = pieces[pieces.length-1]+apad+']';
return pieces.join(',\n');
}else{
var indent2 = indent+opts.indent;
return indent+'[\n'+o.map(function(v){ return build(v,indent2) }).join(',\n')+'\n'+(opts.indentLast?indent2:indent)+']';
}
}else if (o instanceof Object){
var sortedKV=[],i=0;
var sort = opts.sort || opts.sorted;
for (var k in o){
var kv = sortedKV[i++] = [k,o[k]];
if (sort===true) kv[2] = k;
else if (typeof sort==='function') kv[2]=sort(k,o[k],o);
}
if (!sortedKV.length) return indent+'{}';
if (sort) sortedKV = sortedKV.sort(function(a,b){ a=a[2]; b=b[2]; return a<b?-1:a>b?1:0 });
var keyvals=sortedKV.map(function(kv){ return [JSON.stringify(kv[0]), build(kv[1],'')] });
if (opts.sorted) keyvals = keyvals.sort(function(kv1,kv2){ kv1=kv1[0]; kv2=kv2[0]; return kv1<kv2?-1:kv1>kv2?1:0 });
keyvals = keyvals.map(function(kv){ return kv.join(colon1) }).join(comma);
var oneLine = indent+"{"+opad+keyvals+opad+"}";
if (opts.wrap===false || oneLine.length<opts.wrap) return oneLine;
if (opts.short){
keyvals = sortedKV.map(function(kv){ return [indent+' '+opad+JSON.stringify(kv[0]), kv[1]] });
keyvals[0][0] = keyvals[0][0].replace(indent+' ',indent+'{');
if (opts.aligned){
var longest = 0;
for (var i=keyvals.length;i--;) if (keyvals[i][0].length>longest) longest = keyvals[i][0].length;
var padding = repeat(' ',longest);
for (var i=keyvals.length;i--;) keyvals[i][0] = padRight(padding,keyvals[i][0]);
}
for (var i=keyvals.length;i--;){
var k=keyvals[i][0], v=keyvals[i][1];
var indent2 = repeat(' ',(k+colonN).length);
var oneLine = k+colonN+build(v,'');
keyvals[i] = (opts.wrap===false || oneLine.length<=opts.wrap || !v || typeof v!="object") ? oneLine : (k+colonN+build(v,indent2).replace(/^\s+/,''));
}
return keyvals.join(',\n') + opad + '}';
}else{
var keyvals=[],i=0;
for (var k in o) keyvals[i++] = [indent+opts.indent+JSON.stringify(k),o[k]];
if (opts.sorted) keyvals = keyvals.sort(function(kv1,kv2){ kv1=kv1[0]; kv2=kv2[0]; return kv1<kv2?-1:kv1>kv2?1:0 });
if (opts.aligned){
var longest = 0;
for (var i=keyvals.length;i--;) if (keyvals[i][0].length>longest) longest = keyvals[i][0].length;
var padding = repeat(' ',longest);
for (var i=keyvals.length;i--;) keyvals[i][0] = padRight(padding,keyvals[i][0]);
}
var indent2 = indent+opts.indent;
for (var i=keyvals.length;i--;){
var k=keyvals[i][0], v=keyvals[i][1];
var oneLine = k+colonN+build(v,'');
keyvals[i] = (opts.wrap===false || oneLine.length<=opts.wrap || !v || typeof v!="object") ? oneLine : (k+colonN+build(v,indent2).replace(/^\s+/,''));
}
return indent+'{\n'+keyvals.join(',\n')+'\n'+(opts.indentLast?indent2:indent)+'}'
}
}else{
return indent+JSON.stringify(o);
}
}
}
function repeat(str,times){ // http://stackoverflow.com/a/17800645/405017
var result = '';
while(true){
if (times & 1) result += str;
times >>= 1;
if (times) str += str;
else break;
}
return result;
}
function padRight(pad, str){
return (str + pad).substring(0, pad.length);
}
}
neatJSON.version = "0.8.1";
})(typeof exports === 'undefined' ? this : exports);
| Do not jsonify strings when printing
So that multiline content gets printed to multiple lines
| vendor/neat-json/index.js | Do not jsonify strings when printing | <ide><path>endor/neat-json/index.js
<ide> }
<ide> return indent+'{\n'+keyvals.join(',\n')+'\n'+(opts.indentLast?indent2:indent)+'}'
<ide> }
<add> }else if (typeof o === 'string'){
<add> return indent+'\"'+o+'\"';
<ide> }else{
<ide> return indent+JSON.stringify(o);
<ide> } |
|
Java | mit | 0d3edab32629fd72f76914570e22a1044dbe2289 | 0 | mrm1st3r/fh-newsboard,mrm1st3r/fh-newsboard | package de.fhbielefeld.newsboard.model.access;
import de.fhbielefeld.newsboard.model.ValueObject;
/**
* An Access Role grants access to specific parts of the application.
*/
public class AccessRole implements ValueObject {
private final String role;
public AccessRole(String role) {
this.role = role;
}
public String getRole() {
return role;
}
}
| src/main/java/de/fhbielefeld/newsboard/model/access/AccessRole.java | package de.fhbielefeld.newsboard.model.access;
import de.fhbielefeld.newsboard.model.Entity;
/**
* An Access Role grants access to specific parts of the application.
*/
public class AccessRole implements Entity<Access> {
private final String role;
public AccessRole(String role) {
this.role = role;
}
public String getRole() {
return role;
}
}
| changed AccessRole to be a ValueObject
| src/main/java/de/fhbielefeld/newsboard/model/access/AccessRole.java | changed AccessRole to be a ValueObject | <ide><path>rc/main/java/de/fhbielefeld/newsboard/model/access/AccessRole.java
<ide> package de.fhbielefeld.newsboard.model.access;
<ide>
<del>import de.fhbielefeld.newsboard.model.Entity;
<add>import de.fhbielefeld.newsboard.model.ValueObject;
<ide>
<ide> /**
<ide> * An Access Role grants access to specific parts of the application.
<ide> */
<del>public class AccessRole implements Entity<Access> {
<add>public class AccessRole implements ValueObject {
<ide>
<ide> private final String role;
<ide> |
|
JavaScript | mpl-2.0 | d949a90022fb94ae93b7238a903d6cbbcb20f41d | 0 | ctagroup/home-app,ctagroup/home-app,ctagroup/home-app | import './hmisProfile.js';
import './usersCreateView.html';
Template.usersCreateView.events(
{
'submit #create-user': (evt, tmpl) => {
evt.preventDefault();
// TODO: create new users
console.log(tmpl);
/*
$(tmpl.find('.errors')).html('');
const firstName = tmpl.find('.fName').value.trim();
const middleName = tmpl.find('.mName').value.trim();
const lastName = tmpl.find('.lName').value.trim();
const emailAddress = tmpl.find('.email').value.toLowerCase();
const username = emailAddress;
const password = tmpl.find('.password').value;
const confirmPassword = password;
// const projectGroupId = tmpl.find('.projectGroup').value;
const roleIds = $(tmpl.find('.role')).val();
const userProfileId = tmpl.find('.userProfile').value;
// const projectGroup = projectGroups.findOne({ projectGroupId });
const roles = hmisRoles.find({ id: { $in: roleIds } }).fetch();
const profile = userProfiles.findOne({ id: userProfileId });
const errors = [];
if (password.length < 8 || password.length > 16) {
errors.push('Password length should be between 8 & 16.');
}
if (password.search(/[a-z]/) < 0) {
errors.push('Password should contain at least one lowercase character.');
}
if (password.search(/[A-Z]/) < 0) {
errors.push('Password should contain at least one uppercase character.');
}
if (password.search(/[0-9]/) < 0) {
errors.push('Password should contain at least one number.');
}
if (password.search(/[!@#$*"]/) < 0) {
errors.push('Password should contain at least one special character from [! @ # $ * "].');
}
if (errors.length > 0) {
const separator = '</p><p class="alert alert-danger">';
const errorsHtml = `<p class="alert alert-danger">${errors.join(separator)}</p>`;
$(tmpl.find('.errors')).html(errorsHtml);
} else {
const userObj = {
username,
emailAddress,
password,
confirmPassword,
firstName,
middleName,
lastName,
// projectGroup,
roles,
profile,
};
Meteor.call('createHMISUser', userObj, (error, result) => {
if (error) {
logger.info(error);
} else {
logger.info(result);
if (!result) {
const message = 'User could not be created. There was an error in HMIS system.';
const errorsHtml = `<p class="alert alert-danger">${message}</p>`;
$(tmpl.find('.errors')).html(errorsHtml);
} else {
Router.go('/users');
}
}
});
}
*/
},
}
);
| imports/ui/users/usersCreateView.js | import { logger } from '/imports/utils/logger';
import './hmisProfile.js';
import './usersCreateView.html';
Template.usersCreateView.events(
{
'submit #create-user': (evt, tmpl) => {
evt.preventDefault();
$(tmpl.find('.errors')).html('');
const firstName = tmpl.find('.fName').value.trim();
const middleName = tmpl.find('.mName').value.trim();
const lastName = tmpl.find('.lName').value.trim();
const emailAddress = tmpl.find('.email').value.toLowerCase();
const username = emailAddress;
const password = tmpl.find('.password').value;
const confirmPassword = password;
// const projectGroupId = tmpl.find('.projectGroup').value;
const roleIds = $(tmpl.find('.role')).val();
const userProfileId = tmpl.find('.userProfile').value;
// const projectGroup = projectGroups.findOne({ projectGroupId });
const roles = hmisRoles.find({ id: { $in: roleIds } }).fetch();
const profile = userProfiles.findOne({ id: userProfileId });
const errors = [];
if (password.length < 8 || password.length > 16) {
errors.push('Password length should be between 8 & 16.');
}
if (password.search(/[a-z]/) < 0) {
errors.push('Password should contain at least one lowercase character.');
}
if (password.search(/[A-Z]/) < 0) {
errors.push('Password should contain at least one uppercase character.');
}
if (password.search(/[0-9]/) < 0) {
errors.push('Password should contain at least one number.');
}
if (password.search(/[!@#$*"]/) < 0) {
errors.push('Password should contain at least one special character from [! @ # $ * "].');
}
if (errors.length > 0) {
const separator = '</p><p class="alert alert-danger">';
const errorsHtml = `<p class="alert alert-danger">${errors.join(separator)}</p>`;
$(tmpl.find('.errors')).html(errorsHtml);
} else {
const userObj = {
username,
emailAddress,
password,
confirmPassword,
firstName,
middleName,
lastName,
// projectGroup,
roles,
profile,
};
Meteor.call('createHMISUser', userObj, (error, result) => {
if (error) {
logger.info(error);
} else {
logger.info(result);
if (!result) {
const message = 'User could not be created. There was an error in HMIS system.';
const errorsHtml = `<p class="alert alert-danger">${message}</p>`;
$(tmpl.find('.errors')).html(errorsHtml);
} else {
Router.go('/users');
}
}
});
}
},
}
);
| fix linting errors
| imports/ui/users/usersCreateView.js | fix linting errors | <ide><path>mports/ui/users/usersCreateView.js
<del>import { logger } from '/imports/utils/logger';
<ide> import './hmisProfile.js';
<ide> import './usersCreateView.html';
<ide>
<ide> {
<ide> 'submit #create-user': (evt, tmpl) => {
<ide> evt.preventDefault();
<add> // TODO: create new users
<add> console.log(tmpl);
<add> /*
<ide>
<ide> $(tmpl.find('.errors')).html('');
<ide>
<ide> }
<ide> });
<ide> }
<add> */
<ide> },
<ide> }
<ide> ); |
|
Java | mit | aa61972994c8c7c45c2a38ac77fff2d44b45abe4 | 0 | douggie/XChange | package org.knowm.xchange.dto.marketdata;
import java.math.BigDecimal;
import java.util.Date;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.utils.DateUtils;
/**
* <p>
* A class encapsulating the information a "Ticker" can contain. Some fields can be empty if not provided by the exchange.
* </p>
* <p>
* A ticker contains data representing the latest trade.
* </p>
*/
public final class Ticker {
private final CurrencyPair currencyPair;
private final BigDecimal open;
private final BigDecimal last;
private final BigDecimal bid;
private final BigDecimal ask;
private final BigDecimal high;
private final BigDecimal low;
private final BigDecimal vwap;
private final BigDecimal volume;
/**
* the timestamp of the ticker according to the exchange's server, null if not provided
*/
private final Date timestamp;
/**
* Constructor
*
* @param currencyPair The tradable identifier (e.g. BTC in BTC/USD)
* @param last Last price
* @param bid Bid price
* @param ask Ask price
* @param high High price
* @param low Low price
* @param vwap Volume Weighted Average Price
* @param volume 24h volume
* @param timestamp - the timestamp of the ticker according to the exchange's server, null if not provided
*/
private Ticker(CurrencyPair currencyPair, BigDecimal open, BigDecimal last, BigDecimal bid, BigDecimal ask, BigDecimal high, BigDecimal low, BigDecimal vwap,
BigDecimal volume, Date timestamp) {
this.open = open;
this.currencyPair = currencyPair;
this.last = last;
this.bid = bid;
this.ask = ask;
this.high = high;
this.low = low;
this.vwap = vwap;
this.volume = volume;
this.timestamp = timestamp;
}
public CurrencyPair getCurrencyPair() {
return currencyPair;
}
public BigDecimal getOpen() {
return open;
}
public BigDecimal getLast() {
return last;
}
public BigDecimal getBid() {
return bid;
}
public BigDecimal getAsk() {
return ask;
}
public BigDecimal getHigh() {
return high;
}
public BigDecimal getLow() {
return low;
}
public BigDecimal getVwap() {
return vwap;
}
public BigDecimal getVolume() {
return volume;
}
public Date getTimestamp() {
return timestamp;
}
@Override
public String toString() {
return "Ticker [currencyPair=" + currencyPair + ", open=" + open + ", last=" + last + ", bid=" + bid + ", ask=" + ask + ", high=" + high + ", low=" + low + ",avg="
+ vwap + ", volume=" + volume + ", timestamp=" + DateUtils.toMillisNullSafe(timestamp) + "]";
}
/**
* <p>
* Builder to provide the following to {@link Ticker}:
* </p>
* <ul>
* <li>Provision of fluent chained construction interface</li>
* </ul>
*
*/
public static class Builder {
private CurrencyPair currencyPair;
private BigDecimal open;
private BigDecimal last;
private BigDecimal bid;
private BigDecimal ask;
private BigDecimal high;
private BigDecimal low;
private BigDecimal vwap;
private BigDecimal volume;
private Date timestamp;
// Prevent repeat builds
private boolean isBuilt = false;
public Ticker build() {
validateState();
Ticker ticker = new Ticker(currencyPair, open, last, bid, ask, high, low, vwap, volume, timestamp);
isBuilt = true;
return ticker;
}
private void validateState() {
if (isBuilt) {
throw new IllegalStateException("The entity has been built");
}
}
public Builder currencyPair(CurrencyPair currencyPair) {
this.currencyPair = currencyPair;
return this;
}
public Builder open(BigDecimal open) {
this.open = open;
return this;
}
public Builder last(BigDecimal last) {
this.last = last;
return this;
}
public Builder bid(BigDecimal bid) {
this.bid = bid;
return this;
}
public Builder ask(BigDecimal ask) {
this.ask = ask;
return this;
}
public Builder high(BigDecimal high) {
this.high = high;
return this;
}
public Builder low(BigDecimal low) {
this.low = low;
return this;
}
public Builder vwap(BigDecimal vwap) {
this.vwap = vwap;
return this;
}
public Builder volume(BigDecimal volume) {
this.volume = volume;
return this;
}
public Builder timestamp(Date timestamp) {
this.timestamp = timestamp;
return this;
}
}
} | xchange-core/src/main/java/org/knowm/xchange/dto/marketdata/Ticker.java | package org.knowm.xchange.dto.marketdata;
import java.math.BigDecimal;
import java.util.Date;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.utils.DateUtils;
/**
* <p>
* A class encapsulating the information a "Ticker" can contain. Some fields can be empty if not provided by the exchange.
* </p>
* <p>
* A ticker contains data representing the latest trade.
* </p>
*/
public final class Ticker {
private final CurrencyPair currencyPair;
private final BigDecimal last;
private final BigDecimal bid;
private final BigDecimal ask;
private final BigDecimal high;
private final BigDecimal low;
private final BigDecimal vwap;
private final BigDecimal volume;
/**
* the timestamp of the ticker according to the exchange's server, null if not provided
*/
private final Date timestamp;
/**
* Constructor
*
* @param currencyPair The tradable identifier (e.g. BTC in BTC/USD)
* @param last Last price
* @param bid Bid price
* @param ask Ask price
* @param high High price
* @param low Low price
* @param vwap Volume Weighted Average Price
* @param volume 24h volume
* @param timestamp - the timestamp of the ticker according to the exchange's server, null if not provided
*/
private Ticker(CurrencyPair currencyPair, BigDecimal last, BigDecimal bid, BigDecimal ask, BigDecimal high, BigDecimal low, BigDecimal vwap,
BigDecimal volume, Date timestamp) {
this.currencyPair = currencyPair;
this.last = last;
this.bid = bid;
this.ask = ask;
this.high = high;
this.low = low;
this.vwap = vwap;
this.volume = volume;
this.timestamp = timestamp;
}
public CurrencyPair getCurrencyPair() {
return currencyPair;
}
public BigDecimal getLast() {
return last;
}
public BigDecimal getBid() {
return bid;
}
public BigDecimal getAsk() {
return ask;
}
public BigDecimal getHigh() {
return high;
}
public BigDecimal getLow() {
return low;
}
public BigDecimal getVwap() {
return vwap;
}
public BigDecimal getVolume() {
return volume;
}
public Date getTimestamp() {
return timestamp;
}
@Override
public String toString() {
return "Ticker [currencyPair=" + currencyPair + ", last=" + last + ", bid=" + bid + ", ask=" + ask + ", high=" + high + ", low=" + low + ",avg="
+ vwap + ", volume=" + volume + ", timestamp=" + DateUtils.toMillisNullSafe(timestamp) + "]";
}
/**
* <p>
* Builder to provide the following to {@link Ticker}:
* </p>
* <ul>
* <li>Provision of fluent chained construction interface</li>
* </ul>
*
*/
public static class Builder {
private CurrencyPair currencyPair;
private BigDecimal last;
private BigDecimal bid;
private BigDecimal ask;
private BigDecimal high;
private BigDecimal low;
private BigDecimal vwap;
private BigDecimal volume;
private Date timestamp;
// Prevent repeat builds
private boolean isBuilt = false;
public Ticker build() {
validateState();
Ticker ticker = new Ticker(currencyPair, last, bid, ask, high, low, vwap, volume, timestamp);
isBuilt = true;
return ticker;
}
private void validateState() {
if (isBuilt) {
throw new IllegalStateException("The entity has been built");
}
}
public Builder currencyPair(CurrencyPair currencyPair) {
this.currencyPair = currencyPair;
return this;
}
public Builder last(BigDecimal last) {
this.last = last;
return this;
}
public Builder bid(BigDecimal bid) {
this.bid = bid;
return this;
}
public Builder ask(BigDecimal ask) {
this.ask = ask;
return this;
}
public Builder high(BigDecimal high) {
this.high = high;
return this;
}
public Builder low(BigDecimal low) {
this.low = low;
return this;
}
public Builder vwap(BigDecimal vwap) {
this.vwap = vwap;
return this;
}
public Builder volume(BigDecimal volume) {
this.volume = volume;
return this;
}
public Builder timestamp(Date timestamp) {
this.timestamp = timestamp;
return this;
}
}
} | Add 'open' field to 'Ticker'
| xchange-core/src/main/java/org/knowm/xchange/dto/marketdata/Ticker.java | Add 'open' field to 'Ticker' | <ide><path>change-core/src/main/java/org/knowm/xchange/dto/marketdata/Ticker.java
<ide> public final class Ticker {
<ide>
<ide> private final CurrencyPair currencyPair;
<add> private final BigDecimal open;
<ide> private final BigDecimal last;
<ide> private final BigDecimal bid;
<ide> private final BigDecimal ask;
<ide> * @param volume 24h volume
<ide> * @param timestamp - the timestamp of the ticker according to the exchange's server, null if not provided
<ide> */
<del> private Ticker(CurrencyPair currencyPair, BigDecimal last, BigDecimal bid, BigDecimal ask, BigDecimal high, BigDecimal low, BigDecimal vwap,
<add> private Ticker(CurrencyPair currencyPair, BigDecimal open, BigDecimal last, BigDecimal bid, BigDecimal ask, BigDecimal high, BigDecimal low, BigDecimal vwap,
<ide> BigDecimal volume, Date timestamp) {
<del>
<add> this.open = open;
<ide> this.currencyPair = currencyPair;
<ide> this.last = last;
<ide> this.bid = bid;
<ide> return currencyPair;
<ide> }
<ide>
<add> public BigDecimal getOpen() {
<add>
<add> return open;
<add> }
<add>
<ide> public BigDecimal getLast() {
<ide>
<ide> return last;
<ide> @Override
<ide> public String toString() {
<ide>
<del> return "Ticker [currencyPair=" + currencyPair + ", last=" + last + ", bid=" + bid + ", ask=" + ask + ", high=" + high + ", low=" + low + ",avg="
<add> return "Ticker [currencyPair=" + currencyPair + ", open=" + open + ", last=" + last + ", bid=" + bid + ", ask=" + ask + ", high=" + high + ", low=" + low + ",avg="
<ide> + vwap + ", volume=" + volume + ", timestamp=" + DateUtils.toMillisNullSafe(timestamp) + "]";
<ide> }
<ide>
<ide> public static class Builder {
<ide>
<ide> private CurrencyPair currencyPair;
<add> private BigDecimal open;
<ide> private BigDecimal last;
<ide> private BigDecimal bid;
<ide> private BigDecimal ask;
<ide>
<ide> validateState();
<ide>
<del> Ticker ticker = new Ticker(currencyPair, last, bid, ask, high, low, vwap, volume, timestamp);
<add> Ticker ticker = new Ticker(currencyPair, open, last, bid, ask, high, low, vwap, volume, timestamp);
<ide>
<ide> isBuilt = true;
<ide>
<ide> return this;
<ide> }
<ide>
<add> public Builder open(BigDecimal open) {
<add>
<add> this.open = open;
<add> return this;
<add> }
<add>
<ide> public Builder last(BigDecimal last) {
<ide>
<ide> this.last = last; |
|
Java | lgpl-2.1 | 17b4642c02be64e4c1a3fdc5d6b3e1be1b02de2f | 0 | jolie/jolie,jolie/jolie,jolie/jolie | /*
* Copyright (C) 2015 by Fabrizio Montesi <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package com.damnhandy.uri.template;
import java.util.regex.Pattern;
public class UriTemplateMatcherFactory {
public static Pattern getReverseMatchPattern( UriTemplate t ) {
return t.getReverseMatchPattern();
}
}
| lib/jolie-uri/src/main/java/com/damnhandy/uri/template/UriTemplateMatcherFactory.java | package com.damnhandy.uri.template;
import java.util.regex.Pattern;
public class UriTemplateMatcherFactory {
public static Pattern getReverseMatchPattern( UriTemplate t ) {
return t.getReverseMatchPattern();
}
}
| missing license header
| lib/jolie-uri/src/main/java/com/damnhandy/uri/template/UriTemplateMatcherFactory.java | missing license header | <ide><path>ib/jolie-uri/src/main/java/com/damnhandy/uri/template/UriTemplateMatcherFactory.java
<add>/*
<add> * Copyright (C) 2015 by Fabrizio Montesi <[email protected]>
<add> *
<add> * This library is free software; you can redistribute it and/or
<add> * modify it under the terms of the GNU Lesser General Public
<add> * License as published by the Free Software Foundation; either
<add> * version 2.1 of the License, or (at your option) any later version.
<add>
<add> * This library is distributed in the hope that it will be useful,
<add> * but WITHOUT ANY WARRANTY; without even the implied warranty of
<add> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
<add> * Lesser General Public License for more details.
<add>
<add> * You should have received a copy of the GNU Lesser General Public
<add> * License along with this library; if not, write to the Free Software
<add> * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
<add> * USA
<add> */
<add>
<ide> package com.damnhandy.uri.template;
<del>
<del>
<ide>
<ide> import java.util.regex.Pattern;
<ide> |
|
Java | apache-2.0 | error: pathspec 'src/main/java/com/bonsaimanager/backend/domain/Privilege.java' did not match any file(s) known to git
| c833eb9a9c70f64c3f6a9fe210a384830b21833d | 1 | KienKede/bonsai-manager-REST,KienKede/bonsai-manager-REST | package com.bonsaimanager.backend.domain;
public class Privilege {
}
| src/main/java/com/bonsaimanager/backend/domain/Privilege.java | Added Privilege to Domain
| src/main/java/com/bonsaimanager/backend/domain/Privilege.java | Added Privilege to Domain | <ide><path>rc/main/java/com/bonsaimanager/backend/domain/Privilege.java
<add>package com.bonsaimanager.backend.domain;
<add>
<add>public class Privilege {
<add>
<add>} |
|
JavaScript | apache-2.0 | 08f4da0142060ae903f7214d918cfca2c48394cd | 0 | BrowserSync/browser-sync,BrowserSync/browser-sync,BrowserSync/browser-sync,BrowserSync/browser-sync | "use strict";
/**
* @module BrowserSync.options
*/
module.exports = {
/**
* Browsersync includes a user-interface that is accessed via a separate port.
* The UI allows to controls all devices, push sync updates and much more.
* @property ui
* @type Object
* @param {Number} [port=3001]
* @param {Number} [weinre.port=8080]
* @since 2.0.0
* @default false
*/
ui: {
port: 3001,
weinre: {
port: 8080
}
},
/**
* Browsersync can watch your files as you work. Changes you make will either
* be injected into the page (CSS & images) or will cause all browsers to do
* a full-page refresh.
* @property files
* @type Array|String
* @default false
*/
files: false,
/**
* Specify which file events to respond to.
* Available events: `add`, `change`, `unlink`, `addDir`, `unlinkDir`
* @property watchEvents
* @type Array
* @default ["change"]
* @since 2.18.8
*/
watchEvents: ["change"],
/**
* File watching options that get passed along to [Chokidar](https://github.com/paulmillr/chokidar).
* Check their docs for available options
* @property watchOptions
* @type Object
* @default undefined
* @since 2.6.0
*/
watchOptions: {
ignoreInitial: true
/*
persistent: true,
ignored: '*.txt',
followSymlinks: true,
cwd: '.',
usePolling: true,
alwaysStat: false,
depth: undefined,
interval: 100,
ignorePermissionErrors: false,
atomic: true
*/
},
/**
* Use the built-in static server for basic HTML/JS/CSS websites.
* @property server
* @type Object|Boolean
* @default false
*/
server: false,
/**
* Proxy an EXISTING vhost. Browsersync will wrap your vhost with a proxy URL to view your site.
* @property proxy
* @type String|Object|Boolean
* @param {String} [target]
* @param {Boolean} [ws] - Enable websocket proxying
* @param {Function|Array} [middleware]
* @param {Function} [reqHeaders]
* @param {Array} [proxyReq]
* @param {Array} [proxyRes]
* @default false
*/
proxy: false,
/**
* @property port
* @type Number
* @default 3000
*/
port: 3000,
/**
* @property middleware
* @type Function|Array
* @default false
*/
middleware: false,
/**
* Add additional directories from which static
* files should be served. Should only be used in `proxy` or `snippet`
* mode.
* @property serveStatic
* @type Array
* @default []
* @since 2.8.0
*/
serveStatic: [],
/**
* Options that are passed to the serve-static middleware
* when you use the string[] syntax: eg: `serveStatic: ['./app']`. Please see
* [serve-static](https://github.com/expressjs/serve-static) for details
*
* @property serveStaticOptions
* @type Object
* @since 2.17.0
*/
/**
* Enable https for localhost development. **Note** - this is not needed for proxy
* option as it will be inferred from your target url.
* @property https
* @type Boolean
* @default undefined
* @since 1.3.0
*/
/**
* Override http module to allow using 3rd party server modules (such as http2)
* @property httpModule
* @type string
* @default undefined
* @since 2.18.0
*/
/**
* Clicks, Scrolls & Form inputs on any device will be mirrored to all others.
* @property ghostMode
* @param {Boolean} [clicks=true]
* @param {Boolean} [scroll=true]
* @param {Boolean} [location=true]
* @param {Boolean} [forms=true]
* @param {Boolean} [forms.submit=true]
* @param {Boolean} [forms.inputs=true]
* @param {Boolean} [forms.toggles=true]
* @type Object
*/
ghostMode: {
clicks: true,
scroll: true,
location: true,
forms: {
submit: true,
inputs: true,
toggles: true
}
},
/**
* Can be either "info", "debug", "warn", or "silent"
* @property logLevel
* @type String
* @default info
*/
logLevel: "info",
/**
* Change the console logging prefix. Useful if you're creating your
* own project based on Browsersync
* @property logPrefix
* @type String
* @default Browsersync
* @since 1.5.1
*/
logPrefix: "Browsersync",
/**
* @property logConnections
* @type Boolean
* @default false
*/
logConnections: false,
/**
* @property logFileChanges
* @type Boolean
* @default true
*/
logFileChanges: true,
/**
* Log the snippet to the console when you're in snippet mode (no proxy/server)
* @property logSnippet
* @type: Boolean
* @default true
* @since 1.5.2
*/
logSnippet: true,
/**
* You can control how the snippet is injected
* onto each page via a custom regex + function.
* You can also provide patterns for certain urls
* that should be ignored from the snippet injection.
* @property snippetOptions
* @since 2.0.0
* @param {Boolean} [async] - should the script tags have the async attribute?
* @param {Array} [blacklist]
* @param {Array} [whitelist]
* @param {RegExp} [rule.match=/$/]
* @param {Function} [rule.fn=Function]
* @type Object
*/
snippetOptions: {
async: true,
whitelist: [],
blacklist: [],
rule: {
match: /<body[^>]*>/i,
fn: function (snippet, match) {
return match + snippet;
}
}
},
/**
* Add additional HTML rewriting rules.
* @property rewriteRules
* @since 2.4.0
* @type Array
* @default false
*/
rewriteRules: [],
/**
* @property tunnel
* @type String|Boolean
* @default null
*/
/**
* Some features of Browsersync (such as `xip` & `tunnel`) require an internet connection, but if you're
* working offline, you can reduce start-up time by setting this option to `false`
* @property online
* @type Boolean
* @default undefined
*/
/**
* Decide which URL to open automatically when Browsersync starts. Defaults to "local" if none set.
* Can be `true`, `local`, `external`, `ui`, `ui-external`, `tunnel` or `false`
* @property open
* @type Boolean|String
* @default true
*/
open: "local",
/**
* @property browser
* @type String|Array
* @default default
*/
browser: "default",
/**
* Add HTTP access control (CORS) headers to assets served by Browsersync.
* @property cors
* @type boolean
* @default false
* @since 2.16.0
*/
cors: false,
/**
* Requires an internet connection - useful for services such as [Typekit](https://typekit.com/)
* as it allows you to configure domains such as `*.xip.io` in your kit settings
* @property xip
* @type Boolean
* @default false
*/
xip: false,
hostnameSuffix: false,
/**
* Reload each browser when Browsersync is restarted.
* @property reloadOnRestart
* @type Boolean
* @default false
*/
reloadOnRestart: false,
/**
* The small pop-over notifications in the browser are not always needed/wanted.
* @property notify
* @type Boolean
* @default true
*/
notify: true,
/**
* @property scrollProportionally
* @type Boolean
* @default true
*/
scrollProportionally: true,
/**
* @property scrollThrottle
* @type Number
* @default 0
*/
scrollThrottle: 0,
/**
* Decide which technique should be used to restore
* scroll position following a reload.
* Can be `window.name` or `cookie`
* @property scrollRestoreTechnique
* @type String
* @default 'window.name'
*/
scrollRestoreTechnique: "window.name",
/**
* Sync the scroll position of any element
* on the page. Add any amount of CSS selectors
* @property scrollElements
* @type Array
* @default []
* @since 2.9.0
*/
scrollElements: [],
/**
* Sync the scroll position of any element
* on the page - where any scrolled element
* will cause all others to match scroll position.
* This is helpful when a breakpoint alters which element
* is actually scrolling
* @property scrollElementMapping
* @type Array
* @default []
* @since 2.9.0
*/
scrollElementMapping: [],
/**
* Time, in milliseconds, to wait before
* instructing the browser to reload/inject following a
* file change event
* @property reloadDelay
* @type Number
* @default 0
*/
reloadDelay: 0,
/**
* Wait for a specified window of event-silence before
* sending any reload events.
* @property reloadDebounce
* @type Number
* @default 0
* @since 2.6.0
*/
reloadDebounce: 0,
/**
* Emit only the first event during sequential time windows
* of a specified duration.
* @property reloadThrottle
* @type Number
* @default 0
* @since 2.13.0
*/
reloadThrottle: 0,
/**
* User provided plugins
* @property plugins
* @type Array
* @default []
* @since 2.6.0
*/
plugins: [],
/**
* @property injectChanges
* @type Boolean
* @default true
*/
injectChanges: true,
/**
* @property startPath
* @type String|Null
* @default null
*/
startPath: null,
/**
* Whether to minify client script, or not.
* @property minify
* @type Boolean
* @default true
*/
minify: true,
/**
* @property host
* @type String
* @default null
*/
host: null,
/**
* Support environments where dynamic hostnames are not required
* (ie: electron)
* @property localOnly
* @type Boolean
* @default false
* @since 2.14.0
*/
localOnly: false,
/**
* @property codeSync
* @type Boolean
* @default true
*/
codeSync: true,
/**
* @property timestamps
* @type Boolean
* @default true
*/
timestamps: true,
clientEvents: [
"scroll",
"scroll:element",
"input:text",
"input:toggles",
"form:submit",
"form:reset",
"click"
],
/**
* Alter the script path for complete control over where the Browsersync
* Javascript is served from. Whatever you return from this function
* will be used as the script path.
* @property scriptPath
* @default undefined
* @since 1.5.0
* @type Function
*/
/**
* Configure the Socket.IO path and namespace & domain to avoid collisions.
* @property socket
* @param {String} [path="/browser-sync/socket.io"]
* @param {String} [clientPath="/browser-sync"]
* @param {String|Function} [namespace="/browser-sync"]
* @param {String|Function} [domain=undefined]
* @param {String|Function} [port=undefined]
* @param {Object} [clients.heartbeatTimeout=5000]
* @since 1.6.2
* @type Object
*/
socket: {
socketIoOptions: {
log: false
},
socketIoClientConfig: {
reconnectionAttempts: 50
},
path: "/browser-sync/socket.io",
clientPath: "/browser-sync",
namespace: "/browser-sync",
clients: {
heartbeatTimeout: 5000
}
},
/**
* Configure the script domain
* @property script
* @param {String|Function} [domain=undefined]
* @since 2.14.0
* @type Object
*/
tagNames: {
"less": "link",
"scss": "link",
"css": "link",
"jpg": "img",
"jpeg": "img",
"png": "img",
"svg": "img",
"gif": "img",
"js": "script"
},
injectFileTypes: ["css", "png", "jpg", "jpeg", "svg", "gif", "webp", "map"],
excludedFileTypes: [
"js",
"css",
"pdf",
"map",
"svg",
"ico",
"woff",
"json",
"eot",
"ttf",
"png",
"jpg",
"jpeg",
"webp",
"gif",
"mp4",
"mp3",
"3gp",
"ogg",
"ogv",
"webm",
"m4a",
"flv",
"wmv",
"avi",
"swf",
"scss"
]
};
| lib/default-config.js | "use strict";
/**
* @module BrowserSync.options
*/
module.exports = {
/**
* Browsersync includes a user-interface that is accessed via a separate port.
* The UI allows to controls all devices, push sync updates and much more.
* @property ui
* @type Object
* @param {Number} [port=3001]
* @param {Number} [weinre.port=8080]
* @since 2.0.0
* @default false
*/
ui: {
port: 3001,
weinre: {
port: 8080
}
},
/**
* Browsersync can watch your files as you work. Changes you make will either
* be injected into the page (CSS & images) or will cause all browsers to do
* a full-page refresh.
* @property files
* @type Array|String
* @default false
*/
files: false,
/**
* Specify which file events to respond to.
* Available events: `add`, `change`, `unlink`, `addDir`, `unlinkDir`
* @property watchEvents
* @type Array
* @default ["change"]
* @since 2.18.8
*/
watchEvents: ["change"],
/**
* File watching options that get passed along to [Chokidar](https://github.com/paulmillr/chokidar).
* Check their docs for available options
* @property watchOptions
* @type Object
* @default undefined
* @since 2.6.0
*/
watchOptions: {
ignoreInitial: true
/*
persistent: true,
ignored: '*.txt',
followSymlinks: true,
cwd: '.',
usePolling: true,
alwaysStat: false,
depth: undefined,
interval: 100,
ignorePermissionErrors: false,
atomic: true
*/
},
/**
* Use the built-in static server for basic HTML/JS/CSS websites.
* @property server
* @type Object|Boolean
* @default false
*/
server: false,
/**
* Proxy an EXISTING vhost. Browsersync will wrap your vhost with a proxy URL to view your site.
* @property proxy
* @type String|Object|Boolean
* @param {String} [target]
* @param {Boolean} [ws] - Enable websocket proxying
* @param {Function|Array} [middleware]
* @param {Function} [reqHeaders]
* @param {Array} [proxyReq]
* @param {Array} [proxyRes]
* @default false
*/
proxy: false,
/**
* @property port
* @type Number
* @default 3000
*/
port: 3000,
/**
* @property middleware
* @type Function|Array
* @default false
*/
middleware: false,
/**
* Add additional directories from which static
* files should be served. Should only be used in `proxy` or `snippet`
* mode.
* @property serveStatic
* @type Array
* @default []
* @since 2.8.0
*/
serveStatic: [],
/**
* Options that are passed to the serve-static middleware
* when you use the string[] syntax: eg: `serveStatic: ['./app']`. Please see
* [serve-static](https://github.com/expressjs/serve-static) for details
*
* @property serveStaticOptions
* @type Object
* @since 2.17.0
*/
/**
* Enable https for localhost development. **Note** - this is not needed for proxy
* option as it will be inferred from your target url.
* @property https
* @type Boolean
* @default undefined
* @since 1.3.0
*/
/**
* Override http module to allow using 3rd party server modules (such as http2)
* @property httpModule
* @type string
* @default undefined
* @since 2.18.0
*/
/**
* Clicks, Scrolls & Form inputs on any device will be mirrored to all others.
* @property ghostMode
* @param {Boolean} [clicks=true]
* @param {Boolean} [scroll=true]
* @param {Boolean} [location=true]
* @param {Boolean} [forms=true]
* @param {Boolean} [forms.submit=true]
* @param {Boolean} [forms.inputs=true]
* @param {Boolean} [forms.toggles=true]
* @type Object
*/
ghostMode: {
clicks: true,
scroll: true,
location: true,
forms: {
submit: true,
inputs: true,
toggles: true
}
},
/**
* Can be either "info", "debug", "warn", or "silent"
* @property logLevel
* @type String
* @default info
*/
logLevel: "info",
/**
* Change the console logging prefix. Useful if you're creating your
* own project based on Browsersync
* @property logPrefix
* @type String
* @default BS
* @since 1.5.1
*/
logPrefix: "BS",
/**
* @property logConnections
* @type Boolean
* @default false
*/
logConnections: false,
/**
* @property logFileChanges
* @type Boolean
* @default true
*/
logFileChanges: true,
/**
* Log the snippet to the console when you're in snippet mode (no proxy/server)
* @property logSnippet
* @type: Boolean
* @default true
* @since 1.5.2
*/
logSnippet: true,
/**
* You can control how the snippet is injected
* onto each page via a custom regex + function.
* You can also provide patterns for certain urls
* that should be ignored from the snippet injection.
* @property snippetOptions
* @since 2.0.0
* @param {Boolean} [async] - should the script tags have the async attribute?
* @param {Array} [blacklist]
* @param {Array} [whitelist]
* @param {RegExp} [rule.match=/$/]
* @param {Function} [rule.fn=Function]
* @type Object
*/
snippetOptions: {
async: true,
whitelist: [],
blacklist: [],
rule: {
match: /<body[^>]*>/i,
fn: function (snippet, match) {
return match + snippet;
}
}
},
/**
* Add additional HTML rewriting rules.
* @property rewriteRules
* @since 2.4.0
* @type Array
* @default false
*/
rewriteRules: [],
/**
* @property tunnel
* @type String|Boolean
* @default null
*/
/**
* Some features of Browsersync (such as `xip` & `tunnel`) require an internet connection, but if you're
* working offline, you can reduce start-up time by setting this option to `false`
* @property online
* @type Boolean
* @default undefined
*/
/**
* Decide which URL to open automatically when Browsersync starts. Defaults to "local" if none set.
* Can be `true`, `local`, `external`, `ui`, `ui-external`, `tunnel` or `false`
* @property open
* @type Boolean|String
* @default true
*/
open: "local",
/**
* @property browser
* @type String|Array
* @default default
*/
browser: "default",
/**
* Add HTTP access control (CORS) headers to assets served by Browsersync.
* @property cors
* @type boolean
* @default false
* @since 2.16.0
*/
cors: false,
/**
* Requires an internet connection - useful for services such as [Typekit](https://typekit.com/)
* as it allows you to configure domains such as `*.xip.io` in your kit settings
* @property xip
* @type Boolean
* @default false
*/
xip: false,
hostnameSuffix: false,
/**
* Reload each browser when Browsersync is restarted.
* @property reloadOnRestart
* @type Boolean
* @default false
*/
reloadOnRestart: false,
/**
* The small pop-over notifications in the browser are not always needed/wanted.
* @property notify
* @type Boolean
* @default true
*/
notify: true,
/**
* @property scrollProportionally
* @type Boolean
* @default true
*/
scrollProportionally: true,
/**
* @property scrollThrottle
* @type Number
* @default 0
*/
scrollThrottle: 0,
/**
* Decide which technique should be used to restore
* scroll position following a reload.
* Can be `window.name` or `cookie`
* @property scrollRestoreTechnique
* @type String
* @default 'window.name'
*/
scrollRestoreTechnique: "window.name",
/**
* Sync the scroll position of any element
* on the page. Add any amount of CSS selectors
* @property scrollElements
* @type Array
* @default []
* @since 2.9.0
*/
scrollElements: [],
/**
* Sync the scroll position of any element
* on the page - where any scrolled element
* will cause all others to match scroll position.
* This is helpful when a breakpoint alters which element
* is actually scrolling
* @property scrollElementMapping
* @type Array
* @default []
* @since 2.9.0
*/
scrollElementMapping: [],
/**
* Time, in milliseconds, to wait before
* instructing the browser to reload/inject following a
* file change event
* @property reloadDelay
* @type Number
* @default 0
*/
reloadDelay: 0,
/**
* Wait for a specified window of event-silence before
* sending any reload events.
* @property reloadDebounce
* @type Number
* @default 0
* @since 2.6.0
*/
reloadDebounce: 0,
/**
* Emit only the first event during sequential time windows
* of a specified duration.
* @property reloadThrottle
* @type Number
* @default 0
* @since 2.13.0
*/
reloadThrottle: 0,
/**
* User provided plugins
* @property plugins
* @type Array
* @default []
* @since 2.6.0
*/
plugins: [],
/**
* @property injectChanges
* @type Boolean
* @default true
*/
injectChanges: true,
/**
* @property startPath
* @type String|Null
* @default null
*/
startPath: null,
/**
* Whether to minify client script, or not.
* @property minify
* @type Boolean
* @default true
*/
minify: true,
/**
* @property host
* @type String
* @default null
*/
host: null,
/**
* Support environments where dynamic hostnames are not required
* (ie: electron)
* @property localOnly
* @type Boolean
* @default false
* @since 2.14.0
*/
localOnly: false,
/**
* @property codeSync
* @type Boolean
* @default true
*/
codeSync: true,
/**
* @property timestamps
* @type Boolean
* @default true
*/
timestamps: true,
clientEvents: [
"scroll",
"scroll:element",
"input:text",
"input:toggles",
"form:submit",
"form:reset",
"click"
],
/**
* Alter the script path for complete control over where the Browsersync
* Javascript is served from. Whatever you return from this function
* will be used as the script path.
* @property scriptPath
* @default undefined
* @since 1.5.0
* @type Function
*/
/**
* Configure the Socket.IO path and namespace & domain to avoid collisions.
* @property socket
* @param {String} [path="/browser-sync/socket.io"]
* @param {String} [clientPath="/browser-sync"]
* @param {String|Function} [namespace="/browser-sync"]
* @param {String|Function} [domain=undefined]
* @param {String|Function} [port=undefined]
* @param {Object} [clients.heartbeatTimeout=5000]
* @since 1.6.2
* @type Object
*/
socket: {
socketIoOptions: {
log: false
},
socketIoClientConfig: {
reconnectionAttempts: 50
},
path: "/browser-sync/socket.io",
clientPath: "/browser-sync",
namespace: "/browser-sync",
clients: {
heartbeatTimeout: 5000
}
},
/**
* Configure the script domain
* @property script
* @param {String|Function} [domain=undefined]
* @since 2.14.0
* @type Object
*/
tagNames: {
"less": "link",
"scss": "link",
"css": "link",
"jpg": "img",
"jpeg": "img",
"png": "img",
"svg": "img",
"gif": "img",
"js": "script"
},
injectFileTypes: ["css", "png", "jpg", "jpeg", "svg", "gif", "webp", "map"],
excludedFileTypes: [
"js",
"css",
"pdf",
"map",
"svg",
"ico",
"woff",
"json",
"eot",
"ttf",
"png",
"jpg",
"jpeg",
"webp",
"gif",
"mp4",
"mp3",
"3gp",
"ogg",
"ogv",
"webm",
"m4a",
"flv",
"wmv",
"avi",
"swf",
"scss"
]
};
| Set default logPrefix to "Browsersync". Closes #1377
| lib/default-config.js | Set default logPrefix to "Browsersync". Closes #1377 | <ide><path>ib/default-config.js
<ide> * own project based on Browsersync
<ide> * @property logPrefix
<ide> * @type String
<del> * @default BS
<add> * @default Browsersync
<ide> * @since 1.5.1
<ide> */
<del> logPrefix: "BS",
<add> logPrefix: "Browsersync",
<ide>
<ide> /**
<ide> * @property logConnections |
|
Java | apache-2.0 | ebe83d69aa89c6bb913dc772b5a34321d92c061b | 0 | dannil/scb-api,dannil/scb-java-client,dannil/scb-java-client | /*
* Copyright 2014 Daniel Nilsson
*
* 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.github.dannil.scbapi.api;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.dannil.scbapi.utility.JsonUtility;
import com.github.dannil.scbapi.utility.Localization;
import com.github.dannil.scbapi.utility.QueryBuilder;
import com.github.dannil.scbapi.utility.RequestPoster;
public class AbstractAPI {
private static final Logger LOGGER = Logger.getLogger(AbstractAPI.class.getName());
protected Locale locale;
protected QueryBuilder queryBuilder;
protected Localization localization;
protected AbstractAPI() {
this.locale = Locale.getDefault();
this.queryBuilder = QueryBuilder.getInstance();
this.localization = new Localization(this.locale);
}
protected AbstractAPI(Locale locale) {
this();
this.locale = locale;
this.localization.setLanguage(this.locale);
}
public Locale getLocale() {
return this.locale;
}
public void setLocale(Locale locale) {
this.locale = locale;
this.localization.setLanguage(locale);
}
protected String getBaseUrl() {
return "http://api.scb.se/OV0104/v1/doris/" + this.locale.getLanguage() + "/ssd/";
}
// TODO Improve method
protected String get(String address) {
try {
String response = RequestPoster.doGet(getBaseUrl() + address);
return response;
} catch (FileNotFoundException e) {
// 404, call the API again with the fallback language
try {
return RequestPoster.doGet(toFallbackUrl(getBaseUrl() + address));
} catch (IOException e1) {
e1.printStackTrace();
return "UNHANDLED";
}
} catch (IOException e) {
// Handle all other cases
e.printStackTrace();
return "IOException";
}
}
// TODO Improve method
protected String post(String address, String query) {
try {
String response = RequestPoster.doPost(getBaseUrl() + address, query);
LOGGER.log(Level.INFO, query);
return response;
} catch (FileNotFoundException e) {
// 404, call the API again with the fallback language
try {
LOGGER.log(Level.INFO, query);
return RequestPoster.doPost(toFallbackUrl(getBaseUrl() + address), query);
} catch (IOException e1) {
e1.printStackTrace();
return "UNHANDLED";
}
} catch (IOException e) {
// Handle all other cases
e.printStackTrace();
return "IOException";
}
}
// TODO Maybe should be in a separate utility class?
private String toFallbackUrl(String url) {
String internalAddress = url;
// Some tables only support Swedish so we need to fall back to
// Swedish if this is the case
Locale fallback = new Locale("sv", "SE");
int start = internalAddress.indexOf(this.locale.getLanguage(), internalAddress.indexOf("doris"));
int end = start + this.locale.getLanguage().length();
StringBuilder builder = new StringBuilder(internalAddress);
builder.replace(start, end, fallback.getLanguage());
return builder.toString();
}
public List<String> getRegions(String url) {
String content = get(url);
JsonNode contentAsJsonNode = JsonUtility.getNode(content);
List<String> codes = contentAsJsonNode.findValuesAsText("code");
List<JsonNode> values = contentAsJsonNode.findValues("values");
int position = codes.indexOf("Region");
if (position < 0) {
throw new UnsupportedOperationException(
this.localization.getString("regions_is_not_supported_for_url", url));
}
JsonNode jsonRegions = values.get(position);
List<String> regions = new ArrayList<String>(jsonRegions.size());
for (int j = 0; j < jsonRegions.size(); j++) {
regions.add(jsonRegions.get(j).asText());
}
return regions;
}
protected List<String> getYears(String url) {
String content = get(url);
JsonNode contentAsJsonNode = JsonUtility.getNode(content);
List<String> codes = contentAsJsonNode.findValuesAsText("code");
List<JsonNode> values = contentAsJsonNode.findValues("values");
int position = codes.indexOf("Tid");
if (position < 0) {
throw new UnsupportedOperationException(this.localization.getString("years_is_not_supported_for_url", url));
}
JsonNode jsonYears = values.get(position);
List<String> years = new ArrayList<String>(jsonYears.size());
for (int j = 0; j < jsonYears.size(); j++) {
years.add(jsonYears.get(j).asText());
}
return years;
}
}
| src/main/java/com/github/dannil/scbapi/api/AbstractAPI.java | /*
* Copyright 2014 Daniel Nilsson
*
* 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.github.dannil.scbapi.api;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.dannil.scbapi.utility.JsonUtility;
import com.github.dannil.scbapi.utility.Localization;
import com.github.dannil.scbapi.utility.QueryBuilder;
import com.github.dannil.scbapi.utility.RequestPoster;
public class AbstractAPI {
private static final Logger LOGGER = Logger.getLogger(AbstractAPI.class.getName());
protected Locale locale;
protected QueryBuilder queryBuilder;
protected Localization localization;
protected AbstractAPI() {
this.locale = Locale.getDefault();
this.queryBuilder = QueryBuilder.getInstance();
this.localization = new Localization(locale);
}
protected AbstractAPI(Locale locale) {
this();
this.locale = locale;
this.localization.setLanguage(this.locale);
}
public Locale getLocale() {
return this.locale;
}
public void setLocale(Locale locale) {
this.locale = locale;
this.localization.setLanguage(locale);
}
protected String getBaseUrl() {
return "http://api.scb.se/OV0104/v1/doris/" + this.locale.getLanguage() + "/ssd/";
}
// TODO Improve method
protected String get(String address) {
try {
String response = RequestPoster.doGet(getBaseUrl() + address);
return response;
} catch (FileNotFoundException e) {
// 404, call the API again with the fallback language
try {
return RequestPoster.doGet(toFallbackUrl(getBaseUrl() + address));
} catch (IOException e1) {
e1.printStackTrace();
return "UNHANDLED";
}
} catch (IOException e) {
// Handle all other cases
e.printStackTrace();
return "IOException";
}
}
// TODO Improve method
protected String post(String address, String query) {
try {
String response = RequestPoster.doPost(getBaseUrl() + address, query);
LOGGER.log(Level.INFO, query);
return response;
} catch (FileNotFoundException e) {
// 404, call the API again with the fallback language
try {
LOGGER.log(Level.INFO, query);
return RequestPoster.doPost(toFallbackUrl(getBaseUrl() + address), query);
} catch (IOException e1) {
e1.printStackTrace();
return "UNHANDLED";
}
} catch (IOException e) {
// Handle all other cases
e.printStackTrace();
return "IOException";
}
}
// TODO Maybe should be in a separate utility class?
private String toFallbackUrl(String url) {
String internalAddress = url;
// Some tables only support Swedish so we need to fall back to
// Swedish if this is the case
Locale fallback = new Locale("sv", "SE");
int start = internalAddress.indexOf(this.locale.getLanguage(), internalAddress.indexOf("doris"));
int end = start + this.locale.getLanguage().length();
StringBuilder builder = new StringBuilder(internalAddress);
builder.replace(start, end, fallback.getLanguage());
return builder.toString();
}
public List<String> getRegions(String url) {
String content = get(url);
JsonNode contentAsJsonNode = JsonUtility.getNode(content);
List<String> codes = contentAsJsonNode.findValuesAsText("code");
List<JsonNode> values = contentAsJsonNode.findValues("values");
int position = codes.indexOf("Region");
if (position < 0) {
//throw new UnsupportedOperationException(Localization.getString("regions_is_not_supported_for_url", url));
}
JsonNode jsonRegions = values.get(position);
List<String> regions = new ArrayList<String>(jsonRegions.size());
for (int j = 0; j < jsonRegions.size(); j++) {
regions.add(jsonRegions.get(j).asText());
}
return regions;
}
protected List<String> getYears(String url) {
String content = get(url);
JsonNode contentAsJsonNode = JsonUtility.getNode(content);
List<String> codes = contentAsJsonNode.findValuesAsText("code");
List<JsonNode> values = contentAsJsonNode.findValues("values");
int position = codes.indexOf("Tid");
if (position < 0) {
//throw new UnsupportedOperationException(Localization.getString("years_is_not_supported_for_url", url));
}
JsonNode jsonYears = values.get(position);
List<String> years = new ArrayList<String>(jsonYears.size());
for (int j = 0; j < jsonYears.size(); j++) {
years.add(jsonYears.get(j).asText());
}
return years;
}
}
| Added back throws | src/main/java/com/github/dannil/scbapi/api/AbstractAPI.java | Added back throws | <ide><path>rc/main/java/com/github/dannil/scbapi/api/AbstractAPI.java
<ide> this.locale = Locale.getDefault();
<ide>
<ide> this.queryBuilder = QueryBuilder.getInstance();
<del> this.localization = new Localization(locale);
<add> this.localization = new Localization(this.locale);
<ide> }
<ide>
<ide> protected AbstractAPI(Locale locale) {
<ide>
<ide> int position = codes.indexOf("Region");
<ide> if (position < 0) {
<del> //throw new UnsupportedOperationException(Localization.getString("regions_is_not_supported_for_url", url));
<add> throw new UnsupportedOperationException(
<add> this.localization.getString("regions_is_not_supported_for_url", url));
<ide> }
<ide>
<ide> JsonNode jsonRegions = values.get(position);
<ide>
<ide> int position = codes.indexOf("Tid");
<ide> if (position < 0) {
<del> //throw new UnsupportedOperationException(Localization.getString("years_is_not_supported_for_url", url));
<add> throw new UnsupportedOperationException(this.localization.getString("years_is_not_supported_for_url", url));
<ide> }
<ide>
<ide> JsonNode jsonYears = values.get(position); |
|
JavaScript | mit | 243877900dfa298c99a8d5e21e64946615753dc4 | 0 | eladmeidar/failtail,mrhenry/failtale,mrhenry/failtale,eladmeidar/failtail | var currentContent ="content1";
var switching = false;
var switchContent = (function(sender){
var contentBlock = $(sender).attr("rel");
if(!switching && contentBlock!=currentContent){
switching = true;
$("ul.features a").removeClass("active");
$("#"+currentContent).fadeOut(500, function(){
$("#"+contentBlock).fadeIn(1000, function(){
switching = false;
});
});
$("a[rel='"+contentBlock+"']").addClass("active");
currentContent = contentBlock;
}
});
var validateEmail = (function(address){
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
return reg.test(address);
});
/*
* DOM Ready
*/
$(document).ready(function() {
var header = $('#header'),
footer = $('#footer'),
login = $('#login'),
subscribe = $('#subscribe');
//borrowed from jQuery easing plugin
//http://gsgd.co.uk/sandbox/jquery.easing.php
$.easing.easeOutQuad = function(x, t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
};
$(".links a", footer).mouseover(function(){
$(this).stop();
$(this).animate({ opacity: 1 }, 200);
});
$(".links a", footer).mouseout(function(){
$(this).stop();
$(this).animate({ opacity: 0.5 }, 200);
});
$('#selectAll').click(function(){
var checked = $('#selectAll').is(':checked');
$("td input[type='checkbox']").attr('checked', checked);
});
$("ul.features a,#header ul li.request a, a.toTab").each(function(){
$(this).attr("href","javascript:;");
});
$("ul.features a").click(function(){
switchContent(this);
});
$("ul li.login a", header).click(function(){
if (login.hasClass('active')) {
$(this).html("Login");
login.fadeOut(500);
login.removeClass('active');
} else {
$(this).html("Hide");
login.fadeIn(1000);
login.addClass('active');
subscribe.fadeOut(250);
subscribe.removeClass('active');
$("ul li.subscribe a", header).html("Newsletter");
}
});
$("ul li.subscribe a", header).click(function(){
if (subscribe.hasClass('active')) {
$(this).html("Newsletter");
subscribe.fadeOut(500);
subscribe.removeClass('active');
} else {
$(this).html('Hide');
subscribe.fadeIn(1000);
subscribe.addClass('active');
login.fadeOut(250);
login.removeClass('active');
$("ul li.login a", header).html("Login");
}
});
$("a.toTab").click(function(){
switchContent(this);
});
$("ul li.request a", header).click(function(){
switchContent(this);
$.scrollTo($("#container"), 1500, {easing:'easeOutQuad'});
});
$("form.emailForm").submit(function(){
var email = $("#invitation_request_email").attr("value"),
authentity = $("input[name='authenticity_token']").attr("value");
$("span.valid").hide();
$("span.invalid").hide();
if (validateEmail(email)) {
var post_data = {
"invitation_request[email]": email,
"authenticity_token": authentity };
$.post("/invitation_requests.js", post_data, function(data){
$("span.valid").html("Thank you for your request. You will receive an e-mail very soon!");
$("span.valid").attr("style","display:block;");
});
} else {
$("span.invalid").html("Please enter a valid e-mail address.");
$("span.invalid").attr("style","display:block;");
}
return false;
});
/*
* Clearfield
*/
$('.clear-field').clearField();
try {
/*
* Table sorter
*/
$("table.sortable").tablesorter({textExtraction: 'complex'});
$("table.sortable th").filter(function(idx){
if ($(this).hasClass('sortable')) {
return false;
} else {
return $(this);
}
}).unbind('click');
} catch (e) { /* ignore */ };
}); // End DOM ready
| public/javascripts/application.js | var currentContent ="content1";
var switching = false;
var switchContent = (function(sender){
var contentBlock = $(sender).attr("rel");
if(!switching && contentBlock!=currentContent){
switching = true;
$("ul.features a").removeClass("active");
$("#"+currentContent).fadeOut(500, function(){
$("#"+contentBlock).fadeIn(1000, function(){
switching = false;
});
});
$("a[rel='"+contentBlock+"']").addClass("active");
currentContent = contentBlock;
}
});
var validateEmail = (function(address){
// var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
// !(reg.test(address) == false);
return true;
});
/*
* DOM Ready
*/
$(document).ready(function() {
var header = $('#header'),
footer = $('#footer'),
login = $('#login'),
subscribe = $('#subscribe');
//borrowed from jQuery easing plugin
//http://gsgd.co.uk/sandbox/jquery.easing.php
$.easing.easeOutQuad = function(x, t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
};
$(".links a", footer).mouseover(function(){
$(this).stop();
$(this).animate({ opacity: 1 }, 200);
});
$(".links a", footer).mouseout(function(){
$(this).stop();
$(this).animate({ opacity: 0.5 }, 200);
});
$('#selectAll').click(function(){
var checked = $('#selectAll').is(':checked');
$("td input[type='checkbox']").attr('checked', checked);
});
$("ul.features a,#header ul li.request a, a.toTab").each(function(){
$(this).attr("href","javascript:;");
});
$("ul.features a").click(function(){
switchContent(this);
});
$("ul li.login a", header).click(function(){
if (login.hasClass('active')) {
$(this).html("Login");
login.fadeOut(500);
login.removeClass('active');
} else {
$(this).html("Hide");
login.fadeIn(1000);
login.addClass('active');
subscribe.fadeOut(250);
subscribe.removeClass('active');
$("ul li.subscribe a", header).html("Newsletter");
}
});
$("ul li.subscribe a", header).click(function(){
if (subscribe.hasClass('active')) {
$(this).html("Newsletter");
subscribe.fadeOut(500);
subscribe.removeClass('active');
} else {
$(this).html('Hide');
subscribe.fadeIn(1000);
subscribe.addClass('active');
login.fadeOut(250);
login.removeClass('active');
$("ul li.login a", header).html("Login");
}
});
$("a.toTab").click(function(){
switchContent(this);
});
$("ul li.request a", header).click(function(){
switchContent(this);
$.scrollTo($("#container"), 1500, {easing:'easeOutQuad'});
});
$("form.emailForm").submit(function(){
var email = $("#invitation_request_email").attr("value"),
authentity = $("input[name='authenticity_token']").attr("value");
$("span.valid").hide();
$("span.invalid").hide();
if (validateEmail(email)) {
var post_data = {
"invitation_request[email]": email,
"authenticity_token": authentity };
$.post("/invitation_requests.js", post_data, function(data){
$("span.valid").html("Thank you for your request. You will receive an e-mail very soon!");
$("span.valid").attr("style","display:block;");
});
} else {
$("span.invalid").html("Please enter a valid e-mail address.");
$("span.invalid").attr("style","display:block;");
}
return false;
});
/*
* Clearfield
*/
$('.clear-field').clearField();
/*
* Table sorter
*/
// $("table.sortable").tablesorter({textExtraction: 'complex'});
// $("table.sortable th").filter(function(idx){
// if ($(this).hasClass('sortable')) {
// return false;
// } else {
// return $(this);
// }
// }).unbind('click');
}); // End DOM ready
| Re-adding the email validation
| public/javascripts/application.js | Re-adding the email validation | <ide><path>ublic/javascripts/application.js
<ide> });
<ide>
<ide> var validateEmail = (function(address){
<del> // var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
<del> // !(reg.test(address) == false);
<del> return true;
<add> var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
<add> return reg.test(address);
<ide> });
<ide>
<ide> /*
<ide> $('.clear-field').clearField();
<ide>
<ide>
<del> /*
<del> * Table sorter
<del> */
<del> // $("table.sortable").tablesorter({textExtraction: 'complex'});
<del> // $("table.sortable th").filter(function(idx){
<del> // if ($(this).hasClass('sortable')) {
<del> // return false;
<del> // } else {
<del> // return $(this);
<del> // }
<del> // }).unbind('click');
<del>
<add> try {
<add> /*
<add> * Table sorter
<add> */
<add> $("table.sortable").tablesorter({textExtraction: 'complex'});
<add> $("table.sortable th").filter(function(idx){
<add> if ($(this).hasClass('sortable')) {
<add> return false;
<add> } else {
<add> return $(this);
<add> }
<add> }).unbind('click');
<add> } catch (e) { /* ignore */ };
<add>
<ide> }); // End DOM ready |
|
Java | apache-2.0 | 69bba0b8b3bee3bde0641d6f5e31ddccfd53a83a | 0 | Deftwun/libgdx,collinsmith/libgdx,309746069/libgdx,djom20/libgdx,toloudis/libgdx,Zonglin-Li6565/libgdx,bsmr-java/libgdx,js78/libgdx,stinsonga/libgdx,fwolff/libgdx,MathieuDuponchelle/gdx,xoppa/libgdx,jsjolund/libgdx,BlueRiverInteractive/libgdx,hyvas/libgdx,stickyd/libgdx,Badazdz/libgdx,saqsun/libgdx,Arcnor/libgdx,copystudy/libgdx,yangweigbh/libgdx,kagehak/libgdx,srwonka/libGdx,collinsmith/libgdx,bsmr-java/libgdx,djom20/libgdx,haedri/libgdx-1,snovak/libgdx,Wisienkas/libgdx,curtiszimmerman/libgdx,MadcowD/libgdx,shiweihappy/libgdx,309746069/libgdx,MovingBlocks/libgdx,Heart2009/libgdx,samskivert/libgdx,fiesensee/libgdx,fiesensee/libgdx,MovingBlocks/libgdx,flaiker/libgdx,nelsonsilva/libgdx,tell10glu/libgdx,nooone/libgdx,xranby/libgdx,billgame/libgdx,JFixby/libgdx,ThiagoGarciaAlves/libgdx,curtiszimmerman/libgdx,xoppa/libgdx,petugez/libgdx,tell10glu/libgdx,fiesensee/libgdx,yangweigbh/libgdx,fwolff/libgdx,realitix/libgdx,junkdog/libgdx,zhimaijoy/libgdx,thepullman/libgdx,anserran/libgdx,Xhanim/libgdx,Wisienkas/libgdx,basherone/libgdxcn,BlueRiverInteractive/libgdx,jberberick/libgdx,yangweigbh/libgdx,davebaol/libgdx,jsjolund/libgdx,designcrumble/libgdx,davebaol/libgdx,titovmaxim/libgdx,yangweigbh/libgdx,tell10glu/libgdx,libgdx/libgdx,cypherdare/libgdx,designcrumble/libgdx,saqsun/libgdx,Thotep/libgdx,MikkelTAndersen/libgdx,tommycli/libgdx,Deftwun/libgdx,designcrumble/libgdx,MadcowD/libgdx,kzganesan/libgdx,nudelchef/libgdx,Badazdz/libgdx,js78/libgdx,alireza-hosseini/libgdx,NathanSweet/libgdx,GreenLightning/libgdx,tommycli/libgdx,JFixby/libgdx,xoppa/libgdx,1yvT0s/libgdx,KrisLee/libgdx,Gliby/libgdx,fiesensee/libgdx,nelsonsilva/libgdx,designcrumble/libgdx,yangweigbh/libgdx,czyzby/libgdx,billgame/libgdx,bgroenks96/libgdx,MadcowD/libgdx,djom20/libgdx,firefly2442/libgdx,Heart2009/libgdx,FredGithub/libgdx,EsikAntony/libgdx,Deftwun/libgdx,katiepino/libgdx,titovmaxim/libgdx,samskivert/libgdx,sinistersnare/libgdx,zhimaijoy/libgdx,FredGithub/libgdx,kotcrab/libgdx,sarkanyi/libgdx,hyvas/libgdx,MathieuDuponchelle/gdx,PedroRomanoBarbosa/libgdx,junkdog/libgdx,Wisienkas/libgdx,jasonwee/libgdx,Heart2009/libgdx,toa5/libgdx,flaiker/libgdx,saltares/libgdx,haedri/libgdx-1,djom20/libgdx,basherone/libgdxcn,nave966/libgdx,saltares/libgdx,petugez/libgdx,fiesensee/libgdx,bgroenks96/libgdx,gf11speed/libgdx,MadcowD/libgdx,stickyd/libgdx,hyvas/libgdx,youprofit/libgdx,kotcrab/libgdx,ninoalma/libgdx,sarkanyi/libgdx,saqsun/libgdx,JFixby/libgdx,ya7lelkom/libgdx,fwolff/libgdx,bsmr-java/libgdx,titovmaxim/libgdx,tommyettinger/libgdx,xranby/libgdx,libgdx/libgdx,Dzamir/libgdx,JDReutt/libgdx,cypherdare/libgdx,saltares/libgdx,andyvand/libgdx,gouessej/libgdx,UnluckyNinja/libgdx,thepullman/libgdx,FredGithub/libgdx,NathanSweet/libgdx,KrisLee/libgdx,kagehak/libgdx,sarkanyi/libgdx,noelsison2/libgdx,Xhanim/libgdx,ThiagoGarciaAlves/libgdx,gdos/libgdx,Gliby/libgdx,fwolff/libgdx,EsikAntony/libgdx,katiepino/libgdx,sjosegarcia/libgdx,kotcrab/libgdx,309746069/libgdx,samskivert/libgdx,kagehak/libgdx,designcrumble/libgdx,ttencate/libgdx,firefly2442/libgdx,fiesensee/libgdx,1yvT0s/libgdx,junkdog/libgdx,ryoenji/libgdx,zhimaijoy/libgdx,andyvand/libgdx,ryoenji/libgdx,gouessej/libgdx,tell10glu/libgdx,tommycli/libgdx,alireza-hosseini/libgdx,lordjone/libgdx,FredGithub/libgdx,BlueRiverInteractive/libgdx,azakhary/libgdx,bgroenks96/libgdx,ya7lelkom/libgdx,Zonglin-Li6565/libgdx,BlueRiverInteractive/libgdx,noelsison2/libgdx,del-sol/libgdx,toloudis/libgdx,nooone/libgdx,andyvand/libgdx,codepoke/libgdx,xoppa/libgdx,fwolff/libgdx,jberberick/libgdx,Gliby/libgdx,1yvT0s/libgdx,nrallakis/libgdx,Senth/libgdx,kagehak/libgdx,gf11speed/libgdx,sarkanyi/libgdx,gouessej/libgdx,realitix/libgdx,codepoke/libgdx,antag99/libgdx,alex-dorokhov/libgdx,hyvas/libgdx,youprofit/libgdx,ztv/libgdx,antag99/libgdx,katiepino/libgdx,srwonka/libGdx,josephknight/libgdx,Arcnor/libgdx,1yvT0s/libgdx,jsjolund/libgdx,firefly2442/libgdx,JFixby/libgdx,tommycli/libgdx,Senth/libgdx,Badazdz/libgdx,ninoalma/libgdx,kzganesan/libgdx,junkdog/libgdx,saqsun/libgdx,PedroRomanoBarbosa/libgdx,ztv/libgdx,UnluckyNinja/libgdx,zhimaijoy/libgdx,zommuter/libgdx,ttencate/libgdx,nave966/libgdx,ttencate/libgdx,Heart2009/libgdx,MikkelTAndersen/libgdx,youprofit/libgdx,del-sol/libgdx,MetSystem/libgdx,SidneyXu/libgdx,Zonglin-Li6565/libgdx,ninoalma/libgdx,srwonka/libGdx,Deftwun/libgdx,mumer92/libgdx,gf11speed/libgdx,FyiurAmron/libgdx,katiepino/libgdx,MovingBlocks/libgdx,revo09/libgdx,Gliby/libgdx,anserran/libgdx,toa5/libgdx,mumer92/libgdx,UnluckyNinja/libgdx,thepullman/libgdx,nudelchef/libgdx,revo09/libgdx,JDReutt/libgdx,Xhanim/libgdx,noelsison2/libgdx,zhimaijoy/libgdx,MetSystem/libgdx,JDReutt/libgdx,JDReutt/libgdx,nelsonsilva/libgdx,copystudy/libgdx,flaiker/libgdx,stickyd/libgdx,tommyettinger/libgdx,TheAks999/libgdx,jsjolund/libgdx,stinsonga/libgdx,Gliby/libgdx,Zomby2D/libgdx,luischavez/libgdx,davebaol/libgdx,MikkelTAndersen/libgdx,petugez/libgdx,junkdog/libgdx,Arcnor/libgdx,collinsmith/libgdx,designcrumble/libgdx,MathieuDuponchelle/gdx,shiweihappy/libgdx,jasonwee/libgdx,libgdx/libgdx,copystudy/libgdx,titovmaxim/libgdx,SidneyXu/libgdx,1yvT0s/libgdx,kagehak/libgdx,sjosegarcia/libgdx,JFixby/libgdx,FyiurAmron/libgdx,MathieuDuponchelle/gdx,mumer92/libgdx,katiepino/libgdx,youprofit/libgdx,czyzby/libgdx,bsmr-java/libgdx,bgroenks96/libgdx,gf11speed/libgdx,alex-dorokhov/libgdx,SidneyXu/libgdx,jasonwee/libgdx,nudelchef/libgdx,MathieuDuponchelle/gdx,sinistersnare/libgdx,curtiszimmerman/libgdx,thepullman/libgdx,Dzamir/libgdx,sjosegarcia/libgdx,shiweihappy/libgdx,stickyd/libgdx,kzganesan/libgdx,josephknight/libgdx,kzganesan/libgdx,petugez/libgdx,bladecoder/libgdx,hyvas/libgdx,hyvas/libgdx,xoppa/libgdx,Zomby2D/libgdx,nelsonsilva/libgdx,bgroenks96/libgdx,tommycli/libgdx,MikkelTAndersen/libgdx,ya7lelkom/libgdx,kotcrab/libgdx,srwonka/libGdx,bladecoder/libgdx,BlueRiverInteractive/libgdx,Senth/libgdx,PedroRomanoBarbosa/libgdx,lordjone/libgdx,alireza-hosseini/libgdx,gouessej/libgdx,snovak/libgdx,tommycli/libgdx,anserran/libgdx,Gliby/libgdx,nave966/libgdx,xranby/libgdx,Thotep/libgdx,czyzby/libgdx,MadcowD/libgdx,Badazdz/libgdx,nooone/libgdx,JFixby/libgdx,Heart2009/libgdx,MetSystem/libgdx,junkdog/libgdx,MathieuDuponchelle/gdx,del-sol/libgdx,luischavez/libgdx,noelsison2/libgdx,TheAks999/libgdx,saqsun/libgdx,JDReutt/libgdx,tommyettinger/libgdx,ricardorigodon/libgdx,ya7lelkom/libgdx,Deftwun/libgdx,jberberick/libgdx,MathieuDuponchelle/gdx,alex-dorokhov/libgdx,kzganesan/libgdx,toa5/libgdx,JDReutt/libgdx,gf11speed/libgdx,saltares/libgdx,youprofit/libgdx,Senth/libgdx,gf11speed/libgdx,Zomby2D/libgdx,js78/libgdx,Deftwun/libgdx,realitix/libgdx,del-sol/libgdx,thepullman/libgdx,nrallakis/libgdx,EsikAntony/libgdx,nudelchef/libgdx,ryoenji/libgdx,TheAks999/libgdx,katiepino/libgdx,toa5/libgdx,PedroRomanoBarbosa/libgdx,tell10glu/libgdx,cypherdare/libgdx,ninoalma/libgdx,xranby/libgdx,kzganesan/libgdx,realitix/libgdx,Thotep/libgdx,codepoke/libgdx,ryoenji/libgdx,ttencate/libgdx,mumer92/libgdx,jasonwee/libgdx,lordjone/libgdx,GreenLightning/libgdx,shiweihappy/libgdx,yangweigbh/libgdx,TheAks999/libgdx,saltares/libgdx,xpenatan/libgdx-LWJGL3,saltares/libgdx,stinsonga/libgdx,alex-dorokhov/libgdx,billgame/libgdx,Senth/libgdx,Wisienkas/libgdx,alireza-hosseini/libgdx,MadcowD/libgdx,libgdx/libgdx,MetSystem/libgdx,Dzamir/libgdx,samskivert/libgdx,stickyd/libgdx,revo09/libgdx,shiweihappy/libgdx,azakhary/libgdx,xranby/libgdx,tommyettinger/libgdx,nudelchef/libgdx,zommuter/libgdx,haedri/libgdx-1,anserran/libgdx,BlueRiverInteractive/libgdx,basherone/libgdxcn,josephknight/libgdx,gouessej/libgdx,xpenatan/libgdx-LWJGL3,gouessej/libgdx,ttencate/libgdx,kagehak/libgdx,js78/libgdx,Xhanim/libgdx,jsjolund/libgdx,tommyettinger/libgdx,djom20/libgdx,nave966/libgdx,309746069/libgdx,ztv/libgdx,josephknight/libgdx,MadcowD/libgdx,FredGithub/libgdx,andyvand/libgdx,MovingBlocks/libgdx,zommuter/libgdx,titovmaxim/libgdx,tell10glu/libgdx,noelsison2/libgdx,KrisLee/libgdx,Badazdz/libgdx,MikkelTAndersen/libgdx,alireza-hosseini/libgdx,ztv/libgdx,Dzamir/libgdx,nrallakis/libgdx,yangweigbh/libgdx,Badazdz/libgdx,toa5/libgdx,titovmaxim/libgdx,Zomby2D/libgdx,bsmr-java/libgdx,petugez/libgdx,lordjone/libgdx,gf11speed/libgdx,alireza-hosseini/libgdx,gdos/libgdx,revo09/libgdx,petugez/libgdx,Wisienkas/libgdx,js78/libgdx,nudelchef/libgdx,Zonglin-Li6565/libgdx,djom20/libgdx,thepullman/libgdx,FyiurAmron/libgdx,TheAks999/libgdx,codepoke/libgdx,copystudy/libgdx,josephknight/libgdx,anserran/libgdx,sjosegarcia/libgdx,anserran/libgdx,sarkanyi/libgdx,luischavez/libgdx,EsikAntony/libgdx,kotcrab/libgdx,KrisLee/libgdx,bgroenks96/libgdx,MikkelTAndersen/libgdx,zommuter/libgdx,lordjone/libgdx,jberberick/libgdx,noelsison2/libgdx,revo09/libgdx,Thotep/libgdx,curtiszimmerman/libgdx,zommuter/libgdx,ThiagoGarciaAlves/libgdx,FyiurAmron/libgdx,xranby/libgdx,309746069/libgdx,toloudis/libgdx,katiepino/libgdx,jsjolund/libgdx,zommuter/libgdx,flaiker/libgdx,flaiker/libgdx,Gliby/libgdx,js78/libgdx,andyvand/libgdx,snovak/libgdx,xranby/libgdx,thepullman/libgdx,gouessej/libgdx,Xhanim/libgdx,snovak/libgdx,zhimaijoy/libgdx,PedroRomanoBarbosa/libgdx,Dzamir/libgdx,czyzby/libgdx,firefly2442/libgdx,codepoke/libgdx,stickyd/libgdx,MathieuDuponchelle/gdx,NathanSweet/libgdx,SidneyXu/libgdx,309746069/libgdx,GreenLightning/libgdx,gdos/libgdx,antag99/libgdx,sinistersnare/libgdx,ryoenji/libgdx,realitix/libgdx,anserran/libgdx,snovak/libgdx,UnluckyNinja/libgdx,kagehak/libgdx,Badazdz/libgdx,curtiszimmerman/libgdx,EsikAntony/libgdx,youprofit/libgdx,ztv/libgdx,ttencate/libgdx,gouessej/libgdx,ricardorigodon/libgdx,antag99/libgdx,MathieuDuponchelle/gdx,jasonwee/libgdx,KrisLee/libgdx,nave966/libgdx,petugez/libgdx,flaiker/libgdx,UnluckyNinja/libgdx,EsikAntony/libgdx,czyzby/libgdx,noelsison2/libgdx,ThiagoGarciaAlves/libgdx,azakhary/libgdx,Xhanim/libgdx,hyvas/libgdx,del-sol/libgdx,MetSystem/libgdx,billgame/libgdx,ricardorigodon/libgdx,srwonka/libGdx,samskivert/libgdx,xpenatan/libgdx-LWJGL3,nrallakis/libgdx,collinsmith/libgdx,thepullman/libgdx,ricardorigodon/libgdx,ya7lelkom/libgdx,srwonka/libGdx,andyvand/libgdx,stickyd/libgdx,Arcnor/libgdx,toa5/libgdx,Zonglin-Li6565/libgdx,firefly2442/libgdx,Xhanim/libgdx,tommycli/libgdx,Deftwun/libgdx,UnluckyNinja/libgdx,samskivert/libgdx,MovingBlocks/libgdx,alex-dorokhov/libgdx,copystudy/libgdx,haedri/libgdx-1,sjosegarcia/libgdx,ninoalma/libgdx,davebaol/libgdx,ThiagoGarciaAlves/libgdx,MovingBlocks/libgdx,GreenLightning/libgdx,JDReutt/libgdx,kzganesan/libgdx,antag99/libgdx,bsmr-java/libgdx,jasonwee/libgdx,KrisLee/libgdx,ThiagoGarciaAlves/libgdx,toa5/libgdx,Senth/libgdx,shiweihappy/libgdx,lordjone/libgdx,sinistersnare/libgdx,czyzby/libgdx,Dzamir/libgdx,luischavez/libgdx,BlueRiverInteractive/libgdx,sarkanyi/libgdx,bsmr-java/libgdx,ricardorigodon/libgdx,jberberick/libgdx,jsjolund/libgdx,del-sol/libgdx,jberberick/libgdx,sinistersnare/libgdx,realitix/libgdx,bladecoder/libgdx,Zonglin-Li6565/libgdx,realitix/libgdx,bsmr-java/libgdx,nooone/libgdx,kagehak/libgdx,luischavez/libgdx,basherone/libgdxcn,BlueRiverInteractive/libgdx,EsikAntony/libgdx,Heart2009/libgdx,fwolff/libgdx,jberberick/libgdx,309746069/libgdx,cypherdare/libgdx,MikkelTAndersen/libgdx,davebaol/libgdx,Zonglin-Li6565/libgdx,cypherdare/libgdx,sinistersnare/libgdx,shiweihappy/libgdx,basherone/libgdxcn,djom20/libgdx,xoppa/libgdx,Heart2009/libgdx,TheAks999/libgdx,GreenLightning/libgdx,Thotep/libgdx,mumer92/libgdx,Thotep/libgdx,ztv/libgdx,toloudis/libgdx,realitix/libgdx,azakhary/libgdx,noelsison2/libgdx,titovmaxim/libgdx,bladecoder/libgdx,ryoenji/libgdx,samskivert/libgdx,anserran/libgdx,MetSystem/libgdx,youprofit/libgdx,zhimaijoy/libgdx,billgame/libgdx,KrisLee/libgdx,samskivert/libgdx,309746069/libgdx,Wisienkas/libgdx,luischavez/libgdx,josephknight/libgdx,lordjone/libgdx,js78/libgdx,yangweigbh/libgdx,zommuter/libgdx,SidneyXu/libgdx,Zomby2D/libgdx,FyiurAmron/libgdx,alex-dorokhov/libgdx,alireza-hosseini/libgdx,gdos/libgdx,mumer92/libgdx,kotcrab/libgdx,zhimaijoy/libgdx,titovmaxim/libgdx,toloudis/libgdx,ricardorigodon/libgdx,xpenatan/libgdx-LWJGL3,stickyd/libgdx,shiweihappy/libgdx,fiesensee/libgdx,codepoke/libgdx,Xhanim/libgdx,bladecoder/libgdx,haedri/libgdx-1,MetSystem/libgdx,azakhary/libgdx,xpenatan/libgdx-LWJGL3,Senth/libgdx,gf11speed/libgdx,FredGithub/libgdx,NathanSweet/libgdx,xpenatan/libgdx-LWJGL3,JFixby/libgdx,Heart2009/libgdx,ztv/libgdx,mumer92/libgdx,SidneyXu/libgdx,EsikAntony/libgdx,billgame/libgdx,NathanSweet/libgdx,sjosegarcia/libgdx,stinsonga/libgdx,srwonka/libGdx,andyvand/libgdx,UnluckyNinja/libgdx,gdos/libgdx,copystudy/libgdx,jasonwee/libgdx,copystudy/libgdx,hyvas/libgdx,billgame/libgdx,josephknight/libgdx,petugez/libgdx,haedri/libgdx-1,SidneyXu/libgdx,toloudis/libgdx,jasonwee/libgdx,snovak/libgdx,ya7lelkom/libgdx,TheAks999/libgdx,nave966/libgdx,Badazdz/libgdx,JFixby/libgdx,nrallakis/libgdx,collinsmith/libgdx,MetSystem/libgdx,sarkanyi/libgdx,davebaol/libgdx,haedri/libgdx-1,josephknight/libgdx,billgame/libgdx,snovak/libgdx,alireza-hosseini/libgdx,xoppa/libgdx,basherone/libgdxcn,Thotep/libgdx,kotcrab/libgdx,nrallakis/libgdx,sarkanyi/libgdx,gdos/libgdx,GreenLightning/libgdx,xoppa/libgdx,xranby/libgdx,bgroenks96/libgdx,bgroenks96/libgdx,ya7lelkom/libgdx,junkdog/libgdx,ya7lelkom/libgdx,xpenatan/libgdx-LWJGL3,djom20/libgdx,youprofit/libgdx,nrallakis/libgdx,flaiker/libgdx,stinsonga/libgdx,libgdx/libgdx,codepoke/libgdx,junkdog/libgdx,fiesensee/libgdx,jsjolund/libgdx,Dzamir/libgdx,nelsonsilva/libgdx,antag99/libgdx,FredGithub/libgdx,PedroRomanoBarbosa/libgdx,sjosegarcia/libgdx,codepoke/libgdx,nelsonsilva/libgdx,Dzamir/libgdx,JDReutt/libgdx,1yvT0s/libgdx,collinsmith/libgdx,saltares/libgdx,ztv/libgdx,Deftwun/libgdx,PedroRomanoBarbosa/libgdx,collinsmith/libgdx,curtiszimmerman/libgdx,antag99/libgdx,Wisienkas/libgdx,tommycli/libgdx,luischavez/libgdx,MikkelTAndersen/libgdx,alex-dorokhov/libgdx,tell10glu/libgdx,Senth/libgdx,tell10glu/libgdx,antag99/libgdx,Thotep/libgdx,gdos/libgdx,FyiurAmron/libgdx,firefly2442/libgdx,1yvT0s/libgdx,nave966/libgdx,ThiagoGarciaAlves/libgdx,PedroRomanoBarbosa/libgdx,revo09/libgdx,del-sol/libgdx,xpenatan/libgdx-LWJGL3,curtiszimmerman/libgdx,zommuter/libgdx,KrisLee/libgdx,saqsun/libgdx,firefly2442/libgdx,alex-dorokhov/libgdx,nrallakis/libgdx,ricardorigodon/libgdx,haedri/libgdx-1,del-sol/libgdx,andyvand/libgdx,1yvT0s/libgdx,snovak/libgdx,saqsun/libgdx,lordjone/libgdx,mumer92/libgdx,copystudy/libgdx,nave966/libgdx,GreenLightning/libgdx,kotcrab/libgdx,Wisienkas/libgdx,azakhary/libgdx,Arcnor/libgdx,designcrumble/libgdx,GreenLightning/libgdx,nooone/libgdx,collinsmith/libgdx,toloudis/libgdx,ninoalma/libgdx,ricardorigodon/libgdx,toloudis/libgdx,srwonka/libGdx,Arcnor/libgdx,fwolff/libgdx,nudelchef/libgdx,UnluckyNinja/libgdx,Zonglin-Li6565/libgdx,SidneyXu/libgdx,fwolff/libgdx,flaiker/libgdx,nudelchef/libgdx,revo09/libgdx,ThiagoGarciaAlves/libgdx,FyiurAmron/libgdx,toa5/libgdx,sjosegarcia/libgdx,saqsun/libgdx,revo09/libgdx,MadcowD/libgdx,curtiszimmerman/libgdx,jberberick/libgdx,TheAks999/libgdx,ryoenji/libgdx,katiepino/libgdx,ninoalma/libgdx,Gliby/libgdx,FyiurAmron/libgdx,ttencate/libgdx,ninoalma/libgdx,MovingBlocks/libgdx,ttencate/libgdx,js78/libgdx,designcrumble/libgdx,czyzby/libgdx,gdos/libgdx,firefly2442/libgdx,saltares/libgdx,luischavez/libgdx,MovingBlocks/libgdx,czyzby/libgdx,nooone/libgdx,FredGithub/libgdx | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.utils;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.JsonWriter.OutputType;
import com.badlogic.gdx.utils.ObjectMap.Entry;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.security.AccessControlException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** Reads/writes Java objects to/from JSON, automatically.
* @author Nathan Sweet */
public class Json {
private static final boolean debug = false;
private JsonWriter writer;
private String typeName = "class";
private boolean usePrototypes = true;
private OutputType outputType;
private final ObjectMap<Class, ObjectMap<String, FieldMetadata>> typeToFields = new ObjectMap();
private final ObjectMap<String, Class> tagToClass = new ObjectMap();
private final ObjectMap<Class, String> classToTag = new ObjectMap();
private final ObjectMap<Class, Serializer> classToSerializer = new ObjectMap();
private final ObjectMap<Class, Object[]> classToDefaultValues = new ObjectMap();
private boolean ignoreUnknownFields;
public Json () {
outputType = OutputType.minimal;
}
public Json (OutputType outputType) {
this.outputType = outputType;
}
public void setIgnoreUnknownFields (boolean ignoreUnknownFields) {
this.ignoreUnknownFields = ignoreUnknownFields;
}
public void setOutputType (OutputType outputType) {
this.outputType = outputType;
}
public void addClassTag (String tag, Class type) {
tagToClass.put(tag, type);
classToTag.put(type, tag);
}
public Class getClass (String tag) {
Class type = tagToClass.get(tag);
if (type != null) return type;
try {
return Class.forName(tag);
} catch (ClassNotFoundException ex) {
throw new SerializationException(ex);
}
}
public String getTag (Class type) {
String tag = classToTag.get(type);
if (tag != null) return tag;
return type.getName();
}
/** Sets the name of the JSON field to store the Java class name or class tag when required to avoid ambiguity during
* deserialization. Set to null to never output this information, but be warned that deserialization may fail. */
public void setTypeName (String typeName) {
this.typeName = typeName;
}
public <T> void setSerializer (Class<T> type, Serializer<T> serializer) {
classToSerializer.put(type, serializer);
}
public <T> Serializer<T> getSerializer (Class<T> type) {
return classToSerializer.get(type);
}
public void setUsePrototypes (boolean usePrototypes) {
this.usePrototypes = usePrototypes;
}
public void setElementType (Class type, String fieldName, Class elementType) {
ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
if (fields == null) fields = cacheFields(type);
FieldMetadata metadata = fields.get(fieldName);
if (metadata == null) throw new SerializationException("Field not found: " + fieldName + " (" + type.getName() + ")");
metadata.elementType = elementType;
}
private ObjectMap<String, FieldMetadata> cacheFields (Class type) {
ArrayList<Field> allFields = new ArrayList();
Class nextClass = type;
while (nextClass != Object.class) {
Collections.addAll(allFields, nextClass.getDeclaredFields());
nextClass = nextClass.getSuperclass();
}
ObjectMap<String, FieldMetadata> nameToField = new ObjectMap();
for (int i = 0, n = allFields.size(); i < n; i++) {
Field field = allFields.get(i);
int modifiers = field.getModifiers();
if (Modifier.isTransient(modifiers)) continue;
if (Modifier.isStatic(modifiers)) continue;
if (field.isSynthetic()) continue;
if (!field.isAccessible()) {
try {
field.setAccessible(true);
} catch (AccessControlException ex) {
continue;
}
}
nameToField.put(field.getName(), new FieldMetadata(field));
}
typeToFields.put(type, nameToField);
return nameToField;
}
public String toJson (Object object) {
return toJson(object, object == null ? null : object.getClass(), (Class)null);
}
public String toJson (Object object, Class knownType) {
return toJson(object, knownType, (Class)null);
}
/** @param knownType May be null if the type is unknown.
* @param elementType May be null if the type is unknown. */
public String toJson (Object object, Class knownType, Class elementType) {
StringWriter buffer = new StringWriter();
toJson(object, knownType, elementType, buffer);
return buffer.toString();
}
public void toJson (Object object, FileHandle file) {
toJson(object, object == null ? null : object.getClass(), null, file);
}
/** @param knownType May be null if the type is unknown. */
public void toJson (Object object, Class knownType, FileHandle file) {
toJson(object, knownType, null, file);
}
/** @param knownType May be null if the type is unknown.
* @param elementType May be null if the type is unknown. */
public void toJson (Object object, Class knownType, Class elementType, FileHandle file) {
Writer writer = null;
try {
writer = file.writer(false);
toJson(object, knownType, elementType, writer);
} catch (Exception ex) {
throw new SerializationException("Error writing file: " + file, ex);
} finally {
try {
if (writer != null) writer.close();
} catch (IOException ignored) {
}
}
}
public void toJson (Object object, Writer writer) {
toJson(object, object == null ? null : object.getClass(), null, writer);
}
/** @param knownType May be null if the type is unknown. */
public void toJson (Object object, Class knownType, Writer writer) {
toJson(object, knownType, null, writer);
}
/** @param knownType May be null if the type is unknown.
* @param elementType May be null if the type is unknown. */
public void toJson (Object object, Class knownType, Class elementType, Writer writer) {
setWriter(writer);
try {
writeValue(object, knownType, elementType);
} finally {
try {
this.writer.close();
} catch (IOException ignored) {
}
this.writer = null;
}
}
/** Sets the writer where JSON output will go. This is only necessary when not using the toJson methods. */
public void setWriter (Writer writer) {
if (!(writer instanceof JsonWriter)) writer = new JsonWriter(writer);
this.writer = (JsonWriter)writer;
this.writer.setOutputType(outputType);
}
public JsonWriter getWriter () {
return writer;
}
public void writeFields (Object object) {
Class type = object.getClass();
Object[] defaultValues = getDefaultValues(type);
ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
if (fields == null) fields = cacheFields(type);
int i = 0;
for (FieldMetadata metadata : fields.values()) {
Field field = metadata.field;
try {
Object value = field.get(object);
if (defaultValues != null) {
Object defaultValue = defaultValues[i++];
if (value == null && defaultValue == null) continue;
if (value != null && defaultValue != null && value.equals(defaultValue)) continue;
}
if (debug) System.out.println("Writing field: " + field.getName() + " (" + type.getName() + ")");
writer.name(field.getName());
writeValue(value, field.getType(), metadata.elementType);
} catch (IllegalAccessException ex) {
throw new SerializationException("Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
} catch (SerializationException ex) {
ex.addTrace(field + " (" + type.getName() + ")");
throw ex;
} catch (Exception runtimeEx) {
SerializationException ex = new SerializationException(runtimeEx);
ex.addTrace(field + " (" + type.getName() + ")");
throw ex;
}
}
}
private Object[] getDefaultValues (Class type) {
if (!usePrototypes) return null;
if (classToDefaultValues.containsKey(type)) return classToDefaultValues.get(type);
Object object;
try {
object = newInstance(type);
} catch (Exception ex) {
classToDefaultValues.put(type, null);
return null;
}
ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
if (fields == null) fields = cacheFields(type);
Object[] values = new Object[fields.size];
classToDefaultValues.put(type, values);
int i = 0;
for (FieldMetadata metadata : fields.values()) {
Field field = metadata.field;
try {
values[i++] = field.get(object);
} catch (IllegalAccessException ex) {
throw new SerializationException("Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
} catch (SerializationException ex) {
ex.addTrace(field + " (" + type.getName() + ")");
throw ex;
} catch (RuntimeException runtimeEx) {
SerializationException ex = new SerializationException(runtimeEx);
ex.addTrace(field + " (" + type.getName() + ")");
throw ex;
}
}
return values;
}
public void writeField (Object object, String name) {
writeField(object, name, name, null);
}
/** @param elementType May be null if the type is unknown. */
public void writeField (Object object, String name, Class elementType) {
writeField(object, name, name, elementType);
}
public void writeField (Object object, String fieldName, String jsonName) {
writeField(object, fieldName, jsonName, null);
}
/** @param elementType May be null if the type is unknown. */
public void writeField (Object object, String fieldName, String jsonName, Class elementType) {
Class type = object.getClass();
ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
if (fields == null) fields = cacheFields(type);
FieldMetadata metadata = fields.get(fieldName);
if (metadata == null) throw new SerializationException("Field not found: " + fieldName + " (" + type.getName() + ")");
Field field = metadata.field;
if (elementType == null) elementType = metadata.elementType;
try {
if (debug) System.out.println("Writing field: " + field.getName() + " (" + type.getName() + ")");
writer.name(jsonName);
writeValue(field.get(object), field.getType(), elementType);
} catch (IllegalAccessException ex) {
throw new SerializationException("Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
} catch (SerializationException ex) {
ex.addTrace(field + " (" + type.getName() + ")");
throw ex;
} catch (Exception runtimeEx) {
SerializationException ex = new SerializationException(runtimeEx);
ex.addTrace(field + " (" + type.getName() + ")");
throw ex;
}
}
/** @param value May be null. */
public void writeValue (String name, Object value) {
try {
writer.name(name);
} catch (IOException ex) {
throw new SerializationException(ex);
}
if (value == null)
writeValue(value, null, null);
else
writeValue(value, value.getClass(), null);
}
/** @param value May be null.
* @param knownType May be null if the type is unknown. */
public void writeValue (String name, Object value, Class knownType) {
try {
writer.name(name);
} catch (IOException ex) {
throw new SerializationException(ex);
}
writeValue(value, knownType, null);
}
/** @param value May be null.
* @param knownType May be null if the type is unknown.
* @param elementType May be null if the type is unknown. */
public void writeValue (String name, Object value, Class knownType, Class elementType) {
try {
writer.name(name);
} catch (IOException ex) {
throw new SerializationException(ex);
}
writeValue(value, knownType, elementType);
}
/** @param value May be null. */
public void writeValue (Object value) {
if (value == null)
writeValue(value, null, null);
else
writeValue(value, value.getClass(), null);
}
/** @param value May be null.
* @param knownType May be null if the type is unknown. */
public void writeValue (Object value, Class knownType) {
writeValue(value, knownType, null);
}
/** @param value May be null.
* @param knownType May be null if the type is unknown.
* @param elementType May be null if the type is unknown. */
public void writeValue (Object value, Class knownType, Class elementType) {
try {
if (value == null) {
writer.value(null);
return;
}
Class actualType = value.getClass();
if (actualType.isPrimitive() || actualType == String.class || actualType == Integer.class || actualType == Boolean.class
|| actualType == Float.class || actualType == Long.class || actualType == Double.class || actualType == Short.class
|| actualType == Byte.class || actualType == Character.class) {
writer.value(value);
return;
}
if (value instanceof Serializable) {
writeObjectStart(actualType, knownType);
((Serializable)value).write(this);
writeObjectEnd();
return;
}
Serializer serializer = classToSerializer.get(actualType);
if (serializer != null) {
serializer.write(this, value, knownType);
return;
}
if (value instanceof Array) {
if (knownType != null && actualType != knownType)
throw new SerializationException("Serialization of an Array other than the known type is not supported.\n"
+ "Known type: " + knownType + "\nActual type: " + actualType);
writeArrayStart();
Array array = (Array)value;
for (int i = 0, n = array.size; i < n; i++)
writeValue(array.get(i), elementType, null);
writeArrayEnd();
return;
}
if (value instanceof Collection) {
if (knownType != null && actualType != knownType && actualType != ArrayList.class)
throw new SerializationException("Serialization of a Collection other than the known type is not supported.\n"
+ "Known type: " + knownType + "\nActual type: " + actualType);
writeArrayStart();
for (Object item : (Collection)value)
writeValue(item, elementType, null);
writeArrayEnd();
return;
}
if (actualType.isArray()) {
if (elementType == null) elementType = actualType.getComponentType();
int length = java.lang.reflect.Array.getLength(value);
writeArrayStart();
for (int i = 0; i < length; i++)
writeValue(java.lang.reflect.Array.get(value, i), elementType, null);
writeArrayEnd();
return;
}
if (value instanceof OrderedMap) {
if (knownType == null) knownType = OrderedMap.class;
writeObjectStart(actualType, knownType);
OrderedMap map = (OrderedMap)value;
for (Object key : map.orderedKeys()) {
writer.name(convertToString(key));
writeValue(map.get(key), elementType, null);
}
writeObjectEnd();
return;
}
if (value instanceof ArrayMap) {
if (knownType == null) knownType = ArrayMap.class;
writeObjectStart(actualType, knownType);
ArrayMap map = (ArrayMap)value;
for (int i = 0, n = map.size; i < n; i++) {
writer.name(convertToString(map.keys[i]));
writeValue(map.values[i], elementType, null);
}
writeObjectEnd();
return;
}
if (value instanceof ObjectMap) {
if (knownType == null) knownType = OrderedMap.class;
writeObjectStart(actualType, knownType);
for (Entry entry : ((ObjectMap<?, ?>)value).entries()) {
writer.name(convertToString(entry.key));
writeValue(entry.value, elementType, null);
}
writeObjectEnd();
return;
}
if (value instanceof Map) {
if (knownType == null) knownType = OrderedMap.class;
writeObjectStart(actualType, knownType);
for (Map.Entry entry : ((Map<?, ?>)value).entrySet()) {
writer.name(convertToString(entry.getKey()));
writeValue(entry.getValue(), elementType, null);
}
writeObjectEnd();
return;
}
if (Enum.class.isAssignableFrom(actualType)) {
writer.value(value);
return;
}
writeObjectStart(actualType, knownType);
writeFields(value);
writeObjectEnd();
} catch (IOException ex) {
throw new SerializationException(ex);
}
}
public void writeObjectStart (String name) {
try {
writer.name(name);
} catch (IOException ex) {
throw new SerializationException(ex);
}
writeObjectStart();
}
/** @param knownType May be null if the type is unknown. */
public void writeObjectStart (String name, Class actualType, Class knownType) {
try {
writer.name(name);
} catch (IOException ex) {
throw new SerializationException(ex);
}
writeObjectStart(actualType, knownType);
}
public void writeObjectStart () {
try {
writer.object();
} catch (IOException ex) {
throw new SerializationException(ex);
}
}
/** @param knownType May be null if the type is unknown. */
public void writeObjectStart (Class actualType, Class knownType) {
try {
writer.object();
} catch (IOException ex) {
throw new SerializationException(ex);
}
if (knownType == null || knownType != actualType) writeType(actualType);
}
public void writeObjectEnd () {
try {
writer.pop();
} catch (IOException ex) {
throw new SerializationException(ex);
}
}
public void writeArrayStart (String name) {
try {
writer.name(name);
writer.array();
} catch (IOException ex) {
throw new SerializationException(ex);
}
}
public void writeArrayStart () {
try {
writer.array();
} catch (IOException ex) {
throw new SerializationException(ex);
}
}
public void writeArrayEnd () {
try {
writer.pop();
} catch (IOException ex) {
throw new SerializationException(ex);
}
}
public void writeType (Class type) {
if (typeName == null) return;
String className = classToTag.get(type);
if (className == null) className = type.getName();
try {
writer.set(typeName, className);
} catch (IOException ex) {
throw new SerializationException(ex);
}
if (debug) System.out.println("Writing type: " + type.getName());
}
/** @param type May be null if the type is unknown.
* @return May be null. */
public <T> T fromJson (Class<T> type, Reader reader) {
return (T)readValue(type, null, new JsonReader().parse(reader));
}
/** @param type May be null if the type is unknown.
* @param elementType May be null if the type is unknown.
* @return May be null. */
public <T> T fromJson (Class<T> type, Class elementType, Reader reader) {
return (T)readValue(type, elementType, new JsonReader().parse(reader));
}
/** @param type May be null if the type is unknown.
* @return May be null. */
public <T> T fromJson (Class<T> type, InputStream input) {
return (T)readValue(type, null, new JsonReader().parse(input));
}
/** @param type May be null if the type is unknown.
* @param elementType May be null if the type is unknown.
* @return May be null. */
public <T> T fromJson (Class<T> type, Class elementType, InputStream input) {
return (T)readValue(type, elementType, new JsonReader().parse(input));
}
/** @param type May be null if the type is unknown.
* @return May be null. */
public <T> T fromJson (Class<T> type, FileHandle file) {
try {
return (T)readValue(type, null, new JsonReader().parse(file));
} catch (Exception ex) {
throw new SerializationException("Error reading file: " + file, ex);
}
}
/** @param type May be null if the type is unknown.
* @param elementType May be null if the type is unknown.
* @return May be null. */
public <T> T fromJson (Class<T> type, Class elementType, FileHandle file) {
try {
return (T)readValue(type, elementType, new JsonReader().parse(file));
} catch (Exception ex) {
throw new SerializationException("Error reading file: " + file, ex);
}
}
/** @param type May be null if the type is unknown.
* @return May be null. */
public <T> T fromJson (Class<T> type, char[] data, int offset, int length) {
return (T)readValue(type, null, new JsonReader().parse(data, offset, length));
}
/** @param type May be null if the type is unknown.
* @param elementType May be null if the type is unknown.
* @return May be null. */
public <T> T fromJson (Class<T> type, Class elementType, char[] data, int offset, int length) {
return (T)readValue(type, elementType, new JsonReader().parse(data, offset, length));
}
/** @param type May be null if the type is unknown.
* @return May be null. */
public <T> T fromJson (Class<T> type, String json) {
return (T)readValue(type, null, new JsonReader().parse(json));
}
/** @param type May be null if the type is unknown.
* @return May be null. */
public <T> T fromJson (Class<T> type, Class elementType, String json) {
return (T)readValue(type, elementType, new JsonReader().parse(json));
}
public void readField (Object object, String name, Object jsonData) {
readField(object, name, name, null, jsonData);
}
public void readField (Object object, String name, Class elementType, Object jsonData) {
readField(object, name, name, elementType, jsonData);
}
public void readField (Object object, String fieldName, String jsonName, Object jsonData) {
readField(object, fieldName, jsonName, null, jsonData);
}
/** @param elementType May be null if the type is unknown. */
public void readField (Object object, String fieldName, String jsonName, Class elementType, Object jsonData) {
OrderedMap jsonMap = (OrderedMap)jsonData;
Class type = object.getClass();
ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
if (fields == null) fields = cacheFields(type);
FieldMetadata metadata = fields.get(fieldName);
if (metadata == null) throw new SerializationException("Field not found: " + fieldName + " (" + type.getName() + ")");
Field field = metadata.field;
Object jsonValue = jsonMap.get(jsonName);
if (jsonValue == null) return;
if (elementType == null) elementType = metadata.elementType;
try {
field.set(object, readValue(field.getType(), elementType, jsonValue));
} catch (IllegalAccessException ex) {
throw new SerializationException("Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
} catch (SerializationException ex) {
ex.addTrace(field.getName() + " (" + type.getName() + ")");
throw ex;
} catch (RuntimeException runtimeEx) {
SerializationException ex = new SerializationException(runtimeEx);
ex.addTrace(field.getName() + " (" + type.getName() + ")");
throw ex;
}
}
public void readFields (Object object, Object jsonData) {
OrderedMap<String, Object> jsonMap = (OrderedMap)jsonData;
Class type = object.getClass();
ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
if (fields == null) fields = cacheFields(type);
for (Entry<String, Object> entry : jsonMap.entries()) {
FieldMetadata metadata = fields.get(entry.key);
if (metadata == null) {
if (ignoreUnknownFields) {
if (debug) System.out.println("Ignoring unknown field: " + entry.key + " (" + type.getName() + ")");
continue;
} else
throw new SerializationException("Field not found: " + entry.key + " (" + type.getName() + ")");
}
Field field = metadata.field;
if (entry.value == null) continue;
try {
field.set(object, readValue(field.getType(), metadata.elementType, entry.value));
} catch (IllegalAccessException ex) {
throw new SerializationException("Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
} catch (SerializationException ex) {
ex.addTrace(field.getName() + " (" + type.getName() + ")");
throw ex;
} catch (RuntimeException runtimeEx) {
SerializationException ex = new SerializationException(runtimeEx);
ex.addTrace(field.getName() + " (" + type.getName() + ")");
throw ex;
}
}
}
/** @param type May be null if the type is unknown.
* @return May be null. */
public <T> T readValue (String name, Class<T> type, Object jsonData) {
OrderedMap jsonMap = (OrderedMap)jsonData;
return (T)readValue(type, null, jsonMap.get(name));
}
/** @param type May be null if the type is unknown.
* @return May be null. */
public <T> T readValue (String name, Class<T> type, T defaultValue, Object jsonData) {
OrderedMap jsonMap = (OrderedMap)jsonData;
Object jsonValue = jsonMap.get(name);
if (jsonValue == null) return defaultValue;
return (T)readValue(type, null, jsonValue);
}
/** @param type May be null if the type is unknown.
* @param elementType May be null if the type is unknown.
* @return May be null. */
public <T> T readValue (String name, Class<T> type, Class elementType, Object jsonData) {
OrderedMap jsonMap = (OrderedMap)jsonData;
return (T)readValue(type, elementType, jsonMap.get(name));
}
/** @param type May be null if the type is unknown.
* @param elementType May be null if the type is unknown.
* @return May be null. */
public <T> T readValue (String name, Class<T> type, Class elementType, T defaultValue, Object jsonData) {
OrderedMap jsonMap = (OrderedMap)jsonData;
Object jsonValue = jsonMap.get(name);
if (jsonValue == null) return defaultValue;
return (T)readValue(type, elementType, jsonValue);
}
/** @param type May be null if the type is unknown.
* @param elementType May be null if the type is unknown.
* @return May be null. */
public <T> T readValue (Class<T> type, Class elementType, T defaultValue, Object jsonData) {
return (T)readValue(type, elementType, jsonData);
}
/** @param type May be null if the type is unknown.
* @return May be null. */
public <T> T readValue (Class<T> type, Object jsonData) {
return (T)readValue(type, null, jsonData);
}
/** @param type May be null if the type is unknown.
* @param elementType May be null if the type is unknown.
* @return May be null. */
public <T> T readValue (Class<T> type, Class elementType, Object jsonData) {
if (jsonData == null) return null;
if (jsonData instanceof OrderedMap) {
OrderedMap<String, Object> jsonMap = (OrderedMap)jsonData;
String className = typeName == null ? null : (String)jsonMap.remove(typeName);
if (className != null) {
try {
type = (Class<T>)Class.forName(className);
} catch (ClassNotFoundException ex) {
type = tagToClass.get(className);
if (type == null) throw new SerializationException(ex);
}
}
Object object;
if (type != null) {
Serializer serializer = classToSerializer.get(type);
if (serializer != null) return (T)serializer.read(this, jsonMap, type);
object = newInstance(type);
if (object instanceof Serializable) {
((Serializable)object).read(this, jsonMap);
return (T)object;
}
if (object instanceof HashMap) {
HashMap result = (HashMap)object;
for (Entry entry : jsonMap.entries())
result.put(entry.key, readValue(elementType, null, entry.value));
return (T)result;
}
} else
object = new OrderedMap();
if (object instanceof ObjectMap) {
ObjectMap result = (ObjectMap)object;
for (String key : jsonMap.orderedKeys())
result.put(key, readValue(elementType, null, jsonMap.get(key)));
return (T)result;
}
readFields(object, jsonMap);
return (T)object;
}
if (type != null) {
Serializer serializer = classToSerializer.get(type);
if (serializer != null) return (T)serializer.read(this, jsonData, type);
}
if (jsonData instanceof Array) {
Array array = (Array)jsonData;
if (type == null || Array.class.isAssignableFrom(type)) {
Array newArray = type == null ? new Array() : (Array)newInstance(type);
newArray.ensureCapacity(array.size);
for (int i = 0, n = array.size; i < n; i++)
newArray.add(readValue(elementType, null, array.get(i)));
return (T)newArray;
}
if (List.class.isAssignableFrom(type)) {
List newArray = type == null ? new ArrayList(array.size) : (List)newInstance(type);
for (int i = 0, n = array.size; i < n; i++)
newArray.add(readValue(elementType, null, array.get(i)));
return (T)newArray;
}
if (type.isArray()) {
Class componentType = type.getComponentType();
if (elementType == null) elementType = componentType;
Object newArray = java.lang.reflect.Array.newInstance(componentType, array.size);
for (int i = 0, n = array.size; i < n; i++)
java.lang.reflect.Array.set(newArray, i, readValue(elementType, null, array.get(i)));
return (T)newArray;
}
throw new SerializationException("Unable to convert value to required type: " + jsonData + " (" + type.getName() + ")");
}
if (jsonData instanceof Float) {
Float floatValue = (Float)jsonData;
try {
if (type == null || type == float.class || type == Float.class) return (T)(Float)floatValue;
if (type == int.class || type == Integer.class) return (T)(Integer)floatValue.intValue();
if (type == long.class || type == Long.class) return (T)(Long)floatValue.longValue();
if (type == double.class || type == Double.class) return (T)(Double)floatValue.doubleValue();
if (type == short.class || type == Short.class) return (T)(Short)floatValue.shortValue();
if (type == byte.class || type == Byte.class) return (T)(Byte)floatValue.byteValue();
} catch (NumberFormatException ignored) {
}
jsonData = String.valueOf(jsonData);
}
if (jsonData instanceof Boolean) jsonData = String.valueOf(jsonData);
if (jsonData instanceof String) {
String string = (String)jsonData;
if (type == null || type == String.class) return (T)jsonData;
try {
if (type == int.class || type == Integer.class) return (T)Integer.valueOf(string);
if (type == float.class || type == Float.class) return (T)Float.valueOf(string);
if (type == long.class || type == Long.class) return (T)Long.valueOf(string);
if (type == double.class || type == Double.class) return (T)Double.valueOf(string);
if (type == short.class || type == Short.class) return (T)Short.valueOf(string);
if (type == byte.class || type == Byte.class) return (T)Byte.valueOf(string);
} catch (NumberFormatException ignored) {
}
if (type == boolean.class || type == Boolean.class) return (T)Boolean.valueOf(string);
if (type == char.class || type == Character.class) return (T)(Character)string.charAt(0);
if (Enum.class.isAssignableFrom(type)) {
Object[] constants = type.getEnumConstants();
for (int i = 0, n = constants.length; i < n; i++)
if (string.equals(constants[i].toString())) return (T)constants[i];
}
if (type == CharSequence.class) return (T)string;
throw new SerializationException("Unable to convert value to required type: " + jsonData + " (" + type.getName() + ")");
}
return null;
}
private String convertToString (Object object) {
if (object instanceof Class) return ((Class)object).getName();
return String.valueOf(object);
}
private Object newInstance (Class type) {
try {
return type.newInstance();
} catch (Exception ex) {
try {
// Try a private constructor.
Constructor constructor = type.getDeclaredConstructor();
constructor.setAccessible(true);
return constructor.newInstance();
} catch (SecurityException ignored) {
} catch (NoSuchMethodException ignored) {
if (type.isArray())
throw new SerializationException("Encountered JSON object when expected array of type: " + type.getName(), ex);
else if (type.isMemberClass() && !Modifier.isStatic(type.getModifiers()))
throw new SerializationException("Class cannot be created (non-static member class): " + type.getName(), ex);
else
throw new SerializationException("Class cannot be created (missing no-arg constructor): " + type.getName(), ex);
} catch (Exception privateConstructorException) {
ex = privateConstructorException;
}
throw new SerializationException("Error constructing instance of class: " + type.getName(), ex);
}
}
public String prettyPrint (Object object) {
return prettyPrint(object, 0);
}
public String prettyPrint (String json) {
return prettyPrint(json, 0);
}
public String prettyPrint (Object object, int singleLineColumns) {
return prettyPrint(toJson(object), singleLineColumns);
}
public String prettyPrint (String json, int singleLineColumns) {
StringBuilder buffer = new StringBuilder(512);
prettyPrint(new JsonReader().parse(json), buffer, 0, singleLineColumns);
return buffer.toString();
}
private void prettyPrint (Object object, StringBuilder buffer, int indent, int singleLineColumns) {
if (object instanceof OrderedMap) {
OrderedMap<String, ?> map = (OrderedMap)object;
if (map.size == 0) {
buffer.append("{}");
} else {
boolean newLines = !isFlat(map);
int start = buffer.length();
outer:
while (true) {
buffer.append(newLines ? "{\n" : "{ ");
int i = 0;
for (String key : map.orderedKeys()) {
if (newLines) indent(indent, buffer);
buffer.append(outputType.quoteName(key));
buffer.append(": ");
prettyPrint(map.get(key), buffer, indent + 1, singleLineColumns);
if (i++ < map.size - 1) buffer.append(",");
buffer.append(newLines ? '\n' : ' ');
if (!newLines && buffer.length() - start > singleLineColumns) {
buffer.setLength(start);
newLines = true;
continue outer;
}
}
break;
}
if (newLines) indent(indent - 1, buffer);
buffer.append('}');
}
} else if (object instanceof Array) {
Array array = (Array)object;
if (array.size == 0) {
buffer.append("[]");
} else {
boolean newLines = !isFlat(array);
int start = buffer.length();
outer:
while (true) {
buffer.append(newLines ? "[\n" : "[ ");
for (int i = 0, n = array.size; i < n; i++) {
if (newLines) indent(indent, buffer);
prettyPrint(array.get(i), buffer, indent + 1, singleLineColumns);
if (i < array.size - 1) buffer.append(",");
buffer.append(newLines ? '\n' : ' ');
if (!newLines && buffer.length() - start > singleLineColumns) {
buffer.setLength(start);
newLines = true;
continue outer;
}
}
break;
}
if (newLines) indent(indent - 1, buffer);
buffer.append(']');
}
} else if (object instanceof String) {
buffer.append(outputType.quoteValue((String)object));
} else if (object instanceof Float) {
Float floatValue = (Float)object;
int intValue = floatValue.intValue();
buffer.append(floatValue - intValue == 0 ? intValue : object);
} else if (object instanceof Boolean) {
buffer.append(object);
} else if (object == null) {
buffer.append("null");
} else
throw new SerializationException("Unknown object type: " + object.getClass());
}
static private boolean isFlat (ObjectMap<?, ?> map) {
for (Entry entry : map.entries()) {
if (entry.value instanceof ObjectMap) return false;
if (entry.value instanceof Array) return false;
}
return true;
}
static private boolean isFlat (Array array) {
for (int i = 0, n = array.size; i < n; i++) {
Object value = array.get(i);
if (value instanceof ObjectMap) return false;
if (value instanceof Array) return false;
}
return true;
}
static private void indent (int count, StringBuilder buffer) {
for (int i = 0; i < count; i++)
buffer.append('\t');
}
static private class FieldMetadata {
Field field;
Class elementType;
public FieldMetadata (Field field) {
this.field = field;
Type genericType = field.getGenericType();
if (genericType instanceof ParameterizedType) {
Type[] actualTypes = ((ParameterizedType)genericType).getActualTypeArguments();
if (actualTypes.length == 1) {
Type actualType = actualTypes[0];
if (actualType instanceof Class)
elementType = (Class)actualType;
else if (actualType instanceof ParameterizedType)
elementType = (Class)((ParameterizedType)actualType).getRawType();
}
}
}
}
static public interface Serializer<T> {
public void write (Json json, T object, Class knownType);
public T read (Json json, Object jsonData, Class type);
}
static abstract public class ReadOnlySerializer<T> implements Serializer<T> {
public void write (Json json, T object, Class knownType) {
}
abstract public T read (Json json, Object jsonData, Class type);
}
static public interface Serializable {
public void write (Json json);
public void read (Json json, OrderedMap<String, Object> jsonData);
}
}
| gdx/src/com/badlogic/gdx/utils/Json.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.utils;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.JsonWriter.OutputType;
import com.badlogic.gdx.utils.ObjectMap.Entry;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.security.AccessControlException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** Reads/writes Java objects to/from JSON, automatically.
* @author Nathan Sweet */
public class Json {
private static final boolean debug = false;
private JsonWriter writer;
private String typeName = "class";
private boolean usePrototypes = true;
private OutputType outputType;
private final ObjectMap<Class, ObjectMap<String, FieldMetadata>> typeToFields = new ObjectMap();
private final ObjectMap<String, Class> tagToClass = new ObjectMap();
private final ObjectMap<Class, String> classToTag = new ObjectMap();
private final ObjectMap<Class, Serializer> classToSerializer = new ObjectMap();
private final ObjectMap<Class, Object[]> classToDefaultValues = new ObjectMap();
private boolean ignoreUnknownFields;
public Json () {
outputType = OutputType.minimal;
}
public Json (OutputType outputType) {
this.outputType = outputType;
}
public void setIgnoreUnknownFields (boolean ignoreUnknownFields) {
this.ignoreUnknownFields = ignoreUnknownFields;
}
public void setOutputType (OutputType outputType) {
this.outputType = outputType;
}
public void addClassTag (String tag, Class type) {
tagToClass.put(tag, type);
classToTag.put(type, tag);
}
public Class getClass (String tag) {
Class type = tagToClass.get(tag);
if (type != null) return type;
try {
return Class.forName(tag);
} catch (ClassNotFoundException ex) {
throw new SerializationException(ex);
}
}
public String getTag (Class type) {
String tag = classToTag.get(type);
if (tag != null) return tag;
return type.getName();
}
/** Sets the name of the JSON field to store the Java class name or class tag when required to avoid ambiguity during
* deserialization. Set to null to never output this information, but be warned that deserialization may fail. */
public void setTypeName (String typeName) {
this.typeName = typeName;
}
public <T> void setSerializer (Class<T> type, Serializer<T> serializer) {
classToSerializer.put(type, serializer);
}
public <T> Serializer<T> getSerializer (Class<T> type) {
return classToSerializer.get(type);
}
public void setUsePrototypes (boolean usePrototypes) {
this.usePrototypes = usePrototypes;
}
public void setElementType (Class type, String fieldName, Class elementType) {
ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
if (fields == null) fields = cacheFields(type);
FieldMetadata metadata = fields.get(fieldName);
if (metadata == null) throw new SerializationException("Field not found: " + fieldName + " (" + type.getName() + ")");
metadata.elementType = elementType;
}
private ObjectMap<String, FieldMetadata> cacheFields (Class type) {
ArrayList<Field> allFields = new ArrayList();
Class nextClass = type;
while (nextClass != Object.class) {
Collections.addAll(allFields, nextClass.getDeclaredFields());
nextClass = nextClass.getSuperclass();
}
ObjectMap<String, FieldMetadata> nameToField = new ObjectMap();
for (int i = 0, n = allFields.size(); i < n; i++) {
Field field = allFields.get(i);
int modifiers = field.getModifiers();
if (Modifier.isTransient(modifiers)) continue;
if (Modifier.isStatic(modifiers)) continue;
if (field.isSynthetic()) continue;
if (!field.isAccessible()) {
try {
field.setAccessible(true);
} catch (AccessControlException ex) {
continue;
}
}
nameToField.put(field.getName(), new FieldMetadata(field));
}
typeToFields.put(type, nameToField);
return nameToField;
}
public String toJson (Object object) {
return toJson(object, object == null ? null : object.getClass(), (Class)null);
}
public String toJson (Object object, Class knownType) {
return toJson(object, knownType, (Class)null);
}
/** @param knownType May be null if the type is unknown.
* @param elementType May be null if the type is unknown. */
public String toJson (Object object, Class knownType, Class elementType) {
StringWriter buffer = new StringWriter();
toJson(object, knownType, elementType, buffer);
return buffer.toString();
}
public void toJson (Object object, FileHandle file) {
toJson(object, object == null ? null : object.getClass(), null, file);
}
/** @param knownType May be null if the type is unknown. */
public void toJson (Object object, Class knownType, FileHandle file) {
toJson(object, knownType, null, file);
}
/** @param knownType May be null if the type is unknown.
* @param elementType May be null if the type is unknown. */
public void toJson (Object object, Class knownType, Class elementType, FileHandle file) {
Writer writer = null;
try {
writer = file.writer(false);
toJson(object, knownType, elementType, writer);
} catch (Exception ex) {
throw new SerializationException("Error writing file: " + file, ex);
} finally {
try {
if (writer != null) writer.close();
} catch (IOException ignored) {
}
}
}
public void toJson (Object object, Writer writer) {
toJson(object, object == null ? null : object.getClass(), null, writer);
}
/** @param knownType May be null if the type is unknown. */
public void toJson (Object object, Class knownType, Writer writer) {
toJson(object, knownType, null, writer);
}
/** @param knownType May be null if the type is unknown.
* @param elementType May be null if the type is unknown. */
public void toJson (Object object, Class knownType, Class elementType, Writer writer) {
setWriter(writer);
try {
writeValue(object, knownType, elementType);
} finally {
this.writer = null;
}
}
/** Sets the writer where JSON output will go. This is only necessary when not using the toJson methods. */
public void setWriter (Writer writer) {
if (!(writer instanceof JsonWriter)) writer = new JsonWriter(writer);
this.writer = (JsonWriter)writer;
this.writer.setOutputType(outputType);
}
public JsonWriter getWriter () {
return writer;
}
public void writeFields (Object object) {
Class type = object.getClass();
Object[] defaultValues = getDefaultValues(type);
ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
if (fields == null) fields = cacheFields(type);
int i = 0;
for (FieldMetadata metadata : fields.values()) {
Field field = metadata.field;
try {
Object value = field.get(object);
if (defaultValues != null) {
Object defaultValue = defaultValues[i++];
if (value == null && defaultValue == null) continue;
if (value != null && defaultValue != null && value.equals(defaultValue)) continue;
}
if (debug) System.out.println("Writing field: " + field.getName() + " (" + type.getName() + ")");
writer.name(field.getName());
writeValue(value, field.getType(), metadata.elementType);
} catch (IllegalAccessException ex) {
throw new SerializationException("Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
} catch (SerializationException ex) {
ex.addTrace(field + " (" + type.getName() + ")");
throw ex;
} catch (Exception runtimeEx) {
SerializationException ex = new SerializationException(runtimeEx);
ex.addTrace(field + " (" + type.getName() + ")");
throw ex;
}
}
}
private Object[] getDefaultValues (Class type) {
if (!usePrototypes) return null;
if (classToDefaultValues.containsKey(type)) return classToDefaultValues.get(type);
Object object;
try {
object = newInstance(type);
} catch (Exception ex) {
classToDefaultValues.put(type, null);
return null;
}
ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
if (fields == null) fields = cacheFields(type);
Object[] values = new Object[fields.size];
classToDefaultValues.put(type, values);
int i = 0;
for (FieldMetadata metadata : fields.values()) {
Field field = metadata.field;
try {
values[i++] = field.get(object);
} catch (IllegalAccessException ex) {
throw new SerializationException("Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
} catch (SerializationException ex) {
ex.addTrace(field + " (" + type.getName() + ")");
throw ex;
} catch (RuntimeException runtimeEx) {
SerializationException ex = new SerializationException(runtimeEx);
ex.addTrace(field + " (" + type.getName() + ")");
throw ex;
}
}
return values;
}
public void writeField (Object object, String name) {
writeField(object, name, name, null);
}
/** @param elementType May be null if the type is unknown. */
public void writeField (Object object, String name, Class elementType) {
writeField(object, name, name, elementType);
}
public void writeField (Object object, String fieldName, String jsonName) {
writeField(object, fieldName, jsonName, null);
}
/** @param elementType May be null if the type is unknown. */
public void writeField (Object object, String fieldName, String jsonName, Class elementType) {
Class type = object.getClass();
ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
if (fields == null) fields = cacheFields(type);
FieldMetadata metadata = fields.get(fieldName);
if (metadata == null) throw new SerializationException("Field not found: " + fieldName + " (" + type.getName() + ")");
Field field = metadata.field;
if (elementType == null) elementType = metadata.elementType;
try {
if (debug) System.out.println("Writing field: " + field.getName() + " (" + type.getName() + ")");
writer.name(jsonName);
writeValue(field.get(object), field.getType(), elementType);
} catch (IllegalAccessException ex) {
throw new SerializationException("Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
} catch (SerializationException ex) {
ex.addTrace(field + " (" + type.getName() + ")");
throw ex;
} catch (Exception runtimeEx) {
SerializationException ex = new SerializationException(runtimeEx);
ex.addTrace(field + " (" + type.getName() + ")");
throw ex;
}
}
/** @param value May be null. */
public void writeValue (String name, Object value) {
try {
writer.name(name);
} catch (IOException ex) {
throw new SerializationException(ex);
}
if (value == null)
writeValue(value, null, null);
else
writeValue(value, value.getClass(), null);
}
/** @param value May be null.
* @param knownType May be null if the type is unknown. */
public void writeValue (String name, Object value, Class knownType) {
try {
writer.name(name);
} catch (IOException ex) {
throw new SerializationException(ex);
}
writeValue(value, knownType, null);
}
/** @param value May be null.
* @param knownType May be null if the type is unknown.
* @param elementType May be null if the type is unknown. */
public void writeValue (String name, Object value, Class knownType, Class elementType) {
try {
writer.name(name);
} catch (IOException ex) {
throw new SerializationException(ex);
}
writeValue(value, knownType, elementType);
}
/** @param value May be null. */
public void writeValue (Object value) {
if (value == null)
writeValue(value, null, null);
else
writeValue(value, value.getClass(), null);
}
/** @param value May be null.
* @param knownType May be null if the type is unknown. */
public void writeValue (Object value, Class knownType) {
writeValue(value, knownType, null);
}
/** @param value May be null.
* @param knownType May be null if the type is unknown.
* @param elementType May be null if the type is unknown. */
public void writeValue (Object value, Class knownType, Class elementType) {
try {
if (value == null) {
writer.value(null);
return;
}
Class actualType = value.getClass();
if (actualType.isPrimitive() || actualType == String.class || actualType == Integer.class || actualType == Boolean.class
|| actualType == Float.class || actualType == Long.class || actualType == Double.class || actualType == Short.class
|| actualType == Byte.class || actualType == Character.class) {
writer.value(value);
return;
}
if (value instanceof Serializable) {
writeObjectStart(actualType, knownType);
((Serializable)value).write(this);
writeObjectEnd();
return;
}
Serializer serializer = classToSerializer.get(actualType);
if (serializer != null) {
serializer.write(this, value, knownType);
return;
}
if (value instanceof Array) {
if (knownType != null && actualType != knownType)
throw new SerializationException("Serialization of an Array other than the known type is not supported.\n"
+ "Known type: " + knownType + "\nActual type: " + actualType);
writeArrayStart();
Array array = (Array)value;
for (int i = 0, n = array.size; i < n; i++)
writeValue(array.get(i), elementType, null);
writeArrayEnd();
return;
}
if (value instanceof Collection) {
if (knownType != null && actualType != knownType && actualType != ArrayList.class)
throw new SerializationException("Serialization of a Collection other than the known type is not supported.\n"
+ "Known type: " + knownType + "\nActual type: " + actualType);
writeArrayStart();
for (Object item : (Collection)value)
writeValue(item, elementType, null);
writeArrayEnd();
return;
}
if (actualType.isArray()) {
if (elementType == null) elementType = actualType.getComponentType();
int length = java.lang.reflect.Array.getLength(value);
writeArrayStart();
for (int i = 0; i < length; i++)
writeValue(java.lang.reflect.Array.get(value, i), elementType, null);
writeArrayEnd();
return;
}
if (value instanceof OrderedMap) {
if (knownType == null) knownType = OrderedMap.class;
writeObjectStart(actualType, knownType);
OrderedMap map = (OrderedMap)value;
for (Object key : map.orderedKeys()) {
writer.name(convertToString(key));
writeValue(map.get(key), elementType, null);
}
writeObjectEnd();
return;
}
if (value instanceof ArrayMap) {
if (knownType == null) knownType = ArrayMap.class;
writeObjectStart(actualType, knownType);
ArrayMap map = (ArrayMap)value;
for (int i = 0, n = map.size; i < n; i++) {
writer.name(convertToString(map.keys[i]));
writeValue(map.values[i], elementType, null);
}
writeObjectEnd();
return;
}
if (value instanceof ObjectMap) {
if (knownType == null) knownType = OrderedMap.class;
writeObjectStart(actualType, knownType);
for (Entry entry : ((ObjectMap<?, ?>)value).entries()) {
writer.name(convertToString(entry.key));
writeValue(entry.value, elementType, null);
}
writeObjectEnd();
return;
}
if (value instanceof Map) {
if (knownType == null) knownType = OrderedMap.class;
writeObjectStart(actualType, knownType);
for (Map.Entry entry : ((Map<?, ?>)value).entrySet()) {
writer.name(convertToString(entry.getKey()));
writeValue(entry.getValue(), elementType, null);
}
writeObjectEnd();
return;
}
if (Enum.class.isAssignableFrom(actualType)) {
writer.value(value);
return;
}
writeObjectStart(actualType, knownType);
writeFields(value);
writeObjectEnd();
} catch (IOException ex) {
throw new SerializationException(ex);
}
}
public void writeObjectStart (String name) {
try {
writer.name(name);
} catch (IOException ex) {
throw new SerializationException(ex);
}
writeObjectStart();
}
/** @param knownType May be null if the type is unknown. */
public void writeObjectStart (String name, Class actualType, Class knownType) {
try {
writer.name(name);
} catch (IOException ex) {
throw new SerializationException(ex);
}
writeObjectStart(actualType, knownType);
}
public void writeObjectStart () {
try {
writer.object();
} catch (IOException ex) {
throw new SerializationException(ex);
}
}
/** @param knownType May be null if the type is unknown. */
public void writeObjectStart (Class actualType, Class knownType) {
try {
writer.object();
} catch (IOException ex) {
throw new SerializationException(ex);
}
if (knownType == null || knownType != actualType) writeType(actualType);
}
public void writeObjectEnd () {
try {
writer.pop();
} catch (IOException ex) {
throw new SerializationException(ex);
}
}
public void writeArrayStart (String name) {
try {
writer.name(name);
writer.array();
} catch (IOException ex) {
throw new SerializationException(ex);
}
}
public void writeArrayStart () {
try {
writer.array();
} catch (IOException ex) {
throw new SerializationException(ex);
}
}
public void writeArrayEnd () {
try {
writer.pop();
} catch (IOException ex) {
throw new SerializationException(ex);
}
}
public void writeType (Class type) {
if (typeName == null) return;
String className = classToTag.get(type);
if (className == null) className = type.getName();
try {
writer.set(typeName, className);
} catch (IOException ex) {
throw new SerializationException(ex);
}
if (debug) System.out.println("Writing type: " + type.getName());
}
/** @param type May be null if the type is unknown.
* @return May be null. */
public <T> T fromJson (Class<T> type, Reader reader) {
return (T)readValue(type, null, new JsonReader().parse(reader));
}
/** @param type May be null if the type is unknown.
* @param elementType May be null if the type is unknown.
* @return May be null. */
public <T> T fromJson (Class<T> type, Class elementType, Reader reader) {
return (T)readValue(type, elementType, new JsonReader().parse(reader));
}
/** @param type May be null if the type is unknown.
* @return May be null. */
public <T> T fromJson (Class<T> type, InputStream input) {
return (T)readValue(type, null, new JsonReader().parse(input));
}
/** @param type May be null if the type is unknown.
* @param elementType May be null if the type is unknown.
* @return May be null. */
public <T> T fromJson (Class<T> type, Class elementType, InputStream input) {
return (T)readValue(type, elementType, new JsonReader().parse(input));
}
/** @param type May be null if the type is unknown.
* @return May be null. */
public <T> T fromJson (Class<T> type, FileHandle file) {
try {
return (T)readValue(type, null, new JsonReader().parse(file));
} catch (Exception ex) {
throw new SerializationException("Error reading file: " + file, ex);
}
}
/** @param type May be null if the type is unknown.
* @param elementType May be null if the type is unknown.
* @return May be null. */
public <T> T fromJson (Class<T> type, Class elementType, FileHandle file) {
try {
return (T)readValue(type, elementType, new JsonReader().parse(file));
} catch (Exception ex) {
throw new SerializationException("Error reading file: " + file, ex);
}
}
/** @param type May be null if the type is unknown.
* @return May be null. */
public <T> T fromJson (Class<T> type, char[] data, int offset, int length) {
return (T)readValue(type, null, new JsonReader().parse(data, offset, length));
}
/** @param type May be null if the type is unknown.
* @param elementType May be null if the type is unknown.
* @return May be null. */
public <T> T fromJson (Class<T> type, Class elementType, char[] data, int offset, int length) {
return (T)readValue(type, elementType, new JsonReader().parse(data, offset, length));
}
/** @param type May be null if the type is unknown.
* @return May be null. */
public <T> T fromJson (Class<T> type, String json) {
return (T)readValue(type, null, new JsonReader().parse(json));
}
/** @param type May be null if the type is unknown.
* @return May be null. */
public <T> T fromJson (Class<T> type, Class elementType, String json) {
return (T)readValue(type, elementType, new JsonReader().parse(json));
}
public void readField (Object object, String name, Object jsonData) {
readField(object, name, name, null, jsonData);
}
public void readField (Object object, String name, Class elementType, Object jsonData) {
readField(object, name, name, elementType, jsonData);
}
public void readField (Object object, String fieldName, String jsonName, Object jsonData) {
readField(object, fieldName, jsonName, null, jsonData);
}
/** @param elementType May be null if the type is unknown. */
public void readField (Object object, String fieldName, String jsonName, Class elementType, Object jsonData) {
OrderedMap jsonMap = (OrderedMap)jsonData;
Class type = object.getClass();
ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
if (fields == null) fields = cacheFields(type);
FieldMetadata metadata = fields.get(fieldName);
if (metadata == null) throw new SerializationException("Field not found: " + fieldName + " (" + type.getName() + ")");
Field field = metadata.field;
Object jsonValue = jsonMap.get(jsonName);
if (jsonValue == null) return;
if (elementType == null) elementType = metadata.elementType;
try {
field.set(object, readValue(field.getType(), elementType, jsonValue));
} catch (IllegalAccessException ex) {
throw new SerializationException("Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
} catch (SerializationException ex) {
ex.addTrace(field.getName() + " (" + type.getName() + ")");
throw ex;
} catch (RuntimeException runtimeEx) {
SerializationException ex = new SerializationException(runtimeEx);
ex.addTrace(field.getName() + " (" + type.getName() + ")");
throw ex;
}
}
public void readFields (Object object, Object jsonData) {
OrderedMap<String, Object> jsonMap = (OrderedMap)jsonData;
Class type = object.getClass();
ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
if (fields == null) fields = cacheFields(type);
for (Entry<String, Object> entry : jsonMap.entries()) {
FieldMetadata metadata = fields.get(entry.key);
if (metadata == null) {
if (ignoreUnknownFields) {
if (debug) System.out.println("Ignoring unknown field: " + entry.key + " (" + type.getName() + ")");
continue;
} else
throw new SerializationException("Field not found: " + entry.key + " (" + type.getName() + ")");
}
Field field = metadata.field;
if (entry.value == null) continue;
try {
field.set(object, readValue(field.getType(), metadata.elementType, entry.value));
} catch (IllegalAccessException ex) {
throw new SerializationException("Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
} catch (SerializationException ex) {
ex.addTrace(field.getName() + " (" + type.getName() + ")");
throw ex;
} catch (RuntimeException runtimeEx) {
SerializationException ex = new SerializationException(runtimeEx);
ex.addTrace(field.getName() + " (" + type.getName() + ")");
throw ex;
}
}
}
/** @param type May be null if the type is unknown.
* @return May be null. */
public <T> T readValue (String name, Class<T> type, Object jsonData) {
OrderedMap jsonMap = (OrderedMap)jsonData;
return (T)readValue(type, null, jsonMap.get(name));
}
/** @param type May be null if the type is unknown.
* @return May be null. */
public <T> T readValue (String name, Class<T> type, T defaultValue, Object jsonData) {
OrderedMap jsonMap = (OrderedMap)jsonData;
Object jsonValue = jsonMap.get(name);
if (jsonValue == null) return defaultValue;
return (T)readValue(type, null, jsonValue);
}
/** @param type May be null if the type is unknown.
* @param elementType May be null if the type is unknown.
* @return May be null. */
public <T> T readValue (String name, Class<T> type, Class elementType, Object jsonData) {
OrderedMap jsonMap = (OrderedMap)jsonData;
return (T)readValue(type, elementType, jsonMap.get(name));
}
/** @param type May be null if the type is unknown.
* @param elementType May be null if the type is unknown.
* @return May be null. */
public <T> T readValue (String name, Class<T> type, Class elementType, T defaultValue, Object jsonData) {
OrderedMap jsonMap = (OrderedMap)jsonData;
Object jsonValue = jsonMap.get(name);
if (jsonValue == null) return defaultValue;
return (T)readValue(type, elementType, jsonValue);
}
/** @param type May be null if the type is unknown.
* @param elementType May be null if the type is unknown.
* @return May be null. */
public <T> T readValue (Class<T> type, Class elementType, T defaultValue, Object jsonData) {
return (T)readValue(type, elementType, jsonData);
}
/** @param type May be null if the type is unknown.
* @return May be null. */
public <T> T readValue (Class<T> type, Object jsonData) {
return (T)readValue(type, null, jsonData);
}
/** @param type May be null if the type is unknown.
* @param elementType May be null if the type is unknown.
* @return May be null. */
public <T> T readValue (Class<T> type, Class elementType, Object jsonData) {
if (jsonData == null) return null;
if (jsonData instanceof OrderedMap) {
OrderedMap<String, Object> jsonMap = (OrderedMap)jsonData;
String className = typeName == null ? null : (String)jsonMap.remove(typeName);
if (className != null) {
try {
type = (Class<T>)Class.forName(className);
} catch (ClassNotFoundException ex) {
type = tagToClass.get(className);
if (type == null) throw new SerializationException(ex);
}
}
Object object;
if (type != null) {
Serializer serializer = classToSerializer.get(type);
if (serializer != null) return (T)serializer.read(this, jsonMap, type);
object = newInstance(type);
if (object instanceof Serializable) {
((Serializable)object).read(this, jsonMap);
return (T)object;
}
if (object instanceof HashMap) {
HashMap result = (HashMap)object;
for (Entry entry : jsonMap.entries())
result.put(entry.key, readValue(elementType, null, entry.value));
return (T)result;
}
} else
object = new OrderedMap();
if (object instanceof ObjectMap) {
ObjectMap result = (ObjectMap)object;
for (String key : jsonMap.orderedKeys())
result.put(key, readValue(elementType, null, jsonMap.get(key)));
return (T)result;
}
readFields(object, jsonMap);
return (T)object;
}
if (type != null) {
Serializer serializer = classToSerializer.get(type);
if (serializer != null) return (T)serializer.read(this, jsonData, type);
}
if (jsonData instanceof Array) {
Array array = (Array)jsonData;
if (type == null || Array.class.isAssignableFrom(type)) {
Array newArray = type == null ? new Array() : (Array)newInstance(type);
newArray.ensureCapacity(array.size);
for (int i = 0, n = array.size; i < n; i++)
newArray.add(readValue(elementType, null, array.get(i)));
return (T)newArray;
}
if (List.class.isAssignableFrom(type)) {
List newArray = type == null ? new ArrayList(array.size) : (List)newInstance(type);
for (int i = 0, n = array.size; i < n; i++)
newArray.add(readValue(elementType, null, array.get(i)));
return (T)newArray;
}
if (type.isArray()) {
Class componentType = type.getComponentType();
if (elementType == null) elementType = componentType;
Object newArray = java.lang.reflect.Array.newInstance(componentType, array.size);
for (int i = 0, n = array.size; i < n; i++)
java.lang.reflect.Array.set(newArray, i, readValue(elementType, null, array.get(i)));
return (T)newArray;
}
throw new SerializationException("Unable to convert value to required type: " + jsonData + " (" + type.getName() + ")");
}
if (jsonData instanceof Float) {
Float floatValue = (Float)jsonData;
try {
if (type == null || type == float.class || type == Float.class) return (T)(Float)floatValue;
if (type == int.class || type == Integer.class) return (T)(Integer)floatValue.intValue();
if (type == long.class || type == Long.class) return (T)(Long)floatValue.longValue();
if (type == double.class || type == Double.class) return (T)(Double)floatValue.doubleValue();
if (type == short.class || type == Short.class) return (T)(Short)floatValue.shortValue();
if (type == byte.class || type == Byte.class) return (T)(Byte)floatValue.byteValue();
} catch (NumberFormatException ignored) {
}
jsonData = String.valueOf(jsonData);
}
if (jsonData instanceof Boolean) jsonData = String.valueOf(jsonData);
if (jsonData instanceof String) {
String string = (String)jsonData;
if (type == null || type == String.class) return (T)jsonData;
try {
if (type == int.class || type == Integer.class) return (T)Integer.valueOf(string);
if (type == float.class || type == Float.class) return (T)Float.valueOf(string);
if (type == long.class || type == Long.class) return (T)Long.valueOf(string);
if (type == double.class || type == Double.class) return (T)Double.valueOf(string);
if (type == short.class || type == Short.class) return (T)Short.valueOf(string);
if (type == byte.class || type == Byte.class) return (T)Byte.valueOf(string);
} catch (NumberFormatException ignored) {
}
if (type == boolean.class || type == Boolean.class) return (T)Boolean.valueOf(string);
if (type == char.class || type == Character.class) return (T)(Character)string.charAt(0);
if (Enum.class.isAssignableFrom(type)) {
Object[] constants = type.getEnumConstants();
for (int i = 0, n = constants.length; i < n; i++)
if (string.equals(constants[i].toString())) return (T)constants[i];
}
if (type == CharSequence.class) return (T)string;
throw new SerializationException("Unable to convert value to required type: " + jsonData + " (" + type.getName() + ")");
}
return null;
}
private String convertToString (Object object) {
if (object instanceof Class) return ((Class)object).getName();
return String.valueOf(object);
}
private Object newInstance (Class type) {
try {
return type.newInstance();
} catch (Exception ex) {
try {
// Try a private constructor.
Constructor constructor = type.getDeclaredConstructor();
constructor.setAccessible(true);
return constructor.newInstance();
} catch (SecurityException ignored) {
} catch (NoSuchMethodException ignored) {
if (type.isArray())
throw new SerializationException("Encountered JSON object when expected array of type: " + type.getName(), ex);
else if (type.isMemberClass() && !Modifier.isStatic(type.getModifiers()))
throw new SerializationException("Class cannot be created (non-static member class): " + type.getName(), ex);
else
throw new SerializationException("Class cannot be created (missing no-arg constructor): " + type.getName(), ex);
} catch (Exception privateConstructorException) {
ex = privateConstructorException;
}
throw new SerializationException("Error constructing instance of class: " + type.getName(), ex);
}
}
public String prettyPrint (Object object) {
return prettyPrint(object, 0);
}
public String prettyPrint (String json) {
return prettyPrint(json, 0);
}
public String prettyPrint (Object object, int singleLineColumns) {
return prettyPrint(toJson(object), singleLineColumns);
}
public String prettyPrint (String json, int singleLineColumns) {
StringBuilder buffer = new StringBuilder(512);
prettyPrint(new JsonReader().parse(json), buffer, 0, singleLineColumns);
return buffer.toString();
}
private void prettyPrint (Object object, StringBuilder buffer, int indent, int singleLineColumns) {
if (object instanceof OrderedMap) {
OrderedMap<String, ?> map = (OrderedMap)object;
if (map.size == 0) {
buffer.append("{}");
} else {
boolean newLines = !isFlat(map);
int start = buffer.length();
outer:
while (true) {
buffer.append(newLines ? "{\n" : "{ ");
int i = 0;
for (String key : map.orderedKeys()) {
if (newLines) indent(indent, buffer);
buffer.append(outputType.quoteName(key));
buffer.append(": ");
prettyPrint(map.get(key), buffer, indent + 1, singleLineColumns);
if (i++ < map.size - 1) buffer.append(",");
buffer.append(newLines ? '\n' : ' ');
if (!newLines && buffer.length() - start > singleLineColumns) {
buffer.setLength(start);
newLines = true;
continue outer;
}
}
break;
}
if (newLines) indent(indent - 1, buffer);
buffer.append('}');
}
} else if (object instanceof Array) {
Array array = (Array)object;
if (array.size == 0) {
buffer.append("[]");
} else {
boolean newLines = !isFlat(array);
int start = buffer.length();
outer:
while (true) {
buffer.append(newLines ? "[\n" : "[ ");
for (int i = 0, n = array.size; i < n; i++) {
if (newLines) indent(indent, buffer);
prettyPrint(array.get(i), buffer, indent + 1, singleLineColumns);
if (i < array.size - 1) buffer.append(",");
buffer.append(newLines ? '\n' : ' ');
if (!newLines && buffer.length() - start > singleLineColumns) {
buffer.setLength(start);
newLines = true;
continue outer;
}
}
break;
}
if (newLines) indent(indent - 1, buffer);
buffer.append(']');
}
} else if (object instanceof String) {
buffer.append(outputType.quoteValue((String)object));
} else if (object instanceof Float) {
Float floatValue = (Float)object;
int intValue = floatValue.intValue();
buffer.append(floatValue - intValue == 0 ? intValue : object);
} else if (object instanceof Boolean) {
buffer.append(object);
} else if (object == null) {
buffer.append("null");
} else
throw new SerializationException("Unknown object type: " + object.getClass());
}
static private boolean isFlat (ObjectMap<?, ?> map) {
for (Entry entry : map.entries()) {
if (entry.value instanceof ObjectMap) return false;
if (entry.value instanceof Array) return false;
}
return true;
}
static private boolean isFlat (Array array) {
for (int i = 0, n = array.size; i < n; i++) {
Object value = array.get(i);
if (value instanceof ObjectMap) return false;
if (value instanceof Array) return false;
}
return true;
}
static private void indent (int count, StringBuilder buffer) {
for (int i = 0; i < count; i++)
buffer.append('\t');
}
static private class FieldMetadata {
Field field;
Class elementType;
public FieldMetadata (Field field) {
this.field = field;
Type genericType = field.getGenericType();
if (genericType instanceof ParameterizedType) {
Type[] actualTypes = ((ParameterizedType)genericType).getActualTypeArguments();
if (actualTypes.length == 1) {
Type actualType = actualTypes[0];
if (actualType instanceof Class)
elementType = (Class)actualType;
else if (actualType instanceof ParameterizedType)
elementType = (Class)((ParameterizedType)actualType).getRawType();
}
}
}
}
static public interface Serializer<T> {
public void write (Json json, T object, Class knownType);
public T read (Json json, Object jsonData, Class type);
}
static abstract public class ReadOnlySerializer<T> implements Serializer<T> {
public void write (Json json, T object, Class knownType) {
}
abstract public T read (Json json, Object jsonData, Class type);
}
static public interface Serializable {
public void write (Json json);
public void read (Json json, OrderedMap<String, Object> jsonData);
}
}
| Close writer.
| gdx/src/com/badlogic/gdx/utils/Json.java | Close writer. | <ide><path>dx/src/com/badlogic/gdx/utils/Json.java
<ide> try {
<ide> writeValue(object, knownType, elementType);
<ide> } finally {
<add> try {
<add> this.writer.close();
<add> } catch (IOException ignored) {
<add> }
<ide> this.writer = null;
<ide> }
<ide> } |
|
JavaScript | agpl-3.0 | 01b495694a465a94b3512a32784ee30774c812ef | 0 | veo-labs/openveo-publish,veo-labs/openveo-publish,veo-labs/openveo-publish | 'use strict';
/**
* @module publish
*/
var util = require('util');
var events = require('events');
var path = require('path');
var shortid = require('shortid');
var openVeoApi = require('@openveo/api');
var Package = process.requirePublish('app/server/packages/Package.js');
var packageFactory = process.requirePublish('app/server/packages/packageFactory.js');
var ERRORS = process.requirePublish('app/server/packages/errors.js');
var STATES = process.requirePublish('app/server/packages/states.js');
var PublishError = process.requirePublish('app/server/PublishError.js');
var fileSystem = openVeoApi.fileSystem;
var acceptedPackagesExtensions = [fileSystem.FILE_TYPES.TAR, fileSystem.FILE_TYPES.MP4];
var publishManager;
/**
* Fired when an error occurred while processing a package.
*
* @event error
* @param {Error} The error
*/
/**
* Fired when a package process has succeed.
*
* @event complete
* @param {Object} The processed package
*/
/**
* Fired when a media in error restarts.
*
* @event retry
* @param {Object} The media
*/
/**
* Fired when a media stuck in "waiting for upload" state starts uploading.
*
* @event upload
* @param {Object} The media
*/
/**
* Fired when media state has changed.
*
* @event stateChanged
* @param {Object} The media
*/
/**
* Defines the PublishManager which handles the media publication's process.
*
* Media publications are handled in parallel. Media publication's process can be
* different regarding the type of the media.
*
* @example
* var coreApi = process.api.getCoreApi();
* var database = coreApi.getDatabase();
* var PublishManager = process.requirePublish('app/server/PublishManager.js');
* var videoModel = new VideoModel(null, new VideoProvider(database), new PropertyProvider(database));
* var publishManager = new PublishManager(videoModel, 5);
*
* // Listen publish manager's errors
* publishManager.on('error', function(error) {
* // Do something
* });
*
* // Listen to publish manager's end of processing for a media
* publishManager.on('complete', function(mediaPackage){
* // Do something
* });
*
* // Listen to publish manager's event informing that a media processing is retrying
* publishManager.on('retry', function(mediaPackage) {
* // Do something
* });
*
* // Listen to publish manager's event informing that a media, waiting for upload, starts uploading
* publishManager.on('upload', function(mediaPackage) {
* // Do something
* });
*
* publishManager.publish({
* type: 'youtube', // The media platform to use for this media
* originalPackagePath: '/home/openveo/medias/media-package.tar', // Path of the media package
* originalFileName: 'media-package' // File name without extension
* });
*
* @class PublishManager
* @constructor
* @param {VideoModel} videoModel The videoModel
* @param {Number} [maxConcurrentPackage=3] The maximum number of medias to treat in parallel
*/
function PublishManager(videoModel, maxConcurrentPackage) {
if (publishManager)
throw new Error('PublishManager already instanciated, use get method instead');
Object.defineProperties(this, {
/**
* Medias waiting to be processed.
*
* @property queue
* @type Array
* @final
*/
queue: {value: []},
/**
* Medias being processed.
*
* @property pendingPackages
* @type Array
* @final
*/
pendingPackages: {value: []},
/**
* Video model.
*
* @property videoModel
* @type VideoModel
* @final
*/
videoModel: {value: videoModel},
/**
* Maximum number of medias to treat in parallel.
*
* @property maxConcurrentPackage
* @type Number
* @final
*/
maxConcurrentPackage: {value: maxConcurrentPackage || 3}
});
}
util.inherits(PublishManager, events.EventEmitter);
module.exports = PublishManager;
/**
* Removes a media from pending medias.
*
* @method removeFromPending
* @private
* @param {Object} mediaPackage The media package to remove
*/
function removeFromPending(mediaPackage) {
for (var i = 0; i < this.pendingPackages.length; i++) {
if (this.pendingPackages[i]['id'] === mediaPackage.id) {
this.pendingPackages.splice(i, 1);
break;
}
}
for (var j = 0; j < this.pendingPackages.length; j++) {
if (this.pendingPackages[j]['originalFileName'] === mediaPackage.originalFileName) {
this.pendingPackages.splice(j, 1);
break;
}
}
process.logger.debug('Package ' + mediaPackage.id + ' from ' +
mediaPackage.originalFileName + ' is removed from pendingPackages');
}
/**
* Handles media error event.
*
* @method onError
* @private
* @param {Error} error The error
* @param {Object} mediaPackage The media on error
*/
function onError(error, mediaPackage) {
// Remove media from pending medias
removeFromPending.call(this, mediaPackage);
// Publish pending media from FIFO queue
if (this.queue.length)
this.publish(this.queue.shift(0));
// Add media id to the error message
if (error)
error.message += ' (' + mediaPackage.id + ')';
this.emit('error', error, error.code);
}
/**
* Handles media complete event.
*
* @method onComplete
* @private
* @param {Object} mediaPackage The package on error
*/
function onComplete(mediaPackage) {
// Remove package from pending packages
removeFromPending.call(this, mediaPackage);
// Publish pending package from FIFO queue
if (this.queue.length)
this.publish(this.queue.shift(0));
this.emit('complete', mediaPackage);
}
/**
* Creates a media package manager corresponding to the media type.
*
* @method createMediaPackageManager
* @private
* @param {Object} mediaPackage The media to manage
* @return {Package} A media package manager
*/
function createMediaPackageManager(mediaPackage) {
var self = this;
var mediaPackageManager = packageFactory.get(mediaPackage.packageType, mediaPackage);
// Handle errors from media package manager
mediaPackageManager.on('error', function(error) {
onError.call(self, error, mediaPackage);
});
// Handle complete events from media package manager
mediaPackageManager.on('complete', function(completePackage) {
onComplete.call(self, completePackage);
});
// Handle stateChanged events from media package manager
mediaPackageManager.on('stateChanged', function(mediaPackage) {
self.emit('stateChanged', mediaPackage);
});
return mediaPackageManager;
}
/**
* Adds media package to the list of pending packages.
*
* @method addPackage
* @private
* @param {Object} mediaPackage The media package to add to pending packages
* @return {Boolean} true if the media package is successfully added to pending packages
* false if it has been added to queue
*/
function addPackage(mediaPackage) {
process.logger.debug('Actually ' + this.pendingPackages.length + ' pending packages');
var idAllreadyPending = this.pendingPackages.filter(function(pendingPackage) {
return mediaPackage.originalFileName === pendingPackage.originalFileName;
});
// Too much pending packages
if (this.pendingPackages.length >= this.maxConcurrentPackage || idAllreadyPending.length) {
// Add package to queue
this.queue.push(mediaPackage);
process.logger.debug('Add package ' + mediaPackage.originalPackagePath + '(' + mediaPackage.id + ') to queue');
return false;
} else {
// Process can deal with the package
process.logger.debug('Add package ' + mediaPackage.originalPackagePath +
'(' + mediaPackage.id + ') to pending packages');
// Add package to the list of pending packages
this.pendingPackages.push(mediaPackage);
return true;
}
}
/**
* Gets an instance of the PublishManager.
*
* @method get
* @static
* @param {VideoModel} videoModel The videoModel
* @param {Number} [maxConcurrentPackage] The maximum number of medias to treat in parallel
* @return {PublishManager} The PublishManager singleton instance
*/
PublishManager.get = function(videoModel, maxConcurrentPackage) {
if (!publishManager)
publishManager = new PublishManager(videoModel);
return publishManager;
};
/**
* Publishes the given media package.
*
* Media package must be of one of the supported type.
*
* @method publish
* @param {Object} mediaPackage Media to publish
* @param {String} mediaPackage.originalPackagePath Package absolute path
* @param {String} mediaPackage.packageType The package type
* @param {String} [mediaPackage.title] The title to use for this media, default to the file name without extension
*/
PublishManager.prototype.publish = function(mediaPackage) {
var self = this;
if (mediaPackage && (typeof mediaPackage === 'object')) {
openVeoApi.util.validateFiles({
file: mediaPackage.originalPackagePath
}, {
file: {in: acceptedPackagesExtensions}
}, function(error, files) {
if (error || (files.file && !files.file.isValid))
return self.emit('error', new PublishError('Media package type is not valid (' +
mediaPackage.originalPackagePath +
')', ERRORS.INVALID_PACKAGE_TYPE));
// Media package can be in queue and already have an id
if (!mediaPackage.id) {
var pathDescriptor = path.parse(mediaPackage.originalPackagePath);
mediaPackage.packageType = files.file.type;
mediaPackage.id = shortid.generate();
mediaPackage.title = mediaPackage.title || pathDescriptor.name;
}
self.videoModel.get({originalPackagePath: mediaPackage.originalPackagePath}, function(error, videos) {
if (error) {
self.emit('error', new PublishError('Getting medias with original package path "' +
mediaPackage.originalPackagePath + '" failed with message : ' +
error.message, ERRORS.UNKNOWN));
} else if (!videos || !videos.length) {
// Package can be added to pending packages
if (addPackage.call(self, mediaPackage)) {
// Media package does not exist
// Publish it
var mediaPackageManager = createMediaPackageManager.call(self, mediaPackage);
mediaPackageManager.init(Package.STATES.PACKAGE_SUBMITTED, Package.TRANSITIONS.INIT);
mediaPackageManager.executeTransition(Package.TRANSITIONS.INIT);
}
}
});
});
} else
this.emit('error', new PublishError('mediaPackage argument must be an Object', ERRORS.UNKNOWN));
};
/**
* Retries publishing a media package which is on error.
*
* @method retry
* @param {String} packageId The id of the package on error
* @param {Boolean} forceRetry Force retrying a package no matter its state
*/
PublishManager.prototype.retry = function(packageId, forceRetry) {
if (packageId) {
var self = this;
// Retrieve package information
this.videoModel.getOne(packageId, null, function(error, mediaPackage) {
if (error) {
self.emit('error', new PublishError('Getting package ' + packageId + ' failed with message : ' + error.message,
ERRORS.UNKNOWN));
} else if (!mediaPackage) {
// Package does not exist
self.emit('error', new PublishError('Cannot retry package ' + packageId + ' (not found)',
ERRORS.PACKAGE_NOT_FOUND));
} else if (mediaPackage.state === STATES.ERROR || forceRetry) {
// Got package information
// Package is indeed in error
self.videoModel.updateState(mediaPackage.id, STATES.PENDING, function() {
// Retry officially started
self.emit('retry', mediaPackage);
self.emit('stateChanged', mediaPackage);
});
var mediaPackageManager = createMediaPackageManager.call(self, mediaPackage);
process.logger.info('Retry package ' + mediaPackage.id);
mediaPackageManager.init(mediaPackage.lastState, mediaPackage.lastTransition);
// Package can be added to pending packages
if (addPackage.call(self, mediaPackage))
mediaPackageManager.executeTransition(mediaPackage.lastTransition);
}
});
}
};
/**
* Retries publishing all packages in a non stable state.
*
* Stable states are :
* - STATES.ERROR
* - STATES.WAITING_FOR_UPLOAD
* - STATES.READY
* - STATES.PUBLISHED
*
* @method retryAll
*/
PublishManager.prototype.retryAll = function() {
var self = this;
// Retrieve all packages in a non stable state
this.videoModel.get({
state: {
$nin: [
STATES.ERROR,
STATES.WAITING_FOR_UPLOAD,
STATES.READY,
STATES.PUBLISHED
]
}
}, function(error, mediaPackages) {
if (error)
return self.emit('error', new PublishError('Getting packages in non stable state failed with message : ' +
error.message,
ERRORS.UNKNOWN));
mediaPackages.forEach(function(mediaPackage) {
self.retry(mediaPackage.id, true);
});
});
};
/**
* Uploads a media blocked in "waiting to upload" state.
*
* @method upload
* @param {String} packageId The id of the package waiting to be uploaded
* @param {String} platform The type of the video platform to upload to
*/
PublishManager.prototype.upload = function(packageId, platform) {
if (packageId && platform) {
var self = this;
// Retrieve package information
this.videoModel.getOne(packageId, null, function(error, mediaPackage) {
if (error) {
self.emit('error', new PublishError('Getting package ' + packageId + ' failed with message : ' + error.message,
ERRORS.UNKNOWN));
} else if (!mediaPackage) {
// Package does not exist
self.emit('error', new PublishError('Cannot upload package ' + packageId + ' (not found)',
ERRORS.PACKAGE_NOT_FOUND));
} else if (mediaPackage.state === STATES.WAITING_FOR_UPLOAD) {
// Package is indeed waiting for upload
self.videoModel.updateState(mediaPackage.id, STATES.PENDING, function() {
// Upload officially started
self.emit('upload', mediaPackage);
self.emit('stateChanged', mediaPackage);
});
self.videoModel.updateType(mediaPackage.id, platform);
var mediaPackageManager = createMediaPackageManager.call(self, mediaPackage);
process.logger.info('Force upload package ' + mediaPackage.id);
mediaPackage.type = platform;
mediaPackageManager.init(mediaPackage.lastState, mediaPackage.lastTransition);
// Package can be added to pending packages
if (addPackage.call(self, mediaPackage))
mediaPackageManager.executeTransition(mediaPackage.lastTransition);
}
});
}
};
| app/server/PublishManager.js | 'use strict';
/**
* @module publish
*/
var util = require('util');
var events = require('events');
var path = require('path');
var shortid = require('shortid');
var openVeoApi = require('@openveo/api');
var Package = process.requirePublish('app/server/packages/Package.js');
var packageFactory = process.requirePublish('app/server/packages/packageFactory.js');
var ERRORS = process.requirePublish('app/server/packages/errors.js');
var STATES = process.requirePublish('app/server/packages/states.js');
var PublishError = process.requirePublish('app/server/PublishError.js');
var fileSystem = openVeoApi.fileSystem;
var acceptedPackagesExtensions = [fileSystem.FILE_TYPES.TAR, fileSystem.FILE_TYPES.MP4];
var publishManager;
/**
* Fired when an error occurred while processing a package.
*
* @event error
* @param {Error} The error
*/
/**
* Fired when a package process has succeed.
*
* @event complete
* @param {Object} The processed package
*/
/**
* Fired when a media in error restarts.
*
* @event retry
* @param {Object} The media
*/
/**
* Fired when a media stuck in "waiting for upload" state starts uploading.
*
* @event upload
* @param {Object} The media
*/
/**
* Fired when media state has changed.
*
* @event stateChanged
* @param {Object} The media
*/
/**
* Defines the PublishManager which handles the media publication's process.
*
* Media publications are handled in parallel. Media publication's process can be
* different regarding the type of the media.
*
* @example
* var coreApi = process.api.getCoreApi();
* var database = coreApi.getDatabase();
* var PublishManager = process.requirePublish('app/server/PublishManager.js');
* var videoModel = new VideoModel(null, new VideoProvider(database), new PropertyProvider(database));
* var publishManager = new PublishManager(videoModel, 5);
*
* // Listen publish manager's errors
* publishManager.on('error', function(error) {
* // Do something
* });
*
* // Listen to publish manager's end of processing for a media
* publishManager.on('complete', function(mediaPackage){
* // Do something
* });
*
* // Listen to publish manager's event informing that a media processing is retrying
* publishManager.on('retry', function(mediaPackage) {
* // Do something
* });
*
* // Listen to publish manager's event informing that a media, waiting for upload, starts uploading
* publishManager.on('upload', function(mediaPackage) {
* // Do something
* });
*
* publishManager.publish({
* type: 'youtube', // The media platform to use for this media
* originalPackagePath: '/home/openveo/medias/media-package.tar', // Path of the media package
* originalFileName: 'media-package' // File name without extension
* });
*
* @class PublishManager
* @constructor
* @param {VideoModel} videoModel The videoModel
* @param {Number} [maxConcurrentPackage=3] The maximum number of medias to treat in parallel
*/
function PublishManager(videoModel, maxConcurrentPackage) {
if (publishManager)
throw new Error('PublishManager already instanciated, use get method instead');
Object.defineProperties(this, {
/**
* Medias waiting to be processed.
*
* @property queue
* @type Array
* @final
*/
queue: {value: []},
/**
* Medias being processed.
*
* @property pendingPackages
* @type Array
* @final
*/
pendingPackages: {value: []},
/**
* Video model.
*
* @property videoModel
* @type VideoModel
* @final
*/
videoModel: {value: videoModel},
/**
* Maximum number of medias to treat in parallel.
*
* @property maxConcurrentPackage
* @type Number
* @final
*/
maxConcurrentPackage: {value: maxConcurrentPackage || 3}
});
}
util.inherits(PublishManager, events.EventEmitter);
module.exports = PublishManager;
/**
* Removes a media from pending medias.
*
* @method removeFromPending
* @private
* @param {Object} mediaPackage The media package to remove
*/
function removeFromPending(mediaPackage) {
for (var i = 0; i < this.pendingPackages.length; i++) {
if (this.pendingPackages[i]['id'] === mediaPackage.id) {
this.pendingPackages.splice(i, 1);
break;
}
}
for (var j = 0; j < this.pendingPackages.length; j++) {
if (this.pendingPackages[j]['originalFileName'] === mediaPackage.originalFileName) {
this.pendingPackages.splice(j, 1);
break;
}
}
process.logger.debug('Package ' + mediaPackage.id + ' from ' +
mediaPackage.originalFileName + ' is removed from pendingPackages');
}
/**
* Handles media error event.
*
* @method onError
* @private
* @param {Error} error The error
* @param {Object} mediaPackage The media on error
*/
function onError(error, mediaPackage) {
// Remove media from pending medias
removeFromPending.call(this, mediaPackage);
// Publish pending media from FIFO queue
if (this.queue.length)
this.publish(this.queue.shift(0));
// Add media id to the error message
if (error)
error.message += ' (' + mediaPackage.id + ')';
this.emit('error', error, error.code);
}
/**
* Handles media complete event.
*
* @method onComplete
* @private
* @param {Object} mediaPackage The package on error
*/
function onComplete(mediaPackage) {
// Remove package from pending packages
removeFromPending.call(this, mediaPackage);
// Publish pending package from FIFO queue
if (this.queue.length)
this.publish(this.queue.shift(0));
this.emit('complete', mediaPackage);
}
/**
* Creates a media package manager corresponding to the media type.
*
* @method createMediaPackageManager
* @private
* @param {Object} mediaPackage The media to manage
* @return {Package} A media package manager
*/
function createMediaPackageManager(mediaPackage) {
var self = this;
var mediaPackageManager = packageFactory.get(mediaPackage.packageType, mediaPackage);
// Handle errors from media package manager
mediaPackageManager.on('error', function(error) {
onError.call(self, error, mediaPackage);
});
// Handle complete events from media package manager
mediaPackageManager.on('complete', function(completePackage) {
onComplete.call(self, completePackage);
});
// Handle stateChanged events from media package manager
mediaPackageManager.on('stateChanged', function(mediaPackage) {
self.emit('stateChanged', mediaPackage);
});
return mediaPackageManager;
}
/**
* Adds media package to the list of pending packages.
*
* @method addPackage
* @private
* @param {Object} mediaPackage The media package to add to pending packages
* @return {Boolean} true if the media package is successfully added to pending packages
* false if it has been added to queue
*/
function addPackage(mediaPackage) {
process.logger.debug('Actually ' + this.pendingPackages.length + ' pending packages');
var idAllreadyPending = this.pendingPackages.filter(function(pendingPackage) {
return mediaPackage.originalFileName === pendingPackage.originalFileName;
});
// Too much pending packages
if (this.pendingPackages.length >= this.maxConcurrentPackage || idAllreadyPending.length) {
// Add package to queue
this.queue.push(mediaPackage);
process.logger.debug('Add package ' + mediaPackage.originalPackagePath + '(' + mediaPackage.id + ') to queue');
return false;
} else {
// Process can deal with the package
process.logger.debug('Add package ' + mediaPackage.originalPackagePath +
'(' + mediaPackage.id + ') to pending packages');
// Add package to the list of pending packages
this.pendingPackages.push(mediaPackage);
return true;
}
}
/**
* Gets an instance of the PublishManager.
*
* @method get
* @static
* @param {VideoModel} videoModel The videoModel
* @param {Number} [maxConcurrentPackage] The maximum number of medias to treat in parallel
* @return {PublishManager} The PublishManager singleton instance
*/
PublishManager.get = function(videoModel, maxConcurrentPackage) {
if (!publishManager)
publishManager = new PublishManager(videoModel);
return publishManager;
};
/**
* Publishes the given media package.
*
* Media package must be of one of the supported type.
*
* @method publish
* @param {Object} mediaPackage Media to publish
* @param {String} mediaPackage.originalPackagePath Package absolute path
* @param {String} mediaPackage.packageType The package type
* @param {String} [mediaPackage.title] The title to use for this media, default to the file name without extension
*/
PublishManager.prototype.publish = function(mediaPackage) {
var self = this;
if (mediaPackage && (typeof mediaPackage === 'object')) {
openVeoApi.util.validateFiles({
file: mediaPackage.originalPackagePath
}, {
file: {in: acceptedPackagesExtensions}
}, function(error, files) {
if (error || (files.file && !files.file.isValid))
return self.emit('error', new PublishError('Media package type is not valid', ERRORS.INVALID_PACKAGE_TYPE));
// Media package can be in queue and already have an id
if (!mediaPackage.id) {
var pathDescriptor = path.parse(mediaPackage.originalPackagePath);
mediaPackage.packageType = files.file.type;
mediaPackage.id = shortid.generate();
mediaPackage.title = mediaPackage.title || pathDescriptor.name;
}
self.videoModel.get({originalPackagePath: mediaPackage.originalPackagePath}, function(error, videos) {
if (error) {
self.emit('error', new PublishError('Getting medias with original package path "' +
mediaPackage.originalPackagePath + '" failed with message : ' +
error.message, ERRORS.UNKNOWN));
} else if (!videos || !videos.length) {
// Package can be added to pending packages
if (addPackage.call(self, mediaPackage)) {
// Media package does not exist
// Publish it
var mediaPackageManager = createMediaPackageManager.call(self, mediaPackage);
mediaPackageManager.init(Package.STATES.PACKAGE_SUBMITTED, Package.TRANSITIONS.INIT);
mediaPackageManager.executeTransition(Package.TRANSITIONS.INIT);
}
}
});
});
} else
this.emit('error', new PublishError('mediaPackage argument must be an Object', ERRORS.UNKNOWN));
};
/**
* Retries publishing a media package which is on error.
*
* @method retry
* @param {String} packageId The id of the package on error
* @param {Boolean} forceRetry Force retrying a package no matter its state
*/
PublishManager.prototype.retry = function(packageId, forceRetry) {
if (packageId) {
var self = this;
// Retrieve package information
this.videoModel.getOne(packageId, null, function(error, mediaPackage) {
if (error) {
self.emit('error', new PublishError('Getting package ' + packageId + ' failed with message : ' + error.message,
ERRORS.UNKNOWN));
} else if (!mediaPackage) {
// Package does not exist
self.emit('error', new PublishError('Cannot retry package ' + packageId + ' (not found)',
ERRORS.PACKAGE_NOT_FOUND));
} else if (mediaPackage.state === STATES.ERROR || forceRetry) {
// Got package information
// Package is indeed in error
self.videoModel.updateState(mediaPackage.id, STATES.PENDING, function() {
// Retry officially started
self.emit('retry', mediaPackage);
self.emit('stateChanged', mediaPackage);
});
var mediaPackageManager = createMediaPackageManager.call(self, mediaPackage);
process.logger.info('Retry package ' + mediaPackage.id);
mediaPackageManager.init(mediaPackage.lastState, mediaPackage.lastTransition);
// Package can be added to pending packages
if (addPackage.call(self, mediaPackage))
mediaPackageManager.executeTransition(mediaPackage.lastTransition);
}
});
}
};
/**
* Retries publishing all packages in a non stable state.
*
* Stable states are :
* - STATES.ERROR
* - STATES.WAITING_FOR_UPLOAD
* - STATES.READY
* - STATES.PUBLISHED
*
* @method retryAll
*/
PublishManager.prototype.retryAll = function() {
var self = this;
// Retrieve all packages in a non stable state
this.videoModel.get({
state: {
$nin: [
STATES.ERROR,
STATES.WAITING_FOR_UPLOAD,
STATES.READY,
STATES.PUBLISHED
]
}
}, function(error, mediaPackages) {
if (error)
return self.emit('error', new PublishError('Getting packages in non stable state failed with message : ' +
error.message,
ERRORS.UNKNOWN));
mediaPackages.forEach(function(mediaPackage) {
self.retry(mediaPackage.id, true);
});
});
};
/**
* Uploads a media blocked in "waiting to upload" state.
*
* @method upload
* @param {String} packageId The id of the package waiting to be uploaded
* @param {String} platform The type of the video platform to upload to
*/
PublishManager.prototype.upload = function(packageId, platform) {
if (packageId && platform) {
var self = this;
// Retrieve package information
this.videoModel.getOne(packageId, null, function(error, mediaPackage) {
if (error) {
self.emit('error', new PublishError('Getting package ' + packageId + ' failed with message : ' + error.message,
ERRORS.UNKNOWN));
} else if (!mediaPackage) {
// Package does not exist
self.emit('error', new PublishError('Cannot upload package ' + packageId + ' (not found)',
ERRORS.PACKAGE_NOT_FOUND));
} else if (mediaPackage.state === STATES.WAITING_FOR_UPLOAD) {
// Package is indeed waiting for upload
self.videoModel.updateState(mediaPackage.id, STATES.PENDING, function() {
// Upload officially started
self.emit('upload', mediaPackage);
self.emit('stateChanged', mediaPackage);
});
self.videoModel.updateType(mediaPackage.id, platform);
var mediaPackageManager = createMediaPackageManager.call(self, mediaPackage);
process.logger.info('Force upload package ' + mediaPackage.id);
mediaPackage.type = platform;
mediaPackageManager.init(mediaPackage.lastState, mediaPackage.lastTransition);
// Package can be added to pending packages
if (addPackage.call(self, mediaPackage))
mediaPackageManager.executeTransition(mediaPackage.lastTransition);
}
});
}
};
| Add package name to invalid type error message
Log indicating that the package type is not a valid one (tar or mp4) wasn't giving any information about the package. It now indicates the path of the invalid package.
| app/server/PublishManager.js | Add package name to invalid type error message | <ide><path>pp/server/PublishManager.js
<ide> file: {in: acceptedPackagesExtensions}
<ide> }, function(error, files) {
<ide> if (error || (files.file && !files.file.isValid))
<del> return self.emit('error', new PublishError('Media package type is not valid', ERRORS.INVALID_PACKAGE_TYPE));
<add> return self.emit('error', new PublishError('Media package type is not valid (' +
<add> mediaPackage.originalPackagePath +
<add> ')', ERRORS.INVALID_PACKAGE_TYPE));
<ide>
<ide> // Media package can be in queue and already have an id
<ide> if (!mediaPackage.id) { |
|
Java | apache-2.0 | 13919636a5c728676f55c73602e661810943ed62 | 0 | EsupPortail/esup-pstage,EsupPortail/esup-pstage | /**
* ESUP-PStage - Copyright (c) 2006 ESUP-Portail consortium
* http://sourcesup.cru.fr/projects/esup-pstage
*/
package org.esupportail.pstage.web.controllers;
import gouv.education.apogee.commun.transverse.dto.geographie.CommuneDTO;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.apache.log4j.Logger;
import org.esupportail.pstage.exceptions.ExportException;
import org.esupportail.pstage.services.export.CastorService;
import org.esupportail.pstage.utils.Utils;
import org.esupportail.pstage.web.beans.FileUploadBean;
import org.esupportail.pstage.web.beans.ImageUploadBean;
import org.esupportail.pstage.web.comparator.ComparatorSelectItem;
import org.esupportail.pstage.web.paginators.RechercheOffrePaginator;
import org.esupportail.pstage.web.utils.PDFUtils;
import org.esupportail.pstagedata.domain.dto.*;
import org.esupportail.pstagedata.exceptions.DataAddException;
import org.esupportail.pstagedata.exceptions.DataDeleteException;
import org.esupportail.pstagedata.exceptions.DataUpdateException;
import org.esupportail.pstagedata.exceptions.WebServiceDataBaseException;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DualListModel;
import org.springframework.util.StringUtils;
import static org.hsqldb.HsqlDateTime.e;
/**
* OffreController
*/
public class OffreController extends AbstractContextAwareController {
/* ***************************************************************
* Propriétés
****************************************************************/
/**
* Navigation à renvoyer au cours de l'ajout d'offre selon si l'on est coté entreprise ou stage
*/
private String creationOffre;
/**
* The serialization id.
*/
private static final long serialVersionUID = 3430944955282121430L;
/**
* Logger
*/
private final transient Logger logger = Logger.getLogger(this.getClass());
/**
* Page de retour après une modification ou suppression d'offre
*/
private String retour=null;
/**
* Action pour renvoyer sur le récap de l'offre en cours
*/
private String recap=null;
/**
* Offre actuellement gérée
*/
private OffreDTO currentOffre;
/**
* Objet offre utilisé pour l'ajout/modification
*/
private OffreDTO formOffre;
/**
* Liste des contrats mise à jour en fonction du type d'offre
*/
private List<SelectItem> contratsListening;
/**
* Liste FapN3 mise à jour en fonction de la QualificationSimplifiee
*/
private List<SelectItem> fapN3Listening;
/**
* Liste des communes mise à jour en fonction du code postal
*/
private List<SelectItem> formOffreCommunesListening=new ArrayList<SelectItem>();
/**
* Vrai si offre avec un fichier ou un lien
*/
private boolean avecFichierOuLien;
/**
* 1 si fichier, 2 si lien
*/
private int fichierOuLien=0;
/**
* Liste des offres de l'entreprise actuellement gérée
*/
private List<OffreDTO> listeOffres;
/**
* Liste des centres de gestion de la personne actuellement connectée sous de SelectItem
*/
private List<SelectItem> listeItemsCurrentCentresGestion;
//Recherche
/**
* CritereRechercheOffreDTO
*/
private CritereRechercheOffreDTO critereRechercheOffre=initCritereRechercheOffre();
/**
* Liste des types d'offres et contrats pour la recherche
*/
private List<SelectItem> rechTypesContratsOffre;
/**
* Type ou contrat sélectionné pour la recherche
*/
private String rechTypeOuContrat;
/**
* Resultats de la recherche d'offre
*/
private List<OffreDTO> resultatsRechercheOffre;
/**
* Vrai si recherche avancée, faux si recherche simple
*/
private boolean rechercheAvancee=false;
/**
* RechercheOffrePaginator
*/
private RechercheOffrePaginator rechercheOffrePaginator;
//Diffusion à d'autres centres
/**
* Nombre d'éléments dans la liste offresDiffusion de currentOffre
*/
private int currentOffreSizeOffresDiffusion;
/**
* Liste des centres établissement
*/
private List<SelectItem> listesCentresGestionEtablissement=new ArrayList<SelectItem>();
/**
* Liste des centres établissement
*/
private List<CentreGestionDTO> listesCGEtab;
/**
* Id du centre établissement sélectionné
*/
private int idCentreEtablissementSelect;
/**
* Centre de gestion utilisé pour le dépot anonyme
*/
private CentreGestionDTO centreGestionDepotAnonyme;
/**
* EtablissementController
*/
private EtablissementController etablissementController;
/**
* Service to generate Xml.
*/
private CastorService castorService;
/**
* Liste des durees de diffusion disponibles
*/
private List<SelectItem> dureesDiffusion;
/**
* Duree de diffusion choisie
*/
private int dureeDiffusion;
/**
* on diffuse l'offre après ajout/modif si vrai
*/
private boolean diffusionDirecte = false;
/**
* Nombre d'offres à diffuser (pour affichage _menu.jsp partie entreprise)
*/
private int offreADiffuser=0;
public DualListModel<CentreGestionDTO> getDualListCiblageCentres() {
return dualListCiblageCentres;
}
public void setDualListCiblageCentres(DualListModel<CentreGestionDTO> dualListCiblageCentres) {
this.dualListCiblageCentres = dualListCiblageCentres;
}
/**
* DualList des centres de gestion dispos/choisis pour le ciblage
*/
private DualListModel<CentreGestionDTO> dualListCiblageCentres;
/**
* rendered en fonctione du type de contrat de la page __offreEtape2
*/
private boolean affichageDureeOffre = false;
/**
* rendered en fonction du pays de la page __offreEtape2
*/
private boolean paysOffreFrance = false;
/**
* retient dans quel recapitulatif offre nous sommes
* 'offre' = depot
* 'offreEtab' = depot depuis la consultation d'une structure
* 'offreCentre' = stage
* 'offreEtabCentre' = stage depuis la consultation d'une structure
*/
private String currentRecapOffre;
/**
* true si l'on modifie directement les contacts de l'offre (et pas via une étape précédente)
*/
private boolean modificationContactOffre;
/**
* Bean constructor.
*/
public OffreController() {
super();
}
/* ***************************************************************
* Actions
****************************************************************/
/**
* Gestion des offres (entreprise)
*
* @return String
*/
public String goToGestionOffres() {
return "gestionOffres";
}
/**
* Gestion des offres (stage)
*
* @return String
*/
public String goToOffresEtablissement() {
loadOffres();
return "offresEtablissement";
}
/**
* Chargement des offres
*/
public void loadOffres() {
if (getSessionController().getCurrentManageStructure() != null) {
this.listeOffres = getOffreDomainService()
.getOffresFromIdStructureAndIdsCentreGestion(
getSessionController().getCurrentManageStructure()
.getIdStructure(),
getSessionController()
.getCurrentIdsCentresGestion(),
getSessionController().getCurrentAuthEtudiant() != null);
if (this.listeOffres != null && !this.listeOffres.isEmpty()) {
for (OffreDTO o : this.listeOffres) {
o.setStructure(getSessionController()
.getCurrentManageStructure());
}
}
sortListesOffres();
}
}
/**
* Tri
*/
public void sortListesOffres() {
if (this.listeOffres != null && !this.listeOffres.isEmpty()) {
Collections.sort(this.listeOffres, new Comparator<OffreDTO>() {
/**
* @see java.util.Comparator#compare(java.lang.Object,
* java.lang.Object)
*/
@Override
public int compare(OffreDTO o1, OffreDTO o2) {
return o1.getIntitule().compareToIgnoreCase(
o2.getIntitule());
}
});
}
}
/* ***************************************************************
* Ajout d'une offre
* **************************************************************/
/**
* @return String
*/
public String goToEntrepriseCreationOffre() {
this.creationOffre = "creationOffre";
this.formOffre = new OffreDTO();
this.formOffre.setStructure(getSessionController().getCurrentManageStructure());
this.formOffre.setIdStructure(this.formOffre.getStructure().getIdStructure());
this.centreGestionDepotAnonyme = null;
this.formOffre.setIdCentreGestion(getCentreGestionDomainService().getCentreEntreprise().getIdCentreGestion());
// Indemnités à vrai par défaut
this.formOffre.setRemuneration(true);
this.avecFichierOuLien = false;
this.fichierOuLien = 0;
this.contratsListening = null;
this.fapN3Listening = null;
getSessionController().setCreationOffreCurrentPage("_creationOffreEtape1");
return this.creationOffre;
}
/**
* permet de recharger la page courante de l'enchainement d'offre
* @return String
*/
public String goToCreationOffre() {
return this.creationOffre;
}
/**
* Etape 01 : Sélection du centre de gestion
*
* @return String
*/
public String goToCreationOffreSelectionCentre() {
this.creationOffre = "creationCentreEtabOffre";
this.formOffre = new OffreDTO();
this.centreGestionDepotAnonyme = null;
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape01Centre");
return this.creationOffre;
}
/**
* Etape 02 : Sélection établissement
*
* @return String
*/
public String goToCreationOffreSelectionEtab() {
String ret = "creationEtabOffre";
this.formOffre = new OffreDTO();
this.centreGestionDepotAnonyme = null;
return ret;
}
/**
* Etape 03 : Création établissement
* @return a String
*/
public void goToCreationOffreCreaEtab() {
this.etablissementController.goToCreationEtablissement();
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape03CreaEtab");
}
/**
* Bouton d'ajout d'une offre à l'étape 03
*
* @return String
*/
public void ajouterEtablissement() {
String ret = this.etablissementController.ajouterEtablissement();
if (ret != null
&& this.etablissementController.getFormStructure() != null) {
this.etablissementController.getRechercheController()
.setResultatRechercheStructure(
this.etablissementController.getFormStructure());
this.etablissementController.setFormStructure(null);
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape04DetailsEtab");
}
}
/**
* @return String
*/
public String goToCreationOffreModifEtab() {
this.etablissementController.goToModificationEtablissement();
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape05ModifEtab");
return "creationCentreEtabOffre";
}
/**
* @return String
*/
public void modifierEtablissement() {
String ret = this.etablissementController.modifierEtablissement();
FacesContext fc = FacesContext.getCurrentInstance();
Iterator<FacesMessage> ifm = fc.getMessages("formModifEtab");
while (ifm.hasNext()) {
FacesMessage fm = ifm.next();
fc.addMessage(
"formCreationOffre:formModifEtab",
new FacesMessage(FacesMessage.SEVERITY_ERROR, fm
.getSummary(), fm.getDetail()));
ifm.remove();
}
ifm = fc.getMessages("formAffEtab");
while (ifm.hasNext()) {
FacesMessage fm = ifm.next();
fc.addMessage("formCreationOffre:formAffEtab",
new FacesMessage(fm.getSummary(), fm.getDetail()));
ifm.remove();
}
if (StringUtils.hasText(ret)) {
// ret="_creationOffreEtape04DetailsEtab";
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape04DetailsEtab");
}
// return ret;
}
/**
* @return String
*/
public void goToCreationOffreDetailsEtab(){
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape04DetailsEtab");
}
/**
* @return String
*/
public String goToCreationOffreEtape1(){
this.formOffre.setIdStructure(this.formOffre.getStructure().getIdStructure());
getSessionController().setCurrentManageStructure(this.formOffre.getStructure());
getSessionController().setMenuGestionEtab(false);
//Chargement contacts uniquement pour le centre sélectionné
ArrayList<CentreGestionDTO> curCentresTmp = (ArrayList<CentreGestionDTO>) getSessionController().getCurrentCentresGestion();
ArrayList<CentreGestionDTO> centreContacts = new ArrayList<>();
CentreGestionDTO cgTmp = new CentreGestionDTO();
cgTmp.setIdCentreGestion(this.formOffre.getIdCentreGestion());
cgTmp.setNomCentre("");
if(curCentresTmp != null
&& !curCentresTmp.isEmpty()
&& curCentresTmp.indexOf(cgTmp) >= 0){
centreContacts.add(curCentresTmp.get(curCentresTmp.indexOf(cgTmp)));
}
if(centreGestionDepotAnonyme!=null
&& centreGestionDepotAnonyme.getIdCentreGestion() > 0){
centreContacts = new ArrayList<>();
centreContacts.add(centreGestionDepotAnonyme);
}
getSessionController().setCentreGestionRattachement(centreContacts.get(0));
this.etablissementController.loadContactsServices();
//Indemnités à vrai par défaut
this.formOffre.setRemuneration(true);
this.avecFichierOuLien=false;
this.fichierOuLien=0;
this.formOffre.setLienAttache("http://");
this.contratsListening=null;
this.fapN3Listening=null;
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape1");
getSessionController().setCreationOffreCurrentPage("_creationOffreEtape1");
return this.creationOffre;
}
/**
* Envoi vers l'Etape 2 : Saisie de l'offre
* @return String
*/
public String goToCreationOffreEtape2(){
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape2");
getSessionController().setCreationOffreCurrentPage("_creationOffreEtape2");
// Oui par défaut pour la diffusion directe de l'offre :
// this.diffusionDirecte = true;
this.formOffre.setLieuPays(this.formOffre.getStructure().getPays());
this.formOffre.setLieuCodePostal(this.formOffre.getStructure().getCodePostal());
this.formOffre.setLieuCommune(this.formOffre.getStructure().getCommune());
this.formOffre.setCodeCommune(this.formOffre.getStructure().getCodeCommune());
if(getSessionController().isRecupererCommunesDepuisApogee() &&
getBeanUtils().isFrance(this.formOffre.getLieuPays())){
List<SelectItem> lTmp = majCommunes(""+this.formOffre.getLieuCodePostal());
if(lTmp!=null && !lTmp.isEmpty()){
this.formOffreCommunesListening=lTmp;
}else{
this.formOffreCommunesListening=new ArrayList<SelectItem>();
}
}
if(this.avecFichierOuLien){
switch (this.fichierOuLien) {
case 1:
this.formOffre.setAvecFichier(true);
this.formOffre.setAvecLien(false);
this.formOffre.setLienAttache("");
break;
case 2:
this.deleteUploadedFile();
this.formOffre.setAvecFichier(false);
this.formOffre.setAvecLien(true);
break;
default:
this.deleteUploadedFile();
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape1");
getSessionController().setCreationOffreCurrentPage("_creationOffreEtape1");
break;
}
} else {
//Suppression de l'ancien fichier/lien
this.deleteUploadedFile();
}
this.formOffre.setIdTypeOffre(this.formOffre.getTypeOffre().getId());
//Màj liste des contrats
List<ContratOffreDTO> l = getNomenclatureDomainService().getContratsOffreFromIdTypeOffre(this.formOffre.getIdTypeOffre());
if(l!=null && !l.isEmpty()){
this.contratsListening=new ArrayList<>();
for(ContratOffreDTO c : l){
this.contratsListening.add(new SelectItem(c,c.getLibelle()));
}
}else{
this.contratsListening=null;
}
// On initialise l'uniteDuree a vide pour eviter qu'elle soit remplie par defaut.
this.formOffre.setUniteDuree(new UniteDureeDTO());
//Reset de la durée de diffusion
this.dureeDiffusion = 2;
return this.creationOffre;
}
public boolean isAffichageDureeOffre(){
if ((this.formOffre.getContratOffre() != null && this.formOffre.getContratOffre().equals(getBeanUtils().getCdd()))
|| (this.formOffre.getTypeOffre() != null &&
(this.formOffre.getTypeOffre().equals(getBeanUtils().getStage())
|| this.formOffre.getTypeOffre().equals(getBeanUtils().getAlternance())
|| this.formOffre.getTypeOffre().equals(getBeanUtils().getVieVia())))){
return true;
}
return false;
}
public boolean isPaysOffreFrance(){
if ((this.formOffre.getLieuPays() != null && getBeanUtils().isFrance(this.formOffre.getLieuPays()))){
return true;
}
return false;
}
/**
* Envoi vers l'étape 3
* Saisie des contacts
* @return String
*/
public String goToCreationOffreEtape3(){
getSessionController().setCreationOffreCurrentPage("_creationOffreEtape3");
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape3");
return this.creationOffre;
}
/**
* Ajout de l'offre en base
*/
public void ajoutOffre(){
this._ajoutOffre();
if(this.formOffre.getIdOffre() > 0
&& getSessionController().getCurrentManageStructure() != null
&& getSessionController().getCurrentManageStructure().getIdStructure() == this.formOffre.getIdStructure()){
if(this.listeOffres==null)
this.listeOffres=new ArrayList<OffreDTO>();
this.listeOffres.add(this.formOffre);
this.currentOffre = this.formOffre;
this.formOffre=new OffreDTO();
}
// return ret;
}
/**
* Méthode d'ajout d'une offre subdivisée pour gérer l'ajout d'offre d'une entreprise et l'ajout d'offre d'un centre (ne nécessite pas la maj de la liste des offres)
* @return String
*/
public void _ajoutOffre(){
// String ret=null;
if(this.centreGestionDepotAnonyme!=null){
this.formOffre.setLoginCreation("depotAnonyme");
}else{
this.formOffre.setLoginCreation(getSessionController().getCurrentLogin());
}
if(this.formOffre.getLieuPays()!=null){
if(getBeanUtils().isFrance(this.formOffre.getLieuPays()) && getSessionController().isRecupererCommunesDepuisApogee() && !"0".equals(this.formOffre.getCodeCommune())){
//Récupération de la commune pour en avoir le libellé
CommuneDTO c = getGeographieRepositoryDomain().getCommuneFromDepartementEtCodeCommune(this.formOffre.getLieuCodePostal(), ""+this.formOffre.getCodeCommune());
if(c!=null){
this.formOffre.setLieuCommune(c.getLibCommune());
}
}
this.formOffre.setIdLieuPays(this.formOffre.getLieuPays().getId());
}
if(this.formOffre.getFapQualificationSimplifiee()!=null)this.formOffre.setIdQualificationSimplifiee(this.formOffre.getFapQualificationSimplifiee().getId());
if(this.formOffre.getFapN1()!=null)this.formOffre.setCodeFAP_N3(this.formOffre.getFapN1().getCode());
if(this.formOffre.getTypeOffre()!=null)this.formOffre.setIdTypeOffre(this.formOffre.getTypeOffre().getId());
else this.formOffre.setIdTypeOffre(0);
if(this.formOffre.getContratOffre()!=null)this.formOffre.setIdContratOffre(this.formOffre.getContratOffre().getId());
else this.formOffre.setIdContratOffre(0);
if(this.formOffre.getNiveauFormation()!=null)this.formOffre.setIdNiveauFormation(this.formOffre.getNiveauFormation().getId());
else this.formOffre.setIdNiveauFormation(0);
this.formOffre.setAnneeUniversitaire(getBeanUtils().getAnneeUniversitaireCourante(new Date()));
this.formOffre.setCentreGestion(getCentreGestionDomainService().getCentreGestion(this.formOffre.getIdCentreGestion()));
int idOffreAjoutee;
if(this.avecFichierOuLien){
this.formOffre.setIdTempsTravail(0);
this.formOffre.setIdUniteDuree(0);
this.formOffre.setModesCandidature(null);
this.formOffre.setIdsModeCandidature(null);
this.formOffre.setContactCand(null);
this.formOffre.setContactInfo(null);
this.formOffre.setIdContactCand(0);
this.formOffre.setIdContactInfo(0);
switch (this.fichierOuLien) {
case 1:
if(this.formOffre.getIdFichier()>0){
try{
this.formOffre.setAvecFichier(true);
this.formOffre.setAvecLien(false);
this.formOffre.setLienAttache("");
idOffreAjoutee = getOffreDomainService().addOffre(this.formOffre);
this.formOffre.setIdOffre(idOffreAjoutee);
this.formOffre.setDateCreation(new Date());
this.formOffre.setLoginCreation(getSessionController().getCurrentLogin());
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape4Confirmation");
getSessionController().setCreationOffreCurrentPage("_creationOffreEtape4Confirmation");
addInfoMessage(null, "OFFRE.CREATION.CONFIRMATION", this.formOffre.getIdOffre());
// mailAjout();
}catch (DataAddException|WebServiceDataBaseException e) {
logger.error(e);
}
}else{
addErrorMessage("formCreationOffre", "OFFRE.SELECTIONFICHIER.OBLIGATOIRE");
}
break;
case 2:
try{
this.formOffre.setFichier(null);
this.formOffre.setIdFichier(0);
this.formOffre.setAvecFichier(false);
this.formOffre.setAvecLien(true);
idOffreAjoutee = getOffreDomainService().addOffre(this.formOffre);
this.formOffre.setIdOffre(idOffreAjoutee);
this.formOffre.setDateCreation(new Date());
this.formOffre.setLoginCreation(getSessionController().getCurrentLogin());
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape4Confirmation");
getSessionController().setCreationOffreCurrentPage("_creationOffreEtape4Confirmation");
addInfoMessage(null, "OFFRE.CREATION.CONFIRMATION", this.formOffre.getIdOffre());
mailAjout();
}catch (DataAddException|WebServiceDataBaseException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.CREATION.ERREURAJOUT");
}
break;
}
}else{
if(this.formOffre.getTempsTravail()!=null)this.formOffre.setIdTempsTravail(this.formOffre.getTempsTravail().getId());
else this.formOffre.setIdTempsTravail(0);
if(this.formOffre.getUniteDuree()!=null)this.formOffre.setIdUniteDuree(this.formOffre.getUniteDuree().getId());
else this.formOffre.setIdUniteDuree(0);
if(this.formOffre.getModesCandidature()!=null){
ArrayList<Integer> l = new ArrayList<Integer>();
for(ModeCandidatureDTO m : this.formOffre.getModesCandidature()){
l.add(m.getId());
}
if(!l.isEmpty())this.formOffre.setIdsModeCandidature(l);
else this.formOffre.setIdsModeCandidature(null);
}
if(this.formOffre.getContactCand()!=null){
try{
this.formOffre.setIdContactCand(this.formOffre.getContactCand().getId());
if(this.formOffre.getContactInfo()!=null)this.formOffre.setIdContactInfo(this.formOffre.getContactInfo().getId());
this.formOffre.setFichier(null);
this.formOffre.setIdFichier(0);
idOffreAjoutee = getOffreDomainService().addOffre(this.formOffre);
this.formOffre.setIdOffre(idOffreAjoutee);
this.formOffre.setDateCreation(new Date());
this.formOffre.setLoginCreation(getSessionController().getCurrentLogin());
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape4Confirmation");
getSessionController().setCreationOffreCurrentPage("_creationOffreEtape4Confirmation");
addInfoMessage(null, "OFFRE.CREATION.CONFIRMATION", this.formOffre.getIdOffre());
mailAjout();
}catch (DataAddException|WebServiceDataBaseException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.CREATION.ERREURAJOUT");
}
}else{
addErrorMessage("formCreationOffre:contactCand", "OFFRE.SELECTIONCONTACTCAND.OBLIGATOIRE");
}
}
if(this.diffusionDirecte){
this.currentOffre = this.formOffre;
this.diffuserOffre();
} else if (!this.formOffre.isEstDiffusee()){
addInfoMessage(null, "OFFRE.CREATION.CONFIRMATION.DIFFUSION", this.formOffre.getIdOffre());
}
this.diffusionDirecte = false;
// return ret;
}
/**
*
*/
public void mailAjout(){
//Envoi mail sur la mailing list entreprise
String infoPersonne="";
if(getSessionController().isAdminPageAuthorized() && getSessionController().getCurrentAuthAdminStructure()!=null){
infoPersonne+=getSessionController().getCurrentAuthAdminStructure().getNom()+" "+getSessionController().getCurrentAuthAdminStructure().getPrenom()+" ("+getSessionController().getCurrentLogin()+")";
}else if(getSessionController().isPageAuthorized() && getSessionController().getCurrentAuthContact()!=null){
infoPersonne+=getSessionController().getCurrentAuthContact().getNom()+" "+getSessionController().getCurrentAuthContact().getPrenom()+" ("+getSessionController().getCurrentLogin()+")";
}else{
infoPersonne+=getSessionController().getCurrentLogin();
}
if(centreGestionDepotAnonyme!=null && centreGestionDepotAnonyme.getIdCentreGestion()>0){
if(StringUtils.hasText(centreGestionDepotAnonyme.getMail())){
InternetAddress ia = null;
try {
ia = new InternetAddress(centreGestionDepotAnonyme.getMail());
infoPersonne="depot anonyme";
getSmtpService().send(
ia,
getString("MAIL.ADMIN.OFFRE.SUJETAJOUT", getSessionController().getApplicationNameEntreprise(),this.formOffre.getStructure().printAdresse(), infoPersonne),
getString("MAIL.ADMIN.OFFRE.MESSAGEAJOUT", getSessionController().getApplicationNameEntreprise(),this.formOffre.getIdOffre() +", "+this.formOffre.getIntitule(),this.formOffre.getStructure().printAdresse(), infoPersonne),
""
);
} catch (AddressException e) {
logger.info(e);
}
}
}else if(getSessionController().isMailingListEntrMailAvertissementAjoutOffre() && StringUtils.hasText(getSessionController().getMailingListEntr())
&& (getSessionController().isAdminPageAuthorized() || getSessionController().isPageAuthorized())){
getSmtpService().send(
getSessionController().getMailingListEntrIA(),
getString("MAIL.ADMIN.OFFRE.SUJETAJOUT", getSessionController().getApplicationNameEntreprise(),this.formOffre.getStructure().printAdresse(), infoPersonne),
getString("MAIL.ADMIN.OFFRE.MESSAGEAJOUT", getSessionController().getApplicationNameEntreprise(),this.formOffre.getIdOffre() +", "+this.formOffre.getIntitule(),getSessionController().getCurrentManageStructure().printAdresse(), infoPersonne),
""
);
}
}
/* ***************************************************************
* Modification d'une offre
****************************************************************/
public void initVarsOffre(){
this.etablissementController.reloadServices();
this.etablissementController.reloadContacts();
}
/**
* @return String
*/
public String goToEntrepriseModificationOffre(){
String ret=null;
this.formOffre=(OffreDTO) this.currentOffre.clone();
if(this.formOffre!=null){
if(this.formOffre.isAvecFichier() || this.formOffre.isAvecLien()){
this.avecFichierOuLien=true;
if(this.formOffre.isAvecFichier()){
this.fichierOuLien=1;
if(this.currentOffre.getFichier()!=null){
this.formOffre.setFichier((FichierDTO)this.currentOffre.getFichier().clone());
}
}
else if(this.formOffre.isAvecLien())this.fichierOuLien=2;
}else{
this.avecFichierOuLien=false;
this.fichierOuLien=0;
}
ret="modificationOffre";
}
return ret;
}
/**
* @return String
*/
public String goToModificationOffre(){
String ret=null;
if(this.currentOffre!=null){
this.formOffre=(OffreDTO) this.currentOffre.clone();
// Si l'on est cote depot en tant qu'entreprise
if ("offre".equalsIgnoreCase(this.currentRecapOffre)) {
this.retour = "recapitulatifOffre";
} else {
// Sinon on est dans l'un des 3 autres cas
this.currentOffre = getOffreDomainService().getOffreFromId(this.currentOffre.getIdOffre());
this.currentOffre.setStructure(getStructureDomainService().getStructureFromId(this.currentOffre.getIdStructure()));
// Si l'on est dans le cas du recapitulatif d'offre cote stage avec etab
if ("offreEtabCentre".equalsIgnoreCase(this.currentRecapOffre)) {
// On conserve le squelette dans lequel on va revenir
this.retour = "recapitulatifOffreEtabCentre";
getSessionController().setCentreGestionRattachement(this.currentOffre.getCentreGestion());
if (!isListeCurrentIdsCentresGestionContainsIdCGCurrentOffre()) {
CentreGestionDTO c = getCentreGestionDomainService().getCentreGestion(this.currentOffre.getIdCentreGestion());
if (c != null){
this.currentOffre.setCentreGestion(c);
} else {
return ret;
}
} else {
if (getSessionController().getCurrentIdsCentresGestion() != null &&
!getSessionController().getCurrentIdsCentresGestion().isEmpty()) {
for (CentreGestionDTO c : getSessionController().getCurrentCentresGestion()) {
if (c.getIdCentreGestion() == this.currentOffre.getIdCentreGestion()) {
this.currentOffre.setCentreGestion(c);
break;
}
}
}
}
} else {
// On conserve le squelette dans lequel on va revenir
this.retour = "recapitulatifOffreEtab";
}
}
if(this.formOffre.isAvecFichier() || this.formOffre.isAvecLien()){
this.avecFichierOuLien=true;
if(this.formOffre.isAvecFichier()){
this.fichierOuLien=1;
if(this.currentOffre.getFichier()!=null){
this.formOffre.setFichier((FichierDTO)this.currentOffre.getFichier().clone());
}
}
else if(this.formOffre.isAvecLien())this.fichierOuLien=2;
}else{
this.avecFichierOuLien=false;
this.fichierOuLien=0;
}
ret="modificationOffre";
}
return ret;
}
/**
* Vrai si currentIdsCentresGestion contains l'id du centre de gestion de l'offre courante : currentOffre
* Auquel cas modification possible du centre de gestion pour une offre
* @return boolean
*/
public boolean isListeCurrentIdsCentresGestionContainsIdCGCurrentOffre(){
boolean ret=false;
if(getSessionController().getCurrentIdsCentresGestion()!=null &&
!getSessionController().getCurrentIdsCentresGestion().isEmpty() &&
((ArrayList<Integer>)getSessionController().getCurrentIdsCentresGestion()).
contains(this.currentOffre.getIdCentreGestion())){
ret=true;
}
return ret;
}
/**
*
*/
public void goToModificationOffreModifEtab(){
this.etablissementController.goToModificationEtablissement();
getSessionController().setModificationOffreCurrentPage("_modificationOffreEtape05ModifEtab");
}
/**
*
*/
public void modifierOffreModifierEtablissement(){
String ret=this.etablissementController.modifierEtablissement();
this.currentOffre.setStructure(this.etablissementController.getFormStructure());
FacesContext fc = FacesContext.getCurrentInstance();
Iterator<FacesMessage> ifm = fc.getMessages("formModifEtab");
while(ifm.hasNext()){
FacesMessage fm = ifm.next();
fc.addMessage("formModificationOffre:formModifEtab", new FacesMessage(FacesMessage.SEVERITY_ERROR,fm.getSummary(),fm.getDetail()));
ifm.remove();
}
ifm = fc.getMessages("formAffEtab");
while(ifm.hasNext()){
FacesMessage fm = ifm.next();
fc.addMessage("formModificationOffre:formAffEtab", new FacesMessage(fm.getSummary(),fm.getDetail()));
ifm.remove();
}
if(StringUtils.hasText(ret)){
getSessionController().setModificationOffreCurrentPage("_modificationOffreEtape04DetailsEtab");
}
// return "";
}
/**
* @return String
*/
public void modificationOffreDetailsEtab(){
this.formOffre.setCentreGestion(getCentreGestionDomainService().getCentreGestion(this.formOffre.getIdCentreGestion()));
getSessionController().setCentreGestionRattachement(this.formOffre.getCentreGestion());
this.modificationOffre();
}
/**
* Envoi vers l'Etape 2 : Saisie de l'offre
*/
public void goToModificationOffreEtape2(){
getSessionController().setModificationOffreCurrentPage("_modificationOffreEtape2");
if(this.formOffre.getIdLieuPays()<=0){
this.formOffre.setLieuPays(this.formOffre.getStructure().getPays());
if(getSessionController().isRecupererCommunesDepuisApogee() &&
getBeanUtils().isFrance(this.formOffre.getLieuPays())){
List<SelectItem> lTmp = majCommunes(""+this.formOffre.getLieuCodePostal());
if(lTmp!=null && !lTmp.isEmpty()){
this.formOffreCommunesListening=lTmp;
}else{
this.formOffreCommunesListening=new ArrayList<SelectItem>();
}
}
}
if(this.avecFichierOuLien){
switch (this.fichierOuLien) {
case 1:
//Si l'offre modifiée était déjà avec fichier joint, on ne fait rien
if(!this.currentOffre.isAvecFichier()){
this.formOffre.setAvecFichier(true);
this.formOffre.setAvecLien(false);
this.formOffre.setLienAttache("");
try {
FichierDTO o = new FichierDTO();
o.setNomFichier("");
int idFichier = getOffreDomainService().addFichier(o);
o.setIdFichier(idFichier);
this.formOffre.setFichier(o);
getSessionController().getOffreFileUploadBean().setPrefix(idFichier);
} catch (DataAddException|WebServiceDataBaseException e) {
logger.error(e);
}
}
break;
case 2:
//Si l'offre modifiée était déjà avec lien, on ne fait rien
if(!this.currentOffre.isAvecLien()){
this.formOffre.setAvecFichier(false);
this.formOffre.setAvecLien(true);
this.formOffre.setLienAttache("http://");
}
break;
default:
getSessionController().setModificationOffreCurrentPage("_modificationOffreEtape1");
break;
}
}
this.formOffre.setIdTypeOffre(this.formOffre.getTypeOffre().getId());
//Màj liste des contrats
List<ContratOffreDTO> l = getNomenclatureDomainService().getContratsOffreFromIdTypeOffre(this.formOffre.getIdTypeOffre());
if(l!=null && !l.isEmpty()){
this.contratsListening=new ArrayList<>();
for(ContratOffreDTO c : l){
this.contratsListening.add(new SelectItem(c,c.getLibelle()));
}
}else{
this.contratsListening=null;
}
// Initialisations du temps travail et des modes candidature avec ceux deja saisis dans l'ob
if (this.formOffre.getIdTempsTravail() != 0) {
this.formOffre.setTempsTravail(getNomenclatureDomainService().getTempsTravailFromId(this.formOffre.getIdTempsTravail()));
}
if (this.formOffre.getIdsModeCandidature() != null && !this.formOffre.getIdsModeCandidature().isEmpty()){
List<ModeCandidatureDTO> lmc = new ArrayList<>();
for (Integer id : this.formOffre.getIdsModeCandidature()){
lmc.add(getNomenclatureDomainService().getModeCandidatureFromId(id));
}
this.formOffre.setModesCandidature(lmc);
}
this.fapN3Listening=getFapN3FromNumQualif(this.formOffre.getIdQualificationSimplifiee());
if(getSessionController().isRecupererCommunesDepuisApogee() &&
getBeanUtils().isFrance(this.formOffre.getLieuPays())){
List<SelectItem> lTmp = majCommunes(""+this.formOffre.getLieuCodePostal());
if(lTmp!=null && !lTmp.isEmpty()){
this.formOffreCommunesListening=lTmp;
}else{
this.formOffreCommunesListening=new ArrayList<SelectItem>();
}
}
}
/**
* Modification de l'offre
*/
public void modificationOffre(){
String ret=_modificationOffre();
if(StringUtils.hasText(ret)){
getSessionController().setModificationOffreCurrentPage(ret);
this.currentOffre=(OffreDTO) this.formOffre.clone();
if(this.formOffre.getFichier()!=null) this.currentOffre.setFichier((FichierDTO)(this.formOffre.getFichier().clone()));
this.formOffre=null;
if(this.listeOffres!=null && this.listeOffres.contains(this.currentOffre)){
int id = this.listeOffres.indexOf(this.currentOffre);
if(id>0){
this.listeOffres.set(id,this.currentOffre);
}
}
if(this.resultatsRechercheOffre!=null && this.resultatsRechercheOffre.contains(this.currentOffre)){
//rechercherOffre();
int id = this.resultatsRechercheOffre.indexOf(this.currentOffre);
if(id>0){
this.resultatsRechercheOffre.set(id,this.currentOffre);
reloadRechercheOffrePaginator();
}
}
}
// return ret;
}
/**
* Méthode modification de l'offre subDivisée en 2 pour gérer la modification par une entreprise et par un centre
* @return String
*/
public String _modificationOffre(){
String ret=null;
this.formOffre.setLoginModif(getSessionController().getCurrentLogin());
if(this.formOffre.getLieuPays()!=null) {
this.formOffre.setIdLieuPays(this.formOffre.getLieuPays().getId());
if (getBeanUtils().isFrance(this.formOffre.getLieuPays()) && getSessionController().isRecupererCommunesDepuisApogee()) {
if (!"0".equals(this.formOffre.getCodeCommune())) {
//Récupération de la commune pour en avoir le libellé
CommuneDTO c = getGeographieRepositoryDomain().getCommuneFromDepartementEtCodeCommune(this.formOffre.getLieuCodePostal(), "" + this.formOffre.getCodeCommune());
if (c != null) {
this.formOffre.setLieuCommune(c.getLibCommune());
}
}
}
}
if(this.formOffre.getFapQualificationSimplifiee()!=null)this.formOffre.setIdQualificationSimplifiee(this.formOffre.getFapQualificationSimplifiee().getId());
//if(this.formOffre.getFapN3()!=null)this.formOffre.setCodeFAP_N3(this.formOffre.getFapN3().getCode());
if(this.formOffre.getFapN1()!=null)this.formOffre.setCodeFAP_N3(this.formOffre.getFapN1().getCode());
if(this.formOffre.getTypeOffre()!=null)this.formOffre.setIdTypeOffre(this.formOffre.getTypeOffre().getId());
else this.formOffre.setIdContratOffre(0);
if(this.formOffre.getContratOffre()!=null)this.formOffre.setIdContratOffre(this.formOffre.getContratOffre().getId());
else this.formOffre.setIdContratOffre(0);
if(this.formOffre.getNiveauFormation()!=null)this.formOffre.setIdNiveauFormation(this.formOffre.getNiveauFormation().getId());
else this.formOffre.setIdNiveauFormation(0);
this.formOffre.setAnneeUniversitaire(getBeanUtils().getAnneeUniversitaireCourante(new Date()));
if(this.avecFichierOuLien){
this.formOffre.setTempsTravail(null);
this.formOffre.setIdTempsTravail(0);
this.formOffre.setUniteDuree(null);
this.formOffre.setIdUniteDuree(0);
this.formOffre.setModesCandidature(null);
this.formOffre.setIdsModeCandidature(null);
this.formOffre.setContactCand(null);
this.formOffre.setContactInfo(null);
this.formOffre.setIdContactCand(0);
this.formOffre.setIdContactInfo(0);
switch (this.fichierOuLien) {
case 1:
if(this.formOffre.getIdFichier()>0){
try{
this.formOffre.setAvecFichier(true);
this.formOffre.setAvecLien(false);
this.formOffre.setLienAttache(null);
getOffreDomainService().updateOffre(this.formOffre);
this.formOffre.setDateModif(new Date());
this.formOffre.setLoginModif(getSessionController().getCurrentLogin());
//Maj listes
if(this.listeOffres!=null && ((ArrayList<OffreDTO>)this.listeOffres).contains(this.formOffre)){
this.listeOffres.set(this.listeOffres.indexOf(this.formOffre), this.formOffre);
}
if(this.resultatsRechercheOffre!=null && ((ArrayList<OffreDTO>)this.resultatsRechercheOffre).contains(this.formOffre)){
this.resultatsRechercheOffre.set(this.resultatsRechercheOffre.indexOf(this.formOffre), this.formOffre);
checkListeResultats();
}
ret="_modificationOffreEtape4Confirmation";
addInfoMessage(null, "OFFRE.MODIFICATION.CONFIRMATION", this.formOffre.getIdOffre());
mailModif();
}catch (DataAddException|WebServiceDataBaseException e) {
logger.error(e);
}
}else{
addErrorMessage("formModificationOffre:opUploadFile:uploadFile", "OFFRE.SELECTIONFICHIER.OBLIGATOIRE");
return null;
}
break;
case 2:
try{
this.formOffre.setFichier(null);
this.formOffre.setIdFichier(0);
this.formOffre.setAvecFichier(false);
this.formOffre.setAvecLien(true);
getOffreDomainService().updateOffre(this.formOffre);
this.formOffre.setDateModif(new Date());
this.formOffre.setLoginModif(getSessionController().getCurrentLogin());
//Maj listes
if(this.listeOffres!=null && ((ArrayList<OffreDTO>)this.listeOffres).contains(this.formOffre)){
this.listeOffres.set(this.listeOffres.indexOf(this.formOffre), this.formOffre);
}
if(this.resultatsRechercheOffre!=null && ((ArrayList<OffreDTO>)this.resultatsRechercheOffre).contains(this.formOffre)){
this.resultatsRechercheOffre.set(this.resultatsRechercheOffre.indexOf(this.formOffre), this.formOffre);
checkListeResultats();
}
//Suppression de l'ancien fichier
if(this.currentOffre.isAvecFichier() &&
this.currentOffre.getIdFichier()>0){
try{
if(this.currentOffre.getFichier()!=null
&& StringUtils.hasText(this.currentOffre.getFichier().getNomFichier())){
getSessionController().getOffreFileUploadBean().deleteFileFromDirectory(
this.currentOffre.getIdFichier(), this.currentOffre.getFichier().getNomFichier());
}
getOffreDomainService().deleteFichier(this.currentOffre.getIdFichier());
}catch (DataDeleteException|WebServiceDataBaseException e) {
logger.warn(e);
}
}
mailModif();
ret="_modificationOffreEtape4Confirmation";
addInfoMessage(null, "OFFRE.MODIFICATION.CONFIRMATION", this.formOffre.getIdOffre());
}catch (DataAddException|WebServiceDataBaseException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.MODIFICATION.ERREURAJOUT");
return null;
}
break;
}
}else{
this.formOffre.setFichier(null);
this.formOffre.setIdFichier(0);
this.formOffre.setLienAttache(null);
this.formOffre.setAvecFichier(false);
this.formOffre.setAvecLien(false);
if(this.formOffre.getTempsTravail()!=null)this.formOffre.setIdTempsTravail(this.formOffre.getTempsTravail().getId());
else this.formOffre.setIdTempsTravail(0);
if(this.formOffre.getUniteDuree()!=null)this.formOffre.setIdUniteDuree(this.formOffre.getUniteDuree().getId());
else this.formOffre.setIdUniteDuree(0);
if(this.formOffre.getModesCandidature()!=null){
ArrayList<Integer> l = new ArrayList<Integer>();
for(ModeCandidatureDTO m : this.formOffre.getModesCandidature()){
l.add(m.getId());
}
if(!l.isEmpty())this.formOffre.setIdsModeCandidature(l);
else this.formOffre.setIdsModeCandidature(null);
}
if(this.formOffre.getContactCand()!=null){
try{
this.formOffre.setIdContactCand(this.formOffre.getContactCand().getId());
if(this.formOffre.getContactInfo()!=null){
this.formOffre.setIdContactInfo(this.formOffre.getContactInfo().getId());
} else {
this.formOffre.setIdContactInfo(0);
}
this.formOffre.setFichier(null);
this.formOffre.setIdFichier(0);
if(getOffreDomainService().updateOffre(this.formOffre)){
this.formOffre.setDateModif(new Date());
this.formOffre.setLoginModif(getSessionController().getCurrentLogin());
//Maj listes
if(this.listeOffres!=null && ((ArrayList<OffreDTO>)this.listeOffres).contains(this.formOffre)){
this.listeOffres.set(this.listeOffres.indexOf(this.formOffre), this.formOffre);
}
if(this.resultatsRechercheOffre!=null && ((ArrayList<OffreDTO>)this.resultatsRechercheOffre).contains(this.formOffre)){
this.resultatsRechercheOffre.set(this.resultatsRechercheOffre.indexOf(this.formOffre), this.formOffre);
checkListeResultats();
}
//Suppression de l'ancien fichier
if(this.currentOffre.isAvecFichier() &&
this.currentOffre.getIdFichier()>0){
try{
if(this.currentOffre.getFichier()!=null
&& StringUtils.hasText(this.currentOffre.getFichier().getNomFichier())){
getSessionController().getOffreFileUploadBean().deleteFileFromDirectory(
this.currentOffre.getIdFichier(), this.currentOffre.getFichier().getNomFichier());
}
getOffreDomainService().deleteFichier(this.currentOffre.getIdFichier());
}catch (DataDeleteException|WebServiceDataBaseException e) {
logger.warn(e);
}
}
}
ret="_modificationOffreEtape4Confirmation";
addInfoMessage(null, "OFFRE.MODIFICATION.CONFIRMATION", this.formOffre.getIdOffre());
mailModif();
}catch (DataUpdateException|WebServiceDataBaseException e) {
// ret="_modificationOffreEtape4Confirmation";
logger.error(e);
addErrorMessage(null, "OFFRE.MODIFICATION.ERREURMODIF");
return null;
}
}else{
addErrorMessage("formModificationOffre:contactCand", "OFFRE.SELECTIONCONTACTCAND.OBLIGATOIRE");
return null;
}
}
return ret;
}
/**
*
*/
public void mailModif(){
if(getSessionController().isMailingListEntrMailAvertissementModifOffre() && StringUtils.hasText(getSessionController().getMailingListEntr())
&& (getSessionController().isAdminPageAuthorized() || getSessionController().isPageAuthorized())){
//Envoi mail sur la mailing list entreprise
String infoPersonne="";
if(getSessionController().isAdminPageAuthorized() && getSessionController().getCurrentAuthAdminStructure()!=null){
infoPersonne+=getSessionController().getCurrentAuthAdminStructure().getNom()+" "+getSessionController().getCurrentAuthAdminStructure().getPrenom()+" ("+getSessionController().getCurrentLogin()+")";
}else if(getSessionController().isPageAuthorized() && getSessionController().getCurrentAuthContact()!=null){
infoPersonne+=getSessionController().getCurrentAuthContact().getNom()+" "+getSessionController().getCurrentAuthContact().getPrenom()+" ("+getSessionController().getCurrentLogin()+")";
}else{
infoPersonne+=getSessionController().getCurrentLogin();
}
getSmtpService().send(
getSessionController().getMailingListEntrIA(),
getString("MAIL.ADMIN.OFFRE.SUJETMODIF", getSessionController().getApplicationNameEntreprise(),this.formOffre.getIdOffre() +", "+this.formOffre.getIntitule(), infoPersonne),
getString("MAIL.ADMIN.OFFRE.MESSAGEMODIF", getSessionController().getApplicationNameEntreprise(),this.formOffre.getIdOffre() +", "+this.formOffre.getIntitule(),this.formOffre.getStructure().printAdresse(), infoPersonne),
""
);
}
}
/**
* Suppression d'une offre
*/
public void supprimerOffre(){
try{
getSessionController().setSuppressionOffreCurrentPage("_confirmationDialog");
if(getOffreDomainService().deleteOffreLogique(this.currentOffre.getIdOffre())){
//Maj listes
if(this.listeOffres!=null && ((ArrayList<OffreDTO>)this.listeOffres).contains(this.currentOffre)){
this.listeOffres.remove(this.listeOffres.indexOf(this.currentOffre));
}
if(this.resultatsRechercheOffre!=null && ((ArrayList<OffreDTO>)this.resultatsRechercheOffre).contains(this.currentOffre)){
this.resultatsRechercheOffre.remove(this.resultatsRechercheOffre.indexOf(this.currentOffre));
checkListeResultats();
}
mailSuppr();
this.currentOffre=null;
}
addInfoMessage(null, "OFFRE.SUPPR.CONFIRMATION");
}catch (DataUpdateException|WebServiceDataBaseException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.SUPPR.ERREUR");
}
}
/**
*
*/
public void mailSuppr(){
if(getSessionController().isMailingListEntrMailAvertissementSupprOffre() && StringUtils.hasText(getSessionController().getMailingListEntr())
&& (getSessionController().isAdminPageAuthorized() || getSessionController().isPageAuthorized())){
//Envoi mail sur la mailing list entreprise
String infoPersonne="";
if(getSessionController().isAdminPageAuthorized() && getSessionController().getCurrentAuthAdminStructure()!=null){
infoPersonne+=getSessionController().getCurrentAuthAdminStructure().getNom()+" "+getSessionController().getCurrentAuthAdminStructure().getPrenom()+" ("+getSessionController().getCurrentLogin()+")";
}else if(getSessionController().isPageAuthorized() && getSessionController().getCurrentAuthContact()!=null){
infoPersonne+=getSessionController().getCurrentAuthContact().getNom()+" "+getSessionController().getCurrentAuthContact().getPrenom()+" ("+getSessionController().getCurrentLogin()+")";
}else{
infoPersonne+=getSessionController().getCurrentLogin();
}
getSmtpService().send(
getSessionController().getMailingListEntrIA(),
getString("MAIL.ADMIN.OFFRE.SUJETSUPPR", getSessionController().getApplicationNameEntreprise(),this.currentOffre.getIdOffre() +", "+this.currentOffre.getIntitule(), infoPersonne),
getString("MAIL.ADMIN.OFFRE.MESSAGESUPPR", getSessionController().getApplicationNameEntreprise(),this.currentOffre.getIdOffre() +", "+this.currentOffre.getIntitule(),getSessionController().getCurrentManageStructure().printAdresse(), infoPersonne),
""
);
}
}
@SuppressWarnings("unused")
private boolean ciblageInterdit;
public boolean isCiblageInterdit(){
if (this.currentOffre != null){
CentreGestionDTO cgEntr = getCentreGestionDomainService().getCentreEntreprise();
if (cgEntr != null
&& this.currentOffre.getIdCentreGestion() == cgEntr.getIdCentreGestion()
&& getSessionController().getCurrentAuthPersonnel() != null
&& !getSessionController().isPageAuthorized()
&& !getSessionController().isAdminPageAuthorized()
&& !getSessionController().isSuperAdminPageAuthorized()){
return true;
}
}
return false;
}
/**
* @return String
*/
public void diffuserOffre(){
getSessionController().setDiffusionOffreCurrentPage("_confirmationDialog");
if(this.currentOffre!=null && this.currentOffre.getIdOffre()>0){
try{
int x = (this.dureeDiffusion - 1);
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
int annee = Integer.parseInt(dateFormat.format(new Date()).split("/")[2]);
int mois = Integer.parseInt(dateFormat.format(new Date()).split("/")[1]);
int jour = Integer.parseInt(dateFormat.format(new Date()).split("/")[0]);
// date du jour + x mois selon la DureeDiffusion choisie
if ((mois+x) < 12){
mois = mois + x;
} else if((mois+x) > 12 && (mois+x) < 24){
mois = mois + x - 12;
annee = annee + 1;
} else {
mois = mois + x - 24;
annee = annee + 2;
}
gc.set(annee,mois,jour);
getOffreDomainService().updateDiffusionOffre(this.currentOffre.getIdOffre(), getSessionController().getCurrentLogin(),gc.getTime());
getOffreDomainService().updateValidationOffre(this.currentOffre.getIdOffre(), getSessionController().getCurrentLogin());
addInfoMessage(null, "OFFRE.GESTION.DIFFUSION.CONFIRMATION");
getOffreDomainService().updateOffrePourvue(this.currentOffre.getIdOffre(), false);
if (getSessionController().isModerationActive() && getSessionController().isAvertissementEntrepriseDiffusion()){
String text=getString("ALERTES_MAIL.AVERTISSEMENT_ENTREPRISE_DIFFUSION",this.currentOffre.getIdOffre());
String sujet=getString("ALERTES_MAIL.AVERTISSEMENT_ENTREPRISE_DIFFUSION.SUJET",this.currentOffre.getIdOffre());
if (this.currentOffre.isAvecFichier() || this.currentOffre.isAvecLien()){
// Il est necessaire de verifier d'abord si un fichier/lien est present car dans ce cas il n'y aura pas de contact
// et donc pas de mail envoyé
} else {
if (this.currentOffre.getContactCand()!= null && this.currentOffre.getContactCand().getMail() != null
&& !this.currentOffre.getContactCand().getMail().isEmpty()){
getSmtpService().send(new InternetAddress(this.currentOffre.getContactCand().getMail()),
sujet,text,text);
} else {
addErrorMessage(null, "OFFRE.GESTION.DIFFUSION.ALERTE.ERREUR_MAIL");
}
}
}
//Màj de l'objet courant
this.currentOffre.setEstPourvue(false);
this.currentOffre.setEstDiffusee(true);
this.currentOffre.setDateDiffusion(new Date());
this.currentOffre.setDateFinDiffusion(gc.getTime());
this.currentOffre.setEstValidee(true);
this.currentOffre.setEtatValidation(1);
//Maj listes
if(this.listeOffres!=null && ((ArrayList<OffreDTO>)this.listeOffres).contains(this.currentOffre)){
this.listeOffres.set(this.listeOffres.indexOf(this.currentOffre), this.currentOffre);
}
if(this.resultatsRechercheOffre!=null && ((ArrayList<OffreDTO>)this.resultatsRechercheOffre).contains(this.currentOffre)){
this.resultatsRechercheOffre.set(this.resultatsRechercheOffre.indexOf(this.currentOffre), this.currentOffre);
checkListeResultats();
}
}catch (DataUpdateException|WebServiceDataBaseException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.GESTION.DIFFUSION.ERREUR");
}catch (AddressException ade){
logger.error("AddressException", ade);
addErrorMessage(null, "GENERAL.ERREUR_MAIL");
}
}
// return ret;
}
/**
* Arrêt de la diffusion de l'offre actuellement sélectionnée
*/
public void stopDiffusionOffre(){
getSessionController().setStopDiffusionOffreCurrentPage("_confirmationDialog");
if(this.currentOffre!=null){
try{
getOffreDomainService().updateStopDiffusionOffre(this.currentOffre.getIdOffre(), getSessionController().getCurrentLogin());
getOffreDomainService().updateStopValidationOffre(this.currentOffre.getIdOffre(), getSessionController().getCurrentLogin());
addInfoMessage(null, "OFFRE.GESTION.STOPDIFFUSION.CONFIRMATION");
//Màj de l'objet courant
this.currentOffre.setDateDiffusion(null);
this.currentOffre.setDateFinDiffusion(null);
this.currentOffre.setEstDiffusee(false);
this.currentOffre.setEstValidee(false);
this.currentOffre.setEtatValidation(0);
//Maj listes
if(this.listeOffres!=null && ((ArrayList<OffreDTO>)this.listeOffres).contains(this.currentOffre)){
this.listeOffres.set(this.listeOffres.indexOf(this.currentOffre), this.currentOffre);
}
if(this.resultatsRechercheOffre!=null && ((ArrayList<OffreDTO>)this.resultatsRechercheOffre).contains(this.currentOffre)){
this.resultatsRechercheOffre.set(this.resultatsRechercheOffre.indexOf(this.currentOffre), this.currentOffre);
checkListeResultats();
}
}catch (DataUpdateException|WebServiceDataBaseException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.GESTION.STOPDIFFUSION.ERREUR");
}
}
// return ret;
}
/**
* Indiquer l'offre comme pourvue
*/
public void offrePourvue(){
getSessionController().setOffrePourvueCurrentPage("_confirmationDialog");
if(this.currentOffre!=null){
try{
getOffreDomainService().updateOffrePourvue(this.currentOffre.getIdOffre(), !this.currentOffre.isEstPourvue());
getOffreDomainService().updateStopDiffusionOffre(this.currentOffre.getIdOffre(), getSessionController().getCurrentLogin());
//M�j de l'objet courant
this.currentOffre.setEstPourvue(!this.currentOffre.isEstPourvue());
this.currentOffre.setDateDiffusion(null);
this.currentOffre.setDateFinDiffusion(null);
this.currentOffre.setEstDiffusee(false);
this.currentOffre.setEstValidee(false);
this.currentOffre.setEtatValidation(0);
//Maj listes
if(this.listeOffres!=null && ((ArrayList<OffreDTO>)this.listeOffres).contains(this.currentOffre)){
this.listeOffres.set(this.listeOffres.indexOf(this.currentOffre), this.currentOffre);
}
if(this.resultatsRechercheOffre!=null && ((ArrayList<OffreDTO>)this.resultatsRechercheOffre).contains(this.currentOffre)){
this.resultatsRechercheOffre.set(this.resultatsRechercheOffre.indexOf(this.currentOffre), this.currentOffre);
checkListeResultats();
}
if(this.currentOffre.isEstPourvue())addInfoMessage(null, "OFFRE.GESTION.POURVOIROFFRE.CONFIRMATION");
if(!this.currentOffre.isEstPourvue())addInfoMessage(null, "OFFRE.GESTION.POURVOIROFFRE.CONFIRMATIONNON");
}catch (DataUpdateException|WebServiceDataBaseException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.GESTION.POURVOIROFFRE.ERREUR");
}
}
// return ret;
}
/**
* @return int : nombre d'éléments dans la liste offresDiffusion du currentOffre
*/
public int getCurrentOffreSizeOffresDiffusion(){
currentOffreSizeOffresDiffusion = 0;
if(this.currentOffre!=null && this.currentOffre.getOffresDiffusion()!=null){
currentOffreSizeOffresDiffusion=this.currentOffre.getOffresDiffusion().size();
}
return currentOffreSizeOffresDiffusion;
}
/**
* @param l
* @param id
* @return SelectItem
*/
public SelectItem containsSelectItem(List<SelectItem> l, int id){
if(l!=null && !l.isEmpty()){
for(SelectItem si : l){
if(si.getValue() instanceof Integer){
if((Integer)(si.getValue())==id){
return si;
}
}
}
}
return null;
}
/**
* Maj des listes pour le panel de diffusion
*/
public void majListesCentresDiffusion(){
if(this.currentOffre!=null){
this.dualListCiblageCentres = new DualListModel<>(new ArrayList<CentreGestionDTO>(),new ArrayList<CentreGestionDTO>());
if(this.currentOffre.getOffresDiffusion()!=null && !this.currentOffre.getOffresDiffusion().isEmpty()){
for(OffreDiffusionDTO od : this.currentOffre.getOffresDiffusion()){
this.dualListCiblageCentres.getTarget().add(getCentreGestionDomainService().getCentreGestion(od.getIdCentreGestion()));
}
}
if(this.listesCentresGestionEtablissement==null || this.listesCentresGestionEtablissement.isEmpty()){
getListesCentresGestionEtablissement();
}
if(!this.listesCentresGestionEtablissement.isEmpty()){
int id =(Integer) this.listesCentresGestionEtablissement.get(0).getValue();
this.idCentreEtablissementSelect=id;
if(this.listesCentresGestionEtablissement.size()>1){
id=(Integer) this.listesCentresGestionEtablissement.get(1).getValue();
if(id>0){
this.idCentreEtablissementSelect=id;
}
}
if(id>0){
List<CentreGestionDTO> l = getCentreGestionDomainService().getCentreGestionList(
getSessionController().getCodeUniversite());
if(l!=null && !l.isEmpty()){
this.dualListCiblageCentres.setSource(new ArrayList<CentreGestionDTO>());
for(CentreGestionDTO cg : l){
if(cg.getIdCentreGestion()!=id){
// Si la liste des centres selectionnes ne contient pas le centre, on l'ajoute a la liste proposee
if(!this.dualListCiblageCentres.getTarget().contains(cg)){
this.dualListCiblageCentres.getSource().add(cg);
}
}
}
}
}
}
}
}
/**
* Action de diffusion de l'offre aux centres sélectionnés
*/
public void diffusionCentreOffre(){
getSessionController().setDiffusionCentreOffreCurrentPage("_confirmationDialog");
if(this.currentOffre!=null){
if(this.idCentreEtablissementSelect==0 || this.dualListCiblageCentres.getTarget()==null
|| this.dualListCiblageCentres.getTarget().isEmpty()){
try{
if(getOffreDomainService().deleteOffreDiffusionFromId(this.currentOffre.getIdOffre())){
this.currentOffre.setOffresDiffusion(null);
addInfoMessage(null, "OFFRE.GESTION.DIFFUSIONCENTRE.CONFIRMATION");
}
}catch (DataDeleteException|WebServiceDataBaseException|DataAddException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.GESTION.DIFFUSIONCENTRE.ERREUR");
}
} else if(this.dualListCiblageCentres.getTarget()!=null
&& !this.dualListCiblageCentres.getTarget().isEmpty()){
List<OffreDiffusionDTO> l = new ArrayList<OffreDiffusionDTO>();
for(CentreGestionDTO centre : this.dualListCiblageCentres.getTarget()){
OffreDiffusionDTO od = new OffreDiffusionDTO();
od.setIdCentreGestion(centre.getIdCentreGestion());
od.setIdOffre(this.currentOffre.getIdOffre());
od.setNomCentre(centre.getNomCentre());
l.add(od);
}
this.currentOffre.setOffresDiffusion(l);
try{
getOffreDomainService().addOffreDiffusion(l);
addInfoMessage(null, "OFFRE.GESTION.DIFFUSIONCENTRE.CONFIRMATION");
}catch (DataDeleteException|WebServiceDataBaseException|DataAddException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.GESTION.DIFFUSIONCENTRE.ERREUR");
}
}
}
}
/**
* Transfert d'une offre au centre entreprise avec contacts
* @return String
*/
public void transfererOffre(){
getSessionController().setTransfertOffreCurrentPage("_confirmationDialog");
if(this.currentOffre!=null){
try{
CentreGestionDTO cgEntr = getCentreGestionDomainService().getCentreEntreprise();
if(cgEntr!=null){
this.currentOffre.setIdCentreGestion(cgEntr.getIdCentreGestion());
this.currentOffre.setCentreGestion(cgEntr);
getOffreDomainService().updateOffre(this.currentOffre);
if(this.currentOffre.getIdContactCand()>0){
if(this.currentOffre.getContactCand()!=null){
this.currentOffre.getContactCand().setIdCentreGestion(cgEntr.getIdCentreGestion());
getStructureDomainService().updateContact(this.currentOffre.getContactCand());
}
}
if(this.currentOffre.getIdContactInfo()>0){
if(this.currentOffre.getContactInfo()!=null){
this.currentOffre.getContactInfo().setIdCentreGestion(cgEntr.getIdCentreGestion());
getStructureDomainService().updateContact(this.currentOffre.getContactInfo());
}
}
}
addInfoMessage(null, "OFFRE.GESTION.TRANSFERT.CONFIRMATION");
}catch (DataUpdateException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.GESTION.TRANSFERT.ERREUR");
}catch (WebServiceDataBaseException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.GESTION.TRANSFERT.ERREUR");
}catch (Exception e) {
logger.error(e);
addErrorMessage(null, "OFFRE.GESTION.TRANSFERT.ERREUR");
}
}
// return ret;
}
/**
* Page de retour lors de la modif ou suppression
* @return String
*/
public String retourTo(){
return getRetour();
}
/**
* Vers moteur de recherche offre (entreprise)
* @return String
*/
public String goToRechercheOffre(){
String ret="rechercheOffre";
if(this.critereRechercheOffre==null) this.critereRechercheOffre=initCritereRechercheOffre();
return ret;
}
/**
* Vers moteur de recherche offre (stage)
* @return String
*/
public String goToRechercheOffreStage(){
String ret="rechercheOffreStage";
if(this.critereRechercheOffre==null)this.critereRechercheOffre=initCritereRechercheOffre();
// resetRechercheOffre();
return ret;
}
/**
* Vers moteur de recherche offre public (entreprise)
* @return String
*/
public String goToRechercheOffrePublic(){
String ret="rechercheOffrePublic";
if(this.critereRechercheOffre==null)this.critereRechercheOffre=initCritereRechercheOffre();
return ret;
}
/**
* initCritereRechercheOffre
* @return CritereRechercheOffreDTO
*/
public CritereRechercheOffreDTO initCritereRechercheOffre(){
CritereRechercheOffreDTO c;
c = new CritereRechercheOffreDTO();
c.setLieuPays(null);
return c;
}
/**
* @return String
*/
public String rechercherOffrePublic(){
String ret;
if(this.critereRechercheOffre==null) this.critereRechercheOffre=initCritereRechercheOffre();
if(getSessionController().getCurrentCentresGestion()==null
|| getSessionController().getCurrentCentresGestion().isEmpty()){
CentreGestionDTO cgEntr=getCentreGestionDomainService().getCentreEntreprise();
ArrayList<CentreGestionDTO> lcg = new ArrayList<CentreGestionDTO>();
lcg.add(cgEntr);
getSessionController().setCurrentCentresGestion(lcg);
}
ret=rechercherOffre();
return ret;
}
/**
* Recherche des offres
* @return String
*/
public String rechercherOffre(){
String ret="resultatsRechercheOffre";
// Si on est partie entreprise
if (getSessionController().isAdminPageAuthorized()){
List<CentreGestionDTO> l = getCentreGestionDomainService().getCentreFromUid(getSessionController().getCurrentAuthAdminStructure().getLogin(),
getSessionController().getCodeUniversite());
l.add(getCentreGestionDomainService().getCentreEntreprise());
getSessionController().setCurrentCentresGestion(l);
}
List<Integer> idCG = getSessionController().getCurrentIdsCentresGestion();
if (idCG == null) idCG = new ArrayList<>();
boolean trouveCGEtab = false;
// if(getSessionController().getCurrentAuthEtudiant()!=null){
CentreGestionDTO cgEtab = getCentreGestionDomainService().getCentreEtablissement(getSessionController().getCodeUniversite());
if(cgEtab!=null && cgEtab.getIdCentreGestion()>0){
if (!idCG.isEmpty()){
for (Integer intCG : idCG) {
if (intCG.equals(cgEtab.getIdCentreGestion())) {
trouveCGEtab = true;
}
}
}
if (!trouveCGEtab) {
idCG.add(cgEtab.getIdCentreGestion());
}
}
// }
this.critereRechercheOffre.setIdsCentreGestion(idCG);
if(StringUtils.hasText(this.rechTypeOuContrat)){
if(this.rechTypeOuContrat.contains("t")){
if(Utils.isNumber(this.rechTypeOuContrat.substring(1))){
this.critereRechercheOffre.setTypeOffre(getNomenclatureDomainService().getTypeOffreFromId(
Utils.convertStringToInt(this.rechTypeOuContrat.substring(1))));
this.critereRechercheOffre.setContratOffre(null);
}
}
if(this.rechTypeOuContrat.contains("c")){
if(Utils.isNumber(this.rechTypeOuContrat.substring(1))){
this.critereRechercheOffre.setContratOffre(getNomenclatureDomainService().getContratOffreFromId(
Utils.convertStringToInt(this.rechTypeOuContrat.substring(1))));
if(this.critereRechercheOffre.getContratOffre()!=null &&
this.critereRechercheOffre.getContratOffre().getIdParent()>0){
this.critereRechercheOffre.setTypeOffre(getNomenclatureDomainService().getTypeOffreFromId(
this.critereRechercheOffre.getContratOffre().getIdParent()));
}
}
}
}else{
this.critereRechercheOffre.setTypeOffre(null);
this.critereRechercheOffre.setContratOffre(null);
}
if(this.critereRechercheOffre.isEstPrioERQTH()){
this.critereRechercheOffre.setEstAccessERQTH(false);
}
if(getSessionController().isPageAuthorized() || getSessionController().isAdminPageAuthorized()){
this.critereRechercheOffre.setInclureOffresEntreprise(true);
}
this.critereRechercheOffre.setEstFrance(false);
if(this.critereRechercheOffre.getLieuPays()!=null
&& this.critereRechercheOffre.getLieuPays().getId()!=0
&& getBeanUtils()!=null
&& getBeanUtils().isFranceRecherche(this.critereRechercheOffre.getLieuPays())){
this.critereRechercheOffre.setLieuPays(getBeanUtils().getFrance());
if (getBeanUtils().isFranceRecherche(this.critereRechercheOffre.getLieuPays())) {
this.critereRechercheOffre.setEstFrance(true);
}
}
this.resultatsRechercheOffre = getOffreDomainService().getOffresFromCriteres(this.critereRechercheOffre);
if(!checkListeResultats()){
ret=null;
}
return ret;
}
/**
* Passage du moteur simple à avancé et vice-versa
*/
public void rechercheSimpleAvancee(){
if(this.rechercheAvancee) {
this.rechercheAvancee = false;
} else {
this.rechercheAvancee=true;
}
resetRechercheOffre();
}
/**
* Reset des criteres de recherche d'offres
*/
public void resetRechercheOffre(){
this.critereRechercheOffre=initCritereRechercheOffre();
this.rechTypeOuContrat=null;
}
/**
* Re-chargement du paginator
*/
public void reloadRechercheOffrePaginator(){
this.rechercheOffrePaginator.reset();
this.rechercheOffrePaginator.setListe(this.resultatsRechercheOffre);
this.rechercheOffrePaginator.forceReload();
}
/**
* Contrôle la liste des résultats
* @return boolean : vrai si resultats
*/
private boolean checkListeResultats(){
boolean ret=true;
if(this.resultatsRechercheOffre==null || this.resultatsRechercheOffre.isEmpty()){
this.resultatsRechercheOffre=null;
ret=false;
addInfoMessage("formRechOffre", "RECHERCHEOFFRE.AUCUNRESULTAT");
}else if(this.resultatsRechercheOffre!=null && !this.resultatsRechercheOffre.isEmpty()){
reloadRechercheOffrePaginator();
}
return ret;
}
/**
* @return String
*/
public String goToRecapitulatifOffrePostCreation(){
if ("creationOffre".equalsIgnoreCase(this.creationOffre)){
return this.goToRecapitulatifOffre();
} else if ("creationCentreEtabOffre".equalsIgnoreCase(this.creationOffre)){
return this.goToRecapitulatifOffreFromOffreLightAvecCentre();
} else {
return null;
}
}
/**
* @return String
*/
public String goToRecapitulatifOffre(){
String ret=null;
if(this.currentOffre!=null){
ret="recapitulatifOffre";
this.currentRecapOffre = "offre";
this.currentOffre.setOffresDiffusion(getOffreDomainService().getOffreDiffusionFromIdOffre(this.currentOffre.getIdOffre()));
}
return ret;
}
/**
* @return String
*/
public String goToRecapitulatifOffreFromOffreLight(){
String ret=null;
if(this.currentOffre!=null){
this.currentOffre=getOffreDomainService().getOffreFromId(this.currentOffre.getIdOffre());
this.currentOffre.setStructure(getStructureDomainService().getStructureFromId(this.currentOffre.getIdStructure()));
this.currentOffre.setOffresDiffusion(getOffreDomainService().getOffreDiffusionFromIdOffre(this.currentOffre.getIdOffre()));
ret="recapitulatifOffreEtab";
this.currentRecapOffre = "offreEtab";
}
return ret;
}
/**
* @return String
*/
public String goToRecapitulatifOffreFromOffreLightAvecCentre(){
String ret=null;
if(this.currentOffre!=null){
this.currentOffre=getOffreDomainService().getOffreFromId(this.currentOffre.getIdOffre());
this.currentOffre.setStructure(getStructureDomainService().getStructureFromId(this.currentOffre.getIdStructure()));
getSessionController().setCurrentManageStructure(this.currentOffre.getStructure());
this.etablissementController.loadContactsServices();
this.currentOffre.setOffresDiffusion(getOffreDomainService().getOffreDiffusionFromIdOffre(this.currentOffre.getIdOffre()));
this.majListesCentresDiffusion();
// Assignation du centre de l'offre
if(!isListeCurrentIdsCentresGestionContainsIdCGCurrentOffre()){
CentreGestionDTO c = getCentreGestionDomainService().getCentreGestion(this.currentOffre.getIdCentreGestion());
if(c!=null)this.currentOffre.setCentreGestion(c);
else return ret;
}else{
if(getSessionController().getCurrentIdsCentresGestion()!=null &&
!getSessionController().getCurrentIdsCentresGestion().isEmpty()){
for(CentreGestionDTO c : getSessionController().getCurrentCentresGestion()){
if(c.getIdCentreGestion()==this.currentOffre.getIdCentreGestion()){
this.currentOffre.setCentreGestion(c);
break;
}
}
}
}
ret="recapitulatifOffreEtabCentre";
this.currentRecapOffre = "offreEtabCentre";
}
return ret;
}
/**
* @return String
*/
public String goToRecapitulatifOffrePublic(){
String ret=null;
if(this.currentOffre!=null){
this.currentOffre=getOffreDomainService().getOffreFromId(this.currentOffre.getIdOffre());
this.currentOffre.setStructure(getStructureDomainService().getStructureFromId(this.currentOffre.getIdStructure()));
this.etablissementController.loadContactsServices();
this.currentOffre.setOffresDiffusion(getOffreDomainService().getOffreDiffusionFromIdOffre(this.currentOffre.getIdOffre()));
ret="recapitulatifOffreEtab";
this.currentRecapOffre = "offreEtab";
}
return ret;
}
/**
* @param idOffre
* @return String
*/
public String goToOffreEtudiant(Integer idOffre){
String ret="recapitulatifOffreEtab";
this.currentRecapOffre = "offreEtab";
this.currentOffre=null;
OffreDTO oTmp=getOffreDomainService().getOffreFromId(idOffre);
if(oTmp!=null){
CentreGestionDTO cgEntr = getCentreGestionDomainService().getCentreEntreprise();
if(getSessionController().getCurrentIdsCentresGestion()==null){
getSessionController().setCurrentCentresGestion(new ArrayList<CentreGestionDTO>());
getSessionController().getCurrentCentresGestion().add(cgEntr);
}else if(!getSessionController().getCurrentIdsCentresGestion().contains(cgEntr.getIdCentreGestion())){
getSessionController().getCurrentCentresGestion().add(cgEntr);
}
if(getSessionController().getCurrentIdsCentresGestion()!=null
&& getSessionController().getCurrentIdsCentresGestion().contains(oTmp.getIdCentreGestion())){
this.currentOffre=oTmp;
goToRecapitulatifOffreFromOffreLight();
}
}
return ret;
}
/**
* @param idOffreC
* @return String
*/
public String goToOffreEtudiantAvecCentre(Integer idOffreC){
String ret="recapitulatifOffreEtabCentre";
this.currentRecapOffre = "offreEtabCentre";
this.currentOffre=null;
OffreDTO oTmp=getOffreDomainService().getOffreFromId(idOffreC);
if(oTmp!=null){
CentreGestionDTO cgEntr = getCentreGestionDomainService().getCentreEntreprise();
if(getSessionController().getCurrentIdsCentresGestion()==null){
getSessionController().setCurrentCentresGestion(new ArrayList<CentreGestionDTO>());
getSessionController().getCurrentCentresGestion().add(cgEntr);
}else if(!getSessionController().getCurrentIdsCentresGestion().contains(cgEntr.getIdCentreGestion())){
getSessionController().getCurrentCentresGestion().add(cgEntr);
}
if(getSessionController().getCurrentIdsCentresGestion()!=null
&& getSessionController().getCurrentIdsCentresGestion().contains(oTmp.getIdCentreGestion())){
this.currentOffre=getOffreDomainService().getOffreFromId(idOffreC);
goToRecapitulatifOffreFromOffreLightAvecCentre();
}
}
return ret;
}
/**
* @return String
*/
public String goToDetailsOffre(){
return "detailsOffre";
}
/* ***************************************************************
*
****************************************************************/
/**
* Upload du Fichier
*/
public void uploadFileOffre(FileUploadEvent event){
if(logger.isDebugEnabled()){
logger.debug("public String uploadLogoCentre() ");
}
FileUploadBean fileUlBean = getSessionController().getOffreFileUploadBean();
// On met le prefix a -1 sinon '0_' est ajouté au nom
fileUlBean.setPrefix(-1);
// Methode s'occupant de l'upload du fichier
fileUlBean.fileUploadListener(event);
// Recuperation du nom final du fichier
String nomFichier = fileUlBean.getNameUploadedFile();
String nomReel = fileUlBean.getRealNameFile();
//Si nom de fichier non vide (cas des fichiers volumineux)
if(StringUtils.hasText(nomFichier)){
FichierDTO f = new FichierDTO();
f.setNomFichier(nomFichier);
if(StringUtils.hasText(nomReel)){
f.setNomReel(nomReel);
} else {
f.setNomReel("");
}
try {
int idFichier = getOffreDomainService().addFichier(f);
// Maintenant que l'upload s'est bien passé et que l'on a pu inserer le fichier en base,
// on recupere le last insert id pour l'assigner a l'offre qui n'est pas encore creee donc
// pas besoin d'update
f.setIdFichier(idFichier);
this.formOffre.setFichier(f);
this.formOffre.setIdFichier(idFichier);
// Pour que le fichier puisse etre recup par getFileServlet, il faut le prefixer de l'idFichier,
// On le recupere donc pour le renommer
String directory = getSessionController().getUploadFilesOffresPath()+ File.separator;
File fichier = new File(directory + f.getNomFichier());
boolean b = fichier.renameTo(new File(directory+ idFichier +"_"+f.getNomFichier()));
if (b == false){
addErrorMessage("panelUpload","Erreur lors de la tentative de renommage du fichier.");
}
} catch (DataAddException e) {
logger.error(e);
addErrorMessage("panelUpload",e.getMessage());
} catch (DataUpdateException e) {
logger.error(e);
addErrorMessage("panelUpload",e.getMessage());
} catch (WebServiceDataBaseException e) {
logger.error(e);
addErrorMessage("panelUpload",e.getMessage());
}
}
}
/**
* Action appellée après l'upload d'un fichier
*/
public void insertUploadedFile(){
String nomFichier = getSessionController().getOffreFileUploadBean().getNameUploadedFile();
String nomReel = getSessionController().getOffreFileUploadBean().getRealNameFile();
//Si nom de fichier non vide (cas des fichiers volumineux)
if(StringUtils.hasText(nomFichier)){
this.formOffre.getFichier().setNomFichier(nomFichier);
if(StringUtils.hasText(nomReel)){
this.formOffre.getFichier().setNomReel(nomReel);
}
try {
getOffreDomainService().updateFichier(this.formOffre.getFichier());
} catch (DataAddException|WebServiceDataBaseException e) {
logger.error(e);
}
this.formOffre.setIdFichier(this.formOffre.getFichier().getIdFichier());
}
}
/**
* Suppression du fichier actuellement uploadé
*/
public void deleteUploadedFile(){
if(this.formOffre.getIdFichier() > 0 ){
try{
if(this.formOffre.getFichier()!=null
&& StringUtils.hasText(this.formOffre.getFichier().getNomFichier())){
getSessionController().getOffreFileUploadBean().deleteFileFromDirectory(
this.formOffre.getIdFichier(), this.formOffre.getFichier().getNomFichier());
}
getOffreDomainService().deleteFichier(this.formOffre.getIdFichier());
}catch (DataDeleteException|WebServiceDataBaseException e) {
logger.error(e);
}
}
this.formOffre.setFichier(null);
this.formOffre.setIdFichier(0);
this.formOffre.setAvecFichier(false);
}
/**
* Mise à jour de la FapN3 en fonction de la QualificationSimplifiee selectionnée
* @param event
*/
public void valueFapQualificationSimplifieeChanged(ValueChangeEvent event){
if(event.getNewValue() instanceof FapQualificationSimplifieeDTO){
FapQualificationSimplifieeDTO f = (FapQualificationSimplifieeDTO)event.getNewValue();
this.fapN3Listening=getFapN3FromNumQualif(f.getId());
}else{
this.fapN3Listening=null;
}
}
/**
* @param num
* @return List<SelectItem>
*/
public List<SelectItem> getFapN3FromNumQualif(int num){
List<SelectItem> ls = null;
List<FapN3DTO> l = getNomenclatureDomainService().getFapN3FromNumQualifSimplifiee(num);
if(l!=null && !l.isEmpty()){
ls = new ArrayList<SelectItem>();
for(FapN3DTO o : l){
ls.add(new SelectItem(o,o.getLibelle()));
}
}
return ls;
}
/** Formulaire offre
* @param event
*/
public void formOffreValueCodePostalChanged(ValueChangeEvent event){
String s = (String)event.getNewValue();
if(getSessionController().isRecupererCommunesDepuisApogee()){
List<SelectItem> lTmp = majCommunes(s);
if(lTmp!=null && !lTmp.isEmpty()){
this.formOffreCommunesListening=lTmp;
}else{
this.formOffreCommunesListening=new ArrayList<SelectItem>();
addErrorMessage("formCreationOffre:dynaCodePostal", "STRUCTURE.CODE_POSTAL.VALIDATION");
}
}
}
/**
* @param codePostal
* @return List<SelectItem>
*/
public List<SelectItem> majCommunes(String codePostal){
List<SelectItem> l = null;
if(codePostal.length()==5){
List<CommuneDTO> ls = getGeographieRepositoryDomain().getCommuneFromDepartement(codePostal);
if(ls!=null){
l = new ArrayList<SelectItem>();
for(CommuneDTO c : ls){
l.add(new SelectItem(c.getCodeCommune(),c.getLibCommune()));
}
}
}
return l;
}
/**
* @param event
*/
public void valueCentreEtablissementChanged(ValueChangeEvent event){
if(event.getNewValue() instanceof Integer){
if(this.listesCentresGestionEtablissement!=null && this.listesCGEtab!=null
&& !this.listesCentresGestionEtablissement.isEmpty()
&& !this.listesCGEtab.isEmpty()){
int idCTmp = (Integer) event.getNewValue();
if(idCTmp>0){
CentreGestionDTO cTmp = new CentreGestionDTO();
cTmp.setIdCentreGestion(idCTmp);
CentreGestionDTO c = this.listesCGEtab.get(
this.listesCGEtab.indexOf(cTmp));
List<CentreGestionDTO> l = getCentreGestionDomainService().getCentreGestionList(c.getCodeUniversite());
if(l!=null && !l.isEmpty()){
this.dualListCiblageCentres.setSource(new ArrayList<CentreGestionDTO>());
for(CentreGestionDTO cg : l){
if(!cg.equals(cTmp)){
this.dualListCiblageCentres.getSource().add(cg);
}
}
}else{
this.dualListCiblageCentres.setSource(new ArrayList<CentreGestionDTO>());
}
}else{
this.dualListCiblageCentres.setSource(new ArrayList<CentreGestionDTO>());
}
}
}else{
this.dualListCiblageCentres.setSource(new ArrayList<CentreGestionDTO>());
}
}
/**
* Utilisé en etape 3 d'une offre
* @return boolean
*/
public boolean isFormOffreContainModeCourrier(){
return isOffreContainMode(getBeanUtils().getModeCourrier(), this.formOffre);
}
/**
* Utilisé en etape 3 d'une offre
* @return boolean
*/
public boolean isFormOffreContainModeTelephone(){
return isOffreContainMode(getBeanUtils().getModeTelephone(), this.formOffre);
}
/**
* Utilisé en etape 3 d'une offre
* @return boolean
*/
public boolean isFormOffreContainModeMail(){
return isOffreContainMode(getBeanUtils().getModeMail(), this.formOffre);
}
/**
* Utilisé dans le recap d'une offre
* @return boolean
*/
public boolean isCurrentOffreContainModeCourrier(){
return isOffreContainMode(getBeanUtils().getModeCourrier(), this.currentOffre);
}
/**
* Utilisé dans le recap d'une offre
* @return boolean
*/
public boolean isCurrentOffreContainModeTelephone(){
return isOffreContainMode(getBeanUtils().getModeTelephone(), this.currentOffre);
}
/**
* Utilisé dans le recap d'une offre
* @return boolean
*/
public boolean isCurrentOffreContainModeMail(){
return isOffreContainMode(getBeanUtils().getModeMail(), this.currentOffre);
}
/**
* @param mc
* @param o
* @return boolean
*/
public boolean isOffreContainMode(ModeCandidatureDTO mc, OffreDTO o){
boolean ret=false;
if(o!=null){
if(o.getModesCandidature()!=null &&
!o.getModesCandidature().isEmpty()){
for(ModeCandidatureDTO m : o.getModesCandidature()){
if(m.equals(mc)){
ret=true;
break;
}
}
}
}
return ret;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getClass().getSimpleName() + "#" + hashCode();
}
/**
* @see org.esupportail.pstage.web.controllers.AbstractDomainAwareBean#reset()
*/
@Override
public void reset() {
super.reset();
}
/* ****************************************************************************
* DEPOT ANONYME
*****************************************************************************/
private String codeAccesDepotAnonyme;
private String urlAccesDepotAnonyme;
public String getCodeAccesDepotAnonyme() {
return codeAccesDepotAnonyme;
}
public void setCodeAccesDepotAnonyme(String codeAccesDepotAnonyme) {
this.codeAccesDepotAnonyme = codeAccesDepotAnonyme;
}
public String getUrlAccesDepotAnonyme() {
return urlAccesDepotAnonyme;
}
public void setUrlAccesDepotAnonyme(String urlAccesDepotAnonyme) {
this.urlAccesDepotAnonyme = urlAccesDepotAnonyme;
}
/**
* code d'acces au depot anonyme pour une entreprise
*/
public void genererUrlDepotAnonyme() {
// chiffrage de l'id de la convention via blowfish
String idEncode = getBlowfishUtils().encode(
"" + getCentreGestionDomainService().getCentreEntreprise().getIdCentreGestion());
this.urlAccesDepotAnonyme = getSessionController().getBaseUrl()
+ "/stylesheets/depotAnonyme/welcome.xhtml" + "?id="
+ idEncode;
}
/**
* Envoi vers l'enchainement de creation d'offre anonyme
* @return String
*/
public String goToDepotAnonyme(){
String ret=null;
this.centreGestionDepotAnonyme = getCentreGestionDomainService().getCentreEntreprise();
if (this.centreGestionDepotAnonyme != null) {
int idDecode = Utils.convertStringToInt(getBlowfishUtils().decode(this.codeAccesDepotAnonyme));
if(idDecode == this.centreGestionDepotAnonyme.getIdCentreGestion()){
this.formOffre=new OffreDTO();
this.formOffre.setIdCentreGestion(idDecode);
ret = "creationOffreAnon";
this.creationOffre = "creationOffreAnon";
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape02Etab");
} else {
addErrorMessage("formAccueilDepotAnon","DEPOTANONYME.UNAUTHORIZED");
}
} else {
addErrorMessage("formAccueilDepotAnon","DEPOTANONYME.CENTRE_ENTR_VIDE");
}
return ret;
}
/**
* @return String
*/
public String editPdfOffre() {
String ret = null;
try {
/**
** Methodes de creation des documents PDF selon l'edition demandee
**/
String nomDocxsl;
String fileNameXml;
String fileNameXmlfin = ".xml";
OffreDTO offreEdit = this.currentOffre;
String description;
String competences;
String observations;
String commentaires;
if (offreEdit != null) {
if (offreEdit.getDescription() !=null) {
if (StringUtils.hasText(offreEdit.getDescription())) {
description = Utils.replaceHTML(offreEdit.getDescription());
offreEdit.setDescription(description);
}
}
if (offreEdit.getCompetences() != null) {
if (StringUtils.hasText(offreEdit.getCompetences())) {
competences = Utils.replaceHTML(offreEdit.getCompetences());
offreEdit.setCompetences(competences);
}
}
if (offreEdit.getCommentaireTempsTravail() != null) {
if (StringUtils.hasText(offreEdit.getCommentaireTempsTravail())) {
commentaires = Utils.replaceHTML(offreEdit.getCommentaireTempsTravail());
offreEdit.setCommentaireTempsTravail(commentaires);
}
}
if (offreEdit.getObservations() != null) {
if (StringUtils.hasText(offreEdit.getObservations())) {
observations = Utils.replaceHTML(offreEdit.getObservations());
offreEdit.setObservations(observations);
}
}
String idOffre = Integer.toString(offreEdit.getIdOffre());
nomDocxsl = "offre" + ".xsl";
fileNameXml = "offre_" + idOffre;
// appel castor pour fichier xml a partir de objet java convention
castorService.objectToFileXml(offreEdit, fileNameXml + fileNameXmlfin);
//fusion du xsl et xml en pdf
String fileNamePdf = fileNameXml + ".pdf";
PDFUtils.exportPDF(fileNameXml + fileNameXmlfin, FacesContext.getCurrentInstance(),
castorService.getXslXmlPath(),
fileNamePdf, nomDocxsl);
addInfoMessage(null, "CONVENTION.IMPRESSION.RECAP.CONFIRMATION");
}
} catch (ExportException e) {
logger.error("editPdfRecap ", e);
addErrorMessage(null, "CONVENTION.EDIT.RECAP.ERREUR", e.getMessage());
}
return ret;
}
/**
* @return String
*/
public String goToOffreADiffuser(){
this.critereRechercheOffre=initCritereRechercheOffre();
this.critereRechercheOffre.setEstDiffusee(false);
String s = this.rechercherOffre();
if(s != null) return s;
FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(true);
return "rechercheOffreStage";
}
/**
* event lors du choix d'une Offre côté stage menant à la page recapitulatifOffreCentre
*/
public void onOffreSelect(SelectEvent event) {
String retour = this.goToRecapitulatifOffreFromOffreLightAvecCentre();
try {
if (retour != null) {
FacesContext.getCurrentInstance().getExternalContext().redirect("recapitulatifOffreCentre.xhtml");
}
} catch (IOException ioe){
logger.error("Erreur lors de la tentative de redirection de page.", ioe);
addErrorMessage(null, "Erreur lors de la tentative de redirection de page.");
}
}
/**
* event lors du choix d'une Offre côté stage menant à la page recapitulatifOffreEtabCentre
*/
public void onOffreEtabSelect(SelectEvent event) {
String retour = this.goToRecapitulatifOffreFromOffreLightAvecCentre();
try {
if (retour != null) {
FacesContext.getCurrentInstance().getExternalContext().redirect("recapitulatifOffreEtabCentre.xhtml");
}
} catch (IOException ioe){
logger.error("Erreur lors de la tentative de redirection de page.", ioe);
addErrorMessage(null, "Erreur lors de la tentative de redirection de page.");
}
}
/**
* event lors du choix d'une Offre côté depot menant à la page recapitulatifOffreEtab
*/
public void onOffreEtabDepotSelect(SelectEvent event) {
String retour = this.goToRecapitulatifOffreFromOffreLight();
try {
if (retour != null) {
FacesContext.getCurrentInstance().getExternalContext().redirect("recapitulatifOffreEtab.xhtml");
}
} catch (IOException ioe){
logger.error("Erreur lors de la tentative de redirection de page.", ioe);
addErrorMessage(null, "Erreur lors de la tentative de redirection de page.");
}
}
/**
* event lors du choix d'une Offre côté depot menant à la page recapitulatifOffreEtabCentre
*/
public void onOffreDepotSelect(SelectEvent event) {
this.retour = "recapitulatifOffre";
String retour = this.goToRecapitulatifOffre();
try {
if (retour != null) {
FacesContext.getCurrentInstance().getExternalContext().redirect("recapitulatifOffre.xhtml");
}
} catch (IOException ioe){
logger.error("Erreur lors de la tentative de redirection de page.", ioe);
addErrorMessage(null, "Erreur lors de la tentative de redirection de page.");
}
}
/**
* event lors du choix d'un établissement dans l'enchainement de création d'offre
*/
public void onCreaOffreEtabSelect(SelectEvent event) {
this.goToCreationOffreDetailsEtab();
try {
if (this.creationOffre.equalsIgnoreCase("creationOffreAnon")){
FacesContext.getCurrentInstance().getExternalContext().redirect(getSessionController().getBaseUrl()+"/stylesheets/depotAnonyme/creationOffreAnon.xhtml");
} else {
FacesContext.getCurrentInstance().getExternalContext().redirect("creationCentreEtabOffre.xhtml");
}
} catch (IOException ioe){
logger.error("Erreur lors de la tentative de redirection de page.", ioe);
addErrorMessage(null, "Erreur lors de la tentative de redirection de page.");
}
}
/* ***************************************************************
* Getters / Setters
****************************************************************/
/**
* @return the formOffre
*/
public OffreDTO getFormOffre() {
return formOffre;
}
/**
* @param formOffre the formOffre to set
*/
public void setFormOffre(OffreDTO formOffre) {
this.formOffre = formOffre;
}
/**
* @return the contratsListening
*/
public List<SelectItem> getContratsListening() {
return contratsListening;
}
/**
* @param contratsListening the contratsListening to set
*/
public void setContratsListening(List<SelectItem> contratsListening) {
this.contratsListening = contratsListening;
}
/**
* @return the fapN3Listening
*/
public List<SelectItem> getFapN3Listening() {
return fapN3Listening;
}
/**
* @param fapN3Listening the fapN3Listening to set
*/
public void setFapN3Listening(List<SelectItem> fapN3Listening) {
this.fapN3Listening = fapN3Listening;
}
/**
* @return the formOffreCommunesListening
*/
public List<SelectItem> getFormOffreCommunesListening() {
return formOffreCommunesListening;
}
/**
* @param formOffreCommunesListening the formOffreCommunesListening to set
*/
public void setFormOffreCommunesListening(
List<SelectItem> formOffreCommunesListening) {
this.formOffreCommunesListening = formOffreCommunesListening;
}
/**
* @return the avecFichierOuLien
*/
public boolean isAvecFichierOuLien() {
return avecFichierOuLien;
}
/**
* @param avecFichierOuLien the avecFichierOuLien to set
*/
public void setAvecFichierOuLien(boolean avecFichierOuLien) {
this.avecFichierOuLien = avecFichierOuLien;
}
/**
* @return the fichierOuLien
*/
public int getFichierOuLien() {
return fichierOuLien;
}
/**
* @param fichierOuLien the fichierOuLien to set
*/
public void setFichierOuLien(int fichierOuLien) {
this.fichierOuLien = fichierOuLien;
}
/**
* @return the listeOffres
*/
public List<OffreDTO> getListeOffres() {
return listeOffres;
}
/**
* @param listeOffres the listeOffres to set
*/
public void setListeOffres(List<OffreDTO> listeOffres) {
this.listeOffres = listeOffres;
}
/**
* @return the retour
*/
public String getRetour() {
if(!StringUtils.hasText(this.retour)) this.retour="defaut";
return retour;
}
/**
* @param retour the retour to set
*/
public void setRetour(String retour) {
this.retour = retour;
}
/**
* @return the recap
*/
public String getRecap() {
String ret = recap;
recap=null;
return ret;
}
/**
* @param recap the recap to set
*/
public void setRecap(String recap) {
this.recap = recap;
}
/**
* @return the currentOffre
*/
public OffreDTO getCurrentOffre() {
return currentOffre;
}
/**
* @param currentOffre the currentOffre to set
*/
public void setCurrentOffre(OffreDTO currentOffre) {
this.currentOffre = currentOffre;
}
/**
* @return the etablissementController
*/
public EtablissementController getEtablissementController() {
return etablissementController;
}
/**
* @param etablissementController the etablissementController to set
*/
public void setEtablissementController(
EtablissementController etablissementController) {
this.etablissementController = etablissementController;
}
/**
* @return the listeItemsCurrentCentresGestion
*/
public List<SelectItem> getListeItemsCurrentCentresGestion() {
listeItemsCurrentCentresGestion=null;
if(getSessionController().getCurrentCentresGestion()!=null
&& !getSessionController().getCurrentCentresGestion().isEmpty()){
listeItemsCurrentCentresGestion=new ArrayList<SelectItem>();
for(CentreGestionDTO cg : getSessionController().getCurrentCentresGestion()){
listeItemsCurrentCentresGestion.add(new SelectItem(cg.getIdCentreGestion(), cg.getNomCentre()));
}
}
return listeItemsCurrentCentresGestion;
}
/**
* @return the critereRechercheOffre
*/
public CritereRechercheOffreDTO getCritereRechercheOffre() {
return critereRechercheOffre;
}
/**
* @param critereRechercheOffre the critereRechercheOffre to set
*/
public void setCritereRechercheOffre(
CritereRechercheOffreDTO critereRechercheOffre) {
this.critereRechercheOffre = critereRechercheOffre;
}
/**
* @return the rechTypesContratsOffre
*/
public List<SelectItem> getRechTypesContratsOffre() {
rechTypesContratsOffre = new ArrayList<SelectItem>();
List<TypeOffreDTO> lt = getNomenclatureDomainService().getTypesOffre();
for(TypeOffreDTO t : lt){
rechTypesContratsOffre.add(new SelectItem("t"+t.getId(),t.getLibelle()));
List<ContratOffreDTO> lc = getNomenclatureDomainService().getContratsOffreFromIdTypeOffre(t.getId());
if(lc!=null && !lc.isEmpty()){
for(ContratOffreDTO c: lc){
rechTypesContratsOffre.add(new SelectItem("c"+c.getId(), "--- "+c.getLibelle()));
}
}
}
return rechTypesContratsOffre;
}
/**
* @return the rechTypeOuContrat
*/
public String getRechTypeOuContrat() {
return rechTypeOuContrat;
}
/**
* @param rechTypeOuContrat the rechTypeOuContrat to set
*/
public void setRechTypeOuContrat(String rechTypeOuContrat) {
this.rechTypeOuContrat = rechTypeOuContrat;
}
/**
* @return the resultatsRechercheOffre
*/
public List<OffreDTO> getResultatsRechercheOffre() {
return resultatsRechercheOffre;
}
/**
* @param resultatsRechercheOffre the resultatsRechercheOffre to set
*/
public void setResultatsRechercheOffre(List<OffreDTO> resultatsRechercheOffre) {
this.resultatsRechercheOffre = resultatsRechercheOffre;
}
/**
* @return the rechercheAvancee
*/
public boolean isRechercheAvancee() {
return rechercheAvancee;
}
/**
* @param rechercheAvancee the rechercheAvancee to set
*/
public void setRechercheAvancee(boolean rechercheAvancee) {
this.rechercheAvancee = rechercheAvancee;
}
/**
* @return the rechercheOffrePaginator
*/
public RechercheOffrePaginator getRechercheOffrePaginator() {
return rechercheOffrePaginator;
}
/**
* @param rechercheOffrePaginator the rechercheOffrePaginator to set
*/
public void setRechercheOffrePaginator(
RechercheOffrePaginator rechercheOffrePaginator) {
this.rechercheOffrePaginator = rechercheOffrePaginator;
}
/**
* @return the listesCentresGestionEtablissement
*/
public List<SelectItem> getListesCentresGestionEtablissement() {
this.listesCentresGestionEtablissement = new ArrayList<SelectItem>();
CentreGestionDTO cgEntr = getCentreGestionDomainService().getCentreEntreprise();
if(cgEntr!=null && getSessionController().getCurrentCentresGestion()!=null
&& !getSessionController().getCurrentCentresGestion().isEmpty()
&& getSessionController().getCurrentCentresGestion().contains(cgEntr)){
this.listesCentresGestionEtablissement.add(new SelectItem(0,getFacesInfoMessage("OFFRE.GESTION.DIFFUSIONCENTRE.DIFFUSERTLM").getDetail()));
List<CentreGestionDTO> l = getCentreGestionDomainService().getCentresEtablissement(getSessionController().getCodeUniversite());
this.listesCGEtab=l;
if(l!=null && !l.isEmpty()){
for(CentreGestionDTO cg : l){
this.listesCentresGestionEtablissement.add(new SelectItem(cg.getIdCentreGestion(), cg.getNomCentre()));
}
}
} else {
this.listesCentresGestionEtablissement=new ArrayList<SelectItem>();
CentreGestionDTO cgEtab = getCentreGestionDomainService().getCentreEtablissement(
getSessionController().getCodeUniversite());
this.listesCentresGestionEtablissement.add(new SelectItem(cgEtab.getIdCentreGestion(),""+cgEtab.getNomCentre()));
}
return this.listesCentresGestionEtablissement;
}
/**
* @param listesCentresGestionEtablissement the listesCentresGestionEtablissement to set
*/
public void setListesCentresGestionEtablissement(
List<SelectItem> listesCentresGestionEtablissement) {
this.listesCentresGestionEtablissement = listesCentresGestionEtablissement;
}
/**
* @return the idCentreEtablissementSelect
*/
public int getIdCentreEtablissementSelect() {
return idCentreEtablissementSelect;
}
/**
* @param idCentreEtablissementSelect the idCentreEtablissementSelect to set
*/
public void setIdCentreEtablissementSelect(int idCentreEtablissementSelect) {
this.idCentreEtablissementSelect = idCentreEtablissementSelect;
}
/**
* @return the centreGestionDepotAnonyme
*/
public CentreGestionDTO getCentreGestionDepotAnonyme() {
return centreGestionDepotAnonyme;
}
/**
* @param centreGestionDepotAnonyme the centreGestionDepotAnonyme to set
*/
public void setCentreGestionDepotAnonyme(
CentreGestionDTO centreGestionDepotAnonyme) {
this.centreGestionDepotAnonyme = centreGestionDepotAnonyme;
}
/**
* @return the castorService
*/
public CastorService getCastorService() {
return castorService;
}
/**
* @param castorService the castorService to set
*/
public void setCastorService(CastorService castorService) {
this.castorService = castorService;
}
/**
* @return the dureesDiffusion
*/
public List<SelectItem> getDureesDiffusion() {
this.dureesDiffusion = new ArrayList<SelectItem>();
boolean isAdmin;
if (this.currentOffre == null) this.currentOffre = this.formOffre;
Map<Integer,DroitAdministrationDTO> droitAcces = getSessionController().getDroitsAccesMap();
if (droitAcces.get(this.currentOffre.getIdCentreGestion()) == getBeanUtils().getDroitAdmin()
|| getSessionController().isAdminPageAuthorized()
|| getSessionController().isSuperAdminPageAuthorized()){
isAdmin = true;
} else {
isAdmin = false;
}
for(DureeDiffusionDTO dd : getOffreDomainService().getDureeDiffusion()){
if (dd.isAdminSeulement()) {
if (isAdmin) this.dureesDiffusion.add(new SelectItem(dd.getId(), dd.getLibelle()));
} else{
this.dureesDiffusion.add(new SelectItem(dd.getId(), dd.getLibelle()));
}
}
return dureesDiffusion;
}
/**
* @param dureesDiffusion the dureesDiffusion to set
*/
public void setDureesDiffusion(List<SelectItem> dureesDiffusion) {
this.dureesDiffusion = dureesDiffusion;
}
/**
* @return the dureeDiffusion
*/
public int getDureeDiffusion() {
return dureeDiffusion;
}
/**
* @param dureeDiffusion the dureeDiffusion to set
*/
public void setDureeDiffusion(int dureeDiffusion) {
this.dureeDiffusion = dureeDiffusion;
}
/**
* @return the diffusionDirecte
*/
public boolean isDiffusionDirecte() {
return diffusionDirecte;
}
/**
* @param diffusionDirecte the diffusionDirecte to set
*/
public void setDiffusionDirecte(boolean diffusionDirecte) {
this.diffusionDirecte = diffusionDirecte;
}
/**
* @param offreADiffuser the offreADiffuser to set
*/
public void setOffreADiffuser(int offreADiffuser) {
this.offreADiffuser= offreADiffuser;
}
/**
* @return the offreADiffuser
*/
public int getOffreADiffuser() {
this.offreADiffuser=getOffreDomainService().countOffreADiffuser(getSessionController().getCurrentIdsCentresGestion());
return this.offreADiffuser;
}
/**
* @return the creationOffre
*/
public String getCreationOffre() {
return creationOffre;
}
/**
* @param creationOffre the creationOffre to set
*/
public void setCreationOffre(String creationOffre) {
this.creationOffre = creationOffre;
}
public String getCurrentRecapOffre() {
return currentRecapOffre;
}
public void setCurrentRecapOffre(String currentRecapOffre) {
this.currentRecapOffre = currentRecapOffre;
}
public boolean isModificationContactOffre() {
return modificationContactOffre;
}
public void setModificationContactOffre(boolean modificationContactOffre) {
this.modificationContactOffre = modificationContactOffre;
}
}
| esup-pstage-web-jsf-servlet/src/main/java/org/esupportail/pstage/web/controllers/OffreController.java | /**
* ESUP-PStage - Copyright (c) 2006 ESUP-Portail consortium
* http://sourcesup.cru.fr/projects/esup-pstage
*/
package org.esupportail.pstage.web.controllers;
import gouv.education.apogee.commun.transverse.dto.geographie.CommuneDTO;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.apache.log4j.Logger;
import org.esupportail.pstage.exceptions.ExportException;
import org.esupportail.pstage.services.export.CastorService;
import org.esupportail.pstage.utils.Utils;
import org.esupportail.pstage.web.beans.FileUploadBean;
import org.esupportail.pstage.web.beans.ImageUploadBean;
import org.esupportail.pstage.web.comparator.ComparatorSelectItem;
import org.esupportail.pstage.web.paginators.RechercheOffrePaginator;
import org.esupportail.pstage.web.utils.PDFUtils;
import org.esupportail.pstagedata.domain.dto.*;
import org.esupportail.pstagedata.exceptions.DataAddException;
import org.esupportail.pstagedata.exceptions.DataDeleteException;
import org.esupportail.pstagedata.exceptions.DataUpdateException;
import org.esupportail.pstagedata.exceptions.WebServiceDataBaseException;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DualListModel;
import org.springframework.util.StringUtils;
import static org.hsqldb.HsqlDateTime.e;
/**
* OffreController
*/
public class OffreController extends AbstractContextAwareController {
/* ***************************************************************
* Propriétés
****************************************************************/
/**
* Navigation à renvoyer au cours de l'ajout d'offre selon si l'on est coté entreprise ou stage
*/
private String creationOffre;
/**
* The serialization id.
*/
private static final long serialVersionUID = 3430944955282121430L;
/**
* Logger
*/
private final transient Logger logger = Logger.getLogger(this.getClass());
/**
* Page de retour après une modification ou suppression d'offre
*/
private String retour=null;
/**
* Action pour renvoyer sur le récap de l'offre en cours
*/
private String recap=null;
/**
* Offre actuellement gérée
*/
private OffreDTO currentOffre;
/**
* Objet offre utilisé pour l'ajout/modification
*/
private OffreDTO formOffre;
/**
* Liste des contrats mise à jour en fonction du type d'offre
*/
private List<SelectItem> contratsListening;
/**
* Liste FapN3 mise à jour en fonction de la QualificationSimplifiee
*/
private List<SelectItem> fapN3Listening;
/**
* Liste des communes mise à jour en fonction du code postal
*/
private List<SelectItem> formOffreCommunesListening=new ArrayList<SelectItem>();
/**
* Vrai si offre avec un fichier ou un lien
*/
private boolean avecFichierOuLien;
/**
* 1 si fichier, 2 si lien
*/
private int fichierOuLien=0;
/**
* Liste des offres de l'entreprise actuellement gérée
*/
private List<OffreDTO> listeOffres;
/**
* Liste des centres de gestion de la personne actuellement connectée sous de SelectItem
*/
private List<SelectItem> listeItemsCurrentCentresGestion;
//Recherche
/**
* CritereRechercheOffreDTO
*/
private CritereRechercheOffreDTO critereRechercheOffre=initCritereRechercheOffre();
/**
* Liste des types d'offres et contrats pour la recherche
*/
private List<SelectItem> rechTypesContratsOffre;
/**
* Type ou contrat sélectionné pour la recherche
*/
private String rechTypeOuContrat;
/**
* Resultats de la recherche d'offre
*/
private List<OffreDTO> resultatsRechercheOffre;
/**
* Vrai si recherche avancée, faux si recherche simple
*/
private boolean rechercheAvancee=false;
/**
* RechercheOffrePaginator
*/
private RechercheOffrePaginator rechercheOffrePaginator;
//Diffusion à d'autres centres
/**
* Nombre d'éléments dans la liste offresDiffusion de currentOffre
*/
private int currentOffreSizeOffresDiffusion;
/**
* Liste des centres établissement
*/
private List<SelectItem> listesCentresGestionEtablissement=new ArrayList<SelectItem>();
/**
* Liste des centres établissement
*/
private List<CentreGestionDTO> listesCGEtab;
/**
* Id du centre établissement sélectionné
*/
private int idCentreEtablissementSelect;
/**
* Centre de gestion utilisé pour le dépot anonyme
*/
private CentreGestionDTO centreGestionDepotAnonyme;
/**
* EtablissementController
*/
private EtablissementController etablissementController;
/**
* Service to generate Xml.
*/
private CastorService castorService;
/**
* Liste des durees de diffusion disponibles
*/
private List<SelectItem> dureesDiffusion;
/**
* Duree de diffusion choisie
*/
private int dureeDiffusion;
/**
* on diffuse l'offre après ajout/modif si vrai
*/
private boolean diffusionDirecte = true;
/**
* Nombre d'offres à diffuser (pour affichage _menu.jsp partie entreprise)
*/
private int offreADiffuser=0;
public DualListModel<CentreGestionDTO> getDualListCiblageCentres() {
return dualListCiblageCentres;
}
public void setDualListCiblageCentres(DualListModel<CentreGestionDTO> dualListCiblageCentres) {
this.dualListCiblageCentres = dualListCiblageCentres;
}
/**
* DualList des centres de gestion dispos/choisis pour le ciblage
*/
private DualListModel<CentreGestionDTO> dualListCiblageCentres;
/**
* rendered en fonctione du type de contrat de la page __offreEtape2
*/
private boolean affichageDureeOffre = false;
/**
* rendered en fonction du pays de la page __offreEtape2
*/
private boolean paysOffreFrance = false;
/**
* retient dans quel recapitulatif offre nous sommes
* 'offre' = depot
* 'offreEtab' = depot depuis la consultation d'une structure
* 'offreCentre' = stage
* 'offreEtabCentre' = stage depuis la consultation d'une structure
*/
private String currentRecapOffre;
/**
* true si l'on modifie directement les contacts de l'offre (et pas via une étape précédente)
*/
private boolean modificationContactOffre;
/**
* Bean constructor.
*/
public OffreController() {
super();
}
/* ***************************************************************
* Actions
****************************************************************/
/**
* Gestion des offres (entreprise)
*
* @return String
*/
public String goToGestionOffres() {
return "gestionOffres";
}
/**
* Gestion des offres (stage)
*
* @return String
*/
public String goToOffresEtablissement() {
loadOffres();
return "offresEtablissement";
}
/**
* Chargement des offres
*/
public void loadOffres() {
if (getSessionController().getCurrentManageStructure() != null) {
this.listeOffres = getOffreDomainService()
.getOffresFromIdStructureAndIdsCentreGestion(
getSessionController().getCurrentManageStructure()
.getIdStructure(),
getSessionController()
.getCurrentIdsCentresGestion(),
getSessionController().getCurrentAuthEtudiant() != null);
if (this.listeOffres != null && !this.listeOffres.isEmpty()) {
for (OffreDTO o : this.listeOffres) {
o.setStructure(getSessionController()
.getCurrentManageStructure());
}
}
sortListesOffres();
}
}
/**
* Tri
*/
public void sortListesOffres() {
if (this.listeOffres != null && !this.listeOffres.isEmpty()) {
Collections.sort(this.listeOffres, new Comparator<OffreDTO>() {
/**
* @see java.util.Comparator#compare(java.lang.Object,
* java.lang.Object)
*/
@Override
public int compare(OffreDTO o1, OffreDTO o2) {
return o1.getIntitule().compareToIgnoreCase(
o2.getIntitule());
}
});
}
}
/* ***************************************************************
* Ajout d'une offre
* **************************************************************/
/**
* @return String
*/
public String goToEntrepriseCreationOffre() {
this.creationOffre = "creationOffre";
this.formOffre = new OffreDTO();
this.formOffre.setStructure(getSessionController().getCurrentManageStructure());
this.formOffre.setIdStructure(this.formOffre.getStructure().getIdStructure());
this.centreGestionDepotAnonyme = null;
this.formOffre.setIdCentreGestion(getCentreGestionDomainService().getCentreEntreprise().getIdCentreGestion());
// Indemnités à vrai par défaut
this.formOffre.setRemuneration(true);
this.avecFichierOuLien = false;
this.fichierOuLien = 0;
this.contratsListening = null;
this.fapN3Listening = null;
getSessionController().setCreationOffreCurrentPage("_creationOffreEtape1");
return this.creationOffre;
}
/**
* permet de recharger la page courante de l'enchainement d'offre
* @return String
*/
public String goToCreationOffre() {
return this.creationOffre;
}
/**
* Etape 01 : Sélection du centre de gestion
*
* @return String
*/
public String goToCreationOffreSelectionCentre() {
this.creationOffre = "creationCentreEtabOffre";
this.formOffre = new OffreDTO();
this.centreGestionDepotAnonyme = null;
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape01Centre");
return this.creationOffre;
}
/**
* Etape 02 : Sélection établissement
*
* @return String
*/
public String goToCreationOffreSelectionEtab() {
String ret = "creationEtabOffre";
this.formOffre = new OffreDTO();
this.centreGestionDepotAnonyme = null;
return ret;
}
/**
* Etape 03 : Création établissement
* @return a String
*/
public void goToCreationOffreCreaEtab() {
this.etablissementController.goToCreationEtablissement();
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape03CreaEtab");
}
/**
* Bouton d'ajout d'une offre à l'étape 03
*
* @return String
*/
public void ajouterEtablissement() {
String ret = this.etablissementController.ajouterEtablissement();
if (ret != null
&& this.etablissementController.getFormStructure() != null) {
this.etablissementController.getRechercheController()
.setResultatRechercheStructure(
this.etablissementController.getFormStructure());
this.etablissementController.setFormStructure(null);
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape04DetailsEtab");
}
}
/**
* @return String
*/
public String goToCreationOffreModifEtab() {
this.etablissementController.goToModificationEtablissement();
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape05ModifEtab");
return "creationCentreEtabOffre";
}
/**
* @return String
*/
public void modifierEtablissement() {
String ret = this.etablissementController.modifierEtablissement();
FacesContext fc = FacesContext.getCurrentInstance();
Iterator<FacesMessage> ifm = fc.getMessages("formModifEtab");
while (ifm.hasNext()) {
FacesMessage fm = ifm.next();
fc.addMessage(
"formCreationOffre:formModifEtab",
new FacesMessage(FacesMessage.SEVERITY_ERROR, fm
.getSummary(), fm.getDetail()));
ifm.remove();
}
ifm = fc.getMessages("formAffEtab");
while (ifm.hasNext()) {
FacesMessage fm = ifm.next();
fc.addMessage("formCreationOffre:formAffEtab",
new FacesMessage(fm.getSummary(), fm.getDetail()));
ifm.remove();
}
if (StringUtils.hasText(ret)) {
// ret="_creationOffreEtape04DetailsEtab";
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape04DetailsEtab");
}
// return ret;
}
/**
* @return String
*/
public void goToCreationOffreDetailsEtab(){
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape04DetailsEtab");
}
/**
* @return String
*/
public String goToCreationOffreEtape1(){
this.formOffre.setIdStructure(this.formOffre.getStructure().getIdStructure());
getSessionController().setCurrentManageStructure(this.formOffre.getStructure());
getSessionController().setMenuGestionEtab(false);
//Chargement contacts uniquement pour le centre sélectionné
ArrayList<CentreGestionDTO> curCentresTmp = (ArrayList<CentreGestionDTO>) getSessionController().getCurrentCentresGestion();
ArrayList<CentreGestionDTO> centreContacts = new ArrayList<>();
CentreGestionDTO cgTmp = new CentreGestionDTO();
cgTmp.setIdCentreGestion(this.formOffre.getIdCentreGestion());
cgTmp.setNomCentre("");
if(curCentresTmp != null
&& !curCentresTmp.isEmpty()
&& curCentresTmp.indexOf(cgTmp) >= 0){
centreContacts.add(curCentresTmp.get(curCentresTmp.indexOf(cgTmp)));
}
if(centreGestionDepotAnonyme!=null
&& centreGestionDepotAnonyme.getIdCentreGestion() > 0){
centreContacts = new ArrayList<>();
centreContacts.add(centreGestionDepotAnonyme);
}
getSessionController().setCentreGestionRattachement(centreContacts.get(0));
this.etablissementController.loadContactsServices();
//Indemnités à vrai par défaut
this.formOffre.setRemuneration(true);
this.avecFichierOuLien=false;
this.fichierOuLien=0;
this.formOffre.setLienAttache("http://");
this.contratsListening=null;
this.fapN3Listening=null;
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape1");
getSessionController().setCreationOffreCurrentPage("_creationOffreEtape1");
return this.creationOffre;
}
/**
* Envoi vers l'Etape 2 : Saisie de l'offre
* @return String
*/
public String goToCreationOffreEtape2(){
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape2");
getSessionController().setCreationOffreCurrentPage("_creationOffreEtape2");
// Oui par défaut pour la diffusion directe de l'offre :
this.diffusionDirecte = true;
this.formOffre.setLieuPays(this.formOffre.getStructure().getPays());
this.formOffre.setLieuCodePostal(this.formOffre.getStructure().getCodePostal());
this.formOffre.setLieuCommune(this.formOffre.getStructure().getCommune());
this.formOffre.setCodeCommune(this.formOffre.getStructure().getCodeCommune());
if(getSessionController().isRecupererCommunesDepuisApogee() &&
getBeanUtils().isFrance(this.formOffre.getLieuPays())){
List<SelectItem> lTmp = majCommunes(""+this.formOffre.getLieuCodePostal());
if(lTmp!=null && !lTmp.isEmpty()){
this.formOffreCommunesListening=lTmp;
}else{
this.formOffreCommunesListening=new ArrayList<SelectItem>();
}
}
if(this.avecFichierOuLien){
switch (this.fichierOuLien) {
case 1:
this.formOffre.setAvecFichier(true);
this.formOffre.setAvecLien(false);
this.formOffre.setLienAttache("");
break;
case 2:
this.deleteUploadedFile();
this.formOffre.setAvecFichier(false);
this.formOffre.setAvecLien(true);
break;
default:
this.deleteUploadedFile();
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape1");
getSessionController().setCreationOffreCurrentPage("_creationOffreEtape1");
break;
}
} else {
//Suppression de l'ancien fichier/lien
this.deleteUploadedFile();
}
this.formOffre.setIdTypeOffre(this.formOffre.getTypeOffre().getId());
//Màj liste des contrats
List<ContratOffreDTO> l = getNomenclatureDomainService().getContratsOffreFromIdTypeOffre(this.formOffre.getIdTypeOffre());
if(l!=null && !l.isEmpty()){
this.contratsListening=new ArrayList<>();
for(ContratOffreDTO c : l){
this.contratsListening.add(new SelectItem(c,c.getLibelle()));
}
}else{
this.contratsListening=null;
}
// On initialise l'uniteDuree a vide pour eviter qu'elle soit remplie par defaut.
this.formOffre.setUniteDuree(new UniteDureeDTO());
//Reset de la durée de diffusion
this.dureeDiffusion = 2;
return this.creationOffre;
}
public boolean isAffichageDureeOffre(){
if ((this.formOffre.getContratOffre() != null && this.formOffre.getContratOffre().equals(getBeanUtils().getCdd()))
|| (this.formOffre.getTypeOffre() != null &&
(this.formOffre.getTypeOffre().equals(getBeanUtils().getStage())
|| this.formOffre.getTypeOffre().equals(getBeanUtils().getAlternance())
|| this.formOffre.getTypeOffre().equals(getBeanUtils().getVieVia())))){
return true;
}
return false;
}
public boolean isPaysOffreFrance(){
if ((this.formOffre.getLieuPays() != null && getBeanUtils().isFrance(this.formOffre.getLieuPays()))){
return true;
}
return false;
}
/**
* Envoi vers l'étape 3
* Saisie des contacts
* @return String
*/
public String goToCreationOffreEtape3(){
getSessionController().setCreationOffreCurrentPage("_creationOffreEtape3");
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape3");
return this.creationOffre;
}
/**
* Ajout de l'offre en base
*/
public void ajoutOffre(){
this._ajoutOffre();
if(this.formOffre.getIdOffre() > 0
&& getSessionController().getCurrentManageStructure() != null
&& getSessionController().getCurrentManageStructure().getIdStructure() == this.formOffre.getIdStructure()){
if(this.listeOffres==null)
this.listeOffres=new ArrayList<OffreDTO>();
this.listeOffres.add(this.formOffre);
this.currentOffre = this.formOffre;
this.formOffre=new OffreDTO();
}
// return ret;
}
/**
* Méthode d'ajout d'une offre subdivisée pour gérer l'ajout d'offre d'une entreprise et l'ajout d'offre d'un centre (ne nécessite pas la maj de la liste des offres)
* @return String
*/
public void _ajoutOffre(){
// String ret=null;
if(this.centreGestionDepotAnonyme!=null){
this.formOffre.setLoginCreation("depotAnonyme");
}else{
this.formOffre.setLoginCreation(getSessionController().getCurrentLogin());
}
if(this.formOffre.getLieuPays()!=null){
if(getBeanUtils().isFrance(this.formOffre.getLieuPays()) && getSessionController().isRecupererCommunesDepuisApogee() && !"0".equals(this.formOffre.getCodeCommune())){
//Récupération de la commune pour en avoir le libellé
CommuneDTO c = getGeographieRepositoryDomain().getCommuneFromDepartementEtCodeCommune(this.formOffre.getLieuCodePostal(), ""+this.formOffre.getCodeCommune());
if(c!=null){
this.formOffre.setLieuCommune(c.getLibCommune());
}
}
this.formOffre.setIdLieuPays(this.formOffre.getLieuPays().getId());
}
if(this.formOffre.getFapQualificationSimplifiee()!=null)this.formOffre.setIdQualificationSimplifiee(this.formOffre.getFapQualificationSimplifiee().getId());
if(this.formOffre.getFapN1()!=null)this.formOffre.setCodeFAP_N3(this.formOffre.getFapN1().getCode());
if(this.formOffre.getTypeOffre()!=null)this.formOffre.setIdTypeOffre(this.formOffre.getTypeOffre().getId());
else this.formOffre.setIdTypeOffre(0);
if(this.formOffre.getContratOffre()!=null)this.formOffre.setIdContratOffre(this.formOffre.getContratOffre().getId());
else this.formOffre.setIdContratOffre(0);
if(this.formOffre.getNiveauFormation()!=null)this.formOffre.setIdNiveauFormation(this.formOffre.getNiveauFormation().getId());
else this.formOffre.setIdNiveauFormation(0);
this.formOffre.setAnneeUniversitaire(getBeanUtils().getAnneeUniversitaireCourante(new Date()));
this.formOffre.setCentreGestion(getCentreGestionDomainService().getCentreGestion(this.formOffre.getIdCentreGestion()));
int idOffreAjoutee;
if(this.avecFichierOuLien){
this.formOffre.setIdTempsTravail(0);
this.formOffre.setIdUniteDuree(0);
this.formOffre.setModesCandidature(null);
this.formOffre.setIdsModeCandidature(null);
this.formOffre.setContactCand(null);
this.formOffre.setContactInfo(null);
this.formOffre.setIdContactCand(0);
this.formOffre.setIdContactInfo(0);
switch (this.fichierOuLien) {
case 1:
if(this.formOffre.getIdFichier()>0){
try{
this.formOffre.setAvecFichier(true);
this.formOffre.setAvecLien(false);
this.formOffre.setLienAttache("");
idOffreAjoutee = getOffreDomainService().addOffre(this.formOffre);
this.formOffre.setIdOffre(idOffreAjoutee);
this.formOffre.setDateCreation(new Date());
this.formOffre.setLoginCreation(getSessionController().getCurrentLogin());
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape4Confirmation");
getSessionController().setCreationOffreCurrentPage("_creationOffreEtape4Confirmation");
addInfoMessage(null, "OFFRE.CREATION.CONFIRMATION", this.formOffre.getIdOffre());
// mailAjout();
}catch (DataAddException|WebServiceDataBaseException e) {
logger.error(e);
}
}else{
addErrorMessage("formCreationOffre", "OFFRE.SELECTIONFICHIER.OBLIGATOIRE");
}
break;
case 2:
try{
this.formOffre.setFichier(null);
this.formOffre.setIdFichier(0);
this.formOffre.setAvecFichier(false);
this.formOffre.setAvecLien(true);
idOffreAjoutee = getOffreDomainService().addOffre(this.formOffre);
this.formOffre.setIdOffre(idOffreAjoutee);
this.formOffre.setDateCreation(new Date());
this.formOffre.setLoginCreation(getSessionController().getCurrentLogin());
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape4Confirmation");
getSessionController().setCreationOffreCurrentPage("_creationOffreEtape4Confirmation");
addInfoMessage(null, "OFFRE.CREATION.CONFIRMATION", this.formOffre.getIdOffre());
mailAjout();
}catch (DataAddException|WebServiceDataBaseException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.CREATION.ERREURAJOUT");
}
break;
}
}else{
if(this.formOffre.getTempsTravail()!=null)this.formOffre.setIdTempsTravail(this.formOffre.getTempsTravail().getId());
else this.formOffre.setIdTempsTravail(0);
if(this.formOffre.getUniteDuree()!=null)this.formOffre.setIdUniteDuree(this.formOffre.getUniteDuree().getId());
else this.formOffre.setIdUniteDuree(0);
if(this.formOffre.getModesCandidature()!=null){
ArrayList<Integer> l = new ArrayList<Integer>();
for(ModeCandidatureDTO m : this.formOffre.getModesCandidature()){
l.add(m.getId());
}
if(!l.isEmpty())this.formOffre.setIdsModeCandidature(l);
else this.formOffre.setIdsModeCandidature(null);
}
if(this.formOffre.getContactCand()!=null){
try{
this.formOffre.setIdContactCand(this.formOffre.getContactCand().getId());
if(this.formOffre.getContactInfo()!=null)this.formOffre.setIdContactInfo(this.formOffre.getContactInfo().getId());
this.formOffre.setFichier(null);
this.formOffre.setIdFichier(0);
idOffreAjoutee = getOffreDomainService().addOffre(this.formOffre);
this.formOffre.setIdOffre(idOffreAjoutee);
this.formOffre.setDateCreation(new Date());
this.formOffre.setLoginCreation(getSessionController().getCurrentLogin());
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape4Confirmation");
getSessionController().setCreationOffreCurrentPage("_creationOffreEtape4Confirmation");
addInfoMessage(null, "OFFRE.CREATION.CONFIRMATION", this.formOffre.getIdOffre());
mailAjout();
}catch (DataAddException|WebServiceDataBaseException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.CREATION.ERREURAJOUT");
}
}else{
addErrorMessage("formCreationOffre:contactCand", "OFFRE.SELECTIONCONTACTCAND.OBLIGATOIRE");
}
}
if(this.diffusionDirecte){
this.currentOffre = this.formOffre;
this.diffuserOffre();
} else if (!this.formOffre.isEstDiffusee()){
addInfoMessage(null, "OFFRE.CREATION.CONFIRMATION.DIFFUSION", this.formOffre.getIdOffre());
}
// return ret;
}
/**
*
*/
public void mailAjout(){
//Envoi mail sur la mailing list entreprise
String infoPersonne="";
if(getSessionController().isAdminPageAuthorized() && getSessionController().getCurrentAuthAdminStructure()!=null){
infoPersonne+=getSessionController().getCurrentAuthAdminStructure().getNom()+" "+getSessionController().getCurrentAuthAdminStructure().getPrenom()+" ("+getSessionController().getCurrentLogin()+")";
}else if(getSessionController().isPageAuthorized() && getSessionController().getCurrentAuthContact()!=null){
infoPersonne+=getSessionController().getCurrentAuthContact().getNom()+" "+getSessionController().getCurrentAuthContact().getPrenom()+" ("+getSessionController().getCurrentLogin()+")";
}else{
infoPersonne+=getSessionController().getCurrentLogin();
}
if(centreGestionDepotAnonyme!=null && centreGestionDepotAnonyme.getIdCentreGestion()>0){
if(StringUtils.hasText(centreGestionDepotAnonyme.getMail())){
InternetAddress ia = null;
try {
ia = new InternetAddress(centreGestionDepotAnonyme.getMail());
infoPersonne="depot anonyme";
getSmtpService().send(
ia,
getString("MAIL.ADMIN.OFFRE.SUJETAJOUT", getSessionController().getApplicationNameEntreprise(),this.formOffre.getStructure().printAdresse(), infoPersonne),
getString("MAIL.ADMIN.OFFRE.MESSAGEAJOUT", getSessionController().getApplicationNameEntreprise(),this.formOffre.getIdOffre() +", "+this.formOffre.getIntitule(),this.formOffre.getStructure().printAdresse(), infoPersonne),
""
);
} catch (AddressException e) {
logger.info(e);
}
}
}else if(getSessionController().isMailingListEntrMailAvertissementAjoutOffre() && StringUtils.hasText(getSessionController().getMailingListEntr())
&& (getSessionController().isAdminPageAuthorized() || getSessionController().isPageAuthorized())){
getSmtpService().send(
getSessionController().getMailingListEntrIA(),
getString("MAIL.ADMIN.OFFRE.SUJETAJOUT", getSessionController().getApplicationNameEntreprise(),this.formOffre.getStructure().printAdresse(), infoPersonne),
getString("MAIL.ADMIN.OFFRE.MESSAGEAJOUT", getSessionController().getApplicationNameEntreprise(),this.formOffre.getIdOffre() +", "+this.formOffre.getIntitule(),getSessionController().getCurrentManageStructure().printAdresse(), infoPersonne),
""
);
}
}
/* ***************************************************************
* Modification d'une offre
****************************************************************/
public void initVarsOffre(){
this.etablissementController.reloadServices();
this.etablissementController.reloadContacts();
}
/**
* @return String
*/
public String goToEntrepriseModificationOffre(){
String ret=null;
this.formOffre=(OffreDTO) this.currentOffre.clone();
if(this.formOffre!=null){
if(this.formOffre.isAvecFichier() || this.formOffre.isAvecLien()){
this.avecFichierOuLien=true;
if(this.formOffre.isAvecFichier()){
this.fichierOuLien=1;
if(this.currentOffre.getFichier()!=null){
this.formOffre.setFichier((FichierDTO)this.currentOffre.getFichier().clone());
}
}
else if(this.formOffre.isAvecLien())this.fichierOuLien=2;
}else{
this.avecFichierOuLien=false;
this.fichierOuLien=0;
}
ret="modificationOffre";
}
return ret;
}
/**
* @return String
*/
public String goToModificationOffre(){
String ret=null;
if(this.currentOffre!=null){
this.formOffre=(OffreDTO) this.currentOffre.clone();
// Si l'on est cote depot en tant qu'entreprise
if ("offre".equalsIgnoreCase(this.currentRecapOffre)) {
this.retour = "recapitulatifOffre";
} else {
// Sinon on est dans l'un des 3 autres cas
this.currentOffre = getOffreDomainService().getOffreFromId(this.currentOffre.getIdOffre());
this.currentOffre.setStructure(getStructureDomainService().getStructureFromId(this.currentOffre.getIdStructure()));
// Si l'on est dans le cas du recapitulatif d'offre cote stage avec etab
if ("offreEtabCentre".equalsIgnoreCase(this.currentRecapOffre)) {
// On conserve le squelette dans lequel on va revenir
this.retour = "recapitulatifOffreEtabCentre";
getSessionController().setCentreGestionRattachement(this.currentOffre.getCentreGestion());
if (!isListeCurrentIdsCentresGestionContainsIdCGCurrentOffre()) {
CentreGestionDTO c = getCentreGestionDomainService().getCentreGestion(this.currentOffre.getIdCentreGestion());
if (c != null){
this.currentOffre.setCentreGestion(c);
} else {
return ret;
}
} else {
if (getSessionController().getCurrentIdsCentresGestion() != null &&
!getSessionController().getCurrentIdsCentresGestion().isEmpty()) {
for (CentreGestionDTO c : getSessionController().getCurrentCentresGestion()) {
if (c.getIdCentreGestion() == this.currentOffre.getIdCentreGestion()) {
this.currentOffre.setCentreGestion(c);
break;
}
}
}
}
} else {
// On conserve le squelette dans lequel on va revenir
this.retour = "recapitulatifOffreEtab";
}
}
if(this.formOffre.isAvecFichier() || this.formOffre.isAvecLien()){
this.avecFichierOuLien=true;
if(this.formOffre.isAvecFichier()){
this.fichierOuLien=1;
if(this.currentOffre.getFichier()!=null){
this.formOffre.setFichier((FichierDTO)this.currentOffre.getFichier().clone());
}
}
else if(this.formOffre.isAvecLien())this.fichierOuLien=2;
}else{
this.avecFichierOuLien=false;
this.fichierOuLien=0;
}
ret="modificationOffre";
}
return ret;
}
/**
* Vrai si currentIdsCentresGestion contains l'id du centre de gestion de l'offre courante : currentOffre
* Auquel cas modification possible du centre de gestion pour une offre
* @return boolean
*/
public boolean isListeCurrentIdsCentresGestionContainsIdCGCurrentOffre(){
boolean ret=false;
if(getSessionController().getCurrentIdsCentresGestion()!=null &&
!getSessionController().getCurrentIdsCentresGestion().isEmpty() &&
((ArrayList<Integer>)getSessionController().getCurrentIdsCentresGestion()).
contains(this.currentOffre.getIdCentreGestion())){
ret=true;
}
return ret;
}
/**
*
*/
public void goToModificationOffreModifEtab(){
this.etablissementController.goToModificationEtablissement();
getSessionController().setModificationOffreCurrentPage("_modificationOffreEtape05ModifEtab");
}
/**
*
*/
public void modifierOffreModifierEtablissement(){
String ret=this.etablissementController.modifierEtablissement();
this.currentOffre.setStructure(this.etablissementController.getFormStructure());
FacesContext fc = FacesContext.getCurrentInstance();
Iterator<FacesMessage> ifm = fc.getMessages("formModifEtab");
while(ifm.hasNext()){
FacesMessage fm = ifm.next();
fc.addMessage("formModificationOffre:formModifEtab", new FacesMessage(FacesMessage.SEVERITY_ERROR,fm.getSummary(),fm.getDetail()));
ifm.remove();
}
ifm = fc.getMessages("formAffEtab");
while(ifm.hasNext()){
FacesMessage fm = ifm.next();
fc.addMessage("formModificationOffre:formAffEtab", new FacesMessage(fm.getSummary(),fm.getDetail()));
ifm.remove();
}
if(StringUtils.hasText(ret)){
getSessionController().setModificationOffreCurrentPage("_modificationOffreEtape04DetailsEtab");
}
// return "";
}
/**
* @return String
*/
public void modificationOffreDetailsEtab(){
this.formOffre.setCentreGestion(getCentreGestionDomainService().getCentreGestion(this.formOffre.getIdCentreGestion()));
getSessionController().setCentreGestionRattachement(this.formOffre.getCentreGestion());
this.modificationOffre();
}
/**
* Envoi vers l'Etape 2 : Saisie de l'offre
*/
public void goToModificationOffreEtape2(){
getSessionController().setModificationOffreCurrentPage("_modificationOffreEtape2");
if(this.formOffre.getIdLieuPays()<=0){
this.formOffre.setLieuPays(this.formOffre.getStructure().getPays());
if(getSessionController().isRecupererCommunesDepuisApogee() &&
getBeanUtils().isFrance(this.formOffre.getLieuPays())){
List<SelectItem> lTmp = majCommunes(""+this.formOffre.getLieuCodePostal());
if(lTmp!=null && !lTmp.isEmpty()){
this.formOffreCommunesListening=lTmp;
}else{
this.formOffreCommunesListening=new ArrayList<SelectItem>();
}
}
}
if(this.avecFichierOuLien){
switch (this.fichierOuLien) {
case 1:
//Si l'offre modifiée était déjà avec fichier joint, on ne fait rien
if(!this.currentOffre.isAvecFichier()){
this.formOffre.setAvecFichier(true);
this.formOffre.setAvecLien(false);
this.formOffre.setLienAttache("");
try {
FichierDTO o = new FichierDTO();
o.setNomFichier("");
int idFichier = getOffreDomainService().addFichier(o);
o.setIdFichier(idFichier);
this.formOffre.setFichier(o);
getSessionController().getOffreFileUploadBean().setPrefix(idFichier);
} catch (DataAddException|WebServiceDataBaseException e) {
logger.error(e);
}
}
break;
case 2:
//Si l'offre modifiée était déjà avec lien, on ne fait rien
if(!this.currentOffre.isAvecLien()){
this.formOffre.setAvecFichier(false);
this.formOffre.setAvecLien(true);
this.formOffre.setLienAttache("http://");
}
break;
default:
getSessionController().setModificationOffreCurrentPage("_modificationOffreEtape1");
break;
}
}
this.formOffre.setIdTypeOffre(this.formOffre.getTypeOffre().getId());
//Màj liste des contrats
List<ContratOffreDTO> l = getNomenclatureDomainService().getContratsOffreFromIdTypeOffre(this.formOffre.getIdTypeOffre());
if(l!=null && !l.isEmpty()){
this.contratsListening=new ArrayList<>();
for(ContratOffreDTO c : l){
this.contratsListening.add(new SelectItem(c,c.getLibelle()));
}
}else{
this.contratsListening=null;
}
// Initialisations du temps travail et des modes candidature avec ceux deja saisis dans l'ob
if (this.formOffre.getIdTempsTravail() != 0) {
this.formOffre.setTempsTravail(getNomenclatureDomainService().getTempsTravailFromId(this.formOffre.getIdTempsTravail()));
}
if (this.formOffre.getIdsModeCandidature() != null && !this.formOffre.getIdsModeCandidature().isEmpty()){
List<ModeCandidatureDTO> lmc = new ArrayList<>();
for (Integer id : this.formOffre.getIdsModeCandidature()){
lmc.add(getNomenclatureDomainService().getModeCandidatureFromId(id));
}
this.formOffre.setModesCandidature(lmc);
}
this.fapN3Listening=getFapN3FromNumQualif(this.formOffre.getIdQualificationSimplifiee());
if(getSessionController().isRecupererCommunesDepuisApogee() &&
getBeanUtils().isFrance(this.formOffre.getLieuPays())){
List<SelectItem> lTmp = majCommunes(""+this.formOffre.getLieuCodePostal());
if(lTmp!=null && !lTmp.isEmpty()){
this.formOffreCommunesListening=lTmp;
}else{
this.formOffreCommunesListening=new ArrayList<SelectItem>();
}
}
}
/**
* Modification de l'offre
*/
public void modificationOffre(){
String ret=_modificationOffre();
if(StringUtils.hasText(ret)){
getSessionController().setModificationOffreCurrentPage(ret);
this.currentOffre=(OffreDTO) this.formOffre.clone();
if(this.formOffre.getFichier()!=null) this.currentOffre.setFichier((FichierDTO)(this.formOffre.getFichier().clone()));
this.formOffre=null;
if(this.listeOffres!=null && this.listeOffres.contains(this.currentOffre)){
int id = this.listeOffres.indexOf(this.currentOffre);
if(id>0){
this.listeOffres.set(id,this.currentOffre);
}
}
if(this.resultatsRechercheOffre!=null && this.resultatsRechercheOffre.contains(this.currentOffre)){
//rechercherOffre();
int id = this.resultatsRechercheOffre.indexOf(this.currentOffre);
if(id>0){
this.resultatsRechercheOffre.set(id,this.currentOffre);
reloadRechercheOffrePaginator();
}
}
}
// return ret;
}
/**
* Méthode modification de l'offre subDivisée en 2 pour gérer la modification par une entreprise et par un centre
* @return String
*/
public String _modificationOffre(){
String ret=null;
this.formOffre.setLoginModif(getSessionController().getCurrentLogin());
if(this.formOffre.getLieuPays()!=null) {
this.formOffre.setIdLieuPays(this.formOffre.getLieuPays().getId());
if (getBeanUtils().isFrance(this.formOffre.getLieuPays()) && getSessionController().isRecupererCommunesDepuisApogee()) {
if (!"0".equals(this.formOffre.getCodeCommune())) {
//Récupération de la commune pour en avoir le libellé
CommuneDTO c = getGeographieRepositoryDomain().getCommuneFromDepartementEtCodeCommune(this.formOffre.getLieuCodePostal(), "" + this.formOffre.getCodeCommune());
if (c != null) {
this.formOffre.setLieuCommune(c.getLibCommune());
}
}
}
}
if(this.formOffre.getFapQualificationSimplifiee()!=null)this.formOffre.setIdQualificationSimplifiee(this.formOffre.getFapQualificationSimplifiee().getId());
//if(this.formOffre.getFapN3()!=null)this.formOffre.setCodeFAP_N3(this.formOffre.getFapN3().getCode());
if(this.formOffre.getFapN1()!=null)this.formOffre.setCodeFAP_N3(this.formOffre.getFapN1().getCode());
if(this.formOffre.getTypeOffre()!=null)this.formOffre.setIdTypeOffre(this.formOffre.getTypeOffre().getId());
else this.formOffre.setIdContratOffre(0);
if(this.formOffre.getContratOffre()!=null)this.formOffre.setIdContratOffre(this.formOffre.getContratOffre().getId());
else this.formOffre.setIdContratOffre(0);
if(this.formOffre.getNiveauFormation()!=null)this.formOffre.setIdNiveauFormation(this.formOffre.getNiveauFormation().getId());
else this.formOffre.setIdNiveauFormation(0);
this.formOffre.setAnneeUniversitaire(getBeanUtils().getAnneeUniversitaireCourante(new Date()));
if(this.avecFichierOuLien){
this.formOffre.setTempsTravail(null);
this.formOffre.setIdTempsTravail(0);
this.formOffre.setUniteDuree(null);
this.formOffre.setIdUniteDuree(0);
this.formOffre.setModesCandidature(null);
this.formOffre.setIdsModeCandidature(null);
this.formOffre.setContactCand(null);
this.formOffre.setContactInfo(null);
this.formOffre.setIdContactCand(0);
this.formOffre.setIdContactInfo(0);
switch (this.fichierOuLien) {
case 1:
if(this.formOffre.getIdFichier()>0){
try{
this.formOffre.setAvecFichier(true);
this.formOffre.setAvecLien(false);
this.formOffre.setLienAttache(null);
getOffreDomainService().updateOffre(this.formOffre);
this.formOffre.setDateModif(new Date());
this.formOffre.setLoginModif(getSessionController().getCurrentLogin());
//Maj listes
if(this.listeOffres!=null && ((ArrayList<OffreDTO>)this.listeOffres).contains(this.formOffre)){
this.listeOffres.set(this.listeOffres.indexOf(this.formOffre), this.formOffre);
}
if(this.resultatsRechercheOffre!=null && ((ArrayList<OffreDTO>)this.resultatsRechercheOffre).contains(this.formOffre)){
this.resultatsRechercheOffre.set(this.resultatsRechercheOffre.indexOf(this.formOffre), this.formOffre);
checkListeResultats();
}
ret="_modificationOffreEtape4Confirmation";
addInfoMessage(null, "OFFRE.MODIFICATION.CONFIRMATION", this.formOffre.getIdOffre());
mailModif();
}catch (DataAddException|WebServiceDataBaseException e) {
logger.error(e);
}
}else{
addErrorMessage("formModificationOffre:opUploadFile:uploadFile", "OFFRE.SELECTIONFICHIER.OBLIGATOIRE");
return null;
}
break;
case 2:
try{
this.formOffre.setFichier(null);
this.formOffre.setIdFichier(0);
this.formOffre.setAvecFichier(false);
this.formOffre.setAvecLien(true);
getOffreDomainService().updateOffre(this.formOffre);
this.formOffre.setDateModif(new Date());
this.formOffre.setLoginModif(getSessionController().getCurrentLogin());
//Maj listes
if(this.listeOffres!=null && ((ArrayList<OffreDTO>)this.listeOffres).contains(this.formOffre)){
this.listeOffres.set(this.listeOffres.indexOf(this.formOffre), this.formOffre);
}
if(this.resultatsRechercheOffre!=null && ((ArrayList<OffreDTO>)this.resultatsRechercheOffre).contains(this.formOffre)){
this.resultatsRechercheOffre.set(this.resultatsRechercheOffre.indexOf(this.formOffre), this.formOffre);
checkListeResultats();
}
//Suppression de l'ancien fichier
if(this.currentOffre.isAvecFichier() &&
this.currentOffre.getIdFichier()>0){
try{
if(this.currentOffre.getFichier()!=null
&& StringUtils.hasText(this.currentOffre.getFichier().getNomFichier())){
getSessionController().getOffreFileUploadBean().deleteFileFromDirectory(
this.currentOffre.getIdFichier(), this.currentOffre.getFichier().getNomFichier());
}
getOffreDomainService().deleteFichier(this.currentOffre.getIdFichier());
}catch (DataDeleteException|WebServiceDataBaseException e) {
logger.warn(e);
}
}
mailModif();
ret="_modificationOffreEtape4Confirmation";
addInfoMessage(null, "OFFRE.MODIFICATION.CONFIRMATION", this.formOffre.getIdOffre());
}catch (DataAddException|WebServiceDataBaseException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.MODIFICATION.ERREURAJOUT");
return null;
}
break;
}
}else{
this.formOffre.setFichier(null);
this.formOffre.setIdFichier(0);
this.formOffre.setLienAttache(null);
this.formOffre.setAvecFichier(false);
this.formOffre.setAvecLien(false);
if(this.formOffre.getTempsTravail()!=null)this.formOffre.setIdTempsTravail(this.formOffre.getTempsTravail().getId());
else this.formOffre.setIdTempsTravail(0);
if(this.formOffre.getUniteDuree()!=null)this.formOffre.setIdUniteDuree(this.formOffre.getUniteDuree().getId());
else this.formOffre.setIdUniteDuree(0);
if(this.formOffre.getModesCandidature()!=null){
ArrayList<Integer> l = new ArrayList<Integer>();
for(ModeCandidatureDTO m : this.formOffre.getModesCandidature()){
l.add(m.getId());
}
if(!l.isEmpty())this.formOffre.setIdsModeCandidature(l);
else this.formOffre.setIdsModeCandidature(null);
}
if(this.formOffre.getContactCand()!=null){
try{
this.formOffre.setIdContactCand(this.formOffre.getContactCand().getId());
if(this.formOffre.getContactInfo()!=null){
this.formOffre.setIdContactInfo(this.formOffre.getContactInfo().getId());
} else {
this.formOffre.setIdContactInfo(0);
}
this.formOffre.setFichier(null);
this.formOffre.setIdFichier(0);
if(getOffreDomainService().updateOffre(this.formOffre)){
this.formOffre.setDateModif(new Date());
this.formOffre.setLoginModif(getSessionController().getCurrentLogin());
//Maj listes
if(this.listeOffres!=null && ((ArrayList<OffreDTO>)this.listeOffres).contains(this.formOffre)){
this.listeOffres.set(this.listeOffres.indexOf(this.formOffre), this.formOffre);
}
if(this.resultatsRechercheOffre!=null && ((ArrayList<OffreDTO>)this.resultatsRechercheOffre).contains(this.formOffre)){
this.resultatsRechercheOffre.set(this.resultatsRechercheOffre.indexOf(this.formOffre), this.formOffre);
checkListeResultats();
}
//Suppression de l'ancien fichier
if(this.currentOffre.isAvecFichier() &&
this.currentOffre.getIdFichier()>0){
try{
if(this.currentOffre.getFichier()!=null
&& StringUtils.hasText(this.currentOffre.getFichier().getNomFichier())){
getSessionController().getOffreFileUploadBean().deleteFileFromDirectory(
this.currentOffre.getIdFichier(), this.currentOffre.getFichier().getNomFichier());
}
getOffreDomainService().deleteFichier(this.currentOffre.getIdFichier());
}catch (DataDeleteException|WebServiceDataBaseException e) {
logger.warn(e);
}
}
}
ret="_modificationOffreEtape4Confirmation";
addInfoMessage(null, "OFFRE.MODIFICATION.CONFIRMATION", this.formOffre.getIdOffre());
mailModif();
}catch (DataUpdateException|WebServiceDataBaseException e) {
// ret="_modificationOffreEtape4Confirmation";
logger.error(e);
addErrorMessage(null, "OFFRE.MODIFICATION.ERREURMODIF");
return null;
}
}else{
addErrorMessage("formModificationOffre:contactCand", "OFFRE.SELECTIONCONTACTCAND.OBLIGATOIRE");
return null;
}
}
return ret;
}
/**
*
*/
public void mailModif(){
if(getSessionController().isMailingListEntrMailAvertissementModifOffre() && StringUtils.hasText(getSessionController().getMailingListEntr())
&& (getSessionController().isAdminPageAuthorized() || getSessionController().isPageAuthorized())){
//Envoi mail sur la mailing list entreprise
String infoPersonne="";
if(getSessionController().isAdminPageAuthorized() && getSessionController().getCurrentAuthAdminStructure()!=null){
infoPersonne+=getSessionController().getCurrentAuthAdminStructure().getNom()+" "+getSessionController().getCurrentAuthAdminStructure().getPrenom()+" ("+getSessionController().getCurrentLogin()+")";
}else if(getSessionController().isPageAuthorized() && getSessionController().getCurrentAuthContact()!=null){
infoPersonne+=getSessionController().getCurrentAuthContact().getNom()+" "+getSessionController().getCurrentAuthContact().getPrenom()+" ("+getSessionController().getCurrentLogin()+")";
}else{
infoPersonne+=getSessionController().getCurrentLogin();
}
getSmtpService().send(
getSessionController().getMailingListEntrIA(),
getString("MAIL.ADMIN.OFFRE.SUJETMODIF", getSessionController().getApplicationNameEntreprise(),this.formOffre.getIdOffre() +", "+this.formOffre.getIntitule(), infoPersonne),
getString("MAIL.ADMIN.OFFRE.MESSAGEMODIF", getSessionController().getApplicationNameEntreprise(),this.formOffre.getIdOffre() +", "+this.formOffre.getIntitule(),this.formOffre.getStructure().printAdresse(), infoPersonne),
""
);
}
}
/**
* Suppression d'une offre
*/
public void supprimerOffre(){
try{
getSessionController().setSuppressionOffreCurrentPage("_confirmationDialog");
if(getOffreDomainService().deleteOffreLogique(this.currentOffre.getIdOffre())){
//Maj listes
if(this.listeOffres!=null && ((ArrayList<OffreDTO>)this.listeOffres).contains(this.currentOffre)){
this.listeOffres.remove(this.listeOffres.indexOf(this.currentOffre));
}
if(this.resultatsRechercheOffre!=null && ((ArrayList<OffreDTO>)this.resultatsRechercheOffre).contains(this.currentOffre)){
this.resultatsRechercheOffre.remove(this.resultatsRechercheOffre.indexOf(this.currentOffre));
checkListeResultats();
}
mailSuppr();
this.currentOffre=null;
}
addInfoMessage(null, "OFFRE.SUPPR.CONFIRMATION");
}catch (DataUpdateException|WebServiceDataBaseException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.SUPPR.ERREUR");
}
}
/**
*
*/
public void mailSuppr(){
if(getSessionController().isMailingListEntrMailAvertissementSupprOffre() && StringUtils.hasText(getSessionController().getMailingListEntr())
&& (getSessionController().isAdminPageAuthorized() || getSessionController().isPageAuthorized())){
//Envoi mail sur la mailing list entreprise
String infoPersonne="";
if(getSessionController().isAdminPageAuthorized() && getSessionController().getCurrentAuthAdminStructure()!=null){
infoPersonne+=getSessionController().getCurrentAuthAdminStructure().getNom()+" "+getSessionController().getCurrentAuthAdminStructure().getPrenom()+" ("+getSessionController().getCurrentLogin()+")";
}else if(getSessionController().isPageAuthorized() && getSessionController().getCurrentAuthContact()!=null){
infoPersonne+=getSessionController().getCurrentAuthContact().getNom()+" "+getSessionController().getCurrentAuthContact().getPrenom()+" ("+getSessionController().getCurrentLogin()+")";
}else{
infoPersonne+=getSessionController().getCurrentLogin();
}
getSmtpService().send(
getSessionController().getMailingListEntrIA(),
getString("MAIL.ADMIN.OFFRE.SUJETSUPPR", getSessionController().getApplicationNameEntreprise(),this.currentOffre.getIdOffre() +", "+this.currentOffre.getIntitule(), infoPersonne),
getString("MAIL.ADMIN.OFFRE.MESSAGESUPPR", getSessionController().getApplicationNameEntreprise(),this.currentOffre.getIdOffre() +", "+this.currentOffre.getIntitule(),getSessionController().getCurrentManageStructure().printAdresse(), infoPersonne),
""
);
}
}
@SuppressWarnings("unused")
private boolean ciblageInterdit;
public boolean isCiblageInterdit(){
if (this.currentOffre != null){
CentreGestionDTO cgEntr = getCentreGestionDomainService().getCentreEntreprise();
if (cgEntr != null
&& this.currentOffre.getIdCentreGestion() == cgEntr.getIdCentreGestion()
&& getSessionController().getCurrentAuthPersonnel() != null
&& !getSessionController().isPageAuthorized()
&& !getSessionController().isAdminPageAuthorized()
&& !getSessionController().isSuperAdminPageAuthorized()){
return true;
}
}
return false;
}
/**
* @return String
*/
public void diffuserOffre(){
getSessionController().setDiffusionOffreCurrentPage("_confirmationDialog");
if(this.currentOffre!=null && this.currentOffre.getIdOffre()>0){
try{
int x = (this.dureeDiffusion - 1);
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
int annee = Integer.parseInt(dateFormat.format(new Date()).split("/")[2]);
int mois = Integer.parseInt(dateFormat.format(new Date()).split("/")[1]);
int jour = Integer.parseInt(dateFormat.format(new Date()).split("/")[0]);
// date du jour + x mois selon la DureeDiffusion choisie
if ((mois+x) < 12){
mois = mois + x;
} else if((mois+x) > 12 && (mois+x) < 24){
mois = mois + x - 12;
annee = annee + 1;
} else {
mois = mois + x - 24;
annee = annee + 2;
}
gc.set(annee,mois,jour);
getOffreDomainService().updateDiffusionOffre(this.currentOffre.getIdOffre(), getSessionController().getCurrentLogin(),gc.getTime());
getOffreDomainService().updateValidationOffre(this.currentOffre.getIdOffre(), getSessionController().getCurrentLogin());
addInfoMessage(null, "OFFRE.GESTION.DIFFUSION.CONFIRMATION");
getOffreDomainService().updateOffrePourvue(this.currentOffre.getIdOffre(), false);
if (getSessionController().isModerationActive() && getSessionController().isAvertissementEntrepriseDiffusion()){
String text=getString("ALERTES_MAIL.AVERTISSEMENT_ENTREPRISE_DIFFUSION",this.currentOffre.getIdOffre());
String sujet=getString("ALERTES_MAIL.AVERTISSEMENT_ENTREPRISE_DIFFUSION.SUJET",this.currentOffre.getIdOffre());
if (this.currentOffre.isAvecFichier() || this.currentOffre.isAvecLien()){
// Il est necessaire de verifier d'abord si un fichier/lien est present car dans ce cas il n'y aura pas de contact
// et donc pas de mail envoyé
} else {
if (this.currentOffre.getContactCand()!= null && this.currentOffre.getContactCand().getMail() != null
&& !this.currentOffre.getContactCand().getMail().isEmpty()){
getSmtpService().send(new InternetAddress(this.currentOffre.getContactCand().getMail()),
sujet,text,text);
} else {
addErrorMessage(null, "OFFRE.GESTION.DIFFUSION.ALERTE.ERREUR_MAIL");
}
}
}
//Màj de l'objet courant
this.currentOffre.setEstPourvue(false);
this.currentOffre.setEstDiffusee(true);
this.currentOffre.setDateDiffusion(new Date());
this.currentOffre.setDateFinDiffusion(gc.getTime());
this.currentOffre.setEstValidee(true);
this.currentOffre.setEtatValidation(1);
//Maj listes
if(this.listeOffres!=null && ((ArrayList<OffreDTO>)this.listeOffres).contains(this.currentOffre)){
this.listeOffres.set(this.listeOffres.indexOf(this.currentOffre), this.currentOffre);
}
if(this.resultatsRechercheOffre!=null && ((ArrayList<OffreDTO>)this.resultatsRechercheOffre).contains(this.currentOffre)){
this.resultatsRechercheOffre.set(this.resultatsRechercheOffre.indexOf(this.currentOffre), this.currentOffre);
checkListeResultats();
}
}catch (DataUpdateException|WebServiceDataBaseException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.GESTION.DIFFUSION.ERREUR");
}catch (AddressException ade){
logger.error("AddressException", ade);
addErrorMessage(null, "GENERAL.ERREUR_MAIL");
}
}
// return ret;
}
/**
* Arrêt de la diffusion de l'offre actuellement sélectionnée
*/
public void stopDiffusionOffre(){
getSessionController().setStopDiffusionOffreCurrentPage("_confirmationDialog");
if(this.currentOffre!=null){
try{
getOffreDomainService().updateStopDiffusionOffre(this.currentOffre.getIdOffre(), getSessionController().getCurrentLogin());
getOffreDomainService().updateStopValidationOffre(this.currentOffre.getIdOffre(), getSessionController().getCurrentLogin());
addInfoMessage(null, "OFFRE.GESTION.STOPDIFFUSION.CONFIRMATION");
//Màj de l'objet courant
this.currentOffre.setDateDiffusion(null);
this.currentOffre.setDateFinDiffusion(null);
this.currentOffre.setEstDiffusee(false);
this.currentOffre.setEstValidee(false);
this.currentOffre.setEtatValidation(0);
//Maj listes
if(this.listeOffres!=null && ((ArrayList<OffreDTO>)this.listeOffres).contains(this.currentOffre)){
this.listeOffres.set(this.listeOffres.indexOf(this.currentOffre), this.currentOffre);
}
if(this.resultatsRechercheOffre!=null && ((ArrayList<OffreDTO>)this.resultatsRechercheOffre).contains(this.currentOffre)){
this.resultatsRechercheOffre.set(this.resultatsRechercheOffre.indexOf(this.currentOffre), this.currentOffre);
checkListeResultats();
}
}catch (DataUpdateException|WebServiceDataBaseException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.GESTION.STOPDIFFUSION.ERREUR");
}
}
// return ret;
}
/**
* Indiquer l'offre comme pourvue
*/
public void offrePourvue(){
getSessionController().setOffrePourvueCurrentPage("_confirmationDialog");
if(this.currentOffre!=null){
try{
getOffreDomainService().updateOffrePourvue(this.currentOffre.getIdOffre(), !this.currentOffre.isEstPourvue());
getOffreDomainService().updateStopDiffusionOffre(this.currentOffre.getIdOffre(), getSessionController().getCurrentLogin());
//M�j de l'objet courant
this.currentOffre.setEstPourvue(!this.currentOffre.isEstPourvue());
this.currentOffre.setDateDiffusion(null);
this.currentOffre.setDateFinDiffusion(null);
this.currentOffre.setEstDiffusee(false);
this.currentOffre.setEstValidee(false);
this.currentOffre.setEtatValidation(0);
//Maj listes
if(this.listeOffres!=null && ((ArrayList<OffreDTO>)this.listeOffres).contains(this.currentOffre)){
this.listeOffres.set(this.listeOffres.indexOf(this.currentOffre), this.currentOffre);
}
if(this.resultatsRechercheOffre!=null && ((ArrayList<OffreDTO>)this.resultatsRechercheOffre).contains(this.currentOffre)){
this.resultatsRechercheOffre.set(this.resultatsRechercheOffre.indexOf(this.currentOffre), this.currentOffre);
checkListeResultats();
}
if(this.currentOffre.isEstPourvue())addInfoMessage(null, "OFFRE.GESTION.POURVOIROFFRE.CONFIRMATION");
if(!this.currentOffre.isEstPourvue())addInfoMessage(null, "OFFRE.GESTION.POURVOIROFFRE.CONFIRMATIONNON");
}catch (DataUpdateException|WebServiceDataBaseException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.GESTION.POURVOIROFFRE.ERREUR");
}
}
// return ret;
}
/**
* @return int : nombre d'éléments dans la liste offresDiffusion du currentOffre
*/
public int getCurrentOffreSizeOffresDiffusion(){
currentOffreSizeOffresDiffusion = 0;
if(this.currentOffre!=null && this.currentOffre.getOffresDiffusion()!=null){
currentOffreSizeOffresDiffusion=this.currentOffre.getOffresDiffusion().size();
}
return currentOffreSizeOffresDiffusion;
}
/**
* @param l
* @param id
* @return SelectItem
*/
public SelectItem containsSelectItem(List<SelectItem> l, int id){
if(l!=null && !l.isEmpty()){
for(SelectItem si : l){
if(si.getValue() instanceof Integer){
if((Integer)(si.getValue())==id){
return si;
}
}
}
}
return null;
}
/**
* Maj des listes pour le panel de diffusion
*/
public void majListesCentresDiffusion(){
if(this.currentOffre!=null){
this.dualListCiblageCentres = new DualListModel<>(new ArrayList<CentreGestionDTO>(),new ArrayList<CentreGestionDTO>());
if(this.currentOffre.getOffresDiffusion()!=null && !this.currentOffre.getOffresDiffusion().isEmpty()){
for(OffreDiffusionDTO od : this.currentOffre.getOffresDiffusion()){
this.dualListCiblageCentres.getTarget().add(getCentreGestionDomainService().getCentreGestion(od.getIdCentreGestion()));
}
}
if(this.listesCentresGestionEtablissement==null || this.listesCentresGestionEtablissement.isEmpty()){
getListesCentresGestionEtablissement();
}
if(!this.listesCentresGestionEtablissement.isEmpty()){
int id =(Integer) this.listesCentresGestionEtablissement.get(0).getValue();
this.idCentreEtablissementSelect=id;
if(this.listesCentresGestionEtablissement.size()>1){
id=(Integer) this.listesCentresGestionEtablissement.get(1).getValue();
if(id>0){
this.idCentreEtablissementSelect=id;
}
}
if(id>0){
List<CentreGestionDTO> l = getCentreGestionDomainService().getCentreGestionList(
getSessionController().getCodeUniversite());
if(l!=null && !l.isEmpty()){
this.dualListCiblageCentres.setSource(new ArrayList<CentreGestionDTO>());
for(CentreGestionDTO cg : l){
if(cg.getIdCentreGestion()!=id){
// Si la liste des centres selectionnes ne contient pas le centre, on l'ajoute a la liste proposee
if(!this.dualListCiblageCentres.getTarget().contains(cg)){
this.dualListCiblageCentres.getSource().add(cg);
}
}
}
}
}
}
}
}
/**
* Action de diffusion de l'offre aux centres sélectionnés
*/
public void diffusionCentreOffre(){
getSessionController().setDiffusionCentreOffreCurrentPage("_confirmationDialog");
if(this.currentOffre!=null){
if(this.idCentreEtablissementSelect==0 || this.dualListCiblageCentres.getTarget()==null
|| this.dualListCiblageCentres.getTarget().isEmpty()){
try{
if(getOffreDomainService().deleteOffreDiffusionFromId(this.currentOffre.getIdOffre())){
this.currentOffre.setOffresDiffusion(null);
addInfoMessage(null, "OFFRE.GESTION.DIFFUSIONCENTRE.CONFIRMATION");
}
}catch (DataDeleteException|WebServiceDataBaseException|DataAddException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.GESTION.DIFFUSIONCENTRE.ERREUR");
}
} else if(this.dualListCiblageCentres.getTarget()!=null
&& !this.dualListCiblageCentres.getTarget().isEmpty()){
List<OffreDiffusionDTO> l = new ArrayList<OffreDiffusionDTO>();
for(CentreGestionDTO centre : this.dualListCiblageCentres.getTarget()){
OffreDiffusionDTO od = new OffreDiffusionDTO();
od.setIdCentreGestion(centre.getIdCentreGestion());
od.setIdOffre(this.currentOffre.getIdOffre());
od.setNomCentre(centre.getNomCentre());
l.add(od);
}
this.currentOffre.setOffresDiffusion(l);
try{
getOffreDomainService().addOffreDiffusion(l);
addInfoMessage(null, "OFFRE.GESTION.DIFFUSIONCENTRE.CONFIRMATION");
}catch (DataDeleteException|WebServiceDataBaseException|DataAddException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.GESTION.DIFFUSIONCENTRE.ERREUR");
}
}
}
}
/**
* Transfert d'une offre au centre entreprise avec contacts
* @return String
*/
public void transfererOffre(){
getSessionController().setTransfertOffreCurrentPage("_confirmationDialog");
if(this.currentOffre!=null){
try{
CentreGestionDTO cgEntr = getCentreGestionDomainService().getCentreEntreprise();
if(cgEntr!=null){
this.currentOffre.setIdCentreGestion(cgEntr.getIdCentreGestion());
this.currentOffre.setCentreGestion(cgEntr);
getOffreDomainService().updateOffre(this.currentOffre);
if(this.currentOffre.getIdContactCand()>0){
if(this.currentOffre.getContactCand()!=null){
this.currentOffre.getContactCand().setIdCentreGestion(cgEntr.getIdCentreGestion());
getStructureDomainService().updateContact(this.currentOffre.getContactCand());
}
}
if(this.currentOffre.getIdContactInfo()>0){
if(this.currentOffre.getContactInfo()!=null){
this.currentOffre.getContactInfo().setIdCentreGestion(cgEntr.getIdCentreGestion());
getStructureDomainService().updateContact(this.currentOffre.getContactInfo());
}
}
}
addInfoMessage(null, "OFFRE.GESTION.TRANSFERT.CONFIRMATION");
}catch (DataUpdateException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.GESTION.TRANSFERT.ERREUR");
}catch (WebServiceDataBaseException e) {
logger.error(e);
addErrorMessage(null, "OFFRE.GESTION.TRANSFERT.ERREUR");
}catch (Exception e) {
logger.error(e);
addErrorMessage(null, "OFFRE.GESTION.TRANSFERT.ERREUR");
}
}
// return ret;
}
/**
* Page de retour lors de la modif ou suppression
* @return String
*/
public String retourTo(){
return getRetour();
}
/**
* Vers moteur de recherche offre (entreprise)
* @return String
*/
public String goToRechercheOffre(){
String ret="rechercheOffre";
if(this.critereRechercheOffre==null) this.critereRechercheOffre=initCritereRechercheOffre();
return ret;
}
/**
* Vers moteur de recherche offre (stage)
* @return String
*/
public String goToRechercheOffreStage(){
String ret="rechercheOffreStage";
if(this.critereRechercheOffre==null)this.critereRechercheOffre=initCritereRechercheOffre();
// resetRechercheOffre();
return ret;
}
/**
* Vers moteur de recherche offre public (entreprise)
* @return String
*/
public String goToRechercheOffrePublic(){
String ret="rechercheOffrePublic";
if(this.critereRechercheOffre==null)this.critereRechercheOffre=initCritereRechercheOffre();
return ret;
}
/**
* initCritereRechercheOffre
* @return CritereRechercheOffreDTO
*/
public CritereRechercheOffreDTO initCritereRechercheOffre(){
CritereRechercheOffreDTO c;
c = new CritereRechercheOffreDTO();
c.setLieuPays(null);
return c;
}
/**
* @return String
*/
public String rechercherOffrePublic(){
String ret;
if(this.critereRechercheOffre==null) this.critereRechercheOffre=initCritereRechercheOffre();
if(getSessionController().getCurrentCentresGestion()==null
|| getSessionController().getCurrentCentresGestion().isEmpty()){
CentreGestionDTO cgEntr=getCentreGestionDomainService().getCentreEntreprise();
ArrayList<CentreGestionDTO> lcg = new ArrayList<CentreGestionDTO>();
lcg.add(cgEntr);
getSessionController().setCurrentCentresGestion(lcg);
}
ret=rechercherOffre();
return ret;
}
/**
* Recherche des offres
* @return String
*/
public String rechercherOffre(){
String ret="resultatsRechercheOffre";
// Si on est partie entreprise
if (getSessionController().isAdminPageAuthorized()){
List<CentreGestionDTO> l = getCentreGestionDomainService().getCentreFromUid(getSessionController().getCurrentAuthAdminStructure().getLogin(),
getSessionController().getCodeUniversite());
l.add(getCentreGestionDomainService().getCentreEntreprise());
getSessionController().setCurrentCentresGestion(l);
}
List<Integer> idCG = getSessionController().getCurrentIdsCentresGestion();
if (idCG == null) idCG = new ArrayList<>();
boolean trouveCGEtab = false;
// if(getSessionController().getCurrentAuthEtudiant()!=null){
CentreGestionDTO cgEtab = getCentreGestionDomainService().getCentreEtablissement(getSessionController().getCodeUniversite());
if(cgEtab!=null && cgEtab.getIdCentreGestion()>0){
if (!idCG.isEmpty()){
for (Integer intCG : idCG) {
if (intCG.equals(cgEtab.getIdCentreGestion())) {
trouveCGEtab = true;
}
}
}
if (!trouveCGEtab) {
idCG.add(cgEtab.getIdCentreGestion());
}
}
// }
this.critereRechercheOffre.setIdsCentreGestion(idCG);
if(StringUtils.hasText(this.rechTypeOuContrat)){
if(this.rechTypeOuContrat.contains("t")){
if(Utils.isNumber(this.rechTypeOuContrat.substring(1))){
this.critereRechercheOffre.setTypeOffre(getNomenclatureDomainService().getTypeOffreFromId(
Utils.convertStringToInt(this.rechTypeOuContrat.substring(1))));
this.critereRechercheOffre.setContratOffre(null);
}
}
if(this.rechTypeOuContrat.contains("c")){
if(Utils.isNumber(this.rechTypeOuContrat.substring(1))){
this.critereRechercheOffre.setContratOffre(getNomenclatureDomainService().getContratOffreFromId(
Utils.convertStringToInt(this.rechTypeOuContrat.substring(1))));
if(this.critereRechercheOffre.getContratOffre()!=null &&
this.critereRechercheOffre.getContratOffre().getIdParent()>0){
this.critereRechercheOffre.setTypeOffre(getNomenclatureDomainService().getTypeOffreFromId(
this.critereRechercheOffre.getContratOffre().getIdParent()));
}
}
}
}else{
this.critereRechercheOffre.setTypeOffre(null);
this.critereRechercheOffre.setContratOffre(null);
}
if(this.critereRechercheOffre.isEstPrioERQTH()){
this.critereRechercheOffre.setEstAccessERQTH(false);
}
if(getSessionController().isPageAuthorized() || getSessionController().isAdminPageAuthorized()){
this.critereRechercheOffre.setInclureOffresEntreprise(true);
}
this.critereRechercheOffre.setEstFrance(false);
if(this.critereRechercheOffre.getLieuPays()!=null
&& this.critereRechercheOffre.getLieuPays().getId()!=0
&& getBeanUtils()!=null
&& getBeanUtils().isFranceRecherche(this.critereRechercheOffre.getLieuPays())){
this.critereRechercheOffre.setLieuPays(getBeanUtils().getFrance());
if (getBeanUtils().isFranceRecherche(this.critereRechercheOffre.getLieuPays())) {
this.critereRechercheOffre.setEstFrance(true);
}
}
this.resultatsRechercheOffre = getOffreDomainService().getOffresFromCriteres(this.critereRechercheOffre);
if(!checkListeResultats()){
ret=null;
}
return ret;
}
/**
* Passage du moteur simple à avancé et vice-versa
*/
public void rechercheSimpleAvancee(){
if(this.rechercheAvancee) {
this.rechercheAvancee = false;
} else {
this.rechercheAvancee=true;
}
resetRechercheOffre();
}
/**
* Reset des criteres de recherche d'offres
*/
public void resetRechercheOffre(){
this.critereRechercheOffre=initCritereRechercheOffre();
this.rechTypeOuContrat=null;
}
/**
* Re-chargement du paginator
*/
public void reloadRechercheOffrePaginator(){
this.rechercheOffrePaginator.reset();
this.rechercheOffrePaginator.setListe(this.resultatsRechercheOffre);
this.rechercheOffrePaginator.forceReload();
}
/**
* Contrôle la liste des résultats
* @return boolean : vrai si resultats
*/
private boolean checkListeResultats(){
boolean ret=true;
if(this.resultatsRechercheOffre==null || this.resultatsRechercheOffre.isEmpty()){
this.resultatsRechercheOffre=null;
ret=false;
addInfoMessage("formRechOffre", "RECHERCHEOFFRE.AUCUNRESULTAT");
}else if(this.resultatsRechercheOffre!=null && !this.resultatsRechercheOffre.isEmpty()){
reloadRechercheOffrePaginator();
}
return ret;
}
/**
* @return String
*/
public String goToRecapitulatifOffrePostCreation(){
if ("creationOffre".equalsIgnoreCase(this.creationOffre)){
return this.goToRecapitulatifOffre();
} else if ("creationCentreEtabOffre".equalsIgnoreCase(this.creationOffre)){
return this.goToRecapitulatifOffreFromOffreLightAvecCentre();
} else {
return null;
}
}
/**
* @return String
*/
public String goToRecapitulatifOffre(){
String ret=null;
if(this.currentOffre!=null){
ret="recapitulatifOffre";
this.currentRecapOffre = "offre";
this.currentOffre.setOffresDiffusion(getOffreDomainService().getOffreDiffusionFromIdOffre(this.currentOffre.getIdOffre()));
}
return ret;
}
/**
* @return String
*/
public String goToRecapitulatifOffreFromOffreLight(){
String ret=null;
if(this.currentOffre!=null){
this.currentOffre=getOffreDomainService().getOffreFromId(this.currentOffre.getIdOffre());
this.currentOffre.setStructure(getStructureDomainService().getStructureFromId(this.currentOffre.getIdStructure()));
this.currentOffre.setOffresDiffusion(getOffreDomainService().getOffreDiffusionFromIdOffre(this.currentOffre.getIdOffre()));
ret="recapitulatifOffreEtab";
this.currentRecapOffre = "offreEtab";
}
return ret;
}
/**
* @return String
*/
public String goToRecapitulatifOffreFromOffreLightAvecCentre(){
String ret=null;
if(this.currentOffre!=null){
this.currentOffre=getOffreDomainService().getOffreFromId(this.currentOffre.getIdOffre());
this.currentOffre.setStructure(getStructureDomainService().getStructureFromId(this.currentOffre.getIdStructure()));
getSessionController().setCurrentManageStructure(this.currentOffre.getStructure());
this.etablissementController.loadContactsServices();
this.currentOffre.setOffresDiffusion(getOffreDomainService().getOffreDiffusionFromIdOffre(this.currentOffre.getIdOffre()));
this.majListesCentresDiffusion();
// Assignation du centre de l'offre
if(!isListeCurrentIdsCentresGestionContainsIdCGCurrentOffre()){
CentreGestionDTO c = getCentreGestionDomainService().getCentreGestion(this.currentOffre.getIdCentreGestion());
if(c!=null)this.currentOffre.setCentreGestion(c);
else return ret;
}else{
if(getSessionController().getCurrentIdsCentresGestion()!=null &&
!getSessionController().getCurrentIdsCentresGestion().isEmpty()){
for(CentreGestionDTO c : getSessionController().getCurrentCentresGestion()){
if(c.getIdCentreGestion()==this.currentOffre.getIdCentreGestion()){
this.currentOffre.setCentreGestion(c);
break;
}
}
}
}
ret="recapitulatifOffreEtabCentre";
this.currentRecapOffre = "offreEtabCentre";
}
return ret;
}
/**
* @return String
*/
public String goToRecapitulatifOffrePublic(){
String ret=null;
if(this.currentOffre!=null){
this.currentOffre=getOffreDomainService().getOffreFromId(this.currentOffre.getIdOffre());
this.currentOffre.setStructure(getStructureDomainService().getStructureFromId(this.currentOffre.getIdStructure()));
this.etablissementController.loadContactsServices();
this.currentOffre.setOffresDiffusion(getOffreDomainService().getOffreDiffusionFromIdOffre(this.currentOffre.getIdOffre()));
ret="recapitulatifOffreEtab";
this.currentRecapOffre = "offreEtab";
}
return ret;
}
/**
* @param idOffre
* @return String
*/
public String goToOffreEtudiant(Integer idOffre){
String ret="recapitulatifOffreEtab";
this.currentRecapOffre = "offreEtab";
this.currentOffre=null;
OffreDTO oTmp=getOffreDomainService().getOffreFromId(idOffre);
if(oTmp!=null){
CentreGestionDTO cgEntr = getCentreGestionDomainService().getCentreEntreprise();
if(getSessionController().getCurrentIdsCentresGestion()==null){
getSessionController().setCurrentCentresGestion(new ArrayList<CentreGestionDTO>());
getSessionController().getCurrentCentresGestion().add(cgEntr);
}else if(!getSessionController().getCurrentIdsCentresGestion().contains(cgEntr.getIdCentreGestion())){
getSessionController().getCurrentCentresGestion().add(cgEntr);
}
if(getSessionController().getCurrentIdsCentresGestion()!=null
&& getSessionController().getCurrentIdsCentresGestion().contains(oTmp.getIdCentreGestion())){
this.currentOffre=oTmp;
goToRecapitulatifOffreFromOffreLight();
}
}
return ret;
}
/**
* @param idOffreC
* @return String
*/
public String goToOffreEtudiantAvecCentre(Integer idOffreC){
String ret="recapitulatifOffreEtabCentre";
this.currentRecapOffre = "offreEtabCentre";
this.currentOffre=null;
OffreDTO oTmp=getOffreDomainService().getOffreFromId(idOffreC);
if(oTmp!=null){
CentreGestionDTO cgEntr = getCentreGestionDomainService().getCentreEntreprise();
if(getSessionController().getCurrentIdsCentresGestion()==null){
getSessionController().setCurrentCentresGestion(new ArrayList<CentreGestionDTO>());
getSessionController().getCurrentCentresGestion().add(cgEntr);
}else if(!getSessionController().getCurrentIdsCentresGestion().contains(cgEntr.getIdCentreGestion())){
getSessionController().getCurrentCentresGestion().add(cgEntr);
}
if(getSessionController().getCurrentIdsCentresGestion()!=null
&& getSessionController().getCurrentIdsCentresGestion().contains(oTmp.getIdCentreGestion())){
this.currentOffre=getOffreDomainService().getOffreFromId(idOffreC);
goToRecapitulatifOffreFromOffreLightAvecCentre();
}
}
return ret;
}
/**
* @return String
*/
public String goToDetailsOffre(){
return "detailsOffre";
}
/* ***************************************************************
*
****************************************************************/
/**
* Upload du Fichier
*/
public void uploadFileOffre(FileUploadEvent event){
if(logger.isDebugEnabled()){
logger.debug("public String uploadLogoCentre() ");
}
FileUploadBean fileUlBean = getSessionController().getOffreFileUploadBean();
// On met le prefix a -1 sinon '0_' est ajouté au nom
fileUlBean.setPrefix(-1);
// Methode s'occupant de l'upload du fichier
fileUlBean.fileUploadListener(event);
// Recuperation du nom final du fichier
String nomFichier = fileUlBean.getNameUploadedFile();
String nomReel = fileUlBean.getRealNameFile();
//Si nom de fichier non vide (cas des fichiers volumineux)
if(StringUtils.hasText(nomFichier)){
FichierDTO f = new FichierDTO();
f.setNomFichier(nomFichier);
if(StringUtils.hasText(nomReel)){
f.setNomReel(nomReel);
} else {
f.setNomReel("");
}
try {
int idFichier = getOffreDomainService().addFichier(f);
// Maintenant que l'upload s'est bien passé et que l'on a pu inserer le fichier en base,
// on recupere le last insert id pour l'assigner a l'offre qui n'est pas encore creee donc
// pas besoin d'update
f.setIdFichier(idFichier);
this.formOffre.setFichier(f);
this.formOffre.setIdFichier(idFichier);
// Pour que le fichier puisse etre recup par getFileServlet, il faut le prefixer de l'idFichier,
// On le recupere donc pour le renommer
String directory = getSessionController().getUploadFilesOffresPath()+ File.separator;
File fichier = new File(directory + f.getNomFichier());
boolean b = fichier.renameTo(new File(directory+ idFichier +"_"+f.getNomFichier()));
if (b == false){
addErrorMessage("panelUpload","Erreur lors de la tentative de renommage du fichier.");
}
} catch (DataAddException e) {
logger.error(e);
addErrorMessage("panelUpload",e.getMessage());
} catch (DataUpdateException e) {
logger.error(e);
addErrorMessage("panelUpload",e.getMessage());
} catch (WebServiceDataBaseException e) {
logger.error(e);
addErrorMessage("panelUpload",e.getMessage());
}
}
}
/**
* Action appellée après l'upload d'un fichier
*/
public void insertUploadedFile(){
String nomFichier = getSessionController().getOffreFileUploadBean().getNameUploadedFile();
String nomReel = getSessionController().getOffreFileUploadBean().getRealNameFile();
//Si nom de fichier non vide (cas des fichiers volumineux)
if(StringUtils.hasText(nomFichier)){
this.formOffre.getFichier().setNomFichier(nomFichier);
if(StringUtils.hasText(nomReel)){
this.formOffre.getFichier().setNomReel(nomReel);
}
try {
getOffreDomainService().updateFichier(this.formOffre.getFichier());
} catch (DataAddException|WebServiceDataBaseException e) {
logger.error(e);
}
this.formOffre.setIdFichier(this.formOffre.getFichier().getIdFichier());
}
}
/**
* Suppression du fichier actuellement uploadé
*/
public void deleteUploadedFile(){
if(this.formOffre.getIdFichier() > 0 ){
try{
if(this.formOffre.getFichier()!=null
&& StringUtils.hasText(this.formOffre.getFichier().getNomFichier())){
getSessionController().getOffreFileUploadBean().deleteFileFromDirectory(
this.formOffre.getIdFichier(), this.formOffre.getFichier().getNomFichier());
}
getOffreDomainService().deleteFichier(this.formOffre.getIdFichier());
}catch (DataDeleteException|WebServiceDataBaseException e) {
logger.error(e);
}
}
this.formOffre.setFichier(null);
this.formOffre.setIdFichier(0);
this.formOffre.setAvecFichier(false);
}
/**
* Mise à jour de la FapN3 en fonction de la QualificationSimplifiee selectionnée
* @param event
*/
public void valueFapQualificationSimplifieeChanged(ValueChangeEvent event){
if(event.getNewValue() instanceof FapQualificationSimplifieeDTO){
FapQualificationSimplifieeDTO f = (FapQualificationSimplifieeDTO)event.getNewValue();
this.fapN3Listening=getFapN3FromNumQualif(f.getId());
}else{
this.fapN3Listening=null;
}
}
/**
* @param num
* @return List<SelectItem>
*/
public List<SelectItem> getFapN3FromNumQualif(int num){
List<SelectItem> ls = null;
List<FapN3DTO> l = getNomenclatureDomainService().getFapN3FromNumQualifSimplifiee(num);
if(l!=null && !l.isEmpty()){
ls = new ArrayList<SelectItem>();
for(FapN3DTO o : l){
ls.add(new SelectItem(o,o.getLibelle()));
}
}
return ls;
}
/** Formulaire offre
* @param event
*/
public void formOffreValueCodePostalChanged(ValueChangeEvent event){
String s = (String)event.getNewValue();
if(getSessionController().isRecupererCommunesDepuisApogee()){
List<SelectItem> lTmp = majCommunes(s);
if(lTmp!=null && !lTmp.isEmpty()){
this.formOffreCommunesListening=lTmp;
}else{
this.formOffreCommunesListening=new ArrayList<SelectItem>();
addErrorMessage("formCreationOffre:dynaCodePostal", "STRUCTURE.CODE_POSTAL.VALIDATION");
}
}
}
/**
* @param codePostal
* @return List<SelectItem>
*/
public List<SelectItem> majCommunes(String codePostal){
List<SelectItem> l = null;
if(codePostal.length()==5){
List<CommuneDTO> ls = getGeographieRepositoryDomain().getCommuneFromDepartement(codePostal);
if(ls!=null){
l = new ArrayList<SelectItem>();
for(CommuneDTO c : ls){
l.add(new SelectItem(c.getCodeCommune(),c.getLibCommune()));
}
}
}
return l;
}
/**
* @param event
*/
public void valueCentreEtablissementChanged(ValueChangeEvent event){
if(event.getNewValue() instanceof Integer){
if(this.listesCentresGestionEtablissement!=null && this.listesCGEtab!=null
&& !this.listesCentresGestionEtablissement.isEmpty()
&& !this.listesCGEtab.isEmpty()){
int idCTmp = (Integer) event.getNewValue();
if(idCTmp>0){
CentreGestionDTO cTmp = new CentreGestionDTO();
cTmp.setIdCentreGestion(idCTmp);
CentreGestionDTO c = this.listesCGEtab.get(
this.listesCGEtab.indexOf(cTmp));
List<CentreGestionDTO> l = getCentreGestionDomainService().getCentreGestionList(c.getCodeUniversite());
if(l!=null && !l.isEmpty()){
this.dualListCiblageCentres.setSource(new ArrayList<CentreGestionDTO>());
for(CentreGestionDTO cg : l){
if(!cg.equals(cTmp)){
this.dualListCiblageCentres.getSource().add(cg);
}
}
}else{
this.dualListCiblageCentres.setSource(new ArrayList<CentreGestionDTO>());
}
}else{
this.dualListCiblageCentres.setSource(new ArrayList<CentreGestionDTO>());
}
}
}else{
this.dualListCiblageCentres.setSource(new ArrayList<CentreGestionDTO>());
}
}
/**
* Utilisé en etape 3 d'une offre
* @return boolean
*/
public boolean isFormOffreContainModeCourrier(){
return isOffreContainMode(getBeanUtils().getModeCourrier(), this.formOffre);
}
/**
* Utilisé en etape 3 d'une offre
* @return boolean
*/
public boolean isFormOffreContainModeTelephone(){
return isOffreContainMode(getBeanUtils().getModeTelephone(), this.formOffre);
}
/**
* Utilisé en etape 3 d'une offre
* @return boolean
*/
public boolean isFormOffreContainModeMail(){
return isOffreContainMode(getBeanUtils().getModeMail(), this.formOffre);
}
/**
* Utilisé dans le recap d'une offre
* @return boolean
*/
public boolean isCurrentOffreContainModeCourrier(){
return isOffreContainMode(getBeanUtils().getModeCourrier(), this.currentOffre);
}
/**
* Utilisé dans le recap d'une offre
* @return boolean
*/
public boolean isCurrentOffreContainModeTelephone(){
return isOffreContainMode(getBeanUtils().getModeTelephone(), this.currentOffre);
}
/**
* Utilisé dans le recap d'une offre
* @return boolean
*/
public boolean isCurrentOffreContainModeMail(){
return isOffreContainMode(getBeanUtils().getModeMail(), this.currentOffre);
}
/**
* @param mc
* @param o
* @return boolean
*/
public boolean isOffreContainMode(ModeCandidatureDTO mc, OffreDTO o){
boolean ret=false;
if(o!=null){
if(o.getModesCandidature()!=null &&
!o.getModesCandidature().isEmpty()){
for(ModeCandidatureDTO m : o.getModesCandidature()){
if(m.equals(mc)){
ret=true;
break;
}
}
}
}
return ret;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getClass().getSimpleName() + "#" + hashCode();
}
/**
* @see org.esupportail.pstage.web.controllers.AbstractDomainAwareBean#reset()
*/
@Override
public void reset() {
super.reset();
}
/* ****************************************************************************
* DEPOT ANONYME
*****************************************************************************/
private String codeAccesDepotAnonyme;
private String urlAccesDepotAnonyme;
public String getCodeAccesDepotAnonyme() {
return codeAccesDepotAnonyme;
}
public void setCodeAccesDepotAnonyme(String codeAccesDepotAnonyme) {
this.codeAccesDepotAnonyme = codeAccesDepotAnonyme;
}
public String getUrlAccesDepotAnonyme() {
return urlAccesDepotAnonyme;
}
public void setUrlAccesDepotAnonyme(String urlAccesDepotAnonyme) {
this.urlAccesDepotAnonyme = urlAccesDepotAnonyme;
}
/**
* code d'acces au depot anonyme pour une entreprise
*/
public void genererUrlDepotAnonyme() {
// chiffrage de l'id de la convention via blowfish
String idEncode = getBlowfishUtils().encode(
"" + getCentreGestionDomainService().getCentreEntreprise().getIdCentreGestion());
this.urlAccesDepotAnonyme = getSessionController().getBaseUrl()
+ "/stylesheets/depotAnonyme/welcome.xhtml" + "?id="
+ idEncode;
}
/**
* Envoi vers l'enchainement de creation d'offre anonyme
* @return String
*/
public String goToDepotAnonyme(){
String ret=null;
this.centreGestionDepotAnonyme = getCentreGestionDomainService().getCentreEntreprise();
if (this.centreGestionDepotAnonyme != null) {
int idDecode = Utils.convertStringToInt(getBlowfishUtils().decode(this.codeAccesDepotAnonyme));
if(idDecode == this.centreGestionDepotAnonyme.getIdCentreGestion()){
this.formOffre=new OffreDTO();
this.formOffre.setIdCentreGestion(idDecode);
ret = "creationOffreAnon";
this.creationOffre = "creationOffreAnon";
getSessionController().setCreationOffreStageCurrentPage("_creationOffreEtape02Etab");
} else {
addErrorMessage("formAccueilDepotAnon","DEPOTANONYME.UNAUTHORIZED");
}
} else {
addErrorMessage("formAccueilDepotAnon","DEPOTANONYME.CENTRE_ENTR_VIDE");
}
return ret;
}
/**
* @return String
*/
public String editPdfOffre() {
String ret = null;
try {
/**
** Methodes de creation des documents PDF selon l'edition demandee
**/
String nomDocxsl;
String fileNameXml;
String fileNameXmlfin = ".xml";
OffreDTO offreEdit = this.currentOffre;
String description;
String competences;
String observations;
String commentaires;
if (offreEdit != null) {
if (offreEdit.getDescription() !=null) {
if (StringUtils.hasText(offreEdit.getDescription())) {
description = Utils.replaceHTML(offreEdit.getDescription());
offreEdit.setDescription(description);
}
}
if (offreEdit.getCompetences() != null) {
if (StringUtils.hasText(offreEdit.getCompetences())) {
competences = Utils.replaceHTML(offreEdit.getCompetences());
offreEdit.setCompetences(competences);
}
}
if (offreEdit.getCommentaireTempsTravail() != null) {
if (StringUtils.hasText(offreEdit.getCommentaireTempsTravail())) {
commentaires = Utils.replaceHTML(offreEdit.getCommentaireTempsTravail());
offreEdit.setCommentaireTempsTravail(commentaires);
}
}
if (offreEdit.getObservations() != null) {
if (StringUtils.hasText(offreEdit.getObservations())) {
observations = Utils.replaceHTML(offreEdit.getObservations());
offreEdit.setObservations(observations);
}
}
String idOffre = Integer.toString(offreEdit.getIdOffre());
nomDocxsl = "offre" + ".xsl";
fileNameXml = "offre_" + idOffre;
// appel castor pour fichier xml a partir de objet java convention
castorService.objectToFileXml(offreEdit, fileNameXml + fileNameXmlfin);
//fusion du xsl et xml en pdf
String fileNamePdf = fileNameXml + ".pdf";
PDFUtils.exportPDF(fileNameXml + fileNameXmlfin, FacesContext.getCurrentInstance(),
castorService.getXslXmlPath(),
fileNamePdf, nomDocxsl);
addInfoMessage(null, "CONVENTION.IMPRESSION.RECAP.CONFIRMATION");
}
} catch (ExportException e) {
logger.error("editPdfRecap ", e);
addErrorMessage(null, "CONVENTION.EDIT.RECAP.ERREUR", e.getMessage());
}
return ret;
}
/**
* @return String
*/
public String goToOffreADiffuser(){
this.critereRechercheOffre=initCritereRechercheOffre();
this.critereRechercheOffre.setEstDiffusee(false);
String s = this.rechercherOffre();
if(s != null) return s;
FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(true);
return "rechercheOffreStage";
}
/**
* event lors du choix d'une Offre côté stage menant à la page recapitulatifOffreCentre
*/
public void onOffreSelect(SelectEvent event) {
String retour = this.goToRecapitulatifOffreFromOffreLightAvecCentre();
try {
if (retour != null) {
FacesContext.getCurrentInstance().getExternalContext().redirect("recapitulatifOffreCentre.xhtml");
}
} catch (IOException ioe){
logger.error("Erreur lors de la tentative de redirection de page.", ioe);
addErrorMessage(null, "Erreur lors de la tentative de redirection de page.");
}
}
/**
* event lors du choix d'une Offre côté stage menant à la page recapitulatifOffreEtabCentre
*/
public void onOffreEtabSelect(SelectEvent event) {
String retour = this.goToRecapitulatifOffreFromOffreLightAvecCentre();
try {
if (retour != null) {
FacesContext.getCurrentInstance().getExternalContext().redirect("recapitulatifOffreEtabCentre.xhtml");
}
} catch (IOException ioe){
logger.error("Erreur lors de la tentative de redirection de page.", ioe);
addErrorMessage(null, "Erreur lors de la tentative de redirection de page.");
}
}
/**
* event lors du choix d'une Offre côté depot menant à la page recapitulatifOffreEtab
*/
public void onOffreEtabDepotSelect(SelectEvent event) {
String retour = this.goToRecapitulatifOffreFromOffreLight();
try {
if (retour != null) {
FacesContext.getCurrentInstance().getExternalContext().redirect("recapitulatifOffreEtab.xhtml");
}
} catch (IOException ioe){
logger.error("Erreur lors de la tentative de redirection de page.", ioe);
addErrorMessage(null, "Erreur lors de la tentative de redirection de page.");
}
}
/**
* event lors du choix d'une Offre côté depot menant à la page recapitulatifOffreEtabCentre
*/
public void onOffreDepotSelect(SelectEvent event) {
this.retour = "recapitulatifOffre";
String retour = this.goToRecapitulatifOffre();
try {
if (retour != null) {
FacesContext.getCurrentInstance().getExternalContext().redirect("recapitulatifOffre.xhtml");
}
} catch (IOException ioe){
logger.error("Erreur lors de la tentative de redirection de page.", ioe);
addErrorMessage(null, "Erreur lors de la tentative de redirection de page.");
}
}
/**
* event lors du choix d'un établissement dans l'enchainement de création d'offre
*/
public void onCreaOffreEtabSelect(SelectEvent event) {
this.goToCreationOffreDetailsEtab();
try {
if (this.creationOffre.equalsIgnoreCase("creationOffreAnon")){
FacesContext.getCurrentInstance().getExternalContext().redirect(getSessionController().getBaseUrl()+"/stylesheets/depotAnonyme/creationOffreAnon.xhtml");
} else {
FacesContext.getCurrentInstance().getExternalContext().redirect("creationCentreEtabOffre.xhtml");
}
} catch (IOException ioe){
logger.error("Erreur lors de la tentative de redirection de page.", ioe);
addErrorMessage(null, "Erreur lors de la tentative de redirection de page.");
}
}
/* ***************************************************************
* Getters / Setters
****************************************************************/
/**
* @return the formOffre
*/
public OffreDTO getFormOffre() {
return formOffre;
}
/**
* @param formOffre the formOffre to set
*/
public void setFormOffre(OffreDTO formOffre) {
this.formOffre = formOffre;
}
/**
* @return the contratsListening
*/
public List<SelectItem> getContratsListening() {
return contratsListening;
}
/**
* @param contratsListening the contratsListening to set
*/
public void setContratsListening(List<SelectItem> contratsListening) {
this.contratsListening = contratsListening;
}
/**
* @return the fapN3Listening
*/
public List<SelectItem> getFapN3Listening() {
return fapN3Listening;
}
/**
* @param fapN3Listening the fapN3Listening to set
*/
public void setFapN3Listening(List<SelectItem> fapN3Listening) {
this.fapN3Listening = fapN3Listening;
}
/**
* @return the formOffreCommunesListening
*/
public List<SelectItem> getFormOffreCommunesListening() {
return formOffreCommunesListening;
}
/**
* @param formOffreCommunesListening the formOffreCommunesListening to set
*/
public void setFormOffreCommunesListening(
List<SelectItem> formOffreCommunesListening) {
this.formOffreCommunesListening = formOffreCommunesListening;
}
/**
* @return the avecFichierOuLien
*/
public boolean isAvecFichierOuLien() {
return avecFichierOuLien;
}
/**
* @param avecFichierOuLien the avecFichierOuLien to set
*/
public void setAvecFichierOuLien(boolean avecFichierOuLien) {
this.avecFichierOuLien = avecFichierOuLien;
}
/**
* @return the fichierOuLien
*/
public int getFichierOuLien() {
return fichierOuLien;
}
/**
* @param fichierOuLien the fichierOuLien to set
*/
public void setFichierOuLien(int fichierOuLien) {
this.fichierOuLien = fichierOuLien;
}
/**
* @return the listeOffres
*/
public List<OffreDTO> getListeOffres() {
return listeOffres;
}
/**
* @param listeOffres the listeOffres to set
*/
public void setListeOffres(List<OffreDTO> listeOffres) {
this.listeOffres = listeOffres;
}
/**
* @return the retour
*/
public String getRetour() {
if(!StringUtils.hasText(this.retour)) this.retour="defaut";
return retour;
}
/**
* @param retour the retour to set
*/
public void setRetour(String retour) {
this.retour = retour;
}
/**
* @return the recap
*/
public String getRecap() {
String ret = recap;
recap=null;
return ret;
}
/**
* @param recap the recap to set
*/
public void setRecap(String recap) {
this.recap = recap;
}
/**
* @return the currentOffre
*/
public OffreDTO getCurrentOffre() {
return currentOffre;
}
/**
* @param currentOffre the currentOffre to set
*/
public void setCurrentOffre(OffreDTO currentOffre) {
this.currentOffre = currentOffre;
}
/**
* @return the etablissementController
*/
public EtablissementController getEtablissementController() {
return etablissementController;
}
/**
* @param etablissementController the etablissementController to set
*/
public void setEtablissementController(
EtablissementController etablissementController) {
this.etablissementController = etablissementController;
}
/**
* @return the listeItemsCurrentCentresGestion
*/
public List<SelectItem> getListeItemsCurrentCentresGestion() {
listeItemsCurrentCentresGestion=null;
if(getSessionController().getCurrentCentresGestion()!=null
&& !getSessionController().getCurrentCentresGestion().isEmpty()){
listeItemsCurrentCentresGestion=new ArrayList<SelectItem>();
for(CentreGestionDTO cg : getSessionController().getCurrentCentresGestion()){
listeItemsCurrentCentresGestion.add(new SelectItem(cg.getIdCentreGestion(), cg.getNomCentre()));
}
}
return listeItemsCurrentCentresGestion;
}
/**
* @return the critereRechercheOffre
*/
public CritereRechercheOffreDTO getCritereRechercheOffre() {
return critereRechercheOffre;
}
/**
* @param critereRechercheOffre the critereRechercheOffre to set
*/
public void setCritereRechercheOffre(
CritereRechercheOffreDTO critereRechercheOffre) {
this.critereRechercheOffre = critereRechercheOffre;
}
/**
* @return the rechTypesContratsOffre
*/
public List<SelectItem> getRechTypesContratsOffre() {
rechTypesContratsOffre = new ArrayList<SelectItem>();
List<TypeOffreDTO> lt = getNomenclatureDomainService().getTypesOffre();
for(TypeOffreDTO t : lt){
rechTypesContratsOffre.add(new SelectItem("t"+t.getId(),t.getLibelle()));
List<ContratOffreDTO> lc = getNomenclatureDomainService().getContratsOffreFromIdTypeOffre(t.getId());
if(lc!=null && !lc.isEmpty()){
for(ContratOffreDTO c: lc){
rechTypesContratsOffre.add(new SelectItem("c"+c.getId(), "--- "+c.getLibelle()));
}
}
}
return rechTypesContratsOffre;
}
/**
* @return the rechTypeOuContrat
*/
public String getRechTypeOuContrat() {
return rechTypeOuContrat;
}
/**
* @param rechTypeOuContrat the rechTypeOuContrat to set
*/
public void setRechTypeOuContrat(String rechTypeOuContrat) {
this.rechTypeOuContrat = rechTypeOuContrat;
}
/**
* @return the resultatsRechercheOffre
*/
public List<OffreDTO> getResultatsRechercheOffre() {
return resultatsRechercheOffre;
}
/**
* @param resultatsRechercheOffre the resultatsRechercheOffre to set
*/
public void setResultatsRechercheOffre(List<OffreDTO> resultatsRechercheOffre) {
this.resultatsRechercheOffre = resultatsRechercheOffre;
}
/**
* @return the rechercheAvancee
*/
public boolean isRechercheAvancee() {
return rechercheAvancee;
}
/**
* @param rechercheAvancee the rechercheAvancee to set
*/
public void setRechercheAvancee(boolean rechercheAvancee) {
this.rechercheAvancee = rechercheAvancee;
}
/**
* @return the rechercheOffrePaginator
*/
public RechercheOffrePaginator getRechercheOffrePaginator() {
return rechercheOffrePaginator;
}
/**
* @param rechercheOffrePaginator the rechercheOffrePaginator to set
*/
public void setRechercheOffrePaginator(
RechercheOffrePaginator rechercheOffrePaginator) {
this.rechercheOffrePaginator = rechercheOffrePaginator;
}
/**
* @return the listesCentresGestionEtablissement
*/
public List<SelectItem> getListesCentresGestionEtablissement() {
this.listesCentresGestionEtablissement = new ArrayList<SelectItem>();
CentreGestionDTO cgEntr = getCentreGestionDomainService().getCentreEntreprise();
if(cgEntr!=null && getSessionController().getCurrentCentresGestion()!=null
&& !getSessionController().getCurrentCentresGestion().isEmpty()
&& getSessionController().getCurrentCentresGestion().contains(cgEntr)){
this.listesCentresGestionEtablissement.add(new SelectItem(0,getFacesInfoMessage("OFFRE.GESTION.DIFFUSIONCENTRE.DIFFUSERTLM").getDetail()));
List<CentreGestionDTO> l = getCentreGestionDomainService().getCentresEtablissement(getSessionController().getCodeUniversite());
this.listesCGEtab=l;
if(l!=null && !l.isEmpty()){
for(CentreGestionDTO cg : l){
this.listesCentresGestionEtablissement.add(new SelectItem(cg.getIdCentreGestion(), cg.getNomCentre()));
}
}
} else {
this.listesCentresGestionEtablissement=new ArrayList<SelectItem>();
CentreGestionDTO cgEtab = getCentreGestionDomainService().getCentreEtablissement(
getSessionController().getCodeUniversite());
this.listesCentresGestionEtablissement.add(new SelectItem(cgEtab.getIdCentreGestion(),""+cgEtab.getNomCentre()));
}
return this.listesCentresGestionEtablissement;
}
/**
* @param listesCentresGestionEtablissement the listesCentresGestionEtablissement to set
*/
public void setListesCentresGestionEtablissement(
List<SelectItem> listesCentresGestionEtablissement) {
this.listesCentresGestionEtablissement = listesCentresGestionEtablissement;
}
/**
* @return the idCentreEtablissementSelect
*/
public int getIdCentreEtablissementSelect() {
return idCentreEtablissementSelect;
}
/**
* @param idCentreEtablissementSelect the idCentreEtablissementSelect to set
*/
public void setIdCentreEtablissementSelect(int idCentreEtablissementSelect) {
this.idCentreEtablissementSelect = idCentreEtablissementSelect;
}
/**
* @return the centreGestionDepotAnonyme
*/
public CentreGestionDTO getCentreGestionDepotAnonyme() {
return centreGestionDepotAnonyme;
}
/**
* @param centreGestionDepotAnonyme the centreGestionDepotAnonyme to set
*/
public void setCentreGestionDepotAnonyme(
CentreGestionDTO centreGestionDepotAnonyme) {
this.centreGestionDepotAnonyme = centreGestionDepotAnonyme;
}
/**
* @return the castorService
*/
public CastorService getCastorService() {
return castorService;
}
/**
* @param castorService the castorService to set
*/
public void setCastorService(CastorService castorService) {
this.castorService = castorService;
}
/**
* @return the dureesDiffusion
*/
public List<SelectItem> getDureesDiffusion() {
this.dureesDiffusion = new ArrayList<SelectItem>();
boolean isAdmin;
if (this.currentOffre == null) this.currentOffre = this.formOffre;
Map<Integer,DroitAdministrationDTO> droitAcces = getSessionController().getDroitsAccesMap();
if (droitAcces.get(this.currentOffre.getIdCentreGestion()) == getBeanUtils().getDroitAdmin()
|| getSessionController().isAdminPageAuthorized()
|| getSessionController().isSuperAdminPageAuthorized()){
isAdmin = true;
} else {
isAdmin = false;
}
for(DureeDiffusionDTO dd : getOffreDomainService().getDureeDiffusion()){
if (dd.isAdminSeulement()) {
if (isAdmin) this.dureesDiffusion.add(new SelectItem(dd.getId(), dd.getLibelle()));
} else{
this.dureesDiffusion.add(new SelectItem(dd.getId(), dd.getLibelle()));
}
}
return dureesDiffusion;
}
/**
* @param dureesDiffusion the dureesDiffusion to set
*/
public void setDureesDiffusion(List<SelectItem> dureesDiffusion) {
this.dureesDiffusion = dureesDiffusion;
}
/**
* @return the dureeDiffusion
*/
public int getDureeDiffusion() {
return dureeDiffusion;
}
/**
* @param dureeDiffusion the dureeDiffusion to set
*/
public void setDureeDiffusion(int dureeDiffusion) {
this.dureeDiffusion = dureeDiffusion;
}
/**
* @return the diffusionDirecte
*/
public boolean isDiffusionDirecte() {
return diffusionDirecte;
}
/**
* @param diffusionDirecte the diffusionDirecte to set
*/
public void setDiffusionDirecte(boolean diffusionDirecte) {
this.diffusionDirecte = diffusionDirecte;
}
/**
* @param offreADiffuser the offreADiffuser to set
*/
public void setOffreADiffuser(int offreADiffuser) {
this.offreADiffuser= offreADiffuser;
}
/**
* @return the offreADiffuser
*/
public int getOffreADiffuser() {
this.offreADiffuser=getOffreDomainService().countOffreADiffuser(getSessionController().getCurrentIdsCentresGestion());
return this.offreADiffuser;
}
/**
* @return the creationOffre
*/
public String getCreationOffre() {
return creationOffre;
}
/**
* @param creationOffre the creationOffre to set
*/
public void setCreationOffre(String creationOffre) {
this.creationOffre = creationOffre;
}
public String getCurrentRecapOffre() {
return currentRecapOffre;
}
public void setCurrentRecapOffre(String currentRecapOffre) {
this.currentRecapOffre = currentRecapOffre;
}
public boolean isModificationContactOffre() {
return modificationContactOffre;
}
public void setModificationContactOffre(boolean modificationContactOffre) {
this.modificationContactOffre = modificationContactOffre;
}
}
| - Correction du problème de diffusion systématique des offres pourtant déposées par des entreprises.
| esup-pstage-web-jsf-servlet/src/main/java/org/esupportail/pstage/web/controllers/OffreController.java | - Correction du problème de diffusion systématique des offres pourtant déposées par des entreprises. | <ide><path>sup-pstage-web-jsf-servlet/src/main/java/org/esupportail/pstage/web/controllers/OffreController.java
<ide> /**
<ide> * on diffuse l'offre après ajout/modif si vrai
<ide> */
<del> private boolean diffusionDirecte = true;
<add> private boolean diffusionDirecte = false;
<ide>
<ide> /**
<ide> * Nombre d'offres à diffuser (pour affichage _menu.jsp partie entreprise)
<ide> getSessionController().setCreationOffreCurrentPage("_creationOffreEtape2");
<ide>
<ide> // Oui par défaut pour la diffusion directe de l'offre :
<del> this.diffusionDirecte = true;
<add>// this.diffusionDirecte = true;
<ide>
<ide> this.formOffre.setLieuPays(this.formOffre.getStructure().getPays());
<ide> this.formOffre.setLieuCodePostal(this.formOffre.getStructure().getCodePostal());
<ide>
<ide> //Reset de la durée de diffusion
<ide> this.dureeDiffusion = 2;
<add>
<ide>
<ide> return this.creationOffre;
<ide> }
<ide> } else if (!this.formOffre.isEstDiffusee()){
<ide> addInfoMessage(null, "OFFRE.CREATION.CONFIRMATION.DIFFUSION", this.formOffre.getIdOffre());
<ide> }
<add> this.diffusionDirecte = false;
<ide>
<ide> // return ret;
<ide> } |
|
Java | mit | a8f9b1c8425fc48c2f7834ab97c0bc122eb2e8e6 | 0 | wequst/epub3reader,pettarin/epub3reader | /*
The MIT License (MIT)
Copyright (c) 2013, V. Giacometti, M. Giuriato, B. Petrantuono
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 it.angrydroids.epub3reader;
import java.io.IOException;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.webkit.WebViewClient;
public class EpubNavigator extends WebViewClient {
// TODO: generalize
private EpubManipulator book1;
private EpubManipulator book2;
// TODO: better logic
private boolean atLeastOneBookOpen;
private boolean exactlyOneBookOpen;
private boolean synchronizedReadingActive;
private boolean parallelText = false;
private String pageOnView1;
private String pageOnView2;
private static Context context;
public EpubNavigator(Context theContext) {
atLeastOneBookOpen = false;
exactlyOneBookOpen = true;
synchronizedReadingActive = false;
pageOnView1 = "";
pageOnView2 = "";
if (context == null) {
context = theContext;
}
}
public boolean openBook1(String path) {
try {
// if a book is already open, deletes it
if (book1 != null)
book1.destroy();
parallelText = false;
book1 = new EpubManipulator(path, "1", context);
setView1(book1.getSpineElementPath(0));
atLeastOneBookOpen = true;
book1.createTocFile();
return true;
} catch (Exception e) {
return false;
}
}
public boolean openBook2(String path) {
try {
if (book2 != null)
book2.destroy();
parallelText = false;
book2 = new EpubManipulator(path, "2", context);
setView2(book2.getSpineElementPath(0));
book2.createTocFile();
exactlyOneBookOpen = false;
return true;
} catch (Exception e) {
return false;
}
}
public boolean parallelText(BookEnum which, int firstLanguage,
int secondLanguage) {
boolean ok = true;
if (firstLanguage != -1) {
try {
if (which != BookEnum.first) {
openBook1(book2.getFileName());
book1.goToPage(book2.getCurrentSpineElementIndex());
}
book1.setLanguage(firstLanguage);
setView1(book1.getCurrentPageURL());
} catch (Exception e) {
ok = false;
}
}
if (secondLanguage != -1) {
try {
if (which != BookEnum.second) {
openBook2(book1.getFileName());
book2.goToPage(book1.getCurrentSpineElementIndex());
}
book2.setLanguage(secondLanguage);
setView2(book2.getCurrentPageURL());
} catch (Exception e) {
ok = false;
}
}
if (ok && firstLanguage != -1 && secondLanguage != -1)
setSynchronizedReadingActive(true);
parallelText = true;
return ok;
}
public String[] getLanguagesBook1() {
return book1.getLanguages();
}
public String[] getLanguagesBook2() {
return book2.getLanguages();
}
// if synchronized reading is active, change chapter in both books
public void goToNextChapter(BookEnum which) throws Exception {
if ((synchronizedReadingActive) || (which == BookEnum.first))
setView1(book1.goToNextChapter());
if ((synchronizedReadingActive) || (which == BookEnum.second))
setView2(book2.goToNextChapter());
}
// if synchronized reading is active, change chapter in both books
public void goToPrevChapter(BookEnum which) throws Exception {
if ((synchronizedReadingActive) || (which == BookEnum.first))
setView1(book1.goToPreviousChapter());
if ((synchronizedReadingActive) || (which == BookEnum.second))
setView2(book2.goToPreviousChapter());
}
public ViewStateEnum loadPageIntoView1(String pathOfPage) {
EpubReaderMain.getView1().loadUrl(pathOfPage);
if ((book1 != null)
&& ((pathOfPage.equals(book1.getCurrentPageURL())) || (book1
.getPageIndex(pathOfPage) >= 0)))
return ViewStateEnum.books;
else
return ViewStateEnum.notes;
}
public ViewStateEnum loadPageIntoView2(String pathOfPage) {
EpubReaderMain.getView2().loadUrl(pathOfPage);
if ((book2 != null)
&& ((pathOfPage.equals(book1.getCurrentPageURL())) || (book2
.getPageIndex(pathOfPage) >= 0)))
return ViewStateEnum.books;
else
return ViewStateEnum.notes;
}
public ViewStateEnum closeView1() {
// book mode?
if ((book1.getPageIndex(pageOnView1) >= 0)
|| (pageOnView1.equals(book1.getCurrentPageURL()))) {
// book mode: delete it
try {
book1.destroy();
} catch (Exception e) {
}
if ((exactlyOneBookOpen) || (book2 == null)) {
// no second book open
atLeastOneBookOpen = false; // There is no longer any open book
return ViewStateEnum.invisible; // and the first view must be
// closed
} else {
// second book open
// the former book2 now becomes book1
book1 = book2;
book2 = null;
pageOnView1 = pageOnView2;
pageOnView2 = "";
exactlyOneBookOpen = true;
setSynchronizedReadingActive(false);
return loadPageIntoView1(pageOnView1);
}
} else {
// note mode: go back to book mode
pageOnView1 = book1.getCurrentPageURL();
loadPageIntoView1(book1.getCurrentPageURL());
return ViewStateEnum.books;
}
}
public ViewStateEnum closeView2() {
// book mode?
if ((book2 == null) || (book2.getPageIndex(pageOnView2) >= 0)
|| (pageOnView2.equals(book2.getCurrentPageURL()))) {
// book mode: delete it
try {
book2.destroy();
} catch (Exception e) {
}
exactlyOneBookOpen = true;
return ViewStateEnum.invisible;
} else {
// note mode: go back to book mode
pageOnView2 = book2.getCurrentPageURL();
loadPageIntoView2(book2.getCurrentPageURL());
return ViewStateEnum.books;
}
}
public void setSynchronizedReadingActive(boolean value) {
synchronizedReadingActive = value;
}
public boolean flipSynchronizedReadingActive() {
if (exactlyOneBookOpen)
return false;
synchronizedReadingActive = !synchronizedReadingActive;
return true;
}
public boolean synchronizeView2WithView1() throws Exception {
if (!exactlyOneBookOpen) {
setView2(book2.goToPage(book1.getCurrentSpineElementIndex()));
return true;
} else
return false;
}
public boolean synchronizeView1WithView2() throws Exception {
if (!exactlyOneBookOpen) {
setView1(book1.goToPage(book2.getCurrentSpineElementIndex()));
return true;
} else
return false;
}
public ViewStateEnum setView1(String page) {
ViewStateEnum res;
pageOnView1 = page;
if ((book1 != null) && (book1.goToPage(page))) {
// book mode
res = ViewStateEnum.books;
} else {
// note or external link mode
res = ViewStateEnum.notes;
}
loadPageIntoView1(page);
return res;
}
public ViewStateEnum setView2(String page) {
ViewStateEnum res;
pageOnView2 = page;
if ((book2 != null) && (book2.goToPage(page))) {
// book mode
res = ViewStateEnum.books;
} else {
// note or external link mode
res = ViewStateEnum.notes;
}
loadPageIntoView2(page);
return res;
}
// display book metadata
// returns true if metadata are available, false otherwise
public boolean displayMetadata(BookEnum which) {
boolean res = true;
if (which == BookEnum.first)
if (book1 != null) {
pageOnView1 = getS(R.string.metadata);
EpubReaderMain.getView1().loadData(book1.metadata(),
getS(R.string.textOrHTML), null);
} else
res = false;
else if (book2 != null) {
pageOnView2 = getS(R.string.metadata);
EpubReaderMain.getView2().loadData(book2.metadata(),
getS(R.string.textOrHTML), null);
} else
res = false;
return res;
}
// return true if TOC is available, false otherwise
public boolean displayTOC(BookEnum which) {
boolean res = true;
if (which == BookEnum.first)
if (book1 != null) {
pageOnView1 = getS(R.string.Table_of_Contents);
EpubReaderMain.getView1().loadUrl(book1.tableOfContents());
} else
res = false;
else if (book2 != null) {
pageOnView2 = getS(R.string.Table_of_Contents);
EpubReaderMain.getView2().loadUrl(book2.tableOfContents());
} else
res = false;
return res;
}
public void saveState(Editor editor) {
editor.putBoolean(getS(R.string.bookOpen), atLeastOneBookOpen);
editor.putBoolean(getS(R.string.onlyOne), exactlyOneBookOpen);
editor.putBoolean(getS(R.string.sync), synchronizedReadingActive);
editor.putBoolean(getS(R.string.parallelTextBool), parallelText);
if (atLeastOneBookOpen) {
if (book1 != null) {
// book1 exists: save its state and close it
editor.putString(getS(R.string.page1), pageOnView1);
editor.putInt(getS(R.string.CurrentPageBook1),
book1.getCurrentSpineElementIndex());
editor.putInt(getS(R.string.LanguageBook1),
book1.getCurrentLanguage());
editor.putString(getS(R.string.nameEpub1),
book1.getDecompressedFolder());
editor.putString(getS(R.string.pathBook1), book1.getFileName());
try {
book1.closeStream();
} catch (IOException e) {
Log.e(getS(R.string.error_CannotCloseStream),
getS(R.string.Book1_Stream));
e.printStackTrace();
}
editor.putString(getS(R.string.page2), pageOnView2);
if ((!exactlyOneBookOpen) && (book2 != null)) {
// book2 exists: save its state and close it
editor.putInt(getS(R.string.CurrentPageBook2),
book2.getCurrentSpineElementIndex());
editor.putInt(getS(R.string.LanguageBook2),
book2.getCurrentLanguage());
editor.putString(getS(R.string.nameEpub2),
book2.getDecompressedFolder());
editor.putString(getS(R.string.pathBook2),
book2.getFileName());
try {
book2.closeStream();
} catch (IOException e) {
Log.e(getS(R.string.error_CannotCloseStream),
getS(R.string.Book2_Stream));
e.printStackTrace();
}
}
}
}
}
public boolean loadState(SharedPreferences preferences) {
boolean ok = true;
atLeastOneBookOpen = preferences.getBoolean(getS(R.string.bookOpen),
false);
exactlyOneBookOpen = preferences.getBoolean(getS(R.string.onlyOne),
true);
synchronizedReadingActive = preferences.getBoolean(getS(R.string.sync),
false);
parallelText = preferences.getBoolean(getS(R.string.parallelTextBool),
false);
if (atLeastOneBookOpen) {
// load the first book
pageOnView1 = preferences.getString(getS(R.string.page1), "");
int pageIndex = preferences.getInt(getS(R.string.CurrentPageBook1),
0);
int langIndex = preferences.getInt(getS(R.string.LanguageBook1), 0);
String folder = preferences.getString(getS(R.string.nameEpub1), "");
String file = preferences.getString(getS(R.string.pathBook1), "");
// try loading a book already extracted
try {
book1 = new EpubManipulator(file, folder, pageIndex, langIndex,
context);
book1.goToPage(pageIndex);
} catch (Exception e1) {
// error: retry this way
try {
book1 = new EpubManipulator(file, "1", context);
book1.goToPage(pageIndex);
} catch (Exception e2) {
ok = false;
}
}
// Show the first view's actual page
loadPageIntoView1(pageOnView1);
if (pageOnView1 == getS(R.string.metadata)) // if they were
// metadata, reload them
displayMetadata(BookEnum.first);
if (pageOnView1 == getS(R.string.Table_of_Contents)) // if it was
// table of
// content, reload it
displayTOC(BookEnum.first);
// If there is a second book, try to reload it
pageOnView2 = preferences.getString(getS(R.string.page2), "");
if (!exactlyOneBookOpen) {
pageIndex = preferences.getInt(getS(R.string.CurrentPageBook2),
0);
langIndex = preferences.getInt(getS(R.string.LanguageBook2), 0);
folder = preferences.getString(getS(R.string.nameEpub2), "");
file = preferences.getString(getS(R.string.pathBook2), "");
try {
book2 = new EpubManipulator(file, folder, pageIndex,
langIndex, context);
book2.goToPage(pageIndex);
} catch (Exception e3) {
try {
book2 = new EpubManipulator(file, "2", context);
book2.goToPage(pageIndex);
} catch (Exception e4) {
ok = false;
}
}
}
loadPageIntoView2(pageOnView2);
if (pageOnView2 == getS(R.string.metadata))
displayMetadata(BookEnum.second);
if (pageOnView2 == getS(R.string.Table_of_Contents))
displayTOC(BookEnum.second);
}
return ok;
}
public boolean isExactlyOneBookOpen() {
return exactlyOneBookOpen;
}
public String getS(int id) {
return context.getResources().getString(id);
}
public boolean isParallelTextOn() {
return parallelText;
}
public boolean isSynchronized() {
return synchronizedReadingActive;
}
public boolean isAtLeastOneBookOpen() {
return atLeastOneBookOpen;
}
}
| workspaceeclipse/EPUB3Reader/src/it/angrydroids/epub3reader/EpubNavigator.java | /*
The MIT License (MIT)
Copyright (c) 2013, V. Giacometti, M. Giuriato, B. Petrantuono
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 it.angrydroids.epub3reader;
import java.io.IOException;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.webkit.WebViewClient;
public class EpubNavigator extends WebViewClient {
// TODO: generalize
private EpubManipulator book1;
private EpubManipulator book2;
// TODO: better logic
private boolean atLeastOneBookOpen;
private boolean exactlyOneBookOpen;
private boolean synchronizedReadingActive;
private boolean parallelText = false;
private String pageOnView1;
private String pageOnView2;
private static Context context;
public EpubNavigator(Context theContext) {
atLeastOneBookOpen = false;
exactlyOneBookOpen = true;
synchronizedReadingActive = false;
pageOnView1 = "";
pageOnView2 = "";
if (context == null) {
context = theContext;
}
}
public boolean openBook1(String path) {
try {
// if a book is already open, deletes it
if (book1 != null)
book1.destroy();
parallelText = false;
book1 = new EpubManipulator(path, "1", context);
setView1(book1.getSpineElementPath(0));
atLeastOneBookOpen = true;
book1.createTocFile();
return true;
} catch (Exception e) {
return false;
}
}
public boolean openBook2(String path) {
try {
if (book2 != null)
book2.destroy();
parallelText = false;
book2 = new EpubManipulator(path, "2", context);
setView2(book2.getSpineElementPath(0));
book2.createTocFile();
exactlyOneBookOpen = false;
return true;
} catch (Exception e) {
return false;
}
}
public boolean parallelText(BookEnum which, int firstLanguage,
int secondLanguage) {
boolean ok = true;
if (firstLanguage != -1) {
try {
if (which != BookEnum.first) {
openBook1(book2.getFileName());
book1.goToPage(book2.getCurrentSpineElementIndex());
}
book1.setLanguage(firstLanguage);
setView1(book1.getCurrentPageURL());
} catch (Exception e) {
ok = false;
}
}
if (secondLanguage != -1) {
try {
if (which != BookEnum.second) {
openBook2(book1.getFileName());
book2.goToPage(book1.getCurrentSpineElementIndex());
}
book2.setLanguage(secondLanguage);
setView2(book2.getCurrentPageURL());
} catch (Exception e) {
ok = false;
}
}
if (ok && firstLanguage != -1 && secondLanguage != -1)
setSynchronizedReadingActive(true);
parallelText = true;
return ok;
}
public String[] getLanguagesBook1() {
return book1.getLanguages();
}
public String[] getLanguagesBook2() {
return book2.getLanguages();
}
// if synchronized reading is active, change chapter in both books
public void goToNextChapter(BookEnum which) throws Exception {
if ((synchronizedReadingActive) || (which == BookEnum.first))
setView1(book1.goToNextChapter());
if ((synchronizedReadingActive) || (which == BookEnum.second))
setView2(book2.goToNextChapter());
}
// if synchronized reading is active, change chapter in both books
public void goToPrevChapter(BookEnum which) throws Exception {
if ((synchronizedReadingActive) || (which == BookEnum.first))
setView1(book1.goToPreviousChapter());
if ((synchronizedReadingActive) || (which == BookEnum.second))
setView2(book2.goToPreviousChapter());
}
public ViewStateEnum loadPageIntoView1(String pathOfPage) {
EpubReaderMain.getView1().loadUrl(pathOfPage);
if ((book1 != null)
&& ((pathOfPage.equals(book1.getCurrentPageURL())) || (book1
.getPageIndex(pathOfPage) >= 0)))
return ViewStateEnum.books;
else
return ViewStateEnum.notes;
}
public ViewStateEnum loadPageIntoView2(String pathOfPage) {
EpubReaderMain.getView2().loadUrl(pathOfPage);
if ((book2 != null)
&& ((pathOfPage.equals(book1.getCurrentPageURL())) || (book2
.getPageIndex(pathOfPage) >= 0)))
return ViewStateEnum.books;
else
return ViewStateEnum.notes;
}
public ViewStateEnum closeView1() {
parallelText = false;
// book mode?
if ((book1.getPageIndex(pageOnView1) >= 0)
|| (pageOnView1.equals(book1.getCurrentPageURL()))) {
// book mode: delete it
try {
book1.destroy();
} catch (Exception e) {
}
if ((exactlyOneBookOpen) || (book2 == null)) {
// no second book open
atLeastOneBookOpen = false; // There is no longer any open book
return ViewStateEnum.invisible; // and the first view must be
// closed
} else {
// second book open
// the former book2 now becomes book1
book1 = book2;
book2 = null;
pageOnView1 = pageOnView2;
pageOnView2 = "";
exactlyOneBookOpen = true;
setSynchronizedReadingActive(false);
return loadPageIntoView1(pageOnView1);
}
} else {
// note mode: go back to book mode
pageOnView1 = book1.getCurrentPageURL();
loadPageIntoView1(book1.getCurrentPageURL());
return ViewStateEnum.books;
}
}
public ViewStateEnum closeView2() {
parallelText = false;
// book mode?
if ((book2 == null) || (book2.getPageIndex(pageOnView2) >= 0)
|| (pageOnView2.equals(book2.getCurrentPageURL()))) {
// book mode: delete it
try {
book2.destroy();
} catch (Exception e) {
}
exactlyOneBookOpen = true;
return ViewStateEnum.invisible;
} else {
// note mode: go back to book mode
pageOnView2 = book2.getCurrentPageURL();
loadPageIntoView2(book2.getCurrentPageURL());
return ViewStateEnum.books;
}
}
public void setSynchronizedReadingActive(boolean value) {
synchronizedReadingActive = value;
}
public boolean flipSynchronizedReadingActive() {
if (exactlyOneBookOpen)
return false;
synchronizedReadingActive = !synchronizedReadingActive;
return true;
}
public boolean synchronizeView2WithView1() throws Exception {
if (!exactlyOneBookOpen) {
setView2(book2.goToPage(book1.getCurrentSpineElementIndex()));
return true;
} else
return false;
}
public boolean synchronizeView1WithView2() throws Exception {
if (!exactlyOneBookOpen) {
setView1(book1.goToPage(book2.getCurrentSpineElementIndex()));
return true;
} else
return false;
}
public ViewStateEnum setView1(String page) {
ViewStateEnum res;
pageOnView1 = page;
if ((book1 != null) && (book1.goToPage(page))) {
// book mode
res = ViewStateEnum.books;
} else {
// note or external link mode
res = ViewStateEnum.notes;
}
loadPageIntoView1(page);
return res;
}
public ViewStateEnum setView2(String page) {
ViewStateEnum res;
pageOnView2 = page;
if ((book2 != null) && (book2.goToPage(page))) {
// book mode
res = ViewStateEnum.books;
} else {
// note or external link mode
res = ViewStateEnum.notes;
}
loadPageIntoView2(page);
return res;
}
// display book metadata
// returns true if metadata are available, false otherwise
public boolean displayMetadata(BookEnum which) {
boolean res = true;
if (which == BookEnum.first)
if (book1 != null) {
pageOnView1 = getS(R.string.metadata);
EpubReaderMain.getView1().loadData(book1.metadata(),
getS(R.string.textOrHTML), null);
} else
res = false;
else if (book2 != null) {
pageOnView2 = getS(R.string.metadata);
EpubReaderMain.getView2().loadData(book2.metadata(),
getS(R.string.textOrHTML), null);
} else
res = false;
return res;
}
// return true if TOC is available, false otherwise
public boolean displayTOC(BookEnum which) {
boolean res = true;
if (which == BookEnum.first)
if (book1 != null) {
pageOnView1 = getS(R.string.Table_of_Contents);
EpubReaderMain.getView1().loadUrl(book1.tableOfContents());
} else
res = false;
else if (book2 != null) {
pageOnView2 = getS(R.string.Table_of_Contents);
EpubReaderMain.getView2().loadUrl(book2.tableOfContents());
} else
res = false;
return res;
}
public void saveState(Editor editor) {
editor.putBoolean(getS(R.string.bookOpen), atLeastOneBookOpen);
editor.putBoolean(getS(R.string.onlyOne), exactlyOneBookOpen);
editor.putBoolean(getS(R.string.sync), synchronizedReadingActive);
editor.putBoolean(getS(R.string.parallelTextBool), parallelText);
if (atLeastOneBookOpen) {
if (book1 != null) {
// book1 exists: save its state and close it
editor.putString(getS(R.string.page1), pageOnView1);
editor.putInt(getS(R.string.CurrentPageBook1),
book1.getCurrentSpineElementIndex());
editor.putInt(getS(R.string.LanguageBook1),
book1.getCurrentLanguage());
editor.putString(getS(R.string.nameEpub1),
book1.getDecompressedFolder());
editor.putString(getS(R.string.pathBook1), book1.getFileName());
try {
book1.closeStream();
} catch (IOException e) {
Log.e(getS(R.string.error_CannotCloseStream),
getS(R.string.Book1_Stream));
e.printStackTrace();
}
editor.putString(getS(R.string.page2), pageOnView2);
if ((!exactlyOneBookOpen) && (book2 != null)) {
// book2 exists: save its state and close it
editor.putInt(getS(R.string.CurrentPageBook2),
book2.getCurrentSpineElementIndex());
editor.putInt(getS(R.string.LanguageBook2),
book2.getCurrentLanguage());
editor.putString(getS(R.string.nameEpub2),
book2.getDecompressedFolder());
editor.putString(getS(R.string.pathBook2),
book2.getFileName());
try {
book2.closeStream();
} catch (IOException e) {
Log.e(getS(R.string.error_CannotCloseStream),
getS(R.string.Book2_Stream));
e.printStackTrace();
}
}
}
}
}
public boolean loadState(SharedPreferences preferences) {
boolean ok = true;
atLeastOneBookOpen = preferences.getBoolean(getS(R.string.bookOpen),
false);
exactlyOneBookOpen = preferences.getBoolean(getS(R.string.onlyOne),
true);
synchronizedReadingActive = preferences.getBoolean(getS(R.string.sync),
false);
parallelText = preferences.getBoolean(getS(R.string.parallelTextBool),
false);
if (atLeastOneBookOpen) {
// load the first book
pageOnView1 = preferences.getString(getS(R.string.page1), "");
int pageIndex = preferences.getInt(getS(R.string.CurrentPageBook1),
0);
int langIndex = preferences.getInt(getS(R.string.LanguageBook1), 0);
String folder = preferences.getString(getS(R.string.nameEpub1), "");
String file = preferences.getString(getS(R.string.pathBook1), "");
// try loading a book already extracted
try {
book1 = new EpubManipulator(file, folder, pageIndex, langIndex,
context);
book1.goToPage(pageIndex);
} catch (Exception e1) {
// error: retry this way
try {
book1 = new EpubManipulator(file, "1", context);
book1.goToPage(pageIndex);
} catch (Exception e2) {
ok = false;
}
}
// Show the first view's actual page
loadPageIntoView1(pageOnView1);
if (pageOnView1 == getS(R.string.metadata)) // if they were
// metadata, reload them
displayMetadata(BookEnum.first);
if (pageOnView1 == getS(R.string.Table_of_Contents)) // if it was
// table of
// content, reload it
displayTOC(BookEnum.first);
// If there is a second book, try to reload it
pageOnView2 = preferences.getString(getS(R.string.page2), "");
if (!exactlyOneBookOpen) {
pageIndex = preferences.getInt(getS(R.string.CurrentPageBook2),
0);
langIndex = preferences.getInt(getS(R.string.LanguageBook2), 0);
folder = preferences.getString(getS(R.string.nameEpub2), "");
file = preferences.getString(getS(R.string.pathBook2), "");
try {
book2 = new EpubManipulator(file, folder, pageIndex,
langIndex, context);
book2.goToPage(pageIndex);
} catch (Exception e3) {
try {
book2 = new EpubManipulator(file, "2", context);
book2.goToPage(pageIndex);
} catch (Exception e4) {
ok = false;
}
}
}
loadPageIntoView2(pageOnView2);
if (pageOnView2 == getS(R.string.metadata))
displayMetadata(BookEnum.second);
if (pageOnView2 == getS(R.string.Table_of_Contents))
displayTOC(BookEnum.second);
}
return ok;
}
public boolean isExactlyOneBookOpen() {
return exactlyOneBookOpen;
}
public String getS(int id) {
return context.getResources().getString(id);
}
public boolean isParallelTextOn() {
return parallelText;
}
public boolean isSynchronized() {
return synchronizedReadingActive;
}
public boolean isAtLeastOneBookOpen() {
return atLeastOneBookOpen;
}
}
| fix commit
| workspaceeclipse/EPUB3Reader/src/it/angrydroids/epub3reader/EpubNavigator.java | fix commit | <ide><path>orkspaceeclipse/EPUB3Reader/src/it/angrydroids/epub3reader/EpubNavigator.java
<ide>
<ide> public ViewStateEnum closeView1() {
<ide>
<del> parallelText = false;
<del>
<ide> // book mode?
<ide> if ((book1.getPageIndex(pageOnView1) >= 0)
<ide> || (pageOnView1.equals(book1.getCurrentPageURL()))) {
<ide> }
<ide>
<ide> public ViewStateEnum closeView2() {
<del>
<del> parallelText = false;
<ide>
<ide> // book mode?
<ide> if ((book2 == null) || (book2.getPageIndex(pageOnView2) >= 0) |
|
Java | apache-2.0 | a76e4434faa559d91761bf3da18a7cccab45a2a8 | 0 | mhajas/keycloak,brat000012001/keycloak,mposolda/keycloak,ahus1/keycloak,mhajas/keycloak,stianst/keycloak,ahus1/keycloak,stianst/keycloak,thomasdarimont/keycloak,raehalme/keycloak,hmlnarik/keycloak,jpkrohling/keycloak,reneploetz/keycloak,hmlnarik/keycloak,mposolda/keycloak,srose/keycloak,brat000012001/keycloak,reneploetz/keycloak,pedroigor/keycloak,mposolda/keycloak,srose/keycloak,raehalme/keycloak,ahus1/keycloak,jpkrohling/keycloak,vmuzikar/keycloak,keycloak/keycloak,agolPL/keycloak,jpkrohling/keycloak,hmlnarik/keycloak,hmlnarik/keycloak,thomasdarimont/keycloak,vmuzikar/keycloak,agolPL/keycloak,vmuzikar/keycloak,darranl/keycloak,abstractj/keycloak,keycloak/keycloak,mposolda/keycloak,ahus1/keycloak,thomasdarimont/keycloak,agolPL/keycloak,pedroigor/keycloak,reneploetz/keycloak,mposolda/keycloak,keycloak/keycloak,hmlnarik/keycloak,srose/keycloak,vmuzikar/keycloak,mposolda/keycloak,vmuzikar/keycloak,raehalme/keycloak,keycloak/keycloak,jpkrohling/keycloak,pedroigor/keycloak,reneploetz/keycloak,raehalme/keycloak,pedroigor/keycloak,darranl/keycloak,abstractj/keycloak,ssilvert/keycloak,hmlnarik/keycloak,ssilvert/keycloak,brat000012001/keycloak,ssilvert/keycloak,pedroigor/keycloak,mhajas/keycloak,vmuzikar/keycloak,stianst/keycloak,agolPL/keycloak,brat000012001/keycloak,jpkrohling/keycloak,thomasdarimont/keycloak,raehalme/keycloak,keycloak/keycloak,abstractj/keycloak,darranl/keycloak,brat000012001/keycloak,ssilvert/keycloak,thomasdarimont/keycloak,srose/keycloak,ahus1/keycloak,ahus1/keycloak,abstractj/keycloak,raehalme/keycloak,mhajas/keycloak,abstractj/keycloak,pedroigor/keycloak,darranl/keycloak,stianst/keycloak,srose/keycloak,thomasdarimont/keycloak,mhajas/keycloak,stianst/keycloak,reneploetz/keycloak,ssilvert/keycloak | /*
* Copyright 2016 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.keycloak.testsuite.adapter.servlet;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.graphene.page.Page;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.resource.ClientResource;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.authorization.model.Policy;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.common.util.Base64Url;
import org.keycloak.models.ClientModel;
import org.keycloak.models.Constants;
import org.keycloak.models.IdentityProviderModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.protocol.oidc.OIDCLoginProtocolService;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.FederatedIdentityRepresentation;
import org.keycloak.representations.idm.IdentityProviderRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.representations.idm.authorization.ClientPolicyRepresentation;
import org.keycloak.services.resources.admin.permissions.AdminPermissionManagement;
import org.keycloak.services.resources.admin.permissions.AdminPermissions;
import org.keycloak.testsuite.ActionURIUtils;
import org.keycloak.testsuite.adapter.AbstractServletsAdapterTest;
import org.keycloak.testsuite.admin.ApiUtil;
import org.keycloak.testsuite.arquillian.AuthServerTestEnricher;
import org.keycloak.testsuite.broker.BrokerTestTools;
import org.keycloak.testsuite.page.AbstractPageWithInjectedUrl;
import org.keycloak.testsuite.pages.AccountUpdateProfilePage;
import org.keycloak.testsuite.pages.ErrorPage;
import org.keycloak.testsuite.pages.LoginPage;
import org.keycloak.testsuite.pages.LoginUpdateProfilePage;
import org.keycloak.testsuite.util.OAuthClient;
import org.keycloak.testsuite.util.WaitUtils;
import org.keycloak.util.JsonSerialization;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.UriBuilder;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.keycloak.models.AccountRoles.MANAGE_ACCOUNT;
import static org.keycloak.models.AccountRoles.MANAGE_ACCOUNT_LINKS;
import static org.keycloak.models.Constants.ACCOUNT_MANAGEMENT_CLIENT_ID;
import static org.keycloak.testsuite.admin.ApiUtil.createUserAndResetPasswordWithAdminClient;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*/
public abstract class AbstractLinkAndExchangeTest extends AbstractServletsAdapterTest {
public static final String CHILD_IDP = "child";
public static final String PARENT_IDP = "parent-idp";
public static final String PARENT_USERNAME = "parent";
@Page
protected LoginUpdateProfilePage loginUpdateProfilePage;
@Page
protected AccountUpdateProfilePage profilePage;
@Page
private LoginPage loginPage;
@Page
protected ErrorPage errorPage;
public static class ClientApp extends AbstractPageWithInjectedUrl {
public static final String DEPLOYMENT_NAME = "client-linking";
@ArquillianResource
@OperateOnDeployment(DEPLOYMENT_NAME)
private URL url;
@Override
public URL getInjectedUrl() {
return url;
}
}
@Page
private ClientApp appPage;
@Override
public void beforeAuthTest() {
}
@Override
public void addAdapterTestRealms(List<RealmRepresentation> testRealms) {
RealmRepresentation realm = new RealmRepresentation();
realm.setRealm(CHILD_IDP);
realm.setEnabled(true);
ClientRepresentation servlet = new ClientRepresentation();
servlet.setClientId("client-linking");
servlet.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
String uri = "/client-linking";
if (!isRelative()) {
uri = appServerContextRootPage.toString() + uri;
}
servlet.setAdminUrl(uri);
servlet.setDirectAccessGrantsEnabled(true);
servlet.setBaseUrl(uri);
servlet.setRedirectUris(new LinkedList<>());
servlet.getRedirectUris().add(uri + "/*");
servlet.setSecret("password");
servlet.setFullScopeAllowed(true);
realm.setClients(new LinkedList<>());
realm.getClients().add(servlet);
testRealms.add(realm);
realm = new RealmRepresentation();
realm.setRealm(PARENT_IDP);
realm.setEnabled(true);
testRealms.add(realm);
}
@Deployment(name = ClientApp.DEPLOYMENT_NAME)
protected static WebArchive accountLink() {
return servletDeployment(ClientApp.DEPLOYMENT_NAME, LinkAndExchangeServlet.class, ServletTestUtils.class);
}
@Before
public void addIdpUser() {
RealmResource realm = adminClient.realms().realm(PARENT_IDP);
UserRepresentation user = new UserRepresentation();
user.setUsername(PARENT_USERNAME);
user.setEnabled(true);
String userId = createUserAndResetPasswordWithAdminClient(realm, user, "password");
}
private String childUserId = null;
@Before
public void addChildUser() {
RealmResource realm = adminClient.realms().realm(CHILD_IDP);
UserRepresentation user = new UserRepresentation();
user.setUsername("child");
user.setEnabled(true);
childUserId = createUserAndResetPasswordWithAdminClient(realm, user, "password");
UserRepresentation user2 = new UserRepresentation();
user2.setUsername("child2");
user2.setEnabled(true);
String user2Id = createUserAndResetPasswordWithAdminClient(realm, user2, "password");
// have to add a role as undertow default auth manager doesn't like "*". todo we can remove this eventually as undertow fixes this in later versions
realm.roles().create(new RoleRepresentation("user", null, false));
RoleRepresentation role = realm.roles().get("user").toRepresentation();
List<RoleRepresentation> roles = new LinkedList<>();
roles.add(role);
realm.users().get(childUserId).roles().realmLevel().add(roles);
realm.users().get(user2Id).roles().realmLevel().add(roles);
ClientRepresentation brokerService = realm.clients().findByClientId(Constants.BROKER_SERVICE_CLIENT_ID).get(0);
role = realm.clients().get(brokerService.getId()).roles().get(Constants.READ_TOKEN_ROLE).toRepresentation();
roles.clear();
roles.add(role);
realm.users().get(childUserId).roles().clientLevel(brokerService.getId()).add(roles);
realm.users().get(user2Id).roles().clientLevel(brokerService.getId()).add(roles);
}
public static void setupRealm(KeycloakSession session) {
RealmModel realm = session.realms().getRealmByName(CHILD_IDP);
ClientModel client = realm.getClientByClientId("client-linking");
IdentityProviderModel idp = realm.getIdentityProviderByAlias(PARENT_IDP);
Assert.assertNotNull(idp);
AdminPermissionManagement management = AdminPermissions.management(session, realm);
management.idps().setPermissionsEnabled(idp, true);
ClientPolicyRepresentation clientRep = new ClientPolicyRepresentation();
clientRep.setName("toIdp");
clientRep.addClient(client.getId());
ResourceServer server = management.realmResourceServer();
Policy clientPolicy = management.authz().getStoreFactory().getPolicyStore().create(clientRep, server);
management.idps().exchangeToPermission(idp).addAssociatedPolicy(clientPolicy);
}
@Before
public void createBroker() {
createParentChild();
testingClient.server().run(AbstractLinkAndExchangeTest::setupRealm);
}
public void createParentChild() {
BrokerTestTools.createKcOidcBroker(adminClient, CHILD_IDP, PARENT_IDP, suiteContext);
}
@Test
public void testErrorConditions() throws Exception {
RealmResource realm = adminClient.realms().realm(CHILD_IDP);
List<FederatedIdentityRepresentation> links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
ClientRepresentation client = adminClient.realms().realm(CHILD_IDP).clients().findByClientId("client-linking").get(0);
UriBuilder redirectUri = UriBuilder.fromUri(appPage.getInjectedUrl().toString())
.path("link")
.queryParam("response", "true");
UriBuilder directLinking = UriBuilder.fromUri(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth")
.path("realms/child/broker/{provider}/link")
.queryParam("client_id", "client-linking")
.queryParam("redirect_uri", redirectUri.build())
.queryParam("hash", Base64Url.encode("crap".getBytes()))
.queryParam("nonce", UUID.randomUUID().toString());
String linkUrl = directLinking
.build(PARENT_IDP).toString();
// test not logged in
navigateTo(linkUrl);
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
loginPage.login("child", "password");
Assert.assertTrue(driver.getCurrentUrl().contains("link_error=not_logged_in"));
logoutAll();
// now log in
navigateTo( appPage.getInjectedUrl() + "/hello");
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
loginPage.login("child", "password");
Assert.assertTrue(driver.getCurrentUrl().startsWith(appPage.getInjectedUrl() + "/hello"));
Assert.assertTrue(driver.getPageSource().contains("Unknown request:"));
// now test CSRF with bad hash.
navigateTo(linkUrl);
Assert.assertTrue(driver.getPageSource().contains("We're sorry..."));
logoutAll();
// now log in again with client that does not have scope
String accountId = adminClient.realms().realm(CHILD_IDP).clients().findByClientId(ACCOUNT_MANAGEMENT_CLIENT_ID).get(0).getId();
RoleRepresentation manageAccount = adminClient.realms().realm(CHILD_IDP).clients().get(accountId).roles().get(MANAGE_ACCOUNT).toRepresentation();
RoleRepresentation manageLinks = adminClient.realms().realm(CHILD_IDP).clients().get(accountId).roles().get(MANAGE_ACCOUNT_LINKS).toRepresentation();
RoleRepresentation userRole = adminClient.realms().realm(CHILD_IDP).roles().get("user").toRepresentation();
client.setFullScopeAllowed(false);
ClientResource clientResource = adminClient.realms().realm(CHILD_IDP).clients().get(client.getId());
clientResource.update(client);
List<RoleRepresentation> roles = new LinkedList<>();
roles.add(userRole);
clientResource.getScopeMappings().realmLevel().add(roles);
navigateTo( appPage.getInjectedUrl() + "/hello");
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
loginPage.login("child", "password");
Assert.assertTrue(driver.getCurrentUrl().startsWith(appPage.getInjectedUrl() + "/hello"));
Assert.assertTrue(driver.getPageSource().contains("Unknown request:"));
UriBuilder linkBuilder = UriBuilder.fromUri(appPage.getInjectedUrl().toString())
.path("link");
String clientLinkUrl = linkBuilder.clone()
.queryParam("realm", CHILD_IDP)
.queryParam("provider", PARENT_IDP).build().toString();
navigateTo(clientLinkUrl);
Assert.assertTrue(driver.getCurrentUrl().contains("error=not_allowed"));
logoutAll();
// add MANAGE_ACCOUNT_LINKS scope should pass.
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
roles = new LinkedList<>();
roles.add(manageLinks);
clientResource.getScopeMappings().clientLevel(accountId).add(roles);
navigateTo(clientLinkUrl);
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
loginPage.login("child", "password");
Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
loginPage.login(PARENT_USERNAME, "password");
Assert.assertTrue(driver.getCurrentUrl().startsWith(linkBuilder.toTemplate()));
Assert.assertTrue(driver.getPageSource().contains("Account Linked"));
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertFalse(links.isEmpty());
realm.users().get(childUserId).removeFederatedIdentity(PARENT_IDP);
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
clientResource.getScopeMappings().clientLevel(accountId).remove(roles);
logoutAll();
navigateTo(clientLinkUrl);
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
loginPage.login("child", "password");
Assert.assertTrue(driver.getCurrentUrl().contains("link_error=not_allowed"));
logoutAll();
// add MANAGE_ACCOUNT scope should pass
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
roles = new LinkedList<>();
roles.add(manageAccount);
clientResource.getScopeMappings().clientLevel(accountId).add(roles);
navigateTo(clientLinkUrl);
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
loginPage.login("child", "password");
Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
loginPage.login(PARENT_USERNAME, "password");
Assert.assertTrue(driver.getCurrentUrl().startsWith(linkBuilder.toTemplate()));
Assert.assertTrue(driver.getPageSource().contains("Account Linked"));
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertFalse(links.isEmpty());
realm.users().get(childUserId).removeFederatedIdentity(PARENT_IDP);
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
clientResource.getScopeMappings().clientLevel(accountId).remove(roles);
logoutAll();
navigateTo(clientLinkUrl);
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
loginPage.login("child", "password");
Assert.assertTrue(driver.getCurrentUrl().contains("link_error=not_allowed"));
logoutAll();
// undo fullScopeAllowed
client = adminClient.realms().realm(CHILD_IDP).clients().findByClientId("client-linking").get(0);
client.setFullScopeAllowed(true);
clientResource.update(client);
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
logoutAll();
}
@Test
public void testAccountLink() throws Exception {
RealmResource realm = adminClient.realms().realm(CHILD_IDP);
List<FederatedIdentityRepresentation> links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
UriBuilder linkBuilder = UriBuilder.fromUri(appPage.getInjectedUrl().toString())
.path("link");
String linkUrl = linkBuilder.clone()
.queryParam("realm", CHILD_IDP)
.queryParam("provider", PARENT_IDP).build().toString();
System.out.println("linkUrl: " + linkUrl);
navigateTo(linkUrl);
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
Assert.assertTrue(driver.getPageSource().contains(PARENT_IDP));
loginPage.login("child", "password");
Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
loginPage.login(PARENT_USERNAME, "password");
System.out.println("After linking: " + driver.getCurrentUrl());
System.out.println(driver.getPageSource());
Assert.assertTrue(driver.getCurrentUrl().startsWith(linkBuilder.toTemplate()));
Assert.assertTrue(driver.getPageSource().contains("Account Linked"));
OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest(CHILD_IDP, "child", "password", null, "client-linking", "password");
Assert.assertNotNull(response.getAccessToken());
Assert.assertNull(response.getError());
Client httpClient = ClientBuilder.newClient();
String firstToken = getToken(response, httpClient);
Assert.assertNotNull(firstToken);
navigateTo(linkUrl);
Assert.assertTrue(driver.getPageSource().contains("Account Linked"));
String nextToken = getToken(response, httpClient);
Assert.assertNotNull(nextToken);
Assert.assertNotEquals(firstToken, nextToken);
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertFalse(links.isEmpty());
realm.users().get(childUserId).removeFederatedIdentity(PARENT_IDP);
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
logoutAll();
}
private String getToken(OAuthClient.AccessTokenResponse response, Client httpClient) throws Exception {
String idpToken = httpClient.target(OAuthClient.AUTH_SERVER_ROOT)
.path("realms")
.path("child/broker")
.path(PARENT_IDP)
.path("token")
.request()
.header("Authorization", "Bearer " + response.getAccessToken())
.get(String.class);
AccessTokenResponse res = JsonSerialization.readValue(idpToken, AccessTokenResponse.class);
return res.getToken();
}
public void logoutAll() {
String logoutUri = OIDCLoginProtocolService.logoutUrl(authServerPage.createUriBuilder()).build(CHILD_IDP).toString();
navigateTo(logoutUri);
logoutUri = OIDCLoginProtocolService.logoutUrl(authServerPage.createUriBuilder()).build(PARENT_IDP).toString();
navigateTo(logoutUri);
}
@Test
public void testLinkOnlyProvider() throws Exception {
RealmResource realm = adminClient.realms().realm(CHILD_IDP);
IdentityProviderRepresentation rep = realm.identityProviders().get(PARENT_IDP).toRepresentation();
rep.setLinkOnly(true);
realm.identityProviders().get(PARENT_IDP).update(rep);
try {
List<FederatedIdentityRepresentation> links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
UriBuilder linkBuilder = UriBuilder.fromUri(appPage.getInjectedUrl().toString())
.path("link");
String linkUrl = linkBuilder.clone()
.queryParam("realm", CHILD_IDP)
.queryParam("provider", PARENT_IDP).build().toString();
navigateTo(linkUrl);
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
// should not be on login page. This is what we are testing
Assert.assertFalse(driver.getPageSource().contains(PARENT_IDP));
// now test that we can still link.
loginPage.login("child", "password");
Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
loginPage.login(PARENT_USERNAME, "password");
System.out.println("After linking: " + driver.getCurrentUrl());
System.out.println(driver.getPageSource());
Assert.assertTrue(driver.getCurrentUrl().startsWith(linkBuilder.toTemplate()));
Assert.assertTrue(driver.getPageSource().contains("Account Linked"));
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertFalse(links.isEmpty());
realm.users().get(childUserId).removeFederatedIdentity(PARENT_IDP);
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
logoutAll();
System.out.println("testing link-only attack");
navigateTo(linkUrl);
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
System.out.println("login page uri is: " + driver.getCurrentUrl());
// ok, now scrape the code from page
String pageSource = driver.getPageSource();
String action = ActionURIUtils.getActionURIFromPageSource(pageSource);
System.out.println("action uri: " + action);
Map<String, String> queryParams = ActionURIUtils.parseQueryParamsFromActionURI(action);
System.out.println("query params: " + queryParams);
// now try and use the code to login to remote link-only idp
String uri = "/auth/realms/child/broker/parent-idp/login";
uri = UriBuilder.fromUri(AuthServerTestEnricher.getAuthServerContextRoot())
.path(uri)
.queryParam(OAuth2Constants.CODE, queryParams.get(OAuth2Constants.CODE))
.queryParam(Constants.CLIENT_ID, queryParams.get(Constants.CLIENT_ID))
.build().toString();
System.out.println("hack uri: " + uri);
navigateTo(uri);
Assert.assertTrue(driver.getPageSource().contains("Could not send authentication request to identity provider."));
} finally {
rep.setLinkOnly(false);
realm.identityProviders().get(PARENT_IDP).update(rep);
}
}
@Test
public void testAccountNotLinkedAutomatically() throws Exception {
RealmResource realm = adminClient.realms().realm(CHILD_IDP);
List<FederatedIdentityRepresentation> links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
// Login to account mgmt first
profilePage.open(CHILD_IDP);
WaitUtils.waitForPageToLoad();
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
loginPage.login("child", "password");
profilePage.assertCurrent();
// Now in another tab, open login screen with "prompt=login" . Login screen will be displayed even if I have SSO cookie
UriBuilder linkBuilder = UriBuilder.fromUri(appPage.getInjectedUrl().toString())
.path("nosuch");
String linkUrl = linkBuilder.clone()
.queryParam(OIDCLoginProtocol.PROMPT_PARAM, OIDCLoginProtocol.PROMPT_VALUE_LOGIN)
.build().toString();
navigateTo(linkUrl);
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
loginPage.clickSocial(PARENT_IDP);
Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
loginPage.login(PARENT_USERNAME, "password");
// Test I was not automatically linked.
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
loginUpdateProfilePage.assertCurrent();
loginUpdateProfilePage.update("Joe", "Doe", "[email protected]");
errorPage.assertCurrent();
Assert.assertEquals("You are already authenticated as different user 'child' in this session. Please logout first.", errorPage.getError());
logoutAll();
// Remove newly created user
String newUserId = ApiUtil.findUserByUsername(realm, "parent").getId();
getCleanup("child").addUserId(newUserId);
}
@Test
public void testAccountLinkingExpired() throws Exception {
RealmResource realm = adminClient.realms().realm(CHILD_IDP);
List<FederatedIdentityRepresentation> links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
// Login to account mgmt first
profilePage.open(CHILD_IDP);
WaitUtils.waitForPageToLoad();
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
loginPage.login("child", "password");
profilePage.assertCurrent();
// Now in another tab, request account linking
UriBuilder linkBuilder = UriBuilder.fromUri(appPage.getInjectedUrl().toString())
.path("link");
String linkUrl = linkBuilder.clone()
.queryParam("realm", CHILD_IDP)
.queryParam("provider", PARENT_IDP).build().toString();
navigateTo(linkUrl);
Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
// Logout "child" userSession in the meantime (for example through admin request)
realm.logoutAll();
// Finish login on parent.
loginPage.login(PARENT_USERNAME, "password");
// Test I was not automatically linked
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
errorPage.assertCurrent();
Assert.assertEquals("Requested broker account linking, but current session is no longer valid.", errorPage.getError());
logoutAll();
}
private void navigateTo(String uri) {
driver.navigate().to(uri);
WaitUtils.waitForPageToLoad();
}
}
| testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/AbstractLinkAndExchangeTest.java | /*
* Copyright 2016 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.keycloak.testsuite.adapter.servlet;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.graphene.page.Page;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.resource.ClientResource;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.authorization.model.Policy;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.common.util.Base64Url;
import org.keycloak.models.ClientModel;
import org.keycloak.models.Constants;
import org.keycloak.models.IdentityProviderModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.protocol.oidc.OIDCLoginProtocolService;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.FederatedIdentityRepresentation;
import org.keycloak.representations.idm.IdentityProviderRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.representations.idm.authorization.ClientPolicyRepresentation;
import org.keycloak.services.resources.admin.permissions.AdminPermissionManagement;
import org.keycloak.services.resources.admin.permissions.AdminPermissions;
import org.keycloak.testsuite.ActionURIUtils;
import org.keycloak.testsuite.adapter.AbstractServletsAdapterTest;
import org.keycloak.testsuite.admin.ApiUtil;
import org.keycloak.testsuite.arquillian.AuthServerTestEnricher;
import org.keycloak.testsuite.broker.BrokerTestTools;
import org.keycloak.testsuite.page.AbstractPageWithInjectedUrl;
import org.keycloak.testsuite.pages.AccountUpdateProfilePage;
import org.keycloak.testsuite.pages.ErrorPage;
import org.keycloak.testsuite.pages.LoginPage;
import org.keycloak.testsuite.pages.LoginUpdateProfilePage;
import org.keycloak.testsuite.util.OAuthClient;
import org.keycloak.testsuite.util.WaitUtils;
import org.keycloak.util.JsonSerialization;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.UriBuilder;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.keycloak.models.AccountRoles.MANAGE_ACCOUNT;
import static org.keycloak.models.AccountRoles.MANAGE_ACCOUNT_LINKS;
import static org.keycloak.models.Constants.ACCOUNT_MANAGEMENT_CLIENT_ID;
import static org.keycloak.testsuite.admin.ApiUtil.createUserAndResetPasswordWithAdminClient;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*/
public abstract class AbstractLinkAndExchangeTest extends AbstractServletsAdapterTest {
public static final String CHILD_IDP = "child";
public static final String PARENT_IDP = "parent-idp";
public static final String PARENT_USERNAME = "parent";
@Page
protected LoginUpdateProfilePage loginUpdateProfilePage;
@Page
protected AccountUpdateProfilePage profilePage;
@Page
private LoginPage loginPage;
@Page
protected ErrorPage errorPage;
public static class ClientApp extends AbstractPageWithInjectedUrl {
public static final String DEPLOYMENT_NAME = "client-linking";
@ArquillianResource
@OperateOnDeployment(DEPLOYMENT_NAME)
private URL url;
@Override
public URL getInjectedUrl() {
return url;
}
}
@Page
private ClientApp appPage;
@Override
public void beforeAuthTest() {
}
@Override
public void addAdapterTestRealms(List<RealmRepresentation> testRealms) {
RealmRepresentation realm = new RealmRepresentation();
realm.setRealm(CHILD_IDP);
realm.setEnabled(true);
ClientRepresentation servlet = new ClientRepresentation();
servlet.setClientId("client-linking");
servlet.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
String uri = "/client-linking";
if (!isRelative()) {
uri = appServerContextRootPage.toString() + uri;
}
servlet.setAdminUrl(uri);
servlet.setDirectAccessGrantsEnabled(true);
servlet.setBaseUrl(uri);
servlet.setRedirectUris(new LinkedList<>());
servlet.getRedirectUris().add(uri + "/*");
servlet.setSecret("password");
servlet.setFullScopeAllowed(true);
realm.setClients(new LinkedList<>());
realm.getClients().add(servlet);
testRealms.add(realm);
realm = new RealmRepresentation();
realm.setRealm(PARENT_IDP);
realm.setEnabled(true);
testRealms.add(realm);
}
@Deployment(name = ClientApp.DEPLOYMENT_NAME)
protected static WebArchive accountLink() {
return servletDeployment(ClientApp.DEPLOYMENT_NAME, LinkAndExchangeServlet.class, ServletTestUtils.class);
}
@Before
public void addIdpUser() {
RealmResource realm = adminClient.realms().realm(PARENT_IDP);
UserRepresentation user = new UserRepresentation();
user.setUsername(PARENT_USERNAME);
user.setEnabled(true);
String userId = createUserAndResetPasswordWithAdminClient(realm, user, "password");
}
private String childUserId = null;
@Before
public void addChildUser() {
RealmResource realm = adminClient.realms().realm(CHILD_IDP);
UserRepresentation user = new UserRepresentation();
user.setUsername("child");
user.setEnabled(true);
childUserId = createUserAndResetPasswordWithAdminClient(realm, user, "password");
UserRepresentation user2 = new UserRepresentation();
user2.setUsername("child2");
user2.setEnabled(true);
String user2Id = createUserAndResetPasswordWithAdminClient(realm, user2, "password");
// have to add a role as undertow default auth manager doesn't like "*". todo we can remove this eventually as undertow fixes this in later versions
realm.roles().create(new RoleRepresentation("user", null, false));
RoleRepresentation role = realm.roles().get("user").toRepresentation();
List<RoleRepresentation> roles = new LinkedList<>();
roles.add(role);
realm.users().get(childUserId).roles().realmLevel().add(roles);
realm.users().get(user2Id).roles().realmLevel().add(roles);
ClientRepresentation brokerService = realm.clients().findByClientId(Constants.BROKER_SERVICE_CLIENT_ID).get(0);
role = realm.clients().get(brokerService.getId()).roles().get(Constants.READ_TOKEN_ROLE).toRepresentation();
roles.clear();
roles.add(role);
realm.users().get(childUserId).roles().clientLevel(brokerService.getId()).add(roles);
realm.users().get(user2Id).roles().clientLevel(brokerService.getId()).add(roles);
}
public static void setupRealm(KeycloakSession session) {
RealmModel realm = session.realms().getRealmByName(CHILD_IDP);
ClientModel client = realm.getClientByClientId("client-linking");
IdentityProviderModel idp = realm.getIdentityProviderByAlias(PARENT_IDP);
Assert.assertNotNull(idp);
AdminPermissionManagement management = AdminPermissions.management(session, realm);
management.idps().setPermissionsEnabled(idp, true);
ClientPolicyRepresentation clientRep = new ClientPolicyRepresentation();
clientRep.setName("toIdp");
clientRep.addClient(client.getId());
ResourceServer server = management.realmResourceServer();
Policy clientPolicy = management.authz().getStoreFactory().getPolicyStore().create(clientRep, server);
management.idps().exchangeToPermission(idp).addAssociatedPolicy(clientPolicy);
}
@Before
public void createBroker() {
createParentChild();
testingClient.server().run(AbstractLinkAndExchangeTest::setupRealm);
}
public void createParentChild() {
BrokerTestTools.createKcOidcBroker(adminClient, CHILD_IDP, PARENT_IDP, suiteContext);
}
@Test
public void testErrorConditions() throws Exception {
RealmResource realm = adminClient.realms().realm(CHILD_IDP);
List<FederatedIdentityRepresentation> links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
ClientRepresentation client = adminClient.realms().realm(CHILD_IDP).clients().findByClientId("client-linking").get(0);
UriBuilder redirectUri = UriBuilder.fromUri(appPage.getInjectedUrl().toString())
.path("link")
.queryParam("response", "true");
UriBuilder directLinking = UriBuilder.fromUri(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth")
.path("realms/child/broker/{provider}/link")
.queryParam("client_id", "client-linking")
.queryParam("redirect_uri", redirectUri.build())
.queryParam("hash", Base64Url.encode("crap".getBytes()))
.queryParam("nonce", UUID.randomUUID().toString());
String linkUrl = directLinking
.build(PARENT_IDP).toString();
// test not logged in
navigateTo(linkUrl);
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
loginPage.login("child", "password");
Assert.assertTrue(driver.getCurrentUrl().contains("link_error=not_logged_in"));
logoutAll();
// now log in
navigateTo( appPage.getInjectedUrl() + "/hello");
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
loginPage.login("child", "password");
Assert.assertTrue(driver.getCurrentUrl().startsWith(appPage.getInjectedUrl() + "/hello"));
Assert.assertTrue(driver.getPageSource().contains("Unknown request:"));
// now test CSRF with bad hash.
navigateTo(linkUrl);
Assert.assertTrue(driver.getPageSource().contains("We're sorry..."));
logoutAll();
// now log in again with client that does not have scope
String accountId = adminClient.realms().realm(CHILD_IDP).clients().findByClientId(ACCOUNT_MANAGEMENT_CLIENT_ID).get(0).getId();
RoleRepresentation manageAccount = adminClient.realms().realm(CHILD_IDP).clients().get(accountId).roles().get(MANAGE_ACCOUNT).toRepresentation();
RoleRepresentation manageLinks = adminClient.realms().realm(CHILD_IDP).clients().get(accountId).roles().get(MANAGE_ACCOUNT_LINKS).toRepresentation();
RoleRepresentation userRole = adminClient.realms().realm(CHILD_IDP).roles().get("user").toRepresentation();
client.setFullScopeAllowed(false);
ClientResource clientResource = adminClient.realms().realm(CHILD_IDP).clients().get(client.getId());
clientResource.update(client);
List<RoleRepresentation> roles = new LinkedList<>();
roles.add(userRole);
clientResource.getScopeMappings().realmLevel().add(roles);
navigateTo( appPage.getInjectedUrl() + "/hello");
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
loginPage.login("child", "password");
Assert.assertTrue(driver.getCurrentUrl().startsWith(appPage.getInjectedUrl() + "/hello"));
Assert.assertTrue(driver.getPageSource().contains("Unknown request:"));
UriBuilder linkBuilder = UriBuilder.fromUri(appPage.getInjectedUrl().toString())
.path("link");
String clientLinkUrl = linkBuilder.clone()
.queryParam("realm", CHILD_IDP)
.queryParam("provider", PARENT_IDP).build().toString();
navigateTo(clientLinkUrl);
Assert.assertTrue(driver.getCurrentUrl().contains("error=not_allowed"));
logoutAll();
// add MANAGE_ACCOUNT_LINKS scope should pass.
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
roles = new LinkedList<>();
roles.add(manageLinks);
clientResource.getScopeMappings().clientLevel(accountId).add(roles);
navigateTo(clientLinkUrl);
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
loginPage.login("child", "password");
Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
loginPage.login(PARENT_USERNAME, "password");
Assert.assertTrue(driver.getCurrentUrl().startsWith(linkBuilder.toTemplate()));
Assert.assertTrue(driver.getPageSource().contains("Account Linked"));
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertFalse(links.isEmpty());
realm.users().get(childUserId).removeFederatedIdentity(PARENT_IDP);
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
clientResource.getScopeMappings().clientLevel(accountId).remove(roles);
logoutAll();
navigateTo(clientLinkUrl);
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
loginPage.login("child", "password");
Assert.assertTrue(driver.getCurrentUrl().contains("link_error=not_allowed"));
logoutAll();
// add MANAGE_ACCOUNT scope should pass
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
roles = new LinkedList<>();
roles.add(manageAccount);
clientResource.getScopeMappings().clientLevel(accountId).add(roles);
navigateTo(clientLinkUrl);
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
loginPage.login("child", "password");
Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
loginPage.login(PARENT_USERNAME, "password");
Assert.assertTrue(driver.getCurrentUrl().startsWith(linkBuilder.toTemplate()));
Assert.assertTrue(driver.getPageSource().contains("Account Linked"));
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertFalse(links.isEmpty());
realm.users().get(childUserId).removeFederatedIdentity(PARENT_IDP);
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
clientResource.getScopeMappings().clientLevel(accountId).remove(roles);
logoutAll();
navigateTo(clientLinkUrl);
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
loginPage.login("child", "password");
Assert.assertTrue(driver.getCurrentUrl().contains("link_error=not_allowed"));
logoutAll();
// undo fullScopeAllowed
client = adminClient.realms().realm(CHILD_IDP).clients().findByClientId("client-linking").get(0);
client.setFullScopeAllowed(true);
clientResource.update(client);
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
logoutAll();
}
@Test
public void testAccountLink() throws Exception {
RealmResource realm = adminClient.realms().realm(CHILD_IDP);
List<FederatedIdentityRepresentation> links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
UriBuilder linkBuilder = UriBuilder.fromUri(appPage.getInjectedUrl().toString())
.path("link");
String linkUrl = linkBuilder.clone()
.queryParam("realm", CHILD_IDP)
.queryParam("provider", PARENT_IDP).build().toString();
System.out.println("linkUrl: " + linkUrl);
navigateTo(linkUrl);
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
Assert.assertTrue(driver.getPageSource().contains(PARENT_IDP));
loginPage.login("child", "password");
Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
loginPage.login(PARENT_USERNAME, "password");
System.out.println("After linking: " + driver.getCurrentUrl());
System.out.println(driver.getPageSource());
Assert.assertTrue(driver.getCurrentUrl().startsWith(linkBuilder.toTemplate()));
Assert.assertTrue(driver.getPageSource().contains("Account Linked"));
OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest(CHILD_IDP, "child", "password", null, "client-linking", "password");
Assert.assertNotNull(response.getAccessToken());
Assert.assertNull(response.getError());
Client httpClient = ClientBuilder.newClient();
String firstToken = getToken(response, httpClient);
Assert.assertNotNull(firstToken);
navigateTo(linkUrl);
Assert.assertTrue(driver.getPageSource().contains("Account Linked"));
String nextToken = getToken(response, httpClient);
Assert.assertNotNull(nextToken);
Assert.assertNotEquals(firstToken, nextToken);
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertFalse(links.isEmpty());
realm.users().get(childUserId).removeFederatedIdentity(PARENT_IDP);
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
logoutAll();
}
private String getToken(OAuthClient.AccessTokenResponse response, Client httpClient) throws Exception {
String idpToken = httpClient.target(OAuthClient.AUTH_SERVER_ROOT)
.path("realms")
.path("child/broker")
.path(PARENT_IDP)
.path("token")
.request()
.header("Authorization", "Bearer " + response.getAccessToken())
.get(String.class);
AccessTokenResponse res = JsonSerialization.readValue(idpToken, AccessTokenResponse.class);
return res.getToken();
}
public void logoutAll() {
String logoutUri = OIDCLoginProtocolService.logoutUrl(authServerPage.createUriBuilder()).build(CHILD_IDP).toString();
navigateTo(logoutUri);
logoutUri = OIDCLoginProtocolService.logoutUrl(authServerPage.createUriBuilder()).build(PARENT_IDP).toString();
navigateTo(logoutUri);
}
@Test
public void testLinkOnlyProvider() throws Exception {
RealmResource realm = adminClient.realms().realm(CHILD_IDP);
IdentityProviderRepresentation rep = realm.identityProviders().get(PARENT_IDP).toRepresentation();
rep.setLinkOnly(true);
realm.identityProviders().get(PARENT_IDP).update(rep);
try {
List<FederatedIdentityRepresentation> links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
UriBuilder linkBuilder = UriBuilder.fromUri(appPage.getInjectedUrl().toString())
.path("link");
String linkUrl = linkBuilder.clone()
.queryParam("realm", CHILD_IDP)
.queryParam("provider", PARENT_IDP).build().toString();
navigateTo(linkUrl);
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
// should not be on login page. This is what we are testing
Assert.assertFalse(driver.getPageSource().contains(PARENT_IDP));
// now test that we can still link.
loginPage.login("child", "password");
Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
loginPage.login(PARENT_USERNAME, "password");
System.out.println("After linking: " + driver.getCurrentUrl());
System.out.println(driver.getPageSource());
Assert.assertTrue(driver.getCurrentUrl().startsWith(linkBuilder.toTemplate()));
Assert.assertTrue(driver.getPageSource().contains("Account Linked"));
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertFalse(links.isEmpty());
realm.users().get(childUserId).removeFederatedIdentity(PARENT_IDP);
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
logoutAll();
System.out.println("testing link-only attack");
navigateTo(linkUrl);
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
System.out.println("login page uri is: " + driver.getCurrentUrl());
// ok, now scrape the code from page
String pageSource = driver.getPageSource();
String action = ActionURIUtils.getActionURIFromPageSource(pageSource);
System.out.println("action uri: " + action);
Map<String, String> queryParams = ActionURIUtils.parseQueryParamsFromActionURI(action);
System.out.println("query params: " + queryParams);
// now try and use the code to login to remote link-only idp
String uri = "/auth/realms/child/broker/parent-idp/login";
uri = UriBuilder.fromUri(AuthServerTestEnricher.getAuthServerContextRoot())
.path(uri)
.queryParam(OAuth2Constants.CODE, queryParams.get(OAuth2Constants.CODE))
.queryParam(Constants.CLIENT_ID, queryParams.get(Constants.CLIENT_ID))
.build().toString();
System.out.println("hack uri: " + uri);
navigateTo(uri);
Assert.assertTrue(driver.getPageSource().contains("Could not send authentication request to identity provider."));
} finally {
rep.setLinkOnly(false);
realm.identityProviders().get(PARENT_IDP).update(rep);
}
}
@Test
public void testAccountNotLinkedAutomatically() throws Exception {
RealmResource realm = adminClient.realms().realm(CHILD_IDP);
List<FederatedIdentityRepresentation> links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
// Login to account mgmt first
profilePage.open(CHILD_IDP);
WaitUtils.waitForPageToLoad(driver);
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
loginPage.login("child", "password");
profilePage.assertCurrent();
// Now in another tab, open login screen with "prompt=login" . Login screen will be displayed even if I have SSO cookie
UriBuilder linkBuilder = UriBuilder.fromUri(appPage.getInjectedUrl().toString())
.path("nosuch");
String linkUrl = linkBuilder.clone()
.queryParam(OIDCLoginProtocol.PROMPT_PARAM, OIDCLoginProtocol.PROMPT_VALUE_LOGIN)
.build().toString();
navigateTo(linkUrl);
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
loginPage.clickSocial(PARENT_IDP);
Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
loginPage.login(PARENT_USERNAME, "password");
// Test I was not automatically linked.
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
loginUpdateProfilePage.assertCurrent();
loginUpdateProfilePage.update("Joe", "Doe", "[email protected]");
errorPage.assertCurrent();
Assert.assertEquals("You are already authenticated as different user 'child' in this session. Please logout first.", errorPage.getError());
logoutAll();
// Remove newly created user
String newUserId = ApiUtil.findUserByUsername(realm, "parent").getId();
getCleanup("child").addUserId(newUserId);
}
@Test
public void testAccountLinkingExpired() throws Exception {
RealmResource realm = adminClient.realms().realm(CHILD_IDP);
List<FederatedIdentityRepresentation> links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
// Login to account mgmt first
profilePage.open(CHILD_IDP);
WaitUtils.waitForPageToLoad(driver);
Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
loginPage.login("child", "password");
profilePage.assertCurrent();
// Now in another tab, request account linking
UriBuilder linkBuilder = UriBuilder.fromUri(appPage.getInjectedUrl().toString())
.path("link");
String linkUrl = linkBuilder.clone()
.queryParam("realm", CHILD_IDP)
.queryParam("provider", PARENT_IDP).build().toString();
navigateTo(linkUrl);
Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
// Logout "child" userSession in the meantime (for example through admin request)
realm.logoutAll();
// Finish login on parent.
loginPage.login(PARENT_USERNAME, "password");
// Test I was not automatically linked
links = realm.users().get(childUserId).getFederatedIdentity();
Assert.assertTrue(links.isEmpty());
errorPage.assertCurrent();
Assert.assertEquals("Requested broker account linking, but current session is no longer valid.", errorPage.getError());
logoutAll();
}
private void navigateTo(String uri) {
driver.navigate().to(uri);
WaitUtils.waitForPageToLoad(driver);
}
}
| KEYCLOAK-5340 - Testsuite compilation error - waitForPageToLoad without driver param
| testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/AbstractLinkAndExchangeTest.java | KEYCLOAK-5340 - Testsuite compilation error - waitForPageToLoad without driver param | <ide><path>estsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/AbstractLinkAndExchangeTest.java
<ide>
<ide> // Login to account mgmt first
<ide> profilePage.open(CHILD_IDP);
<del> WaitUtils.waitForPageToLoad(driver);
<add> WaitUtils.waitForPageToLoad();
<ide>
<ide> Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
<ide> loginPage.login("child", "password");
<ide>
<ide> // Login to account mgmt first
<ide> profilePage.open(CHILD_IDP);
<del> WaitUtils.waitForPageToLoad(driver);
<add> WaitUtils.waitForPageToLoad();
<ide>
<ide> Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
<ide> loginPage.login("child", "password");
<ide>
<ide> private void navigateTo(String uri) {
<ide> driver.navigate().to(uri);
<del> WaitUtils.waitForPageToLoad(driver);
<add> WaitUtils.waitForPageToLoad();
<ide> }
<ide>
<ide> |
|
Java | mit | e25f91b03e12f5a05f5a748359a3374d82f85380 | 0 | dalton/P2P-Project,dalton/P2P-Project | package edu.ufl.cise.cnt5106c.log;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Giacomo Benincasa ([email protected])
*/
public class LogHelper {
private static final LogHelper _log = new LogHelper (Logger.getLogger("CNT5106C"));
static {
// TODO: configure logger here
}
private final Logger _l;
LogHelper (Logger log) {
_l = log;
}
public static LogHelper getLogger () {
return _log;
}
public synchronized void info (String msg) {
_l.log(Level.INFO, msg);
}
public synchronized void severe (String msg) {
_l.log(Level.SEVERE, msg);
}
public synchronized void warning (String msg) {
_l.log(Level.WARNING, msg);
}
public synchronized void severe (Throwable e) {
_l.log(Level.SEVERE, stackTraceToString (e));
}
public synchronized void warning (Throwable e) {
_l.log(Level.WARNING, stackTraceToString (e));
}
private static String stackTraceToString (Throwable t) {
final Writer sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
return sw.toString();
}
}
| src/main/java/edu/ufl/cise/cnt5106c/log/LogHelper.java | package edu.ufl.cise.cnt5106c.log;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Giacomo Benincasa ([email protected])
*/
public class LogHelper {
private static final LogHelper _log = new LogHelper (Logger.getLogger("CNT5106C"));
static {
// TODO: configure logger here
}
private final Logger _l;
LogHelper (Logger log) {
_l = log;
}
public static LogHelper getLogger () {
return _log;
}
public synchronized void info (String msg) {
_l.log(Level.INFO, msg);
}
public synchronized void severe (String msg) {
_l.log(Level.SEVERE, msg);
}
public synchronized void warning (String msg) {
_l.log(Level.WARNING, msg);
}
public synchronized void severe (Throwable e) {
_l.log(Level.SEVERE, stackTraceToString (e));
}
public synchronized void warning (Throwable e) {
_l.log(Level.WARNING, stackTraceToString (e));
}
private static String stackTraceToString (Throwable t) {
// TODO: imlement this
return new String ();
}
}
| Implemented stackTraceToString(). | src/main/java/edu/ufl/cise/cnt5106c/log/LogHelper.java | Implemented stackTraceToString(). | <ide><path>rc/main/java/edu/ufl/cise/cnt5106c/log/LogHelper.java
<ide> package edu.ufl.cise.cnt5106c.log;
<ide>
<add>import java.io.PrintWriter;
<add>import java.io.StringWriter;
<add>import java.io.Writer;
<ide> import java.util.logging.Level;
<ide> import java.util.logging.Logger;
<ide>
<ide> }
<ide>
<ide> private static String stackTraceToString (Throwable t) {
<del> // TODO: imlement this
<del> return new String ();
<add> final Writer sw = new StringWriter();
<add> t.printStackTrace(new PrintWriter(sw));
<add> return sw.toString();
<ide> }
<ide> } |
|
Java | apache-2.0 | c409523b857f1d8474a03afda0241890e480f6e6 | 0 | doortts/forked-for-history,ihoneymon/yobi,ChangsungKim/TestRepository01,doortts/fork-yobi,oolso/yobi,oolso/yobi,violetag/demo,ihoneymon/yobi,yona-projects/yona,oolso/yobi,violetag/demo,Limseunghwan/oss,doortts/fork-yobi,yona-projects/yona,doortts/fork-yobi,doortts/forked-for-history,ihoneymon/yobi,brainagenet/yobi,brainagenet/yobi,ahb0327/yobi,ahb0327/yobi,naver/yobi,ahb0327/yobi,Limseunghwan/oss,yona-projects/yona,doortts/forked-for-history,yona-projects/yona,bloodybear/yona,bloodybear/yona,brainagenet/yobi,bloodybear/yona,doortts/fork-yobi,ChangsungKim/TestRepository01,bloodybear/yona,naver/yobi,Limseunghwan/oss,naver/yobi | package models.enumeration;
public enum IssueState {
ENROLLED("enrolled"), ASSIGNED("assigned"), SOLVED("solved"), FINISHED("finished");
private String state;
IssueState(String state) {
this.state = state;
}
public String state() {
return this.state;
}
public static IssueState getValue(String value) {
for (IssueState issueState : IssueState.values()) {
if (issueState.state().equals(value)) {
return issueState;
}
}
return IssueState.ENROLLED;
}
}
| app/models/enumeration/IssueState.java | package models.enumeration;
public enum IssueState {
OPEN("open"), CLOSED("closed"), ALL("all");
private String state;
IssueState(String state) {
this.state = state;
}
public String state() {
return this.state;
}
public static IssueState getValue(String value) {
for (IssueState issueState : IssueState.values()) {
if (issueState.state().equals(value)) {
return issueState;
}
}
return IssueState.ALL;
}
}
| Change IssueState enum type
| app/models/enumeration/IssueState.java | Change IssueState enum type | <ide><path>pp/models/enumeration/IssueState.java
<ide> package models.enumeration;
<ide>
<ide> public enum IssueState {
<del> OPEN("open"), CLOSED("closed"), ALL("all");
<add> ENROLLED("enrolled"), ASSIGNED("assigned"), SOLVED("solved"), FINISHED("finished");
<ide> private String state;
<ide>
<ide> IssueState(String state) {
<ide> return issueState;
<ide> }
<ide> }
<del> return IssueState.ALL;
<add> return IssueState.ENROLLED;
<ide> }
<ide> } |
|
Java | mit | 689bf3fff60f722828465af022d8fb20ac36904e | 0 | CS2103AUG2016-T11-C3/main,CS2103AUG2016-T11-C3/main | package seedu.address.model;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.model.task.ReadOnlyTask;
import seedu.address.model.task.Task;
import seedu.address.model.task.UniqueTaskList;
import seedu.address.model.undo.UndoTask;
import java.util.Set;
/**
* The API of the Model component.
*/
public interface Model {
/** Clears existing backing model and replaces with the provided new data. */
void resetData(ReadOnlyTaskBook newData);
/** Returns the TaskBook */
ReadOnlyTaskBook getTaskBook();
/** Deletes the given task. */
void deleteTask(ReadOnlyTask target) throws UniqueTaskList.TaskNotFoundException;
/** Adds the given task */
void addTask(Task toAdd) throws UniqueTaskList.DuplicateTaskException;
/** Adds the given undo */
void addUndo(String command, ReadOnlyTask data);
/** Adds the given undo */
void addUndo(String command, ReadOnlyTask postData, ReadOnlyTask preData);
/** Marks the given task as completed */
void completeTask(ReadOnlyTask target) throws UniqueTaskList.TaskNotFoundException;
/** Marks the given task as uncompleted */
void uncompleteTask(ReadOnlyTask target) throws UniqueTaskList.TaskNotFoundException;
/** Undoes the last reversible action */
UndoTask undoTask();
/** Returns the filtered dated task list as an {@code UnmodifiableObservableList<ReadOnlyTask>} */
UnmodifiableObservableList<ReadOnlyTask> getFilteredDatedTaskList();
/** Returns the filtered undated task list as an {@code UnmodifiableObservableList<ReadOnlyTask>} */
UnmodifiableObservableList<ReadOnlyTask> getFilteredUndatedTaskList();
/** Updates the filter of the filtered tasks list to show all persons */
void updateFilteredListToShowAll();
/** Updates the filter of the filtered tasks list to filter by the given keywords*/
void updateFilteredTaskListByKeywords(Set<String> keywords);
/** Updates the filter of the filtered tasks list to filter by the given keyword (od/done)*/
void updateFilteredTaskListByStatus(String... keyword);
/** Marks task as overdue as compared to system current Datetime */
void overdueTask(ReadOnlyTask target) throws UniqueTaskList.TaskNotFoundException;
}
| src/main/java/seedu/address/model/Model.java | package seedu.address.model;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.model.task.ReadOnlyTask;
import seedu.address.model.task.Task;
import seedu.address.model.task.UniqueTaskList;
import seedu.address.model.undo.UndoTask;
import java.util.Set;
/**
* The API of the Model component.
*/
public interface Model {
/** Clears existing backing model and replaces with the provided new data. */
void resetData(ReadOnlyTaskBook newData);
/** Returns the TaskBook */
ReadOnlyTaskBook getTaskBook();
/** Deletes the given task. */
void deleteTask(ReadOnlyTask target) throws UniqueTaskList.TaskNotFoundException;
/** Adds the given task */
void addTask(Task toAdd) throws UniqueTaskList.DuplicateTaskException;
/** Adds the given undo */
void addUndo(String command, ReadOnlyTask data);
/** Adds the given undo */
void addUndo(String command, ReadOnlyTask postData, ReadOnlyTask preData);
/** Marks the given task as completed */
void completeTask(ReadOnlyTask target) throws UniqueTaskList.TaskNotFoundException;
/** Marks the given task as uncompleted */
void uncompleteTask(ReadOnlyTask target) throws UniqueTaskList.TaskNotFoundException;
/** Undoes the last reversible action */
UndoTask undoTask();
/** Returns the filtered dated task list as an {@code UnmodifiableObservableList<ReadOnlyTask>} */
UnmodifiableObservableList<ReadOnlyTask> getFilteredDatedTaskList();
/** Returns the filtered undated task list as an {@code UnmodifiableObservableList<ReadOnlyTask>} */
UnmodifiableObservableList<ReadOnlyTask> getFilteredUndatedTaskList();
/** Updates the filter of the filtered tasks list to show all persons */
void updateFilteredListToShowAll();
/** Updates the filter of the filtered tasks list to filter by the given keywords*/
void updateFilteredTaskList(Set<String> keywords);
/** Updates the filter of the filtered tasks list to filter by the given keyword (od/done)*/
void updateFilteredTaskList(String... keyword);
/** Marks task as overdue as compared to system current Datetime */
void overdueTask(ReadOnlyTask target) throws UniqueTaskList.TaskNotFoundException;
}
| Model: refactor filtering methods to more intuitive names
| src/main/java/seedu/address/model/Model.java | Model: refactor filtering methods to more intuitive names | <ide><path>rc/main/java/seedu/address/model/Model.java
<ide> void updateFilteredListToShowAll();
<ide>
<ide> /** Updates the filter of the filtered tasks list to filter by the given keywords*/
<del> void updateFilteredTaskList(Set<String> keywords);
<add> void updateFilteredTaskListByKeywords(Set<String> keywords);
<ide>
<ide> /** Updates the filter of the filtered tasks list to filter by the given keyword (od/done)*/
<del> void updateFilteredTaskList(String... keyword);
<add> void updateFilteredTaskListByStatus(String... keyword);
<ide>
<ide> /** Marks task as overdue as compared to system current Datetime */
<ide> void overdueTask(ReadOnlyTask target) throws UniqueTaskList.TaskNotFoundException; |
|
Java | mit | e517576307aea546f903ed60738f26567a66cfec | 0 | BP2014W1/JEngine,bptlab/JEngine,bptlab/JEngine,BP2014W1/JEngine,BP2014W1/JEngine,bptlab/JEngine,BP2014W1/JEngine,bptlab/JEngine | package de.uni_potsdam.hpi.bpt.bp2014.jcore;
import javax.ws.rs.core.Application;
import de.uni_potsdam.hpi.bpt.bp2014.database.DbObject;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import static org.junit.Assert.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
public class RestConnection2Test extends JerseyTest {
/* #############################################################################
*
* TEST SETUP
*
* #############################################################################
*/
@Before
public void setUpDatabase() {
DbObject dbObject = new DbObject();
dbObject.executeUpdateStatement("DROP DATABASE JEngineV2");
dbObject.executeUpdateStatement("CREATE DATABASE JEngineV2");
Document sqlFile = getDocumentFromSQLFile(new File("src/main/resources/JEngineV2.sql"));
}
@Override
protected Application configure() {
return new ResourceConfig(de.uni_potsdam.hpi.bpt.bp2014.jcore.RestConnection.class);
}
/* #############################################################################
*
* HTTP GET REQUEST
*
* #############################################################################
*/
@Test
public void testGetAllScenarios(){
final Response test = target("/interface/v1/en/scenario/0/").request().get();
assertEquals("{\"ids\":[1,2,3,100,101,103,105,111,113,114,115,116,117,118,134]}", test.readEntity(String.class));
}
@Test
public void testGetScenarioInstances(){
final Response test = target("/interface/v1/en/scenario/1/instance/0/").request().get();
assertEquals("{\"ids\":[47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,92,94,95,97,99,101,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,212,214,215,216,217,218,219,220,221,222,223,224,226,228,244,246,248,250,252,255,257,259,261,262,263,265,266,270,279,281,282,284,285,286,294,296,309,310,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,333,334,346,348,349,351,353,356,358,359,361,363,365,366,367,369,370,371,372,373,374,375,376,377,378,379,380,381,383,385,386,387,388,390,392,394,396,398,400,402,404,406,408,409,410,411,412,413,415,416,417,418,419,420,421,422,430,433,438,441,444,445,446,448,449,452,456,459,460,461,464,467,470,473,476,479,482,485,488,491,492,493,494,497,505,515,519,527,531,552,561,563,572,582,590,598,605,612,614,621,628,635,642,649,656,663,670,677,684,691,698,705,712,719,726,733,740,747,754,756,763,770,777,784,791]}", test.readEntity(String.class));
}
@Test
public void testGetAllActivitiesForScenarioInstance(){
final Response test = target("/interface/v1/en/scenario/1/instance/47/activityinstance/0/").request().get();
assertEquals("{\"ids\":[5,4,16],\"label\":{\"16\":\"ActivityFragment4\",\"4\":\"Activity1Fragment2\",\"5\":\"Activity2Fragment1\"}}", test.readEntity(String.class));
}
@Test
public void testGetAllDataobjectForScenarioInstance(){
final Response test = target("/interface/v1/en/scenario/1/instance/328/dataobject/0/").request().get();
assertEquals("{\"ids\":[1,2],\"label\":{\"1\":\"bearbeitet\",\"2\":\"init\"}}", test.readEntity(String.class));
}
/* #############################################################################
*
* HTTP POST REQUEST
*
* #############################################################################
*/
@Test
public void testPostActivityStatusUpdate(){
//final Response test = target("/interface/v1/en/scenario/1/instance/0/activityinstance/319/?status=enabled").request().post();
//assertEquals("true", test.readEntity(String.class));
}
@Test
public void testPostNewInstanceForScenario(){
//final Response test = target("/interface/v1/en/scenario/1/").request().post();
//assertEquals("123", test.readEntity(String.class));
}
private Document getDocumentFromSQLFile(final File sql) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(sql);
doc.getDocumentElement().normalize();
return doc;
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
return null;
}
}
| src/test/java/de/uni_potsdam/hpi/bpt/bp2014/jcore/RestConnection2Test.java | package de.uni_potsdam.hpi.bpt.bp2014.jcore;
import javax.ws.rs.core.Application;
import de.uni_potsdam.hpi.bpt.bp2014.database.DbObject;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import static org.junit.Assert.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
public class RestConnection2Test extends JerseyTest {
/* #############################################################################
*
* TEST SETUP
*
* #############################################################################
*/
@Before
public void setUpDatabase() {
DbObject dbObject = new DbObject();
dbObject.executeUpdateStatement("DROP DATABASE JEngineV2");
dbObject.executeUpdateStatement("CREATE DATABASE JEngineV2");
Document sqlFile = getDocumentFromSQLFile(new File("src/main/resources/JEngineV2.sql"));
}
@Override
protected Application configure() {
return new ResourceConfig(de.uni_potsdam.hpi.bpt.bp2014.jcore.RestConnection.class);
}
/* #############################################################################
*
* HTTP GET REQUEST
*
* #############################################################################
*/
@Test
public void testGetAllScenarios(){
final Response test = target("/interface/v1/en/scenario/0/").request().get();
assertEquals("{\"ids\":[1,2,3,100,101,103,105,111,113,114,115,116,117,118,134]}", test.readEntity(String.class));
}
@Test
public void testGetScenarioInstances(){
final Response test = target("/interface/v1/en/scenario/1/instance/0/").request().get();
assertEquals("{\"ids\":[47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,92,94,95,97,99,101,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,212,214,215,216,217,218,219,220,221,222,223,224,226,228,244,246,248,250,252,255,257,259,261,262,263,265,266,270,279,281,282,284,285,286,294,296,309,310,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,333,334,346,348,349,351,353,356,358,359,361,363,365,366,367,369,370,371,372,373,374,375,376,377,378,379,380,381,383,385,386,387,388,390,392,394,396,398,400,402,404,406,408,409,410,411,412,413,415,416,417,418,419,420,421,422,430,433,438,441,444,445,446,448,449,452,456,459,460,461,464,467,470,473,476,479,482,485,488,491,492,493,494,497,505,515,519,527,531,552,561,563,572,582,590,598,605,612,614,621,628,635,642,649,656,663,670,677,684,691,698,705,712,719,726,733,740,747,754,756,763,770,777,784,791]}", test.readEntity(String.class));
}
@Test
public void testGetAllActivitiesForScenarioInstance(){
final Response test = target("/interface/v1/en/scenario/1/instance/47/activityinstance/0/").request().get();
assertEquals("{\"ids\":[1,2,3,100,101,103,105,111,113,114,115,116,117,118,134]}", test.readEntity(String.class));
}
@Test
public void testGetAllDataobjectForScenarioInstance(){
final Response test = target("/interface/v1/en/scenario/0/").request().get();
assertEquals("{\"ids\":[1,2,3,100,101,103,105,111,113,114,115,116,117,118,134]}", test.readEntity(String.class));
}
/* #############################################################################
*
* HTTP POST REQUEST
*
* #############################################################################
*/
@Test
public void testPostActivityStatusUpdate(){
//final Response test = target("/interface/v1/en/scenario/1/instance/0/activityinstance/319/?status=enabled").request().post();
//assertEquals("true", test.readEntity(String.class));
}
@Test
public void testPostNewInstanceForScenario(){
//final Response test = target("/interface/v1/en/scenario/1/").request().post();
//assertEquals("123", test.readEntity(String.class));
}
private Document getDocumentFromSQLFile(final File sql) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(sql);
doc.getDocumentElement().normalize();
return doc;
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
return null;
}
}
| status quo
| src/test/java/de/uni_potsdam/hpi/bpt/bp2014/jcore/RestConnection2Test.java | status quo | <ide><path>rc/test/java/de/uni_potsdam/hpi/bpt/bp2014/jcore/RestConnection2Test.java
<ide> @Test
<ide> public void testGetAllActivitiesForScenarioInstance(){
<ide> final Response test = target("/interface/v1/en/scenario/1/instance/47/activityinstance/0/").request().get();
<del> assertEquals("{\"ids\":[1,2,3,100,101,103,105,111,113,114,115,116,117,118,134]}", test.readEntity(String.class));
<add> assertEquals("{\"ids\":[5,4,16],\"label\":{\"16\":\"ActivityFragment4\",\"4\":\"Activity1Fragment2\",\"5\":\"Activity2Fragment1\"}}", test.readEntity(String.class));
<ide> }
<ide>
<ide> @Test
<ide> public void testGetAllDataobjectForScenarioInstance(){
<del> final Response test = target("/interface/v1/en/scenario/0/").request().get();
<del> assertEquals("{\"ids\":[1,2,3,100,101,103,105,111,113,114,115,116,117,118,134]}", test.readEntity(String.class));
<add> final Response test = target("/interface/v1/en/scenario/1/instance/328/dataobject/0/").request().get();
<add> assertEquals("{\"ids\":[1,2],\"label\":{\"1\":\"bearbeitet\",\"2\":\"init\"}}", test.readEntity(String.class));
<ide> }
<ide>
<ide> /* ############################################################################# |
|
Java | apache-2.0 | 601a5e687dc1caab355d6572dd19f8e570901cda | 0 | aldaris/wicket,topicusonderwijs/wicket,freiheit-com/wicket,aldaris/wicket,apache/wicket,astrapi69/wicket,Servoy/wicket,klopfdreh/wicket,dashorst/wicket,AlienQueen/wicket,apache/wicket,freiheit-com/wicket,topicusonderwijs/wicket,astrapi69/wicket,freiheit-com/wicket,apache/wicket,dashorst/wicket,mafulafunk/wicket,mosoft521/wicket,mosoft521/wicket,selckin/wicket,selckin/wicket,bitstorm/wicket,zwsong/wicket,AlienQueen/wicket,bitstorm/wicket,klopfdreh/wicket,zwsong/wicket,AlienQueen/wicket,Servoy/wicket,topicusonderwijs/wicket,mafulafunk/wicket,bitstorm/wicket,zwsong/wicket,freiheit-com/wicket,zwsong/wicket,freiheit-com/wicket,mosoft521/wicket,apache/wicket,klopfdreh/wicket,bitstorm/wicket,martin-g/wicket-osgi,selckin/wicket,mosoft521/wicket,AlienQueen/wicket,bitstorm/wicket,dashorst/wicket,martin-g/wicket-osgi,martin-g/wicket-osgi,klopfdreh/wicket,aldaris/wicket,astrapi69/wicket,aldaris/wicket,Servoy/wicket,topicusonderwijs/wicket,apache/wicket,selckin/wicket,topicusonderwijs/wicket,selckin/wicket,dashorst/wicket,mosoft521/wicket,dashorst/wicket,aldaris/wicket,astrapi69/wicket,AlienQueen/wicket,klopfdreh/wicket,Servoy/wicket,mafulafunk/wicket,Servoy/wicket | /*
* $Id: HeaderContributor.java 4855 2006-03-11 12:57:08 -0800 (Sat, 11 Mar 2006)
* jdonnerstag $ $Revision$ $Date: 2006-03-11 12:57:08 -0800 (Sat, 11 Mar
* 2006) $
*
* ==============================================================================
* 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 wicket.behavior;
import java.util.ArrayList;
import java.util.List;
import wicket.Application;
import wicket.RequestCycle;
import wicket.Response;
import wicket.markup.html.IHeaderContributor;
import wicket.markup.html.IHeaderResponse;
import wicket.markup.html.PackageResourceReference;
import wicket.model.AbstractReadOnlyModel;
import wicket.protocol.http.WebRequestCycle;
import wicket.util.string.AppendingStringBuffer;
import wicket.util.string.JavascriptUtils;
/**
* A {@link wicket.behavior.AbstractHeaderContributor} behavior that is
* specialized on package resources. If you use this class, you have to
* pre-register the resources you want to contribute. A shortcut for common
* cases is to call {@link #forCss(Class, String)} to contribute a package css
* file or {@link #forJavaScript(Class, String)} to contribute a packaged
* javascript file. For instance:
*
* <pre>
* add(HeaderContributor.forCss(MyPanel.class, "mystyle.css"));
* </pre>
*
* @author Eelco Hillenius
*/
// TODO Cache pattern results, at least the ones that were fetched by callin the
// javascript or css methods. The cache could be put in an application scoped
// meta data object to avoid the use of a static map
public class HeaderContributor extends AbstractHeaderContributor
{
/**
* Contributes a reference to a javascript file relative to the context
* path.
*/
public static final class JavaScriptHeaderContributor extends StringHeaderContributor
{
private static final long serialVersionUID = 1L;
/**
* Construct.
*
* @param location
* the location of the CSS file relative to the context path.
*/
public JavaScriptHeaderContributor(final String location)
{
super(new AbstractReadOnlyModel<String>()
{
private static final long serialVersionUID = 1L;
private String path = null;
@Override
public String getObject()
{
if (path == null)
{
String contextPath = Application.get().getApplicationSettings()
.getContextPath();
if (contextPath == null)
{
contextPath = ((WebRequestCycle)RequestCycle.get()).getWebRequest()
.getContextPath();
if (contextPath == null)
{
contextPath = "";
}
}
AppendingStringBuffer b = new AppendingStringBuffer();
b.append("<script type=\"text/javascript\" src=\"");
b.append(contextPath);
if (!contextPath.endsWith("/") && !location.startsWith("/"))
{
b.append("/");
}
b.append((location != null) ? location : "");
b.append("\"></script>");
path = b.toString();
}
return path;
}
});
}
}
/**
* Contributes a reference to a css file relative to the context path.
*/
public static final class CSSHeaderContributor extends StringHeaderContributor
{
private static final long serialVersionUID = 1L;
/**
* Construct.
*
* @param location
* the location of the CSS file relative to the context path.
*/
public CSSHeaderContributor(final String location)
{
super(new AbstractReadOnlyModel<String>()
{
private static final long serialVersionUID = 1L;
private String path = null;
@Override
public String getObject()
{
if (path == null)
{
String contextPath = Application.get().getApplicationSettings()
.getContextPath();
if (contextPath == null)
{
contextPath = ((WebRequestCycle)RequestCycle.get()).getWebRequest()
.getContextPath();
if (contextPath == null)
{
contextPath = "";
}
}
AppendingStringBuffer b = new AppendingStringBuffer();
b.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"");
b.append(contextPath);
if (!contextPath.endsWith("/") && !location.startsWith("/"))
{
b.append("/");
}
b.append((location != null) ? location : "");
b.append("\"></link>");
path = b.toString();
}
return path;
}
});
}
}
/**
* prints a css resource reference.
*/
public static final class CSSReferenceHeaderContributor
extends
PackageResourceReferenceHeaderContributor
{
private static final long serialVersionUID = 1L;
/**
* Construct.
*
* @param scope
* The scope of the reference (typically the calling class)
* @param name
* The name of the reference.
*/
public CSSReferenceHeaderContributor(Class scope, String name)
{
super(scope, name);
}
/**
* @see wicket.markup.html.IHeaderContributor#renderHead(wicket.Response)
*/
public void renderHead(IHeaderResponse headerResponse)
{
Response response = headerResponse.getResponse();
final CharSequence url = RequestCycle.get().urlFor(getPackageResourceReference());
response.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"");
response.write(url);
response.println("\"></link>");
}
}
/**
* prints a javascript resource reference.
*/
public static final class JavaScriptReferenceHeaderContributor
extends
PackageResourceReferenceHeaderContributor
{
private static final long serialVersionUID = 1L;
/**
* Construct.
*
* @param scope
* The scope of the reference (typically the calling class)
* @param name
* The name .
*/
public JavaScriptReferenceHeaderContributor(Class scope, String name)
{
super(scope, name);
}
/**
* @see wicket.markup.html.IHeaderContributor#renderHead(wicket.Response)
*/
public void renderHead(IHeaderResponse response)
{
final CharSequence url = RequestCycle.get().urlFor(getPackageResourceReference());
JavascriptUtils.writeJavascriptUrl(response.getResponse(), url);
}
}
/**
* Wraps a {@link PackageResourceReference} and knows how to print a header
* statement based on that resource. Default implementations are
* {@link JavaScriptReferenceHeaderContributor} and
* {@link CSSReferenceHeaderContributor}, which print out javascript
* statements and css ref statements respectively.
*/
public static abstract class PackageResourceReferenceHeaderContributor
implements
IHeaderContributor
{
private static final long serialVersionUID = 1L;
/** the pre calculated hash code. */
private final int hash;
/** the package resource reference. */
private final PackageResourceReference packageResourceReference;
/**
* Construct.
*
* @param scope
* The scope of the reference (typically the calling class)
* @param name
* The name of the reference (typically the name of the
* packaged resource, like 'myscripts.js').
*/
public PackageResourceReferenceHeaderContributor(Class scope, String name)
{
this.packageResourceReference = new PackageResourceReference(scope, name);
int result = 17;
result = 37 * result + getClass().hashCode();
result = 37 * result + packageResourceReference.hashCode();
hash = result;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj)
{
if (obj.getClass().equals(getClass()))
{
PackageResourceReferenceHeaderContributor that = (PackageResourceReferenceHeaderContributor)obj;
return this.packageResourceReference.equals(that.packageResourceReference);
}
return false;
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
return hash;
}
/**
* Gets the package resource reference.
*
* @return the package resource reference
*/
protected final PackageResourceReference getPackageResourceReference()
{
return packageResourceReference;
}
}
private static final long serialVersionUID = 1L;
/**
* Returns a new instance of {@link HeaderContributor} with a header
* contributor that references a CSS file that lives in the web application
* directory and that is addressed relative to the context path.
*
* @param location
* The location of the css file relative to the context path
* @return the new header contributor instance
*/
public static final HeaderContributor forCss(final String location)
{
return new HeaderContributor(new CSSHeaderContributor(location));
}
/**
* Returns a new instance of {@link HeaderContributor} with a header
* contributor that references a JavaScript file that lives in the web
* application directory and that is addressed relative to the context path.
*
* @param location
* The location of the css file relative to the context path
* @return the new header contributor instance
*/
public static final HeaderContributor forJavaScript(final String location)
{
return new HeaderContributor(new JavaScriptHeaderContributor(location));
}
/**
* Returns a new instance of {@link HeaderContributor} with a header
* contributor that references a CSS file that lives in a package.
*
* @param scope
* The scope of the package resource (typically the class of the
* caller, or a class that lives in the package where the
* resource lives).
* @param path
* The path
* @return the new header contributor instance
*/
public static final HeaderContributor forCss(final Class scope, final String path)
{
return new HeaderContributor(new CSSReferenceHeaderContributor(scope, path));
}
/**
* Returns a new instance of {@link HeaderContributor} with a header
* contributor that references a java script file that lives in a package.
*
* @param scope
* The scope of the package resource (typically the class of the
* caller, or a class that lives in the package where the
* resource lives).
* @param path
* The path
* @return the new header contributor instance
*/
public static final HeaderContributor forJavaScript(final Class scope, final String path)
{
return new HeaderContributor(new JavaScriptReferenceHeaderContributor(scope, path));
}
/**
* set of resource references to contribute.
*/
private List<IHeaderContributor> headerContributors = null;
/**
* Construct.
*/
public HeaderContributor()
{
}
/**
* Construct with a single header contributor.
*
* @param headerContributor
* the header contributor
*/
public HeaderContributor(IHeaderContributor headerContributor)
{
headerContributors = new ArrayList<IHeaderContributor>(1);
headerContributors.add(headerContributor);
}
/**
* Adds a custom header contributor.
*
* @param headerContributor
* instance of {@link IHeaderContributor}
*/
public final void addContributor(final IHeaderContributor headerContributor)
{
checkHeaderContributors();
if (!headerContributors.contains(headerContributor))
{
headerContributors.add(headerContributor);
}
}
/**
* Adds a custom header contributor at the given position.
*
* @param index
* the position where the contributor should be added (e.g. 0 to
* put it in front of the rest).
* @param headerContributor
* instance of {@link IHeaderContributor}
*
* @throws IndexOutOfBoundsException
* if the index is out of range (index < 0 || index >
* size()).
*/
public final void addContributor(final int index, final IHeaderContributor headerContributor)
{
checkHeaderContributors();
if (!headerContributors.contains(headerContributor))
{
headerContributors.add(index, headerContributor);
}
}
/**
* Adds a reference to a css file that should be contributed to the page
* header.
*
* @param scope
* The scope of the package resource (typically the class of the
* caller, or a class that lives in the package where the
* resource lives).
* @param path
* The path
*/
public final void addCssReference(final Class scope, final String path)
{
addContributor(new CSSReferenceHeaderContributor(scope, path));
}
/**
* Adds a reference to a javascript file that should be contributed to the
* page header.
*
* @param scope
* The scope of the package resource (typically the class of the
* caller, or a class that lives in the package where the
* resource lives).
* @param path
* The path
*/
public final void addJavaScriptReference(final Class scope, final String path)
{
addContributor(new JavaScriptReferenceHeaderContributor(scope, path));
}
/**
* @see wicket.behavior.AbstractHeaderContributor#getHeaderContributors()
*/
@Override
public final IHeaderContributor[] getHeaderContributors()
{
if (headerContributors != null)
{
return headerContributors.toArray(new IHeaderContributor[headerContributors.size()]);
}
return null;
}
/**
* Create lazily to save memory.
*/
private void checkHeaderContributors()
{
if (headerContributors == null)
{
headerContributors = new ArrayList<IHeaderContributor>(1);
}
}
} | wicket/src/java/wicket/behavior/HeaderContributor.java | /*
* $Id: HeaderContributor.java 4855 2006-03-11 12:57:08 -0800 (Sat, 11 Mar 2006)
* jdonnerstag $ $Revision$ $Date: 2006-03-11 12:57:08 -0800 (Sat, 11 Mar
* 2006) $
*
* ==============================================================================
* 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 wicket.behavior;
import java.util.ArrayList;
import java.util.List;
import wicket.Application;
import wicket.RequestCycle;
import wicket.Response;
import wicket.markup.html.IHeaderContributor;
import wicket.markup.html.IHeaderResponse;
import wicket.markup.html.PackageResourceReference;
import wicket.model.AbstractReadOnlyModel;
import wicket.protocol.http.WebRequestCycle;
import wicket.util.string.AppendingStringBuffer;
import wicket.util.string.JavascriptUtils;
/**
* A {@link wicket.behavior.AbstractHeaderContributor} behavior that is
* specialized on package resources. If you use this class, you have to
* pre-register the resources you want to contribute. A shortcut for common
* cases is to call {@link #forCss(Class, String)} to contribute a package css
* file or {@link #forJavaScript(Class, String)} to contribute a packaged
* javascript file. For instance:
*
* <pre>
* add(HeaderContributor.forCss(MyPanel.class, "mystyle.css"));
* </pre>
*
* @author Eelco Hillenius
*/
// TODO Cache pattern results, at least the ones that were fetched by callin the
// javascript or css methods. The cache could be put in an application scoped
// meta data object to avoid the use of a static map
public class HeaderContributor extends AbstractHeaderContributor
{
/**
* Contributes a reference to a javascript file relative to the context
* path.
*/
public static final class JavaScriptHeaderContributor extends StringHeaderContributor
{
private static final long serialVersionUID = 1L;
/**
* Construct.
*
* @param location
* the location of the CSS file relative to the context path.
*/
public JavaScriptHeaderContributor(final String location)
{
super(new AbstractReadOnlyModel<String>()
{
private static final long serialVersionUID = 1L;
private String path = null;
@Override
public String getObject()
{
if (path == null)
{
String contextPath = Application.get().getApplicationSettings()
.getContextPath();
if (contextPath == null)
{
contextPath = ((WebRequestCycle)RequestCycle.get()).getWebRequest()
.getContextPath();
if (contextPath == null)
{
contextPath = "";
}
}
AppendingStringBuffer b = new AppendingStringBuffer();
b.append("<script type=\"text/javascript\" src=\"");
b.append(contextPath);
if (!contextPath.endsWith("/") && !location.startsWith("/"))
{
b.append("/");
}
b.append((location != null) ? location : "");
b.append("\"></script>");
path = b.toString();
}
return path;
}
});
}
}
/**
* Contributes a reference to a css file relative to the context path.
*/
public static final class CSSHeaderContributor extends StringHeaderContributor
{
private static final long serialVersionUID = 1L;
/**
* Construct.
*
* @param location
* the location of the CSS file relative to the context path.
*/
public CSSHeaderContributor(final String location)
{
super(new AbstractReadOnlyModel<String>()
{
private static final long serialVersionUID = 1L;
private String path = null;
@Override
public String getObject()
{
if (path == null)
{
String contextPath = Application.get().getApplicationSettings()
.getContextPath();
if (contextPath == null)
{
contextPath = ((WebRequestCycle)RequestCycle.get()).getWebRequest()
.getContextPath();
if (contextPath == null)
{
contextPath = "";
}
}
AppendingStringBuffer b = new AppendingStringBuffer();
b.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"");
b.append(contextPath);
if (!contextPath.endsWith("/") && !location.startsWith("/"))
{
b.append("/");
}
b.append((location != null) ? location : "");
b.append("\"></link>");
path = b.toString();
}
return path;
}
});
}
}
/**
* prints a css resource reference.
*/
public static final class CSSReferenceHeaderContributor
extends
PackageResourceReferenceHeaderContributor
{
private static final long serialVersionUID = 1L;
/**
* Construct.
*
* @param scope
* The scope of the reference (typically the calling class)
* @param name
* The name of the reference.
*/
public CSSReferenceHeaderContributor(Class scope, String name)
{
super(scope, name);
}
/**
* @see wicket.markup.html.IHeaderContributor#renderHead(wicket.Response)
*/
public void renderHead(IHeaderResponse headerResponse)
{
Response response = headerResponse.getResponse();
final CharSequence url = RequestCycle.get().urlFor(getPackageResourceReference());
response.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"");
response.write(url);
response.println("\"></link>");
}
}
/**
* prints a javascript resource reference.
*/
public static final class JavaScriptReferenceHeaderContributor
extends
PackageResourceReferenceHeaderContributor
{
private static final long serialVersionUID = 1L;
/**
* Construct.
*
* @param scope
* The scope of the reference (typically the calling class)
* @param name
* The name .
*/
public JavaScriptReferenceHeaderContributor(Class scope, String name)
{
super(scope, name);
}
/**
* @see wicket.markup.html.IHeaderContributor#renderHead(wicket.Response)
*/
public void renderHead(IHeaderResponse response)
{
final CharSequence url = RequestCycle.get().urlFor(getPackageResourceReference());
JavascriptUtils.writeJavascriptUrl(response.getResponse(), url);
}
}
/**
* Wraps a {@link PackageResourceReference} and knows how to print a header
* statement based on that resource. Default implementations are
* {@link JavaScriptReferenceHeaderContributor} and
* {@link CSSReferenceHeaderContributor}, which print out javascript
* statements and css ref statements respectively.
*/
public static abstract class PackageResourceReferenceHeaderContributor
implements
IHeaderContributor
{
private static final long serialVersionUID = 1L;
/** the pre calculated hash code. */
private final int hash;
/** the package resource reference. */
private final PackageResourceReference packageResourceReference;
/**
* Construct.
*
* @param scope
* The scope of the reference (typically the calling class)
* @param name
* The name of the reference (typically the name of the
* packaged resource, like 'myscripts.js').
*/
public PackageResourceReferenceHeaderContributor(Class scope, String name)
{
this.packageResourceReference = new PackageResourceReference(scope, name);
int result = 17;
result = 37 * result + getClass().hashCode();
result = 37 * result + packageResourceReference.hashCode();
hash = result;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj)
{
if (obj.getClass().equals(getClass()))
{
PackageResourceReferenceHeaderContributor that = (PackageResourceReferenceHeaderContributor)obj;
return this.packageResourceReference.equals(that.packageResourceReference);
}
return false;
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
return hash;
}
/**
* Gets the package resource reference.
*
* @return the package resource reference
*/
protected final PackageResourceReference getPackageResourceReference()
{
return packageResourceReference;
}
}
private static final long serialVersionUID = 1L;
/**
* Returns a new instance of {@link HeaderContributor} with a header
* contributor that references a CSS file that lives in the web application
* directory and that is addressed relative to the context path.
*
* @param location
* The location of the css file relative to the context path
* @return the new header contributor instance
*/
public static final HeaderContributor forCss(final String location)
{
return new HeaderContributor(new CSSHeaderContributor(location));
}
/**
* Returns a new instance of {@link HeaderContributor} with a header
* contributor that references a JavaScript file that lives in the web
* application directory and that is addressed relative to the context path.
*
* @param location
* The location of the css file relative to the context path
* @return the new header contributor instance
*/
public static final HeaderContributor forJavaScript(final String location)
{
return new HeaderContributor(new JavaScriptHeaderContributor(location));
}
/**
* Returns a new instance of {@link HeaderContributor} with a header
* contributor that references a CSS file that lives in a package.
*
* @param scope
* The scope of the package resource (typically the class of the
* caller, or a class that lives in the package where the
* resource lives).
* @param path
* The path
* @return the new header contributor instance
*/
public static final HeaderContributor forCss(final Class scope, final String path)
{
return new HeaderContributor(new CSSReferenceHeaderContributor(scope, path));
}
/**
* Returns a new instance of {@link HeaderContributor} with a header
* contributor that references a java script file that lives in a package.
*
* @param scope
* The scope of the package resource (typically the class of the
* caller, or a class that lives in the package where the
* resource lives).
* @param path
* The path
* @return the new header contributor instance
*/
public static final HeaderContributor forJavaScript(final Class scope, final String path)
{
return new HeaderContributor(new JavaScriptReferenceHeaderContributor(scope, path));
}
/**
* set of resource references to contribute.
*/
private List<IHeaderContributor> headerContributors = null;
/**
* Construct.
*/
public HeaderContributor()
{
}
/**
* Construct with a single header contributor.
*
* @param headerContributor
* the header contributor
*/
public HeaderContributor(IHeaderContributor headerContributor)
{
headerContributors = new ArrayList<IHeaderContributor>();
headerContributors.add(headerContributor);
}
/**
* Adds a custom header contributor.
*
* @param headerContributor
* instance of {@link IHeaderContributor}
*/
public final void addContributor(final IHeaderContributor headerContributor)
{
checkHeaderContributors();
if (!headerContributors.contains(headerContributor))
{
headerContributors.add(headerContributor);
}
}
/**
* Adds a custom header contributor at the given position.
*
* @param index
* the position where the contributor should be added (e.g. 0 to
* put it in front of the rest).
* @param headerContributor
* instance of {@link IHeaderContributor}
*
* @throws IndexOutOfBoundsException
* if the index is out of range (index < 0 || index >
* size()).
*/
public final void addContributor(final int index, final IHeaderContributor headerContributor)
{
checkHeaderContributors();
if (!headerContributors.contains(headerContributor))
{
headerContributors.add(index, headerContributor);
}
}
/**
* Adds a reference to a css file that should be contributed to the page
* header.
*
* @param scope
* The scope of the package resource (typically the class of the
* caller, or a class that lives in the package where the
* resource lives).
* @param path
* The path
*/
public final void addCssReference(final Class scope, final String path)
{
addContributor(new CSSReferenceHeaderContributor(scope, path));
}
/**
* Adds a reference to a javascript file that should be contributed to the
* page header.
*
* @param scope
* The scope of the package resource (typically the class of the
* caller, or a class that lives in the package where the
* resource lives).
* @param path
* The path
*/
public final void addJavaScriptReference(final Class scope, final String path)
{
addContributor(new JavaScriptReferenceHeaderContributor(scope, path));
}
/**
* @see wicket.behavior.AbstractHeaderContributor#getHeaderContributors()
*/
@Override
public final IHeaderContributor[] getHeaderContributors()
{
if (headerContributors != null)
{
return headerContributors.toArray(new IHeaderContributor[headerContributors.size()]);
}
return null;
}
/**
* Create lazily to save memory.
*/
private void checkHeaderContributors()
{
if (headerContributors == null)
{
headerContributors = new ArrayList<IHeaderContributor>();
}
}
} | common case is one header contributor per instance
git-svn-id: ac804e38dcddf5e42ac850d29d9218b7df6087b7@462036 13f79535-47bb-0310-9956-ffa450edef68
| wicket/src/java/wicket/behavior/HeaderContributor.java | common case is one header contributor per instance | <ide><path>icket/src/java/wicket/behavior/HeaderContributor.java
<ide> */
<ide> public HeaderContributor(IHeaderContributor headerContributor)
<ide> {
<del> headerContributors = new ArrayList<IHeaderContributor>();
<add> headerContributors = new ArrayList<IHeaderContributor>(1);
<ide> headerContributors.add(headerContributor);
<ide> }
<ide>
<ide> {
<ide> if (headerContributors == null)
<ide> {
<del> headerContributors = new ArrayList<IHeaderContributor>();
<add> headerContributors = new ArrayList<IHeaderContributor>(1);
<ide> }
<ide> }
<ide> } |
|
JavaScript | mit | d503439e92056424a13429b76a65ae777afd6104 | 0 | Backendless/JS-Code-Runner | 'use strict';
const ServerCode = require('../api'),
events = require('../events'),
ServiceWrapper = require('./service'),
jsdoc = require('../../util/jsdoc'),
logger = require('../../util/logger'),
printer = require('./printer');
class Dictionary {
keys() {
return Object.keys(this);
}
values() {
return this.keys().map(key => this[key]);
}
}
class Definitions {
constructor() {
this.files = [];
this.types = {};
}
setExplicitly(definitions) {
this.explicit = true;
this.files = definitions && definitions.files || [];
this.types = definitions && definitions.types || [];
}
addFile(file) {
if (!this.explicit && this.files.indexOf(file.relativePath) === -1) {
this.files.push(file.relativePath);
const foundClasses = jsdoc.describeClasses(file.absolutePath);
foundClasses.forEach(classDef => this.types[classDef.name] = classDef);
}
}
}
class ServerCodeModel {
constructor() {
this.types = new Dictionary();
this.handlers = new Dictionary();
this.services = new Dictionary();
this.definitions = new Definitions();
this.errors = [];
}
addHandler(handler) {
const key = ServerCodeModel.computeHandlerKey(handler.eventId, handler.target);
if (this.handlers[key]) {
const methodName = events.get(handler.eventId).name;
throw new Error(`{${methodName}(${handler.target}) event handler already exists`);
}
this.handlers[key] = handler;
}
getHandler(eventId, target) {
return this.handlers[ServerCodeModel.computeHandlerKey(eventId, target)];
}
getService(serviceName) {
return this.services[serviceName];
}
addService(service, file) {
this.definitions.addFile(file);
const serviceWrapper = new ServiceWrapper(service, file.relativePath, this);
if (this.services[serviceWrapper.name]) {
throw new Error(`"["${serviceWrapper.name}" service already exists`);
}
this.services[serviceWrapper.name] = serviceWrapper;
}
addType(type, file) {
this.definitions.addFile(file);
if (this.types[type.name]) {
throw new Error(`"["${type.name}" custom type already exists`);
}
this.types[type.name] = { name: type.name, clazz: type, file: file.relativePath };
}
addError(error, serverCodeFile, erredFile) {
this.errors.push({
message : error.message || error,
serverCodeFile,
erredFile: erredFile && erredFile.relativePath
});
}
get classMappings() {
const result = {};
Object.keys(this.types).forEach(name => {
result[name] = this.types[name].clazz;
});
return result;
}
print() {
printer.print(this);
}
loadFiles(basePath, files) {
ServerCode.load(basePath, files, this);
}
isEmpty() {
return this.handlers.values().length === 0 && this.services.values().length === 0;
}
static computeHandlerKey(eventId, target) {
const isTimer = events.get(eventId).provider === events.providers.TIMER;
if (isTimer) {
target = JSON.parse(target).timername;
}
return [eventId, target].join('-');
}
/**
* @param {String} basePath
* @param {Array.<String>} files
* @returns {ServerCodeModel}
*/
static build(basePath, files) {
logger.info('Building Model..');
const model = new ServerCodeModel();
model.loadFiles(basePath, files);
logger.info('Model Build completed');
model.print();
return model;
}
}
module.exports = ServerCodeModel; | lib/server-code/model/index.js | 'use strict';
const ServerCode = require('../api'),
events = require('../events'),
ServiceWrapper = require('./service'),
jsdoc = require('../../util/jsdoc'),
logger = require('../../util/logger'),
printer = require('./printer');
class Dictionary {
keys() {
return Object.keys(this);
}
values() {
return this.keys().map(key => this[key]);
}
}
class Definitions {
constructor() {
this.files = [];
this.types = {};
}
setExplicitly(definitions) {
this.explicit = true;
this.files = definitions && definitions.files || [];
this.types = definitions && definitions.types || [];
}
addFile(file) {
if (!this.explicit && this.files.indexOf(file.relativePath) === -1) {
this.files.push(file.relativePath);
const foundClasses = jsdoc.describeClasses(file.absolutePath);
foundClasses.forEach(classDef => this.types[classDef.name] = classDef);
}
}
}
class ServerCodeModel {
constructor() {
this.types = new Dictionary();
this.handlers = new Dictionary();
this.services = new Dictionary();
this.definitions = new Definitions();
this.errors = [];
}
addHandler(handler) {
const key = ServerCodeModel.computeHandlerKey(handler.eventId, handler.target);
if (this.handlers[key]) {
const methodName = events.get(handler.eventId).name;
throw new Error(`{${methodName}(${handler.target}) event handler already exists`);
}
this.handlers[key] = handler;
}
getHandler(eventId, target) {
return this.handlers[ServerCodeModel.computeHandlerKey(eventId, target)];
}
getService(serviceName) {
return this.services[serviceName];
}
addService(service, file) {
this.definitions.addFile(file);
const serviceWrapper = new ServiceWrapper(service, file.relativePath, this);
if (this.services[serviceWrapper.name]) {
throw new Error(`"["${serviceWrapper.name}" service already exists`);
}
this.services[serviceWrapper.name] = serviceWrapper;
}
addType(type, file) {
this.definitions.addFile(file);
if (this.types[type.name]) {
throw new Error(`"["${type.name}" custom type already exists`);
}
this.types[type.name] = { name: type.name, clazz: type, file: file.relativePath };
}
addError(error, serverCodeFile, erredFile) {
this.errors.push({ message: error.message || error, serverCodeFile, erredFile: erredFile.relativePath });
}
get classMappings() {
const result = {};
Object.keys(this.types).forEach(name => {
result[name] = this.types[name].clazz;
});
return result;
}
print() {
printer.print(this);
}
loadFiles(basePath, files) {
ServerCode.load(basePath, files, this);
}
isEmpty() {
return this.handlers.values().length === 0 && this.services.values().length === 0;
}
static computeHandlerKey(eventId, target) {
const isTimer = events.get(eventId).provider === events.providers.TIMER;
if (isTimer) {
target = JSON.parse(target).timername;
}
return [eventId, target].join('-');
}
/**
* @param {String} basePath
* @param {Array.<String>} files
* @returns {ServerCodeModel}
*/
static build(basePath, files) {
logger.info('Building Model..');
const model = new ServerCodeModel();
model.loadFiles(basePath, files);
logger.info('Model Build completed');
model.print();
return model;
}
}
module.exports = ServerCodeModel; | fix (model) safe check for erredFile existence
| lib/server-code/model/index.js | fix (model) safe check for erredFile existence | <ide><path>ib/server-code/model/index.js
<ide> }
<ide>
<ide> addError(error, serverCodeFile, erredFile) {
<del> this.errors.push({ message: error.message || error, serverCodeFile, erredFile: erredFile.relativePath });
<add> this.errors.push({
<add> message : error.message || error,
<add> serverCodeFile,
<add> erredFile: erredFile && erredFile.relativePath
<add> });
<ide> }
<ide>
<ide> get classMappings() { |
|
Java | apache-2.0 | 05ddb015a1bd62186fcd10325f63950a4a25defd | 0 | treasure-data/digdag,treasure-data/digdag,KimuraTakaumi/digdag,treasure-data/digdag,treasure-data/digdag,KimuraTakaumi/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,KimuraTakaumi/digdag,KimuraTakaumi/digdag,KimuraTakaumi/digdag,KimuraTakaumi/digdag | package io.digdag.core.repository;
import java.time.Instant;
import com.google.common.base.*;
import com.google.common.collect.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.immutables.value.Value;
@Value.Immutable
@JsonSerialize(as = ImmutableStoredRevision.class)
@JsonDeserialize(as = ImmutableStoredRevision.class)
public abstract class StoredRevision
extends Revision
{
public abstract int getId();
public abstract int getProjectId();
public abstract Instant getCreatedAt();
}
| digdag-core/src/main/java/io/digdag/core/repository/StoredRevision.java | package io.digdag.core.repository;
import java.time.Instant;
import com.google.common.base.*;
import com.google.common.collect.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.immutables.value.Value;
@Value.Immutable
@JsonSerialize(as = ImmutableStoredProject.class)
@JsonDeserialize(as = ImmutableStoredProject.class)
public abstract class StoredRevision
extends Revision
{
public abstract int getId();
public abstract int getProjectId();
public abstract Instant getCreatedAt();
}
| fix revision json serialization | digdag-core/src/main/java/io/digdag/core/repository/StoredRevision.java | fix revision json serialization | <ide><path>igdag-core/src/main/java/io/digdag/core/repository/StoredRevision.java
<ide> import org.immutables.value.Value;
<ide>
<ide> @Value.Immutable
<del>@JsonSerialize(as = ImmutableStoredProject.class)
<del>@JsonDeserialize(as = ImmutableStoredProject.class)
<add>@JsonSerialize(as = ImmutableStoredRevision.class)
<add>@JsonDeserialize(as = ImmutableStoredRevision.class)
<ide> public abstract class StoredRevision
<ide> extends Revision
<ide> { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.